text stringlengths 185 73.3k | repo stringlengths 7 100 | path stringlengths 4 146 | language stringclasses 7
values | hash stringlengths 16 16 | score float64 7 8.5 | stars int64 0 237k |
|---|---|---|---|---|---|---|
"""
Recovery / CFCFRMS fund-blocking loop (Phase 6 — the money story).
GET /recovery/recommendations -> fund-block queue (bank-scoped for BANK role)
POST /recovery/{rec_id}/status -> freeze_requested / held / recovered
GET /recovery/funnel -> flagged -> held -> recovered (synthetic, lab... | stunninghacker/CashGuard-AI | backend/api/routes/recovery.py | .py | cee874868552a9f2 | 7 | 0 |
"""
Risk scoring endpoints — the predictive intelligence output (deliverable a).
GET /risk-scores -> per-ATM P(fraud withdrawal in next 24h), role-scoped
GET /hotspots -> top-K high-risk ATMs (filterable by city / time / category)
DEMO_MODE=true serves the pre-computed golden-path cache (fallback plan).
"""
fr... | stunninghacker/CashGuard-AI | backend/api/routes/risk.py | .py | 02a4e613d151b094 | 7 | 0 |
"""
Database engine / session management.
* Hackathon: SQLite file at data/cashguard.db
* Production: set DATABASE_URL to a PostgreSQL DSN — the ORM layer and all
repositories work unchanged (SQLAlchemy abstracts the dialect).
Data-access note: no route handler ever touches SQLAlchemy directly; every
query goes thr... | stunninghacker/CashGuard-AI | backend/database.py | .py | 86dd9cba2bab0098 | 7 | 0 |
"""
Multi-node ledger replication (Raft-style, demo-grade).
Implements a small replicated log of ledger blocks across 3 simulated nodes
with majority (2/3) quorum writes and per-node chain verification. This is a
REAL replication mechanism (each node stores and verifies its own copy) running
on one machine for demo pu... | stunninghacker/CashGuard-AI | backend/ledger_replication.py | .py | f5be9b67155526d5 | 7 | 0 |
"""
Inference — live risk scoring.
predict_risk(as_of) computes P(fraud withdrawal in next 24h) for every ATM
using only data available BEFORE `as_of`, then joins ATM metadata so the
dashboard can render the heatmap without further lookups.
"""
from __future__ import annotations
from datetime import datetime, timedel... | stunninghacker/CashGuard-AI | backend/ml/inference.py | .py | 55cf6049145acc1c | 7 | 0 |
"""
ORM models — mirror the real NCRP / CFCFRMS / bank ATM data schema.
In production these tables would be populated by ETL pipelines pulling from:
* NCRP (National Cyber Crime Reporting Portal) complaint records
* CFCFRMS (Citizen Financial Cyber Fraud Reporting and Management System)
* Bank ATM/transaction f... | stunninghacker/CashGuard-AI | backend/models.py | .py | 5a17bdc73441f13b | 7 | 0 |
"""
Authentication & RBAC (Phase 3 — "secure" Law Enforcement Interface).
* bcrypt password hashing (passlib) against the `users` table.
* JWT access tokens (short TTL) + refresh tokens (long TTL) via python-jose.
* Roles: POLICE_STATE / POLICE_DISTRICT / BANK / I4C_ADMIN, each with a SCOPE
(state | district | bank_... | stunninghacker/CashGuard-AI | backend/security.py | .py | 1364f8eafa42a7ea | 7 | 0 |
"""Spatial generalization splits (red-team final pass).
A) random split (shuffled ATM-days)
B) time-forward split (chronological; the production split)
C) cold-ATM split (20% of ATMs never seen in training)
D) cold-city split (one city held out of training)
E) cold-district split (one district held out — district == c... | stunninghacker/CashGuard-AI | scripts/generalization_splits.py | .py | a7130d33bee42254 | 7 | 0 |
#!/usr/bin/env python3
# PreToolUse decider for allow-readonly-psql.sh (FRE-867). See that file for the rationale.
#
# Why this is a file rather than a heredoc inside the shell wrapper. It used to be carried as
# `decider=$(cat <<'PY' ... PY)` and passed to `python3 -c`. Under bash 5 that parses fine, but
# bash 3.2 --... | alextra-lab/personal_agent | .claude/hooks/allow-readonly-psql.py | .py | de2abec87add045d | 7.3 | 3 |
"""Setup DSPy with LM Studio configuration.
This script configures DSPy to work with LM Studio's OpenAI-compatible endpoint.
"""
import dspy
from personal_agent.config import settings
from personal_agent.config.model_loader import load_model_config
def configure_dspy(model_name: str | None = None) -> None:
"""... | alextra-lab/personal_agent | experiments/dspy_prototype/setup_dspy.py | .py | 0a743d2ac5e0f6af | 7.3 | 3 |
"""E-018: Run baseline vs LangExtract treatment for entity extraction.
Usage (from repo root):
uv run python -m experiments.langextract_evaluation.run_comparison
Prerequisites:
- Local LLM running (same as entity_extraction config)
- Optional: LANGEXTRACT_DATASET_PATH pointing to JSONL with user_message, ... | alextra-lab/personal_agent | experiments/langextract_evaluation/run_comparison.py | .py | b76ee964abc8c4bf | 7.3 | 3 |
"""Experiment configuration for Graphiti vs Seshat comparison."""
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
@dataclass(frozen=True)
class LLMConfig:
"""Configuration for a single LLM provider in the experiment."""
name: str
medium_model: str
... | alextra-lab/personal_agent | scripts/archive/graphiti_experiment/experiment/config.py | .py | 3d33bbac212731c0 | 7.3 | 3 |
"""Run experiment scenarios against Graphiti."""
from __future__ import annotations
import os
import time
from datetime import datetime, timedelta, timezone
from typing import Any
# Disable Graphiti telemetry before importing
os.environ["GRAPHITI_TELEMETRY_ENABLED"] = "false"
from graphiti_core import Graphiti
from... | alextra-lab/personal_agent | scripts/archive/graphiti_experiment/experiment/graphiti_runner.py | .py | 9dd199c56258586c | 7.3 | 3 |
"""Format experiment results as JSON and markdown."""
from __future__ import annotations
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
import orjson
def save_json_results(
results: dict[str, Any],
output_dir: Path,
run_id: str,
) -> Path:
"""Save full resul... | alextra-lab/personal_agent | scripts/archive/graphiti_experiment/experiment/report.py | .py | 7c3eab868e77ceda | 7.3 | 3 |
"""Run experiment scenarios against the current Seshat Neo4j backend."""
from __future__ import annotations
import time
from typing import Any
from personal_agent.memory.models import Entity, MemoryQuery, Relationship, TurnNode
from personal_agent.memory.service import MemoryService
from .config import ExperimentCo... | alextra-lab/personal_agent | scripts/archive/graphiti_experiment/experiment/seshat_runner.py | .py | b9a501990ecef32f | 7.3 | 3 |
#!/usr/bin/env python
"""Graphiti vs Seshat Experiment — EVAL-02 / FRE-147.
Compares Graphiti against the current Seshat Neo4j backend across 6 scenarios:
1. Episodic Memory — Store + Retrieve
2. Semantic Memory — Consolidation Quality
3. Temporal Queries
4. Entity Deduplication
5. Consolidation Lifecycle
... | alextra-lab/personal_agent | scripts/archive/graphiti_experiment/graphiti_experiment.py | .py | 458389dbaa9a1550 | 7.3 | 3 |
"""Config-inventory generator + verifier (FRE-648, ADR-0099 stage 0).
The canonical configuration inventory (`docs/reference/CONFIG_INVENTORY.md`) has one
machine-generated section — the ``AppConfig`` scalar table — and several hand-curated
sections (model-role matrix, profiles, governance, compose, findings). This mo... | alextra-lab/personal_agent | scripts/audit/config_inventory.py | .py | 2906f18d1f53bdec | 7.3 | 3 |
#!/usr/bin/env python3
"""FRE-1021 — entity-candidate participation census.
Read-only audit tool backing the FRE-1021 measurement. ADR-0126 D2 and the FRE-1021
ticket both assert a *mechanism* — entities and turn/episode candidates compete in one
ranked, capped, fused pool, so a topic's own recent turns can displace i... | alextra-lab/personal_agent | scripts/audit/fre1021_entity_participation_census.py | .py | b0325c09013587a7 | 7.3 | 3 |
"""Inventory the free-text surface of ``agent-logs-*`` (FRE-1068).
Every figure in ``docs/research/2026-08-06-fre1068-telemetry-free-text-inventory.md``
is produced by this script. Re-run it and diff rather than trusting committed
numbers.
Usage:
python3 scripts/audit/fre1068_free_text_inventory.py # m... | alextra-lab/personal_agent | scripts/audit/fre1068_free_text_inventory.py | .py | a8bf17fceede72a7 | 7.3 | 3 |
#!/usr/bin/env python3
"""FRE-942 — compaction-outcome and tool-result size census.
Read-only audit tool backing the FRE-942 decision (see
``docs/superpowers/plans/2026-07-23-fre-942-compaction-tail-ceiling.md`` §1). It
reproduces the two measurements the decision rests on, so the numbers quoted in the
ticket, the ADR... | alextra-lab/personal_agent | scripts/audit/fre942_compaction_census.py | .py | 7c526aa4eb90a383 | 7.3 | 3 |
r"""AST alias-aware read detection for the config-usage audit (FRE-896, ADR-0099 hygiene).
FRE-893's audit detected reads of ``AppConfig`` fields with a line-oriented ``git grep``
for ``settings.<field>`` / ``getattr(settings, "<field>")``. Three real read patterns
evade a per-line literal grep and were systematically... | alextra-lab/personal_agent | scripts/audit/settings_reads.py | .py | 63bcfe980c144b19 | 7.3 | 3 |
#!/usr/bin/env python3
"""Backfill ILM lifecycle policy to existing slm-requests-* indices (FRE-1106).
This script idempotently sets index.lifecycle.name on all existing slm-requests-*
indices to make them lifecycle-managed. It is meant to be run once after the
slm-requests-ilm-policy is deployed.
The script:
1. Disc... | alextra-lab/personal_agent | scripts/backfill-slm-requests-ilm.py | .py | 600a3f847e81cb24 | 7.3 | 3 |
"""FRE-343 one-shot backfill — populate (:Person)-[:PARTICIPATED_IN]->(:Turn) edges.
Idempotent. Algorithm:
1. Resolve OWNER_UUID from settings.agent_owner_email.
2. Stream all Sessions from Postgres.
3. For each Session: target_uid = session.user_id OR OWNER_UUID (NULL fallback).
4. MERGE the edge in Neo4j fo... | alextra-lab/personal_agent | scripts/backfill_participated_in.py | .py | 8625527afd615f5e | 7.3 | 3 |
#!/usr/bin/env python3
"""Build the FRE-531 E2E artifact render-harness fixtures (ADR-0089 Addendum A7).
The Playwright harness (``e2e/artifact-lib/``) needs three things produced from
the *real* curated-toolkit plumbing, with no access to the live Access-gated
``/lib/`` origin:
1. a ``/lib/`` **mirror** of the versi... | alextra-lab/personal_agent | scripts/build_e2e_artifact_fixtures.py | .py | e769c290f52d925d | 7.3 | 3 |
"""AST lint: flag silent truncation of evidence-path content (ADR-0125 D5, AC-5).
D5 forbids silent truncation on any path feeding a durable artifact or assembled
context: content must be stored whole, or shortened with an explicit marker
recording that it was shortened and by how much
(``personal_agent.captains_log.t... | alextra-lab/personal_agent | scripts/check_evidence_truncation.py | .py | b21376793edf8243 | 7.3 | 3 |
"""AST lint: flag log/bus.publish/Cypher MERGE sites missing identity kwargs.
Enforces ADR-0074 §I3 (every async boundary preserves identity) and §I5
(memory writes carry origination). Pulled forward from FRE-376 Phase 5 as the
definition-of-done for Phase 3.
Genuine false-positives are suppressed with an inline ``# ... | alextra-lab/personal_agent | scripts/check_identity_threaded.py | .py | c97110ee4d79f834 | 7.3 | 3 |
#!/usr/bin/env python3
"""Fail if tracked files contain a real deployment identifier (FRE-895).
Scans ``git ls-files`` text for the real deployment domain and the real
Cloudflare Access team domain — neither ever written in this file as a
contiguous literal (built from concatenated fragments), so the checker
doesn't t... | alextra-lab/personal_agent | scripts/check_no_deployment_identifier.py | .py | ccbc1f25d0258814 | 7.3 | 3 |
#!/usr/bin/env python3
"""Fail if test/eval scripts contain direct production-substrate access patterns.
Scans Python files under ``tests/``, ``scripts/eval/``, and ``scripts/research/``
for patterns that indicate raw access to the production Neo4j, Elasticsearch, or
PostgreSQL substrates, or bare ``MemoryService()`` ... | alextra-lab/personal_agent | scripts/check_no_direct_substrate_in_tests.py | .py | f910f623c224ef5f | 7.8 | 3 |
#!/usr/bin/env python3
"""Fail if tracked files contain machine-specific path examples.
Scans ``git ls-files`` text for patterns that leak a developer's local layout
(e.g. macOS user home mount + ``Users`` segment, tilde + ``/Dev/`` layout, Windows profile
paths).
Returns:
0 if no violations; 1 if any match; 2 on... | alextra-lab/personal_agent | scripts/check_no_personal_paths.py | .py | 36dd03d26fddbc7c | 7.3 | 3 |
#!/usr/bin/env python3
"""Headless /context: a session's live context usage from its transcript JSONL.
Lets the gating watcher poll context% + idle without scraping the pane.
Signals emitted (key=value, one line — the SAME keys on every path):
session tmux session asked about
jsonl the transcript file resol... | alextra-lab/personal_agent | scripts/dispatch/context_probe.py | .py | ba1bdf1f38f2bd41 | 7.3 | 3 |
# -*- coding: utf-8 -*-
"""
check_sensitive.py <date> — 国内平台发布前的关键字筛查。
扫 reports/<date>/ 下的 daily.json、口播稿.md、dist/daily.zhihu.md,
对照 scripts/sensitive_words.txt(用户可编辑),命中就打出 文件+词+上下文。
命中不等于禁发:这是给人看的提醒,人工决定删改还是该平台跳过这条。
退出码:0 无命中,1 有命中(方便脚本串联)。
"""
import sys, re, pathlib
ROOT = pathlib.Path(__file__).resolve().paren... | unryuu/dailydigest | scripts/check_sensitive.py | .py | f50b99f33611075e | 7 | 0 |
# -*- coding: utf-8 -*-
"""daily.json 的容错读取 + 标点归一化。
用户会直接手工编辑 daily.json,手编必然留尾逗号(`... },\n]`),标准 json
解析直接报错——严格解析失败时去掉尾逗号重试。写手/上游偶发把中文标点写成
半角(07-24 事故:主 agent 半角污染整条流水线)——读取时把「紧邻汉字或全角
字符的半角 ,:;?!」归一化为全角。两类修正都回写,让仓库里的 daily.json
始终合法且标点统一。
不会误伤:URL 和英文语境是纯 ASCII、不与汉字相邻,不会被改;
去完尾逗号仍解析不了的真语法错误照常抛。
"""
import json
imp... | unryuu/dailydigest | scripts/dailyjson.py | .py | 9950323d17852181 | 7 | 0 |
# -*- coding: utf-8 -*-
"""
recent_titles.py <date> [N=3] — 打印目标日期之前最近 N 期的已发条目清单。
用途:防内容重复的语料(同一事件换个链接、换个说法也别再收)。
步骤 1:把输出附进 scout 的派活 prompt;
步骤 2:定牌时主 agent 自己对照(昨天那期还要读 daily.json 全文,正文里
一句话带过的点也算报过——标题清单只能兜住标题级重复)。
数据直接来自 reports/<d>/daily.json,零维护。
"""
import sys, re, os, json, pathlib
ROOT = pathlib.Path... | unryuu/dailydigest | scripts/recent_titles.py | .py | ec1195b382ff0d58 | 7 | 0 |
# -*- coding: utf-8 -*-
"""
subs_align.py <date> — 把口播稿文本对齐到 whisper 转写的时间轴,生成「稿件字幕」。
输入:reports/<date>/口播稿.md(定稿文本)+ reports/<date>/video/字幕.audio.srt(whisper 直出)
输出:reports/<date>/video/字幕.script.srt(时间轴来自音频、文字来自稿件)
原理(v2,字符级全局对齐):
1. whisper 各段内按字符线性插值,得到「转写文本每个字 → 时间」;
2. 转写全文 vs 稿件全文做 SequenceMatcher,equal 块直接继承... | unryuu/dailydigest | scripts/subs_align.py | .py | 01cf0c09150518db | 7 | 0 |
# -*- coding: utf-8 -*-
"""
subs_polish.py <in.srt> <out.srt> [gap_ms=80] — 烧录前的字幕抛光(不改源文件)。
1. 行尾的句号「。」和分号「;」删掉(行中不动)。
2. 相邻字幕留最小间隙:两条挨得太近时**把前一条的结束时间提前**到
下一条开始前 gap_ms,切换不突兀。参照 Netflix Timed Text 规范的
最小 2 帧间隙(24fps 约 83ms),默认 80ms,可调。
下一条的开始时间永远不动(它咬着开口时刻)。
用在用户手工修完的 字幕.script.srt 之后、烧录之前;源文件保持原样。
"""
imp... | unryuu/dailydigest | scripts/subs_polish.py | .py | f87af384c9fdae39 | 7 | 0 |
# -*- coding: utf-8 -*-
"""
subs_shift.py <in.srt> <out.srt> [delay_ms=50] — 把字幕切换点整体延后。
人类习惯「下一句开口时才换字幕」,whisper 的段首尾相接、切换偏早。
处理:除第一条外,每条 start 加 delay;前一条原本与它相接的,end 跟着顺延,保持无缝。
"""
import sys, re, pathlib
def t2s(ts):
h, m, rest = ts.split(":")
s, ms = rest.split(",")
return int(h) * 3600 + int(m) * 60 ... | unryuu/dailydigest | scripts/subs_shift.py | .py | ae5800edfdd02a1e | 7 | 0 |
# -*- coding: utf-8 -*-
"""
video_cover.py <date> <日期标题> <看点一行> — 渲视频横屏封面 1920x1080。
例:python scripts/video_cover.py 2026-07-22 "7 月 22 日" "OpenAI 自认 HF 入侵 · Turner 辞职内幕 · 15 亿和解获批"
(日期标题只写日期,不带「口播版」——07-22 用户定)
输出:reports/<date>/video/视频卡.横屏.png
"""
import sys, pathlib
from PIL import Image, ImageDraw, ImageFont
ROO... | unryuu/dailydigest | scripts/video_cover.py | .py | fabc4d928359941c | 7 | 0 |
"""create_tenants_table
Revision ID: 000000000001
Revises:
Create Date: 2026-07-29 00:00:00.000000
"""
from collections.abc import Sequence
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "000000000001"
down_revisio... | anurag-jaiswal-aj/hiron | apps/api/alembic/versions/20260729_0000_000000000001_create_tenants_table.py | .py | 33edd5cc52a98a3a | 7.15 | 1 |
"""Add cursor pagination indexes for audit and ai usage
Revision ID: b3b6a3f2c986
Revises: '000000000015'
Create Date: 2026-08-10 18:42:12.437370
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "b3b6a3f2c986"
down_rev... | anurag-jaiswal-aj/hiron | apps/api/alembic/versions/20260810_1842_b3b6a3f2c986_add_cursor_pagination_indexes_for_audit_.py | .py | d9ea086d8e73c98a | 7.15 | 1 |
"""Enable RLS and create isolation policies for all tenant-scoped tables.
Revision ID: phase16_rls_001
Revises: b3b6a3f2c986
Create Date: 2026-08-11 12:00:00.000000
"""
from collections.abc import Sequence
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "phase16_rls_001"
down_revisio... | anurag-jaiswal-aj/hiron | apps/api/alembic/versions/20260811_1200_phase16_rls_001.py | .py | e1a5a6cbd85df722 | 7.15 | 1 |
"""Add BatchScoreJob
Revision ID: d336f5d8940e
Revises: 'phase16_rls_001'
Create Date: 2026-08-13 11:29:47.659295
"""
from collections.abc import Sequence
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "d336f5d8940... | anurag-jaiswal-aj/hiron | apps/api/alembic/versions/20260813_1129_d336f5d8940e_add_batchscorejob.py | .py | bcf191625ae07e63 | 7.15 | 1 |
"""AI Usage domain exceptions."""
from fastapi import status
from hiron.common.exceptions import HironException
class InsufficientAIUsagePermissionsError(HironException):
"""Raised when user role is not authorized for AI usage analytics."""
def __init__(self, message: str = "Only org_admin users can access... | anurag-jaiswal-aj/hiron | apps/api/hiron/ai_usage/exceptions.py | .py | f7198054589e8590 | 7.15 | 1 |
"""Thin FastAPI router for AI Usage Monitoring per API Contract §USAGE-1..2."""
import datetime
from fastapi import APIRouter, Depends, Query, status
from sqlalchemy.ext.asyncio import AsyncSession
from hiron.ai_usage.schemas import AIUsageLogsResponse, AIUsageSummaryResponse
from hiron.ai_usage.service import AIUsa... | anurag-jaiswal-aj/hiron | apps/api/hiron/ai_usage/router.py | .py | 31d2caa4c955befc | 7.15 | 1 |
"""Audit domain exceptions."""
from fastapi import status
from hiron.common.exceptions import HironException
class InsufficientAuditPermissionsError(HironException):
"""Raised when user role is not authorized for audit log access."""
def __init__(self, message: str = "Insufficient permissions for audit log... | anurag-jaiswal-aj/hiron | apps/api/hiron/audit/exceptions.py | .py | 947f96cb28c0929d | 7.15 | 1 |
"""Pydantic schemas for Audit Logs per API Contract §AUDIT-1..2."""
import datetime
import uuid
from typing import Any
from pydantic import BaseModel, ConfigDict, Field
class AuditActorInfo(BaseModel):
"""Actor metadata embedded in audit log response."""
model_config = ConfigDict(populate_by_name=True)
... | anurag-jaiswal-aj/hiron | apps/api/hiron/audit/schemas.py | .py | 04372a7a0cba312a | 7.15 | 1 |
"""Utilities for generating and sanitizing audit logs."""
import datetime
import uuid
from decimal import Decimal
from enum import Enum
from typing import Any
from sqlalchemy import inspect
# Case-insensitive secret keywords for redaction
REDACTION_KEYS = {
"password",
"hashed_password",
"password_hash",... | anurag-jaiswal-aj/hiron | apps/api/hiron/audit/utils.py | .py | 078360f1673774c5 | 7.15 | 1 |
"""FastAPI authentication and authorization (RBAC) dependencies per API Contract §4 & Engineering Guidelines §16.1."""
import uuid
from collections.abc import Sequence
from typing import Annotated
from fastapi import Depends
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from jwt.exceptions imp... | anurag-jaiswal-aj/hiron | apps/api/hiron/auth/dependencies.py | .py | 1880a44767f28338 | 7.15 | 1 |
"""FastAPI authentication router implementing login, refresh, and logout endpoints per API Contract §6.1."""
from typing import Annotated
from fastapi import APIRouter, Cookie, Depends, Request, Response, status
from sqlalchemy.ext.asyncio import AsyncSession
from hiron.auth.dependencies import get_current_user
from... | anurag-jaiswal-aj/hiron | apps/api/hiron/auth/router.py | .py | acea2dbe93eae7f1 | 7.15 | 1 |
"""Authentication service providing core login, credential verification, token issuance, and rotation business logic."""
import hashlib
import uuid
from datetime import UTC, datetime, timedelta
import structlog
from sqlalchemy.ext.asyncio import AsyncSession
from hiron.common.exceptions import HironException
from hi... | anurag-jaiswal-aj/hiron | apps/api/hiron/auth/service.py | .py | cb56729a4b37c079 | 7.15 | 1 |
"""Candidate repository responsible ONLY for database persistence per Engineering Guidelines §6."""
import uuid
from collections.abc import Sequence
from typing import Any
from sqlalchemy import ColumnElement, func, literal, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import select... | anurag-jaiswal-aj/hiron | apps/api/hiron/candidates/repository.py | .py | a81ad390f40392fe | 7.15 | 1 |
"""Reading v2 execution metadata through v1's ``flytekit.current_context()``.
v1 code reaches for execution metadata via ``flytekit.current_context()``. The shim rewires
``ExecutionParameters``' properties onto ``flyte.ctx()``, so the same v1 calls return the real
v2 values.
The interesting part is what happens when ... | flyteorg/flyte-migrate | examples/context_example.py | .py | 7cae5ac77e68ccab | 7.3 | 3 |
import logging
import time
import flytekit
import pandas as pd
from flytekitplugins.deck.renderer import FrameProfilingRenderer
"""
These are packages for frame_renderer example
"""
custom_image = flytekit.ImageSpec(
packages=[
"flytekitplugins-deck-standard",
"pandas",
"ydata_profiling",
... | flyteorg/flyte-migrate | examples/deck_example.py | .py | 0ace3348bef4c7c4 | 7.3 | 3 |
import flyte_migrate # noqa: F401, I001
import logging
import os
import torch
from flytekit import ImageSpec, Resources, task, workflow
from flytekitplugins.kfpytorch import CleanPodPolicy, Elastic, RunPolicy
from torch import nn, optim
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.dat... | flyteorg/flyte-migrate | examples/plugins/pytorch_example.py | .py | 6c34b62787a3ef51 | 7.3 | 3 |
import flyte_migrate # noqa: F401, I001
import datetime
import logging
from operator import add
import flytekit
from flytekit import ImageSpec, PodTemplate, Resources, task, workflow
from flytekitplugins.spark import Spark
custom_image = ImageSpec(
base_image="apache/spark-py:v3.4.0", python_version="3.10", pac... | flyteorg/flyte-migrate | examples/plugins/spark_example.py | .py | 964b9dd8ccd0e015 | 7.3 | 3 |
"""v1 ``@reference_launch_plan`` running on a v2 cluster.
References the ``greet_wf`` workflow registered by reference_task_target.py.
v1 workflows register as tasks in the ``flytekit_workflow`` environment, so the
launch plan name is ``flytekit_workflow.greet_wf``.
"""
import flyte_migrate # noqa: F401, I001
from ... | flyteorg/flyte-migrate | examples/reference_launch_plan_example.py | .py | 39e530e6986c4f4d | 7.3 | 3 |
"""Target workflow for the reference_task / reference_launch_plan examples.
Run this first — it deploys ``greet_env.greet`` and ``flytekit_workflow.greet_wf``
to the cluster, which the reference examples then invoke. Note: tasks must be
*deployed* (not just run) to be resolvable by reference.
"""
import flyte_migrate... | flyteorg/flyte-migrate | examples/reference_task_target.py | .py | 74ad95e473e88d60 | 7.3 | 3 |
"""v1 ``@reference_workflow`` running on a v2 cluster.
References the ``greet_wf`` workflow deployed by reference_task_target.py
(shimmed v1 workflows register as tasks named ``flytekit_workflow.<wf_name>``).
"""
import flyte_migrate # noqa: F401, I001
from flytekit import reference_workflow, task, workflow
@refe... | flyteorg/flyte-migrate | examples/reference_workflow_example.py | .py | 6e8ac7f0b77d5b91 | 7.3 | 3 |
import flyte_migrate # noqa: F401, I001
import logging
import os
from pathlib import Path
from typing import Tuple
from flytekit import Secret, task, workflow
# --- Task 1: Mixed mounts (ENV_VAR + FILE) ---
@task(
secret_requests=[
Secret(group="", key="API_TOKEN", env_var="API_TOKEN_ENV"),
Secr... | flyteorg/flyte-migrate | examples/secret_comprehensive.py | .py | 0beffbdd548d4157 | 7.3 | 3 |
"""
Comprehensive v1 flytekit example exercising:
- @dynamic with typed I/O
- Subworkflows (@workflow calling @workflow)
- Typed inputs/outputs: str, int, float, List[int], Dict[str, str], Optional[int], NamedTuple
- flytekit.Deck with HTML content
- @task with environment variables
- @task with enable_deck=True
"""
i... | flyteorg/flyte-migrate | examples/subworkflow_dynamic.py | .py | bcd275ef4f34e15d | 7.3 | 3 |
"""Mixing v1 and v2 code: a v1 workflow whose task image is built with the v2 ``flyte.Image`` API.
flyte-migrate lets you adopt v2 incrementally — keep ``@task``/``@workflow`` from
flytekit while switching individual pieces (here, the image definition) to the v2 SDK.
A ``flyte.Image`` passed as ``container_image`` is ... | flyteorg/flyte-migrate | examples/v2_image.py | .py | 3b18019a9cff0cb6 | 7.3 | 3 |
"""Shim for v1 BigQueryTask -> v2 TaskTemplate.
Patches ``flytekitplugins.bigquery.BigQueryTask`` so that instantiation produces
a v2-compatible ``TaskTemplate`` which serialises with task-type
``bigquery_query_job_task``, the correct ``custom`` config, and an embedded SQL
statement. The v2 Flyte backend routes this ... | flyteorg/flyte-migrate | src/flyte_migrate/_bigquery.py | .py | 9add6f189c1f54d7 | 7.3 | 3 |
"""Shim v1 ``flytekit.ContainerTask`` onto v2 ``flyte.extras.ContainerTask``.
v2 has a near-identical raw-container task; this factory translates the v1 constructor
arguments (resources, secrets, pod templates, TaskMetadata, metadata format enum) and
registers the resulting task in the defining module's parent workflo... | flyteorg/flyte-migrate | src/flyte_migrate/_container_task.py | .py | b8ee3ebd88bd76f7 | 7.3 | 3 |
"""Replace ``flytekit.Deck`` with a v2-compatible implementation backed by ``flyte.report``.
In FlyteKit v1, ``Deck`` is used to render HTML visualisations in the Flyte
console. In v2, the equivalent functionality is provided by the ``flyte.report``
module which organises output into named tabs.
This module maps the... | flyteorg/flyte-migrate | src/flyte_migrate/_deck.py | .py | d77b0d94e02f24a4 | 7.3 | 3 |
"""Records the local ``sys.path`` on environments at deploy time.
``flyte.run`` stamps the sys.path entries under the root directory into the
``_F_SYS_PATH`` container env var, and the runtime re-adds them before importing the
task module. ``flyte.deploy`` does not do this — it only ever mattered for tasks the
client ... | flyteorg/flyte-migrate | src/flyte_migrate/_deploy.py | .py | 37592e6f9cf17c71 | 7.3 | 3 |
"""Type transformer bridging v1 ``flytekit.types.directory.FlyteDirectory`` to v2 blob literals.
Same story as :mod:`flyte_migrate._file`: v2's TypeEngine has no transformer for the v1
type, so it falls back to pickling the ``FlyteDirectory`` object — shipping the producing
container's local path and nothing else. Thi... | flyteorg/flyte-migrate | src/flyte_migrate/_directory.py | .py | dfeed0510c23f118 | 7.3 | 3 |
"""Type transformer bridging v1 ``flytekit.types.file.FlyteFile`` to v2 blob literals.
v2's TypeEngine has no transformer for the v1 type, so it falls back to pickling the
``FlyteFile`` object. That ships the *producing* container's local path and nothing
else, and the consumer then fails with ``File /tmp/... does not... | flyteorg/flyte-migrate | src/flyte_migrate/_file.py | .py | 8f0c4ffeabd12d38 | 7.3 | 3 |
"""Shim v1 gate nodes (``approve``, ``wait_for_input``, ``sleep``) onto v2 primitives.
In v1 these create gate nodes in the DAG. In the shimmed world, workflows are plain
Python running inside the parent workflow task, so:
- ``wait_for_input`` / ``approve`` map onto ``flyte.new_condition(...).wait()``, which
pause... | flyteorg/flyte-migrate | src/flyte_migrate/_gate.py | .py | bf3f3401783e3925 | 7.3 | 3 |
"""Transforms v1 flytekit.ImageSpec into v2 flyte.Image.
The main entry point is :func:`_transform_image_spec_v1_to_v2`, which accepts a
v1 ``ImageSpec``, a raw image string, or an already-converted ``flyte.Image``
and returns a v2 ``flyte.Image``.
The v1-to-v2 plugin package name mapping is defined in :data:`_PACKAG... | flyteorg/flyte-migrate | src/flyte_migrate/_image.py | .py | 49827ba58f9f7ecc | 7.3 | 3 |
"""Transform v1 ``flytekit.LaunchPlan`` into v2 ``Trigger`` objects.
FlyteKit v1 uses ``LaunchPlan.create()`` / ``LaunchPlan.get_or_create()`` to
attach schedules (cron or fixed-rate) to workflows. In v2, the equivalent
concept is a ``Trigger`` attached to a ``TaskEnvironment``.
This module provides:
- ``merge_inpu... | flyteorg/flyte-migrate | src/flyte_migrate/_launchplan.py | .py | 2bb66dac18f8c6c7 | 7.3 | 3 |
import math
from typing import Any, Optional, Union
import flyte
import flytekit.remote
class MapShim:
"""Shim that wraps ``flyte.map()`` to provide a v1-compatible ``map_task`` interface.
``concurrency`` is forwarded to ``flyte.map()``, which supports it natively.
``min_successes`` / ``min_success_rati... | flyteorg/flyte-migrate | src/flyte_migrate/_map.py | .py | 8ef3f64ab5d36414 | 7.3 | 3 |
"""Plugin configuration transformers for v1-to-v2 migration.
Each plugin module provides a transformer function that converts a v1 plugin
configuration object into its v2 equivalent. The registry pattern used here
allows new plugins to be added without modifying the dispatch logic.
Supported plugins:
- Spark (``f... | flyteorg/flyte-migrate | src/flyte_migrate/_plugins/__init__.py | .py | 4926860f9ad0e287 | 7.3 | 3 |
from __future__ import annotations
import argparse
import asyncio
import json
import os
from collections.abc import Sequence
import mcp_types as types
from mcp.server.lowlevel import Server
from . import __version__
from .engine import SearchEngine
from .models import SearchRequest, SearchResponse
from .output impor... | JerryLiu369/agent-web-search | agent_web_search/mcp.py | .py | 6dbd4c435b24490b | 7.35 | 4 |
from __future__ import annotations
import os
from collections.abc import Iterable
from threading import Lock
def configured_models(
*,
models: Iterable[str] | None,
env_name: str,
defaults: Iterable[str],
) -> list[str]:
"""Resolve models from constructor values, environment, or defaults."""
... | JerryLiu369/agent-web-search | agent_web_search/model_pool.py | .py | cb831b18f328553a | 7.35 | 4 |
"""GPT-2 with optional architecture modifications, for attribution experiments.
One class, three architectures selected by ``config.arch_mod``:
- ``"none"``: exactly stock GPT-2. No extra modules, no extra parameters; stock
``gpt2`` checkpoints load with zero missing/unexpected keys, and logits match
``GPT2LMHead... | EleutherAI/metasmoothness | gpt2_custom/modeling_gpt2_custom.py | .py | efc475131933a994 | 7 | 0 |
import pytest
import torch
from transformers import AutoModelForCausalLM
from transformers.models.gpt2.modeling_gpt2 import GPT2Config, GPT2LMHeadModel
from modeling_gpt2_custom import GPT2CustomConfig, GPT2CustomLMHeadModel
SMALL = dict(n_embd=32, n_head=4, n_layer=2, n_positions=64, vocab_size=97)
def small_custo... | EleutherAI/metasmoothness | gpt2_custom/test_gpt2_custom.py | .py | 239a4e84707213aa | 7.5 | 0 |
#!/usr/bin/env python3
"""Which axis a row belongs to, whether it is cut, and how much we care.
Ruling (Lucia, 2026-08-25): weight decay, gradient clipping and logit scale are
CUT. Not deprioritised -- no further results are wanted for them, ever. GPU time
goes to batch scaling, and to as much token / step-count data ... | EleutherAI/metasmoothness | scripts/axes.py | .py | 46b5ffd534bde370 | 7 | 0 |
#!/usr/bin/env python3
"""Map CephFS disk usage via the ceph.dir.rbytes xattr.
du walks the tree and stats every file, which on this filesystem is one network
round trip per cache miss. CephFS already maintains a recursive byte count per
directory, so one getxattr per directory replaces the whole walk.
python cep... | EleutherAI/metasmoothness | scripts/cephdu.py | .py | b6be025996a481c9 | 7 | 0 |
"""EK-FAC LDS: correlate bank ground truth with EK-FAC scores.
Usage:
python ekfac_lds.py --scores DIR --bank DIR [--n-boot 10000]
--scores: an ekfac_scores/scores dir (scores.bin + info.json, the bergson
structured memmap: float32 score_i + bool written_i per query).
--bank: a dir containing subsets.json and eva... | EleutherAI/metasmoothness | scripts/ekfac_lds.py | .py | 163dd129fe640e79 | 7 | 0 |
"""Correlate filter delta against LDS, propagating BOTH measurement errors.
filter_stat_vs_lds.py bootstraps over rows and treats each row's delta and LDS as
exact. They are not. Both carry their own bootstrap CIs, and the delta's is wide:
the median CI spans 0.49 x the delta itself, and on one row it spans 9.57 x.
M... | EleutherAI/metasmoothness | scripts/filter_lds_with_error.py | .py | d9779f0c38011d9b | 7 | 0 |
#!/usr/bin/env python3
"""Does a scorer's tail-filter power track its LDS, measured per QUERY?
The row-level version of this question tops out at thirteen points -- the number
of rows that have an LDS, still have their bank, and are not cut -- and at n=13
a Spearman interval is about +-0.45. It cannot answer the quest... | EleutherAI/metasmoothness | scripts/filter_vs_lds_perquery.py | .py | 9fd88896300149b0 | 7 | 0 |
"""Emit bank_build.yaml for a row that has scores but no retrain bank.
Builds the bank the cheap way: `validate` with method: lds and save_models: true,
pointed at scores that already exist. That skips MAGIC scoring entirely, which is
serial and unshardable and costs 38-112 h on the larger rows.
Hyperparameters are c... | EleutherAI/metasmoothness | scripts/gen_bank.py | .py | c4abd35015c7b11c | 7 | 0 |
"""Generate a runnable bank+MAGIC config for one experiments.csv planned row.
Usage:
python scripts/gen_experiment_run.py plan_adam_eps1e17_8k_bs256 [--nproc 4]
Reads the row, writes a bergson `magic` pipeline config (base training with
checkpoints kept, 100 leave-1%-out retrains, per-query MAGIC over query_20) t... | EleutherAI/metasmoothness | scripts/gen_experiment_run.py | .py | 6ae2ee9a6d5cab7f | 7 | 0 |
"""Generate a tail-filter validation config for one run and one score source.
The tail-filter estimator (bergson PR #430, merged) removes, per query, the
`filter_fraction` slice of documents that a scorer ranks most influential,
retrains once, and measures that query's loss change against the unablated
baseline. The m... | EleutherAI/metasmoothness | scripts/gen_filter.py | .py | 16f9a249c63bf6d5 | 7 | 0 |
"""Generate a runnable training config + commands for one tuning.csv row.
Usage:
python scripts/gen_tuning_run.py tune_adamw_8k_lr0.0002 [--seed 42] [--nproc 2]
Reads the row from tuning.csv, writes a bergson `train` config under
/mnt/ssd-2/lucia/paper_runs/tuning/<run_id>_s<seed>/, mirrors it to
<repo>/configs/t... | EleutherAI/metasmoothness | scripts/gen_tuning_run.py | .py | 9293b2f9c45f39f6 | 7 | 0 |
"""Report live bergson jobs whose output has stopped advancing.
check_runs.py and filter_health.py both ask "does someone own this row and is the
claim fresh". Neither can see a hang, because a hung process is alive and a hang
produces no output at all -- and no output was being scored as no problem.
Two failures mad... | EleutherAI/metasmoothness | scripts/hung_check.py | .py | aa535b37c719cd2a | 7 | 0 |
"""MAGIC LDS from a bank's validation.csv — the grid's one implementation.
Usage:
python magic_lds.py <run_dir-or-validation.csv> [--n-boot 10000] [--seed 0]
Definitions (CONTROLS "Attribution / estimator"):
- ``magic_lds`` is the MEAN over queries of the per-query Spearman correlation
between each subset's sum... | EleutherAI/metasmoothness | scripts/magic_lds.py | .py | c847cf740397dc0f | 7 | 0 |
#!/usr/bin/env python3
"""Parameter-update norms for each run: ||theta_final - theta_0|| in L1 and L2.
Fills the delta_l1 / delta_l2 columns of experiments.csv, which have been empty for the
whole paper grid since the legacy eps-root-damping family was excluded (2026-08-22) --
the only rows that ever carried them. Rea... | EleutherAI/metasmoothness | scripts/param_delta.py | .py | fe84bad3e373cc7f | 7 | 0 |
"""
agent/incident_agent.py
Core agent that analyzes an error log and decides whether to create an incident.
Flow:
1. Receives AgentInput (log fields)
2. Builds a structured prompt explaining the decision rules
3. Calls Groq API with the prompt
4. Parses the JSON response into AgentOutput
5. Retur... | saikumar0210/ams-incident-agent | agent/incident_agent.py | .py | 1a4fc850cc891fcd | 7 | 0 |
"""
agent/models.py
Pydantic models for the Incident Agent.
Models:
AgentInput - Log fields sent to the agent for analysis
AgentOutput - Agent decision returned after analyzing the log
"""
from typing import Optional, Union
from pydantic import BaseModel, field_validator
# Input sent to the agent — contain... | saikumar0210/ams-incident-agent | agent/models.py | .py | 68d9e0e097bef0cc | 7 | 0 |
"""格式化工具集中点。
包含:
- format_cid: 统一 "CH-NN" 格式(13 处硬编码已统一)
- divmod3600: 时间 divmod 内核(narrative / countdown_widget 共用)
- format_hms: H:MM:SS / MM:SS 双格式
"""
from typing import Tuple
def format_cid(cid: int) -> str:
"""通道 ID → "CH-NN" 字符串。
全工程统一入口,修改格式只需改这一处。
之前 f"CH-{cid:02d}" 散落 13 处,现已集中。
Args:
... | Limit-r/Aging | app/core/formatting.py | .py | 0abda79c561d3753 | 7 | 0 |
"""全局历史数据环形缓冲(按 channel_id 索引)。
设计要点:
- 容量 = HISTORY_FRAMES(默认 90 帧 = 180s @ 2s/帧,对应详情页只显示最近 180 秒)
- 每帧存完整 ChannelReading
- append(reading) O(1)
- snapshot(cid) 返回该 channel 的 (timestamps, currents_matrix)
- currents_matrix: shape (4, N) 用于 I-t 曲线
- 详情页订阅 append 信号即可
线程安全:append 由 MainWindow 接收 on_reading 时调用(来自 Da... | Limit-r/Aging | app/data/history_buffer.py | .py | da8216aa0d3a5cab | 7 | 0 |
"""Qt signal 桥接:把 logger 消息推到 UI 线程。
约束:emit_log_message() 可以从任何线程调用,内部用 QMetaObject.invokeMethod
切到 Qt 主线程 emit。QtLogHandler 在主线程接收后 emit 同名 signal。
"""
import logging
from enum import IntEnum
from PyQt5.QtCore import QObject, pyqtSignal
class LogLevel(IntEnum):
DEBUG = 0
INFO = 1
WARNING = 2
ERRO... | Limit-r/Aging | app/observability/log_signals.py | .py | 91cc1f10fbc9fb05 | 7 | 0 |
"""CellUIManager:cell 视觉状态统一管理器。
迁移自 d:\\Aging_backup_20260717\\app\\ui\\cell_ui_manager.py
Phase 5 M7 改造:_STATE_TO_STATUS 字典删除,统一走
labels.DETECTION_STATE_PRESENTATION(视觉 + 文本合并表)。
"""
from __future__ import annotations
from typing import Optional
from app.core import labels
from app.services.cell_controller impor... | Limit-r/Aging | app/services/cell_ui_manager.py | .py | 92df5eaa1dd50bb5 | 7 | 0 |
"""QSS 合并:把分块模板拼接为一份完整 stylesheet。
调用入口:`StylesheetBuilder.render(tokens)`。
"""
from app.core.tokens import DesignTokens
from app.styles import templates as T
class StylesheetBuilder:
@staticmethod
def render(tokens: DesignTokens) -> str:
return "".join((
T.main_window(tokens),
... | Limit-r/Aging | app/styles/stylesheet.py | .py | e41727f9f285d0af | 7 | 0 |
"""页面路由(v3.0)。
薄壳:包裹 QStackedWidget + key→widget 映射。
- register(key, widget):注册页面(顺序与 NAV_ITEMS 保持一致)
- navigate(key):切换到 key 对应页面
- current_key:当前页面 key
- 首次 register 自动跳到第一页
"""
from __future__ import annotations
from typing import Dict, Optional
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QSt... | Limit-r/Aging | app/ui/router.py | .py | 1666e452fe56e8c2 | 7 | 0 |
#!/usr/bin/env python3
"""Quiz-gate scaffolding and grading for rule-architect.
Usage:
python3 quiz.py scaffold <project-root> [--lang ko|en] [--run-id ID]
python3 quiz.py grade <project-root> --run-id ID --results <results.json>
This script does NOT run the quiz. There is no portable way for a script to
spawn... | moveju112/rule-architect | scripts/quiz.py | .py | 9a0b31d1f3a718cc | 7.15 | 1 |
#!/usr/bin/env python3
"""PreToolUse guard: enforce the rules a machine can check, generated by rule-architect.
This file is copied into a project as `.claude/hooks/rule_guard.py` by
`hookgen.py`. It is generic: every project-specific detail lives in
`.rule-architect/hooks.json`, so the guard itself never needs regene... | moveju112/rule-architect | scripts/rule_guard.py | .py | f0b667869e0d15f9 | 7.15 | 1 |
#!/usr/bin/env python3
"""Verification script for rule-architect output.
Usage: python3 verify_rules.py <project-root> [--lenient] [--json]
[--index AI_RULES.md] [--docs-dir docs]
[--entries CLAUDE.md,AGENTS.md]
Checks:
1. AI_RULES.md exists + line budget (60 target, hard limit 80)
2. docs/*.md line bud... | moveju112/rule-architect | scripts/verify_rules.py | .py | 55b5367db75e3783 | 7.15 | 1 |
"""Scores the contradiction judge so a prompt change to it can be measured.
Issue #558: the judge read antonymy (two concepts defined in opposition) as
factual contradiction, at the same 1.00 confidence as a true date collision
-- two of three findings in a real run were false positives, and the
confidence gate carrie... | jasonssdev/openkos | evals/contradictions/run_contradictions_eval.py | .py | 5d6cf47cdecf2b41 | 7.24 | 2 |
"""Scores `suggest_edge_types` so a prompt change to it can be measured.
Issue #508 asked for confidence-threshold auto-acceptance and named a
cap-harness A/B as the gate. That gate did not exist: `evals/` scored
EXTRACTION and nothing scored this suggester at all, so any change to its
prompt would have been adopted o... | jasonssdev/openkos | evals/edge_typing/run_edge_typing_eval.py | .py | 770f8e785c96c6b0 | 7.24 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.