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 |
|---|---|---|---|---|---|---|
"""Magika file type detector using ggbond Tensor API.
Usage:
python examples/magika.py <model.gguf> <file1> [file2 ...]
"""
import argparse
import os
from dataclasses import dataclass
import numpy as np
from ggbond.ggml import Backend, Context, GAllocr, GGUF, Tensor, F32, POOL_MAX
MAGIKA_LABELS = [
"ai", ... | aisk/ggbond | examples/magika.py | .py | 51d95c9915359ca0 | 7.48 | 8 |
"""Error and null-check helpers shared across the wrapper.
Modules import the backing bindings directly as ``import ggml as _ggml`` (and
``from ggml import utils as _utils``); the alias keeps the external package
visually distinct from this ``ggbond.ggml`` subpackage. This module only holds
the small helpers built on ... | aisk/ggbond | ggbond/ggml/errors.py | .py | ad2e4dd3911d0ad5 | 7.48 | 8 |
"""Thin OO wrapper around ``ggml_gallocr`` (graph memory allocator)."""
from __future__ import annotations
from typing import TYPE_CHECKING
import ggml as _ggml
from .buffer import BufferType
from .errors import GGMLError, nonnull
if TYPE_CHECKING:
from .backend import Backend
from .graph import Graph
cl... | aisk/ggbond | ggbond/ggml/gallocr.py | .py | 81c50a737a593b9b | 7.48 | 8 |
"""GGML data types and numpy dtype conversion.
Reuses :class:`ggml.utils.GGML_TYPE` directly instead of defining a second
enum, so the values never drift from the underlying bindings.
"""
from __future__ import annotations
import numpy as np
from ggml import utils as _utils
# The canonical ggml type enum (F32 = 0,... | aisk/ggbond | ggbond/ggml/types.py | .py | 11cee1bd3a23b73f | 7.48 | 8 |
#!/usr/bin/env python3
"""Unit tests for scripts/pipeline.py.
Tests workflow argument parsing, pipeline orchestration, error propagation,
and trend-pulse integration. All subprocess and external calls are mocked.
"""
import json
import sys
import unittest
from unittest.mock import MagicMock, call, patch
class TestP... | jakubs2623/notebooklm-skill | tests/test_pipeline.py | .py | 638ee3954d072e6f | 7.95 | 7 |
"""Compute the README reproducibility-badge text from a canonical bench JSON.
The nightly `bench-canonical` cron writes a merged report under
`benchmarks/results/v2.0.0-cron-<date>.json`. This module reads that
report and produces the one-line badge text that the workflow splices
between the `<!-- bench-canonical-badg... | robotrocketscience/aelfrice | benchmarks/badge.py | .py | 313e8f28f5b40bbd | 7.45 | 7 |
"""#1384 — sweep every codepoint's tokenisation against a real FTS5 oracle.
The #1348 changelog published a codepoint-sweep figure for the diacritic
fold. That figure was measured against the fold rule #1384 replaced, so it
no longer describes anything the code does. Per the project rule that a
published number ships ... | robotrocketscience/aelfrice | benchmarks/bm25_fold_codepoint_sweep.py | .py | 3ca57408d85b6f71 | 7.45 | 7 |
"""How far the BM25F index vocabulary is from the FTS5 one (#1348, #1158 §2).
``retrieval`` presents the BM25F and FTS5 lanes as interchangeable, and
``AELFRICE_BM25F=0`` is the documented way to debug one against the other.
That only holds if both describe the same corpus. They did not:
``beliefs_fts`` is declared ``... | robotrocketscience/aelfrice | benchmarks/bm25_fts5_divergence.py | .py | 5297cbee585f9237 | 7.45 | 7 |
"""What the #1348 tokeniser change does to BM25F results (#1348, #1268).
`benchmarks/bm25_fts5_divergence.py` answers "does the index vocabulary
match FTS5". This answers the question that actually gates the change:
BM25F is the **default** retrieval lane — `resolve_use_bm25f_anchors`
returns True with no env, no kwar... | robotrocketscience/aelfrice | benchmarks/bm25_tokenizer_retrieval_ab.py | .py | 051aa55a54f8950a | 7.45 | 7 |
"""#1316 blocking-recall audit — does the rescue fallback lose anything?
`consolidate._blocked_pairs` posts a belief to every shingle under
`max_shingle_df`, and rescues beliefs the cap leaves with **no** posting
onto their rarest shared shingles instead. The rescue exists because a
family larger than the cap shares n... | robotrocketscience/aelfrice | benchmarks/consolidate_blocking_recall.py | .py | e485579425f6548b | 7.45 | 7 |
"""LLM-judge stage for the context-rebuilder eval harness.
Open-ended eval turns produce free-text continuations that substring
match (the deterministic path in #600's `score_fidelity`) misclassifies
as wrong. Those rows surface with `reason="needs_llm_judge"`. This
module turns each such row into a request file the h... | robotrocketscience/aelfrice | benchmarks/context-rebuilder/judges/llm_judge.py | .py | 30b790bbd80f5833 | 7.45 | 7 |
"""Command-line entry point for `python -m benchmarks.context_rebuilder.replay`.
Invocation form (per the v1.4.0 acceptance criteria):
python -m benchmarks.context_rebuilder.replay <fixture> [--clear-at N] [--out PATH]
Default behaviour: replay the fixture full-baseline (no clear
injection), print the resulting ... | robotrocketscience/aelfrice | benchmarks/context_rebuilder/__main__.py | .py | dd5d8d55ee277267 | 7.45 | 7 |
"""Midpoint-clear injection for the context-rebuilder eval harness.
Forces a synthetic context-clear at a configurable point in a
replay. The injection is a contract between `__main__` /
`replay.run()` and the test suite: when a `ClearInjection` is
passed in, the replay walks turns 0..clear_at-1 normally,
substitutes ... | robotrocketscience/aelfrice | benchmarks/context_rebuilder/inject.py | .py | 1c668c26cae4aab1 | 7.45 | 7 |
"""Cohen's-κ inter-rater agreement for eval-judge calibration (#687).
Computes pairwise inter-judge κ across N≥3 independent judge runs over
the same `(expected, actual)` pairs, plus a judge-vs-baseline κ where
the baseline is the zero-LLM substring-exact-match path. Emits the
`judge_kappa.json` artifact specified in ... | robotrocketscience/aelfrice | benchmarks/context_rebuilder/kappa.py | .py | 839ff23c964f544f | 7.45 | 7 |
"""Token-cost + hook-latency measurement primitives.
Two scaffolding metrics for the context-rebuilder eval harness:
1. **Token-budget delta.** `rebuild_block_tokens / full_replay_tokens`
in the headline metric framing; this module exposes the per-turn
signed delta used to build that ratio.
2. **Hook la... | robotrocketscience/aelfrice | benchmarks/context_rebuilder/measure.py | .py | e590f4419ceefa94 | 7.45 | 7 |
"""Transcript-replay loader for the context-rebuilder eval harness.
Reads a `turns.jsonl` file (per `docs/design/transcript_ingest.md` schema)
and walks the per-turn agent state, returning a structured
`ReplayResult` that includes per-turn `token_budget_delta` and
`hook_latency_ms` measurements.
Scaffolding only -- t... | robotrocketscience/aelfrice | benchmarks/context_rebuilder/replay.py | .py | 7105d6b022c5719b | 7.45 | 7 |
"""Continuation-fidelity scorer for the context-rebuilder eval harness.
Implements the v1.4.0 answer-match metric (#138) on top of the
scaffolding that shipped with #136. Sits between `replay.run()` (which
walks a fixture turn-by-turn) and the headline JSON output (which now
carries `continuation_fidelity` alongside `... | robotrocketscience/aelfrice | benchmarks/context_rebuilder/score.py | .py | 17d52c0cd2529c16 | 7.45 | 7 |
"""#1291 / #1177 proposal 16 — free precision proxy for attributed correction.
Proposal 16 replaces the uniform valence smear in
`sentiment_feedback.apply_sentiment_to_pending` — which credits every live,
unlocked belief injected on the prior turn with an equal share of the same
valence, a locked one getting an audit-... | robotrocketscience/aelfrice | benchmarks/correction_attribution_proxy.py | .py | 523fa5bc2d9e007a | 7.45 | 7 |
"""#1096 entity-persistence demotion — offline ranking ablation (G3).
Builds a SYNTHETIC labeled corpus (durable technical beliefs grounded to
file paths vs ephemeral coordination grounded to bare PR numbers, all at
the same Beta posterior) and reports the AUC for ranking durable above
ephemeral under three priors:
... | robotrocketscience/aelfrice | benchmarks/entity_persist_ablation.py | .py | 360be19abfa3aedb | 7.45 | 7 |
"""#981 HRR vocabulary-bridge expansion-lane ablation (the #977-sweep arm).
Runs LoCoMo under four retrieval configurations to isolate the
``use_hrr_expand`` lane:
baseline — BFS off, HRR-expand off (production-style default)
+hrr-expand — HRR-expand on, BFS off
+bfs — BFS on, HRR-expa... | robotrocketscience/aelfrice | benchmarks/hrr_expand_ablation.py | .py | 7798b528ffa96be9 | 7.45 | 7 |
"""Characterise the ULID-prefix date clusters in `ingest_log` (#1283).
#1283's AC2 keys a deterministic spine recompute on
`(created_at, ingest_log ULID)`, and one of its stated constraints is to
**refuse to key on migration-synth ULIDs** — rows whose 48-bit ULID
prefix is migration wall-clock rather than anything abo... | robotrocketscience/aelfrice | benchmarks/ingest_log_ulid_clusters.py | .py | 2b4e2d545fc87ca5 | 7.45 | 7 |
"""Protocol-correct LoCoMo scoring.
Reads predictions JSON and ground truth JSON (separate files).
Handles category 5 forced-choice scoring per the original protocol.
Usage:
uv run python benchmarks/locomo_score_protocol.py <predictions.json> <ground_truth.json>
"""
from __future__ import annotations
import argp... | robotrocketscience/aelfrice | benchmarks/locomo_score_protocol.py | .py | 5147fcf6a7b658e9 | 7.45 | 7 |
"""LongMemEval scoring: compute accuracy from judge results.
Reads predictions + GT + judge verdicts, reports per-category accuracy.
Usage:
uv run python benchmarks/longmemeval_score.py \
/tmp/longmemeval_preds.json /tmp/longmemeval_gt.json /tmp/longmemeval_judge.json
"""
from __future__ import annotation... | robotrocketscience/aelfrice | benchmarks/longmemeval_score.py | .py | 1f5776fd4776ef3d | 7.45 | 7 |
"""#1274 injection-block ordering — movable-set and lock-displacement bound.
Sizes an ordering A/B *before* it is run, from the hook audit alone. Two
questions, both answerable without a reader model or a judge:
1. **Movable set.** A block renders byte-identically under every policy
unless there are at least t... | robotrocketscience/aelfrice | benchmarks/order_policy_movable_bound.py | .py | 4aced226fa0f4095 | 7.45 | 7 |
"""#1089 axis-2 origin-priority tie-break — offline ablation (G3).
Builds a SYNTHETIC mixed-provenance corpus: for each query, one curated
belief (origin `user_validated`, as claude-memory user/feedback lands)
and one conversational belief (origin `user_transcript`, as passive
capture lands) share the query tokens so ... | robotrocketscience/aelfrice | benchmarks/origin_tiebreak_ablation.py | .py | dca862c06ff66e4b | 7.45 | 7 |
"""CLI for the pollution-recovery benchmark (#1011 doc-chunk signal/noise).
python -m benchmarks.pollution_recovery [--fixtures PATH] [-k K] [--json]
Reports, per retrieval regime, whether user-stated facts survive a store
flooded with keyword-overlapping document chunks. Baseline only — the
#1011 R&D found no vi... | robotrocketscience/aelfrice | benchmarks/pollution_recovery/__main__.py | .py | 85d89405320d589f | 7.45 | 7 |
"""Core scoring for the pollution-recovery benchmark (#1011).
Each fixture case is: a query, one or more user-stated `facts` that
answer it, and a set of keyword-overlapping document `chunks` that
should NOT out-rank the facts. We build a fresh in-memory store per
case, insert facts as `user_stated` and chunks as `doc... | robotrocketscience/aelfrice | benchmarks/pollution_recovery/run.py | .py | d3e66978ef3b99f3 | 7.45 | 7 |
"""#1267 posterior-channel audit — which channels move a belief posterior,
in which direction, at default settings.
#1267 states an asymmetry: *"The system has an automatic, evidence-driven
channel that moves posteriors up, and none that moves them down."* This
enumerates every `apply_feedback` route on the production... | robotrocketscience/aelfrice | benchmarks/posterior_channel_audit.py | .py | 3d0082be78598dd2 | 7.45 | 7 |
"""
Legado Book Source Debugger - Pure Debug Engine
纯调试引擎 - 只负责调试模拟模型
职责说明:
- 只负责调试模拟模型
- 基于真实Legado Kotlin代码翻译
- 返回Python对象/字典
- 不负责JSON输出(由技能包处理)
- 不负责修复优化(由技能包处理)
"""
__version__ = "2.3.0"
from .engine.analyze_rule import AnalyzeRule
from .engine.book_source import BookSource, BookInfoRule, ContentRule, SearchRul... | rezmdie/legadoSkill | debugger/__init__.py | .py | b388fedf5c9f47fa | 7.52 | 10 |
"""
Book Source File Organizer
Automatically organizes generated files into book source specific folders
This module provides functionality to:
1. Create or use existing 'temp' folder in project root
2. Create book source specific subfolders
3. Move all related files to the appropriate subfolder
"""
import os
import ... | rezmdie/legadoSkill | debugger/engine/file_organizer.py | .py | 7e37aaa9d95edd21 | 7.52 | 10 |
"""
Reading Environment Simulator - 阅读环境模拟模型
精确复制真实阅读环境的目录结构、文件类型和数据关系
功能说明:
- 模拟Legado阅读APP的运行环境
- 提供书源测试的沙箱环境
- 支持多种书源类型的测试
"""
import json
import os
import re
import time
import hashlib
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, Lis... | rezmdie/legadoSkill | debugger/environment_simulator.py | .py | 98060575c66d1a81 | 7.52 | 10 |
"""
Legado Repository Checker - 实时检查和更新Legado源码
功能:
1. 检查legado仓库是否存在
2. 获取最新源码参考
3. 对比Python实现与Kotlin源码
4. 提供源码参考路径
使用方法:
from debugger.legado_checker import LegadoChecker
checker = LegadoChecker()
checker.check_analyze_rule()
"""
import os
from pathlib import Path
from typing import Dict, List, Optiona... | rezmdie/legadoSkill | debugger/legado_checker.py | .py | da71e9b320c76e61 | 7.52 | 10 |
"""Propaga `scripts/one_paste.ps1` a los documentos que lo ofrecen.
El bloque de un pegado vive en TRES sitios: el canonico y las dos copias que
lee una persona. Mantenerlas a mano garantiza que un dia diverjan, y la que se
quede atras sera precisamente la que alguien copie -nadie pega desde
`scripts/`-. `tests/test_o... | HorizunGroup/horizun-pbi-mcp | scripts/sync_one_paste.py | .py | 167ddf0fa7f7e79a | 7.56 | 12 |
"""Identidad del producto, en un solo sitio.
El nombre vive aqui y no repartido por el codigo: renombrar un producto no
deberia obligar a buscar cadenas sueltas en veinte archivos.
COMPATIBILIDAD: las 132 tools conservan el prefijo `pbi_`. Renombrarlas romperia
a cualquier cliente ya configurado, y el nombre comercia... | HorizunGroup/horizun-pbi-mcp | src/horizun_pbi_mcp/branding.py | .py | 98ea0b0d62b7859f | 7.56 | 12 |
"""Descarga VERIFICADA de las DLL de ADOMD.NET y TOM (Fase J3).
Que hacia antes
---------------
`latest_stable()` preguntaba a NuGet cual era la ultima version y se la
tragaba, sin hash y sin comprobar nada. Dos instalaciones del mismo commit
podian acabar con DLL distintas, y una version nueva podia romper el servido... | HorizunGroup/horizun-pbi-mcp | src/horizun_pbi_mcp/completado/libs.py | .py | ec88530f4c6ff8cf | 7.56 | 12 |
"""Instala el validador PBIR oficial de Microsoft (Fase E3.2).
python scripts/fetch_report_validator.py
Version EXACTA y hash fijado. Ninguna operacion normal ejecuta `npx -y` ni
descarga `@latest`: eso convertiria cada escritura en una descarga de codigo
sin verificar, ejecutado sobre el proyecto del usuario.
E... | HorizunGroup/horizun-pbi-mcp | src/horizun_pbi_mcp/completado/validador.py | .py | 76f3c05ab22889b5 | 7.56 | 12 |
"""Backups de proyectos .pbip, con destino validado y manifiesto verificable.
Fase 1A. Tres reglas que antes no se cumplian:
1. El destino NUNCA puede estar dentro del `.pbip`, del `.Report` ni del
`.SemanticModel`. Si lo estuviera, Power BI podria interpretar la copia como
parte del informe. La validacion vive... | HorizunGroup/horizun-pbi-mcp | src/horizun_pbi_mcp/pbip/backup.py | .py | d4e0b308cb6064ad | 7.56 | 12 |
"""Lectura de `filterConfig`: el inverso de `filter_builder`.
Existe para una sola pregunta: cuando se exporta el CONTENIDO de un visual,
que estaba filtrando lo que se ve en pantalla. Un export que ignora los
filtros da cifras que no cuadran con el tablero, y eso es peor que no
exportar: nadie duda de un Excel.
Por ... | HorizunGroup/horizun-pbi-mcp | src/horizun_pbi_mcp/pbip/filter_reader.py | .py | 2ce37b8c5616fc11 | 7.56 | 12 |
"""Lectura del contenedor .pbix (paquete OPC / ZIP).
Un .pbix es un ZIP con partes de nombre fijo. Las que nos importan para
convertir a .pbip son:
- ``Report/Layout`` informe en formato HEREDADO (JSON en UTF-16LE, con
sub-JSON serializados dentro de strings).
- ``Report/definition/`... | HorizunGroup/horizun-pbi-mcp | src/horizun_pbi_mcp/pbip/pbix_reader.py | .py | 5e6dcf7391ebf511 | 7.56 | 12 |
"""Ubicacion y validacion de proyectos Power BI Project (.pbip)."""
from __future__ import annotations
from pathlib import Path
from typing import Any, Dict, Optional
from horizun_pbi_mcp.config import ActivePbip, Session
from horizun_pbi_mcp.logging_config import get_logger
from horizun_pbi_mcp.powerbi.errors import... | HorizunGroup/horizun-pbi-mcp | src/horizun_pbi_mcp/pbip/project_locator.py | .py | d91b195e1bfd6dfc | 7.56 | 12 |
"""Abstract base class for job application adapters."""
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Self
from jobclaw.models import Application, Job, Profile
class BaseApplier(ABC):
"""Base applier that platform-specific appliers must implement."""
@abstractme... | Eldin162/jobclaw | jobclaw/applier/base.py | .py | a3104e531954a153 | 7.6 | 15 |
"""Apply history tracker to prevent duplicate applications."""
from __future__ import annotations
import json
import logging
from datetime import date, datetime, timezone
from pathlib import Path
from typing import Any
logger = logging.getLogger(__name__)
class ApplyHistory:
"""Track applied jobs to avoid dupl... | Eldin162/jobclaw | jobclaw/applier/history.py | .py | e5e40de541ff10e9 | 7.6 | 15 |
"""LinkedIn auto-apply adapter."""
from __future__ import annotations
import logging
from jobclaw.applier.base import BaseApplier
from jobclaw.models import Application, ApplicationStatus, Job, JobSource, Profile
logger = logging.getLogger(__name__)
class LinkedInApplier(BaseApplier):
"""Auto-apply to jobs on... | Eldin162/jobclaw | jobclaw/applier/linkedin.py | .py | 7d507c5f7281dbb5 | 7.6 | 15 |
"""Interactive browser login for job platforms.
Opens a headed browser, lets the user log in manually, then extracts
and persists cookies for future use by scraper / applier layers.
"""
from __future__ import annotations
import json
import logging
import os
import stat
import time
from pathlib import Path
from play... | Eldin162/jobclaw | jobclaw/auth/browser_login.py | .py | 610f10879297ce9c | 7.6 | 15 |
"""Extract Claude OAuth token from the locally installed Claude Code CLI."""
from __future__ import annotations
import json
from pathlib import Path
from pydantic import BaseModel
_DEFAULT_CREDENTIALS_PATH = Path.home() / ".claude" / ".credentials.json"
class ClaudeToken(BaseModel):
"""Parsed Claude OAuth cre... | Eldin162/jobclaw | jobclaw/auth/claude_auth.py | .py | 894631e6b94c6c27 | 7.6 | 15 |
"""Unified cookie loading: config (.env) > persisted file > prompt login.
Provides a single entry point for all cookie needs across scraper and applier layers.
"""
from __future__ import annotations
import logging
from jobclaw.auth.browser_login import load_cookies
logger = logging.getLogger(__name__)
# Maps plat... | Eldin162/jobclaw | jobclaw/auth/cookie_manager.py | .py | 96a5527f93c312b7 | 7.6 | 15 |
"""Application configuration loaded from environment variables."""
from functools import lru_cache
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
"""Runtime settings for the JobClaw agent."""
model_config = SettingsConfigDict(
... | Eldin162/jobclaw | jobclaw/config.py | .py | f83165699fde30a0 | 7.6 | 15 |
"""Core domain models used across scraping, matching, and applying."""
from __future__ import annotations
from datetime import datetime, timezone
from enum import Enum
from typing import Any
from uuid import uuid4
from pydantic import BaseModel, Field, HttpUrl, model_validator
class JobSource(str, Enum):
"""Su... | Eldin162/jobclaw | jobclaw/domain.py | .py | fcf197b51767d5ca | 7.6 | 15 |
"""LLM-based job-profile matching engine."""
from __future__ import annotations
import json
import logging
from pathlib import Path
from langchain.chat_models import init_chat_model
from langchain.schema import HumanMessage, SystemMessage
from jobclaw.config import get_settings
from jobclaw.models import Job, Match... | Eldin162/jobclaw | jobclaw/matcher/llm_matcher.py | .py | 4ef4de9bd2e786a4 | 7.6 | 15 |
"""Async Claude wrapper built on the unified streaming layer."""
from __future__ import annotations
from jobclaw.auth import ClaudeToken, ensure_valid_token, get_claude_token
from jobclaw.models.streaming import (
StreamContext,
StreamOptions,
UnifiedStreamer,
)
_DEFAULT_MODEL = "claude-sonnet-4-6"
cla... | Eldin162/jobclaw | jobclaw/models/claude_api.py | .py | 532e39f43961fce8 | 7.6 | 15 |
"""Async SSE streaming layer for Anthropic Claude Messages API."""
from __future__ import annotations
import asyncio
import json
import random
from dataclasses import dataclass
import httpx
_API_VERSION = "2023-06-01"
_RETRYABLE_STATUS_CODES = {429, 500, 502, 503, 504}
_OAUTH_BETAS = [
"claude-code-20250219",
... | Eldin162/jobclaw | jobclaw/models/streaming.py | .py | 339989c172bc897f | 7.6 | 15 |
"""Discord notification channel via webhook."""
from __future__ import annotations
import logging
import httpx
logger = logging.getLogger(__name__)
class DiscordNotifier:
"""Send notifications via Discord webhook."""
def __init__(self, webhook_url: str) -> None:
self._webhook_url = webhook_url
... | Eldin162/jobclaw | jobclaw/notifier/discord.py | .py | 2bc89ecf7d623519 | 7.6 | 15 |
"""Telegram notification channel via Bot API."""
from __future__ import annotations
import logging
import httpx
logger = logging.getLogger(__name__)
class TelegramNotifier:
"""Send notifications via Telegram Bot API."""
BASE_URL = "https://api.telegram.org/bot{token}"
def __init__(self, bot_token: s... | Eldin162/jobclaw | jobclaw/notifier/telegram.py | .py | 55860f856da5c825 | 7.6 | 15 |
"""Abstract base class for job scrapers."""
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Self
from jobclaw.models import Job, JobSource
class BaseScraper(ABC):
"""Base scraper that all platform scrapers must implement."""
source: JobSource
@abstractmethod
... | Eldin162/jobclaw | jobclaw/scraper/base.py | .py | 0f2ca6d3e512f654 | 7.6 | 15 |
"""Tests for ApplyHistory — anti-duplicate tracking."""
from __future__ import annotations
import json
from pathlib import Path
import pytest
from jobclaw.applier.history import ApplyHistory
@pytest.fixture()
def history_path(tmp_path: Path) -> Path:
return tmp_path / "history.json"
class TestApplyHistory:
... | Eldin162/jobclaw | tests/test_apply_history.py | .py | 108560a1eda92841 | 8.1 | 15 |
"""Tests for Claude OAuth token auto-refresh."""
from __future__ import annotations
import json
import time
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
from jobclaw.auth.token_refresh import ensure_valid_token
@pytest.fixture()
def creds_file(tmp_path: Path) -> Path:
"""C... | Eldin162/jobclaw | tests/test_token_refresh.py | .py | a22aac784a3a51a0 | 8.1 | 15 |
"""Conftest.py (root-level).
We keep this in root pytest fixtures in pytest's doctest plugin to be available, as well
as avoiding conftest.py from being included in the wheel, in addition to pytest_plugin
for pytester only being available via the root directory.
See "pytest_plugins in non-top-level conftest files" in... | tmux-python/libtmux-mcp | conftest.py | .py | 483974239b9a487b | 8.06 | 12 |
"""Base class for widgets and the docutils node that wraps rendered output."""
from __future__ import annotations
import abc
import collections.abc
import pathlib
import typing as t
import jinja2
import markupsafe
from docutils import nodes
from sphinx.builders.html import StandaloneHTMLBuilder
if t.TYPE_CHECKING:
... | tmux-python/libtmux-mcp | docs/_ext/widgets/_base.py | .py | 453bd3ee1b5ea6a4 | 7.56 | 12 |
"""Factory that manufactures a Sphinx Directive class for a given widget."""
from __future__ import annotations
import pathlib
import typing as t
from docutils import nodes
from sphinx.util.docutils import SphinxDirective
from ._base import ASSET_FILES, BaseWidget, widget_container
def make_widget_directive(widge... | tmux-python/libtmux-mcp | docs/_ext/widgets/_directive.py | .py | fc17f5710a0b455f | 7.56 | 12 |
"""Autodiscover widget classes from sibling modules in this package."""
from __future__ import annotations
import importlib
import pkgutil
from ._base import BaseWidget
def discover() -> dict[str, type[BaseWidget]]:
"""Import every non-underscore submodule; collect ``BaseWidget`` subclasses.
Adding a new ... | tmux-python/libtmux-mcp | docs/_ext/widgets/_discovery.py | .py | b6e8eec6a967f7fb | 7.56 | 12 |
"""Prevent flash-of-wrong-selection on the ``mcp-install`` widget.
The widget's server-rendered HTML always marks the first
client/method/scope tab ``aria-selected="true"`` and ``hidden=""`` on
every panel except the ``(claude-code, uvx, local, off)`` cell.
``widget.js`` then reads ``localStorage`` and mutates the DOM... | tmux-python/libtmux-mcp | docs/_ext/widgets/_prehydrate.py | .py | 417db3128ceb137f | 7.56 | 12 |
"""Sphinx configuration for libtmux-mcp."""
from __future__ import annotations
import pathlib
import re
import sys
import typing as t
from gp_sphinx.config import make_linkcode_resolve, merge_sphinx_config
from gp_sphinx.defaults import DEFAULT_SPHINX_FONT_PRELOAD
# Docs-only shim: ``sphinx_autodoc_fastmcp.ToolColl... | tmux-python/libtmux-mcp | docs/conf.py | .py | 8bbfc6c5f9c1323d | 7.56 | 12 |
"""libtmux MCP server - programmatic tmux control for AI agents."""
from __future__ import annotations
import argparse
import sys
import typing as t
from .__about__ import __version__
__all__ = ["__version__"]
def _build_parser() -> argparse.ArgumentParser:
"""Build the local command-line parser."""
parse... | tmux-python/libtmux-mcp | src/libtmux_mcp/__init__.py | .py | a6d000b7b96c92f8 | 7.56 | 12 |
"""Semantic shell-history policy helpers."""
from __future__ import annotations
import typing as t
if t.TYPE_CHECKING:
from fastmcp import FastMCP
_COMMAND_HISTORY_DEFAULT_TOOLS = ("run_command",)
def _resolve_suppress_history(value: str | None) -> bool:
"""Resolve the strict startup history-suppression ... | tmux-python/libtmux-mcp | src/libtmux_mcp/_history.py | .py | 7d68938420894c64 | 7.56 | 12 |
"""Duration policy for the pane wait tools.
A wait tool is the only MCP tool in this server that blocks for a
caller-chosen duration. The ceiling bounds the AGENT'S TURN, not the
transport: the wait tools await throughout, so a long wait does not
stall the connection. Measured on fastmcp 3.4.4 over stdio, a tool
await... | tmux-python/libtmux-mcp | src/libtmux_mcp/_wait_policy.py | .py | 807b2d33445f6861 | 7.56 | 12 |
"""Reusable workflow recipes for the libtmux-mcp prompt surface.
Each function here is a FastMCP prompt — a template that returns the
text MCP clients should send to their model. Prompts are the
protocol-level way to package operator-discovered best practices.
The authoritative narrative lives at :doc:`docs/topics/pro... | tmux-python/libtmux-mcp | src/libtmux_mcp/prompts/recipes.py | .py | a4e1ac2d9230fee5 | 7.56 | 12 |
"""Generic MCP tool batching helpers."""
from __future__ import annotations
import json
import time
import typing as t
from fastmcp import Context
from fastmcp.tools.base import ToolResult
from pydantic import BaseModel
from libtmux_mcp._utils import (
ANNOTATIONS_RO,
TAG_DESTRUCTIVE,
TAG_MUTATING,
... | tmux-python/libtmux-mcp | src/libtmux_mcp/tools/batch_tools.py | .py | c35fa3b38a1a2f6a | 7.56 | 12 |
"""Agent-namespaced tmux paste buffer tools.
Tmux paste buffers are server-global: every buffer lives in a single
flat namespace shared by all clients on that tmux server. If two MCP
agents — or two parallel tool calls from one agent — independently
created a buffer named ``clipboard`` they would silently overwrite
ea... | tmux-python/libtmux-mcp | src/libtmux_mcp/tools/buffer_tools.py | .py | 577d64c2dc948148 | 7.56 | 12 |
"""Read-only MCP tools for tmux hook introspection.
Why read-only only
------------------
Write-hooks (``set-hook`` / ``unset-hook``) are deliberately excluded.
The reason is side-effect leakage: tmux servers outlive the MCP
process, so if an MCP agent installs a hook that runs arbitrary shell
on ``pane-exited`` or ``... | tmux-python/libtmux-mcp | src/libtmux_mcp/tools/hook_tools.py | .py | 2638a7988be39f50 | 7.56 | 12 |
"""Incremental capture tool for tmux pane observation."""
from __future__ import annotations
import asyncio
import base64
import binascii
import hashlib
import json
import time
import typing as t
from dataclasses import dataclass
from libtmux_mcp._utils import (
ExpectedToolError,
_get_server,
_resolve_p... | tmux-python/libtmux-mcp | src/libtmux_mcp/tools/pane_tools/capture_since.py | .py | 1977083600e8c1fe | 7.56 | 12 |
"""Pane sizing, selection, and swap tools."""
from __future__ import annotations
import typing as t
from libtmux_mcp._utils import (
ExpectedToolError,
_get_server,
_resolve_pane,
_resolve_window,
_serialize_pane,
handle_tool_errors,
)
from libtmux_mcp.models import (
PaneInfo,
)
@handl... | tmux-python/libtmux-mcp | src/libtmux_mcp/tools/pane_tools/layout.py | .py | 238b1019eb723138 | 7.56 | 12 |
"""Pane lifecycle tools: kill, respawn, title, info."""
from __future__ import annotations
import typing as t
from libtmux_mcp._history import _prepare_spawn_environment
from libtmux_mcp._utils import (
ExpectedToolError,
_caller_is_on_server,
_get_caller_identity,
_get_server,
_resolve_pane,
... | tmux-python/libtmux-mcp | src/libtmux_mcp/tools/pane_tools/lifecycle.py | .py | 54cf1b86b12d2cc7 | 7.56 | 12 |
"""Display-message and snapshot tools for pane introspection."""
from __future__ import annotations
from libtmux_mcp._utils import (
ExpectedToolError,
_coerce_bool,
_coerce_int,
_compute_is_caller,
_get_server,
_resolve_pane,
handle_tool_errors,
)
from libtmux_mcp.models import (
Pane... | tmux-python/libtmux-mcp | src/libtmux_mcp/tools/pane_tools/meta.py | .py | 4ce625e3966251b8 | 7.56 | 12 |
"""Pipe-pane tool for streaming pane output to a file."""
from __future__ import annotations
import re
import shlex
from libtmux_mcp._utils import (
ExpectedToolError,
_get_server,
_resolve_pane,
handle_tool_errors,
)
#: A maximal run of ``#``, plus the ``[`` that may follow it. tmux
#: treats a ``#... | tmux-python/libtmux-mcp | src/libtmux_mcp/tools/pane_tools/pipe.py | .py | b6941d1e92f4d359 | 7.56 | 12 |
"""Content-search across tmux panes."""
from __future__ import annotations
import re
from libtmux_mcp._utils import (
ExpectedToolError,
_coerce_bool,
_coerce_int,
_compute_is_caller,
_get_server,
_resolve_session,
handle_tool_errors,
)
from libtmux_mcp.models import (
PaneContentMatc... | tmux-python/libtmux-mcp | src/libtmux_mcp/tools/pane_tools/search.py | .py | a3424fa1b4ea0688 | 7.56 | 12 |
"""Shared tmux pane state helpers for read and wait tools."""
from __future__ import annotations
import typing as t
from libtmux_mcp._utils import ExpectedToolError
if t.TYPE_CHECKING:
from libtmux.pane import Pane
class _PaneState(t.NamedTuple):
"""Per-read snapshot of tmux pane grid and lifecycle state.... | tmux-python/libtmux-mcp | src/libtmux_mcp/tools/pane_tools/state.py | .py | a0c1d2c1109389af | 7.56 | 12 |
"""MCP tools for tmux server operations."""
from __future__ import annotations
import contextlib
import logging
import os
import pathlib
import socket
import typing as t
from fastmcp.exceptions import ToolError
from libtmux_mcp._history import _prepare_spawn_environment
from libtmux_mcp._utils import (
ANNOTATI... | tmux-python/libtmux-mcp | src/libtmux_mcp/tools/server_tools.py | .py | de6cd5443c864a19 | 7.56 | 12 |
"""MCP tools for tmux session operations."""
from __future__ import annotations
import typing as t
from libtmux.constants import WindowDirection
from libtmux_mcp._history import _prepare_spawn_environment
from libtmux_mcp._utils import (
ANNOTATIONS_CREATE,
ANNOTATIONS_DESTRUCTIVE,
ANNOTATIONS_MUTATING,... | tmux-python/libtmux-mcp | src/libtmux_mcp/tools/session_tools.py | .py | 695e4af7e72bd534 | 7.56 | 12 |
"""Shared runtime-evidence recording for AdaMAST integrations."""
from __future__ import annotations
import json
import time
from contextlib import contextmanager
from pathlib import Path
from typing import Any
from .fsio import read_text_retry, write_text_atomic_retry
from .reflection import ReflectionResult
EVIDE... | multi-agent-systems-failure-taxonomy/AdaMAST | adamast/core/evidence.py | .py | 2d4f1bf8555afad4 | 7.64 | 18 |
"""Windows-safe file primitives for state shared across hooks and workers.
CPython opens files without FILE_SHARE_DELETE, so on Windows an
``os.replace`` racing a concurrent reader — or a reader racing an in-flight
replace — raises ``PermissionError`` even though both sides are correct.
Writers hold the file for micro... | multi-agent-systems-failure-taxonomy/AdaMAST | adamast/core/fsio.py | .py | f39887fc38e53477 | 7.64 | 18 |
"""The one definition of the AdaMAST base directory.
``ADAMAST_HOME`` moves the ``~/.adamast`` base directory (see
``docs/CONFIGURATION.md``). Every root derived from it — the taxonomy store,
the trace root, the project-root cache, and the interactive routing root —
resolves through this module so they cannot disagree... | multi-agent-systems-failure-taxonomy/AdaMAST | adamast/core/home.py | .py | 3c93a20db2f63a89 | 7.64 | 18 |
"""Stable project/group identity for interactive harness programs."""
from __future__ import annotations
import hashlib
import json
import os
import re
import subprocess
from pathlib import Path
from .home import adamast_home
_SAFE_SCOPE_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
def validate_scope_id... | multi-agent-systems-failure-taxonomy/AdaMAST | adamast/core/project_scope.py | .py | 6811786f906e2807 | 7.64 | 18 |
"""Dependency-free helpers for redacting traces before persistence."""
from __future__ import annotations
import re
from collections.abc import Mapping, Sequence
from dataclasses import replace
from typing import Any, Pattern
from .traces import GenerationTrace
REDACTION = "[REDACTED]"
DEFAULT_SECRET_PATTERNS: tup... | multi-agent-systems-failure-taxonomy/AdaMAST | adamast/core/redaction.py | .py | e3be3868f1694b0e | 7.64 | 18 |
"""Flat taxonomy store: one JSON file per taxonomy, keyed by taxonomy_id.
Layout::
taxonomies/
<taxonomy_id>.json # exactly one record per taxonomy
A record carries: taxonomy_id, repo, domain, codes (failure modes).
`repo` and `domain` are recorded display-only fields; only taxonomy_id
identifies, look... | multi-agent-systems-failure-taxonomy/AdaMAST | adamast/core/store.py | .py | 8e494cfef0184d07 | 7.64 | 18 |
"""Crash-safe trace files in the exact AdaMAST generation-input shape.
Each trace is an independent JSON record with exactly:
problem_id, task, raw_trajectory, metadata
Program warm-up traces first land in ``<trace_output>/pending``. Approved or
inherited taxonomy traces live in ``<trace_root>/<taxonomy_id>``.
"... | multi-agent-systems-failure-taxonomy/AdaMAST | adamast/core/traces.py | .py | fbf40192d0316d08 | 7.64 | 18 |
"""Durable heartbeat files for detached AdaMAST background workers."""
from __future__ import annotations
import json
import os
import threading
import time
from contextlib import AbstractContextManager
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from .fsio import read_tex... | multi-agent-systems-failure-taxonomy/AdaMAST | adamast/core/worker_state.py | .py | 805cd6b3bbea31a9 | 7.64 | 18 |
"""HTTP server primitives for AdaMAST's localhost-only browser surfaces."""
from __future__ import annotations
from http.server import ThreadingHTTPServer
from socketserver import TCPServer
class LocalThreadingHTTPServer(ThreadingHTTPServer):
"""Bind without HTTPServer's unnecessary reverse-DNS lookup.
``H... | multi-agent-systems-failure-taxonomy/AdaMAST | adamast/dashboard/_http.py | .py | 66a044b873f13d48 | 7.64 | 18 |
"""当前请求 meta 的 contextvar(中立模块)。
server.Execute/ExecuteStream 在调 handle 前把整份 request.meta 写入这里;
- base.AgentClient 读 call_depth/call_stack(跨进程深度/环检测护栏);
- clients.LLMClient 读 thinking(复杂任务动态开思考,无需改各 Agent 业务码)。
抽到独立模块是为了解开 base ↔ clients 的循环依赖(base import clients,clients 又要读它)。
"""
from __future__ import annotations
... | SuperdeMan/cockpit-agent | agents/_sdk/_ctx.py | .py | e21f0fd72e8abe33 | 7.56 | 12 |
"""视觉地标描述 → 地图可检索的正式 POI 名解析(导航/充电等多 Agent 共用)。
用户常用外观/造型描述指代建筑(“像笋的建筑”)。地图 POI 库按**正式注册名**检索,
故须经 LLM 把视觉描述转成地图可检索的正式名(如“中国华润大厦”而非俗称“华润春笋大厦”)——
否则高德等会对俗称返回**同位置的邻近无关 POI**(搜“华润春笋大厦”→ V东滨店)。
约定:LLM 只产出“候选正式名”,由调用方用地图验证后才采用;模型不得直接决定导航目的地。
"""
from __future__ import annotations
import json
import logging
_DEFAULT_LOGG... | SuperdeMan/cockpit-agent | agents/_sdk/landmark.py | .py | ab53a9764d547675 | 7.56 | 12 |
"""会话级当前位置解析。
精确坐标只来自已获浏览器授权的请求 ``meta``,不写入记忆或持久化存储。
调用方负责在入口处完成 ``location.read`` 权限校验;本模块只做格式与范围校验。
"""
from __future__ import annotations
from dataclasses import dataclass
@dataclass(frozen=True)
class CurrentLocation:
lat: float
lng: float
def current_location_from_meta(meta: dict | None) -> CurrentL... | SuperdeMan/cockpit-agent | agents/_sdk/location.py | .py | acad6f6b06ede1e6 | 7.56 | 12 |
"""加载 manifest.yaml -> AgentManifest proto。"""
from __future__ import annotations
import yaml
from google.protobuf.struct_pb2 import Struct
from cockpit.agent.v1 import agent_pb2
def build_verification(raw) -> agent_pb2.Verification | None:
"""capability.verification(M2 Outcome Verifier)YAML → proto。
缺省 / 非 ... | SuperdeMan/cockpit-agent | agents/_sdk/manifest.py | .py | 729ad8798558c9e6 | 7.56 | 12 |
"""Provider 决议真实性护栏(数据真实性治理 P0)。
设计:docs/design/2026-07-17-data-authenticity-governance.md(§4 D2 层1/层3);
契约登记:docs/conventions.md §9.3。
两个约定,所有 Provider 工厂(`agents/*/src/providers/__init__.py`)收口处使用:
1. **fail-fast**:显式要求真实数据(vendor env 显式填了非 mock 值,或配了该域专属
凭证)而构造不出真实 Provider 时,`fail()` 抛 ProviderConfigError——Ag... | SuperdeMan/cockpit-agent | agents/_sdk/provenance.py | .py | aa086af45626cd79 | 7.56 | 12 |
"""Agent 业务返回的友好结构,SDK 负责转成 proto ExecuteResponse。"""
from __future__ import annotations
from dataclasses import dataclass, field
OK = "ok"
NEED_CONFIRM = "need_confirm"
NEED_SLOT = "need_slot"
FAILED = "failed"
REJECTED = "rejected"
@dataclass
class AgentResult:
speech: str = "" # 给 TTS 的播... | SuperdeMan/cockpit-agent | agents/_sdk/result.py | .py | 1306a00b9f83b575 | 7.56 | 12 |
"""把 BaseAgent 包装成 gRPC Agent 服务并自注册到 Registry。"""
from __future__ import annotations
import asyncio
import contextlib
import os
import socket
import grpc
from google.protobuf import struct_pb2
from runtime.grpcio import aio_server, bind_port, run_aio_server
from cockpit.agent.v1 import agent_pb2, agent_pb2_grpc
from... | SuperdeMan/cockpit-agent | agents/_sdk/server.py | .py | fab36b32794fe664 | 7.56 | 12 |
"""信源质量分层(共享)——按域名权威给来源分档,供检索后重排。
动机:Exa/搜索引擎按**相关性**返回,不区分权威性——学术/官方文档与内容农场会平等进池子
(深调研实测「混少量内容农场」)。本模块给来源一个**权威档位**,调用方据此重排:把学术/官方/
百科上移、内容农场下沉,让最权威的源优先进合成材料(top-N)并拿到靠前的引用编号。
设计取舍:
- **只重排、不丢弃**(诚实优先):低质源沉到末尾,仅当更优源不足以填满 top-N 时才会用到,
绝不因「权威性」静默删掉唯一信源。
- **稳定排序**:同档保留调用方传入的原相对序(即搜索引擎的相关性序),权威性只在跨档时起作用。
- 注入式、零依赖:纯函... | SuperdeMan/cockpit-agent | agents/_sdk/source_quality.py | .py | 12f20d02bcc12c23 | 7.56 | 12 |
"""接地兜底与 prompt 消毒单测(badcase 6d29929e:合成 422 全败 → 兜底把两篇原文
snippet 整段倾倒进 speech、SEO 标题/「正文」样板字直达用户、结尾拦腰截断)。"""
from agents._sdk.grounding import (
build_materials, clip_sentence, fallback_brief, sanitize_prompt_text,
)
# 仿真实 badcase 的 Exa snippet:SEO 标题行(| 分隔)+ 重复标题 + 「正文」样板行 + 长正文
_BADCASE_SNIPPET = (
"英格兰vs阿根... | SuperdeMan/cockpit-agent | agents/_sdk/tests/test_grounding_fallback.py | .py | ce1796afd6789f3e | 8.06 | 12 |
"""speech 通道 markdown 归一单测(2026-07-12 决策:不上渲染、后端出口硬剥)。"""
from agents._sdk.grounding import strip_markdown_speech
def test_strip_bold_code_heading_quote_bullet():
raw = ("# 结论\n"
"> 引用一句\n"
"**固态电池**的`能量密度`更高。\n"
"- 要点甲\n"
"* 要点乙\n"
"1. 保留数字分行要点")
out = s... | SuperdeMan/cockpit-agent | agents/_sdk/tests/test_grounding_md.py | .py | 6ed0ca836424fa8f | 8.06 | 12 |
"""共享地标解析器单测:名字匹配过滤 + 候选解析(不依赖真实 LLM)。"""
import asyncio
from agents._sdk.landmark import (
is_landmark_description, landmark_candidates, name_matches)
def test_is_landmark_description():
assert is_landmark_description("深圳外形像笋一样的建筑")
assert is_landmark_description("像船的建筑物")
assert not is_landmark_des... | SuperdeMan/cockpit-agent | agents/_sdk/tests/test_landmark.py | .py | eaeae868a3bd2bd3 | 8.06 | 12 |
"""共享时刻/时间窗解析单测(E1):时刻消歧、事件时刻、用餐窗反推、**业务时区**。
⚠ 断言一律用 `runtime.clock`(业务时区 UTC+8)构造期望值,**不用 `time.mktime` /
`time.localtime`**——后者按宿主本地时解释,而宿主恰好就是 UTC+8,于是
「容器 TZ=UTC 导致整体偏 8 小时」这类缺陷在本机**永远不红**(真栈实测
「预计 05:17 到达,比您要求的 17:00 早约 703 分钟」,两个 provider 逐字一致)。
另配一条**源码级守卫**:时钟族里不许再出现裸 `time.localtime` / `time.mktime`。
"""
im... | SuperdeMan/cockpit-agent | agents/_sdk/tests/test_timewindow.py | .py | 22ae00e4b444ad71 | 8.06 | 12 |
"""时刻与时间窗的**确定性**解析(G1 时间约束求解的共享实现)。
三件事,各有明确边界:
- `parse_clock_time`:中文/数字时刻 → epoch 秒(原 navigation `_parse_arrive_by`,
行为逐字不变)。**唯一实现**——nearby 要用同一套消歧语义,判定抄两份正是 B1 那个
bug 的成因(CLAUDE.md §6)。
- `parse_event_time`:**事件时刻**(「晚上7点的电影」「7点半那场话剧」)。与到达时限
(「5点前到」)刻意互斥:后者归 navigation 的 `arrive_by`,两条链不许抢同一句。
- `dining_w... | SuperdeMan/cockpit-agent | agents/_sdk/timewindow.py | .py | ae702e69407ea6b3 | 7.56 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.