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
"""Local cache for detail-page HTML. Layout: detail_cache/<source>/<source_id>.html. TTL: 24h by default. Re-runs the same day skip the network entirely. """ import time from pathlib import Path CACHE_DIR = Path(__file__).parent.parent.parent / "detail_cache" DEFAULT_TTL_S = 24 * 60 * 60 # 24h def _path(source: st...
luke-song/rent-kit
src/rentkit/cache.py
.py
4a3c1059eb400360
7
0
"""GCS-canonical Rentkit DB. Private deployments can mirror the SQLite DB to a GCS object. Every write verb pulls a fresh copy, mutates locally, and pushes back with an if-generation-match precondition. If the precondition fails, the caller can pull once more and retry the verb. Read-only verbs can use `with_db(read_...
luke-song/rent-kit
src/rentkit/cloud_sync.py
.py
66ca77d1e994ca4b
7
0
"""Craigslist scraper. No bot wall to speak of. Uses the configured sub-area searches, filtered by the bedroom range and dog flag from `search.toml`. Drops the neighborhood-id filter on purpose: codes drift, and the result set is small enough to filter on the title/hood text client-side. """ import re from playwright...
luke-song/rent-kit
src/rentkit/craigslist.py
.py
d9f695a4bbc2d038
7
0
"""Cross-source dedup. Two listings are the same property if: - both have lat/lng and they're within ~80m, AND - bed counts match (or one is None), AND - prices are within 20%. Fallback when lat/lng is missing on one side: normalized street-address match. When merging a cluster, fields are coalesced in source priori...
luke-song/rent-kit
src/rentkit/dedup.py
.py
8e9cd185fbb544b3
7
0
"""Local mirror of listing photos. Each listing's photos get downloaded once to tmp/photos/<source>/<source_id>/N.jpg and the listing.photos URLs are rewritten to relative paths the Firebase host serves directly. This protects against Zillow CDN expiry and source-page delisting. """ import asyncio import os from pathl...
luke-song/rent-kit
src/rentkit/photos.py
.py
cfca8fe3e3906fde
7
0
"""Rank listings by fit. Heuristic baseline. Higher score = better. Inputs are weighted in line with stated priorities, in priority order: - Dogs OK (large or any-size) — gate; no-dogs heavily penalized - Walk-to-trail — primary - Walk-to-beach — secondary - 3 bedrooms preferred, ≥ 1.5 baths preferred - In-...
luke-song/rent-kit
src/rentkit/rank.py
.py
1eecb6e760964ef0
7
0
"""Redfin scraper. Redfin sits behind PerimeterX (same wall as Zillow), so we drive the shared persistent Playwright profile (`.chrome-profile`) — a captcha cleared once via `rentkit solve`-style flow sticks across runs. The rental search server-renders the listing cards into the page (the data is NOT in an XHR), so w...
luke-song/rent-kit
src/rentkit/redfin.py
.py
ddcd79566fc9c12c
7
0
"""The search config: where you're looking, and what you want. Everything market-specific used to live as literals spread across the scrapers, the geocoder, the anchor lists, the scorer, and the LLM prompts. This module is the one place that knows those answers, read from a `search.toml` file so a new city is a config...
luke-song/rent-kit
src/rentkit/search_config.py
.py
4df4c7e652f48a79
7
0
"""What a source run actually covered. A blocked search and an empty search both used to return `[]`. `search` reads that list twice: once to upsert what it found, and once — through `succeeded_sources` — to decide which listings are gone from the market and should be marked inactive. That second read is where the di...
luke-song/rent-kit
src/rentkit/sources.py
.py
fe83a1c71da6d83b
7
0
"""SQLite-backed storage for listings. One row per (source, source_id). Each search upserts; `last_seen` tracks freshness, `active` marks whether the most recent run saw the listing. """ import json import os import sqlite3 from contextlib import contextmanager from datetime import datetime from pathlib import Path f...
luke-song/rent-kit
src/rentkit/storage.py
.py
92de6a02239b6c29
7
0
"""Walking-time estimates from a listing to named anchors. The anchors come from the search config, in four groups: - BEACHES / TRAILS / BAKERIES: the "somewhere worth walking to" set. Each group is collapsed to its nearest member, so adding an anchor to the config widens the search rather than adding anothe...
luke-song/rent-kit
src/rentkit/walk.py
.py
838ecabb57ccccf1
7
0
"""Zillow scraper. Search results: parse `__NEXT_DATA__` JSON from the search page (clean, structured, doesn't need a real browser render). Detail enrichment: Zillow embeds the facts as a flat list of "Key: Value" items inside `<ul class*=Fact> <li>`. We pull the list raw and key off it instead of regex-grepping the ...
luke-song/rent-kit
src/rentkit/zillow.py
.py
27c109e758f772ca
7
0
"""Zumper scraper. Zumper hydrates the search results into `window.__PRELOADED_STATE__` under `currentSearch.listables.listables` — same shape-trick as Zillow's `__NEXT_DATA__` but stashed on the window instead of a script tag. We pull the array directly via `page.evaluate` and skip DOM parsing. The configured URL fi...
luke-song/rent-kit
src/rentkit/zumper.py
.py
50cadf015ecc18e0
7
0
"""A cloud-synced verb without a bucket should explain itself, not traceback. Cloud sync is optional plumbing, but the verbs that use it default to it. On a single-machine setup — which is every setup until someone deliberately sets up GCS — the first `rentkit why` used to end in a RuntimeError raised several frames i...
luke-song/rent-kit
tests/test_cloud_not_configured.py
.py
7e97dc60bd4208ad
7.5
0
"""A source that could not look has not established that anything is gone. `storage.upsert_run` marks a listing inactive when a source reported in and the listing was not among what it reported. That inference is only sound if the source actually read everywhere it searches. Blocking happens per area; the guard was pe...
luke-song/rent-kit
tests/test_partial_coverage.py
.py
0720bb369eba3ad8
7.5
0
"""A score of zero has two causes, and the integer cannot tell them apart. `score_detail` mirrors `score` term for term. The mirroring is the risk in this change, so the first test here is the one that holds the two together across the whole fixture. """ import shutil import rentkit from rentkit import storage, walk...
luke-song/rent-kit
tests/test_score_detail.py
.py
a9a99ff053f52c20
7.5
0
"""The config is now load-bearing, so it gets tested like code. Every market literal used to live next to the code that consumed it, where a typo broke one scraper loudly. Now one file feeds the scrapers, the geocoder, the anchors, the scorer and the prompts, so a wrong value is wrong everywhere at once and a missing ...
luke-song/rent-kit
tests/test_search_config.py
.py
04de4a1f64fbc254
7.5
0
import pytest from rentkit import craigslist, dedup from rentkit.locations import PRIMARY_TERMS, SECONDARY_TERMS def test_source_priority_keeps_zillow_as_primary_source(): assert dedup.SOURCE_PRIORITY["zillow"] == 0 assert dedup.SOURCE_PRIORITY["zillow"] < dedup.SOURCE_PRIORITY["craigslist"] def _respaced(...
luke-song/rent-kit
tests/test_source_config.py
.py
19cb13a99b9c742a
7.5
0
"""A weight table is a claim about the scorer, so it gets checked like one. `TERM_WEIGHTS` is what `rentkit why` prints when it says what the policy weighs most. Hand-written tables drift from the code they describe and then report something nobody verified — which is the failure this whole branch is about. These test...
luke-song/rent-kit
tests/test_term_weights.py
.py
ada44ea3921b1550
7.5
0
"""The output is the feature, so the output gets tested. `score_detail` returning correct lists is not the change — a person reading a screen and coming away with the right belief is. These tests pin the sentences that carry that, because a refactor that silently drops "never evaluated" turns the tool back into the th...
luke-song/rent-kit
tests/test_why_output.py
.py
2c94f05e96042609
7.5
0
"""Top 10 candidates — domain-colored bar chart with track-colored gene names.""" from __future__ import annotations import sys; sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent)) from style import * import matplotlib.pyplot as plt, numpy as np, pandas as pd from matplotlib.patches import Pa...
dhzso/neuraltf
projects/NeuralTF/scripts/figures/05_top10_candidate_atlas.py
.py
c6269079317949aa
7.15
1
"""Composite bonus waterfall — shows base score + each bonus for top-10.""" from __future__ import annotations import sys; sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent)) from style import * import matplotlib.pyplot as plt, numpy as np, pandas as pd GO_NEURAL_KW = {"neurogenesis","nervou...
dhzso/neuraltf
projects/NeuralTF/scripts/figures/18_composite_bonus_waterfall.py
.py
d0d9408f2bedff79
7.15
1
"""Validate NeuralTF top-10 candidates against Perez 2025 ANANSE predictions. Cross-references our prioritized TFs against the ANANSE-predicted TF-target regulatory network from Perez et al. 2025 (MOESM22). """ from __future__ import annotations import sys from pathlib import Path import pandas as pd ROOT = Path(__...
dhzso/neuraltf
projects/NeuralTF/scripts/validate_with_perez.py
.py
dba8ba61a20c9a96
7.15
1
#!/usr/bin/env python """Permutation baseline for NeuralTF pipeline. Shuffles cluster labels in scRNA-seq atlases to generate null distribution of integrated scores. Computes empirical p-values for real candidates. Usage: python scripts/permutation_baseline.py --n-perm 10 --subsample 2000 """ import argparse imp...
dhzso/neuraltf
scripts/permutation_baseline.py
.py
e8eb53b36ed16d0c
7.15
1
"""Generate concise, evidence-backed portfolio findings from the loaded real dataset.""" from __future__ import annotations import argparse import sqlite3 from pathlib import Path ROOT = Path(__file__).resolve().parents[1] def rows(connection, query): return connection.execute(query).fetchall() def main() -> int...
dytcoke23/ecommerce-revenue-customer-experience-analytics
src/generate_reports.py
.py
7b301508bbddf565
7
0
# -*- coding: utf-8 -*- """ 文档速读工具 read_files.py 按扩展名自动分派最优提取器,批量输出结构化文本。 用法: python read_files.py <path> [path...] path 可以是文件或文件夹(文件夹会递归处理) python read_files.py --markitdown <path> # PDF/docx/pptx/图片 走 MarkItDown 统一转换 python read_files.py --mineru <path> # PDF 走 MinerU 深度解析(Windows 命令行不稳) 工具映射: ....
GZLns/Document-reader-
read_files.py
.py
1e4a871831922754
7
0
# -*- coding: utf-8 -*- """ xlsx/xls/csv 速查工具 xlsx_query.py(2026-08-25 升级版) 读取层:python-calamine(Rust 引擎,支持 .xlsx/.xls/.ods,速度远超 openpyxl) 查询层:原生细粒度查询 + duckdb SQL 模式(直查 xlsx/csv,无需导入) 用法: python xlsx_query.py <file> --list # 列出所有 sheet 和尺寸 python xlsx_query.py <file> --sheet Sheet0 --head 10 ...
GZLns/Document-reader-
xlsx_query.py
.py
ec1eb78493d876a1
7
0
# -*- coding: utf-8 -*- """ 仓库级 PLC 规范审查(CI 门禁)。 检查项(对应 AGENTS.md R1~R4 + 制表/编码规则): 1. 编码:CSV 必须 GBK,.md 必须 UTF8(无 BOM) 2. R1 标识符仅英文:扫描 .st 代码文件中的中文字符 3. 魔法数字检查:代码中裸数字字面量告警(白名单除外) 4. CSV 列数一致性:每行字段数 = 表头字段数(拦截"含逗号字段未加引号"导致的列错位) 5. 通讯字表专项:5 列结构、Mobus=40001+offset、写1触发段标记 6. 通讯字表 ↔ host 变量表一致性:host_Rcv_* 的 D ...
TReaur1/ELE
scripts/ci_check.py
.py
531cd3813f1f626d
7
0
# -*- coding: utf-8 -*- """一键生成 + 审查. 用法: python scripts/generate.py <project> 流程: 加载规格单 -> 生成表格 -> 生成ST -> 审查ST 若审查发现未声明符号/R1违规, 返回非0退出码. """ import os, subprocess, sys BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def run(script, *args): r = subprocess.run([sys.executable, os.path.join(BAS...
TReaur1/ELE
设备模型库/scripts/generate.py
.py
b998c2b93c1cd085
7
0
# -*- coding: utf-8 -*- """生成代码审查 (review_st): 校验生成 ST 是否符合 AGENTS.md 规则. 检查项: R1 标识符仅英文(注释外的中文) 未声明符号(变量/实例/常量/类型 须在表中声明) FB 结构平衡(VAR_INPUT/OUTPUT/IN_OUT/END_VAR) CASE 选择器为整型 魔法数字(数值字面量) 常见缺陷清单(见 AGENTS.md 六) """ import os, re, sqlite3, sys BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))...
TReaur1/ELE
设备模型库/scripts/review_st.py
.py
fa634efa1fee343e
7
0
"""Windows-headless / detached process-spawn helpers (shared, vendored per plugin). A copilot-extensions runtime frequently runs **windowless**: under a hidden Windows Scheduled Task launched via ``conhost --headless``, inside the agent-bridge daemon, or from a session-start hook whose parent has no console of its own...
ThomasMichon/copilot-extensions
libs/agent-procutil/src/agent_procutil/__init__.py
.py
8a61fc73adc72264
7.24
2
"""Core migration primitives: ``migrate_doc`` (in-memory) and ``migrate_file``. Two call sites, one migrator registry -- the *migrate-by-rewrite* model: * ``migrate_doc`` applies the ordered ``vN->vN+1`` migrators to a parsed config document **in memory** and returns ``(new_doc, changed)``. This is the **loader's...
ThomasMichon/copilot-extensions
libs/config-migrate/src/config_migrate/core.py
.py
77d2469a245ee27f
7.24
2
"""Schema registry: schema_id -> current version + ordered vN->vN+1 migrators. A ``SchemaRegistry`` is the single source of shape-change truth for a set of managed config files. Each managed schema declares: * a stable ``schema_id`` (e.g. ``"agent-worktrees/config"``), * a monotonic integer ``current_version`` (match...
ThomasMichon/copilot-extensions
libs/config-migrate/src/config_migrate/registry.py
.py
e542436a67d0ca48
7.24
2
"""Runner: migrate a set of managed config files against a registry. The *discovery* of which files are managed (by convention from an install root) is deliberately left to the consuming plugin -- only the plugin knows its own config layout. The runner takes an explicit list of ``ManagedFile`` entries and applies ``mi...
ThomasMichon/copilot-extensions
libs/config-migrate/src/config_migrate/runner.py
.py
5d5ab7c743567c5b
7.24
2
"""Provider source-injection API for the credential relay. agent-bridge runs the relay in its daemon and discovers provider plugins that inject credential sources for their targets. Each provider exposes:: # <provider_pkg>/relay_provider.py def register_relay(builder: RelayBuilder) -> None: builder.ad...
ThomasMichon/copilot-extensions
libs/credential-relay/src/credential_relay/registry.py
.py
89046008e218fc0f
7.24
2
"""Pluggable credential resolution sources. Each source handles a subset of credential requests (by action and/or host pattern). The relay server routes requests to the first source whose ``supports()`` returns True. """ from __future__ import annotations from typing import Protocol, runtime_checkable @runtime_che...
ThomasMichon/copilot-extensions
libs/credential-relay/src/credential_relay/sources/__init__.py
.py
a63b123e4ea4888b
7.24
2
"""Azure CLI token source. Returns Azure access tokens via ``az account get-access-token``. Handles the ``get-azure-token`` relay action, returning the token in git-credential-protocol key=value format for uniform framing. This is a HIGH-TRUST credential source. It must be explicitly enabled and configured with an ex...
ThomasMichon/copilot-extensions
libs/credential-relay/src/credential_relay/sources/az_login.py
.py
3364aa3f90a8e74d
7.24
2
"""GitHub CLI auth token source. Returns ``gh auth token`` output for GitHub hosts. Handles the ``get-github-token`` relay action, returning the token in git-credential-protocol key=value format for uniform framing. """ from __future__ import annotations import asyncio import logging import subprocess import sys lo...
ThomasMichon/copilot-extensions
libs/credential-relay/src/credential_relay/sources/gh_auth.py
.py
2b59fa78243414ce
7.24
2
"""Git Credential Manager (GCM) proxy source. Proxies credential requests to the local ``git credential`` command, which typically resolves through Git Credential Manager. Includes WSL detection (routes through PowerShell when running under WSL), credential caching with TTL, and request coalescing for expensive GCM ro...
ThomasMichon/copilot-extensions
libs/credential-relay/src/credential_relay/sources/git_credential.py
.py
0940520b086d77e8
7.24
2
"""Injected Azure-token source (test/relay-shim affordance). Serves the ``get-azure-token`` action from a **pre-minted bearer supplied in an environment variable**, instead of shelling ``az account get-access-token`` like :class:`~credential_relay.sources.az_login.AzLoginSource`. Why this exists --------------- The r...
ThomasMichon/copilot-extensions
libs/credential-relay/src/credential_relay/sources/injected_token.py
.py
0ed8198b0c1d9e6b
7.24
2
"""Tests for the injected Azure-token relay source (test/relay-shim affordance). Covers the production-inert passthrough contract and the serve/allowlist/expiry behavior. The build-wiring assertion (injected source placed BEFORE az-login) lives in test_relay_shim.py, which has the relay_token isolation fixture. """ f...
ThomasMichon/copilot-extensions
libs/credential-relay/tests/test_injected_token.py
.py
0958152529408f38
7.74
2
"""Tests for relay-port reclaim on a stale holder (#19).""" from __future__ import annotations import asyncio import errno import os import socket import subprocess import sys from credential_relay.server import ( CredentialRelayServer, _addr_in_use, _pid_on_port, _reclaim_port, ) def _free_port() ...
ThomasMichon/copilot-extensions
libs/credential-relay/tests/test_port_reclaim.py
.py
9a3004d863526016
7.74
2
"""Structured scan and entry verdicts shared by drop-in registry consumers.""" from __future__ import annotations import hashlib import json from collections.abc import Mapping from dataclasses import dataclass, field from enum import Enum from typing import Generic, TypeVar T = TypeVar("T") class ScanAuthority(st...
ThomasMichon/copilot-extensions
libs/dropin-registry/src/dropin_registry/model.py
.py
d290082f3c5c5088
7.24
2
"""Bounded operational-warning selection.""" from __future__ import annotations import time from collections.abc import Iterable from dataclasses import dataclass, field from .model import Finding @dataclass(frozen=True) class WarningBatch: """Detailed findings selected for one operational emission.""" em...
ThomasMichon/copilot-extensions
libs/dropin-registry/src/dropin_registry/warnings.py
.py
922eb1b43fd456cd
7.24
2
"""Rendezvous (port-mapping) files for discoverable, collision-free local endpoints. A *service-bearing* Copilot CLI plugin needs its clients -- its own CLI, sibling plugins, and agents on the box -- to reach it without hardcoding a fixed loopback TCP port. Pinning a port collides with siblings, with the ``127.0.0.1``...
ThomasMichon/copilot-extensions
libs/endpoint-rendezvous/src/endpoint_rendezvous/rendezvous.py
.py
7ae999b9b2ec81a4
7.24
2
"""Load a plugin **marketplace** manifest and resolve a plugin's on-disk source directory, across the Copilot-native and Claude conventions. A marketplace directory carries a ``marketplace.json`` (at ``.github/plugin/``, the root, ``.plugin/``, or ``.claude-plugin/`` -- native-first) listing plugins, each with a ``sou...
ThomasMichon/copilot-extensions
libs/plugin-resolve/src/plugin_resolve/marketplace.py
.py
847f6dbf1a64d6d2
7.24
2
#!/usr/bin/env python3 """Hermes shell hook: convention + failure signal recorder (post_tool_call). ⚠️ IMPORTANT — ``post_tool_call`` results are OBSERVATIONAL in Hermes: the shell-hook bridge parses ``{"context": ...}`` for any event, but the sole emitter (``model_tools._emit_post_tool_call_hook``) **discards the ret...
zaxbysauce/zmem
hermes-plugin/hooks/zmem-hermes-convention.py
.py
86a9e5de86d9a6c9
7
0
#!/usr/bin/env python3 """Hermes shell hook: reflect nudge DELIVERY (pre_llm_call) — universal surface. This is the DELIVERY side of the reflection loop. The convention hook (``post_tool_call``, observational — its results are discarded by Hermes) records pending-nudge flags in zmem's ``meta`` table; THIS hook fires o...
zaxbysauce/zmem
hermes-plugin/hooks/zmem-hermes-reflect.py
.py
8ade08d420518ea1
7
0
#!/usr/bin/env python3 """Hermes shell hook: coding-stop reflect nudge (pre_verify). Fires only on coding turns where the agent edited files and is about to verify/finish (Hermes gates ``pre_verify`` on ``_turn_file_mutation_paths``, so non-coding gateway sessions never reach this hook). Emits ``{"action": "continue",...
zaxbysauce/zmem
hermes-plugin/hooks/zmem-hermes-verify.py
.py
636dc228dd013600
7
0
"""SDK-native Bearer-token auth for the zmem MCP server. Uses the ``mcp`` SDK's built-in ``TokenVerifier`` Protocol rather than custom Starlette middleware. The SDK wires ``BearerAuthBackend`` + ``RequireAuthMiddleware`` automatically when ``FastMCP(auth=..., token_verifier=...)`` is constructed (verified in mcp/serve...
zaxbysauce/zmem
hermes-plugin/server/auth.py
.py
165a997ed770e587
7
0
"""Bind-address guard for the zmem MCP server. Security control (not just docs): refuse to bind to a wildcard address (``0.0.0.0`` / ``::``) unless the operator has explicitly opted in via ``ZMEM_MCP_ALLOW_INSECURE_BIND=1``. A Bearer-protected store broadcasting on the whole network is a real exposure — the token is t...
zaxbysauce/zmem
hermes-plugin/server/bind_guard.py
.py
3539d23ea8c2f9f4
7
0
#!/usr/bin/env python3 """Shared recall body for the injecting hooks (issue #58, 3.5/3.8/3.9). Consumers (all invoke this file AS A SCRIPT — the hyphenated filename cannot be imported): - zmem-recall.sh (UserPromptSubmit) mode "user_prompt" - zmem-precompact.sh (PreCompact, Claude only) mode "pr...
zaxbysauce/zmem
hooks/lib/zmem-recall-body.py
.py
a7bfa44570096145
7
0
"""Public-corpus adapters for the zmem eval gold format (issue #64, 9.3). Converts published eval sets into the gold JSONL shape that scripts/eval_runner.py and `store.py tune-weights` consume: python scripts/eval_adapters.py --adapter longmemeval --input <path> --out <path> python scripts/eval_adapters.py --...
zaxbysauce/zmem
scripts/eval_adapters.py
.py
8bc4bf51c74f2359
7
0
"""Offline eval runner for the zmem memory store (issue #64, 9.1 + 9.5). THE canonical eval command — CI (`.github/workflows/ci.yml`) runs exactly this, and SKILL.md documents exactly this: python scripts/eval_runner.py --store <path> [--gold eval/gold.jsonl] \\ [--k 5] [--fail-under X] [--json-out PATH] ...
zaxbysauce/zmem
scripts/eval_runner.py
.py
7403d89ef75e9f86
7
0
#!/usr/bin/env python3 """Ingest a closeout-remote harvest JSON array into the zmem store. Reads a harvest JSON file (the array format documented in skills/closeout-remote/SKILL.md's "Output format" section), validates each row's shape and enum values, and calls `store.py add` via subprocess for each valid row. This ...
zaxbysauce/zmem
scripts/ingest_harvest.py
.py
4deed83a20c9227a
7
0
#!/usr/bin/env python3 """Pattern-tuning harness for zmem's correction-pattern library (issue #46). Adapted from claude-reflect (https://github.com/BayramAnnakov/claude-reflect), MIT-licensed, `scripts/compare_detection.py` — minus the semantic/LLM side. zmem's scripts must be stdlib-only and multi-host: this harness ...
zaxbysauce/zmem
scripts/pattern_harness.py
.py
428b33978ee59b7c
7
0
#!/usr/bin/env python """Release gate: make the repo's release contract self-enforcing. The documented contract (README / CHANGELOG) is "released versions are marked with a git tag (vX.Y.Z) and a GitHub Release". That step was manual, and the manual step silently rotted: v0.8.5/v0.8.6/v0.8.8 were never tagged and v0.9...
zaxbysauce/zmem
scripts/release_gate.py
.py
e176740d5f2ddeeb
7
0
"""Embedding profile registry (issue #63, 8.2). Single source of truth for the model/dim/hash facts of every shipped embedding profile. Both ``embeddings.py`` (the loader), ``storelib/schema.py`` (the vec0 DDL dim), ``storelib/cli.py`` (profile selection + dim-mismatch refusal), and ``doctor.py`` (the embeddings_healt...
zaxbysauce/zmem
skills/memory/scripts/embed_profiles.py
.py
0666878e7c4924bf
7
0
#!/usr/bin/env python """ZMem legacy-store import — Phase 1 (box-wide unified memory, PLAN.md P1). Copies the existing per-plugin ZCode store into the new box-neutral location (~/.zmem by default) WITHOUT ever opening the source read-write. The legacy store may be live (an active ZCode session writing to it) so this s...
zaxbysauce/zmem
skills/memory/scripts/import-store.py
.py
75047ada65ad486b
7
0
from __future__ import annotations # PRR-032 note: the from-import lines below re-import several names from # DIFFERENT submodules (ALLOWED_SIGNALS, STORE_PATH, stdlib modules, ...). # Python binds the LAST occurrence, so when adding a new submodule line, # verify any name it re-exports that an earlier line also impor...
zaxbysauce/zmem
skills/memory/scripts/storelib/__init__.py
.py
9881fab5981720d4
7
0
"""Optional post-MMR cross-encoder rerank (issue #63, 8.6). POLICY (load-bearing — do not weaken): - Default OFF everywhere. Enablement requires ZMEM_CROSS_ENCODER to opt in. - Rerank fires ONLY on explicit CLI `recall` runs that also mutate telemetry: `cli_allowed` demands recall-without---no-bump. Every hook surfa...
zaxbysauce/zmem
skills/memory/scripts/storelib/cross_encoder.py
.py
be9da0f236b28d38
7
0
from __future__ import annotations import argparse import calendar import contextlib import hashlib import json import math import os import re import shutil import sqlite3 import struct import subprocess import sys import time import uuid import glob from datetime import datetime, timezone from pathlib import Path fr...
zaxbysauce/zmem
skills/memory/scripts/storelib/promote.py
.py
d6f7eb5b82c31761
7
0
"""Build a tiny deterministic store fixture for CLI characterization. Task 2.1 (issue #57): the characterization suite freezes stdout hashes of `stats`, `list --json`, `recall --json` and `export-jsonl` against a fixture store, and must fail if the public CLI surface (subcommands / required flags) drifts. This builder...
zaxbysauce/zmem
tests/fixtures/store_builder.py
.py
4d4c1a687e2ce60b
7.5
0
"""Issue #58, 3.6: ``--as-of ISO-8601`` temporal predicate. Three rows with staggered ``valid_from``; recall at T2 returns only the first two. Absent flag → all live rows (current behavior). Also tests the Z-suffix normalization: ``+00:00`` input must compare correctly against ``valid_from`` stored with a Z-suffix (I...
zaxbysauce/zmem
tests/test_as_of_recall.py
.py
7fd01ae3f8c0ddd6
7.5
0
"""Executable transformation-family classifiers (human side only). These implement PREREG-CENSUS section 4 and 5. They are used to ATTACK the grammar (is a human mutation taxonomy privileged by the physics?). They are never visible to any learner, never enter generation, selection, routing or admission, and are record...
jcraig949jfi/Prometheus
agent_d2_blind/d2/classify.py
.py
8818b99fa68a508c
7.24
2
"""G3B REWRITE-ONEPASS basis. Identical grammar to G3. Only the rewrite strategy differs: a single pre-order pass over the ORIGINAL positions, each position rewritten at most once and the result never re-scanned. Why this variant exists (disclosed multiplicity): a smoke test — run before any census — showed that the ...
jcraig949jfi/Prometheus
agent_d2_blind/d2/g3b.py
.py
28a81189d82673db
7.24
2
"""Anti-cheat battery. Must pass before any evidence is read. Static checks scan code with comments and string literals stripped, so a docstring mentioning a forbidden word cannot pass or fail a check by itself. """ import io import json import os import sys import tokenize HERE = os.path.dirname(os.path.abspath(__fi...
jcraig949jfi/Prometheus
agent_d3_blind/anti_cheat/checks.py
.py
3ad38463dbcf5360
7.24
2
"""Shared M0 harness: identical physics, identical validity API, identical meter. The baselines see ONLY the whitelisted numeric observation dict returned by `Ctx.evaluate`. Semantic fingerprints, targets, witnesses and family labels are recorded on the harness side and are never returned to a baseline. """ import ra...
jcraig949jfi/Prometheus
agent_d3_blind/m0/harness.py
.py
5c76f4c35ec5e336
7.24
2
"""Frozen probe batteries. VALUE_PROBES fix all semantic equivalence in this experiment; every equivalence claim is therefore probe-relative and is labelled as such. EXT_PROBES exist only for the preregistered probe-stability check. """ import hashlib import random VALUE_PROBES = [ (), (0,), (5,), (1...
jcraig949jfi/Prometheus
agent_d3_blind/probes/battery.py
.py
da398ea3e6ca3f19
7.24
2
"""Basis registry and canonical-order control (frozen).""" import random from . import s1_tpc, s2_flat, s3_trs, s4_rev BASES = {"S1": s1_tpc, "S2": s2_flat, "S3": s3_trs, "S4": s4_rev} ORDER_SPACES = { "S1": (s1_tpc.NSLOT, s1_tpc.NARG), "S2": (s2_flat.NOPS, s2_flat.NARG), "S3": (s3_trs.NKIND, s3_trs.NPAY)...
jcraig949jfi/Prometheus
agent_d3_blind/substrates/registry.py
.py
faf09da7613b6be8
7.24
2
"""Anti-cheat static battery. Spec: constitution section 39. Seam doctrine: learner-visible data is ALLOWLISTED at field level. The only learner-visible object is learner_view(task) == {'domain', 'table'}; both hold pure integers. Anything else (family, seed, gen_meta, witness, strata, oracle solutions) is oracle-side...
jcraig949jfi/Prometheus
agent_d5_blind/anti_cheat/static_checks.py
.py
ab391ae45a3b7383
7.24
2
""" MechKernel Adaptive Renderer(M1 阶段) C 方案的核心:决定每步操作该用哪个 render_level。 - none: 不渲染(默认) - iso_only: 1 张 iso 视角 - full: 4 视角 策略: 1. 拓扑变化必渲染 iso_only 2. 失败恢复必渲染 iso_only 3. 间隔 N 步渲染一次 full 4. 草图/查询/状态操作不渲染 """ from typing import Optional, Dict import time from .features import FeatureType, TOPOLOGY_CHANGING_OPS, NON_...
vanyu0710/mechcad-kernel
mech_kernel/adaptive_renderer.py
.py
c97070ea1127f443
7
0
""" MechKernel AI Orchestrator (v1 单 orchestrator) P2-10 (v8 DeepSeek): 加结构化日志 """ import logging _logger = logging.getLogger("mech_kernel.orchestrator") if not _logger.handlers: _h = logging.StreamHandler() _h.setFormatter(logging.Formatter( "[%(asctime)s] %(levelname)s orchestrator: %(message)s", ...
vanyu0710/mechcad-kernel
mech_kernel/ai_orchestrator.py
.py
568af85c83b58444
7
0
""" MechKernel Capability Registry v2 升级基础设施:自动注册 + schema 描述 + 参数校验 + 权限分级 专家第 5 轮审查建议: - 当前 PUBLIC_OPS = frozenset({...}) 硬编码白名单不可维护 - 真实 LLM 需要结构化 op 描述 - 需要权限分级(public / read / internal) - 需要参数类型/范围/必填校验 设计目标: - 装饰器自动注册(@cap.register(...)) - JSON Schema 风格的 input_schema - LLM 友好的 list_public() 输出 """ from typing...
vanyu0710/mechcad-kernel
mech_kernel/capability_registry.py
.py
f8dabb3c6cd220c7
7
0
""" MechKernel 类型化错误定义(v1.1 修复版) 5 类 + 1 类: 1. InvalidRequestError - 编程错误,必须抛 2. KernelBugError - 内部 bug,必须抛 3. StateCorruptionError - 状态损坏,必须抛 4. GEOMETRY_FAILURE - 预期内几何失败,StepResult 表达 5. RECOVERABLE - 可修复失败,StepResult 表达 6. NOT_IMPLEMENTED - 能力未实现(占位 API),StepResult 表达(P0 修复新增)...
vanyu0710/mechcad-kernel
mech_kernel/errors.py
.py
cdb2bd3ff75cd3be
7
0
""" Demo 3: M1 阶段 — 用 MockMesh 展示 3D 渲染 M1 阶段实现: - geometry_inspector:BRep 指标(体积/面数/包围盒/流形/水密/连通) - renderer:matplotlib 离屏 4 视角渲染 - adaptive_renderer:智能决定何时渲染 """ import os import sys sys.path.insert(0, '/workspace') from mech_kernel import MechKernel class MockBox: """Mock 一个 10x10x10 的立方体""" def __init__(...
vanyu0710/mechcad-kernel
mech_kernel/examples/03_mock_render.py
.py
efa394bb1feb145f
7
0
""" Demo 4: M2 E2E — 用户说"建一个圆柱体",AI 自动建 展示 MechAgent v1 单 orchestrator: - Mock Planner 解析用户 prompt - Mock Vision 验证 - Kernel 一步一步执行 - 每步打印结果 """ import sys import os sys.path.insert(0, '/workspace') from mech_kernel import MechKernel from mech_kernel.ai_orchestrator import MockPlanner, MockVision, run_loop, PlannerAc...
vanyu0710/mechcad-kernel
mech_kernel/examples/04_e2e_orchestrator.py
.py
1148849bbeb2bea3
7
0
""" Demo 06: 端到端 Vision LLM + Planner LLM + MechKernel + 真实 build123d 几何 流程: 1. 准备手绘 PNG(matplotlib 模拟) 2. Vision LLM(DeepSeek Vision)→ 零件 JSON 3. Planner LLM(DeepSeek Chat)→ op 序列 4. MechKernel 执行 op → build123d 真实几何 5. 渲染对比图(手绘草图 vs 真实几何) 运行:PYTHONPATH=/workspace python3 mech_kernel/examples/06_end_to_end_llm.py 环境...
vanyu0710/mechcad-kernel
mech_kernel/examples/06_end_to_end_llm.py
.py
8fd8ad5897eafa46
7
0
""" Demo 07: 复杂实际零件端到端 4 个工程件: 1. 带孔方板(80×60×10 + Ø20 通孔) 2. 阶梯轴(Ø40×30 + Ø25×50,两段同轴) 3. 键槽轴(Ø40×80 + 12×5×40 键槽) 4. L 形支架(两个矩形 extrude union) 每件: - 画手绘 PNG - Vision LLM 识别 - Planner LLM 拆 op - Kernel 真实几何 - 渲染对比图 """ from __future__ import annotations import os import sys import json import base64 from pathlib impo...
vanyu0710/mechcad-kernel
mech_kernel/examples/07_complex_parts.py
.py
5311fc44924ab0ac
7
0
""" Demo 09: Fillet + Chamfer 在真实零件上的应用 4 个 demo: 1. 圆角立方体(基本 fillet) 2. 倒角方板(基本 chamfer) 3. 带沉孔 + 圆角(fillet 复合 boolean) 4. 法兰盘带圆角(fillet 圆盘边缘 + 沉孔边) 每个 demo 输出对比图(带 fillet/chamfer 前 vs 后) """ from __future__ import annotations import os, sys, math from pathlib import Path HERE = Path(__file__).parent OUT = HERE / "f...
vanyu0710/mechcad-kernel
mech_kernel/examples/09_fillet_chamfer.py
.py
3351ece2401f86d2
7
0
""" Demo 10: Boolean op 显式 API(v1.7 新增) 4 个 boolean demo: 1. union: 两个 box 合并 2. subtract: 盒 - 圆柱(多 tool 一起切) 3. intersect: 盒 ∩ 圆柱 4. 实际工程:L 形盒用 boolean union """ from __future__ import annotations import os, math from pathlib import Path HERE = Path(__file__).parent OUT = HERE / "boolean_out" OUT.mkdir(exist_ok=True)...
vanyu0710/mechcad-kernel
mech_kernel/examples/10_boolean.py
.py
a8a74aeb5f1b6968
7
0
""" Demo 11: Hole + Mirror + Linear Pattern(v1.8-1.10 新增) 4 个工程件: 1. 法兰盘:4 孔用 hole 2. 对称键槽:用 mirror 3. 散热板:8 孔用 linear_pattern 4. 综合:板 + 4 hole + mirror + fillet(完整流程) """ from __future__ import annotations import math from pathlib import Path HERE = Path(__file__).parent OUT = HERE / "hole_out" OUT.mkdir(exist_ok=Tru...
vanyu0710/mechcad-kernel
mech_kernel/examples/11_hole_mirror_pattern.py
.py
79bd84e7cf44d570
7
0
""" Demo 12: Query / Select / Measure (v1.11-1.15) 5 个 query 能力 + select 按类型 + measure 3 种度量 + delete/update """ from __future__ import annotations from pathlib import Path HERE = Path(__file__).parent OUT = HERE / "query_out" OUT.mkdir(exist_ok=True) def make_bracket(): """造一个测试件:带孔的板""" from mech_kernel im...
vanyu0710/mechcad-kernel
mech_kernel/examples/12_query_measure.py
.py
55e36318e0ce9fc0
7
0
""" MechKernel Feature Graph(DAG) 替代 v1.0 的 List[FeatureNode],支持: - 拓扑排序 - 循环检测 - 依赖追踪 - 子图删除 """ from typing import Dict, List, Set, Optional from collections import deque from .features import FeatureNode, FeatureState from .errors import StateCorruptionError, KernelBugError class FeatureGraph: """ Featur...
vanyu0710/mechcad-kernel
mech_kernel/feature_graph.py
.py
698d48a129004efe
7
0
""" MechKernel Geometry Inspector(M1.1 修复版) P0-2 修复:manifold/watertight/connected 用三态 (valid/invalid/unknown) 避免欧拉公式误判(圆环 g=1 欧拉=0,不能用 V-E+F==2 判断) 其他修复: - bbox 解析容错(NaN/Inf → 兜底) - 异常隔离,绝不让 kernel 崩 """ from typing import Any, Optional, Tuple, Literal import math from .step_result import GeometrySummary # 拓扑检查结果:...
vanyu0710/mechcad-kernel
mech_kernel/geometry_inspector.py
.py
3738f6a2cfcbcf31
7.5
0
""" MechKernel LLM 客户端(DeepSeek OpenAI 兼容) 专家 v8 审查后接真实 LLM(替换 MockPlanner / MockVision)。 DeepSeek 视觉模型:deepseek-v4-flash-vision-exp DeepSeek 推理模型:deepseek-reasoner DeepSeek 通用模型:deepseek-chat 环境变量:DSKEY(DeepSeek 官方 API key) """ from __future__ import annotations import os import json import logging import base64 imp...
vanyu0710/mechcad-kernel
mech_kernel/llm/deepseek.py
.py
375f96dbc896713f
7
0
""" MechKernel Persistent Naming(v1.1 修复版) P1-4 修复: - 改用 semantic_name -> role -> candidates[] 结构 - 查询必须显式 role - 多候选返回歧义结果(不静默选最新) 专家审查原话: "如果查询只按 semantic_name,body 和 top_face 会产生歧义, 最新时间戳可能导致非确定性覆盖。建议改成 semantic_name -> role -> candidates[], 查询必须显式要求 role;多候选时返回 ambiguity,而不是静默选最新。" """ from typing import Dict, Li...
vanyu0710/mechcad-kernel
mech_kernel/persistent_naming.py
.py
35edcd1fe7a81ce4
7
0
""" MechKernel Renderer(M1.1 修复版) 第 4 轮专家审查修复: - P0-1 缓存键:用 (id, geometry_revision, level, config) 替代裸 id - P0-4 异常隔离:坏几何/NaN/空/缺顶点不崩 - LRU 限制(默认 32 个) - 任何异常都隔离,**绝不**让 kernel 崩溃 """ from typing import Any, Optional, Dict, List, Tuple from collections import OrderedDict import io import math try: import matplotl...
vanyu0710/mechcad-kernel
mech_kernel/renderer.py
.py
ce75fce12dbd3555
7
0
""" MechKernel StepResult 数据结构 C 方案:自适应渲染 - 默认不渲染,拓扑变化 / 关键决策点才渲染 """ from dataclasses import dataclass, field from typing import List, Optional, Dict, Any, Literal import time import base64 RenderLevel = Literal["none", "iso_only", "full"] ErrorKind = Literal["INVALID_REQUEST", "GEOMETRY_FAILURE", "RECOVERABLE", "KE...
vanyu0710/mechcad-kernel
mech_kernel/step_result.py
.py
079ef5bd62b2a3ee
7
0
""" 测试 5 类类型化错误 """ import pytest from mech_kernel.errors import ( MechKernelError, InvalidRequestError, KernelBugError, StateCorruptionError, make_geometry_failure, make_recoverable, GeometryFailureReason ) def test_invalid_request_error_inherits_base(): """InvalidRequestError 继承 MechKernelError""" e...
vanyu0710/mechcad-kernel
mech_kernel/tests/test_errors.py
.py
e4d8fe11edfe8ce7
7.5
0
""" 测试 M1:GeometryInspector + Renderer + AdaptiveRenderer """ import pytest from mech_kernel.geometry_inspector import GeometryInspector from mech_kernel.renderer import Renderer from mech_kernel.adaptive_renderer import AdaptiveRenderer from mech_kernel import MechKernel from mech_kernel.step_result import GeometrySum...
vanyu0710/mechcad-kernel
mech_kernel/tests/test_m1.py
.py
b9338263d6b92f9d
7.5
0
""" 测试 M2: AI Orchestrator(v1 单 Agent) - Mock Planner 解析用户指令生成 plan - run_loop 跑通 Plan→Execute→Inspect→Decide 循环 - E2E:建圆柱/立方体/法兰盘 """ import pytest from mech_kernel import MechKernel from mech_kernel.ai_orchestrator import ( MockPlanner, MockVision, run_loop, PlannerAction ) def test_planner_action_to_dict(): ...
vanyu0710/mechcad-kernel
mech_kernel/tests/test_m2_orchestrator.py
.py
c16dbf4d2768e98c
7.5
0
""" 测试 P0 修复: 1. NOT_IMPLEMENTED 错误类型 2. 事务 / undo 栈不被污染 3. 失败渲染策略(按 error_kind) 4. Reference 的 frozen=True """ import pytest from mech_kernel import ( MechKernel, InvalidRequestError, KernelBugError, StateCorruptionError ) from mech_kernel.errors import make_not_implemented, get_render_level_for_error from mech_ke...
vanyu0710/mechcad-kernel
mech_kernel/tests/test_p0_fixes.py
.py
8dce0685a164144d
7.5
0
""" 测试 savepoint 模型(P0 事务修复 #2) - 默认嵌套:内层 join 外层(只有一个 undo entry) - savepoint 模式:内层独立入 undo - __exit__ finally:rollback 异常不影响 _txn_depth 递减 """ import pytest from mech_kernel import MechKernel, InvalidRequestError, DeprecatedInternalAPIError from mech_kernel.transaction import Transaction def test_default_nested_jo...
vanyu0710/mechcad-kernel
mech_kernel/tests/test_savepoint.py
.py
5e0f7927240e5940
7.5
0
""" MechKernel 事务管理(v1.1 修复版 #2) P3 原则:任何操作都在事务中,失败整体回滚。 P0 修复(专家第 3 轮): - `__exit__` 必须有 `finally` 保护 _txn_depth(rollback 抛异常时不递减) - 删除 _push_undo 尸体 API(不再静默 pass) - savepoint 明确语义: - 默认嵌套:内层 join 外层(只在外层 commit 时入 undo) - savepoint 显式 API:`Transaction.savepoint()` 标记内层独立点 P1 优化: - 只在 commit 时才深拷贝完整状态(之前每次都拍两次...
vanyu0710/mechcad-kernel
mech_kernel/transaction.py
.py
f6b31ff0ca95cf2c
7
0
""" MechKernel 单位管理 P7 原则:内部全部毫米,API 不暴露 inch。 所有输入参数默认 mm,返回值默认 mm。 """ from typing import Union Number = Union[int, float] # 内部单位 INTERNAL_UNIT = "mm" # 单位转换表(输入侧只支持 mm 和 inch) _TO_MM = { "mm": 1.0, "cm": 10.0, "m": 1000.0, "in": 25.4, "inch": 25.4, "ft": 304.8, } def to_mm(value: Number...
vanyu0710/mechcad-kernel
mech_kernel/units.py
.py
1cd58141a059807e
7
0
""" MechKernel 输入校验器(v1.1 修复版) P1-6 修复:统一行为 - 校验函数:返回规范化值 - 失败时:抛 InvalidRequestError - 不再做"返回清洗值 vs 抛异常"的混合行为 专家审查原话: "有的函数抛异常,有的返回清洗后的值,调用方很容易漏处理。 统一为'纯校验返回规范化值,失败统一抛 InvalidRequestError',不要混合隐式修正。" """ from typing import Any, List, Tuple, Optional from .errors import InvalidRequestError from .units import is_posit...
vanyu0710/mechcad-kernel
mech_kernel/validators.py
.py
a0ead4027bd00fd6
7
0
"""Canonical fingerprinting for MiniMax H3 cached-CLIP requests. Turns (prompt, the kwargs SpyClipProxy.tokenize() captured, clip identity, cache schema version) into one deterministic sha256 hex digest, used as the cache key. Pure function of the data already captured by the proxy -- no ComfyUI imports, no GPU, no di...
Mu5hr00moO/ComfyUI-MiniMaxH3-CLIPCached
minimaxh3_clipcache/fingerprint.py
.py
8bc13c325131bc27
7
0
"""Thin wrappers around ComfyUI's own CLIP-loading path (folder_paths, comfy.sd.load_clip), used only for what CachedClipProxy needs: identifying the encoder file on disk for the cache fingerprint, and lazily constructing the real clip object on a cache MISS. Neither function reimplements ComfyUI's loading logic -- bot...
Mu5hr00moO/ComfyUI-MiniMaxH3-CLIPCached
minimaxh3_clipcache/loader.py
.py
2f7a284f8c7ba618
7
0
"""CachedClipProxy: transparent clip.tokenize()/encode_from_tokens_scheduled() replacement that fingerprints the request and serves/saves conditioning from disk instead of always re-running the real Qwen3-VL encoder. tokenize() is lazy (phase 4 of the project plan): it does not touch real_clip at all, it just remember...
Mu5hr00moO/ComfyUI-MiniMaxH3-CLIPCached
minimaxh3_clipcache/proxy.py
.py
dcc1080924f6320f
7
0