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 """ 🜁∀ BaseClient — Abstract parent for all sovereign AI clients Provides conversation history, trimming, and phi-harmonic identity. """ import logging from typing import List, Dict, Any, Optional from abc import ABC, abstractmethod logger = logging.getLogger("sovereign_core.base") class Bas...
AxiomicCoreness/hello_world.py
clients/base_client.py
.py
7ae069fb92453cb2
7.15
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 🜁∀ MISTRAL SOVEREIGN CLIENT with quantum daemon integration ∀🜁 """ import os from typing import Optional, Dict, Any from core.quantum import QuantumSovereignDaemon from core.agents import Agents class MTLSConfig: """Placeholder for mTLS configuration.""" p...
AxiomicCoreness/hello_world.py
clients/mistral.py
.py
184c5f4396283d1b
7.15
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ compute_seal.py – Compute SHA3-256 seals for ledger entries. Usage: python3 compute_seal.py < ledger_aggregate.yaml > ledger_sealed.yaml # Or process a single entry file python3 compute_seal.py ledger/0351.yaml # Or process all entries in led...
AxiomicCoreness/hello_world.py
compute_seal.py
.py
03c54319c91f924d
7.15
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ core/__init__.py – Sovereign service entry point with automatic restart. Usage: python -m core or python core/__init__.py Environment: RESTART_INTERVAL_HOURS = 6 (default, float) """ import asyncio import os import signal import subprocess import sys im...
AxiomicCoreness/hello_world.py
core/__init__.py
.py
3a60086c109a200f
7.15
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Activate sovereign core + optional sidecar. python -m core.activate --dry-run python -m core.activate --sidecar-only --once python -m core.activate --core # long-running uvicorn supervisor """ from __future__ import annotations import argparse import json im...
AxiomicCoreness/hello_world.py
core/activate.py
.py
298e1d803ebbe042
7.15
1
#!/usr/bin/env python3 """ 🜁∀ SovereignConfig — Environment & API Key Management """ import os from typing import Dict from dotenv import load_dotenv load_dotenv() class SovereignConfig: """Sovereign configuration manager with φ-harmonic defaults.""" def __init__(self): self.grok_api_key = os.gete...
AxiomicCoreness/hello_world.py
core/config.py
.py
b8000c98777a3c41
7.15
1
""" core/diffuse_kl_cache.py Diffuse KL hashed cache implementation (Entry 616 materialised). API: DiffuseKLCache(hash_entry, add_entry, cache_distribution, base_distribution, diffuse_kl, objective, summary, health_report) This implementation is deterministic, uses SHA3-256 modulo M, stable soft...
AxiomicCoreness/hello_world.py
core/diffuse_kl_cache.py
.py
759f46c6eb321ecb
7.15
1
from typing import Dict, Any, Optional from clients.base_client import BaseClient from .config import SovereignConfig try: # Optional import of the DiffuseKLCache for ledger caching/health from core.diffuse_kl_cache import DiffuseKLCache except Exception: DiffuseKLCache = None class SovereignOrchestrator...
AxiomicCoreness/hello_world.py
core/orchestrator.py
.py
da2b852f6bf24016
7.15
1
#!/usr/bin/env python3 """ Precompute FRB bridge lattice weights for the next convergence window. Outputs JSON (default /tmp/lattice_weights.json) for CronJob + Grafana injection. Seal: ∀∞φ² · GRAFANA_CRD_LATTICE_8645 · SEALED """ from __future__ import annotations import json import math import os import time from d...
AxiomicCoreness/hello_world.py
cronjobs/precompute_lattice.py
.py
c1e2067355db9efe
7.15
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Sovereign CMAC-512 (dual AES-256 construction placeholder) Deterministic, side-channel-free MAC for ledger witness chains. AES math remains pure finite-field arithmetic; no telemetry required. """ from __future__ import annotations import hashlib import hmac from typ...
AxiomicCoreness/hello_world.py
cryptography/cmac512.py
.py
6e34d6afe21a2d9c
7.15
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Merkle tree (SHA-256) over ordered leaf digests. Seal: ∀∞φ² · APP_MAIN_MERKLE_8653 · SEALED """ from __future__ import annotations import hashlib from pathlib import Path from typing import Any, Dict, List, Optional, Sequence, Tuple def sha256_hex(data: bytes) -> st...
AxiomicCoreness/hello_world.py
cryptography/merkle.py
.py
3abd657d742e8e99
7.15
1
"""Data models for supermarket simulator.""" from dataclasses import dataclass from typing import List, Optional from datetime import datetime import uuid @dataclass class Product: """Represents a product in the supermarket.""" name: str price: float quantity: int category: str product_id: str...
upperambassadorarbor/supermarket-simulator-tool
supermarket_simulator_tool/models.py
.py
20db1aab533dc67f
7
0
"""Core supermarket simulator engine.""" from typing import List, Optional from .models import Product, Customer, Transaction from datetime import datetime import random class SupermarketSimulator: """Simulates a supermarket environment with inventory and transactions.""" def __init__(self, name: str = "Supe...
upperambassadorarbor/supermarket-simulator-tool
supermarket_simulator_tool/simulator.py
.py
9f8a6007cf9326cc
7
0
"""Trainer module for optimizing supermarket operations.""" from typing import List, Dict, Tuple from .models import Product from .simulator import SupermarketSimulator import random class Trainer: """Provides optimization and training methods for supermarket simulation.""" def __init__(self, simulator: Supe...
upperambassadorarbor/supermarket-simulator-tool
supermarket_simulator_tool/trainer.py
.py
4b0c3541be6e116e
7
0
#!/usr/bin/env python3 """attention-reminder.py — PreToolUse / UserPromptSubmit hook. Once per --round token window, emit a reminder listing active MCP servers so context drift doesn't make the model fall back to built-in tools. Stdin: PreToolUse or UserPromptSubmit JSON payload (uses .transcript_path and .hook_event...
pontscho/prompt-heaven
ClaudeCode/hooks/attention-reminder.py
.py
1beb62c6bd82bced
7.24
2
#!/usr/bin/env python3 """ DuckDuckGo search script using only Python standard library. Usage: python3 search_duckduckgo.py "search phrase" python3 search_duckduckgo.py "query1" "query2" "query3" # batch mode """ import sys import urllib.request import urllib.parse import re import html def clean_html_tags(text...
pontscho/prompt-heaven
ClaudeCode/scripts/search_duckduckgo.py
.py
1529286a073814c0
7.24
2
#!/usr/bin/env python3 """ GitHub code search using grep.app API with Python standard library only. Usage: python3 search_github.py "search query" [options] python3 search_github.py "query1" "query2" "query3" # batch mode """ import sys import urllib.request import urllib.parse import json import argparse import ...
pontscho/prompt-heaven
ClaudeCode/scripts/search_github.py
.py
0784f80636e0bf29
7.24
2
#!/usr/bin/env python3 """ CMakeLists.txt Validator - Detect legacy CMake patterns This script checks CMakeLists.txt files for legacy patterns and suggests modern target-based alternatives following CMake best practices. Usage: python3 cmake-validator.py [file_or_directory] python3 cmake-validator.py CMakeLis...
pontscho/prompt-heaven
ClaudeCode/skills/cmake/cmake-validator.py
.py
0429594f8f3eb2c2
7.24
2
#!/usr/bin/env python3 """ Static Build Helper for CMake Projects Automates building CMake projects with static linking configurations for different platforms. Usage: python3 build-static.py python3 build-static.py --build-dir build-static python3 build-static.py --verify python3 build-static.py --cle...
pontscho/prompt-heaven
ClaudeCode/skills/static-linking/build-static.py
.py
80b190bd14f86aa0
7.24
2
"""Shared helpers for the p:wiki scripts. stdlib-only, Python 3.9+. No third-party dependencies, no LLM calls. Implements a deliberately minimal frontmatter parser covering only the subset documented in the p:wiki schema (SKILL.md §5): - top-level `key: scalar` - one level of nesting (block `key:` then indented `s...
pontscho/prompt-heaven
ClaudeCode/skills/wiki/scripts/_wikilib.py
.py
fe27abc341d8e2e0
7.24
2
#!/usr/bin/env python3 """freshness.py -- read-only staleness detector for the p:wiki docs tree. Determines which wiki pages may be out of date by comparing each page's `verified.commit` against the current tree, using git only. No LLM, no code navigation: this is the cheap pre-filter that tells the LLM lint pass *whi...
pontscho/prompt-heaven
ClaudeCode/skills/wiki/scripts/freshness.py
.py
35b2455abe83879d
7.24
2
#!/usr/bin/env python3 """reindex.py -- regenerate docs/INDEX.md and audit the wiki structure. Deterministic, stdlib-only, no LLM. Walks the wiki root, reads every page's frontmatter, and: - regenerates INDEX.md (one line per page, grouped by type), and - audits for orphans (no inbound link), duplicate slugs, and ...
pontscho/prompt-heaven
ClaudeCode/skills/wiki/scripts/reindex.py
.py
47d4c1e8dddbfae2
7.24
2
#!/usr/bin/env python3 """ Task Batch Planner - Dependency-aware batch optimization for task execution. Usage: task-batch-planner.py /path/to/requirements.yaml [--max-score=4] Algorithm: 1. Build dependency graph from tasks 2. Topological sort to create execution levels 3. Detect file conflicts within each level 4. F...
pontscho/prompt-heaven
Scripts/task-batch-planner.py
.py
20d256effac977a1
7.24
2
#!/usr/bin/env python3 """ Extract implementation plan from requirements.yaml in compact YAML format. Usage: python3 task-implementation-plan.py [path_to_requirements.yaml] [task_id1] [task_id2] ... If task_id(s) are provided, only those specific tasks will be displayed. If no task_id is provided, the complete implemen...
pontscho/prompt-heaven
Scripts/task-implementation-plan.py
.py
ab61afcd8f89eaf0
7.24
2
#!/usr/bin/env python3 """ Task Plan - Combined task status and batch planning for requirements.yaml. Usage: task-plan.py /path/to/requirements.yaml [--max-score=6] Features: 1. Display all tasks with status, size, and description 2. Show summary statistics (completed, pending, in_progress) 3. Dependency analysis wit...
pontscho/prompt-heaven
Scripts/task-plan.py
.py
94a68f866521967b
7.24
2
#!/usr/bin/env python3 """ Display raw YAML blocks for specific tasks from requirements.yaml file. Usage: task-show-details.py task-001 task-002 task-003 ... """ import re import sys import os def find_task_yaml_block(content, task_id): """Find and extract the raw YAML block for a specific task""" # Find the...
pontscho/prompt-heaven
Scripts/task-show-details.py
.py
cceb12444ee5672b
7.24
2
#!/usr/bin/env python3 """Convert Trac/MoinMoin wiki syntax to Markdown.""" import os import re import sys from urllib.parse import unquote link_root = os.environ.get("LINK_ROOT") trac_root = os.environ.get("TRAC_ROOT") add_h_ids = os.environ.get("ADD_H_IDS") _code_blocks = [] def link_wiki2md(t): t = unquote(...
pontscho/prompt-heaven
Scripts/trac2md.py
.py
a4c3738e5c333661
7.24
2
#!/usr/bin/env python3 """OWASP Benchmark adapter — CSV parser + test case loader (v0.31).""" import csv, re from dataclasses import dataclass from pathlib import Path from typing import Dict, List, Tuple @dataclass class TestCase: test_id: str file_path: str cwe: str is_vulnerable: bool def parse_e...
poliakarmai/gsc
benchmark/adapter.py
.py
b4c430c78fe7868d
7.39
5
#!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 # Copyright (c) 2026 Алексей Поляков # Licensed under Apache License 2.0 — see LICENSE """GSC performance benchmarks — synthetic repos at 10K / 100K / 1M LOC. Measures wall-clock scan time, peak RSS (via RUSAGE_CHILDREN), and findings count for each size. B...
poliakarmai/gsc
benchmark/benchmark_perf.py
.py
8860d1ff189bf2f8
7.39
5
#!/usr/bin/env python3 """CWE → GSC rule mapping for OWASP Benchmark (v0.31). Derived from COMPLIANCE_MAP — single source of truth. CWE without a detector → honest uncovered gap. """ from typing import Dict, List import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent)) from gsc_compli...
poliakarmai/gsc
benchmark/cwe_map.py
.py
87660b1d1cc316bd
7.39
5
#!/usr/bin/env python3 """Synthetic snippet benchmark for GSC — ground truth from known patterns. Each pair: vulnerable code (MUST fire) + fixed code (MUST NOT fire). Covers: GS005 SQLi, GS020 XSS, GS004 CmdInj, GS029 Secrets. """ import sys, json, time, tempfile from pathlib import Path from collections import defaul...
poliakarmai/gsc
benchmark/ghsa_benchmark.py
.py
988a75d604734f1b
7.39
5
#!/usr/bin/env python3 """Замер GSC на PoF-корпусе: detect (нашёл?) → PoC-gen → PoF-verify. Двухфазный: --detect-only — только скан + детект (быстро, без LLM-PoC). (без флага) — + gsc pof generate для TP-находок (медленно, LLM). Метрики на vuln-приложениях: TP / FN / MISLABELED + PoF-verified. На clean: FP / ...
poliakarmai/gsc
benchmark/pof_corpus/measure_pof.py
.py
d4cb95486c205834
7.39
5
"""Parameter sweep for 15m futures trading. Train window and validation window are strictly separated: pick the config on TRAIN numbers only, then judge it once on VALID. Re-running this with configs chosen from validation results is overfitting - don't. Usage: python scripts/sweep_15m.py train # sweep all con...
Kalpadith/trade-advisor
scripts/sweep_15m.py
.py
5929db6027eab138
7
0
"""Exchange adapter protocol. Only Binance is implemented in v1, but any exchange that can serve OHLCV candles can be plugged in behind this interface.""" from typing import Protocol from tradeadvisor.models import Candle class ExchangeAdapter(Protocol): def fetch_klines( self, symbol: str, ...
Kalpadith/trade-advisor
src/tradeadvisor/data/exchange.py
.py
eaec43c1b2ae562f
7
0
"""Cache-aside market data service: serve candles from SQLite, fetching only what is missing from the exchange. The still-forming candle is dropped here - everything downstream sees closed candles only. Holds one adapter per market ("spot", "futures"); every method takes the market it should read from.""" import time...
Kalpadith/trade-advisor
src/tradeadvisor/data/service.py
.py
12167deb10f1c942
7
0
"""Fibonacci retracement/extension levels off the most recent significant swing leg. Built only from confirmed swings, so it inherits their lookahead-safety: a leg endpoint is invisible until k bars confirm it.""" from dataclasses import dataclass from tradeadvisor.indicators.levels import Swings RETRACEMENT_RATIOS ...
Kalpadith/trade-advisor
src/tradeadvisor/indicators/fibonacci.py
.py
b2b544e379c14bd4
7
0
"""SignalEngine - the single analysis entrypoint. The CLI, the API and the backtester all call `analyze()`, which is what guarantees backtests measure the same logic that produces live recommendations. This module only receives DataFrames; it never touches HTTP or SQLite.""" import math from dataclasses import datacl...
Kalpadith/trade-advisor
src/tradeadvisor/signals/engine.py
.py
bef46a335affd941
7
0
"""Turn a directional signal into a concrete trade plan: entry zone, ATR-based stop, R-multiple take-profits and fixed-risk position sizing.""" from dataclasses import dataclass, field import pandas as pd from tradeadvisor.indicators.fibonacci import GOLDEN_POCKET, FibLevels from tradeadvisor.indicators.levels impor...
Kalpadith/trade-advisor
src/tradeadvisor/signals/plan.py
.py
4eb92c3a574e6992
7
0
import numpy as np from helpers import df_from_rows, make_ohlcv from tradeadvisor.indicators.levels import cluster_levels, find_swings def _zigzag(n_cycles: int = 6, period: int = 10): """Triangle wave: swing highs at the peaks, lows at the troughs.""" rows = [] for cycle in range(n_cycles): for ...
Kalpadith/trade-advisor
tests/test_levels.py
.py
47463c86df681e68
7.5
0
"""In-memory session store — the M2 stand-in for the M7 Redis checkpoint. Keep-latest snapshot per session, in a plain dict (architecture §4: each snapshot is cumulative, so latest-only suffices for resume; keep-latest = overwrite). Single-process, single-event-loop by design (§2: one uvicorn worker) and saves are awa...
dustinxie/turnstile
src/turnstile/capabilities/persistence/memory_store.py
.py
ba6de8b2bd3e32c8
7
0
"""KB search tool — query -> embedding server -> Milvus hybrid search. A pure retrieval leg. The tool embeds the model's query text and searches ONE Milvus collection under a FIXED scope filter (`expr`) that is passed through to the search service verbatim. It never resolves users, owners, or grants — the embedder dec...
dustinxie/turnstile
src/turnstile/capabilities/tools/kb_search.py
.py
af82bce85f2ed5be
7
0
"""MCP tool wrapper — surfaces a discovered MCP tool as a kernel Tool. Thin marshaling over an MCP client session (the `mcp` SDK or anything speaking its types): `list_tools` discovery mounts one adapter per remote tool under the `mcp__{server}__{tool}` name; `call_tool` results flatten into the kernel ToolResult (tex...
dustinxie/turnstile
src/turnstile/capabilities/tools/mcp.py
.py
07e6851e21675e11
7
0
"""Typed configuration — environment in, one frozen object out. Root's input (architecture.md §1): every endpoint, credential and knob the assembly needs, validated once at startup so a misconfigured deployment fails loudly at boot instead of mid-turn. Products never import this class — specs read attributes duck-type...
dustinxie/turnstile
src/turnstile/config.py
.py
9f90ac7899b7c980
7
0
"""L0 ports — the behavioral contract the loop calls through. Seven interfaces + the Requester handle. L1 capabilities implement the I/O ports (Tool, LlmProvider, CompactionStrategy, CompactionCheckpoint); L2 products implement the discipline seams (LifecycleHooks, ToolMiddleware). The engine holds ONLY these types — ...
dustinxie/turnstile
src/turnstile/kernel/ports.py
.py
ccf2bf1c5bdf4661
7
0
"""Quality judge — the offer_continuation retry seam + the envelope's verdict. When the model wants to stop, a small eval-LLM call grades the answer against the question (JSON {"score": 0..1, "critique": "..."}). Low score -> return critique text, which the kernel injects as a synthetic user message and runs another r...
dustinxie/turnstile
src/turnstile/products/hooks/quality_judge.py
.py
d1dd7849bf5a2f38
7
0
"""Reference collector — the citation NUMBERING AUTHORITY and ground truth. Citations work like a bibliography: someone numbers the list, the writer cites the numbers. Here the server numbers and the model cites. Retrieval tools render their hits with per-call numbers ("[1] ..." restarting every call), so two kb_searc...
dustinxie/turnstile
src/turnstile/products/middleware/references.py
.py
dc464bd7f52a1069
7
0
"""AgentSpec — the L2 composition seam (design doc §3). One subclass per product. The application root (the one place allowed to know all products) constructs the right spec from config and injects it into the neutral assembly — the loop and the assembly name NO product; products are pure plug-ins, siblings that never...
dustinxie/turnstile
src/turnstile/products/spec.py
.py
41f7e3dc81b942ed
7.5
0
"""support_bot — the first product: an internal support/HR assistant over a curated knowledge base, with the web as a supplementary source. Composition only: which shared L1 tools it mounts, its persona, its neutral knobs. Hooks (quality judge) and middleware (reference collector) attach in their own commits and regis...
dustinxie/turnstile
src/turnstile/products/specs/support_bot.py
.py
eb625981f4e719b0
7.5
0
"""Application root — config in, an assembled agent out. The one module allowed to know every layer (architecture.md §1): it reads the typed config, builds the L1 capabilities, picks the L2 spec, and hands back a driver-neutral bundle. Web, CLI and batch drivers all call the same `assemble()` and get the identical obj...
dustinxie/turnstile
src/turnstile/root.py
.py
cf2ce64f99c6a423
7
0
"""FastAPI app factory — the web driver's entry point. `create_app()` reads config via root (the service never imports the config layer — the c6 contract), builds the process-wide snapshot store, and wires the routes. The process starts at the driver; root is a function it calls, not an entry point (architecture.md §2...
dustinxie/turnstile
src/turnstile/service/app.py
.py
21b84cc40784578f
7
0
"""AuthN — who is making this request. JWT (HS256) verified against the deployment's `jwt_secret`; the principal is the token's `sub` claim. Secret unset = auth OFF: every request resolves to the ANONYMOUS principal, so ownership logic stays uniform in dev. The IdP story (SAML/FortiAuthenticator) terminates at a futu...
dustinxie/turnstile
src/turnstile/service/auth.py
.py
f5e1e9c857fecf70
7
0
"""The response envelope — the service-added closing event of every turn. Everything a chat client needs to FINISH rendering a turn, in one frame: the final answer (from the snapshot, so a judge-retried turn reports the accepted answer, never a concatenation of drafts) with its References section appended, a determini...
dustinxie/turnstile
src/turnstile/service/envelope.py
.py
f084fe95336d2f73
7
0
"""Citation file serving — one endpoint, opaque expiring recipient-bound tokens. The Reference section links documents as `/v1/files/<token>`; the token IS the (encrypted) claim `{region, filename, sub, exp}` — Fernet, so it is opaque in the URL (no path, no region, no filename leaks), tamper-proof (decryption fails o...
dustinxie/turnstile
src/turnstile/service/files.py
.py
7839cd39611d713e
7
0
"""Worker-local conversation registry — HTTP conversation id ↔ running agent. One entry per conversation: the AssembledAgent bundle plus its spawned handle. Created on the conversation's first request (resume comes free — assemble() reads the shared store); reused for every later request, so a mid-turn POST steers the...
dustinxie/turnstile
src/turnstile/service/registry.py
.py
947ec72268464c48
7
0
"""The turn endpoint — POST a message, receive the turn as Server-Sent Events. The SSE stream IS the driver protocol serialized verbatim (architecture.md §2): one SSE event per AgentEvent — `event:` carries the snake_cased event class, `data:` its fields as JSON — ending with the terminal turn_complete. (The service-a...
dustinxie/turnstile
src/turnstile/service/routes.py
.py
a432cb8df701177e
7
0
"""SSO login — SAML in, our JWT out. FortiAuthenticator (the IdP) authenticates the employee; THIS service issues the credential (auth.mint_token — the one minting path). The browser flow: GET /sso -> 302 to the IdP's login page POST /sso/acs <- the IdP posts the signed SAMLResponse here; ...
dustinxie/turnstile
src/turnstile/service/sso.py
.py
156ab0e7fc56e372
7
0
""" Update the CI permissions configuration file. This script updates the `CI_PERMISSIONS.json` file, which defines the CI permissions granted to each user. The format of `CI_PERMISSIONS.json` is as follows: { "username1": { "can_tag_run_ci_label": true, "can_rerun_failed_ci": true, "cool...
kunpengcompute/sglang
.github/update_ci_permission.py
.py
e82d2cf7748ed4fa
7
0
""" Benchmark: Fused Gate+Cumsum vs Separate Gate + Cumsum. Compares two paths: - Separate: torch gate activation -> chunk_local_cumsum (2 steps) - Fused: kda_gate_chunk_cumsum (single kernel) Both produce the same output: cumsum of gate-activated g. Usage: python bench_fused_gate_cumsum.py python ben...
kunpengcompute/sglang
benchmark/bench_linear_attention/bench_fused_gate_cumsum.py
.py
907c1a06988c3922
7
0
# This script benchmarks MRotaryEmbedding.get_rope_index_glm4v (GLM4V mrope index builder). # It generates synthetic multimodal input_ids + attention_mask (+ optional image/video grids), # runs benchmarks. # # == Usage Examples == # # python3 benchmark_rope_index.py --device cuda --num-tokens 1024 2048 --benchmark-iter...
kunpengcompute/sglang
benchmark/bench_rope/benchmark_rope_index.py
.py
13ec7a491ef29cc0
7
0
""" Adapted from https://github.com/stanfordnlp/dspy/blob/34d8420383ec752037aa271825c1d3bf391e1277/intro.ipynb#L9 """ import argparse import dspy from dspy.datasets import HotPotQA class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = ds...
kunpengcompute/sglang
benchmark/dspy/bench_dspy_intro.py
.py
560b89ece928d7fa
7
0
from typing import Optional import numpy as np import torch # Import the function to benchmark from sglang.srt.layers.attention.fla.layernorm_gated import ( _layer_norm_fwd as layer_norm_fwd, ) from sglang.srt.layers.attention.fla.layernorm_gated import ( rms_norm_ref, ) def benchmark_layer_norm_fwd( M:...
kunpengcompute/sglang
benchmark/fla/benchmark_layernorm_gated.py
.py
11ed1677e67feda9
7
0
import os import sys from typing import List import av from datasets import load_dataset def find_video_files(video_dir) -> List[str]: if os.path.isfile(video_dir): return [video_dir] video_files = [] for root, dirs, files in os.walk(video_dir): for file in files: if file.end...
kunpengcompute/sglang
benchmark/hicache/nextqa.py
.py
e9df6be92812245a
7
0
""" Acceptance Checker - 驗收記錄檢查 檢查 Ticket 是否有驗收記錄(關鍵字搜尋),以及是否需要驗收。 """ import sys from pathlib import Path from typing import Optional, Tuple # 加入 hooks 目錄(acceptance_checkers 的上層) _hooks_dir = Path(__file__).parent.parent _claude_dir = _hooks_dir.parent if str(_claude_dir) not in sys.path: sys.path.insert(0, st...
tarrragon/graph_project_docs_manager
.claude/hooks/acceptance_checkers/acceptance_checker.py
.py
81df03b5ebaba408
7
0
""" Children Checker - 子任務完成度檢查(遞迴,含 closed/completed 終態) 檢查父 Ticket 的所有後代(子、孫…)是否已落入終止狀態 (`completed` 或 `closed`),未完成時產生阻擋訊息。 設計理念(對應 0.18.0-W10-036 任務鏈核心哲學): 父 Ticket 的責任是「問題被解決」,不是「分析報告寫完」。 子 Ticket 實作/驗證完成才是父責任履行的證據; 若後代仍有未完成項,父就不應該 complete。 """ import sys from pathlib import Path from typing import...
tarrragon/graph_project_docs_manager
.claude/hooks/acceptance_checkers/children_checker.py
.py
3e5d3f1327a2294b
7
0
""" Custom H2 Checker - 自定義 H2 章節偵測(W17-072) W17-072:偵測 ticket body 中出現的非 Schema H2 章節,於 complete 時輸出 warning (不阻擋)。配合 `.claude/references/agent-definition-standard-details.md`「章節結構規則 (W17-072)」「禁止自定義 H2」條款,讓 agent 違規寫入 `## 實作摘要` / `## 驗證指令與結果` 等自定義 H2 時能被 主線程及時察覺。 設計要點: - 不阻擋(僅警告):避免與 W17-071 既有 hook 邏輯重複擋,warning 是...
tarrragon/graph_project_docs_manager
.claude/hooks/acceptance_checkers/custom_h2_checker.py
.py
7599c847c8010984
7
0
""" Error Pattern Attribution Filter - 精確歸屬新增 error-pattern 至來源 Ticket PC-099 防護:acceptance-gate-hook 場景 #17 AUQ 原本僅比對 mtime > ticket.started_at, 會把「同一 session 內其他工作新增的 PC」誤報為「當前 ticket 新增」,造成 false positive。 本模組提供 `filter_error_patterns_by_ticket_scope()`,將 mtime-based 候選清單再依 「是否真正屬於當前 ticket scope」過濾,僅保留與當前 ticket ...
tarrragon/graph_project_docs_manager
.claude/hooks/acceptance_checkers/error_pattern_attribution.py
.py
870de68b1a9beafb
7
0
""" Execution Log Checker - 執行日誌填寫檢查 檢查 Ticket 的 Solution/Test Results 區段是否有實質內容。 """ import re # W17-071:Schema 定義章節名清單(與 ticket_validator._SCHEMA_SECTION_NAMES 同步)。 # 擷取 section 內容時只把這些章節名當作邊界,避免 agent 自定義 H2 # (如 `## 實作摘要`)把 schema section 範圍切斷。 # 來源:.claude/pm-rules/ticket-body-schema.md # Spawn Requests 於 0.0.1...
tarrragon/graph_project_docs_manager
.claude/hooks/acceptance_checkers/execution_log_checker.py
.py
ae4699a4c5d13ac1
7
0
""" Experiment Artifact Checker - complete 前實驗器材殘留掃描 `ticket track complete <id>` 前掃描工作區,找出屬於本票、依規範命名 (`experiment-<ticket-id>-<用途>.<副檔名>`)但尚未妥善處置的實驗器材, 不依賴票面登記本身是否完整。 背景:實驗器材存活期治理規範原僅要求「執行 complete 的一方於 complete 前人工掃描工作區」,多視角審查指出人工自檢的執行完全依賴收尾方記得執行, 而該規範的制訂本身正是源於一次收尾判斷失準的實測案例。本 checker 把該 人工步驟自動化,人工自檢降為 fallback(para...
tarrragon/graph_project_docs_manager
.claude/hooks/acceptance_checkers/experiment_artifact_checker.py
.py
2e13d33588fc6382
7
0
""" 5W1H Checker - 5W1H 欄位完整性檢查 檢查 Ticket frontmatter 的 5W1H 欄位是否仍有「待定義」。 """ from typing import List def check_5w1h_completeness(frontmatter: dict, logger) -> List[str]: """ 檢查 5W1H 欄位是否仍有「待定義」。 Args: frontmatter: Ticket frontmatter 結構 logger: 日誌物件 Returns: List[str] - 仍為待...
tarrragon/graph_project_docs_manager
.claude/hooks/acceptance_checkers/five_w1h_checker.py
.py
62518c5940ccffa6
7
0
""" Hook Protection Acceptance Checker - 防護類 hook ticket 的必含 acceptance + 產生路徑盤點表正本檢查 背景:一個新註冊的 guard hook 可能已註冊卻零效力且日誌零筆,而撰寫者與 PM 皆會因單元測試全綠、settings.json 已註冊、實機 dogfooding 通過三項訊號而誤信 防護已生效。此為結構性風險而非個案,且規則文字層級的預防措施(PC-BAL-033 早已列出對應要求)已證明無法單靠文件落實——用戶因此裁示強制層須為 acceptance 條目加 hook 硬擋。 零效力有兩條各自成立的成因,2026-08-18 實測後範圍已收窄(P...
tarrragon/graph_project_docs_manager
.claude/hooks/acceptance_checkers/hook_protection_acceptance_checker.py
.py
ac1257cdef14f0db
7
0
""" Responsibility Scope Checker - Ticket 職責邊界判準(0.2.1-W3-052.1 由 C3 移植) 移植自 `.claude/lib/ticket_quality/detectors.py` 的 C3 Ambiguous Responsibility 檢測。原始四項判準(層級標示 / 職責描述清晰度 / 檔案範圍對齊層級 / 驗收條件對齊 層級關鍵詞)全數依賴 `[Layer X]` / `Layer X:` 標示格式,該格式在現行 154+ 既有 ticket 語料普及度 0(父票 Problem Analysis 盤點結論),無法直接沿用。 重寫依據(實測,見 0.2.1-W3-...
tarrragon/graph_project_docs_manager
.claude/hooks/acceptance_checkers/responsibility_scope_checker.py
.py
83ea9f9ee07f2aaa
7
0
""" Self-Check Visibility Checker - Layer 1 自檢可觀測性檢查(W17-064) W17-064:偵測 IMP/ANA/DOC ticket 的 Solution 章節是否含 `### 自檢結果` 子章節。 若缺少則輸出 warning(不阻擋 complete),提示代理人執行 Layer 1 自檢 (依 `.claude/references/agent-self-check-template.md`)。 設計依據(Hook 行為 / 觸發範圍 / 豁免機制三維度決策): - Hook 行為:B warning only(exit 0 + stderr,不阻擋 complete) -...
tarrragon/graph_project_docs_manager
.claude/hooks/acceptance_checkers/self_check_visibility_checker.py
.py
b8fc39bf931996ec
7
0
""" Spawn Request Checker - Spawn Requests 章節處理狀態檢查 對應 Ticket 1.5.0-W5-024(1.5.0-W5-022 ANA 結論): agent 執行中透過 `ticket track add-spawn-request` 產生的 Spawn Requests 條目, 若在 ticket complete 前仍為 `status: pending`,代表 PM 尚未評估是否要建立對應 ticket(`processed`)或評估後決定不需要(`dismissed`)。 Why: Spawn Request 條目有確定性 schema(what/why/priority/...
tarrragon/graph_project_docs_manager
.claude/hooks/acceptance_checkers/spawn_request_checker.py
.py
4dbb821e4c5a7fc7
7
0
""" Ticket Parser - Ticket frontmatter 欄位提取和型別判斷 負責從 Ticket frontmatter 提取 children、status、type 等欄位, 以及判斷 Ticket 類型(DOC/ANA)。 """ import sys from pathlib import Path from datetime import datetime from typing import Optional, List, Tuple # 加入 hooks 目錄(acceptance_checkers 的上層) _hooks_dir = Path(__file__).parent.parent...
tarrragon/graph_project_docs_manager
.claude/hooks/acceptance_checkers/ticket_parser.py
.py
f449e91db88f8dda
7
0
#!/usr/bin/env python3 # /// script # requires-python = ">=3.9" # dependencies = ["pyyaml"] # /// """ Active Dispatch Tracker Hook - PostToolUse (Agent) 功能: PostToolUse(Agent) 觸發時記錄派發到 dispatch-active.json(含 agent_id)+ housekeeping(超時清理/orphan 偵測)。 dispatch 記錄清理和完成廣播已遷移至 SubagentStop handler(W10-066)。 觸發時...
tarrragon/graph_project_docs_manager
.claude/hooks/active-dispatch-tracker-hook.py
.py
b067408492c3f4bc
7
0
#!/usr/bin/env python3 """ Agent Definition Standard Check Hook(SessionStart) 對 .claude/agents/*.md 執行知識載體分配約束的執法掃描: 1. 三區塊結構計數(允許產出 / 禁止行為 / 適用情境)須 == 3,缺漏輸出 top 3 違規檔。 2. 內容錯置啟發式 WARNING:偵測本應放規則/方法論層的「品質檢查全文 / 步驟化清單」 被塞進 agent 定義檔(規範表的存在即病史,agent-definition-standard-details.md)。 3. 模板同步檢查:language-agent-template....
tarrragon/graph_project_docs_manager
.claude/hooks/agent-definition-standard-check-hook.py
.py
5eab2db9aa686ddb
7
0
#!/usr/bin/env python3 # /// script # requires-python = ">=3.9" # dependencies = [] # /// """ Agent Prompt Length Guard Hook - PreToolUse Hook 功能: 1. 硬上限:檢查 Agent/Task 派發的 prompt 行數是否超過 30 行限制(PC-040)。 超過表示 context 未正確存入 Ticket,應先更新 Ticket Context Bundle。 2. 軟提示(W17-048 方案 B):prompt 介於 10-30 行且未偵測到模板關鍵字時, ...
tarrragon/graph_project_docs_manager
.claude/hooks/agent-prompt-length-guard-hook.py
.py
849666de6df8f178
7
0
#!/usr/bin/env python3 """ 5W1H Token 生成器 生成和管理 5W1H 對話 Token """ import os import re import secrets import string import sys from datetime import datetime from pathlib import Path def get_token_dir() -> Path: """取得 Token 目錄路徑""" script_dir = Path(__file__).parent project_root = script_dir.parent.parent ...
tarrragon/graph_project_docs_manager
.claude/hooks/archived/5w1h-token-generator.py
.py
3031086f41ddee86
7
0
#!/usr/bin/env python3 """ 代理人分派錯誤恢復工具模組 提供錯誤訊息解析、自動重試邏輯和糾正歷史記錄功能。 版本:v0.12.N.7 作者:rosemary-project-manager 日期:2025-10-18 使用範例: from agent_dispatch_recovery import dispatch_with_auto_retry, record_agent_correction # 自動重試邏輯(主線程使用) success, final_agent, attempts = dispatch_with_auto_retry( prompt=...
tarrragon/graph_project_docs_manager
.claude/hooks/archived/agent_dispatch_recovery.py
.py
e501700872e3a3b5
7
0
#!/usr/bin/env python3 """ check-next-objectives.py 檢查中版本層級的 todolist.yaml 任務狀態 用於 smart-version-check 指令的第三階段檢查 """ import os import sys import re from pathlib import Path def get_project_root(): script_dir = Path(__file__).parent.absolute() return str(Path(script_dir).parent.parent) def read_file(path): ...
tarrragon/graph_project_docs_manager
.claude/hooks/archived/check-next-objectives.py
.py
71195a768a93a58f
7
0
#!/usr/bin/env python3 # /// script # requires-python = ">=3.10" # dependencies = [] # /// """ Required Features Check - Session 啟動必要功能驗證 驗證所有在 required-features-config.json 中定義的必要功能是否正確配置和可用。 檢查類型: - script: 執行腳本並檢查返回值 - script_exists: 檢查腳本是否存在且有執行權限 - settings_hook: 檢查 Hook 是否已在 settings.json 中註冊 Usage: uv run...
tarrragon/graph_project_docs_manager
.claude/hooks/archived/required-features-check.py
.py
d7799fdf28e25b06
7
0
#!/usr/bin/env python3 """ show-cache-stats.py - Ticket Quality Gate 快取統計查詢腳本 """ import json import sys from pathlib import Path def get_project_root(): """定位專案根目錄""" current_dir = Path.cwd() while current_dir != current_dir.parent: if (current_dir / "CLAUDE.md").exists(): return curr...
tarrragon/graph_project_docs_manager
.claude/hooks/archived/show-cache-stats.py
.py
73d58e79b81f00af
7
0
#!/usr/bin/env python3 """ TDD Phase 完整性檢查 Hook 確保 TDD 四階段完整執行,不可跳過或簡化 """ import os import re import sys from datetime import datetime from pathlib import Path # 添加 hooks 目錄到 path 以便導入 common_functions sys.path.insert(0, str(Path(__file__).parent)) try: from lib.common_functions import setup_project_environment...
tarrragon/graph_project_docs_manager
.claude/hooks/archived/tdd-phase-check-hook.py
.py
82a55a6fc1604870
7
0
#!/usr/bin/env python3 """ test-summary.py - 測試摘要腳本 功能: 執行 flutter test 並生成簡潔摘要 解決 flutter test 輸出過大問題 (4.6MB+ → <50KB) 使用: python3 test-summary.py [可選測試路徑] 例如: python3 test-summary.py test/unit/ """ import os import sys import subprocess import tempfile from pathlib import Path from datetime import datetime d...
tarrragon/graph_project_docs_manager
.claude/hooks/archived/test-summary.py
.py
02ff84f09796f010
7.5
0
#!/usr/bin/env -S uv run --quiet --script # /// script # requires-python = ">=3.11" # dependencies = ["pyyaml"] # /// """ AUQ Option Pattern Detector Hook - PM 回覆含選項 pattern 時提醒使用 AskUserQuestion 補齊 PC-064 多層防護的最後一層(Hook 層)。既有 askuserquestion-reminder-hook 只處 理 Task 工具派發含多 Ticket ID 的場景;本 Hook 偵測 PM 對話中途列選項(A./B./C.、 ...
tarrragon/graph_project_docs_manager
.claude/hooks/auq-option-pattern-detector-hook.py
.py
d9089cb20d7a7071
7
0
#!/usr/bin/env -S uv run --quiet --script # /// script # requires-python = ">=3.11" # dependencies = ["pyyaml"] # /// """ Bash Edit Guard Hook - PreToolUse Hook 功能: 偵測 Bash 中的高風險操作。兩模式處置不同——原地編輯出警告後放行, 裸 cd / pushd 直接擋下並指引 git -C 觸發時機: 執行 Bash 工具時 檢測模式 A(原地編輯,建議改用 Edit 工具): - sed -i 或 sed --in-place (原地編輯,不...
tarrragon/graph_project_docs_manager
.claude/hooks/bash-edit-guard-hook.py
.py
e860cec8394b587f
7
0
#!/usr/bin/env -S uv run --quiet --script # /// script # requires-python = ">=3.10" # dependencies = ["pyyaml"] # /// """ Branch Status Reminder - SessionStart Hook 用於顯示分支狀態 在 Session 啟動時顯示當前分支狀態和 worktree 列表, 如果在保護分支上,會提醒建立 feature 分支。 Hook Event: SessionStart 改進 (v1.3.0, W13-011): - PC-076 防護落地:列出全部 tracked-modifi...
tarrragon/graph_project_docs_manager
.claude/hooks/branch-status-reminder.py
.py
f39665d1bc05e3c9
7
0
"""Anthropic Mythos bridge for GPT-Doug. This module does not copy, redistribute, or modify Anthropic model weights. It routes GPT-Doug requests through Anthropic's Messages API using the existing :class:`agents.llm_backend.AnthropicProvider` implementation. Claude Mythos 5 requires Anthropic authorization. The bridg...
sonoxo/gpt-doug-llm
agents/mythos_bridge.py
.py
2f80c0e267b163f9
7.24
2
from holidaylens.aliases import canonical_name from holidaylens.models import Holiday from holidaylens.normalization import normalize_name def split_names(name: str) -> list[str]: """Split a combined holiday name into individual names.""" return [ part.strip() for part in name.split(";") ...
Drona-jadhav7/HolidayLens
src/holidaylens/matching.py
.py
f61e960ecf80091e
7
0
"""Scientific dependency graph without duplicated experiment parameters.""" from __future__ import annotations from dataclasses import asdict, dataclass COLLECTION = "gamma-gated-sparsity" @dataclass(frozen=True) class Experiment: slug: str dependencies: tuple[str, ...] = () training_run: str | None = ...
eoinmurray/pinglab
experiments/collections/gamma_gated_sparsity/graph.py
.py
fa126863ed44ca77
7
0
"""Draw exp023's existing panels from retained analysis; no measurements or simulation.""" from pathlib import Path import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np from experiments.helpers import theme from experiments.helpers.figsave import save_figure from matplotlib.patc...
eoinmurray/pinglab
experiments/exp023/plots.py
.py
edc5b4f8526acba6
7
0
"""Convergence audit definitions; training identities remain owned by exp022.""" from experiments.exp022.recipe import training_run_cell, training_run_values SLUG = "exp024" TRAINING_RUN = "TR-02" MODELS = training_run_values(TRAINING_RUN, "model") SEEDS = training_run_values(TRAINING_RUN, "seed") WINDOW = 10 ACCURAC...
eoinmurray/pinglab
experiments/exp024/recipe.py
.py
0fd2920485a34283
7
0
"""Numerical definitions retained from the flat exp041 runner.""" import numpy as np from scipy import signal as sp_signal from .recipe import F_GAMMA_BAND_HZ def _peak_with_parabolic(psd: np.ndarray, freqs: np.ndarray) -> float: """Locate the gamma-band peak with parabolic sub-bin interpolation. Returns N...
eoinmurray/pinglab
experiments/exp041/measurements.py
.py
b783f060c6bfc165
7
0
"""ZMQ protocol between trainer (PUSH/PULL bind) and stateless scorer worker. Audio crosses as absolute tmpfs paths (/dev/shm); scores come back raw — sigmoid/std/lambda composition lives in qwen3_tts_post_training.reward. Validated with pydantic — no manual json building. """ from __future__ import annotations from...
FelysNeko/qwen3-tts-post-training
src/qwen3_tts_post_training/client/protocol.py
.py
d7d1c7622950d9eb
7
0
"""Scorer-side ZMQ worker client (mirror of trainer Client). Trainer binds PUSH/PULL; this worker connects PULL/PUSH. Encapsulates the connect block so serve.py has no raw zmq boilerplate. """ from __future__ import annotations import zmq from qwen3_tts_post_training.client.protocol import ScoreRequest, ScoreRespon...
FelysNeko/qwen3-tts-post-training
src/qwen3_tts_post_training/client/scorer.py
.py
a057819ffc78bd6b
7
0
"""metrics.json (preprocess output, §16) → reward-side calibration. The preprocess worker computes the SV centroid and the sim distribution of the actual training corpus; these two functions are the ONLY consumers the trainer/scorer need, replacing the playground npy path and the hardcoded 0.8585/0.0966 pair. """ fro...
FelysNeko/qwen3-tts-post-training
src/qwen3_tts_post_training/reward/metrics.py
.py
28a7c14b8339a6ee
7
0
"""Reward v3.1 (design truth source: playground/SV_REWARD_FINDINGS.md §四/§七). R = λ_sv·r_sv + λ_wer·r_wer + λ_mos·r_mos (RAW magnitudes, no std division) - r_sv = sigmoid((sim_e2v2 − 0.8585)/0.0966) (E2V2 speaker sim, unit-normalized) - r_wer = 1 − CER_qwen3asr (normalize() + edit...
FelysNeko/qwen3-tts-post-training
src/qwen3_tts_post_training/reward/reward.py
.py
8b1a1ed06e33ef24
7
0
"""GRPO family training losses — pure torch, no model, switchable variants. The three algorithms (design truth source: MD §七 + §4.3 of Fish S2 report, arXiv:2603.08823): - "vanilla" A = (R − mean) / (std + eps); per-token clipped ratio loss. DeepSeekMath / FlowTTS-GRPO. - "dr" A = R − mean (NO st...
FelysNeko/qwen3-tts-post-training
src/qwen3_tts_post_training/train/grpo.py
.py
a3332afb779cf7ce
7
0
"""MossFormer2_SE_48K checkpoint loading — ported from clearvoice/clearvoice/networks.py::SpeechModel.load_model/_load_model (the non-ModuleList branch, model_key='model'), with the fetch moved to a plain huggingface_hub snapshot_download (canonical HF cache, no CWD-relative checkpoint_dir, no chdir sandbox, no symlink...
FelysNeko/qwen3-tts-post-training
workers/preprocess/src/preprocess/clearvoice/load.py
.py
4006b8b3b7d027b3
7
0
import torch import torch.nn as nn from torch import Tensor import torch.nn.init as init import torch.nn.functional as F EPS = 1e-8 class GlobalLayerNorm(nn.Module): """Calculate Global Layer Normalization. Arguments --------- dim : (int or list or torch.Size) Input shape from an expect...
FelysNeko/qwen3-tts-post-training
workers/preprocess/src/preprocess/clearvoice/mossformer2_se/conv_module.py
.py
cd16d84a55ed22a2
7
0