Stevesolun commited on
Commit
4eef289
·
verified ·
1 Parent(s): 65ccbd8

Sync ctx 711582e (part 2)

Browse files

GitHub commit: 711582e373fea0c43204213279f9ebd5c8937f26

pyproject.toml CHANGED
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
 
5
  [project]
6
  name = "claude-ctx"
7
- version = "1.0.20"
8
  description = "Not an Amazon-style catalog: a recommendation layer for loading the right skills, agents, MCPs, and harnesses at the right development moment"
9
  authors = [{ name = "Steve Solun" }]
10
  license = "MIT"
 
4
 
5
  [project]
6
  name = "claude-ctx"
7
+ version = "1.0.21"
8
  description = "Not an Amazon-style catalog: a recommendation layer for loading the right skills, agents, MCPs, and harnesses at the right development moment"
9
  authors = [{ name = "Steve Solun" }]
10
  license = "MIT"
qa/bug_smoke_status.csv CHANGED
@@ -25,3 +25,13 @@ AUDIT-023,CLI UX,MCP ingest,--status creates wiki path,src/mcp_ingest.py; src/te
25
  AUDIT-024,Security,Dashboard docs,entity-encoded active URL attributes,src/ctx/dashboard_docs.py; src/tests/test_security_hardening.py,Dashboard audit found entity-encoded active schemes survived docs sanitization in URL-bearing attributes.,High,Docs HTML sanitization should neutralize active URL schemes after entity decoding and control-character stripping.,parallel dashboard audit + focused pytest,Retested Pass,Entity-encoded javascript and data HTML schemes survived in href src xlink:href or formaction before fix.,Docs sanitization missed encoded active URL schemes in URL-bearing attributes.,Render sanitized docs HTML with entity-encoded active schemes in href src xlink:href and formaction before the fix.,Decode and normalize URL-bearing attribute values before active-scheme checks and cover the four attributes.,Fixed,.venv/bin/python -m pytest src/tests/test_security_hardening.py -q --tb=short,PASS: security hardening suite reported 41 passed with encoded active URL regressions.,2026-07-05,Codex,Reviewed by worker tests + local static audit,Ponytail: sanitize URL-bearing attributes only; preserve safe tabbed-input behavior.,Closed; continue repo-wide discovery.
26
  AUDIT-025,API Correctness,Monitor readonly API,HTML 404 for missing skill sidecar,src/ctx/monitor/api/readonly.py; src/tests/test_ctx_monitor.py,Dashboard audit found /api/skill/<slug>.json returned an HTML 404 body when the sidecar was missing.,Medium,JSON API routes should return JSON error payloads for missing resources.,parallel dashboard audit + focused pytest,Retested Pass,Missing skill sidecar API response had text/html content before fix.,Readonly skill API returned HTML for a JSON endpoint failure.,GET /api/skill/missing-sidecar.json before the fix and inspect status content type and body.,Return a JSON detail payload with 404 status for missing sidecars and add monitor regression coverage.,Fixed,.venv/bin/python -m pytest src/tests/test_ctx_monitor.py::test_skill_sidecar_api_missing_sidecar_returns_json_404 src/tests/test_ctx_monitor.py::test_skill_sidecar_api_reads_typed_sidecar -q,PASS: focused monitor API sidecar tests reported 2 passed.,2026-07-05,Codex,Reviewed by worker tests + local static audit,Ponytail: route-local JSON error only; no dispatcher refactor.,Closed; continue repo-wide discovery.
27
  AUDIT-026,Privacy,Core wiki tool,absolute wiki path in model-facing output,src/ctx/adapters/generic/ctx_core_tools.py; src/tests/test_harness_ctx_core.py,Runtime audit found ctx__wiki_get returned absolute wiki filesystem paths in success and missing-page outputs.,High,Model-facing wiki fetch results should expose wiki-relative paths or candidate labels without host absolute paths.,parallel runtime audit + focused pytest,Retested Pass,ctx__wiki_get success path and looked_in candidates included host absolute wiki paths before fix.,Wiki fetch tool leaked local filesystem layout into persisted tool results.,Call ctx__wiki_get for an existing page or missing slug under a temp wiki before the fix and inspect JSON output.,Return wiki-relative entity paths for success and missing candidates and assert temp absolute paths are absent.,Fixed,.venv/bin/python -m pytest src/tests/test_harness_ctx_core.py::TestWikiGet -q,PASS: TestWikiGet reported 6 passed with absolute-path privacy regressions.,2026-07-05,Codex,Reviewed by worker tests + local static audit,Ponytail: replace host paths with existing wiki-relative entity paths only.,Closed; continue repo-wide discovery.
 
 
 
 
 
 
 
 
 
 
 
25
  AUDIT-024,Security,Dashboard docs,entity-encoded active URL attributes,src/ctx/dashboard_docs.py; src/tests/test_security_hardening.py,Dashboard audit found entity-encoded active schemes survived docs sanitization in URL-bearing attributes.,High,Docs HTML sanitization should neutralize active URL schemes after entity decoding and control-character stripping.,parallel dashboard audit + focused pytest,Retested Pass,Entity-encoded javascript and data HTML schemes survived in href src xlink:href or formaction before fix.,Docs sanitization missed encoded active URL schemes in URL-bearing attributes.,Render sanitized docs HTML with entity-encoded active schemes in href src xlink:href and formaction before the fix.,Decode and normalize URL-bearing attribute values before active-scheme checks and cover the four attributes.,Fixed,.venv/bin/python -m pytest src/tests/test_security_hardening.py -q --tb=short,PASS: security hardening suite reported 41 passed with encoded active URL regressions.,2026-07-05,Codex,Reviewed by worker tests + local static audit,Ponytail: sanitize URL-bearing attributes only; preserve safe tabbed-input behavior.,Closed; continue repo-wide discovery.
26
  AUDIT-025,API Correctness,Monitor readonly API,HTML 404 for missing skill sidecar,src/ctx/monitor/api/readonly.py; src/tests/test_ctx_monitor.py,Dashboard audit found /api/skill/<slug>.json returned an HTML 404 body when the sidecar was missing.,Medium,JSON API routes should return JSON error payloads for missing resources.,parallel dashboard audit + focused pytest,Retested Pass,Missing skill sidecar API response had text/html content before fix.,Readonly skill API returned HTML for a JSON endpoint failure.,GET /api/skill/missing-sidecar.json before the fix and inspect status content type and body.,Return a JSON detail payload with 404 status for missing sidecars and add monitor regression coverage.,Fixed,.venv/bin/python -m pytest src/tests/test_ctx_monitor.py::test_skill_sidecar_api_missing_sidecar_returns_json_404 src/tests/test_ctx_monitor.py::test_skill_sidecar_api_reads_typed_sidecar -q,PASS: focused monitor API sidecar tests reported 2 passed.,2026-07-05,Codex,Reviewed by worker tests + local static audit,Ponytail: route-local JSON error only; no dispatcher refactor.,Closed; continue repo-wide discovery.
27
  AUDIT-026,Privacy,Core wiki tool,absolute wiki path in model-facing output,src/ctx/adapters/generic/ctx_core_tools.py; src/tests/test_harness_ctx_core.py,Runtime audit found ctx__wiki_get returned absolute wiki filesystem paths in success and missing-page outputs.,High,Model-facing wiki fetch results should expose wiki-relative paths or candidate labels without host absolute paths.,parallel runtime audit + focused pytest,Retested Pass,ctx__wiki_get success path and looked_in candidates included host absolute wiki paths before fix.,Wiki fetch tool leaked local filesystem layout into persisted tool results.,Call ctx__wiki_get for an existing page or missing slug under a temp wiki before the fix and inspect JSON output.,Return wiki-relative entity paths for success and missing candidates and assert temp absolute paths are absent.,Fixed,.venv/bin/python -m pytest src/tests/test_harness_ctx_core.py::TestWikiGet -q,PASS: TestWikiGet reported 6 passed with absolute-path privacy regressions.,2026-07-05,Codex,Reviewed by worker tests + local static audit,Ponytail: replace host paths with existing wiki-relative entity paths only.,Closed; continue repo-wide discovery.
28
+ AUDIT-027,CLI Reliability,MCP add,JSONL batch preload,src/mcp_add.py; src/tests/test_mcp_add.py,Local static probe found ctx-mcp-add --from-jsonl read the whole JSONL file and stored all records before processing.,Medium,ctx-mcp-add --from-jsonl and --from-stdin should process records as a stream instead of preloading large catalogs.,manual static scan + focused pytest,Retested Pass,JSONL input used read_text().splitlines() and raw_records collected all records before batch processing.,Large MCP add catalogs could use unnecessary memory and delay first-record processing.,Monkeypatch Path.read_text to fail and run ctx-mcp-add --from-jsonl before the fix.,Stream JSONL/stdin records through the existing batch processor and use unknown-total progress for streaming inputs.,Fixed,.venv/bin/python -m pytest src/tests/test_mcp_add.py::TestAddMcpCliInput -q --tb=short,PASS: MCP add CLI input tests reported 4 passed including JSONL streaming regression.,2026-07-06,Codex,Reviewed by local tests + static audit,Ponytail: preserve existing add semantics; only replace input buffering with streaming iteration.,Closed; continue repo-wide discovery.
29
+ AUDIT-028,CLI UX,MCP install,installed dry-run manifest reconciliation,src/ctx/adapters/claude_code/install/mcp_install.py; src/tests/test_mcp_install.py,Hegel runtime audit found dry-run already-installed branch called record_install before dry-run guard.,Medium,ctx-mcp-install dry-run should not mutate manifest state.,parallel runtime audit + focused pytest,Retested Pass,Already-installed dry-run recorded a manifest load entry before fix.,Dry-run install changed local manifest for an already installed MCP.,Call install_mcp on installed entity with dry_run=True and inspect manifest load before fix.,Skip manifest reconciliation when dry_run is true while preserving normal already-installed reconciliation.,Fixed,.venv/bin/python -m pytest src/tests/test_mcp_install.py -q --tb=short,PASS: test_mcp_install.py reported 113 passed and integrated bundle reported 500 passed.,2026-07-06,Codex,Reviewed by local tests + static audit,Ponytail: guard only dry-run reconciliation path; non-dry-run manifest repair remains.,Closed; continue repo-wide discovery.
30
+ AUDIT-029,Privacy,Monitor API,entity detail absolute path,src/ctx/monitor/services/wiki.py; src/tests/test_ctx_monitor.py,Turing monitor audit found /api/entity/<slug>.json returned absolute wiki filesystem paths.,Medium,Monitor entity detail JSON should expose wiki-relative paths and no host root.,parallel monitor audit + focused pytest,Retested Pass,Entity detail payload path contained the temp wiki absolute path before fix.,Monitor API leaked local wiki filesystem layout to JSON clients.,GET /api/entity/python-patterns.json under a temp wiki and inspect detail path before fix.,Return wiki_relative_path for entity_detail and assert the host path is absent.,Fixed,.venv/bin/python -m pytest src/tests/test_ctx_monitor.py::test_entity_search_and_detail_apis_support_edit_flow -q --tb=short,PASS: focused monitor API test passed and integrated bundle reported 500 passed.,2026-07-06,Codex,Reviewed by local tests + static audit,Ponytail: change only the API path field to the existing wiki-relative helper.,Closed; continue repo-wide discovery.
31
+ AUDIT-030,CI Gate,Hugging Face sync,card-only classifier stale tracked files,.github/workflows/huggingface-sync.yml; src/tests/test_huggingface_sync.py,Lagrange CI audit found src/tests and .github changes routed to --card-only uploads.,High,Hugging Face sync should only use card-only mode for docs or explicit card files and should fully sync source test and workflow changes.,parallel CI audit + focused pytest,Retested Pass,src/tests and .github workflow edits selected card-only mode before fix.,HF dataset sync could leave tracked repository files stale while updating only README metadata.,Classify changed files under src/tests and .github before fix and inspect SYNC_MODE.,Limit card_only_prefixes to docs plus explicit card files and add workflow regression assertions.,Fixed,.venv/bin/python -m pytest src/tests/test_huggingface_sync.py src/tests/test_ci_classifier.py -q --tb=short,PASS: Hugging Face and CI classifier suites reported 80 passed and integrated bundle reported 500 passed.,2026-07-06,Codex,Reviewed by worker + local validation,Ponytail: tighten classifier tuple only; existing README and docs card-only behavior remains.,Closed; continue repo-wide discovery.
32
+ AUDIT-031,CI Gate,No-test policy,maintainer script contract coverage,scripts/ci_no_test_policy.py; src/tests/test_ci_classifier.py,Lagrange CI audit found release sync and artifact maintainer scripts were not contract files for no-test policy.,High,Changes to release sync or artifact maintainer scripts should require matching tests.,parallel CI audit + focused pytest,Retested Pass,scripts/sync_huggingface.py and graph artifact scripts passed no-test policy without tests before fix.,Release and artifact script changes could bypass test-change requirements.,Evaluate no-test policy with scripts/sync_huggingface.py and graph artifact scripts before fix.,Add named maintainer scripts to contract file set and cover them in classifier tests.,Fixed,.venv/bin/python -m pytest src/tests/test_huggingface_sync.py src/tests/test_ci_classifier.py -q --tb=short,PASS: Hugging Face and CI classifier suites reported 80 passed and integrated bundle reported 500 passed.,2026-07-06,Codex,Reviewed by worker + local validation,Ponytail: explicit allowlist extension only; normal release metadata exemptions unchanged.,Closed; continue repo-wide discovery.
33
+ AUDIT-032,Privacy,Graph artifacts,host paths in public wiki archives,graph/wiki-graph.tar.gz; graph/wiki-graph-runtime.tar.gz; scripts/pack_full_wiki_tar.py; src/validate_graph_artifacts.py,Turing graph audit found shipped wiki archives contained C:\\Users and /Users host paths in log and packed markdown pages.,High,Public graph and runtime wiki archives should omit generated local catalogs and redact host-user paths from markdown payloads.,parallel graph audit + artifact validator,Retested Pass,Top-level log and catalog pages plus packed converted references contained host paths before fix.,Published graph artifacts leaked local filesystem paths.,Scan wiki graph tarballs and wiki-pack pages for C:\\Users C:/Users or /Users before fix.,Omit generated local markdown catalogs redact host-user paths during repack and enforce strict archive markdown validation.,Fixed,.venv/bin/python src/validate_graph_artifacts.py --graph-dir graph,PASS: graph artifact validator passed and direct wiki-pack scans found no C:\\Users C:/Users or /Users signatures.,2026-07-06,Codex,Reviewed by worker + local artifact validation,Ponytail: sanitize public archive payloads at pack time and keep validator strict.,Closed; continue repo-wide discovery.
34
+ AUDIT-033,CLI Safety,Backup prune,legacy keep dry-run deletion,src/backup_mirror.py; src/tests/test_backup_mirror.py,Hegel runtime audit found prune --keep N --dry-run deleted snapshots in the legacy branch.,High,backup prune --keep N --dry-run should report planned removals without deleting snapshots.,parallel runtime audit + focused pytest,Retested Pass,Legacy keep dry-run called prune_snapshots and removed old snapshot directories before fix.,Dry-run backup pruning could delete snapshots.,Run backup_mirror prune --keep 1 --dry-run on three temp snapshots and inspect remaining snapshots before fix.,Thread dry_run through legacy prune_snapshots and print would-remove messages.,Fixed,.venv/bin/python -m pytest src/tests/test_backup_config.py src/tests/test_backup_mirror.py src/tests/test_harness_cli_run.py -q --tb=short,PASS: runtime safety focused suite reported 154 passed and integrated bundle reported 500 passed.,2026-07-06,Codex,Reviewed by worker + local validation,Ponytail: preserve keep-prune semantics and only bypass deletion in dry-run.,Closed; continue repo-wide discovery.
35
+ AUDIT-034,Security,Backup config,unsafe top_files entries,src/backup_config.py; src/tests/test_backup_config.py,Hegel runtime audit found top_files accepted traversal absolute drive and UNC paths.,High,backup top_files should be top-level filenames only and should never escape the configured home root.,parallel runtime audit + focused pytest,Retested Pass,top_files accepted ../../.ssh/id_rsa and absolute paths before fix.,Backup mirror configuration could include files outside the intended top-level home scope.,Load backup config with traversal absolute drive and UNC top_files values before fix.,Validate top_files as non-empty top-level filenames before ALWAYS_EXCLUDE filtering.,Fixed,.venv/bin/python -m pytest src/tests/test_backup_config.py src/tests/test_backup_mirror.py src/tests/test_harness_cli_run.py -q --tb=short,PASS: runtime safety focused suite reported 154 passed and integrated bundle reported 500 passed.,2026-07-06,Codex,Reviewed by worker + local validation,Ponytail: validate configured filenames only; existing exclude filtering remains.,Closed; continue repo-wide discovery.
36
+ AUDIT-035,Security,ctx run MCP inline specs,inline secret argv persistence,src/ctx/cli/run.py; src/tests/test_harness_cli_run.py,Hegel runtime audit found --mcp specs accepted token-looking argv that could be persisted in session metadata.,High,ctx run --mcp inline commands should reject secret-looking argv and direct users to --mcp-env.,parallel runtime audit + focused pytest,Retested Pass,Inline MCP command args accepted --token and ghp_ values before fix.,MCP secrets could be embedded in command args and session metadata.,Parse an --mcp spec containing --token or ghp_ before fix and inspect parsed args.,Use existing secret scanner in _parse_mcp_spec and fail with --mcp-env guidance.,Fixed,.venv/bin/python -m pytest src/tests/test_backup_config.py src/tests/test_backup_mirror.py src/tests/test_harness_cli_run.py -q --tb=short,PASS: runtime safety focused suite reported 154 passed and integrated bundle reported 500 passed.,2026-07-06,Codex,Reviewed by worker + local validation,Ponytail: block inline secret-looking args only; --mcp-env remains the supported credential path.,Closed; continue repo-wide discovery.
37
+ AUDIT-036,Security,Wiki queue artifact promotion,arbitrary target_path overwrite,src/ctx/core/wiki/wiki_queue_worker.py; src/tests/test_wiki_queue_worker.py,Turing graph audit found queued artifact promotion trusted payload target_path and could replace arbitrary files.,High,Queued artifact promotion should only promote known graph and wiki artifact targets from sibling staged files.,parallel graph audit + focused pytest,Retested Pass,ARTIFACT_PROMOTION_JOB payload could promote /tmp/staged to /tmp/outside before fix.,Queue worker could overwrite files outside allowed graph artifact locations.,Enqueue artifact promotion with outside target_path and inspect overwritten outside file before fix.,Resolve paths validate exact allowed target names and require staged_path to equal target sibling .staged before promotion.,Fixed,.venv/bin/python -m pytest src/tests/test_wiki_queue_worker.py src/tests/test_wiki_queue.py src/tests/test_wiki_queue_producers.py src/tests/test_artifact_promotion.py -q --tb=short,PASS: wiki queue and artifact promotion suites reported 50 passed and integrated bundle reported 500 passed.,2026-07-06,Codex,Reviewed by worker + local validation,Ponytail: restrict promotion boundary only; known graph and wiki artifact promotions still work.,Closed; continue repo-wide discovery.
qa/feature_status.csv CHANGED
The diff for this file is too large to render. See raw diff
 
scripts/ci_no_test_policy.py CHANGED
@@ -20,6 +20,15 @@ RELEASE_GENERATED_STATS_FILES = {
20
  "docs/index.md",
21
  "docs/knowledge-graph.md",
22
  }
 
 
 
 
 
 
 
 
 
23
  VERSION_LINE_RE = re.compile(r'version = "\d+\.\d+\.\d+(?:[-+._a-zA-Z0-9]*)?"')
24
  INIT_VERSION_LINE_RE = re.compile(r'__version__ = "\d+\.\d+\.\d+(?:[-+._a-zA-Z0-9]*)?"')
25
  TEST_COUNT_STATS_RE = re.compile(
@@ -55,7 +64,8 @@ def is_contract_file(path: str) -> bool:
55
  return (
56
  (path.startswith("src/") and path.endswith((".py", ".json")))
57
  or path.startswith("scripts/ci_")
58
- or path == "scripts/clean_host_contract.py"
 
59
  or path == "pyproject.toml"
60
  or (path.startswith(".github/workflows/") and path.endswith((".yml", ".yaml")))
61
  ) and not path.startswith("src/tests/")
 
20
  "docs/index.md",
21
  "docs/knowledge-graph.md",
22
  }
23
+ MAINTAINER_SCRIPT_CONTRACT_FILES = {
24
+ "scripts/clean_host_contract.py",
25
+ "scripts/graph_artifact_guard.py",
26
+ "scripts/pack_full_wiki_tar.py",
27
+ "scripts/sync_huggingface.py",
28
+ }
29
+ GATE_CONFIG_CONTRACT_FILES = {
30
+ ".no-mistakes.yaml",
31
+ }
32
  VERSION_LINE_RE = re.compile(r'version = "\d+\.\d+\.\d+(?:[-+._a-zA-Z0-9]*)?"')
33
  INIT_VERSION_LINE_RE = re.compile(r'__version__ = "\d+\.\d+\.\d+(?:[-+._a-zA-Z0-9]*)?"')
34
  TEST_COUNT_STATS_RE = re.compile(
 
64
  return (
65
  (path.startswith("src/") and path.endswith((".py", ".json")))
66
  or path.startswith("scripts/ci_")
67
+ or path in MAINTAINER_SCRIPT_CONTRACT_FILES
68
+ or path in GATE_CONFIG_CONTRACT_FILES
69
  or path == "pyproject.toml"
70
  or (path.startswith(".github/workflows/") and path.endswith((".yml", ".yaml")))
71
  ) and not path.startswith("src/tests/")
scripts/ci_preflight.py CHANGED
@@ -9,6 +9,7 @@ from __future__ import annotations
9
 
10
  import argparse
11
  from dataclasses import dataclass
 
12
  import os
13
  from pathlib import Path
14
  import shutil
@@ -71,6 +72,26 @@ GRAPH_VALIDATE_ARGS = (
71
  "--max-stage-lines",
72
  "40",
73
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
 
76
  @dataclass(frozen=True)
@@ -80,6 +101,13 @@ class Check:
80
  env: dict[str, str] | None = None
81
 
82
 
 
 
 
 
 
 
 
83
  def _run_git(args: list[str], *, allow_failure: bool = False) -> list[str]:
84
  proc = subprocess.run(
85
  ["git", *args],
@@ -137,6 +165,122 @@ def _diffs_for_files(base_ref: str, files: list[str]) -> dict[str, str]:
137
  return diffs
138
 
139
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  def select_checks(
141
  *,
142
  base_ref: str,
@@ -146,7 +290,7 @@ def select_checks(
146
  ) -> tuple[list[Check], list[str]]:
147
  flags = classify_paths(files)
148
  checks: list[Check] = [
149
- Check("whitespace", ("git", "diff", "--check")),
150
  Check("repo stats", (python, "src/update_repo_stats.py", "--check")),
151
  ]
152
  notes = [
@@ -256,6 +400,9 @@ def select_checks(
256
  )
257
 
258
  if flags["graph_artifact_changed"]:
 
 
 
259
  checks.append(Check("graph artifact validation", (python, *GRAPH_VALIDATE_ARGS)))
260
 
261
  if source_required and flags["similarity_changed"]:
@@ -396,11 +543,26 @@ def main(argv: list[str] | None = None) -> int:
396
  action="store_true",
397
  help=argparse.SUPPRESS,
398
  )
 
 
 
 
 
 
 
 
 
 
399
  args = parser.parse_args(argv)
400
 
401
  if not shutil.which("git"):
402
  raise SystemExit("git is required for ci_preflight")
403
 
 
 
 
 
 
404
  files = changed_files(args.base)
405
  if args.internal_no_test_policy:
406
  return _run_no_test_policy_for_files(files, base_ref=args.base)
 
9
 
10
  import argparse
11
  from dataclasses import dataclass
12
+ import hashlib
13
  import os
14
  from pathlib import Path
15
  import shutil
 
72
  "--max-stage-lines",
73
  "40",
74
  )
75
+ GRAPH_LFS_ARTIFACTS = (
76
+ "graph/wiki-graph.tar.gz",
77
+ "graph/wiki-graph-runtime.tar.gz",
78
+ )
79
+ GRAPH_LFS_MAX_FALLBACK_SIZES = {
80
+ "graph/wiki-graph.tar.gz": 350_000_000,
81
+ "graph/wiki-graph-runtime.tar.gz": 150_000_000,
82
+ }
83
+ LFS_POINTER_PREFIX = "version https://git-lfs.github.com/spec/v1"
84
+ LFS_POINTER_MAX_BYTES = 4096
85
+ GIT_LFS_FILTER_CONFIG = (
86
+ "-c",
87
+ "filter.lfs.process=git-lfs filter-process",
88
+ "-c",
89
+ "filter.lfs.smudge=git-lfs smudge -- %f",
90
+ "-c",
91
+ "filter.lfs.clean=git-lfs clean -- %f",
92
+ "-c",
93
+ "filter.lfs.required=true",
94
+ )
95
 
96
 
97
  @dataclass(frozen=True)
 
101
  env: dict[str, str] | None = None
102
 
103
 
104
+ @dataclass(frozen=True)
105
+ class LfsPointer:
106
+ path: str
107
+ sha256: str
108
+ size: int
109
+
110
+
111
  def _run_git(args: list[str], *, allow_failure: bool = False) -> list[str]:
112
  proc = subprocess.run(
113
  ["git", *args],
 
165
  return diffs
166
 
167
 
168
+ def _read_lfs_pointer(path: Path) -> LfsPointer | None:
169
+ if not path.exists():
170
+ return None
171
+ prefix_bytes = LFS_POINTER_PREFIX.encode("utf-8")
172
+ with path.open("rb") as fh:
173
+ prefix = fh.read(len(prefix_bytes))
174
+ if prefix != prefix_bytes:
175
+ return None
176
+ pointer_bytes = prefix + fh.read(LFS_POINTER_MAX_BYTES - len(prefix_bytes))
177
+ expected_oid = ""
178
+ expected_size = 0
179
+ pointer = pointer_bytes.decode("utf-8", errors="replace")
180
+ for line in pointer.splitlines():
181
+ if line.startswith("oid sha256:"):
182
+ expected_oid = line.split(":", 1)[1].strip()
183
+ elif line.startswith("size "):
184
+ expected_size = int(line.split(" ", 1)[1].strip())
185
+ if expected_oid and expected_size:
186
+ return LfsPointer(path.relative_to(REPO_ROOT).as_posix(), expected_oid, expected_size)
187
+ raise RuntimeError(f"{path.relative_to(REPO_ROOT)} has incomplete Git LFS pointer metadata")
188
+
189
+
190
+ def _file_sha256_and_size(path: Path) -> tuple[str, int]:
191
+ sha = hashlib.sha256()
192
+ total = 0
193
+ with path.open("rb") as fh:
194
+ while True:
195
+ chunk = fh.read(1024 * 1024)
196
+ if not chunk:
197
+ break
198
+ sha.update(chunk)
199
+ total += len(chunk)
200
+ return sha.hexdigest(), total
201
+
202
+
203
+ def _verify_hydrated_lfs_pointer(pointer: LfsPointer) -> None:
204
+ path = REPO_ROOT / pointer.path
205
+ if _read_lfs_pointer(path) is not None:
206
+ raise RuntimeError(f"{pointer.path} is still a Git LFS pointer after hydration")
207
+ actual_sha256, actual_size = _file_sha256_and_size(path)
208
+ if actual_sha256 != pointer.sha256 or actual_size != pointer.size:
209
+ raise RuntimeError(
210
+ f"{pointer.path} does not match its Git LFS pointer: "
211
+ f"sha256:{actual_sha256} size:{actual_size}"
212
+ )
213
+
214
+
215
+ def hydrate_graph_lfs_artifacts() -> int:
216
+ pointers = [
217
+ pointer
218
+ for relpath in GRAPH_LFS_ARTIFACTS
219
+ if (pointer := _read_lfs_pointer(REPO_ROOT / relpath)) is not None
220
+ ]
221
+ if not pointers:
222
+ print("Graph LFS artifacts are already hydrated.")
223
+ return 0
224
+
225
+ if not shutil.which("git"):
226
+ print("git is required to hydrate graph LFS artifacts", file=sys.stderr)
227
+ return 127
228
+
229
+ env = os.environ.copy()
230
+ env.setdefault("GIT_LFS_SKIP_SMUDGE", "1")
231
+ env.setdefault("GIT_LFS_ACTIVITYTIMEOUT", "600")
232
+ env.setdefault("GIT_LFS_DIALTIMEOUT", "120")
233
+ env.setdefault("GIT_LFS_TLSTIMEOUT", "120")
234
+ for pointer in pointers:
235
+ max_size = GRAPH_LFS_MAX_FALLBACK_SIZES[pointer.path]
236
+ if pointer.size > max_size:
237
+ print(
238
+ f"Refusing Git LFS fallback for {pointer.path}: "
239
+ f"pointer size {pointer.size} exceeds cap {max_size}",
240
+ file=sys.stderr,
241
+ )
242
+ return 1
243
+ print(f"Hydrating {pointer.path} from Git LFS sha256:{pointer.sha256} size:{pointer.size}")
244
+ proc = subprocess.run(
245
+ [
246
+ "git",
247
+ *GIT_LFS_FILTER_CONFIG,
248
+ "lfs",
249
+ "pull",
250
+ "--include",
251
+ pointer.path,
252
+ "--exclude",
253
+ "",
254
+ ],
255
+ cwd=REPO_ROOT,
256
+ check=False,
257
+ env=env,
258
+ )
259
+ if proc.returncode != 0:
260
+ print(f"git lfs pull failed for {pointer.path}", file=sys.stderr)
261
+ return proc.returncode
262
+ try:
263
+ _verify_hydrated_lfs_pointer(pointer)
264
+ except RuntimeError as exc:
265
+ print(str(exc), file=sys.stderr)
266
+ return 1
267
+ return 0
268
+
269
+
270
+ def _run_whitespace_check(base_ref: str) -> int:
271
+ base = _diff_base(base_ref)
272
+ commands = (
273
+ ["diff", "--check", base, "HEAD"],
274
+ ["diff", "--cached", "--check"],
275
+ ["diff", "--check"],
276
+ )
277
+ for args in commands:
278
+ proc = subprocess.run(["git", *args], check=False)
279
+ if proc.returncode != 0:
280
+ return proc.returncode
281
+ return 0
282
+
283
+
284
  def select_checks(
285
  *,
286
  base_ref: str,
 
290
  ) -> tuple[list[Check], list[str]]:
291
  flags = classify_paths(files)
292
  checks: list[Check] = [
293
+ Check("whitespace", (python, __file__, "--base", base_ref, "--internal-whitespace")),
294
  Check("repo stats", (python, "src/update_repo_stats.py", "--check")),
295
  ]
296
  notes = [
 
400
  )
401
 
402
  if flags["graph_artifact_changed"]:
403
+ checks.append(
404
+ Check("hydrate graph LFS", (python, __file__, "--internal-hydrate-graph-lfs"))
405
+ )
406
  checks.append(Check("graph artifact validation", (python, *GRAPH_VALIDATE_ARGS)))
407
 
408
  if source_required and flags["similarity_changed"]:
 
543
  action="store_true",
544
  help=argparse.SUPPRESS,
545
  )
546
+ parser.add_argument(
547
+ "--internal-hydrate-graph-lfs",
548
+ action="store_true",
549
+ help=argparse.SUPPRESS,
550
+ )
551
+ parser.add_argument(
552
+ "--internal-whitespace",
553
+ action="store_true",
554
+ help=argparse.SUPPRESS,
555
+ )
556
  args = parser.parse_args(argv)
557
 
558
  if not shutil.which("git"):
559
  raise SystemExit("git is required for ci_preflight")
560
 
561
+ if args.internal_hydrate_graph_lfs:
562
+ return hydrate_graph_lfs_artifacts()
563
+ if args.internal_whitespace:
564
+ return _run_whitespace_check(args.base)
565
+
566
  files = changed_files(args.base)
567
  if args.internal_no_test_policy:
568
  return _run_no_test_policy_for_files(files, base_ref=args.base)
scripts/local_fast_gate.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run PR preflight checks in isolated parallel local lanes.
2
+
3
+ The regular CI preflight stays the serial source of truth. This runner is a
4
+ fast local front door: it selects the same checks, groups independent work into
5
+ lanes, and runs each lane in a temporary git worktree so caches, graph hydration,
6
+ and package builds do not contend with each other.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ from concurrent.futures import ThreadPoolExecutor
13
+ from concurrent.futures import as_completed
14
+ from dataclasses import dataclass
15
+ import os
16
+ from pathlib import Path
17
+ import shutil
18
+ import subprocess
19
+ import sys
20
+ import tempfile
21
+ import time
22
+
23
+ REPO_ROOT = Path(__file__).resolve().parents[1]
24
+ if str(REPO_ROOT) not in sys.path:
25
+ sys.path.insert(0, str(REPO_ROOT))
26
+
27
+ from scripts.ci_preflight import Check # noqa: E402
28
+ from scripts.ci_preflight import changed_files # noqa: E402
29
+ from scripts.ci_preflight import select_checks # noqa: E402
30
+
31
+ LANE_ORDER = ("cheap", "static", "unit", "docs", "graph", "feature", "package", "misc")
32
+ CHECK_LANES = {
33
+ "whitespace": "cheap",
34
+ "repo stats": "cheap",
35
+ "no-test policy": "cheap",
36
+ "ruff format": "static",
37
+ "ruff": "static",
38
+ "mypy": "static",
39
+ "pip check": "static",
40
+ "unit-linux equivalent": "unit",
41
+ "A-Z canary": "unit",
42
+ "contract compatibility local": "unit",
43
+ "clean host contract": "unit",
44
+ "public docs tracker": "docs",
45
+ "docs strict build": "docs",
46
+ "hydrate graph LFS": "graph",
47
+ "graph artifact validation": "graph",
48
+ "telemetry enterprise": "feature",
49
+ "similarity precision/recall": "feature",
50
+ "browser monitor security": "feature",
51
+ "clean preflight dist": "package",
52
+ "build wheel": "package",
53
+ "twine check": "package",
54
+ }
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class Lane:
59
+ name: str
60
+ checks: tuple[Check, ...]
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class LaneResult:
65
+ name: str
66
+ returncode: int
67
+ elapsed: float
68
+ worktree: Path | None = None
69
+
70
+
71
+ def _lane_name(check: Check) -> str:
72
+ return CHECK_LANES.get(check.name, "misc")
73
+
74
+
75
+ def group_checks(checks: list[Check]) -> list[Lane]:
76
+ grouped: dict[str, list[Check]] = {lane: [] for lane in LANE_ORDER}
77
+ for check in checks:
78
+ grouped[_lane_name(check)].append(_worktree_safe_check(check))
79
+ return [Lane(name, tuple(grouped[name])) for name in LANE_ORDER if grouped[name]]
80
+
81
+
82
+ def _worktree_safe_check(check: Check) -> Check:
83
+ ci_preflight = (REPO_ROOT / "scripts" / "ci_preflight.py").resolve()
84
+ argv = tuple(
85
+ "scripts/ci_preflight.py" if _same_path_arg(arg, ci_preflight) else arg
86
+ for arg in check.argv
87
+ )
88
+ return Check(check.name, argv, check.env)
89
+
90
+
91
+ def _same_path_arg(arg: str, expected: Path) -> bool:
92
+ try:
93
+ return Path(arg).resolve() == expected
94
+ except OSError:
95
+ return False
96
+
97
+
98
+ def _git_stdout(args: list[str]) -> str:
99
+ return subprocess.check_output(["git", *args], cwd=REPO_ROOT, text=True)
100
+
101
+
102
+ def _is_worktree_dirty() -> bool:
103
+ return bool(_git_stdout(["status", "--porcelain"]).strip())
104
+
105
+
106
+ def _create_worktree(lane: str) -> Path:
107
+ parent = Path(tempfile.mkdtemp(prefix="ctx-local-fast-"))
108
+ worktree = parent / lane
109
+ env = os.environ.copy()
110
+ env.setdefault("GIT_LFS_SKIP_SMUDGE", "1")
111
+ subprocess.check_call(
112
+ ["git", "worktree", "add", "--detach", str(worktree), "HEAD"],
113
+ cwd=REPO_ROOT,
114
+ env=env,
115
+ stdout=subprocess.DEVNULL,
116
+ )
117
+ return worktree
118
+
119
+
120
+ def _remove_worktree(worktree: Path) -> None:
121
+ subprocess.run(
122
+ ["git", "worktree", "remove", "--force", str(worktree)],
123
+ cwd=REPO_ROOT,
124
+ check=False,
125
+ stdout=subprocess.DEVNULL,
126
+ stderr=subprocess.DEVNULL,
127
+ )
128
+ shutil.rmtree(worktree.parent, ignore_errors=True)
129
+
130
+
131
+ def _run_check(check: Check, *, cwd: Path, index: int, total: int, lane: str) -> int:
132
+ print(
133
+ f"[{lane} {index}/{total}] {check.name}: {' '.join(check.argv)}",
134
+ flush=True,
135
+ )
136
+ env = os.environ.copy()
137
+ env.setdefault("PYTHONDONTWRITEBYTECODE", "1")
138
+ env.setdefault("PIP_DISABLE_PIP_VERSION_CHECK", "1")
139
+ env.setdefault("GIT_LFS_SKIP_SMUDGE", "1")
140
+ if check.env:
141
+ env.update(check.env)
142
+ proc = subprocess.run(check.argv, cwd=cwd, check=False, env=env)
143
+ if proc.returncode != 0:
144
+ print(f"[{lane} fail] {check.name} exited {proc.returncode}", file=sys.stderr)
145
+ return proc.returncode
146
+
147
+
148
+ def run_lane(lane: Lane, *, keep_worktrees: bool) -> LaneResult:
149
+ start = time.monotonic()
150
+ worktree = _create_worktree(lane.name)
151
+ try:
152
+ for index, check in enumerate(lane.checks, start=1):
153
+ returncode = _run_check(
154
+ check,
155
+ cwd=worktree,
156
+ index=index,
157
+ total=len(lane.checks),
158
+ lane=lane.name,
159
+ )
160
+ if returncode != 0:
161
+ return LaneResult(lane.name, returncode, time.monotonic() - start, worktree)
162
+ return LaneResult(lane.name, 0, time.monotonic() - start, worktree)
163
+ finally:
164
+ if not keep_worktrees:
165
+ _remove_worktree(worktree)
166
+
167
+
168
+ def run_lanes(
169
+ lanes: list[Lane],
170
+ *,
171
+ jobs: int,
172
+ keep_worktrees: bool = False,
173
+ ) -> int:
174
+ if not lanes:
175
+ print("No local-fast lanes selected.")
176
+ return 0
177
+ worker_count = max(1, min(jobs, len(lanes)))
178
+ print(f"Running {len(lanes)} local-fast lanes with {worker_count} workers.")
179
+ failures: list[LaneResult] = []
180
+ with ThreadPoolExecutor(max_workers=worker_count) as executor:
181
+ futures = {
182
+ executor.submit(run_lane, lane, keep_worktrees=keep_worktrees): lane for lane in lanes
183
+ }
184
+ for future in as_completed(futures):
185
+ result = future.result()
186
+ status = "pass" if result.returncode == 0 else "fail"
187
+ print(f"[{status}] {result.name} lane in {result.elapsed:.1f}s")
188
+ if result.returncode != 0:
189
+ failures.append(result)
190
+
191
+ if failures:
192
+ for failure in failures:
193
+ print(
194
+ f"[fail] {failure.name} lane exited {failure.returncode}",
195
+ file=sys.stderr,
196
+ )
197
+ return 1
198
+ return 0
199
+
200
+
201
+ def print_dry_run(lanes: list[Lane]) -> None:
202
+ for lane in lanes:
203
+ print(f"[lane] {lane.name}")
204
+ for check in lane.checks:
205
+ print(f" - {check.name}: {' '.join(check.argv)}")
206
+
207
+
208
+ def _default_jobs() -> int:
209
+ cpu_count = os.cpu_count() or 2
210
+ return max(1, min(cpu_count, len(LANE_ORDER)))
211
+
212
+
213
+ def main(argv: list[str] | None = None) -> int:
214
+ parser = argparse.ArgumentParser(description=__doc__)
215
+ parser.add_argument("--base", default="origin/main")
216
+ parser.add_argument("--profile", choices=("pr", "full"), default="pr")
217
+ parser.add_argument("--python", default=sys.executable)
218
+ parser.add_argument("--jobs", type=int, default=_default_jobs())
219
+ parser.add_argument("--dry-run", action="store_true")
220
+ parser.add_argument("--keep-worktrees", action="store_true")
221
+ parser.add_argument(
222
+ "--allow-dirty",
223
+ action="store_true",
224
+ help="allow a dirty worktree; uncommitted changes still are not run in temp worktrees",
225
+ )
226
+ args = parser.parse_args(argv)
227
+
228
+ if not shutil.which("git"):
229
+ raise SystemExit("git is required for local_fast_gate")
230
+ if not args.dry_run and not args.allow_dirty and _is_worktree_dirty():
231
+ raise SystemExit(
232
+ "local-fast runs committed HEAD in temp worktrees; commit or stash changes first "
233
+ "(or pass --allow-dirty if you only need a committed-HEAD gate)."
234
+ )
235
+
236
+ files = changed_files(args.base)
237
+ checks, notes = select_checks(
238
+ base_ref=args.base,
239
+ files=files,
240
+ profile=args.profile,
241
+ python=args.python,
242
+ )
243
+ lanes = group_checks(checks)
244
+ for note in notes:
245
+ print(f"[note] {note}")
246
+ print("[note] local-fast runs selected committed-HEAD checks in isolated temp worktrees.")
247
+ if args.dry_run:
248
+ print_dry_run(lanes)
249
+ return 0
250
+ return run_lanes(lanes, jobs=args.jobs, keep_worktrees=args.keep_worktrees)
251
+
252
+
253
+ if __name__ == "__main__":
254
+ raise SystemExit(main())
scripts/no_mistakes_codex_env.sh CHANGED
@@ -3,8 +3,11 @@ set -euo pipefail
3
 
4
  # no-mistakes agents run in a stripped-down environment. Keep ctx validation fast
5
  # by exposing the verified project Python toolchain and Codex-bundled ripgrep.
6
- default_ctx_python_bin="/tmp/ctx-verify-venv/bin"
7
- ctx_python_bin="${CTX_NO_MISTAKES_PYTHON_BIN:-${default_ctx_python_bin}}"
 
 
 
8
  codex_resources="${CTX_NO_MISTAKES_CODEX_RESOURCES:-/Applications/Codex.app/Contents/Resources}"
9
  real_codex="${CTX_NO_MISTAKES_REAL_CODEX:-${codex_resources}/codex}"
10
 
@@ -13,19 +16,43 @@ is_trusted_python_bin() {
13
  local venv_dir="${bin_dir%/bin}"
14
 
15
  [[ -d "${bin_dir}" && -x "${bin_dir}/python" ]] || return 1
 
16
  [[ -O "${venv_dir}" && -O "${bin_dir}" ]] || return 1
17
  [[ -z "$(find "${venv_dir}" "${bin_dir}" -prune -perm -022 -print -quit)" ]]
18
  }
19
 
20
- trusted_ctx_python_bin=""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  if [[ -n "${CTX_NO_MISTAKES_PYTHON_BIN:-}" ]]; then
22
- trusted_ctx_python_bin="${ctx_python_bin}"
23
- elif is_trusted_python_bin "${ctx_python_bin}"; then
24
- trusted_ctx_python_bin="${ctx_python_bin}"
25
  fi
 
 
 
 
 
 
 
 
 
26
 
27
  if [[ -n "${trusted_ctx_python_bin}" ]]; then
28
  export PATH="${trusted_ctx_python_bin}:${codex_resources}:${PATH}"
 
29
  if [[ -x "${trusted_ctx_python_bin}/python" ]]; then
30
  export VIRTUAL_ENV="${VIRTUAL_ENV:-${trusted_ctx_python_bin%/bin}}"
31
  fi
 
3
 
4
  # no-mistakes agents run in a stripped-down environment. Keep ctx validation fast
5
  # by exposing the verified project Python toolchain and Codex-bundled ripgrep.
6
+ script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
7
+ repo_root="$(cd -- "${script_dir}/.." && pwd -P)"
8
+ pwd_ctx_python_bin="${PWD}/.venv/bin"
9
+ repo_ctx_python_bin="${repo_root}/.venv/bin"
10
+ fallback_ctx_python_bin="/tmp/ctx-verify-venv/bin"
11
  codex_resources="${CTX_NO_MISTAKES_CODEX_RESOURCES:-/Applications/Codex.app/Contents/Resources}"
12
  real_codex="${CTX_NO_MISTAKES_REAL_CODEX:-${codex_resources}/codex}"
13
 
 
16
  local venv_dir="${bin_dir%/bin}"
17
 
18
  [[ -d "${bin_dir}" && -x "${bin_dir}/python" ]] || return 1
19
+ [[ -f "${venv_dir}/pyvenv.cfg" ]] || return 1
20
  [[ -O "${venv_dir}" && -O "${bin_dir}" ]] || return 1
21
  [[ -z "$(find "${venv_dir}" "${bin_dir}" -prune -perm -022 -print -quit)" ]]
22
  }
23
 
24
+ has_validation_tools() {
25
+ local bin_dir="$1"
26
+
27
+ PYTHONDONTWRITEBYTECODE=1 "${bin_dir}/python" - <<'PY' >/dev/null 2>&1
28
+ import importlib.util
29
+
30
+ missing = [
31
+ module
32
+ for module in ("pytest", "ruff", "mypy")
33
+ if importlib.util.find_spec(module) is None
34
+ ]
35
+ raise SystemExit(1 if missing else 0)
36
+ PY
37
+ }
38
+
39
+ candidate_python_bins=()
40
  if [[ -n "${CTX_NO_MISTAKES_PYTHON_BIN:-}" ]]; then
41
+ candidate_python_bins+=("${CTX_NO_MISTAKES_PYTHON_BIN}")
 
 
42
  fi
43
+ candidate_python_bins+=("${pwd_ctx_python_bin}" "${repo_ctx_python_bin}" "${fallback_ctx_python_bin}")
44
+
45
+ trusted_ctx_python_bin=""
46
+ for candidate_python_bin in "${candidate_python_bins[@]}"; do
47
+ if is_trusted_python_bin "${candidate_python_bin}" && has_validation_tools "${candidate_python_bin}"; then
48
+ trusted_ctx_python_bin="${candidate_python_bin}"
49
+ break
50
+ fi
51
+ done
52
 
53
  if [[ -n "${trusted_ctx_python_bin}" ]]; then
54
  export PATH="${trusted_ctx_python_bin}:${codex_resources}:${PATH}"
55
+ export CTX_NO_MISTAKES_PYTHON_BIN_RESOLVED="${trusted_ctx_python_bin}"
56
  if [[ -x "${trusted_ctx_python_bin}/python" ]]; then
57
  export VIRTUAL_ENV="${VIRTUAL_ENV:-${trusted_ctx_python_bin%/bin}}"
58
  fi
scripts/no_mistakes_run.sh ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
5
+ repo_root="$(cd -- "${script_dir}/.." && pwd -P)"
6
+ action="${1:-}"
7
+
8
+ is_trusted_python_bin() {
9
+ local bin_dir="$1"
10
+ local venv_dir="${bin_dir%/bin}"
11
+
12
+ [[ -d "${bin_dir}" && -x "${bin_dir}/python" ]] || return 1
13
+ [[ -f "${venv_dir}/pyvenv.cfg" ]] || return 1
14
+ [[ -O "${venv_dir}" && -O "${bin_dir}" ]] || return 1
15
+ [[ -z "$(find "${venv_dir}" "${bin_dir}" -prune -perm -022 -print -quit)" ]]
16
+ }
17
+
18
+ has_validation_tools() {
19
+ local bin_dir="$1"
20
+
21
+ PYTHONDONTWRITEBYTECODE=1 "${bin_dir}/python" - <<'PY' >/dev/null 2>&1
22
+ import importlib.util
23
+
24
+ missing = [
25
+ module
26
+ for module in ("pytest", "ruff", "mypy")
27
+ if importlib.util.find_spec(module) is None
28
+ ]
29
+ raise SystemExit(1 if missing else 0)
30
+ PY
31
+ }
32
+
33
+ append_agent_wrapper_venv() {
34
+ local config_path="${HOME:-}/.no-mistakes/config.yaml"
35
+ local wrapper_path
36
+ local wrapper_root
37
+
38
+ [[ -f "${config_path}" ]] || return 0
39
+ wrapper_path="$(awk '/^[[:space:]]+codex:[[:space:]]/ {print $2; exit}' "${config_path}")"
40
+ [[ -n "${wrapper_path}" && -f "${wrapper_path}" ]] || return 0
41
+ wrapper_root="$(cd -- "$(dirname -- "${wrapper_path}")/.." && pwd -P)"
42
+ candidate_python_bins+=("${wrapper_root}/.venv/bin")
43
+ }
44
+
45
+ candidate_python_bins=()
46
+ if [[ -n "${CTX_NO_MISTAKES_PYTHON_BIN:-}" ]]; then
47
+ candidate_python_bins+=("${CTX_NO_MISTAKES_PYTHON_BIN}")
48
+ fi
49
+ candidate_python_bins+=("${PWD}/.venv/bin" "${repo_root}/.venv/bin")
50
+ append_agent_wrapper_venv
51
+ candidate_python_bins+=("/tmp/ctx-verify-venv/bin")
52
+
53
+ trusted_ctx_python_bin=""
54
+ for candidate_python_bin in "${candidate_python_bins[@]}"; do
55
+ if is_trusted_python_bin "${candidate_python_bin}" && has_validation_tools "${candidate_python_bin}"; then
56
+ trusted_ctx_python_bin="${candidate_python_bin}"
57
+ break
58
+ fi
59
+ done
60
+
61
+ if [[ -z "${trusted_ctx_python_bin}" ]]; then
62
+ echo "No trusted ctx validation Python found with pytest, ruff, and mypy." >&2
63
+ exit 127
64
+ fi
65
+
66
+ export PATH="${trusted_ctx_python_bin}:${PATH}"
67
+ export VIRTUAL_ENV="${trusted_ctx_python_bin%/bin}"
68
+ export CTX_NO_MISTAKES_PYTHON_BIN_RESOLVED="${trusted_ctx_python_bin}"
69
+ export PYTHONDONTWRITEBYTECODE="${PYTHONDONTWRITEBYTECODE:-1}"
70
+ export PIP_DISABLE_PIP_VERSION_CHECK="${PIP_DISABLE_PIP_VERSION_CHECK:-1}"
71
+
72
+ case "${action}" in
73
+ fast)
74
+ exec python scripts/local_fast_gate.py --profile pr "${@:2}"
75
+ ;;
76
+ test)
77
+ exec python scripts/ci_preflight.py --profile pr
78
+ ;;
79
+ lint)
80
+ python -m ruff check .
81
+ python -m ruff format --check src hooks scripts
82
+ exec python -m mypy src
83
+ ;;
84
+ format)
85
+ exec python -m ruff format src hooks scripts
86
+ ;;
87
+ *)
88
+ echo "Usage: scripts/no_mistakes_run.sh {fast|test|lint|format}" >&2
89
+ exit 64
90
+ ;;
91
+ esac
scripts/pack_full_wiki_tar.py CHANGED
@@ -13,8 +13,51 @@ from pathlib import Path, PurePosixPath
13
  from ctx.core.wiki.wiki_packs import load_merged_wiki_pages, write_wiki_base_pack
14
 
15
  _WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  _GRAPH_MANIFEST = "graphify-out/graph-export-manifest.json"
17
  _REQUIRED_EXPANDED_MARKDOWN = frozenset({"graphify-out/graph-report.md"})
 
 
 
 
 
 
 
 
18
 
19
 
20
  @dataclass(frozen=True)
@@ -60,7 +103,13 @@ def repack_full_wiki_tar(source: Path, target: Path | None = None) -> RepackStat
60
  if not export_id:
61
  raise ValueError(f"{source} is missing graph export id")
62
  if existing_pack_root.exists():
63
- pages.update(load_merged_wiki_pages(existing_pack_root))
 
 
 
 
 
 
64
 
65
  pack_root = tmp_root / "wiki-packs"
66
  write_wiki_base_pack(
@@ -112,8 +161,19 @@ def _rewrite_tar_with_pack(
112
  if extracted is None:
113
  raise ValueError(f"archive file is unreadable: {member.name}")
114
  with extracted:
115
- member.name = name
116
- dst.addfile(member, extracted)
 
 
 
 
 
 
 
 
 
 
 
117
  written_names.add(name)
118
  elif member.isdir():
119
  member.name = name
@@ -122,9 +182,9 @@ def _rewrite_tar_with_pack(
122
  else:
123
  raise ValueError(f"unsupported archive member: {member.name}")
124
  for name in sorted(_REQUIRED_EXPANDED_MARKDOWN - written_names):
125
- text = pages.get(name)
126
- if text is not None:
127
- _add_text(dst, name=name, text=text)
128
  for path in sorted(pack_root.rglob("*")):
129
  if path.is_file():
130
  dst.add(path, arcname=path.relative_to(pack_root.parent).as_posix())
@@ -175,7 +235,17 @@ def _validate_pack_payload(pack_root: Path, expected_pages: dict[str, str]) -> N
175
 
176
 
177
  def _normalise_page_text(text: str) -> str:
178
- return text if text.strip() else "<!-- empty markdown page -->\n"
 
 
 
 
 
 
 
 
 
 
179
 
180
 
181
  def _safe_tar_name(raw_name: str) -> str:
@@ -212,11 +282,15 @@ def _is_high_fanout_entity_page(name: str) -> bool:
212
 
213
 
214
  def _should_pack_markdown_page(name: str) -> bool:
215
- return name.endswith(".md") and not name.startswith("wiki-packs/")
 
 
 
 
216
 
217
 
218
  def _should_skip_expanded_markdown_member(name: str) -> bool:
219
- return (
220
  name.endswith(".md")
221
  and name not in _REQUIRED_EXPANDED_MARKDOWN
222
  and "/" in name
@@ -224,6 +298,14 @@ def _should_skip_expanded_markdown_member(name: str) -> bool:
224
  )
225
 
226
 
 
 
 
 
 
 
 
 
227
  def _add_text(tf: tarfile.TarFile, *, name: str, text: str) -> None:
228
  payload = text.encode("utf-8")
229
  info = tarfile.TarInfo(name)
 
13
  from ctx.core.wiki.wiki_packs import load_merged_wiki_pages, write_wiki_base_pack
14
 
15
  _WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:")
16
+ _PATH_CHAR = r"[^`\"'<>|\s\r\n)]"
17
+ _PATH_TOKEN = rf"{_PATH_CHAR}+"
18
+ _PATH_TERMINAL_WORD = r"[A-Z0-9][^`\"'<>|/\\\s\r\n)]*"
19
+ _PATH_LOWER_PROSE_WORDS = (
20
+ r"(?:a|an|and|are|as|at|by|for|from|in|is|of|on|or|the|to|was|were|with|without)"
21
+ )
22
+ _PATH_LOWER_TERMINAL_WORD = (
23
+ rf"(?!(?:{_PATH_LOWER_PROSE_WORDS})(?=$|[\s),.;:!?]))"
24
+ r"[a-z][^`\"'<>|/\\\s\r\n),.;:!?]*"
25
+ )
26
+ _PATH_TERMINAL_END = r"(?=$|[\r\n`\"'),.;:!?>\]])"
27
+ _PATH_SPACED_COMPONENT = (
28
+ rf"(?: {_PATH_CHAR}*[\\/]{_PATH_CHAR}*| {_PATH_CHAR}*\.{_PATH_CHAR}+"
29
+ rf"|(?: {_PATH_TERMINAL_WORD})+"
30
+ rf"|(?: {_PATH_LOWER_TERMINAL_WORD}){{1,2}}{_PATH_TERMINAL_END})"
31
+ )
32
+ _PATH_BOUNDARY = r"(?:^|(?<=[`\"'(<\[\s=,:]))"
33
+ _QUOTED_PATH_BOUNDARY = r"(?<=[`\"'(<\[])"
34
+ _QUOTED_PATH_TOKEN = r"[^`\"'<>|\r\n)]+"
35
+ _QUOTED_PATH_END = r"(?=[`\"')>\]])"
36
+ _QUOTED_WINDOWS_USER_PATH_RE = re.compile(
37
+ rf"(?i){_QUOTED_PATH_BOUNDARY}[A-Z]:[\\/]+Users[\\/]+{_QUOTED_PATH_TOKEN}{_QUOTED_PATH_END}"
38
+ )
39
+ _QUOTED_POSIX_USER_PATH_RE = re.compile(
40
+ rf"{_QUOTED_PATH_BOUNDARY}(?:(?i:file:///)|/)(?:Users|home)/"
41
+ rf"{_QUOTED_PATH_TOKEN}{_QUOTED_PATH_END}"
42
+ )
43
+ _WINDOWS_USER_PATH_RE = re.compile(
44
+ rf"(?i)\b[A-Z]:[\\/]+Users[\\/]+{_PATH_TOKEN}(?:{_PATH_SPACED_COMPONENT})*"
45
+ )
46
+ _POSIX_USER_PATH_RE = re.compile(
47
+ rf"{_PATH_BOUNDARY}(?:(?i:file:///)|/)(?:Users|home)/{_PATH_TOKEN}"
48
+ rf"(?:{_PATH_SPACED_COMPONENT})*"
49
+ )
50
+ _POSIX_USER_PATH_PREFIX_RE = re.compile(rf"{_PATH_BOUNDARY}(?:(?i:file:///)|/)(?:Users|home)/")
51
  _GRAPH_MANIFEST = "graphify-out/graph-export-manifest.json"
52
  _REQUIRED_EXPANDED_MARKDOWN = frozenset({"graphify-out/graph-report.md"})
53
+ _LOCAL_GENERATED_MARKDOWN = frozenset(
54
+ {
55
+ "catalog.md",
56
+ "converted-index.md",
57
+ "log.md",
58
+ "versions-catalog.md",
59
+ }
60
+ )
61
 
62
 
63
  @dataclass(frozen=True)
 
103
  if not export_id:
104
  raise ValueError(f"{source} is missing graph export id")
105
  if existing_pack_root.exists():
106
+ pages.update(
107
+ {
108
+ name: _normalise_page_text(text)
109
+ for name, text in load_merged_wiki_pages(existing_pack_root).items()
110
+ if _should_pack_markdown_page(name)
111
+ }
112
+ )
113
 
114
  pack_root = tmp_root / "wiki-packs"
115
  write_wiki_base_pack(
 
161
  if extracted is None:
162
  raise ValueError(f"archive file is unreadable: {member.name}")
163
  with extracted:
164
+ if name.endswith(".md"):
165
+ text = _normalise_page_text(
166
+ extracted.read().decode("utf-8", errors="replace")
167
+ )
168
+ _add_text(dst, name=name, text=text)
169
+ elif _should_redact_text_member(name):
170
+ text = _redact_host_user_paths(
171
+ extracted.read().decode("utf-8", errors="replace")
172
+ )
173
+ _add_text(dst, name=name, text=text)
174
+ else:
175
+ member.name = name
176
+ dst.addfile(member, extracted)
177
  written_names.add(name)
178
  elif member.isdir():
179
  member.name = name
 
182
  else:
183
  raise ValueError(f"unsupported archive member: {member.name}")
184
  for name in sorted(_REQUIRED_EXPANDED_MARKDOWN - written_names):
185
+ required_text = pages.get(name)
186
+ if required_text is not None:
187
+ _add_text(dst, name=name, text=required_text)
188
  for path in sorted(pack_root.rglob("*")):
189
  if path.is_file():
190
  dst.add(path, arcname=path.relative_to(pack_root.parent).as_posix())
 
235
 
236
 
237
  def _normalise_page_text(text: str) -> str:
238
+ if not text.strip():
239
+ return "<!-- empty markdown page -->\n"
240
+ return _redact_host_user_paths(text)
241
+
242
+
243
+ def _redact_host_user_paths(text: str) -> str:
244
+ redacted = _QUOTED_WINDOWS_USER_PATH_RE.sub("<host-user-path>", text)
245
+ redacted = _QUOTED_POSIX_USER_PATH_RE.sub("<host-user-path>", redacted)
246
+ redacted = _WINDOWS_USER_PATH_RE.sub("<host-user-path>", redacted)
247
+ redacted = _POSIX_USER_PATH_RE.sub("<host-user-path>", redacted)
248
+ return _POSIX_USER_PATH_PREFIX_RE.sub("<host-user-path>", redacted)
249
 
250
 
251
  def _safe_tar_name(raw_name: str) -> str:
 
282
 
283
 
284
  def _should_pack_markdown_page(name: str) -> bool:
285
+ return (
286
+ name.endswith(".md")
287
+ and name not in _LOCAL_GENERATED_MARKDOWN
288
+ and not name.startswith("wiki-packs/")
289
+ )
290
 
291
 
292
  def _should_skip_expanded_markdown_member(name: str) -> bool:
293
+ return name in _LOCAL_GENERATED_MARKDOWN or (
294
  name.endswith(".md")
295
  and name not in _REQUIRED_EXPANDED_MARKDOWN
296
  and "/" in name
 
298
  )
299
 
300
 
301
+ def _should_redact_text_member(name: str) -> bool:
302
+ return (
303
+ name.startswith("graphify-out/")
304
+ and not name.startswith("graphify-out/packs/")
305
+ and name.endswith((".json", ".jsonl"))
306
+ )
307
+
308
+
309
  def _add_text(tf: tarfile.TarFile, *, name: str, text: str) -> None:
310
  payload = text.encode("utf-8")
311
  info = tarfile.TarInfo(name)
scripts/sync_huggingface.py CHANGED
@@ -40,6 +40,8 @@ HYDRATED_ARTIFACT_MIN_BYTES = {
40
  Path("graph/wiki-graph-runtime.tar.gz"): 10_000_000,
41
  Path("graph/skills-sh-catalog.json.gz"): 1_000_000,
42
  }
 
 
43
  GRAPH_VALIDATOR_INT_FLAGS = {
44
  "--min-nodes": "min_nodes",
45
  "--min-edges": "min_edges",
@@ -231,21 +233,35 @@ def _export_tracked_tree(repo: Path, export_dir: Path) -> None:
231
  repo_root = repo.resolve()
232
  export_root = export_dir.resolve()
233
  for rel in _iter_tracked_files(repo):
234
- source = (repo_root / rel).resolve()
235
- if source != repo_root and not source.is_relative_to(repo_root):
236
- raise ValueError(f"unsafe source path: {rel}")
237
- if source.is_symlink():
238
- raise ValueError(f"refusing to follow symlink during HF sync: {rel}")
239
- if not source.is_file():
240
- continue
241
- target = (export_root / rel).resolve()
242
- if target != export_root and not target.is_relative_to(export_root):
243
- raise ValueError(f"unsafe export path: {rel}")
244
- target.parent.mkdir(parents=True, exist_ok=True)
245
- shutil.copy2(source, target)
246
  _copy_hydrated_artifacts(repo_root, export_root)
247
 
248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
  def _copy_hydrated_artifacts(repo_root: Path, export_root: Path) -> None:
250
  """Copy required graph artifacts even when they are intentionally untracked."""
251
  for rel in HYDRATED_ARTIFACT_MIN_BYTES:
@@ -342,6 +358,25 @@ def _upload_readme_card(
342
  shutil.rmtree(workspace, ignore_errors=True)
343
 
344
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345
  def sync_to_huggingface(
346
  *,
347
  repo: Path,
@@ -379,19 +414,27 @@ def sync_card_to_huggingface(
379
  repo_type: str,
380
  token: str,
381
  ) -> str:
382
- """Upload only the Hugging Face repo card README."""
383
  from huggingface_hub import HfApi
384
 
385
  head = _git(repo, "rev-parse", "HEAD")
386
- api = HfApi(token=token)
387
- _ensure_hf_repo_exists(api=api, repo_id=repo_id, repo_type=repo_type)
388
- return _upload_readme_card(
389
- api=api,
390
- repo=repo,
391
- repo_id=repo_id,
392
- repo_type=repo_type,
393
- head=head,
394
- )
 
 
 
 
 
 
 
 
395
 
396
 
397
  def main() -> None:
@@ -412,7 +455,7 @@ def main() -> None:
412
  parser.add_argument(
413
  "--card-only",
414
  action="store_true",
415
- help="Only refresh README.md repo-card metadata without uploading artifacts",
416
  )
417
  args = parser.parse_args()
418
  token = os.environ.get("HF_TOKEN")
 
40
  Path("graph/wiki-graph-runtime.tar.gz"): 10_000_000,
41
  Path("graph/skills-sh-catalog.json.gz"): 1_000_000,
42
  }
43
+ CARD_ONLY_DELETE_PATTERNS = ("README.md", "CHANGELOG.md", "docs/**")
44
+ _CARD_ONLY_FILES = frozenset({Path("README.md"), Path("CHANGELOG.md")})
45
  GRAPH_VALIDATOR_INT_FLAGS = {
46
  "--min-nodes": "min_nodes",
47
  "--min-edges": "min_edges",
 
233
  repo_root = repo.resolve()
234
  export_root = export_dir.resolve()
235
  for rel in _iter_tracked_files(repo):
236
+ _copy_export_file(repo_root, export_root, rel)
 
 
 
 
 
 
 
 
 
 
 
237
  _copy_hydrated_artifacts(repo_root, export_root)
238
 
239
 
240
+ def _export_card_inputs(repo: Path, export_dir: Path) -> None:
241
+ repo_root = repo.resolve()
242
+ export_root = export_dir.resolve()
243
+ for rel in _iter_tracked_files(repo):
244
+ if rel in _CARD_ONLY_FILES or (rel.parts and rel.parts[0] == "docs"):
245
+ _copy_export_file(repo_root, export_root, rel)
246
+ _patch_export_readme(export_dir)
247
+
248
+
249
+ def _copy_export_file(repo_root: Path, export_root: Path, rel: Path) -> None:
250
+ raw_source = repo_root / rel
251
+ if raw_source.is_symlink():
252
+ raise ValueError(f"refusing to follow symlink during HF sync: {rel}")
253
+ source = raw_source.resolve()
254
+ if source != repo_root and not source.is_relative_to(repo_root):
255
+ raise ValueError(f"unsafe source path: {rel}")
256
+ if not source.is_file():
257
+ return
258
+ target = (export_root / rel).resolve()
259
+ if target != export_root and not target.is_relative_to(export_root):
260
+ raise ValueError(f"unsafe export path: {rel}")
261
+ target.parent.mkdir(parents=True, exist_ok=True)
262
+ shutil.copy2(source, target)
263
+
264
+
265
  def _copy_hydrated_artifacts(repo_root: Path, export_root: Path) -> None:
266
  """Copy required graph artifacts even when they are intentionally untracked."""
267
  for rel in HYDRATED_ARTIFACT_MIN_BYTES:
 
358
  shutil.rmtree(workspace, ignore_errors=True)
359
 
360
 
361
+ def _upload_card_inputs(
362
+ *,
363
+ api: Any,
364
+ export_dir: Path,
365
+ repo_id: str,
366
+ repo_type: str,
367
+ head: str,
368
+ ) -> str:
369
+ info = api.upload_folder(
370
+ repo_id=repo_id,
371
+ repo_type=repo_type,
372
+ folder_path=str(export_dir),
373
+ commit_message=f"Sync ctx card {head[:7]}",
374
+ commit_description=f"GitHub commit: {head}",
375
+ delete_patterns=list(CARD_ONLY_DELETE_PATTERNS),
376
+ )
377
+ return str(getattr(info, "commit_url", info))
378
+
379
+
380
  def sync_to_huggingface(
381
  *,
382
  repo: Path,
 
414
  repo_type: str,
415
  token: str,
416
  ) -> str:
417
+ """Upload only Hugging Face repo-card inputs."""
418
  from huggingface_hub import HfApi
419
 
420
  head = _git(repo, "rev-parse", "HEAD")
421
+ _assert_repo_stats_current(repo)
422
+ workspace = Path(tempfile.mkdtemp(prefix="ctx-hf-card-"))
423
+ export_dir = workspace / "export"
424
+ try:
425
+ export_dir.mkdir()
426
+ _export_card_inputs(repo, export_dir)
427
+ api = HfApi(token=token)
428
+ _ensure_hf_repo_exists(api=api, repo_id=repo_id, repo_type=repo_type)
429
+ return _upload_card_inputs(
430
+ api=api,
431
+ export_dir=export_dir,
432
+ repo_id=repo_id,
433
+ repo_type=repo_type,
434
+ head=head,
435
+ )
436
+ finally:
437
+ shutil.rmtree(workspace, ignore_errors=True)
438
 
439
 
440
  def main() -> None:
 
455
  parser.add_argument(
456
  "--card-only",
457
  action="store_true",
458
+ help="Only refresh repo-card inputs without uploading artifacts",
459
  )
460
  args = parser.parse_args()
461
  token = os.environ.get("HF_TOKEN")
src/__init__.py CHANGED
@@ -1,3 +1,3 @@
1
  """ctx — skill and agent recommendation for Claude Code."""
2
 
3
- __version__ = "1.0.20"
 
1
  """ctx — skill and agent recommendation for Claude Code."""
2
 
3
+ __version__ = "1.0.21"
src/backup_config.py CHANGED
@@ -41,6 +41,27 @@ ALWAYS_EXCLUDE: frozenset[str] = frozenset(
41
  _ALLOWED_SCOPES: frozenset[str] = frozenset({"full", "incremental", "hybrid"})
42
 
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  # ── Schema ──────────────────────────────────────────────────────────────────
45
 
46
 
@@ -81,6 +102,7 @@ class BackupConfig:
81
  # Phase 2 implements incremental/hybrid. Phase 1 only honours "full".
82
  scope: str = "full"
83
  max_file_bytes: int = 5 * 1024 * 1024 # 5 MB
 
84
  top_files: tuple[str, ...] = (
85
  "settings.json",
86
  "skill-manifest.json",
@@ -115,11 +137,10 @@ class BackupConfig:
115
  raise ValueError(f"retention.keep_daily must be >= 0, got {self.retention.keep_daily}")
116
  if "{timestamp}" not in self.name_format:
117
  raise ValueError(f"name_format must contain '{{timestamp}}', got {self.name_format!r}")
 
118
  # Silently drop ALWAYS_EXCLUDE names from top_files. frozen
119
  # dataclass requires object.__setattr__ for the rewrite.
120
- filtered_top = tuple(
121
- name for name in self.top_files if Path(name).name not in ALWAYS_EXCLUDE
122
- )
123
  if filtered_top != self.top_files:
124
  object.__setattr__(self, "top_files", filtered_top)
125
 
@@ -198,6 +219,41 @@ def _coerce_trees(raw: Any, default: tuple[BackupTree, ...]) -> tuple[BackupTree
198
  return tuple(out)
199
 
200
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  def _coerce_retention(raw: Any) -> BackupRetention:
202
  if not isinstance(raw, dict):
203
  return BackupRetention()
@@ -266,14 +322,14 @@ def from_ctx_config() -> BackupConfig:
266
  except Exception:
267
  base_raw = {}
268
 
269
- merged: dict[str, Any] = dict(base_raw) if isinstance(base_raw, dict) else {}
270
 
271
  user_override = Path(os.path.expanduser("~/.claude/backup-config.json"))
272
  if user_override.is_file():
273
  try:
274
  user_raw = json.loads(user_override.read_text(encoding="utf-8"))
275
  if isinstance(user_raw, dict):
276
- _deep_merge(merged, user_raw)
277
  except (OSError, json.JSONDecodeError):
278
  pass
279
 
 
41
  _ALLOWED_SCOPES: frozenset[str] = frozenset({"full", "incremental", "hybrid"})
42
 
43
 
44
+ def _validate_top_file(value: str) -> str:
45
+ """Validate a top-level file name from backup.top_files."""
46
+ value = value.strip()
47
+ if not value:
48
+ raise ValueError("top_files[] must be a non-empty filename")
49
+ parts = value.replace("\\", "/").split("/")
50
+ if any(part == ".." for part in parts):
51
+ raise ValueError(f"top_files[]: {value!r} contains '..' path traversal")
52
+ if value == ".":
53
+ raise ValueError("top_files[]: '.' is not a filename")
54
+ if value.startswith(("//", "\\\\")):
55
+ raise ValueError(f"top_files[]: {value!r} is a UNC path")
56
+ if len(value) >= 2 and value[1] == ":":
57
+ raise ValueError(f"top_files[]: {value!r} contains a drive letter")
58
+ if value.startswith(("/", "\\")):
59
+ raise ValueError(f"top_files[]: {value!r} is absolute")
60
+ if "/" in value or "\\" in value:
61
+ raise ValueError(f"top_files[]: {value!r} contains a path separator")
62
+ return value
63
+
64
+
65
  # ── Schema ──────────────────────────────────────────────────────────────────
66
 
67
 
 
102
  # Phase 2 implements incremental/hybrid. Phase 1 only honours "full".
103
  scope: str = "full"
104
  max_file_bytes: int = 5 * 1024 * 1024 # 5 MB
105
+ # Top-level filenames under ~/.claude only; paths and traversal are rejected.
106
  top_files: tuple[str, ...] = (
107
  "settings.json",
108
  "skill-manifest.json",
 
137
  raise ValueError(f"retention.keep_daily must be >= 0, got {self.retention.keep_daily}")
138
  if "{timestamp}" not in self.name_format:
139
  raise ValueError(f"name_format must contain '{{timestamp}}', got {self.name_format!r}")
140
+ validated_top = tuple(_validate_top_file(str(name)) for name in self.top_files)
141
  # Silently drop ALWAYS_EXCLUDE names from top_files. frozen
142
  # dataclass requires object.__setattr__ for the rewrite.
143
+ filtered_top = tuple(name for name in validated_top if name not in ALWAYS_EXCLUDE)
 
 
144
  if filtered_top != self.top_files:
145
  object.__setattr__(self, "top_files", filtered_top)
146
 
 
219
  return tuple(out)
220
 
221
 
222
+ def _coerce_user_top_files(raw: Any) -> tuple[str, ...] | None:
223
+ if raw is None:
224
+ return None
225
+ if not isinstance(raw, list):
226
+ _warn_ignored_config("top_files override must be a list")
227
+ return None
228
+ out: list[str] = []
229
+ for entry in raw:
230
+ try:
231
+ out.append(_validate_top_file(str(entry)))
232
+ except ValueError as exc:
233
+ _warn_ignored_config(f"ignoring top_files entry: {exc}")
234
+ return tuple(out)
235
+
236
+
237
+ def _sanitize_user_override(raw: dict[str, Any]) -> dict[str, Any]:
238
+ sanitized = dict(raw)
239
+ if "top_files" in sanitized:
240
+ raw_top_files = sanitized["top_files"]
241
+ top_files = _coerce_user_top_files(raw_top_files)
242
+ if top_files is None:
243
+ sanitized.pop("top_files", None)
244
+ elif not top_files and raw_top_files:
245
+ sanitized.pop("top_files", None)
246
+ else:
247
+ sanitized["top_files"] = list(top_files)
248
+ return sanitized
249
+
250
+
251
+ def _warn_ignored_config(message: str) -> None:
252
+ import sys as _sys
253
+
254
+ print(f"[backup-config] {message}", file=_sys.stderr)
255
+
256
+
257
  def _coerce_retention(raw: Any) -> BackupRetention:
258
  if not isinstance(raw, dict):
259
  return BackupRetention()
 
322
  except Exception:
323
  base_raw = {}
324
 
325
+ merged: dict[str, Any] = _sanitize_user_override(base_raw) if isinstance(base_raw, dict) else {}
326
 
327
  user_override = Path(os.path.expanduser("~/.claude/backup-config.json"))
328
  if user_override.is_file():
329
  try:
330
  user_raw = json.loads(user_override.read_text(encoding="utf-8"))
331
  if isinstance(user_raw, dict):
332
+ _deep_merge(merged, _sanitize_user_override(user_raw))
333
  except (OSError, json.JSONDecodeError):
334
  pass
335
 
src/backup_mirror.py CHANGED
@@ -33,8 +33,9 @@ Commands:
33
  Restore the snapshot over the live tree. Without --dry-run this
34
  overwrites live files; with --dry-run it prints what would change.
35
 
36
- python src/backup_mirror.py prune --keep <N>
37
- Delete all but the N newest snapshots. Legacy mode.
 
38
 
39
  python src/backup_mirror.py prune --policy [--dry-run] [--json]
40
  Apply the configured retention policy (keep_latest + keep_daily).
@@ -645,27 +646,47 @@ def _delete_snapshot_dirs(
645
  backups_dir) or any path that fails the containment check.
646
  """
647
  removed: list[str] = []
648
- for snap in snaps_to_remove:
649
  snap_path = Path(snap.path)
650
- if snap_path.is_symlink() or not _contained(snap_path, backups_dir):
651
- continue
652
  shutil.rmtree(snap_path, ignore_errors=True)
653
  removed.append(snap.snapshot_id)
654
  return removed
655
 
656
 
657
- def prune_snapshots(keep: int, backups_dir: Path | None = None) -> tuple[str, ...]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
658
  """Legacy prune: keep only the ``keep`` newest snapshots.
659
 
660
  Retained for backward compatibility. New callers should prefer
661
  :func:`prune_by_policy`, which honours both ``keep_latest`` and
662
- ``keep_daily`` from the active :class:`BackupRetention`.
 
 
663
  """
664
  if keep < 0:
665
  raise ValueError(f"keep must be >= 0, got {keep}")
666
  backups_dir = backups_dir if backups_dir is not None else BACKUPS_DIR
667
  snaps = list_snapshots(backups_dir)
668
  to_remove = snaps[keep:]
 
 
669
  return tuple(_delete_snapshot_dirs(to_remove, backups_dir))
670
 
671
 
@@ -702,11 +723,18 @@ def prune_by_policy(
702
  snaps = list_snapshots(backups_dir)
703
  plan = plan_prune(snaps, policy, now=now)
704
 
705
- if dry_run:
706
- return plan
707
-
708
  by_id = {s.snapshot_id: s for s in snaps}
709
  to_remove = [by_id[i] for i in plan.delete if i in by_id]
 
 
 
 
 
 
 
 
 
 
710
  removed = _delete_snapshot_dirs(to_remove, backups_dir)
711
  # Any snapshot in plan.delete that we refused to touch (symlink or
712
  # containment failure) stays on disk — surface that honestly by
@@ -916,10 +944,11 @@ def cmd_prune(args: argparse.Namespace) -> int:
916
  if args.keep is None:
917
  print("prune requires either --policy or --keep N", file=sys.stderr)
918
  return 2
919
- removed = prune_snapshots(args.keep)
920
  for r in removed:
921
- print(f"removed {r}")
922
- print(f"kept {args.keep} newest snapshot(s); removed {len(removed)}.")
 
923
  return 0
924
 
925
 
 
33
  Restore the snapshot over the live tree. Without --dry-run this
34
  overwrites live files; with --dry-run it prints what would change.
35
 
36
+ python src/backup_mirror.py prune --keep <N> [--dry-run]
37
+ Delete all but the N newest snapshots. Legacy mode. With
38
+ ``--dry-run`` it prints what would be removed without deleting.
39
 
40
  python src/backup_mirror.py prune --policy [--dry-run] [--json]
41
  Apply the configured retention policy (keep_latest + keep_daily).
 
646
  backups_dir) or any path that fails the containment check.
647
  """
648
  removed: list[str] = []
649
+ for snap in _safe_prune_snapshots(snaps_to_remove, backups_dir):
650
  snap_path = Path(snap.path)
 
 
651
  shutil.rmtree(snap_path, ignore_errors=True)
652
  removed.append(snap.snapshot_id)
653
  return removed
654
 
655
 
656
+ def _safe_prune_snapshots(
657
+ snaps_to_remove: Iterable[SnapshotInfo],
658
+ backups_dir: Path,
659
+ ) -> list[SnapshotInfo]:
660
+ safe: list[SnapshotInfo] = []
661
+ for snap in snaps_to_remove:
662
+ snap_path = Path(snap.path)
663
+ if snap_path.is_symlink() or not _contained(snap_path, backups_dir):
664
+ continue
665
+ safe.append(snap)
666
+ return safe
667
+
668
+
669
+ def prune_snapshots(
670
+ keep: int,
671
+ backups_dir: Path | None = None,
672
+ *,
673
+ dry_run: bool = False,
674
+ ) -> tuple[str, ...]:
675
  """Legacy prune: keep only the ``keep`` newest snapshots.
676
 
677
  Retained for backward compatibility. New callers should prefer
678
  :func:`prune_by_policy`, which honours both ``keep_latest`` and
679
+ ``keep_daily`` from the active :class:`BackupRetention`. When
680
+ ``dry_run`` is true, return the snapshot IDs that would be removed without
681
+ deleting their directories.
682
  """
683
  if keep < 0:
684
  raise ValueError(f"keep must be >= 0, got {keep}")
685
  backups_dir = backups_dir if backups_dir is not None else BACKUPS_DIR
686
  snaps = list_snapshots(backups_dir)
687
  to_remove = snaps[keep:]
688
+ if dry_run:
689
+ return tuple(s.snapshot_id for s in _safe_prune_snapshots(to_remove, backups_dir))
690
  return tuple(_delete_snapshot_dirs(to_remove, backups_dir))
691
 
692
 
 
723
  snaps = list_snapshots(backups_dir)
724
  plan = plan_prune(snaps, policy, now=now)
725
 
 
 
 
726
  by_id = {s.snapshot_id: s for s in snaps}
727
  to_remove = [by_id[i] for i in plan.delete if i in by_id]
728
+ if dry_run:
729
+ safe_delete = {snap.snapshot_id for snap in _safe_prune_snapshots(to_remove, backups_dir)}
730
+ pruned_delete = tuple(i for i in plan.delete if i in safe_delete)
731
+ return RetentionPlan(
732
+ keep=plan.keep,
733
+ delete=pruned_delete,
734
+ protected_by_latest=plan.protected_by_latest,
735
+ protected_by_daily=plan.protected_by_daily,
736
+ )
737
+
738
  removed = _delete_snapshot_dirs(to_remove, backups_dir)
739
  # Any snapshot in plan.delete that we refused to touch (symlink or
740
  # containment failure) stays on disk — surface that honestly by
 
944
  if args.keep is None:
945
  print("prune requires either --policy or --keep N", file=sys.stderr)
946
  return 2
947
+ removed = prune_snapshots(args.keep, dry_run=args.dry_run)
948
  for r in removed:
949
+ print(f"{'would remove' if args.dry_run else 'removed'} {r}")
950
+ action = "would remove" if args.dry_run else "removed"
951
+ print(f"kept {args.keep} newest snapshot(s); {action} {len(removed)}.")
952
  return 0
953
 
954
 
src/ctx/__init__.py CHANGED
@@ -37,7 +37,7 @@ Package layout:
37
  ctx.utils - low-level primitives (safe names, atomic IO)
38
  """
39
 
40
- __version__ = "1.0.20"
41
 
42
 
43
  # Public library surface — anything listed here is safe for third-
 
37
  ctx.utils - low-level primitives (safe names, atomic IO)
38
  """
39
 
40
+ __version__ = "1.0.21"
41
 
42
 
43
  # Public library surface — anything listed here is safe for third-
src/ctx/adapters/claude_code/install/mcp_install.py CHANGED
@@ -446,12 +446,13 @@ def install_mcp(
446
  install_cmd = _safe_manifest_command(fm.get("install_cmd"))
447
  if install_cmd:
448
  skipped_extra["command"] = install_cmd
449
- record_install(
450
- slug,
451
- entity_type="mcp-server",
452
- source="ctx-mcp-install",
453
- extra=skipped_extra,
454
- )
 
455
  return InstallResult(
456
  slug=slug,
457
  status="skipped-existing",
 
446
  install_cmd = _safe_manifest_command(fm.get("install_cmd"))
447
  if install_cmd:
448
  skipped_extra["command"] = install_cmd
449
+ if not dry_run:
450
+ record_install(
451
+ slug,
452
+ entity_type="mcp-server",
453
+ source="ctx-mcp-install",
454
+ extra=skipped_extra,
455
+ )
456
  return InstallResult(
457
  slug=slug,
458
  status="skipped-existing",
src/ctx/adapters/generic/tools/mcp_router.py CHANGED
@@ -47,7 +47,7 @@ import threading
47
  import time
48
  from contextlib import contextmanager
49
  from dataclasses import dataclass, field
50
- from typing import Any, Iterator
51
 
52
  from ctx.adapters.generic.providers.base import ToolDefinition
53
  from ctx.telemetry import (
@@ -57,6 +57,7 @@ from ctx.telemetry import (
57
  telemetry_span,
58
  traceparent_from_span,
59
  )
 
60
 
61
  _logger = logging.getLogger(__name__)
62
 
@@ -88,13 +89,18 @@ _ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
88
  _RESERVED_SERVER_NAMES = frozenset({"ctx"})
89
  _SENSITIVE_ASSIGNMENT_RE = re.compile(
90
  r"(?i)\b([A-Z0-9_-]*(?:API[_-]?KEY|TOKEN|SECRET|PASSWORD|"
91
- r"CREDENTIAL|AUTHORIZATION)[A-Z0-9_-]*)\s*([:=])\s*([^\s]+)"
 
92
  )
93
  _BEARER_RE = re.compile(r"(?i)\bbearer\s+[A-Za-z0-9._~+/=-]{8,}")
94
  _TOKEN_VALUE_RE = re.compile(
95
  r"\b(?:ghp|gho|ghu|ghs|ghr|github_pat|hf|sk|xox[baprs])"
96
  r"[_-]?[A-Za-z0-9_./+=-]{8,}\b"
97
  )
 
 
 
 
98
 
99
 
100
  def _duration_ms(started: float) -> float:
@@ -187,14 +193,25 @@ def _validate_env_name(name: str) -> None:
187
  raise ValueError(f"invalid MCP credential env var name: {name!r}")
188
 
189
 
190
- def _redact_sensitive_text(text: str) -> str:
191
  """Remove likely credential values from diagnostics before retention."""
192
  text = _BEARER_RE.sub("Bearer [REDACTED]", text)
193
  text = _SENSITIVE_ASSIGNMENT_RE.sub(
194
  lambda match: f"{match.group(1)}{match.group(2)}[REDACTED]",
195
  text,
196
  )
197
- return _TOKEN_VALUE_RE.sub("[REDACTED]", text)
 
 
 
 
 
 
 
 
 
 
 
198
 
199
 
200
  def _child_env_for_config(config: "McpServerConfig") -> dict[str, str]:
@@ -206,6 +223,65 @@ def _child_env_for_config(config: "McpServerConfig") -> dict[str, str]:
206
  return env
207
 
208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
  def _popen_process_group_kwargs() -> dict[str, Any]:
210
  if os.name == "nt":
211
  return {"creationflags": getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)}
@@ -282,6 +358,12 @@ class McpServerConfig:
282
  so there is no shell interpolation — a server config cannot inject
283
  shell metacharacters into the spawn call.
284
 
 
 
 
 
 
 
285
  ``env`` is the explicit child overlay. Parent secrets are not
286
  inherited by default; only a small process-basics allowlist
287
  (PATH, temp/home, locale, Windows runtime vars) is passed through.
@@ -299,6 +381,8 @@ class McpServerConfig:
299
  startup_timeout: float = 10.0
300
  request_timeout: float = 30.0
301
  inherit_env: bool = False
 
 
302
 
303
  def __post_init__(self) -> None:
304
  _validate_server_name(self.name)
@@ -337,6 +421,7 @@ class McpClient:
337
  # thread so a chatty server doesn't block the pipe.
338
  self._stderr_lines: list[str] = []
339
  self._stderr_thread: threading.Thread | None = None
 
340
 
341
  # ── lifecycle ──────────────────────────────────────────────────────────
342
 
@@ -347,11 +432,13 @@ class McpClient:
347
 
348
  self._stdout_frames = queue.Queue()
349
  env = _child_env_for_config(self._config)
 
350
 
351
  command = _resolve_executable(self._config.command, env)
 
352
  try:
353
  self._proc = subprocess.Popen(
354
- [command, *self._config.args],
355
  stdin=subprocess.PIPE,
356
  stdout=subprocess.PIPE,
357
  stderr=subprocess.PIPE,
@@ -360,6 +447,7 @@ class McpClient:
360
  **_popen_process_group_kwargs(),
361
  )
362
  except OSError as exc:
 
363
  raise McpServerError(
364
  f"{self._config.name}: failed to start MCP command {self._config.command!r}: {exc}"
365
  ) from exc
@@ -367,7 +455,11 @@ class McpClient:
367
 
368
  # Drain stderr in the background so a verbose server can't fill
369
  # the OS pipe buffer and deadlock us.
370
- self._stderr_thread = threading.Thread(target=self._drain_stderr, daemon=True)
 
 
 
 
371
  self._stderr_thread.start()
372
  self._stdout_thread = threading.Thread(target=self._drain_stdout, daemon=True)
373
  self._stdout_thread.start()
@@ -395,6 +487,7 @@ class McpClient:
395
  proc = self._proc
396
  self._proc = None
397
  if proc is None:
 
398
  return
399
  try:
400
  # Close stdin to signal the server to exit cleanly.
@@ -424,6 +517,7 @@ class McpClient:
424
  thread.join(timeout=0.2)
425
  self._stdout_thread = None
426
  self._stderr_thread = None
 
427
 
428
  def __enter__(self) -> "McpClient":
429
  self.start()
@@ -649,7 +743,7 @@ class McpClient:
649
  finally:
650
  self._stdout_frames.put(None)
651
 
652
- def _drain_stderr(self) -> None:
653
  """Consume stderr in the background; keep the last ~200 lines."""
654
  proc = self._proc
655
  if proc is None or proc.stderr is None:
@@ -659,7 +753,7 @@ class McpClient:
659
  line = raw.decode("utf-8", errors="replace").rstrip()
660
  if not line:
661
  continue
662
- self._stderr_lines.append(_redact_sensitive_text(line))
663
  # Cap memory usage on a chatty server.
664
  if len(self._stderr_lines) > 200:
665
  del self._stderr_lines[:-200]
 
47
  import time
48
  from contextlib import contextmanager
49
  from dataclasses import dataclass, field
50
+ from typing import Any, Iterable, Iterator
51
 
52
  from ctx.adapters.generic.providers.base import ToolDefinition
53
  from ctx.telemetry import (
 
57
  telemetry_span,
58
  traceparent_from_span,
59
  )
60
+ from ctx.utils._secret_scan import find_inline_secret_arg, secret_key_like
61
 
62
  _logger = logging.getLogger(__name__)
63
 
 
89
  _RESERVED_SERVER_NAMES = frozenset({"ctx"})
90
  _SENSITIVE_ASSIGNMENT_RE = re.compile(
91
  r"(?i)\b([A-Z0-9_-]*(?:API[_-]?KEY|TOKEN|SECRET|PASSWORD|"
92
+ r"PASSWD|PRIVATE[_-]?KEY|CREDENTIAL|ACCESS[_-]?KEY|"
93
+ r"CLIENT[_-]?SECRET|AUTHORIZATION|BEARER)[A-Z0-9_-]*)\s*([:=])\s*([^\s]+)"
94
  )
95
  _BEARER_RE = re.compile(r"(?i)\bbearer\s+[A-Za-z0-9._~+/=-]{8,}")
96
  _TOKEN_VALUE_RE = re.compile(
97
  r"\b(?:ghp|gho|ghu|ghs|ghr|github_pat|hf|sk|xox[baprs])"
98
  r"[_-]?[A-Za-z0-9_./+=-]{8,}\b"
99
  )
100
+ _ENV_PLACEHOLDER_RE = re.compile(
101
+ r"\$(?:\{(?P<braced>[A-Za-z_][A-Za-z0-9_]*)\}|(?P<bare>[A-Za-z_][A-Za-z0-9_]*))"
102
+ )
103
+ _MIN_LITERAL_SECRET_LENGTH = 4
104
 
105
 
106
  def _duration_ms(started: float) -> float:
 
193
  raise ValueError(f"invalid MCP credential env var name: {name!r}")
194
 
195
 
196
+ def _redact_sensitive_text(text: str, literal_values: Iterable[str] = ()) -> str:
197
  """Remove likely credential values from diagnostics before retention."""
198
  text = _BEARER_RE.sub("Bearer [REDACTED]", text)
199
  text = _SENSITIVE_ASSIGNMENT_RE.sub(
200
  lambda match: f"{match.group(1)}{match.group(2)}[REDACTED]",
201
  text,
202
  )
203
+ text = _TOKEN_VALUE_RE.sub("[REDACTED]", text)
204
+ for value in sorted(
205
+ {
206
+ value
207
+ for value in literal_values
208
+ if len(value) >= _MIN_LITERAL_SECRET_LENGTH and "[REDACTED]" not in value
209
+ },
210
+ key=len,
211
+ reverse=True,
212
+ ):
213
+ text = text.replace(value, "[REDACTED]")
214
+ return text
215
 
216
 
217
  def _child_env_for_config(config: "McpServerConfig") -> dict[str, str]:
 
223
  return env
224
 
225
 
226
+ def _stderr_redaction_values(config: "McpServerConfig", env: dict[str, str]) -> tuple[str, ...]:
227
+ credential_keys = {key.upper() for key in config.credential_env}
228
+ values = []
229
+ for key, value in env.items():
230
+ if key.upper() in credential_keys or secret_key_like(key):
231
+ values.append(value)
232
+ return tuple(dict.fromkeys(values))
233
+
234
+
235
+ def _env_placeholder_names(value: str) -> tuple[str, ...]:
236
+ names: list[str] = []
237
+ for match in _ENV_PLACEHOLDER_RE.finditer(value):
238
+ name = match.group("braced") or match.group("bare")
239
+ if name is not None:
240
+ names.append(name)
241
+ return tuple(names)
242
+
243
+
244
+ def _is_sensitive_env_reference(config: "McpServerConfig", name: str) -> bool:
245
+ credential_keys = {key.upper() for key in config.credential_env}
246
+ return name.upper() in credential_keys or secret_key_like(name)
247
+
248
+
249
+ def _expand_env_placeholders(value: str, env: dict[str, str]) -> str:
250
+ def replace_match(match: re.Match[str]) -> str:
251
+ name = match.group("braced") or match.group("bare")
252
+ if name is None:
253
+ return match.group(0)
254
+ return env.get(name, match.group(0))
255
+
256
+ return _ENV_PLACEHOLDER_RE.sub(replace_match, value)
257
+
258
+
259
+ def _expand_config_args(config: "McpServerConfig", env: dict[str, str]) -> tuple[str, ...]:
260
+ if not config.expand_argv_env:
261
+ return config.args
262
+ if not config.allow_argv_secret_expansion:
263
+ for arg in config.args:
264
+ for name in _env_placeholder_names(arg):
265
+ if name in env and _is_sensitive_env_reference(config, name):
266
+ raise ValueError(
267
+ f"MCP server {config.name!r} argv references sensitive env var "
268
+ f"{name!r}; pass secrets through the child environment or set "
269
+ "allow_argv_secret_expansion=True only for trusted local servers"
270
+ )
271
+ expanded = tuple(_expand_env_placeholders(arg, env) for arg in config.args)
272
+ if not config.allow_argv_secret_expansion:
273
+ secret_arg = find_inline_secret_arg(list(expanded))
274
+ bearer_arg = next((arg for arg in expanded if _BEARER_RE.search(arg)), None)
275
+ if secret_arg is not None or bearer_arg is not None:
276
+ marker = secret_arg if secret_arg is not None else "Bearer"
277
+ raise ValueError(
278
+ f"MCP server {config.name!r} argv expands an env var into secret-looking "
279
+ f"argument {marker!r}; pass secrets through the child environment or set "
280
+ "allow_argv_secret_expansion=True only for trusted local servers"
281
+ )
282
+ return expanded
283
+
284
+
285
  def _popen_process_group_kwargs() -> dict[str, Any]:
286
  if os.name == "nt":
287
  return {"creationflags": getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)}
 
358
  so there is no shell interpolation — a server config cannot inject
359
  shell metacharacters into the spawn call.
360
 
361
+ ``args`` are literal by default. Set ``expand_argv_env=True`` to expand
362
+ ``$ENVVAR`` or ``${ENVVAR}`` placeholders from the final child environment
363
+ immediately before spawn. Sensitive env vars are not expanded into argv
364
+ unless ``allow_argv_secret_expansion`` is explicitly enabled for a trusted
365
+ local server.
366
+
367
  ``env`` is the explicit child overlay. Parent secrets are not
368
  inherited by default; only a small process-basics allowlist
369
  (PATH, temp/home, locale, Windows runtime vars) is passed through.
 
381
  startup_timeout: float = 10.0
382
  request_timeout: float = 30.0
383
  inherit_env: bool = False
384
+ allow_argv_secret_expansion: bool = False
385
+ expand_argv_env: bool = False
386
 
387
  def __post_init__(self) -> None:
388
  _validate_server_name(self.name)
 
421
  # thread so a chatty server doesn't block the pipe.
422
  self._stderr_lines: list[str] = []
423
  self._stderr_thread: threading.Thread | None = None
424
+ self._stderr_redaction_values: tuple[str, ...] = ()
425
 
426
  # ── lifecycle ──────────────────────────────────────────────────────────
427
 
 
432
 
433
  self._stdout_frames = queue.Queue()
434
  env = _child_env_for_config(self._config)
435
+ self._stderr_redaction_values = _stderr_redaction_values(self._config, env)
436
 
437
  command = _resolve_executable(self._config.command, env)
438
+ args = _expand_config_args(self._config, env)
439
  try:
440
  self._proc = subprocess.Popen(
441
+ [command, *args],
442
  stdin=subprocess.PIPE,
443
  stdout=subprocess.PIPE,
444
  stderr=subprocess.PIPE,
 
447
  **_popen_process_group_kwargs(),
448
  )
449
  except OSError as exc:
450
+ self._stderr_redaction_values = ()
451
  raise McpServerError(
452
  f"{self._config.name}: failed to start MCP command {self._config.command!r}: {exc}"
453
  ) from exc
 
455
 
456
  # Drain stderr in the background so a verbose server can't fill
457
  # the OS pipe buffer and deadlock us.
458
+ self._stderr_thread = threading.Thread(
459
+ target=self._drain_stderr,
460
+ args=(self._stderr_redaction_values,),
461
+ daemon=True,
462
+ )
463
  self._stderr_thread.start()
464
  self._stdout_thread = threading.Thread(target=self._drain_stdout, daemon=True)
465
  self._stdout_thread.start()
 
487
  proc = self._proc
488
  self._proc = None
489
  if proc is None:
490
+ self._stderr_redaction_values = ()
491
  return
492
  try:
493
  # Close stdin to signal the server to exit cleanly.
 
517
  thread.join(timeout=0.2)
518
  self._stdout_thread = None
519
  self._stderr_thread = None
520
+ self._stderr_redaction_values = ()
521
 
522
  def __enter__(self) -> "McpClient":
523
  self.start()
 
743
  finally:
744
  self._stdout_frames.put(None)
745
 
746
+ def _drain_stderr(self, redaction_values: tuple[str, ...]) -> None:
747
  """Consume stderr in the background; keep the last ~200 lines."""
748
  proc = self._proc
749
  if proc is None or proc.stderr is None:
 
753
  line = raw.decode("utf-8", errors="replace").rstrip()
754
  if not line:
755
  continue
756
+ self._stderr_lines.append(_redact_sensitive_text(line, redaction_values))
757
  # Cap memory usage on a chatty server.
758
  if len(self._stderr_lines) > 200:
759
  del self._stderr_lines[:-200]
src/ctx/cli/run.py CHANGED
@@ -55,6 +55,7 @@ from ctx.adapters.generic.state import (
55
  )
56
  from ctx.adapters.generic.tools import McpRouter, McpServerConfig
57
  from ctx.telemetry import record_event, record_exception, telemetry_span
 
58
 
59
 
60
  _logger = logging.getLogger(__name__)
@@ -253,7 +254,9 @@ def _parse_mcp_spec(spec: str) -> McpServerConfig:
253
  name:<shell-invocation>
254
  Example: filesystem:npx -y @modelcontextprotocol/server-filesystem /data
255
  The part before the colon is the name; the part after is the
256
- command + args (split on whitespace, no shell).
 
 
257
 
258
  name (bare)
259
  Names that match a known preset get a default invocation.
@@ -279,6 +282,13 @@ def _parse_mcp_spec(spec: str) -> McpServerConfig:
279
  raise SystemExit(f"malformed --mcp spec: {spec!r}: {exc}") from exc
280
  if not parts:
281
  raise SystemExit(f"malformed --mcp spec: {spec!r}")
 
 
 
 
 
 
 
282
  if name == "filesystem" and len(parts) == 1:
283
  filesystem_preset = _MCP_PRESETS["filesystem"]
284
  return McpServerConfig(
@@ -760,7 +770,8 @@ def _build_parser() -> argparse.ArgumentParser:
760
  metavar="NAME[:COMMAND]",
761
  help=(
762
  "Attach an MCP server. Repeatable. Forms: "
763
- "'filesystem' (preset) or 'name:npx -y ...' (explicit)."
 
764
  ),
765
  )
766
  r.add_argument(
 
55
  )
56
  from ctx.adapters.generic.tools import McpRouter, McpServerConfig
57
  from ctx.telemetry import record_event, record_exception, telemetry_span
58
+ from ctx.utils._secret_scan import find_inline_secret_arg
59
 
60
 
61
  _logger = logging.getLogger(__name__)
 
254
  name:<shell-invocation>
255
  Example: filesystem:npx -y @modelcontextprotocol/server-filesystem /data
256
  The part before the colon is the name; the part after is the
257
+ command + args (split on whitespace, no shell). Secret-looking
258
+ inline args are rejected; pass credentials through the child
259
+ environment with --mcp-env.
260
 
261
  name (bare)
262
  Names that match a known preset get a default invocation.
 
282
  raise SystemExit(f"malformed --mcp spec: {spec!r}: {exc}") from exc
283
  if not parts:
284
  raise SystemExit(f"malformed --mcp spec: {spec!r}")
285
+ secret_arg = find_inline_secret_arg(parts)
286
+ if secret_arg is not None:
287
+ raise SystemExit(
288
+ f"--mcp inline command for server {name!r} contains secret-looking "
289
+ f"argv {secret_arg!r}; use --mcp-env {name}:ENVVAR and configure "
290
+ "the server to read that environment variable instead"
291
+ )
292
  if name == "filesystem" and len(parts) == 1:
293
  filesystem_preset = _MCP_PRESETS["filesystem"]
294
  return McpServerConfig(
 
770
  metavar="NAME[:COMMAND]",
771
  help=(
772
  "Attach an MCP server. Repeatable. Forms: "
773
+ "'filesystem' (preset) or 'name:npx -y ...' (explicit; "
774
+ "secret-looking argv rejected)."
775
  ),
776
  )
777
  r.add_argument(
src/ctx/core/wiki/wiki_queue_worker.py CHANGED
@@ -3,6 +3,7 @@
3
  from __future__ import annotations
4
 
5
  import argparse
 
6
  import os
7
  import socket
8
  import subprocess
@@ -21,7 +22,12 @@ from ctx.core.graph.graph_packs import (
21
  )
22
  from ctx.core.graph.graph_store import ensure_graph_store
23
  from ctx.core.graph.incremental_attach import attach_entity
24
- from ctx.core.wiki.artifact_promotion import promote_staged_artifact
 
 
 
 
 
25
  from ctx.core.wiki import wiki_queue
26
  from ctx.core.wiki.pack_compaction import (
27
  compact_active_pack_sets,
@@ -41,6 +47,30 @@ _ENTITY_SUBJECT_TYPES = {
41
  }
42
  _DEFAULT_ATTACH_MIN_FINAL_WEIGHT = 0.03
43
  _VECTOR_INDEX_META_NAME = "vector-index.meta.json"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  MaintenanceHandler = Callable[[Path, dict[str, Any]], str]
45
 
46
 
@@ -556,21 +586,266 @@ def _handle_tar_refresh(_wiki_path: Path, payload: dict[str, Any]) -> str:
556
  return "tar refresh completed"
557
 
558
 
559
- def _handle_artifact_promotion(_wiki_path: Path, payload: dict[str, Any]) -> str:
560
- staged = Path(_required_payload_string(payload, "staged_path"))
561
- target = Path(_required_payload_string(payload, "target_path"))
 
 
 
562
  validator = payload.get("validator")
563
- validate = None
564
- if validator == "wiki-tar":
565
- from import_skills_sh_catalog import _validate_wiki_tarball_candidate # noqa: PLC0415
566
-
567
- validate = _validate_wiki_tarball_candidate
568
- elif validator not in (None, "", "none"):
569
  raise ValueError(f"unsupported artifact validator: {validator}")
 
570
  result = promote_staged_artifact(staged, target, validate=validate)
571
  return f"promoted artifact to {result.target}"
572
 
573
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
574
  def _handle_pack_compaction(wiki_path: Path, payload: dict[str, Any]) -> str:
575
  threshold = _optional_payload_int(
576
  payload,
 
3
  from __future__ import annotations
4
 
5
  import argparse
6
+ import json
7
  import os
8
  import socket
9
  import subprocess
 
22
  )
23
  from ctx.core.graph.graph_store import ensure_graph_store
24
  from ctx.core.graph.incremental_attach import attach_entity
25
+ from ctx.core.wiki.artifact_promotion import (
26
+ ArtifactValidator,
27
+ promote_staged_artifact,
28
+ validate_gzip_json_artifact,
29
+ validate_json_artifact,
30
+ )
31
  from ctx.core.wiki import wiki_queue
32
  from ctx.core.wiki.pack_compaction import (
33
  compact_active_pack_sets,
 
47
  }
48
  _DEFAULT_ATTACH_MIN_FINAL_WEIGHT = 0.03
49
  _VECTOR_INDEX_META_NAME = "vector-index.meta.json"
50
+ _WIKI_GRAPH_PROMOTION_TARGET_NAMES = frozenset(
51
+ {
52
+ "communities.json",
53
+ "graph-delta.json",
54
+ "graph-export-manifest.json",
55
+ "graph-report.md",
56
+ "graph.json",
57
+ }
58
+ )
59
+ _REPO_GRAPH_PROMOTION_TARGET_NAMES = frozenset(
60
+ {
61
+ "communities.json",
62
+ "dedup-report.json",
63
+ "dedup-report.md",
64
+ "entity-overlays.jsonl",
65
+ "skills-sh-catalog.json.gz",
66
+ "skillspector-audit.jsonl.gz",
67
+ "tag-backfill.json",
68
+ "tag-backfill.md",
69
+ "wiki-graph-runtime.tar.gz",
70
+ "wiki-graph-stats.json",
71
+ "wiki-graph.tar.gz",
72
+ }
73
+ )
74
  MaintenanceHandler = Callable[[Path, dict[str, Any]], str]
75
 
76
 
 
586
  return "tar refresh completed"
587
 
588
 
589
+ def _handle_artifact_promotion(wiki_path: Path, payload: dict[str, Any]) -> str:
590
+ staged, target = _resolve_artifact_promotion_paths(
591
+ wiki_path,
592
+ _required_payload_string(payload, "staged_path"),
593
+ _required_payload_string(payload, "target_path"),
594
+ )
595
  validator = payload.get("validator")
596
+ if validator not in (None, "", "none", "wiki-tar"):
 
 
 
 
 
597
  raise ValueError(f"unsupported artifact validator: {validator}")
598
+ validate = _artifact_validator_for_target(target)
599
  result = promote_staged_artifact(staged, target, validate=validate)
600
  return f"promoted artifact to {result.target}"
601
 
602
 
603
+ def _artifact_validator_for_target(target: Path) -> ArtifactValidator | None:
604
+ name = target.name
605
+ if name == "wiki-graph.tar.gz":
606
+ from import_skills_sh_catalog import _validate_wiki_tarball_candidate # noqa: PLC0415
607
+
608
+ return _validate_wiki_tarball_candidate
609
+ if name == "wiki-graph-runtime.tar.gz":
610
+ return _validate_runtime_graph_tar_gz_artifact
611
+ if name.endswith(".jsonl.gz"):
612
+ return _validate_gzip_jsonl_artifact
613
+ if name.endswith(".json.gz"):
614
+ return validate_gzip_json_artifact
615
+ if name.endswith(".jsonl"):
616
+ return _validate_jsonl_artifact
617
+ if name == "graph.json":
618
+ return _validate_graph_json_artifact
619
+ if name == "graph-delta.json":
620
+ return _validate_graph_delta_json_artifact
621
+ if name == "communities.json":
622
+ return _validate_communities_json_artifact
623
+ if name == "graph-export-manifest.json":
624
+ return _validate_graph_export_manifest_artifact
625
+ if name.endswith(".json"):
626
+ return validate_json_artifact
627
+ return None
628
+
629
+
630
+ def _validate_tar_gz_artifact(path: Path) -> None:
631
+ import tarfile
632
+
633
+ try:
634
+ with tarfile.open(path, "r:gz"):
635
+ pass
636
+ except tarfile.TarError as exc:
637
+ raise ValueError(f"invalid tar.gz artifact: {path}") from exc
638
+
639
+
640
+ def _validate_runtime_graph_tar_gz_artifact(path: Path) -> None:
641
+ import tarfile
642
+
643
+ from validate_graph_artifacts import ( # noqa: PLC0415
644
+ GraphArtifactError,
645
+ validate_runtime_graph_archive,
646
+ )
647
+
648
+ _validate_tar_gz_artifact(path)
649
+ try:
650
+ validate_runtime_graph_archive(path)
651
+ except (GraphArtifactError, OSError, tarfile.TarError) as exc:
652
+ raise ValueError(f"invalid runtime graph artifact: {path}: {exc}") from exc
653
+
654
+
655
+ def _validate_jsonl_artifact(path: Path) -> None:
656
+ try:
657
+ with path.open("rt", encoding="utf-8") as fh:
658
+ for line in fh:
659
+ if line.strip():
660
+ json.loads(line)
661
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
662
+ raise ValueError(f"invalid JSONL artifact: {path}") from exc
663
+
664
+
665
+ def _validate_gzip_jsonl_artifact(path: Path) -> None:
666
+ import gzip
667
+
668
+ try:
669
+ with gzip.open(path, "rt", encoding="utf-8") as fh:
670
+ for line in fh:
671
+ if line.strip():
672
+ json.loads(line)
673
+ except (OSError, EOFError, UnicodeDecodeError, json.JSONDecodeError) as exc:
674
+ raise ValueError(f"invalid gzip JSONL artifact: {path}") from exc
675
+
676
+
677
+ def _read_json_object_artifact(path: Path) -> dict[str, Any]:
678
+ try:
679
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
680
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
681
+ raise ValueError(f"invalid JSON artifact: {path}") from exc
682
+ if not isinstance(data, dict):
683
+ raise ValueError(f"invalid JSON artifact: {path} must contain an object")
684
+ return data
685
+
686
+
687
+ def _validate_graph_json_artifact(path: Path) -> None:
688
+ data = _read_json_object_artifact(path)
689
+ if not isinstance(data.get("nodes"), list):
690
+ raise ValueError(f"invalid graph.json artifact: {path} missing nodes list")
691
+ if not isinstance(data.get("edges"), list):
692
+ raise ValueError(f"invalid graph.json artifact: {path} missing edges list")
693
+ if not isinstance(data.get("graph"), dict):
694
+ raise ValueError(f"invalid graph.json artifact: {path} missing graph object")
695
+
696
+
697
+ def _validate_graph_delta_json_artifact(path: Path) -> None:
698
+ data = _read_json_object_artifact(path)
699
+ if data.get("version") != 1:
700
+ raise ValueError(f"invalid graph-delta.json artifact: {path} version must be 1")
701
+ if not isinstance(data.get("full_rebuild"), bool):
702
+ raise ValueError(f"invalid graph-delta.json artifact: {path} missing full_rebuild bool")
703
+ if not isinstance(data.get("export_id"), str) or not data["export_id"].strip():
704
+ raise ValueError(f"invalid graph-delta.json artifact: {path} missing export_id")
705
+ if data["full_rebuild"]:
706
+ for key in ("node_count", "edge_count"):
707
+ if isinstance(data.get(key), bool) or not isinstance(data.get(key), int):
708
+ raise ValueError(f"invalid graph-delta.json artifact: {path} missing {key} int")
709
+ else:
710
+ if not isinstance(data.get("nodes"), list):
711
+ raise ValueError(f"invalid graph-delta.json artifact: {path} missing nodes list")
712
+ if not isinstance(data.get("edges"), list):
713
+ raise ValueError(f"invalid graph-delta.json artifact: {path} missing edges list")
714
+
715
+
716
+ def _validate_communities_json_artifact(path: Path) -> None:
717
+ data = _read_json_object_artifact(path)
718
+ if not isinstance(data.get("export_id"), str) or not data["export_id"].strip():
719
+ raise ValueError(f"invalid communities.json artifact: {path} missing export_id")
720
+ if not isinstance(data.get("communities"), dict):
721
+ raise ValueError(f"invalid communities.json artifact: {path} missing communities object")
722
+ if isinstance(data.get("total_communities"), bool) or not isinstance(
723
+ data.get("total_communities"), int
724
+ ):
725
+ raise ValueError(f"invalid communities.json artifact: {path} missing total_communities int")
726
+
727
+
728
+ def _validate_graph_export_manifest_artifact(path: Path) -> None:
729
+ data = _read_json_object_artifact(path)
730
+ if data.get("version") != 1:
731
+ raise ValueError(f"invalid graph-export-manifest artifact: {path} version must be 1")
732
+ if not isinstance(data.get("export_id"), str) or not data["export_id"].strip():
733
+ raise ValueError(f"invalid graph-export-manifest artifact: {path} missing export_id")
734
+ artifacts = data.get("artifacts")
735
+ if not isinstance(artifacts, dict):
736
+ raise ValueError(f"invalid graph-export-manifest artifact: {path} missing artifacts object")
737
+ expected_artifacts = {
738
+ "delta": "graph-delta.json",
739
+ "communities": "communities.json",
740
+ "report": "graph-report.md",
741
+ }
742
+ if set(artifacts) != {"graph", *expected_artifacts}:
743
+ raise ValueError(f"invalid graph-export-manifest artifact: {path} invalid artifacts map")
744
+ if artifacts.get("graph") not in {"graph.json", "packs"}:
745
+ raise ValueError(f"invalid graph-export-manifest artifact: {path} invalid graph artifact")
746
+ for key, expected in expected_artifacts.items():
747
+ if artifacts.get(key) != expected:
748
+ raise ValueError(
749
+ f"invalid graph-export-manifest artifact: {path} invalid artifacts map"
750
+ )
751
+ counts = data.get("counts")
752
+ if not isinstance(counts, dict):
753
+ raise ValueError(f"invalid graph-export-manifest artifact: {path} missing counts object")
754
+ for key in ("nodes", "edges", "communities"):
755
+ if isinstance(counts.get(key), bool) or not isinstance(counts.get(key), int):
756
+ raise ValueError(f"invalid graph-export-manifest artifact: {path} missing {key} count")
757
+
758
+
759
+ def _resolve_artifact_promotion_paths(
760
+ wiki_path: Path,
761
+ raw_staged_path: str,
762
+ raw_target_path: str,
763
+ ) -> tuple[Path, Path]:
764
+ wiki_root = Path(wiki_path).expanduser().resolve()
765
+ repo_root = _source_root()
766
+ target = _resolve_artifact_target_path(raw_target_path, wiki_root, repo_root)
767
+ staged = _resolve_staged_artifact_path(raw_staged_path, target, wiki_root, repo_root)
768
+ expected_staged = target.with_name(f"{target.name}.staged")
769
+ if staged != expected_staged:
770
+ raise ValueError(
771
+ f"artifact promotion staged_path must be the target sibling {expected_staged}"
772
+ )
773
+ reject_symlink_path(staged)
774
+ reject_symlink_path(target)
775
+ return staged, target
776
+
777
+
778
+ def _resolve_artifact_target_path(
779
+ raw_target_path: str,
780
+ wiki_root: Path,
781
+ repo_root: Path | None,
782
+ ) -> Path:
783
+ bases = (wiki_root,) if repo_root is None else (wiki_root, repo_root)
784
+ for base in bases:
785
+ target = _resolve_payload_path(raw_target_path, base)
786
+ if _is_allowed_artifact_target(target, wiki_root, repo_root):
787
+ return target
788
+ target = _resolve_payload_path(raw_target_path, wiki_root)
789
+ raise ValueError(f"artifact promotion target_path is not an allowed artifact target: {target}")
790
+
791
+
792
+ def _resolve_staged_artifact_path(
793
+ raw_staged_path: str,
794
+ target: Path,
795
+ wiki_root: Path,
796
+ repo_root: Path | None,
797
+ ) -> Path:
798
+ path = Path(raw_staged_path).expanduser()
799
+ if path.is_absolute():
800
+ return path.resolve()
801
+ expected_staged = target.with_name(f"{target.name}.staged")
802
+ bases = (
803
+ (target.parent, wiki_root) if repo_root is None else (target.parent, wiki_root, repo_root)
804
+ )
805
+ for base in bases:
806
+ staged = (base / path).resolve()
807
+ if staged == expected_staged:
808
+ return staged
809
+ return (wiki_root / path).resolve()
810
+
811
+
812
+ def _resolve_payload_path(raw_path: str, base: Path) -> Path:
813
+ path = Path(raw_path).expanduser()
814
+ if path.is_absolute():
815
+ return path.resolve()
816
+ return (base / path).resolve()
817
+
818
+
819
+ def _is_allowed_artifact_target(target: Path, wiki_root: Path, repo_root: Path | None) -> bool:
820
+ if target.parent == wiki_root / "graphify-out":
821
+ return target.name in _WIKI_GRAPH_PROMOTION_TARGET_NAMES
822
+ if repo_root is not None and target.parent == repo_root / "graph":
823
+ return target.name in _REPO_GRAPH_PROMOTION_TARGET_NAMES
824
+ return False
825
+
826
+
827
+ def _source_root() -> Path | None:
828
+ source = Path(__file__).resolve()
829
+ for parent in source.parents:
830
+ if _is_ctx_source_root(parent, source):
831
+ return parent
832
+ return None
833
+
834
+
835
+ def _is_ctx_source_root(parent: Path, source: Path) -> bool:
836
+ pyproject = parent / "pyproject.toml"
837
+ repo_source = parent / "src" / "ctx" / "core" / "wiki" / "wiki_queue_worker.py"
838
+ if not pyproject.is_file() or not repo_source.is_file():
839
+ return False
840
+ try:
841
+ return (
842
+ 'name = "claude-ctx"' in pyproject.read_text(encoding="utf-8")
843
+ and repo_source.resolve() == source
844
+ )
845
+ except OSError:
846
+ return False
847
+
848
+
849
  def _handle_pack_compaction(wiki_path: Path, payload: dict[str, Any]) -> str:
850
  threshold = _optional_payload_int(
851
  payload,
src/ctx/dashboard_entities.py CHANGED
@@ -24,6 +24,7 @@ class EntityCrudDeps:
24
  wiki_entity_target_path: Callable[[str, str], Path]
25
  wiki_entity_path: Callable[[str, str | None], Path | None]
26
  iter_wiki_entity_paths: Callable[[str | None], list[tuple[str, str, Path]]]
 
27
  read_manifest: Callable[[], dict[str, Any]]
28
  perform_unload: Callable[[str, str], tuple[bool, str]]
29
  queue_entity_refresh: Callable[[str, str, Path, str, str], None]
@@ -270,12 +271,14 @@ def search_wiki_entities(
270
  if isinstance(detail, dict):
271
  frontmatter = detail.get("frontmatter")
272
  body = str(detail.get("body") or "")[:4096]
 
273
  else:
274
  try:
275
  head = path.read_text(encoding="utf-8", errors="replace")[:4096]
276
  except OSError:
277
  continue
278
  frontmatter, body = deps.parse_frontmatter(head)
 
279
  if not isinstance(frontmatter, dict):
280
  frontmatter = {}
281
  tags = deps.frontmatter_tags(frontmatter.get("tags", ""))
@@ -297,7 +300,7 @@ def search_wiki_entities(
297
  "title": title,
298
  "description": description,
299
  "tags": tags[:12],
300
- "path": str(path),
301
  "href": deps.entity_wiki_href(slug, current_type),
302
  }
303
  )
 
24
  wiki_entity_target_path: Callable[[str, str], Path]
25
  wiki_entity_path: Callable[[str, str | None], Path | None]
26
  iter_wiki_entity_paths: Callable[[str | None], list[tuple[str, str, Path]]]
27
+ wiki_relative_path: Callable[[Path], str | None]
28
  read_manifest: Callable[[], dict[str, Any]]
29
  perform_unload: Callable[[str, str], tuple[bool, str]]
30
  queue_entity_refresh: Callable[[str, str, Path, str, str], None]
 
271
  if isinstance(detail, dict):
272
  frontmatter = detail.get("frontmatter")
273
  body = str(detail.get("body") or "")[:4096]
274
+ relpath = str(detail.get("path") or "")
275
  else:
276
  try:
277
  head = path.read_text(encoding="utf-8", errors="replace")[:4096]
278
  except OSError:
279
  continue
280
  frontmatter, body = deps.parse_frontmatter(head)
281
+ relpath = deps.wiki_relative_path(path) or ""
282
  if not isinstance(frontmatter, dict):
283
  frontmatter = {}
284
  tags = deps.frontmatter_tags(frontmatter.get("tags", ""))
 
300
  "title": title,
301
  "description": description,
302
  "tags": tags[:12],
303
+ "path": relpath,
304
  "href": deps.entity_wiki_href(slug, current_type),
305
  }
306
  )
src/ctx/monitor/compat.py CHANGED
@@ -237,6 +237,7 @@ _iter_wiki_entity_paths = _wiki_call(_wiki_service.iter_entity_paths)
237
  _wiki_entity_detail = _wiki_call(_wiki_service.entity_detail)
238
  _wiki_pack_entity_from_relpath = _wiki_service.pack_entity_from_relpath
239
  _read_wiki_entity_text = _wiki_call(_wiki_service.read_entity_text)
 
240
 
241
 
242
  def _search_wiki_entities(
@@ -311,6 +312,7 @@ def _entity_crud_deps() -> dashboard_entities.EntityCrudDeps:
311
  wiki_entity_target_path=_wiki_entity_target_path,
312
  wiki_entity_path=_wiki_entity_path,
313
  iter_wiki_entity_paths=_iter_wiki_entity_paths,
 
314
  read_manifest=_read_manifest,
315
  perform_unload=_perform_unload,
316
  queue_entity_refresh=lambda entity_type, slug, entity_path, content, action: (
 
237
  _wiki_entity_detail = _wiki_call(_wiki_service.entity_detail)
238
  _wiki_pack_entity_from_relpath = _wiki_service.pack_entity_from_relpath
239
  _read_wiki_entity_text = _wiki_call(_wiki_service.read_entity_text)
240
+ _wiki_relative_path = _wiki_call(_wiki_service.wiki_relative_path)
241
 
242
 
243
  def _search_wiki_entities(
 
312
  wiki_entity_target_path=_wiki_entity_target_path,
313
  wiki_entity_path=_wiki_entity_path,
314
  iter_wiki_entity_paths=_iter_wiki_entity_paths,
315
+ wiki_relative_path=_wiki_relative_path,
316
  read_manifest=_read_manifest,
317
  perform_unload=_perform_unload,
318
  queue_entity_refresh=lambda entity_type, slug, entity_path, content, action: (
src/ctx/monitor/services/wiki.py CHANGED
@@ -214,7 +214,7 @@ def entity_detail(
214
  return {
215
  "slug": slug,
216
  "type": detected_type,
217
- "path": str(path),
218
  "frontmatter": frontmatter,
219
  "body": body,
220
  }
 
214
  return {
215
  "slug": slug,
216
  "type": detected_type,
217
+ "path": wiki_relative_path(wiki_dir, path) or "",
218
  "frontmatter": frontmatter,
219
  "body": body,
220
  }