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 |
|---|---|---|---|---|---|---|
#!/usr/bin/env python3
"""Inject a changed detached-PR-monitor result on the next user prompt.
A monitor that tracks a consecutive-error streak (today only the
all-open-PRs monitor writes `error_streak`) is surfaced too once its last
N polls all errored with the same text: a watcher answering "no" forever
in the same ... | Morrison-Lab/ai-config | hooks/inject-pr-monitor-status.py | .py | d554b443d4506fe0 | 7.15 | 1 |
#!/usr/bin/env python3
"""PreToolUse guard: refuse expensive commands run on a cluster's head node.
On 2026-07-31 the shiva sysadmin reported CPU-load alerts on the login node,
caused by two `R -e '...devtools::test()...'` processes that had been running
for 262 and 90 CPU-minutes. The rule they broke was already writ... | Morrison-Lab/ai-config | hooks/no-heavy-work-on-head-node.py | .py | b762cc28b9174cd5 | 7.15 | 1 |
#!/usr/bin/env python3
"""Stop-hook guard: catch declaring a PR clean on a short check list alone.
`gh pr checks` does not enumerate every check run on a head. Measured
2026-08-19 on ucdavis/bcs#651 at a5f4f3f2: it printed 21 rows, all passing,
while `commits/<sha>/check-runs` returned 24 runs, one of them a `failure`... | Morrison-Lab/ai-config | hooks/no-incomplete-check-enumeration.py | .py | ec304c91eef0374a | 7.15 | 1 |
#!/usr/bin/env python3
"""Stop-hook guard: catch offering to file/record instead of just doing it.
`report-mistakes-proactively` and the user's standing `cai` both say to file
issues and record learnings *without* asking. The rule is read at load time;
the violation happens at composition time, in the closing paragrap... | Morrison-Lab/ai-config | hooks/no-offer-to-file.py | .py | 58901d6488b8261f | 7.15 | 1 |
#!/usr/bin/env python3
"""Stop-hook guard: catch asserting a PR's check state from a pre-push reading.
A CI status reading measures one commit and expires the instant a new commit
lands -- including your own. The failure is not forgetting to check. It is
checking, pushing, and then reporting the earlier reading in the... | Morrison-Lab/ai-config | hooks/no-stale-pr-status.py | .py | fbf045845a067d24 | 7.15 | 1 |
#!/usr/bin/env python3
"""Stop-hook guard: a successful commit must be pushed before reporting done."""
import hashlib
import json
import os
import re
import sys
import tempfile
# `(?![\w-])`, not `\b`. A word boundary sits happily between `commit` and
# `-`, because `-` is a non-word character -- so `git\s+commit\b` ... | Morrison-Lab/ai-config | hooks/no-unshipped-commit.py | .py | 1d86d54e000a7a7f | 7.15 | 1 |
#!/usr/bin/env python3
"""PreToolUse guard: refuse an unscoped whole-file punctuation replace.
`shared/coding/ascii-punctuation-in-source.md` bans em-dashes and friends
everywhere, and records the over-application too: a whole-file replace turns
a one-line finding into a huge diff. The rule exists and was broken twice... | Morrison-Lab/ai-config | hooks/no-whole-file-punct-replace.py | .py | 3929399db7aff83d | 7.15 | 1 |
#!/usr/bin/env python3
"""PreToolUse guard: refuse mutating, repo-scoped `gh` commands that omit -R.
Without an explicit -R/--repo, `gh` takes its target from the current working
directory. That is fine for reads and dangerous for writes: on 2026-07-29 a
`gh secret set CLAUDE_CODE_OAUTH_TOKEN` meant for Morrison-Lab/w... | Morrison-Lab/ai-config | hooks/require-gh-repo-flag.py | .py | 1c68f5bc954b643d | 7.15 | 1 |
"""Test the flag-cop-out-offer guard.
Two design choices carry the value, and each has its own negative case.
TAIL-ANCHORED: the failure is a recap that CLOSES on an offer. An offer
mid-message followed by real substance is usually a question posed in passing,
so it must not warn.
NOT whole-message: unlike no-placeh... | Morrison-Lab/ai-config | hooks/test-flag-cop-out-offer.py | .py | 7d11e852289b6828 | 7.65 | 1 |
"""HPC-tuned Dask helpers for single-node runs on NCI Gadi.
A drop-in convenience wrapper around dask.distributed.LocalCluster + Client that:
- Auto-detects CPU cores and memory from PBS/SLURM environment variables
- Routes all temp/spill files to $PBS_JOBFS for performance
- Configures aggressive memory spilling to p... | 21centuryweather/dask_setup | src/dask_setup/__init__.py | .py | 12fd65c210608acf | 7.15 | 1 |
"""Dask cluster creation and configuration."""
from __future__ import annotations
import logging
from pathlib import Path
import dask
from dask.distributed import LocalCluster
from .logging import get_logger
from .types import MemorySpec, TopologySpec
logger = get_logger("cluster")
#: Smallest per-worker memory ... | 21centuryweather/dask_setup | src/dask_setup/cluster.py | .py | d400258a951a635b | 7.15 | 1 |
"""Configuration management for dask_setup with profile support."""
from __future__ import annotations
import os
from dataclasses import dataclass, field
from typing import Any, ClassVar
from .error_handling import ConfigurationValidationError
@dataclass
class DaskSetupConfig:
"""Configuration for dask_setup w... | 21centuryweather/dask_setup | src/dask_setup/config.py | .py | 6090f72d7fb9c8b2 | 7.15 | 1 |
"""Dashboard utilities for dask_setup."""
from __future__ import annotations
import os
import socket
from urllib.parse import urlparse
from dask.distributed import Client
#: Set this to name the host users should SSH into for a dashboard tunnel.
LOGIN_HOST_ENV = "DASK_SETUP_LOGIN_HOST"
def get_login_host() -> str... | 21centuryweather/dask_setup | src/dask_setup/dashboard.py | .py | 148b7fa13f77ac8c | 7.15 | 1 |
"""Runtime environment detection for dask_setup.
Detects the host runtime so other modules can adapt their behaviour — for
example, rendering a clickable dashboard URL instead of an SSH tunnel hint
when running inside a Jupyter notebook.
Detection results are cached after the first call so repeated checks are free.
"... | 21centuryweather/dask_setup | src/dask_setup/environment.py | .py | d084ffb683f46230 | 7.15 | 1 |
"""Custom exceptions for the dask_setup package."""
from __future__ import annotations
class DaskSetupError(Exception):
"""Base exception for all dask_setup errors."""
pass
class InsufficientResourcesError(DaskSetupError):
"""Raised when system resources are insufficient for the requested configuratio... | 21centuryweather/dask_setup | src/dask_setup/exceptions.py | .py | 9700f4cecf900cd4 | 7.15 | 1 |
"""
setup_dask_client() — single-node Dask helper tuned for NCI Gadi.
- Detects cores/RAM from PBS/SLURM env, else psutil.
- Routes temp/spill to $PBS_JOBFS if available (fallback TMPDIR or /tmp).
- Picks processes/threads by workload_type ("cpu", "io", "mixed").
- Sets spill thresholds to avoid OOM.
- Returns (client... | 21centuryweather/dask_setup | src/dask_setup/legacy.py | .py | 8e9d4d2032398e51 | 7.15 | 1 |
"""Centralized logging configuration for dask_setup.
This module provides structured logging with consistent formatting across all dask_setup modules.
Supports both human-readable and structured (JSON) output formats.
"""
from __future__ import annotations
import logging
import os
import sys
class StructuredFormat... | 21centuryweather/dask_setup | src/dask_setup/logging.py | .py | fbb622b6173273b0 | 7.15 | 1 |
"""Resource detection from PBS/SLURM/psutil."""
from __future__ import annotations
import os
import re
import psutil
from .exceptions import ResourceDetectionError
from .logging import get_logger
from .types import ResourceSpec
logger = get_logger("resources")
def validate_memory_value(value_bytes: int, context:... | 21centuryweather/dask_setup | src/dask_setup/resources.py | .py | 34263ed67eb1878f | 7.15 | 1 |
"""Temporary directory management for dask_setup."""
from __future__ import annotations
import os
import re
import shutil
from pathlib import Path
#: Matches the leaf name this module creates, e.g. ``dask-12345``.
_DASK_TEMP_LEAF = re.compile(r"^dask-\d+$")
def _strip_dask_leaves(path: Path) -> Path:
"""Return... | 21centuryweather/dask_setup | src/dask_setup/tempdir.py | .py | 544a9a20af36d26e | 7.15 | 1 |
"""Worker topology decision logic for dask_setup."""
from __future__ import annotations
import math
from .exceptions import InvalidConfigurationError
from .logging import get_logger
from .types import TopologySpec
logger = get_logger("topology")
def _count_gpus() -> int:
"""Return the number of CUDA-capable G... | 21centuryweather/dask_setup | src/dask_setup/topology.py | .py | 93f798db92451058 | 7.15 | 1 |
"""Type definitions for the dask_setup package."""
from __future__ import annotations
from typing import NamedTuple
class ResourceSpec(NamedTuple):
"""Resource specification detected from the environment.
Attributes:
total_cores: Number of logical CPU cores available
total_mem_bytes: Total ... | 21centuryweather/dask_setup | src/dask_setup/types.py | .py | db1305ef5e213a86 | 7.15 | 1 |
"""Pytest configuration and fixtures for dask_setup tests."""
import os
from unittest.mock import patch
import pytest
@pytest.fixture
def isolated_env():
"""
Fixture that snapshots and restores os.environ.
Yields a dict-like object that can be modified during tests,
with automatic cleanup afterward... | 21centuryweather/dask_setup | tests/conftest.py | .py | c839825a1ad00254 | 7.65 | 1 |
"""Tests for spill compression functionality in dask_setup."""
import tempfile
from pathlib import Path
import dask
import pytest
from dask_setup.cluster import configure_dask_settings
from dask_setup.config import DaskSetupConfig
from dask_setup.error_handling import ConfigurationValidationError
class TestCompres... | 21centuryweather/dask_setup | tests/test_compression.py | .py | 6166510849cf359b | 7.65 | 1 |
"""Tests for enhanced error handling framework."""
import os
from unittest.mock import patch
import pytest
from src.dask_setup.error_handling import (
ClusterSetupError,
ConfigurationValidationError,
DependencyError,
EnhancedDaskSetupError,
ErrorContext,
ResourceConstraintError,
StorageCon... | 21centuryweather/dask_setup | tests/test_error_handling.py | .py | d3a4bbffffa7b199 | 7.65 | 1 |
"""Unit tests for dask_setup.exceptions module."""
import pytest
from dask_setup.exceptions import (
DaskSetupError,
InsufficientResourcesError,
InvalidConfigurationError,
ResourceDetectionError,
)
class TestDaskSetupError:
"""Test base DaskSetupError exception."""
@pytest.mark.unit
def... | 21centuryweather/dask_setup | tests/test_exceptions.py | .py | 210be95a07e25585 | 7.65 | 1 |
"""Tests for dask_setup.logging configuration."""
from __future__ import annotations
import logging
import pytest
from dask_setup.logging import DaskSetupLogger, configure_from_env, configure_logging, get_logger
@pytest.fixture(autouse=True)
def _restore_logging_state():
"""Logging config is process-global; p... | 21centuryweather/dask_setup | tests/test_logging.py | .py | f9a51a1bcb528bdd | 7.65 | 1 |
"""Unit tests for dask_setup.reporting."""
from __future__ import annotations
from unittest.mock import MagicMock
import pytest
from dask_setup.reporting import ClusterReport, cluster_report, worker_spill_bytes
class TestWorkerSpillBytes:
"""Spill must be read from the key distributed actually publishes.
... | 21centuryweather/dask_setup | tests/test_reporting.py | .py | d27ee81c60a88649 | 7.65 | 1 |
"""Unit tests for dask_setup.tune memory threshold tuning."""
from __future__ import annotations
from unittest.mock import MagicMock
import pytest
from dask_setup.tune import _apply_thresholds, tune_memory_thresholds
class FakeSpillBuffer:
"""Stand-in for distributed's SpillBuffer (a zict.Buffer subclass).
... | 21centuryweather/dask_setup | tests/test_tune.py | .py | 8d3b7fea5b60317a | 7.65 | 1 |
"""Unit tests for dask_setup.types module."""
import pytest
from dask_setup.types import MemorySpec, ResourceSpec, TopologySpec
class TestResourceSpec:
"""Test ResourceSpec NamedTuple."""
@pytest.mark.unit
def test_creation(self):
"""Test ResourceSpec creation with valid parameters."""
... | 21centuryweather/dask_setup | tests/test_types.py | .py | d6e8968b3453a2e6 | 7.65 | 1 |
"""Regression test for sync-brand-to-tokens.cjs.
The color parser required a parenthesized name in the Quick Reference row
(`#2563EB (name)`) and a bolded label in the color tables (`**Primary Blue**`),
neither of which the bundled starter template uses. As a result the base hex
came back `undefined` and `adjustBright... | UtkarshSingh-09/MerchentMind- | .agents/skills/ui-ux-pro-max/cli/assets/skills/brand/scripts/tests/test_sync_brand_to_tokens.py | .py | b6d046bb3113dc2b | 7.5 | 0 |
"""Test bootstrap for KittyMarket contract tests.
Two concerns handled here:
1. Windows gltest direct-mode fix — os.unlink() on the stdin temp file
while fd 0 still maps to it raises PermissionError; cleanup is
best-effort, so swallow it. No-op on POSIX.
2. SDK priming — the `genlayer` placeholder package on P... | rizqhika29/kitty-market | tests/conftest.py | .py | 02331ed099823f9a | 7.5 | 0 |
import asyncio
from logging.config import fileConfig
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config
from alembic import context
# AgentPay: pull the real DB URL from Settings (which reads .env) instead of
# the placeholder in alembic.i... | m-karthika14/agent-pay | backend/alembic/env.py | .py | 4deb795d527f4abf | 7 | 0 |
"""add password_hash to users
Revision ID: 207cea5307e4
Revises: a53d11a41c37
Create Date: 2026-08-26 14:06:07.143029
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '207cea5307e4'
down_revision: Union[str, Sequence[str]... | m-karthika14/agent-pay | backend/alembic/versions/207cea5307e4_add_password_hash_to_users.py | .py | 089969dd87487453 | 7 | 0 |
"""add razorpay_event_id to transactions
Revision ID: 4ae917627462
Revises: 517bfeae9544
Create Date: 2026-08-24 19:58:08.873046
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '4ae917627462'
down_revision: Union[str, Se... | m-karthika14/agent-pay | backend/alembic/versions/4ae917627462_add_razorpay_event_id_to_transactions.py | .py | 8dd2cfe5d18b35f9 | 7 | 0 |
"""add audit_events sequence column
Revision ID: 517bfeae9544
Revises: d8bab1ba6281
Create Date: 2026-08-24 18:56:28.625442
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '517bfeae9544'
down_revision: Union[str, Sequenc... | m-karthika14/agent-pay | backend/alembic/versions/517bfeae9544_add_audit_events_sequence_column.py | .py | 5da77ae2fa6798d1 | 7 | 0 |
"""add payload_json to audit_events
Revision ID: 6d3a31103127
Revises: 207cea5307e4
Create Date: 2026-08-26 14:42:04.249617
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision: str = '6d3a3... | m-karthika14/agent-pay | backend/alembic/versions/6d3a31103127_add_payload_json_to_audit_events.py | .py | b56a31c089249de8 | 7 | 0 |
"""add authorization_requests table
Revision ID: 89b10077c4b4
Revises: 6d3a31103127
Create Date: 2026-08-26 20:15:44.336431
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision: str = '89b10... | m-karthika14/agent-pay | backend/alembic/versions/89b10077c4b4_add_authorization_requests_table.py | .py | 827e2930bd29e6f4 | 7 | 0 |
"""add mandate_id to carts
Revision ID: a53d11a41c37
Revises: 4ae917627462
Create Date: 2026-08-25 20:22:02.710566
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'a53d11a41c37'
down_revision: Union[str, Sequence[str], N... | m-karthika14/agent-pay | backend/alembic/versions/a53d11a41c37_add_mandate_id_to_carts.py | .py | eb1f05b8cbad90be | 7 | 0 |
"""add user_id to audit_events
Revision ID: d0bc94f8aa37
Revises: 89b10077c4b4
Create Date: 2026-08-26 20:16:28.961779
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'd0bc94f8aa37'
down_revision: Union[str, Sequence[str... | m-karthika14/agent-pay | backend/alembic/versions/d0bc94f8aa37_add_user_id_to_audit_events.py | .py | 4722e8075037e5c4 | 7 | 0 |
"""initial schema
Revision ID: d8bab1ba6281
Revises:
Create Date: 2026-08-24 18:50:55.721237
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'd8bab1ba6281'
down_revision: Union[str, Sequence[str], None] = None
branch_la... | m-karthika14/agent-pay | backend/alembic/versions/d8bab1ba6281_initial_schema.py | .py | 1bf414cdfe777b4e | 7 | 0 |
"""add ai budget to users
Revision ID: f3a1c9b02e77
Revises: d0bc94f8aa37
Create Date: 2026-08-27 07:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'f3a1c9b02e77'
down_revision: Union[str, Sequence[str], No... | m-karthika14/agent-pay | backend/alembic/versions/f3a1c9b02e77_add_ai_budget_to_users.py | .py | a6303c2aa7c4550c | 7 | 0 |
"""
Purpose: Build the Merchant Revenue Agent's LangGraph workflow
(plan.md Section 13.5) -- the only LangGraph component in AgentPay
(plan.md Section 13, Section 10.1 rationale: this agent has a real
multi-step, stateful, tool-using workflow with a bounded revision loop,
which is exactly what LangGraph models well).
... | m-karthika14/agent-pay | backend/app/agents/merchant/graph.py | .py | c4b1f33235274c56 | 7 | 0 |
"""
Purpose: LangGraph node implementations for the Merchant Revenue Agent
(plan.md Section 13.4).
Each `make_*_node(session)` function is a factory that closes over the
active AsyncSession and returns the actual node coroutine -- LangGraph node
functions only receive `state`, so per-request dependencies like a DB
ses... | m-karthika14/agent-pay | backend/app/agents/merchant/nodes.py | .py | 9c6032bc75aeba6b | 7 | 0 |
"""
Purpose: Tool wrappers the Merchant Revenue Agent's graph nodes call
(plan.md Section 13.3).
Every wrapper here calls an existing AgentPay service function -- never its
own reimplementation (plan.md Section 17's "one source of truth" rule
applies just as much here as to the MCP tools). In particular,
submit_propos... | m-karthika14/agent-pay | backend/app/agents/merchant/tools.py | .py | a8e642b698affcc0 | 7 | 0 |
"""
Purpose: LLM-layer exceptions used to implement fail-closed behavior
(plan.md Rule 2 / Section 2 Rule 2: "If intent classification is unavailable
... BLOCK -> escalate").
Provider-neutral names (renamed from GeminiError/GeminiUnavailableError/
GeminiResponseError when the project switched its LLM provider from Gem... | m-karthika14/agent-pay | backend/app/ai/errors.py | .py | fe0c5daeeadc8280 | 7 | 0 |
"""
Purpose: Centralize all access to the LLM API (plan.md Section 12).
Originally written for Gemini (`google-genai`); the project now uses Groq,
switched at the user's explicit direction after Gemini's API quota was
persistently exhausted through Phases 6-11 (a real implementation blocker
per plan.md's "do not add a... | m-karthika14/agent-pay | backend/app/ai/llm_client.py | .py | 51dd61e430eaaa18 | 7 | 0 |
"""
Purpose: Pure hashing primitives for the AgentPay audit hash chain.
Responsibilities:
- Deterministically hash an audit event's payload (payload_hash).
- Chain a payload_hash to the previous event's hash to produce event_hash.
This module has no database or side effects — it is pure functions over
bytes/strings, ... | m-karthika14/agent-pay | backend/app/audit/hashing.py | .py | ea0147f15806a05f | 7 | 0 |
"""
Purpose: Append events to AgentPay's hash-chained audit log.
Responsibilities:
- Build a fully-hashed AuditEventRecord from caller-supplied event content,
chaining it to the current latest event.
- Persist that record as a new AuditEvent row.
This is the ONLY module allowed to write to the `audit_events` table ... | m-karthika14/agent-pay | backend/app/audit/service.py | .py | 2cf0566ea395afec | 7 | 0 |
"""
Purpose: Verify the integrity of the AgentPay hash-chained audit log.
Responsibilities:
- Walk an ordered sequence of audit events.
- Recompute each event_hash from (previous_hash, payload_hash) and check it
matches the stored value.
- Check each event's previous_hash matches the prior event's event_hash.
- Repo... | m-karthika14/agent-pay | backend/app/audit/verifier.py | .py | 8d640e2706dd93ea | 7 | 0 |
"""
Purpose: Create, list, and decide Claude-initiated authorization requests
(plan.md Phase 2).
Responsibilities:
- Let a buyer agent (Claude, via MCP) propose spending terms for a cart it
has already created -- before any mandate exists.
- Let a human Reject or Approve (optionally with edited terms) a pending
re... | m-karthika14/agent-pay | backend/app/authorization/service.py | .py | 48148a5e80ca8aff | 7 | 0 |
"""
Purpose: A user's own "AI Shopping Budget" -- an independent spending
ceiling they set themselves, before Claude ever creates an
authorization_request (plan.md Phase 4).
Stored directly on the User row (ai_budget_* columns) rather than a new
table: a user has at most one active budget at a time, and it's read on
e... | m-karthika14/agent-pay | backend/app/budgets/service.py | .py | 11f08a13fb181e72 | 7 | 0 |
"""
MedSignal - 最小鉴权层(P3-1)
设计原则:Demo 友好 + 安全叙事自洽
- 默认开放(无 token 也能访问,保证 Demo 流畅)
- 配置了 API_KEY 环境变量时,要求 X-API-Key 头校验
- 提供 get_current_user 依赖(基于 user_id 的简单会话)
这样"安全守门 Agent"名副其实,路演时可演示"未授权访问被拦截"。
"""
import hashlib
import logging
import os
from fastapi import Header, HTTPException, status
logger = logging.getLo... | yigenfeng0707-netizen/medsignal-agent | backend/app/auth.py | .py | 658c7a9e0afa66de | 7 | 0 |
from datetime import UTC, datetime
from sqlalchemy import (
Boolean,
Column,
DateTime,
Float,
ForeignKey,
Integer,
String,
Text,
)
from sqlalchemy.orm import DeclarativeBase, relationship
class Base(DeclarativeBase):
pass
class User(Base):
__tablename__ = "users"
id = C... | yigenfeng0707-netizen/medsignal-agent | backend/app/models.py | .py | c8273b666e14e671 | 7 | 0 |
"""
MedSignal - 智能体编排路由
P0-1 升级:激活真实 AI 链路
- 移除 mock 优先 return 逻辑
- 真实走 orchestrator → LLM/RAG
- 从数据库注入用户画像作为 LLM 上下文
- mock 仅作为 orchestrator 内部最终降级兜底
"""
import logging
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from app import crud
from app.auth import require_api_key
f... | yigenfeng0707-netizen/medsignal-agent | backend/app/routers/agents.py | .py | 301d3c6b93f954f4 | 7 | 0 |
"""
MedSignal - OCR 服务封装
基于 OCR.space API 的票据识别服务,支持:
- 医疗发票/票据图片识别
- 中文文字提取
- 结构化费用信息解析
- 降级到 mock 数据
"""
import logging
from typing import TYPE_CHECKING
import httpx
from app.config import settings
if TYPE_CHECKING:
from app.services.llm_service import LLMService
logger = logging.getLogger(__name__)
class... | yigenfeng0707-netizen/medsignal-agent | backend/app/services/ocr_service.py | .py | 029ca304045212db | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MedSignal - 数据库初始化脚本
读取 mock_data.json,将数据插入到数据库中。
支持 SQLite(开发环境)和 PostgreSQL(生产环境)。
用法:
# 使用默认SQLite
python init_db.py
# 使用PostgreSQL
DATABASE_URL=postgresql+asyncpg://user:pass@host:5432/dbname python init_db.py
# 指定JSON路径
python init_db.... | yigenfeng0707-netizen/medsignal-agent | backend/scripts/init_db.py | .py | c3b78293393ec219 | 7 | 0 |
"""
P0 升级冒烟测试:用 TestClient 验证所有 Router 真实数据链路
不依赖端口启动,直接走 ASGI in-process。
覆盖:agents / coverage / claims / health / policy / security
"""
import json
import os
import sys
# 让脚本能从 backend 目录直接运行时找到 app 包
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Windows GBK 控制台无法输出 emoji,遇到编码错... | yigenfeng0707-netizen/medsignal-agent | backend/scripts/smoke_test.py | .py | aa846fa79bbf0e14 | 7.5 | 0 |
"""线上全功能端到端验证(线上 Render 后端)
逐个测试 8 大功能,给出权威结论。
用法:
python verify_production.py # 默认线上地址
python verify_production.py --base http://localhost:8000 # 本地后端
"""
import argparse
import json
import urllib.request
import urllib.error
import ssl
import time
# 默认线上地址(可通过命令行参数覆盖)
DEFAULT_BASE... | yigenfeng0707-netizen/medsignal-agent | backend/scripts/verify_production.py | .py | d4ea9beddf320c88 | 7 | 0 |
"""报销计算引擎单元测试(P3-3)
覆盖:起付线/报销比例/封顶线/乙类自付/大病保险/调整因子/多场景对比
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app.services import claims_engine as ce
class TestClaimsEngineBasic:
"""基础计算测试"""
def test_simple_outpatient_employee(self):
"""职工... | yigenfeng0707-netizen/medsignal-agent | backend/tests/test_claims_engine.py | .py | aa74e3e0bcc02e95 | 7.5 | 0 |
"""健康风险评分引擎测试(P3-3)
覆盖:5维评分/用药相互作用/主动预警/慢病推断
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app.services import health_engine
def _profile(name="测试用户", age=60, chronic=None, meds=None, visit_6m=3):
"""构造测试用户画像"""
return {
"found": True... | yigenfeng0707-netizen/medsignal-agent | backend/tests/test_health_engine.py | .py | e89dc62258ecb6b5 | 7.5 | 0 |
"""政策精准匹配引擎测试(P3-3)
覆盖:慢病匹配/省钱计算/年龄差异化/知识库关键词匹配
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app.services import policy_matcher
def _profile(name="测试用户", age=60, chronic=None, ins_type="职工医保",
emp="在职", annual_med=5000, annual_drug=2000... | yigenfeng0707-netizen/medsignal-agent | backend/tests/test_policy_matcher.py | .py | 5e4e6ef4d5667cc4 | 7.5 | 0 |
#!/usr/bin/env python3
"""Standalone agent output evaluator using the 5-axis rubric.
Reads a task description and agent output from stdin or files,
scores each axis, and prints a structured evaluation report.
Usage:
# Pipe output directly
echo "Task: Add retry logic" | evaluate.py --output response.txt
#... | stewardyohanes/meleo | .claude/skills/agent-self-evaluation/scripts/evaluate.py | .py | 5f21321971c23ffa | 7 | 0 |
#!/usr/bin/env python3
"""
specback build-trace.py
Extracts every `<!-- REF: path:start-end -->` written in drafts/*.md (or
final/*.md), matches them against the source units in
`.specback/source-map.json`, and produces `.specback/trace.json`.
This produces in one pass:
- Spec → source citations (the REF the agent wr... | nekolife1984/specback | scripts/build-trace.py | .py | 9533e2b9e61dd3e4 | 7 | 0 |
#!/usr/bin/env python3
"""
common.py — shared micro-helpers for specback scripts.
Several scripts previously re-implemented the same tiny helpers with subtly
different behaviour: UTC timestamps, safe JSON read/write, SHA-256 digests and
the ubiquitous ``--specback-dir`` argparse block. This module is the single
home ... | nekolife1984/specback | scripts/common.py | .py | 65957f051b32a7a6 | 7 | 0 |
#!/usr/bin/env python3
"""
git_utils.py — shared, safe git helpers for specback scripts.
The helpers here exist to keep git subprocess commands safe from argument
injection. A user-controlled "base" value (``--base`` CLI argument or
``state.json.generated_at_commit``) is passed straight into a ``git diff
<base>`` comm... | nekolife1984/specback | scripts/git_utils.py | .py | 86499c9cb7b021ff | 7 | 0 |
#!/usr/bin/env python3
"""
refutils.py — shared REF marker parsing and resolution helpers.
Several scripts previously re-implemented the same regexes and scan/resolve
loops with slightly different shapes: `<!-- REF: path:line -->` parsing,
`<!-- REF: SRC-NNNN -->` parsing, and the path→unit index matching used to
reso... | nekolife1984/specback | scripts/refutils.py | .py | d0d8c601b6fce11f | 7 | 0 |
#!/usr/bin/env python3
"""Restore a source-map.json to old IDs + append new units (after full regeneration).
Background: a full re-run of source-map.py renumbers SRC-IDs in file-scan
order, silently breaking every existing `<!-- REF: SRC-NNNN -->` marker in
the spec (build-trace.py does not error on a valid-looking ID... | nekolife1984/specback | scripts/restore-sourcemap-from-trace.py | .py | c04343d5bbd042cf | 7 | 0 |
"""specback source-map v2 — layer 1: framework detection.
Sniffs project manifests and directory conventions to decide which framework a
language is using, so layer-2 extractors can pick the right query set (e.g. the
same Python ``def`` is an endpoint under FastAPI but a plain callable elsewhere).
Detection is best-e... | nekolife1984/specback | scripts/source_map_v2/detect.py | .py | fc9ba0b32c85ea99 | 7 | 0 |
"""specback source-map v2 — layer 2: per-language extractor registry.
Each language gets one extractor (a subclass of ``Extractor``) registered here.
M0 ships an EMPTY registry: the three-layer skeleton runs end to end, but any
file whose language has no registered extractor falls back to a coarse
file-level unit and ... | nekolife1984/specback | scripts/source_map_v2/extractors/__init__.py | .py | e495498dcf5b5f77 | 7 | 0 |
"""M6 — C extractor (tree-sitter based).
Extracts C constructs:
- struct_specifier → c_struct
- enum_specifier → c_enum
- union_specifier → c_union
- type_definition → c_typedef
- function_definition → c_function
"""
from __future__ import annotations
from typing import Callable
from .. import taxonomy
fr... | nekolife1984/specback | scripts/source_map_v2/extractors/c_ext.py | .py | e814a6101d2f19e0 | 7 | 0 |
"""M3 — Python extractor (tree-sitter based, framework-aware).
Recovers what the v1 regex dropped:
- async def endpoints (FastAPI/Flask) with method + path role-typing
- Pydantic schemas (BaseModel/RootModel subclasses) as role=schema
- Django models as role=model
- Celery tasks / FastAPI middleware / exceptio... | nekolife1984/specback | scripts/source_map_v2/extractors/python_ext.py | .py | 803bc838e778a1c2 | 7 | 0 |
"""M4 — Ruby / Rails extractor (tree-sitter based).
Upgrades the v1 behaviour (every class -> undifferentiated ``ruby_class``) to the
Rails 14-unit catalogue, role-typed by file path (the catalogue is path-driven):
controllers / models / concerns / services / jobs / mailers / helpers / lib,
plus controller actions (en... | nekolife1984/specback | scripts/source_map_v2/extractors/ruby_ext.py | .py | e5474a4096051f99 | 7 | 0 |
"""tree-sitter helpers shared by the language extractors.
tree-sitter is an OPTIONAL dependency (design risk #1): if it (or a grammar) is
not installed, ``have(language)`` returns False and the language extractor does
not register, so the pipeline falls back to file-level units + a loud warning.
"""
from __future__ i... | nekolife1984/specback | scripts/source_map_v2/extractors/tshelpers.py | .py | 6a96acac686793e3 | 7 | 0 |
"""specback source-map v2 — orchestrator wiring the three layers together.
layer 1 detect.detect_frameworks(root)
layer 2 extractors.get_extractor(language).extract(...)
layer 3 map to taxonomy + assemble SourceMap (with loud warnings)
M0 goal: this runs end to end on any tree and produces a schema-0.2.0 Source... | nekolife1984/specback | scripts/source_map_v2/pipeline.py | .py | 08047ecc2957b701 | 7 | 0 |
"""CLI output-path guard tests for source_map_v2 (Issue #318).
Run from the scripts/ directory:
python -m pytest source_map_v2/tests/test_cli_output_guard.py -q
Covers the --output symlink rejection and the atomic-write behaviour of
main() — the link target must never be overwritten, and a normal write
must produ... | nekolife1984/specback | scripts/source_map_v2/tests/test_cli_output_guard.py | .py | 485e2e965c4cb2c8 | 7.5 | 0 |
"""Exact balanced-ternary word arithmetic and integer helpers.
Word addition uses the carry rewrite in :mod:`bt.normalization`.
Trial-division helpers are for inspection of individual values, not a
primality library.
"""
from __future__ import annotations
from bt.normalization import rewrite_sum
from bt.representati... | sneakyweasel/balanced_ternary | src/bt/arithmetic.py | .py | b824b08b94c61155 | 7 | 0 |
"""Deterministic residue automaton for a single modulus q.
States are residues ``{0, ..., q-1}``. The automaton reads a balanced
ternary word most-significant digit first. If the current prefix has
residue ``r``, appending digit ``a in {-1, 0, +1}`` yields
r' ≡ 3r + a (mod q).
This is independent of whether ``q... | sneakyweasel/balanced_ternary | src/bt/automata/modular.py | .py | c28f45d9b5a23d89 | 7 | 0 |
"""Newton-class image of the cubic residual machine of ``x^3``.
Along an LSD-first trit word ``w`` of length ``m`` with packed prefix
``p = p(w)``,
f_w(x) = 3^{2m} x^3 + 3^{m+1} p x^2 + 3 p^2 x + D^m(p^3)
= D^m( (p + 3^m x)^3 ).
The finite-horizon class is the Newton residue ``Φ_k(f_w)``. Then
M_... | sneakyweasel/balanced_ternary | src/bt/calculus/cubic.py | .py | cfcf415821d2965a | 7 | 0 |
"""Digit derivative ``D`` as a calculus operator.
Wraps :func:`bt.operators.digit_derivative` and :func:`bt.operators.lsd_digit`.
Does not reimplement balanced-ternary encoding.
"""
from __future__ import annotations
from bt.calculus.trit import Trit, as_trit
from bt.operators import digit_derivative, lsd_digit, mul... | sneakyweasel/balanced_ternary | src/bt/calculus/derivative.py | .py | 4942c2d75d45e49f | 7 | 0 |
"""Exact sum and product rules for the digit derivative.
The sum correction reuses :func:`bt.normalization.rewrite_sum`. The product
rule is the twisted Leibniz identity
D(xy) = lsd(x) D(y) + lsd(y) D(x) + 3 D(x) D(y)
with ``lsd(xy) = lsd(x) lsd(y)``. This is not the ordinary product rule.
"""
from __future__ i... | sneakyweasel/balanced_ternary | src/bt/calculus/differential.py | .py | b6dcaf47dbf5045d | 7 | 0 |
"""Bounded identity discovery. Candidates are never auto-promoted to theorems."""
from __future__ import annotations
from dataclasses import dataclass
from bt.calculus.expressions import ED, EI0, EIm, EInt, EIp, ENeg, EShift3, Expr, render
from bt.calculus.rewrite import rewrite_expr
from bt.calculus.semantics import... | sneakyweasel/balanced_ternary | src/bt/calculus/discovery.py | .py | 132042b55d70ddb4 | 7 | 0 |
"""Digit integrals ``I_a`` and projections ``P_a = I_a ∘ D``.
``I_a(x) = a + 3x`` for ``a in {-1, 0, +1}``. ``I_0 = S``.
Integer maps wrap :mod:`bt.operators`; they do not re-encode words.
"""
from __future__ import annotations
from bt.calculus.derivative import D, S, lsd
from bt.calculus.trit import Trit, as_trit
f... | sneakyweasel/balanced_ternary | src/bt/calculus/integral.py | .py | 6b37250de589e2a1 | 7 | 0 |
"""Integer jets and function-side residual section jets.
Integer jet (existing object, kept):
J_k(n) = (lsd(n), lsd(D(n)), ..., lsd(D^{k-1}(n)))
Function jet along a section word ``w = a0...a_{k-1}``:
f_ε = f
f_{wa} = 𝔇_a(f_w)
b_i = ρ_{a_i}(f_{a0...a_{i-1}})
This is a path of residual polynomials,... | sneakyweasel/balanced_ternary | src/bt/calculus/jets.py | .py | 4144b30b25982881 | 7 | 0 |
"""Lifting trees of polynomial congruences ``f(x) ≡ 0 (mod 3^k)``.
A residue modulo ``3^k`` is a balanced-ternary word ``w = (a_0,…,a_{k-1})``
of length ``k`` with value ``n_w = Σ a_i 3^i``, which ranges bijectively
over ``[-(3^k-1)/2, (3^k-1)/2]``.
Iterating the section reconstruction ``f(a+3x) = ρ_a(f) + 3 𝔇_a f(x... | sneakyweasel/balanced_ternary | src/bt/calculus/lifting.py | .py | 0408fc74672ee9c2 | 7 | 0 |
"""Finite-horizon Myhill–Nerode equivalence for residual polynomial states.
Two states are equivalent at horizon ``k`` when they emit the same output
word on every balanced input of length ``k``. Equivalently, by prefix
locality, they produce the same length-``k`` integer jet of ``f(n_w)``
for every section word ``w``... | sneakyweasel/balanced_ternary | src/bt/calculus/myhill_nerode.py | .py | 41b7400e73092e4a | 7 | 0 |
"""Normal forms for the operator-only fragment ``{D, I_a, S, N}``."""
from __future__ import annotations
from bt.calculus.expressions import (
ED,
EI0,
EIm,
EInt,
EIp,
ENeg,
EShift3,
ETrit,
Expr,
render,
)
from bt.calculus.rewrite import rewrite_expr
from bt.calculus.semantics ... | sneakyweasel/balanced_ternary | src/bt/calculus/normalization.py | .py | 5ee11d403ddeecc0 | 7 | 0 |
"""Bounded-alphabet transducers for ``hat D`` and residual/normalizer composition.
``hat D`` on unbounded integer coefficients is not one finite-state
transducer. For a fixed bound ``B``, LSD normalization is a Mealy machine
with carry in ``[-B, B]``, and canonical ``hat D`` is that machine followed
by dropping the fi... | sneakyweasel/balanced_ternary | src/bt/calculus/normalizer_compose.py | .py | c4d1482a9703515c | 7 | 0 |
"""Three-way comparison as a trit-valued operation."""
from __future__ import annotations
from bt.calculus.trit import Trit, as_trit, sign_trit
def _require_int(n: int, name: str = "n") -> int:
if isinstance(n, bool) or not isinstance(n, int):
raise TypeError(f"{name} must be int, got {type(n).__name__}... | sneakyweasel/balanced_ternary | src/bt/calculus/order.py | .py | 0ef8db767ed7b16a | 7 | 0 |
"""Polynomial function congruence modulo ``3^k``.
Finite-horizon residual equivalence of ordinary ``Z[x]`` polynomials is
function congruence:
f ≡_k g iff 3^k | (f-g)(n) for every integer n.
The kernel
I_k = { h ∈ Z[x] : h(n) ≡ 0 (mod 3^k) for all n }
is **not** ``3^k Z[x]``. It is the set of polynomial... | sneakyweasel/balanced_ternary | src/bt/calculus/poly_congruence.py | .py | 6dd11335c20d7fb0 | 7 | 0 |
"""Closed form of quadratic residuals of ``x^2``.
Every residual along a trit word ``w`` (LSD-first) is
f_w(x) = 3^{|w|} x^2 + 2 p(w) x + D^{|w|}(p(w)^2)
where ``p(w)`` is the packed prefix. Distinct prefixes give distinct
polynomials, and for degree ``≤ 2`` the Myhill–Nerode class at horizon
``k`` is exactly th... | sneakyweasel/balanced_ternary | src/bt/calculus/quadratic.py | .py | 768aa8da7fa9c975 | 7 | 0 |
"""Residual Mealy machine of a polynomial section calculus.
For a state ``f ∈ Z[x]`` and input trit ``a ∈ {-1,0,+1}``:
ρ_a(f) = [f(a)]_3
δ(f, a) = 𝔇_a f
f --[a / ρ_a(f)]--> 𝔇_a f
The emitted word on a trit path ``w`` is the first ``|w|`` balanced
output trits of ``f`` along that section path. Prefix... | sneakyweasel/balanced_ternary | src/bt/calculus/residual.py | .py | 6326f5a9e56f0769 | 7 | 0 |
"""Classified rewrite rules for operator words and calculus expressions.
Word-level rules are the canonical store previously kept in
``research.operator_dynamics.algebra``. Tree rules are added only when
they are exact integer identities.
"""
from __future__ import annotations
from dataclasses import dataclass
from... | sneakyweasel/balanced_ternary | src/bt/calculus/rewrite.py | .py | f601c150b65bd8ea | 7 | 0 |
"""Integer and word semantics for calculus expressions."""
from __future__ import annotations
from bt.calculus.derivative import D, lsd
from bt.calculus.expressions import (
EAdd,
ECmp3,
ED,
EI0,
EIm,
EInt,
EIp,
EMul,
ENeg,
ENormalize,
ESelect3,
EShift3,
ETrit,
... | sneakyweasel/balanced_ternary | src/bt/calculus/semantics.py | .py | 3c59fafe38652437 | 7 | 0 |
"""Metrics, digit statistics, and executable balanced-ternary identities.
Theorem status lives in documentation. Functions here are exact
computations, not proofs.
"""
from __future__ import annotations
from collections.abc import Iterator
from dataclasses import dataclass, field
from bt.automata.modular import Mod... | sneakyweasel/balanced_ternary | src/bt/metrics.py | .py | 34612e6decc51841 | 7 | 0 |
"""Canonical carry / borrow rewrite for balanced ternary coefficients.
The local identity is the same algorithm previously used by word addition:
2 = 3 - 1, -2 = -3 + 1
so a coefficient sum ``s`` in ``{-3,...,3}`` is rewritten as
``digit + 3 * carry`` with ``digit in {-1, 0, +1}``.
"""
from __future__ import... | sneakyweasel/balanced_ternary | src/bt/normalization.py | .py | ef6f9e9f6b3ce5ea | 7 | 0 |
"""Addition, convolution, and FMA via coefficients, then normalize.
Values always match ``encode`` of the integer result. Costs need not.
There is no generic sparsity-preservation theorem.
"""
from __future__ import annotations
from dataclasses import dataclass
from bt.normtheory.coeffword import CoeffWord
from bt.... | sneakyweasel/balanced_ternary | src/bt/normtheory/arithmetic.py | .py | fdb2e0c3ad3bd70a | 7 | 0 |
"""Digit calculus on coefficient words versus after normalization.
``D_coeff`` drops ``c_0``. ``I_a`` prepends a trit ``a``. ``S`` prepends ``0``.
``D(normalize(P)) = normalize(D_coeff(P))`` fails when ``c_0`` is not a
trit: the low coefficient still contributes to the integer value until
it is rewritten.
"""
from _... | sneakyweasel/balanced_ternary | src/bt/normtheory/calculus_link.py | .py | db1598ec88bdaadd | 7 | 0 |
"""
Mock notification gateway — SMS + email.
Hackathon: writes human-readable logs (stored on the Alert record and shown
in the dashboard's alert feed). No external calls.
PRODUCTION INTEGRATION POINT:
* SMS -> NIC SMS Gateway / MSG91 / Twilio (send_sms)
* Email-> NIC email / SendGrid / AWS SES (send_ema... | stunninghacker/CashGuard-AI | backend/alerts/notifier.py | .py | 905b22f1f046752a | 7 | 0 |
"""
Alert scheduler — runs the risk engine periodically and generates alerts.
APScheduler BackgroundScheduler triggers an alert cycle every
SCHEDULER_INTERVAL_MINUTES (default 60). Each cycle:
1. scores every ATM for the next 24h
2. flags ATMs above RISK_THRESHOLD
3. dedupes against open alerts (cooldown w... | stunninghacker/CashGuard-AI | backend/alerts/scheduler.py | .py | b6205163ce033371 | 7 | 0 |
"""
Tamper-evident ledger endpoints (Blockchain & Cybersecurity theme — Phase 4).
GET /ledger -> list blocks (chain-of-custody record)
GET /ledger/verify -> recompute the SHA-256 chain; reports integrity
POST /ledger/tamper-demo -> DEMO ONLY (ALLOW_TAMPER_DEMO=true): flip one block
... | stunninghacker/CashGuard-AI | backend/api/routes/ledger.py | .py | 0781e16660363309 | 7 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.