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

Sync ctx 711582e (part 3)

Browse files

GitHub commit: 711582e373fea0c43204213279f9ebd5c8937f26

src/ctx/utils/_secret_scan.py CHANGED
@@ -34,6 +34,9 @@ TOKEN_VALUE_PATTERNS: tuple[re.Pattern[str], ...] = (
34
  re.compile(r"\bsk-[A-Za-z0-9_-]{20,}\b"),
35
  re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{20,}\b"),
36
  )
 
 
 
37
 
38
 
39
  def secret_key_like(key: str) -> bool:
@@ -68,6 +71,35 @@ def _value_has_token_pattern(value: str) -> bool:
68
  return any(pattern.search(value) for pattern in TOKEN_VALUE_PATTERNS)
69
 
70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  def find_inline_secret(obj: object, *, path: str = "") -> str | None:
72
  """Return the first path that appears to contain an inline secret."""
73
  if isinstance(obj, dict):
@@ -95,13 +127,21 @@ def find_inline_secret(obj: object, *, path: str = "") -> str | None:
95
 
96
  def find_inline_secret_arg(tokens: list[str]) -> str | None:
97
  for token in tokens:
98
- assignment = SECRET_ASSIGNMENT_RE.search(token)
99
- if assignment and not placeholder_secret_value(assignment.group(2)):
100
- return assignment.group(1)
101
  if token.startswith("--") and "=" in token:
102
  key, value = token.split("=", 1)
103
- if secret_key_like(key) and not placeholder_secret_value(value):
104
- return key
 
 
 
 
 
 
 
 
 
 
 
105
 
106
  for index, token in enumerate(tokens[:-1]):
107
  if not token.startswith("-"):
@@ -113,6 +153,7 @@ def find_inline_secret_arg(tokens: list[str]) -> str | None:
113
  and value
114
  and not value.startswith("-")
115
  and not placeholder_secret_value(value)
 
116
  ):
117
  return token
118
 
 
34
  re.compile(r"\bsk-[A-Za-z0-9_-]{20,}\b"),
35
  re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{20,}\b"),
36
  )
37
+ ENV_VAR_NAME_RE = re.compile(r"[A-Z_][A-Z0-9_]*")
38
+ HIGH_ENTROPY_ENV_LITERAL_RE = re.compile(r"(?=.*[A-Z])(?=.*\d)[A-Z0-9]{16,}")
39
+ PATH_SHAPED_VALUE_RE = re.compile(r"(?:^file://|^[A-Za-z]:[\\/]|^~?[\\/]|^\.\.?[\\/]|[\\/])")
40
 
41
 
42
  def secret_key_like(key: str) -> bool:
 
71
  return any(pattern.search(value) for pattern in TOKEN_VALUE_PATTERNS)
72
 
73
 
74
+ def _looks_like_env_secret_literal(value: str) -> bool:
75
+ stripped = value.strip()
76
+ return "_" not in stripped and HIGH_ENTROPY_ENV_LITERAL_RE.fullmatch(stripped) is not None
77
+
78
+
79
+ def _secret_arg_indirection_kind(key: str) -> str | None:
80
+ normalized = re.sub(r"[^a-z0-9]+", "_", key.lstrip("-").lower()).strip("_")
81
+ for kind in ("file", "path", "env", "var"):
82
+ if normalized.endswith(f"_{kind}"):
83
+ return kind
84
+ return None
85
+
86
+
87
+ def _secret_arg_allows_indirection(key: str, value: str) -> bool:
88
+ kind = _secret_arg_indirection_kind(key)
89
+ stripped = value.strip()
90
+ if kind in {"file", "path"}:
91
+ return (
92
+ placeholder_secret_value(stripped) or PATH_SHAPED_VALUE_RE.search(stripped) is not None
93
+ )
94
+ if kind in {"env", "var"}:
95
+ return placeholder_secret_value(stripped) or (
96
+ not _value_has_token_pattern(stripped)
97
+ and not _looks_like_env_secret_literal(stripped)
98
+ and ENV_VAR_NAME_RE.fullmatch(stripped) is not None
99
+ )
100
+ return False
101
+
102
+
103
  def find_inline_secret(obj: object, *, path: str = "") -> str | None:
104
  """Return the first path that appears to contain an inline secret."""
105
  if isinstance(obj, dict):
 
127
 
128
  def find_inline_secret_arg(tokens: list[str]) -> str | None:
129
  for token in tokens:
 
 
 
130
  if token.startswith("--") and "=" in token:
131
  key, value = token.split("=", 1)
132
+ if secret_key_like(key):
133
+ if not placeholder_secret_value(value) and not _secret_arg_allows_indirection(
134
+ key, value
135
+ ):
136
+ return key
137
+ continue
138
+ assignment = SECRET_ASSIGNMENT_RE.search(token)
139
+ if (
140
+ assignment
141
+ and not placeholder_secret_value(assignment.group(2))
142
+ and not _secret_arg_allows_indirection(assignment.group(1), assignment.group(2))
143
+ ):
144
+ return assignment.group(1)
145
 
146
  for index, token in enumerate(tokens[:-1]):
147
  if not token.startswith("-"):
 
153
  and value
154
  and not value.startswith("-")
155
  and not placeholder_secret_value(value)
156
+ and not _secret_arg_allows_indirection(token, value)
157
  ):
158
  return token
159
 
src/ctx_init.py CHANGED
@@ -232,8 +232,8 @@ _GRAPH_ARCHIVE_NAMES = {
232
  "full": _GRAPH_ARCHIVE_NAME,
233
  }
234
  _GRAPH_ARCHIVE_SHA256 = {
235
- "runtime": "993fc08377fdb09edcff4414c59b10fc121189b4a161bf796e3f8f6600907bb1",
236
- "full": "d051d4f21208abe3e73975a9c30650150138d88919c27979d725be936a6ea10a",
237
  }
238
  _GRAPH_RELEASE_URL = "https://github.com/stevesolun/ctx/releases/download/v{version}/{archive_name}"
239
  _GRAPH_REQUIRED_FILES = frozenset(
 
232
  "full": _GRAPH_ARCHIVE_NAME,
233
  }
234
  _GRAPH_ARCHIVE_SHA256 = {
235
+ "runtime": "d4a39836aab5f558b546842580b2e20c523b9a9ab901ed681f84c09b5c4d6515",
236
+ "full": "2ce8a945c17a7345df9d27d8f101319a9f963b0fc85d399f104630bc06a7c4a0",
237
  }
238
  _GRAPH_RELEASE_URL = "https://github.com/stevesolun/ctx/releases/download/v{version}/{archive_name}"
239
  _GRAPH_REQUIRED_FILES = frozenset(
src/mcp_add.py CHANGED
@@ -11,10 +11,10 @@ Usage
11
  # Single record from JSON file
12
  ctx-mcp-add --from-json /path/to/record.json
13
 
14
- # JSONL from file (one JSON object per line)
15
  ctx-mcp-add --from-jsonl /path/to/records.jsonl
16
 
17
- # JSONL from stdin
18
  ctx-mcp-add --from-stdin
19
 
20
  [--dry-run] [--wiki PATH] [--skip-existing]
@@ -25,6 +25,7 @@ import json
25
  import os
26
  import re
27
  import sys
 
28
  from dataclasses import replace
29
  from datetime import datetime, timezone
30
  from pathlib import Path
@@ -605,15 +606,16 @@ def add_mcp(
605
 
606
 
607
  def _process_batch(
608
- records: list[dict[str, Any]],
609
  wiki_path: Path,
610
  dry_run: bool,
611
  skip_existing: bool,
612
  update_existing: bool,
 
613
  ) -> tuple[int, int, int, int, int]:
614
- """Process records. Returns (added, merged, reviewed, rejected, errors)."""
615
  added = merged = reviewed = rejected = errors = 0
616
- total = len(records)
617
 
618
  for i, raw in enumerate(records, 1):
619
  slug = raw.get("slug", "<unknown>")
@@ -621,7 +623,7 @@ def _process_batch(
621
  record = McpRecord.from_dict(raw)
622
  except Exception as exc: # noqa: BLE001 — batch CLI must not crash on one bad record
623
  errors += 1
624
- print(f" [{i}/{total}] ERROR: {slug}: {exc}", file=sys.stderr)
625
  continue
626
 
627
  entity_rel = record.entity_relpath()
@@ -629,7 +631,7 @@ def _process_batch(
629
 
630
  if skip_existing and _read_entity_page(wiki_path, target_relpath) is not None:
631
  merged += 1
632
- print(f" [{i}/{total}] [skipped] {record.slug}")
633
  continue
634
 
635
  try:
@@ -651,18 +653,29 @@ def _process_batch(
651
  else:
652
  merged += 1
653
  status = "updated" if update_existing else "merged"
654
- print(f" [{i}/{total}] [{status}] {record.slug}")
655
  except IntakeRejected as exc:
656
  rejected += 1
657
  codes = ", ".join(f.code for f in exc.decision.failures) or "unknown"
658
- print(f" [{i}/{total}] [rejected] {record.slug}: {codes}", file=sys.stderr)
659
  except Exception as exc: # noqa: BLE001 — batch CLI must continue past one failure
660
  errors += 1
661
- print(f" [{i}/{total}] ERROR: {record.slug}: {exc}", file=sys.stderr)
662
 
663
  return added, merged, reviewed, rejected, errors
664
 
665
 
 
 
 
 
 
 
 
 
 
 
 
666
  def main() -> None:
667
  """Entry point for the ctx-mcp-add CLI."""
668
  parser = argparse.ArgumentParser(description="Add MCP server records to the wiki catalog")
@@ -701,8 +714,6 @@ def main() -> None:
701
  wiki_path = Path(os.path.expanduser(args.wiki))
702
  ensure_wiki(str(wiki_path))
703
 
704
- raw_records: list[dict[str, Any]] = []
705
-
706
  if args.from_json:
707
  json_path = Path(os.path.expanduser(args.from_json))
708
  if not json_path.exists():
@@ -713,43 +724,42 @@ def main() -> None:
713
  except json.JSONDecodeError as exc:
714
  print(f"Error: failed to parse JSON: {exc}", file=sys.stderr)
715
  sys.exit(1)
 
 
 
 
 
 
 
 
716
 
717
  elif args.from_jsonl:
718
  jsonl_path = Path(os.path.expanduser(args.from_jsonl))
719
  if not jsonl_path.exists():
720
  print(f"Error: {jsonl_path} does not exist.", file=sys.stderr)
721
  sys.exit(1)
722
- for lineno, line in enumerate(jsonl_path.read_text(encoding="utf-8-sig").splitlines(), 1):
723
- line = line.lstrip("\ufeff").strip()
724
- if not line:
725
- continue
726
- try:
727
- raw_records.append(json.loads(line))
728
- except json.JSONDecodeError as exc:
729
- print(f"Warning: line {lineno} skipped (bad JSON): {exc}", file=sys.stderr)
730
-
731
- elif args.from_stdin:
732
- for lineno, line in enumerate(sys.stdin, 1):
733
- line = line.lstrip("\ufeff").strip()
734
- if not line:
735
- continue
736
- try:
737
- raw_records.append(json.loads(line))
738
- except json.JSONDecodeError as exc:
739
- print(f"Warning: line {lineno} skipped (bad JSON): {exc}", file=sys.stderr)
740
 
741
- if not raw_records:
 
 
 
 
 
 
 
 
 
742
  print("No records to process.", file=sys.stderr)
743
  sys.exit(0)
744
 
745
- added, merged, reviewed, rejected, errors = _process_batch(
746
- records=raw_records,
747
- wiki_path=wiki_path,
748
- dry_run=args.dry_run,
749
- skip_existing=args.skip_existing,
750
- update_existing=args.update_existing,
751
- )
752
-
753
  dry_label = " (dry-run)" if args.dry_run else ""
754
  print(
755
  f"\nDone{dry_label}: {added} added, {merged} updated, "
 
11
  # Single record from JSON file
12
  ctx-mcp-add --from-json /path/to/record.json
13
 
14
+ # JSONL from file, streamed one JSON object per line
15
  ctx-mcp-add --from-jsonl /path/to/records.jsonl
16
 
17
+ # JSONL from stdin, streamed one JSON object per line
18
  ctx-mcp-add --from-stdin
19
 
20
  [--dry-run] [--wiki PATH] [--skip-existing]
 
25
  import os
26
  import re
27
  import sys
28
+ from collections.abc import Iterable
29
  from dataclasses import replace
30
  from datetime import datetime, timezone
31
  from pathlib import Path
 
606
 
607
 
608
  def _process_batch(
609
+ records: Iterable[dict[str, Any]],
610
  wiki_path: Path,
611
  dry_run: bool,
612
  skip_existing: bool,
613
  update_existing: bool,
614
+ total: int | None = None,
615
  ) -> tuple[int, int, int, int, int]:
616
+ """Process record iterables. Returns (added, merged, reviewed, rejected, errors)."""
617
  added = merged = reviewed = rejected = errors = 0
618
+ total_label = str(total) if total is not None else "?"
619
 
620
  for i, raw in enumerate(records, 1):
621
  slug = raw.get("slug", "<unknown>")
 
623
  record = McpRecord.from_dict(raw)
624
  except Exception as exc: # noqa: BLE001 — batch CLI must not crash on one bad record
625
  errors += 1
626
+ print(f" [{i}/{total_label}] ERROR: {slug}: {exc}", file=sys.stderr)
627
  continue
628
 
629
  entity_rel = record.entity_relpath()
 
631
 
632
  if skip_existing and _read_entity_page(wiki_path, target_relpath) is not None:
633
  merged += 1
634
+ print(f" [{i}/{total_label}] [skipped] {record.slug}")
635
  continue
636
 
637
  try:
 
653
  else:
654
  merged += 1
655
  status = "updated" if update_existing else "merged"
656
+ print(f" [{i}/{total_label}] [{status}] {record.slug}")
657
  except IntakeRejected as exc:
658
  rejected += 1
659
  codes = ", ".join(f.code for f in exc.decision.failures) or "unknown"
660
+ print(f" [{i}/{total_label}] [rejected] {record.slug}: {codes}", file=sys.stderr)
661
  except Exception as exc: # noqa: BLE001 — batch CLI must continue past one failure
662
  errors += 1
663
+ print(f" [{i}/{total_label}] ERROR: {record.slug}: {exc}", file=sys.stderr)
664
 
665
  return added, merged, reviewed, rejected, errors
666
 
667
 
668
+ def _iter_jsonl_records(lines: Iterable[str]) -> Iterable[dict[str, Any]]:
669
+ for lineno, line in enumerate(lines, 1):
670
+ line = line.lstrip("\ufeff").strip()
671
+ if not line:
672
+ continue
673
+ try:
674
+ yield json.loads(line)
675
+ except json.JSONDecodeError as exc:
676
+ print(f"Warning: line {lineno} skipped (bad JSON): {exc}", file=sys.stderr)
677
+
678
+
679
  def main() -> None:
680
  """Entry point for the ctx-mcp-add CLI."""
681
  parser = argparse.ArgumentParser(description="Add MCP server records to the wiki catalog")
 
714
  wiki_path = Path(os.path.expanduser(args.wiki))
715
  ensure_wiki(str(wiki_path))
716
 
 
 
717
  if args.from_json:
718
  json_path = Path(os.path.expanduser(args.from_json))
719
  if not json_path.exists():
 
724
  except json.JSONDecodeError as exc:
725
  print(f"Error: failed to parse JSON: {exc}", file=sys.stderr)
726
  sys.exit(1)
727
+ added, merged, reviewed, rejected, errors = _process_batch(
728
+ records=raw_records,
729
+ wiki_path=wiki_path,
730
+ dry_run=args.dry_run,
731
+ skip_existing=args.skip_existing,
732
+ update_existing=args.update_existing,
733
+ total=1,
734
+ )
735
 
736
  elif args.from_jsonl:
737
  jsonl_path = Path(os.path.expanduser(args.from_jsonl))
738
  if not jsonl_path.exists():
739
  print(f"Error: {jsonl_path} does not exist.", file=sys.stderr)
740
  sys.exit(1)
741
+ with jsonl_path.open(encoding="utf-8-sig") as handle:
742
+ added, merged, reviewed, rejected, errors = _process_batch(
743
+ records=_iter_jsonl_records(handle),
744
+ wiki_path=wiki_path,
745
+ dry_run=args.dry_run,
746
+ skip_existing=args.skip_existing,
747
+ update_existing=args.update_existing,
748
+ )
 
 
 
 
 
 
 
 
 
 
749
 
750
+ else:
751
+ added, merged, reviewed, rejected, errors = _process_batch(
752
+ records=_iter_jsonl_records(sys.stdin),
753
+ wiki_path=wiki_path,
754
+ dry_run=args.dry_run,
755
+ skip_existing=args.skip_existing,
756
+ update_existing=args.update_existing,
757
+ )
758
+
759
+ if not any((added, merged, reviewed, rejected, errors)):
760
  print("No records to process.", file=sys.stderr)
761
  sys.exit(0)
762
 
 
 
 
 
 
 
 
 
763
  dry_label = " (dry-run)" if args.dry_run else ""
764
  print(
765
  f"\nDone{dry_label}: {added} added, {merged} updated, "
src/tests/test_backup_config.py CHANGED
@@ -92,6 +92,24 @@ def test_name_format_without_timestamp_placeholder_rejected():
92
  bc.BackupConfig(name_format="backup_{reason}")
93
 
94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  # ── ALWAYS_EXCLUDE safety net ───────────────────────────────────────────────
96
 
97
 
 
92
  bc.BackupConfig(name_format="backup_{reason}")
93
 
94
 
95
+ @pytest.mark.parametrize(
96
+ "top_file",
97
+ [
98
+ "../settings.json",
99
+ "nested/settings.json",
100
+ r"nested\settings.json",
101
+ "/tmp/settings.json",
102
+ r"\tmp\settings.json",
103
+ "C:settings.json",
104
+ r"C:\settings.json",
105
+ r"\\server\share\settings.json",
106
+ ],
107
+ )
108
+ def test_top_files_reject_unsafe_entries(top_file: str):
109
+ with pytest.raises(ValueError, match="top_files"):
110
+ bc.load_backup_config({"top_files": [top_file]})
111
+
112
+
113
  # ── ALWAYS_EXCLUDE safety net ───────────────────────────────────────────────
114
 
115
 
src/tests/test_backup_mirror.py CHANGED
@@ -18,6 +18,7 @@ if str(SRC) not in sys.path:
18
  sys.path.insert(0, str(SRC))
19
 
20
  import backup_mirror as bm # noqa: E402
 
21
 
22
 
23
  # ── Fixtures ────────────────────────────────────────────────────────────────
@@ -57,6 +58,24 @@ def _seed_home(home: Path) -> None:
57
  (mem / "MEMORY.md").write_text("- [role](user_role.md)\n", encoding="utf-8")
58
 
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  # ── create_snapshot ─────────────────────────────────────────────────────────
61
 
62
 
@@ -354,11 +373,7 @@ def test_prune_refuses_symlink_outside_backups(fake_home, tmp_path):
354
  pytest.skip("symlink creation often requires admin on Windows")
355
  _seed_home(fake_home)
356
  bm.create_snapshot(now=1.0)
357
- # Plant a symlink inside backups_dir pointing outside.
358
- outside = tmp_path / "outside"
359
- outside.mkdir()
360
- (outside / "canary.txt").write_text("must-not-be-deleted")
361
- (bm.BACKUPS_DIR / "99999999T999999Z.evil").symlink_to(outside)
362
  bm.prune_snapshots(keep=0)
363
  # Canary still exists -- symlinked dir was not removed.
364
  assert (outside / "canary.txt").exists()
@@ -388,6 +403,38 @@ def test_prune_with_keep_zero_removes_all(fake_home):
388
  assert bm.list_snapshots() == []
389
 
390
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
391
  def test_prune_negative_raises(fake_home):
392
  with pytest.raises(ValueError):
393
  bm.prune_snapshots(keep=-1)
@@ -463,3 +510,15 @@ def test_cli_prune_keeps_newest(fake_home):
463
  rc = bm.main(["prune", "--keep", "1"])
464
  assert rc == 0
465
  assert len(bm.list_snapshots()) == 1
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  sys.path.insert(0, str(SRC))
19
 
20
  import backup_mirror as bm # noqa: E402
21
+ from backup_config import BackupRetention # noqa: E402
22
 
23
 
24
  # ── Fixtures ────────────────────────────────────────────────────────────────
 
58
  (mem / "MEMORY.md").write_text("- [role](user_role.md)\n", encoding="utf-8")
59
 
60
 
61
+ def _plant_external_snapshot_symlink(tmp_path: Path) -> Path:
62
+ outside = tmp_path / "outside"
63
+ outside.mkdir()
64
+ (outside / "canary.txt").write_text("must-not-be-deleted")
65
+ (outside / "manifest.json").write_text(
66
+ json.dumps(
67
+ {
68
+ "snapshot_id": "99999999T999999Z.evil",
69
+ "created_at": 9_999_999_999.0,
70
+ "entries": [],
71
+ }
72
+ ),
73
+ encoding="utf-8",
74
+ )
75
+ (bm.BACKUPS_DIR / "99999999T999999Z.evil").symlink_to(outside)
76
+ return outside
77
+
78
+
79
  # ── create_snapshot ─────────────────────────────────────────────────────────
80
 
81
 
 
373
  pytest.skip("symlink creation often requires admin on Windows")
374
  _seed_home(fake_home)
375
  bm.create_snapshot(now=1.0)
376
+ outside = _plant_external_snapshot_symlink(tmp_path)
 
 
 
 
377
  bm.prune_snapshots(keep=0)
378
  # Canary still exists -- symlinked dir was not removed.
379
  assert (outside / "canary.txt").exists()
 
403
  assert bm.list_snapshots() == []
404
 
405
 
406
+ def test_prune_dry_run_excludes_symlink_outside_backups(fake_home, tmp_path):
407
+ if sys.platform == "win32":
408
+ pytest.skip("symlink creation often requires admin on Windows")
409
+ _seed_home(fake_home)
410
+ real = bm.create_snapshot(now=1.0)
411
+ outside = _plant_external_snapshot_symlink(tmp_path)
412
+
413
+ removed = bm.prune_snapshots(keep=0, dry_run=True)
414
+
415
+ assert removed == (real.name,)
416
+ assert (outside / "canary.txt").exists()
417
+ assert (bm.BACKUPS_DIR / "99999999T999999Z.evil").exists()
418
+
419
+
420
+ def test_prune_policy_dry_run_excludes_symlink_outside_backups(fake_home, tmp_path):
421
+ if sys.platform == "win32":
422
+ pytest.skip("symlink creation often requires admin on Windows")
423
+ _seed_home(fake_home)
424
+ real = bm.create_snapshot(now=1.0)
425
+ outside = _plant_external_snapshot_symlink(tmp_path)
426
+
427
+ plan = bm.prune_by_policy(
428
+ BackupRetention(keep_latest=0, keep_daily=0),
429
+ dry_run=True,
430
+ now=10.0,
431
+ )
432
+
433
+ assert plan.delete == (real.name,)
434
+ assert (outside / "canary.txt").exists()
435
+ assert (bm.BACKUPS_DIR / "99999999T999999Z.evil").exists()
436
+
437
+
438
  def test_prune_negative_raises(fake_home):
439
  with pytest.raises(ValueError):
440
  bm.prune_snapshots(keep=-1)
 
510
  rc = bm.main(["prune", "--keep", "1"])
511
  assert rc == 0
512
  assert len(bm.list_snapshots()) == 1
513
+
514
+
515
+ def test_cli_prune_keep_dry_run_does_not_delete(fake_home, capsys):
516
+ _seed_home(fake_home)
517
+ bm.create_snapshot(now=1.0)
518
+ bm.create_snapshot(now=2.0)
519
+ bm.create_snapshot(now=3.0)
520
+ rc = bm.main(["prune", "--keep", "1", "--dry-run"])
521
+ out = capsys.readouterr().out
522
+ assert rc == 0
523
+ assert "would remove" in out
524
+ assert len(bm.list_snapshots()) == 3
src/tests/test_ci_classifier.py CHANGED
@@ -202,6 +202,18 @@ def test_no_test_policy_treats_all_workflows_as_contract_files() -> None:
202
  assert result.contract_files == (workflow,)
203
 
204
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  def test_ci_workflows_default_to_read_only_token_permissions() -> None:
206
  for workflow_path in _workflow_paths():
207
  workflow = workflow_path.read_text(encoding="utf-8")
@@ -212,11 +224,14 @@ def test_ci_workflows_default_to_read_only_token_permissions() -> None:
212
  def test_graph_artifact_job_uses_release_asset_fallback_for_lfs_budget() -> None:
213
  workflow = Path(".github/workflows/test.yml").read_text(encoding="utf-8")
214
 
215
- assert "Resolve graph artifacts from release assets" in workflow
216
- assert "Resolving graph artifacts from matching release assets" in workflow
217
- assert "git lfs pull" not in workflow
218
  assert 'tag_name.startswith("graph-artifacts-")' in workflow
219
  assert "sha256:{expected_oid} size:{expected_size}" in workflow
 
 
 
 
220
  assert "Hydrated {path_name} from" in workflow
221
  assert "graph/wiki-graph-runtime.tar.gz" in workflow
222
  assert "python src/validate_graph_artifacts.py" in workflow
@@ -272,8 +287,10 @@ def test_publish_workflow_validates_and_uploads_graph_assets() -> None:
272
  workflow = Path(".github/workflows/publish.yml").read_text(encoding="utf-8")
273
 
274
  assert "Resolve release graph artifacts from release assets" in workflow
275
- assert "Resolving graph artifacts from matching release assets" in workflow
276
- assert "git lfs pull" not in workflow
 
 
277
  assert 'tag_name.startswith("graph-artifacts-")' in workflow
278
  assert "sha256:{expected_oid} size:{expected_size}" in workflow
279
  assert "Validate release graph artifacts" in workflow
 
202
  assert result.contract_files == (workflow,)
203
 
204
 
205
+ def test_no_test_policy_requires_tests_for_release_sync_artifact_scripts() -> None:
206
+ for script in (
207
+ "scripts/sync_huggingface.py",
208
+ "scripts/pack_full_wiki_tar.py",
209
+ "scripts/graph_artifact_guard.py",
210
+ ):
211
+ result = evaluate_policy([script], (), {script: "+print('changed')\n"})
212
+
213
+ assert result.passed is False
214
+ assert result.contract_files == (script,)
215
+
216
+
217
  def test_ci_workflows_default_to_read_only_token_permissions() -> None:
218
  for workflow_path in _workflow_paths():
219
  workflow = workflow_path.read_text(encoding="utf-8")
 
224
  def test_graph_artifact_job_uses_release_asset_fallback_for_lfs_budget() -> None:
225
  workflow = Path(".github/workflows/test.yml").read_text(encoding="utf-8")
226
 
227
+ assert "Resolve graph artifacts from release assets or targeted LFS" in workflow
228
+ assert "Resolving graph artifacts from release cache, or targeted Git LFS" in workflow
 
229
  assert 'tag_name.startswith("graph-artifacts-")' in workflow
230
  assert "sha256:{expected_oid} size:{expected_size}" in workflow
231
+ assert "Pointer for {path_name} is not in release cache" in workflow
232
+ assert "searching release caches before targeted Git LFS" in workflow
233
+ assert '"git", "lfs", "pull", "--include", path_name' in workflow
234
+ assert "GIT_LFS_ACTIVITYTIMEOUT" in workflow
235
  assert "Hydrated {path_name} from" in workflow
236
  assert "graph/wiki-graph-runtime.tar.gz" in workflow
237
  assert "python src/validate_graph_artifacts.py" in workflow
 
287
  workflow = Path(".github/workflows/publish.yml").read_text(encoding="utf-8")
288
 
289
  assert "Resolve release graph artifacts from release assets" in workflow
290
+ assert "Resolving graph artifacts from release cache, or targeted Git LFS" in workflow
291
+ assert "searching release caches before targeted Git LFS" in workflow
292
+ assert '"git", "lfs", "pull", "--include", path_name' in workflow
293
+ assert "verify_hydrated_file(graph_tar, expected_oid, expected_size)" in workflow
294
  assert 'tag_name.startswith("graph-artifacts-")' in workflow
295
  assert "sha256:{expected_oid} size:{expected_size}" in workflow
296
  assert "Validate release graph artifacts" in workflow
src/tests/test_ci_preflight.py CHANGED
@@ -1,10 +1,13 @@
1
  from __future__ import annotations
2
 
 
3
  import shlex
4
  from pathlib import Path
5
 
6
  import yaml # type: ignore[import-untyped]
7
 
 
 
8
  from scripts.ci_preflight import _run_no_test_policy_for_files
9
  from scripts.ci_preflight import Check
10
  from scripts.ci_preflight import PUBLIC_DOCS_TRACKER_TESTS
@@ -75,10 +78,100 @@ def test_preflight_runs_source_gates_for_source_changes() -> None:
75
 
76
  def test_preflight_runs_graph_validation_for_graph_artifacts() -> None:
77
  names = _names_for(["graph/wiki-graph.tar.gz"])
 
 
 
78
 
 
79
  assert "graph artifact validation" in names
80
  assert "no-test policy" not in names
81
  assert "unit-linux equivalent" not in names
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
 
84
  def test_preflight_no_test_policy_invocation_uses_current_dirty_file_set() -> None:
@@ -136,6 +229,24 @@ def test_preflight_full_profile_forces_source_gates_for_docs_changes() -> None:
136
 
137
  def test_preflight_runs_browser_and_similarity_when_classified() -> None:
138
  names = _names_for([".github/workflows/test.yml"])
 
 
 
 
 
 
 
 
 
139
 
140
  assert "browser monitor security" in names
141
  assert "similarity precision/recall" in names
 
 
 
 
 
 
 
 
 
 
1
  from __future__ import annotations
2
 
3
+ import hashlib
4
  import shlex
5
  from pathlib import Path
6
 
7
  import yaml # type: ignore[import-untyped]
8
 
9
+ from scripts import ci_preflight
10
+ from scripts import local_fast_gate
11
  from scripts.ci_preflight import _run_no_test_policy_for_files
12
  from scripts.ci_preflight import Check
13
  from scripts.ci_preflight import PUBLIC_DOCS_TRACKER_TESTS
 
78
 
79
  def test_preflight_runs_graph_validation_for_graph_artifacts() -> None:
80
  names = _names_for(["graph/wiki-graph.tar.gz"])
81
+ lanes = local_fast_gate.group_checks(_checks_for(["graph/wiki-graph.tar.gz"]))
82
+ graph_lane = next(lane for lane in lanes if lane.name == "graph")
83
+ graph_names = [check.name for check in graph_lane.checks]
84
 
85
+ assert names.index("hydrate graph LFS") < names.index("graph artifact validation")
86
  assert "graph artifact validation" in names
87
  assert "no-test policy" not in names
88
  assert "unit-linux equivalent" not in names
89
+ assert graph_names == ["hydrate graph LFS", "graph artifact validation"]
90
+ assert graph_lane.checks[0].argv[1] == "scripts/ci_preflight.py"
91
+
92
+
93
+ def test_local_fast_whitespace_check_runs_against_base() -> None:
94
+ whitespace = next(
95
+ check for check in _checks_for(["src/ctx/cli/run.py"]) if check.name == "whitespace"
96
+ )
97
+ lanes = local_fast_gate.group_checks([whitespace])
98
+
99
+ assert lanes[0].name == "cheap"
100
+ assert lanes[0].checks[0].argv == (
101
+ "python",
102
+ "scripts/ci_preflight.py",
103
+ "--base",
104
+ "origin/main",
105
+ "--internal-whitespace",
106
+ )
107
+
108
+
109
+ def test_preflight_graph_lfs_pointer_verification(tmp_path: Path, monkeypatch) -> None:
110
+ monkeypatch.setattr(ci_preflight, "REPO_ROOT", tmp_path)
111
+ artifact = tmp_path / "graph" / "wiki-graph.tar.gz"
112
+ artifact.parent.mkdir()
113
+ payload = b"hydrated graph payload"
114
+ expected_sha256 = hashlib.sha256(payload).hexdigest()
115
+ artifact.write_text(
116
+ "version https://git-lfs.github.com/spec/v1\n"
117
+ f"oid sha256:{expected_sha256}\n"
118
+ f"size {len(payload)}\n",
119
+ encoding="utf-8",
120
+ )
121
+
122
+ pointer = ci_preflight._read_lfs_pointer(artifact)
123
+
124
+ assert pointer == ci_preflight.LfsPointer(
125
+ "graph/wiki-graph.tar.gz",
126
+ expected_sha256,
127
+ len(payload),
128
+ )
129
+ artifact.write_bytes(payload)
130
+ ci_preflight._verify_hydrated_lfs_pointer(pointer)
131
+
132
+
133
+ def test_preflight_graph_lfs_pull_uses_per_command_filters(
134
+ tmp_path: Path,
135
+ monkeypatch,
136
+ ) -> None:
137
+ monkeypatch.setattr(ci_preflight, "REPO_ROOT", tmp_path)
138
+ monkeypatch.setattr(ci_preflight.shutil, "which", lambda _name: "/usr/bin/git")
139
+ artifact = tmp_path / "graph" / "wiki-graph.tar.gz"
140
+ artifact.parent.mkdir()
141
+ artifact.write_text(
142
+ f"version https://git-lfs.github.com/spec/v1\noid sha256:{'a' * 64}\nsize 1\n",
143
+ encoding="utf-8",
144
+ )
145
+ calls: list[list[str]] = []
146
+
147
+ class Result:
148
+ returncode = 0
149
+
150
+ def fake_run(argv: list[str], **_kwargs) -> Result:
151
+ calls.append(argv)
152
+ return Result()
153
+
154
+ verified: list[ci_preflight.LfsPointer] = []
155
+ monkeypatch.setattr(ci_preflight.subprocess, "run", fake_run)
156
+ monkeypatch.setattr(ci_preflight, "_verify_hydrated_lfs_pointer", verified.append)
157
+
158
+ assert ci_preflight.hydrate_graph_lfs_artifacts() == 0
159
+
160
+ assert len(calls) == 1
161
+ argv = calls[0]
162
+ lfs_index = argv.index("lfs")
163
+ assert argv[:lfs_index] == ["git", *ci_preflight.GIT_LFS_FILTER_CONFIG]
164
+ assert argv[lfs_index:] == [
165
+ "lfs",
166
+ "pull",
167
+ "--include",
168
+ "graph/wiki-graph.tar.gz",
169
+ "--exclude",
170
+ "",
171
+ ]
172
+ assert verified == [
173
+ ci_preflight.LfsPointer("graph/wiki-graph.tar.gz", "a" * 64, 1),
174
+ ]
175
 
176
 
177
  def test_preflight_no_test_policy_invocation_uses_current_dirty_file_set() -> None:
 
229
 
230
  def test_preflight_runs_browser_and_similarity_when_classified() -> None:
231
  names = _names_for([".github/workflows/test.yml"])
232
+ lanes = local_fast_gate.group_checks(_checks_for([".github/workflows/test.yml"]))
233
+ lane_names = [lane.name for lane in lanes]
234
+ workflow = yaml.safe_load(Path(".github/workflows/test.yml").read_text(encoding="utf-8"))
235
+ graph_steps = workflow["jobs"]["graph-check"]["steps"]
236
+ graph_resolver_script = next(
237
+ step["run"]
238
+ for step in graph_steps
239
+ if step.get("name") == "Resolve graph artifacts from release assets or targeted LFS"
240
+ )
241
 
242
  assert "browser monitor security" in names
243
  assert "similarity precision/recall" in names
244
+ assert "cheap" in lane_names
245
+ assert "static" in lane_names
246
+ assert "unit" in lane_names
247
+ assert "feature" in lane_names
248
+ assert "package" in lane_names
249
+ assert "release_asset_wait_seconds = 300" in graph_resolver_script
250
+ assert 'os.environ.get("GITHUB_EVENT_NAME") == "pull_request"' in graph_resolver_script
251
+ assert "release_asset_wait_seconds = 0" in graph_resolver_script
252
+ assert 'env.setdefault("GIT_LFS_CONCURRENTTRANSFERS", "1")' in graph_resolver_script
src/tests/test_ctx_monitor.py CHANGED
@@ -5294,6 +5294,8 @@ def test_entity_search_and_detail_apis_support_edit_flow(
5294
  )
5295
  assert status == 200
5296
  assert detail["slug"] == "python-patterns"
 
 
5297
  assert detail["frontmatter"]["description"] == "Idiomatic Python patterns"
5298
  assert "Use dataclasses" in detail["body"]
5299
  finally:
 
5294
  )
5295
  assert status == 200
5296
  assert detail["slug"] == "python-patterns"
5297
+ assert detail["path"] == "entities/skills/python-patterns.md"
5298
+ assert str(fake_claude) not in detail["path"]
5299
  assert detail["frontmatter"]["description"] == "Idiomatic Python patterns"
5300
  assert "Use dataclasses" in detail["body"]
5301
  finally:
src/tests/test_dashboard_entities.py CHANGED
@@ -30,6 +30,7 @@ def test_skill_upsert_requires_security_gate_before_write(tmp_path: Path) -> Non
30
  wiki_entity_target_path=lambda slug, _etype: tmp_path / f"{slug}.md",
31
  wiki_entity_path=lambda _slug, _etype: None,
32
  iter_wiki_entity_paths=lambda _etype: [],
 
33
  read_manifest=lambda: {"load": []},
34
  perform_unload=lambda _slug, _etype: (True, "unloaded"),
35
  queue_entity_refresh=lambda *args: queued.append(args), # type: ignore[arg-type]
 
30
  wiki_entity_target_path=lambda slug, _etype: tmp_path / f"{slug}.md",
31
  wiki_entity_path=lambda _slug, _etype: None,
32
  iter_wiki_entity_paths=lambda _etype: [],
33
+ wiki_relative_path=lambda path: path.relative_to(tmp_path).as_posix(),
34
  read_manifest=lambda: {"load": []},
35
  perform_unload=lambda _slug, _etype: (True, "unloaded"),
36
  queue_entity_refresh=lambda *args: queued.append(args), # type: ignore[arg-type]
src/tests/test_harness_cli_run.py CHANGED
@@ -203,6 +203,32 @@ class TestParseMcpSpec:
203
  assert cfg.command == "myserver"
204
  assert cfg.args == ()
205
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  def test_filesystem_colon_path_uses_preset_command(self) -> None:
207
  cfg = _parse_mcp_spec("filesystem:/tmp/project")
208
  assert cfg.name == "filesystem"
 
203
  assert cfg.command == "myserver"
204
  assert cfg.args == ()
205
 
206
+ @pytest.mark.parametrize(
207
+ "spec",
208
+ [
209
+ "fs:npx server --token secret-value",
210
+ "fs:npx server --api-key=secret-value",
211
+ "fs:npx server GITHUB_TOKEN=secret-value",
212
+ "fs:npx server ghp_1234567890abcdefghijkl",
213
+ ],
214
+ )
215
+ def test_explicit_form_rejects_inline_secret_args(self, spec: str) -> None:
216
+ with pytest.raises(SystemExit, match="--mcp-env"):
217
+ _parse_mcp_spec(spec)
218
+
219
+ def test_explicit_form_allows_secret_indirection_args(self) -> None:
220
+ cfg = _parse_mcp_spec(
221
+ "fs:npx server --token-file /run/secrets/token --credential-env GITHUB_TOKEN"
222
+ )
223
+
224
+ assert cfg.args == (
225
+ "server",
226
+ "--token-file",
227
+ "/run/secrets/token",
228
+ "--credential-env",
229
+ "GITHUB_TOKEN",
230
+ )
231
+
232
  def test_filesystem_colon_path_uses_preset_command(self) -> None:
233
  cfg = _parse_mcp_spec("filesystem:/tmp/project")
234
  assert cfg.name == "filesystem"
src/tests/test_huggingface_sync.py CHANGED
@@ -161,8 +161,10 @@ def test_hf_sync_workflow_uses_secret_and_hardened_script() -> None:
161
 
162
  assert "HF_TOKEN: ${{ secrets.HF_TOKEN }}" in text
163
  assert "lfs: false" in text
164
- assert "git lfs pull" not in text
165
- assert "Resolving graph artifacts from matching release assets" in text
 
 
166
  assert 'tag_name.startswith("graph-artifacts-")' in text
167
  assert "latest_tag" not in text
168
  for artifact in _required_hydrated_artifacts():
@@ -172,6 +174,8 @@ def test_hf_sync_workflow_uses_secret_and_hardened_script() -> None:
172
  assert "--repo-type dataset" in text
173
  assert "--repo-type model" not in text
174
  assert "Classify sync scope" in text
 
 
175
  assert "card_only_files" in text
176
  assert 'SYNC_MODE" == "card"' in text
177
  assert "--card-only" in text
 
161
 
162
  assert "HF_TOKEN: ${{ secrets.HF_TOKEN }}" in text
163
  assert "lfs: false" in text
164
+ assert "Resolving graph artifacts from release cache, or targeted Git LFS" in text
165
+ assert "searching release caches before targeted Git LFS" in text
166
+ assert '"git", "lfs", "pull", "--include", path_name' in text
167
+ assert "verify_hydrated_file(artifact, expected_oid, expected_size)" in text
168
  assert 'tag_name.startswith("graph-artifacts-")' in text
169
  assert "latest_tag" not in text
170
  for artifact in _required_hydrated_artifacts():
 
174
  assert "--repo-type dataset" in text
175
  assert "--repo-type model" not in text
176
  assert "Classify sync scope" in text
177
+ assert 'card_only_prefixes = ("docs/",)' in text
178
+ assert 'card_only_prefixes = (".github/", "docs/", "src/tests/")' not in text
179
  assert "card_only_files" in text
180
  assert 'SYNC_MODE" == "card"' in text
181
  assert "--card-only" in text
src/tests/test_mcp_add.py CHANGED
@@ -899,6 +899,53 @@ class TestAddMcpCliInput:
899
 
900
  assert (wiki / "entities" / "mcp-servers" / "b" / "bom-stdin-mcp.md").exists()
901
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
902
  def test_rejected_batch_exits_nonzero(
903
  self,
904
  monkeypatch: pytest.MonkeyPatch,
 
899
 
900
  assert (wiki / "entities" / "mcp-servers" / "b" / "bom-stdin-mcp.md").exists()
901
 
902
+ def test_from_jsonl_streams_without_read_text(
903
+ self,
904
+ monkeypatch: pytest.MonkeyPatch,
905
+ tmp_path: Path,
906
+ ) -> None:
907
+ import mcp_add # noqa: PLC0415
908
+
909
+ record_path = tmp_path / "mcp.jsonl"
910
+ record_path.write_text(
911
+ json.dumps(
912
+ {
913
+ "name": "streamed-jsonl-mcp",
914
+ "description": "MCP loaded from a streamed JSONL file.",
915
+ "sources": ["test"],
916
+ "github_url": "https://github.com/example/streamed-jsonl-mcp",
917
+ "tags": ["testing"],
918
+ }
919
+ )
920
+ + "\n",
921
+ encoding="utf-8",
922
+ )
923
+ wiki = tmp_path / "wiki"
924
+
925
+ def _fail_read_text(self: Path, *args: Any, **kwargs: Any) -> str:
926
+ raise AssertionError(f"unexpected read_text for {self}")
927
+
928
+ monkeypatch.setattr(Path, "read_text", _fail_read_text)
929
+ monkeypatch.setattr(
930
+ sys,
931
+ "argv",
932
+ [
933
+ "mcp_add.py",
934
+ "--from-jsonl",
935
+ str(record_path),
936
+ "--wiki",
937
+ str(wiki),
938
+ ],
939
+ )
940
+ monkeypatch.setattr("mcp_add.check_intake", _fake_allow)
941
+ monkeypatch.setattr("mcp_add.record_embedding", _fake_record_embedding)
942
+ monkeypatch.setattr("mcp_add.update_index", lambda *a, **k: None)
943
+ monkeypatch.setattr("mcp_add.append_log", lambda *a, **k: None)
944
+
945
+ mcp_add.main()
946
+
947
+ assert (wiki / "entities" / "mcp-servers" / "s" / "streamed-jsonl-mcp.md").exists()
948
+
949
  def test_rejected_batch_exits_nonzero(
950
  self,
951
  monkeypatch: pytest.MonkeyPatch,
src/tests/test_mcp_install.py CHANGED
@@ -329,6 +329,22 @@ class TestInstallMcp:
329
  }
330
  ]
331
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
332
  def test_force_overrides_skip(
333
  self,
334
  wiki_dir: Path,
 
329
  }
330
  ]
331
 
332
+ def test_already_installed_dry_run_does_not_reconcile_manifest(
333
+ self,
334
+ wiki_dir: Path,
335
+ isolated_manifest: Path,
336
+ ) -> None:
337
+ _write_entity(
338
+ wiki_dir,
339
+ "gh",
340
+ {"status": "installed", "install_cmd": "npx -y old-pkg"},
341
+ )
342
+
343
+ r = mcp_install.install_mcp("gh", wiki_dir=wiki_dir, auto=True, dry_run=True)
344
+
345
+ assert r.status == "skipped-existing"
346
+ assert install_utils.load_manifest()["load"] == []
347
+
348
  def test_force_overrides_skip(
349
  self,
350
  wiki_dir: Path,
src/tests/test_mcp_router.py CHANGED
@@ -12,6 +12,7 @@ so there's no cross-test state.
12
  from __future__ import annotations
13
 
14
  import json
 
15
  import subprocess
16
  import sys
17
  import time
@@ -238,6 +239,10 @@ class TestClientRobustness:
238
  ("OPENAI_API_KEY=sk-proj-abcdefghijklmnop", ("sk-proj-abcdefghijklmnop",)),
239
  ("SLACK_BOT_TOKEN=xoxb-1234567890-secret", ("xoxb-1234567890-secret",)),
240
  ("db_password: supersecretpassword", ("supersecretpassword",)),
 
 
 
 
241
  ],
242
  )
243
  def test_redact_sensitive_text_matrix(
@@ -360,6 +365,38 @@ class TestClientRobustness:
360
  assert "Authorization:" in stderr_tail
361
  assert "[REDACTED]" in stderr_tail
362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
363
  def test_request_before_start_raises(self) -> None:
364
  client = McpClient(_make_config())
365
  with pytest.raises(RuntimeError, match="not started"):
@@ -441,6 +478,93 @@ class TestClientRobustness:
441
  with McpClient(_make_config(inherit_env=True)) as client:
442
  assert client.call_tool("echo_env", {"name": "CTX_LEGACY_INHERIT_TEST"}) == "visible"
443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
444
 
445
  # ── McpRouter ─────────────────────────────────────────────────────────────────
446
 
 
12
  from __future__ import annotations
13
 
14
  import json
15
+ import io
16
  import subprocess
17
  import sys
18
  import time
 
239
  ("OPENAI_API_KEY=sk-proj-abcdefghijklmnop", ("sk-proj-abcdefghijklmnop",)),
240
  ("SLACK_BOT_TOKEN=xoxb-1234567890-secret", ("xoxb-1234567890-secret",)),
241
  ("db_password: supersecretpassword", ("supersecretpassword",)),
242
+ ("PRIVATE_KEY=supersecretprivatekey", ("supersecretprivatekey",)),
243
+ ("ACCESS_KEY=supersecretaccesskey", ("supersecretaccesskey",)),
244
+ ("SERVICE_PASSWD=supersecretpasswd", ("supersecretpasswd",)),
245
+ ("BEARER=supersecretbearer", ("supersecretbearer",)),
246
  ],
247
  )
248
  def test_redact_sensitive_text_matrix(
 
365
  assert "Authorization:" in stderr_tail
366
  assert "[REDACTED]" in stderr_tail
367
 
368
+ def test_stderr_redacts_credential_env_values(
369
+ self,
370
+ monkeypatch: pytest.MonkeyPatch,
371
+ ) -> None:
372
+ secret = "argv-only-secret"
373
+ monkeypatch.setenv("MCP_API_KEY", secret)
374
+ cfg = _make_config(
375
+ extra_env={
376
+ "FAKE_MCP_NOISY_STDERR": "1",
377
+ "FAKE_MCP_STDERR_LINE": secret,
378
+ },
379
+ credential_env=("MCP_API_KEY",),
380
+ )
381
+
382
+ with McpClient(cfg) as client:
383
+ client.list_tools()
384
+ _wait_until(lambda: "[REDACTED]" in client._stderr_tail())
385
+ stderr_tail = client._stderr_tail()
386
+
387
+ assert secret not in stderr_tail
388
+ assert "[REDACTED]" in stderr_tail
389
+
390
+ def test_stderr_drain_uses_thread_redaction_snapshot(self) -> None:
391
+ secret = "late-secret"
392
+ client = McpClient(_make_config())
393
+ client._proc = type("Proc", (), {"stderr": io.BytesIO(f"{secret}\n".encode())})() # type: ignore[assignment]
394
+ client._stderr_redaction_values = ()
395
+
396
+ client._drain_stderr((secret,))
397
+
398
+ assert client._stderr_lines == ["[REDACTED]"]
399
+
400
  def test_request_before_start_raises(self) -> None:
401
  client = McpClient(_make_config())
402
  with pytest.raises(RuntimeError, match="not started"):
 
478
  with McpClient(_make_config(inherit_env=True)) as client:
479
  assert client.call_tool("echo_env", {"name": "CTX_LEGACY_INHERIT_TEST"}) == "visible"
480
 
481
+ def test_env_placeholders_are_literal_by_default(
482
+ self,
483
+ monkeypatch: pytest.MonkeyPatch,
484
+ ) -> None:
485
+ monkeypatch.setenv("MCP_API_KEY", "argv-only-secret")
486
+ cfg = McpServerConfig(
487
+ name="argvserver",
488
+ command="server",
489
+ args=("--api-key", "${MCP_API_KEY}", "--header=Bearer $MCP_API_KEY"),
490
+ credential_env=("MCP_API_KEY",),
491
+ )
492
+
493
+ assert mcp_router._expand_config_args(cfg, mcp_router._child_env_for_config(cfg)) == (
494
+ "--api-key",
495
+ "${MCP_API_KEY}",
496
+ "--header=Bearer $MCP_API_KEY",
497
+ )
498
+
499
+ def test_sensitive_env_placeholders_are_not_expanded_into_argv_by_default(
500
+ self,
501
+ monkeypatch: pytest.MonkeyPatch,
502
+ ) -> None:
503
+ monkeypatch.setenv("MCP_API_KEY", "argv-only-secret")
504
+ cfg = McpServerConfig(
505
+ name="argvserver",
506
+ command="server",
507
+ args=("--api-key", "${MCP_API_KEY}", "--header=Bearer $MCP_API_KEY"),
508
+ credential_env=("MCP_API_KEY",),
509
+ expand_argv_env=True,
510
+ )
511
+
512
+ with pytest.raises(ValueError, match="sensitive env var 'MCP_API_KEY'"):
513
+ mcp_router._expand_config_args(cfg, mcp_router._child_env_for_config(cfg))
514
+
515
+ @pytest.mark.parametrize(
516
+ "env_name",
517
+ ("MCP_PRIVATE_KEY", "MCP_ACCESS_KEY", "SERVICE_PASSWD", "MCP_BEARER"),
518
+ )
519
+ def test_sensitive_env_placeholder_key_markers_are_rejected_by_default(
520
+ self,
521
+ env_name: str,
522
+ ) -> None:
523
+ cfg = McpServerConfig(
524
+ name="argvserver",
525
+ command="server",
526
+ args=(f"--auth=${{{env_name}}}",),
527
+ env={env_name: "argv-only-secret"},
528
+ expand_argv_env=True,
529
+ )
530
+ env = mcp_router._child_env_for_config(cfg)
531
+
532
+ with pytest.raises(ValueError, match=env_name):
533
+ mcp_router._expand_config_args(cfg, env)
534
+ assert "argv-only-secret" in mcp_router._stderr_redaction_values(cfg, env)
535
+
536
+ def test_non_secret_env_placeholders_expand_when_enabled(self) -> None:
537
+ cfg = McpServerConfig(
538
+ name="argvserver",
539
+ command="server",
540
+ args=("--port=${MCP_PORT}",),
541
+ env={"MCP_PORT": "8123"},
542
+ expand_argv_env=True,
543
+ )
544
+
545
+ assert mcp_router._expand_config_args(cfg, mcp_router._child_env_for_config(cfg)) == (
546
+ "--port=8123",
547
+ )
548
+
549
+ def test_argv_secret_expansion_requires_explicit_opt_in(
550
+ self,
551
+ monkeypatch: pytest.MonkeyPatch,
552
+ ) -> None:
553
+ monkeypatch.setenv("MCP_API_KEY", "argv-only-secret")
554
+ cfg = McpServerConfig(
555
+ name="argvserver",
556
+ command="server",
557
+ args=("--api-key", "${MCP_API_KEY}"),
558
+ credential_env=("MCP_API_KEY",),
559
+ allow_argv_secret_expansion=True,
560
+ expand_argv_env=True,
561
+ )
562
+
563
+ assert mcp_router._expand_config_args(cfg, mcp_router._child_env_for_config(cfg)) == (
564
+ "--api-key",
565
+ "argv-only-secret",
566
+ )
567
+
568
 
569
  # ── McpRouter ─────────────────────────────────────────────────────────────────
570
 
src/tests/test_no_mistakes_env.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import shutil
5
+ import subprocess
6
+ from pathlib import Path
7
+
8
+ import yaml
9
+
10
+
11
+ def _write_executable(path: Path, content: str) -> None:
12
+ path.write_text(content, encoding="utf-8")
13
+ path.chmod(0o755)
14
+
15
+
16
+ def test_no_mistakes_wrapper_prefers_valid_worktree_venv_over_broken_override(
17
+ tmp_path: Path,
18
+ ) -> None:
19
+ repo = tmp_path / "repo"
20
+ script_dir = repo / "scripts"
21
+ script_dir.mkdir(parents=True)
22
+ shutil.copy2(
23
+ Path("scripts/no_mistakes_codex_env.sh"),
24
+ script_dir / "no_mistakes_codex_env.sh",
25
+ )
26
+
27
+ worktree_bin = repo / ".venv" / "bin"
28
+ worktree_bin.mkdir(parents=True)
29
+ (repo / ".venv" / "pyvenv.cfg").write_text("home = /usr/bin\n", encoding="utf-8")
30
+ _write_executable(worktree_bin / "python", "#!/usr/bin/env sh\ncat >/dev/null\n")
31
+
32
+ broken_bin = tmp_path / "broken" / "bin"
33
+ broken_bin.mkdir(parents=True)
34
+ _write_executable(broken_bin / "python", "#!/usr/bin/env sh\ncat >/dev/null\nexit 1\n")
35
+
36
+ fake_codex = tmp_path / "codex"
37
+ _write_executable(
38
+ fake_codex,
39
+ "#!/usr/bin/env sh\n"
40
+ "printf 'resolved=%s\\nvenv=%s\\npath=%s\\n' "
41
+ '"$CTX_NO_MISTAKES_PYTHON_BIN_RESOLVED" "$VIRTUAL_ENV" "$PATH"\n',
42
+ )
43
+
44
+ env = os.environ.copy()
45
+ env.pop("VIRTUAL_ENV", None)
46
+ env["CTX_NO_MISTAKES_PYTHON_BIN"] = str(broken_bin)
47
+ env["CTX_NO_MISTAKES_CODEX_RESOURCES"] = str(tmp_path / "codex-resources")
48
+ env["CTX_NO_MISTAKES_REAL_CODEX"] = str(fake_codex)
49
+
50
+ result = subprocess.run(
51
+ ["bash", str(script_dir / "no_mistakes_codex_env.sh")],
52
+ cwd=repo,
53
+ env=env,
54
+ check=True,
55
+ text=True,
56
+ stdout=subprocess.PIPE,
57
+ stderr=subprocess.PIPE,
58
+ )
59
+
60
+ assert f"resolved={worktree_bin}" in result.stdout
61
+ assert f"venv={repo / '.venv'}" in result.stdout
62
+ assert result.stdout.splitlines()[2].startswith(f"path={worktree_bin}:")
63
+
64
+
65
+ def test_no_mistakes_repo_config_defines_deterministic_commands() -> None:
66
+ config = yaml.safe_load(Path(".no-mistakes.yaml").read_text(encoding="utf-8"))
67
+
68
+ assert config["commands"] == {
69
+ "test": "scripts/no_mistakes_run.sh test",
70
+ "lint": "scripts/no_mistakes_run.sh lint",
71
+ "format": "scripts/no_mistakes_run.sh format",
72
+ }
73
+ assert config["auto_fix"]["review"] == 0
74
+ assert config["auto_fix"]["test"] == 3
75
+ assert config["auto_fix"]["lint"] == 3
76
+
77
+
78
+ def test_no_mistakes_run_script_uses_trusted_python_for_configured_commands(
79
+ tmp_path: Path,
80
+ ) -> None:
81
+ repo = tmp_path / "repo"
82
+ script_dir = repo / "scripts"
83
+ script_dir.mkdir(parents=True)
84
+ shutil.copy2(
85
+ Path("scripts/no_mistakes_run.sh"),
86
+ script_dir / "no_mistakes_run.sh",
87
+ )
88
+
89
+ fake_bin = repo / ".venv" / "bin"
90
+ fake_bin.mkdir(parents=True)
91
+ (repo / ".venv" / "pyvenv.cfg").write_text("home = /usr/bin\n", encoding="utf-8")
92
+ log_path = tmp_path / "python-args.log"
93
+ _write_executable(
94
+ fake_bin / "python",
95
+ "#!/usr/bin/env python3\n"
96
+ "import os, pathlib, sys\n"
97
+ "if len(sys.argv) > 1 and sys.argv[1] == '-':\n"
98
+ " sys.stdin.read()\n"
99
+ " raise SystemExit(0)\n"
100
+ "log = pathlib.Path(os.environ['FAKE_PYTHON_LOG'])\n"
101
+ "with log.open('a', encoding='utf-8') as fh:\n"
102
+ " fh.write(repr(sys.argv[1:]) + '\\n')\n",
103
+ )
104
+
105
+ env = os.environ.copy()
106
+ env["CTX_NO_MISTAKES_PYTHON_BIN"] = str(fake_bin)
107
+ env["FAKE_PYTHON_LOG"] = str(log_path)
108
+
109
+ subprocess.run(
110
+ ["bash", str(script_dir / "no_mistakes_run.sh"), "test"],
111
+ cwd=repo,
112
+ env=env,
113
+ check=True,
114
+ )
115
+ subprocess.run(
116
+ ["bash", str(script_dir / "no_mistakes_run.sh"), "lint"],
117
+ cwd=repo,
118
+ env=env,
119
+ check=True,
120
+ )
121
+
122
+ assert log_path.read_text(encoding="utf-8").splitlines() == [
123
+ "['scripts/ci_preflight.py', '--profile', 'pr']",
124
+ "['-m', 'ruff', 'check', '.']",
125
+ "['-m', 'ruff', 'format', '--check', 'src', 'hooks', 'scripts']",
126
+ "['-m', 'mypy', 'src']",
127
+ ]
src/tests/test_pack_full_wiki_tar.py CHANGED
@@ -3,6 +3,7 @@ from __future__ import annotations
3
  import io
4
  import json
5
  import tarfile
 
6
  from pathlib import Path
7
 
8
  from ctx.core.wiki.wiki_packs import load_merged_wiki_pages
@@ -23,11 +24,23 @@ def test_repack_full_wiki_tar_moves_high_fanout_pages_into_wiki_pack(
23
  target = tmp_path / "wiki-graph-packed.tar.gz"
24
  with tarfile.open(source, "w:gz") as tf:
25
  _add_text(tf, "index.md", "# Wiki\n")
26
- _add_text(tf, "entities/skills/current.md", "# Current Skill\n")
 
 
 
 
 
 
 
 
27
  _add_text(tf, "entities/skills/empty.md", "")
28
  _add_text(tf, "entities/agents/reviewer.md", "# Reviewer Agent\n")
29
  _add_text(tf, "entities/mcp-servers/github.md", "# GitHub MCP\n")
30
- _add_text(tf, "entities/harnesses/langgraph.md", "# LangGraph Harness\n")
 
 
 
 
31
  _add_text(tf, "concepts/empty.md", "")
32
  _add_text(
33
  tf,
@@ -40,7 +53,7 @@ def test_repack_full_wiki_tar_moves_high_fanout_pages_into_wiki_pack(
40
 
41
  stats = repack_full_wiki_tar(source, target)
42
 
43
- assert stats.removed_expanded_markdown_pages == 5
44
  assert stats.packed_pages == 8
45
  with tarfile.open(target, "r:gz") as tf:
46
  names = {member.name for member in tf.getmembers()}
@@ -52,16 +65,31 @@ def test_repack_full_wiki_tar_moves_high_fanout_pages_into_wiki_pack(
52
  assert "entities/mcp-servers/github.md" not in names
53
  assert "entities/harnesses/langgraph.md" in names
54
  assert "concepts/empty.md" not in names
 
 
 
 
55
  assert "graphify-out/graph-report.md" in names
56
  assert "wiki-packs/base-test-export/wiki-pack-manifest.json" in names
57
  assert "wiki-packs/base-test-export/pages.jsonl" in names
 
 
 
 
 
58
 
59
  pages = load_merged_wiki_pages(tmp_path / "extracted" / "wiki-packs")
60
- assert pages["entities/skills/current.md"] == "# Current Skill\n"
 
 
61
  assert pages["entities/skills/empty.md"] == "<!-- empty markdown page -->\n"
62
  assert pages["entities/agents/reviewer.md"] == "# Reviewer Agent\n"
63
  assert pages["entities/mcp-servers/github.md"] == "# GitHub MCP\n"
64
  assert pages["concepts/empty.md"] == "<!-- empty markdown page -->\n"
 
 
 
 
65
 
66
  second_target = tmp_path / "wiki-graph-packed-again.tar.gz"
67
  repack_full_wiki_tar(target, second_target)
@@ -70,6 +98,95 @@ def test_repack_full_wiki_tar_moves_high_fanout_pages_into_wiki_pack(
70
  tf.extractall(tmp_path / "extracted-again")
71
  assert "graphify-out/graph-report.md" in second_names
72
  repacked_pages = load_merged_wiki_pages(tmp_path / "extracted-again" / "wiki-packs")
73
- assert repacked_pages["entities/skills/current.md"] == "# Current Skill\n"
 
 
 
74
  assert repacked_pages["entities/agents/reviewer.md"] == "# Reviewer Agent\n"
75
  assert repacked_pages["entities/mcp-servers/github.md"] == "# GitHub MCP\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import io
4
  import json
5
  import tarfile
6
+ from hashlib import sha256
7
  from pathlib import Path
8
 
9
  from ctx.core.wiki.wiki_packs import load_merged_wiki_pages
 
24
  target = tmp_path / "wiki-graph-packed.tar.gz"
25
  with tarfile.open(source, "w:gz") as tf:
26
  _add_text(tf, "index.md", "# Wiki\n")
27
+ _add_text(tf, "catalog.md", "| skill | `C:\\Users\\steves\\ctx\\SKILL.md` |\n")
28
+ _add_text(tf, "converted-index.md", "`/Users/steves/ctx/converted`\n")
29
+ _add_text(tf, "log.md", "local export: /Users/steves/ctx C:\\Users\\steves\\ctx\n")
30
+ _add_text(tf, "versions-catalog.md", "`C:\\Users\\steves\\ctx\\versions`\n")
31
+ _add_text(
32
+ tf,
33
+ "entities/skills/current.md",
34
+ "# Current Skill\nSource: /Users/steves/ctx\nLinux: /home/steves/ctx\n",
35
+ )
36
  _add_text(tf, "entities/skills/empty.md", "")
37
  _add_text(tf, "entities/agents/reviewer.md", "# Reviewer Agent\n")
38
  _add_text(tf, "entities/mcp-servers/github.md", "# GitHub MCP\n")
39
+ _add_text(
40
+ tf,
41
+ "entities/harnesses/langgraph.md",
42
+ "# LangGraph Harness\nRun C:\\Users\\steves\\ctx\\harness.py\n",
43
+ )
44
  _add_text(tf, "concepts/empty.md", "")
45
  _add_text(
46
  tf,
 
53
 
54
  stats = repack_full_wiki_tar(source, target)
55
 
56
+ assert stats.removed_expanded_markdown_pages == 9
57
  assert stats.packed_pages == 8
58
  with tarfile.open(target, "r:gz") as tf:
59
  names = {member.name for member in tf.getmembers()}
 
65
  assert "entities/mcp-servers/github.md" not in names
66
  assert "entities/harnesses/langgraph.md" in names
67
  assert "concepts/empty.md" not in names
68
+ assert "catalog.md" not in names
69
+ assert "converted-index.md" not in names
70
+ assert "log.md" not in names
71
+ assert "versions-catalog.md" not in names
72
  assert "graphify-out/graph-report.md" in names
73
  assert "wiki-packs/base-test-export/wiki-pack-manifest.json" in names
74
  assert "wiki-packs/base-test-export/pages.jsonl" in names
75
+ harness_text = (tmp_path / "extracted" / "entities" / "harnesses" / "langgraph.md").read_text(
76
+ encoding="utf-8"
77
+ )
78
+ assert "C:\\Users\\steves" not in harness_text
79
+ assert "<host-user-path>" in harness_text
80
 
81
  pages = load_merged_wiki_pages(tmp_path / "extracted" / "wiki-packs")
82
+ assert pages["entities/skills/current.md"] == (
83
+ "# Current Skill\nSource: <host-user-path>\nLinux: <host-user-path>\n"
84
+ )
85
  assert pages["entities/skills/empty.md"] == "<!-- empty markdown page -->\n"
86
  assert pages["entities/agents/reviewer.md"] == "# Reviewer Agent\n"
87
  assert pages["entities/mcp-servers/github.md"] == "# GitHub MCP\n"
88
  assert pages["concepts/empty.md"] == "<!-- empty markdown page -->\n"
89
+ assert "catalog.md" not in pages
90
+ assert "converted-index.md" not in pages
91
+ assert "log.md" not in pages
92
+ assert "versions-catalog.md" not in pages
93
 
94
  second_target = tmp_path / "wiki-graph-packed-again.tar.gz"
95
  repack_full_wiki_tar(target, second_target)
 
98
  tf.extractall(tmp_path / "extracted-again")
99
  assert "graphify-out/graph-report.md" in second_names
100
  repacked_pages = load_merged_wiki_pages(tmp_path / "extracted-again" / "wiki-packs")
101
+ assert (
102
+ repacked_pages["entities/skills/current.md"]
103
+ == "# Current Skill\nSource: <host-user-path>\nLinux: <host-user-path>\n"
104
+ )
105
  assert repacked_pages["entities/agents/reviewer.md"] == "# Reviewer Agent\n"
106
  assert repacked_pages["entities/mcp-servers/github.md"] == "# GitHub MCP\n"
107
+ assert "catalog.md" not in repacked_pages
108
+
109
+
110
+ def test_repack_full_wiki_tar_redacts_file_uri_host_paths(tmp_path: Path) -> None:
111
+ source = tmp_path / "wiki-graph.tar.gz"
112
+ target = tmp_path / "wiki-graph-packed.tar.gz"
113
+ with tarfile.open(source, "w:gz") as tf:
114
+ _add_text(
115
+ tf,
116
+ "entities/skills/current.md",
117
+ "macOS: file:///Users/steves/ctx\nLinux: file:///home/steves/ctx\n",
118
+ )
119
+ _add_text(
120
+ tf,
121
+ "graphify-out/graph-export-manifest.json",
122
+ json.dumps({"export_id": "test-export"}),
123
+ )
124
+
125
+ repack_full_wiki_tar(source, target)
126
+
127
+ with tarfile.open(target, "r:gz") as tf:
128
+ tf.extractall(tmp_path / "extracted")
129
+ pages = load_merged_wiki_pages(tmp_path / "extracted" / "wiki-packs")
130
+ assert pages["entities/skills/current.md"] == (
131
+ "macOS: <host-user-path>\nLinux: <host-user-path>\n"
132
+ )
133
+
134
+
135
+ def test_repack_full_wiki_tar_preserves_graph_pack_checksums(tmp_path: Path) -> None:
136
+ source = tmp_path / "wiki-graph.tar.gz"
137
+ target = tmp_path / "wiki-graph-packed.tar.gz"
138
+ graph_pack_payload = (
139
+ '{"graph":{"export_id":"test-export"},"nodes":[{"id":"/Users/steves/private"}],'
140
+ '"edges":[]}\n'
141
+ )
142
+ graph_pack_manifest = {
143
+ "schema_version": 1,
144
+ "pack_id": "base-test-export",
145
+ "pack_type": "base",
146
+ "base_export_id": "test-export",
147
+ "parent_export_id": None,
148
+ "config_hash": "config-sha",
149
+ "model_id": "test-model",
150
+ "node_count": 1,
151
+ "edge_count": 0,
152
+ "tombstone_count": 0,
153
+ "checksums": {"graph.json": sha256(graph_pack_payload.encode("utf-8")).hexdigest()},
154
+ }
155
+ with tarfile.open(source, "w:gz") as tf:
156
+ _add_text(
157
+ tf,
158
+ "graphify-out/graph-export-manifest.json",
159
+ json.dumps({"export_id": "test-export"}),
160
+ )
161
+ _add_text(
162
+ tf,
163
+ "graphify-out/graph.json",
164
+ '{"nodes":[{"id":"/Users/steves/private"}],"edges":[]}\n',
165
+ )
166
+ _add_text(
167
+ tf,
168
+ "graphify-out/packs/base-test-export/graph-pack-manifest.json",
169
+ json.dumps(graph_pack_manifest),
170
+ )
171
+ _add_text(tf, "graphify-out/packs/base-test-export/graph.json", graph_pack_payload)
172
+
173
+ repack_full_wiki_tar(source, target)
174
+
175
+ with tarfile.open(target, "r:gz") as tf:
176
+ top_graph = tf.extractfile("graphify-out/graph.json")
177
+ pack_graph = tf.extractfile("graphify-out/packs/base-test-export/graph.json")
178
+ pack_manifest = tf.extractfile(
179
+ "graphify-out/packs/base-test-export/graph-pack-manifest.json"
180
+ )
181
+ assert top_graph is not None
182
+ assert pack_graph is not None
183
+ assert pack_manifest is not None
184
+ top_graph_text = top_graph.read().decode("utf-8")
185
+ pack_graph_text = pack_graph.read().decode("utf-8")
186
+ manifest = json.loads(pack_manifest.read().decode("utf-8"))
187
+
188
+ assert "/Users/steves/private" not in top_graph_text
189
+ assert "/Users/steves/private" in pack_graph_text
190
+ assert (
191
+ manifest["checksums"]["graph.json"] == sha256(pack_graph_text.encode("utf-8")).hexdigest()
192
+ )
src/tests/test_release_graph_count_sync.py CHANGED
@@ -2,6 +2,7 @@ from __future__ import annotations
2
 
3
  import json
4
  from pathlib import Path
 
5
  from urllib.parse import quote
6
 
7
  import yaml # type: ignore[import-untyped]
@@ -50,6 +51,21 @@ def _workflow_job_steps(path: str, job_name: str) -> list[dict[str, object]]:
50
  return steps
51
 
52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  def _graph_contract_counts() -> dict[str, int]:
54
  flags = _flag_values(GRAPH_VALIDATE_ARGS[1:])
55
  return {
@@ -99,6 +115,24 @@ def test_pr_graph_check_runs_repo_stats_after_artifact_validation() -> None:
99
  assert steps[stats_index]["run"] == "python src/update_repo_stats.py --check"
100
 
101
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  def test_public_docs_and_readmes_expose_current_graph_counts() -> None:
103
  counts = _graph_contract_counts()
104
  core_nodes = counts["nodes"] - counts["body_backed_skills"]
 
2
 
3
  import json
4
  from pathlib import Path
5
+ import subprocess
6
  from urllib.parse import quote
7
 
8
  import yaml # type: ignore[import-untyped]
 
51
  return steps
52
 
53
 
54
+ def _head_lfs_pointer(path: str) -> dict[str, int | str]:
55
+ pointer = subprocess.check_output(
56
+ ["git", "cat-file", "-p", f"HEAD:{path}"],
57
+ text=True,
58
+ )
59
+ values: dict[str, int | str] = {}
60
+ for line in pointer.splitlines():
61
+ if line.startswith("oid sha256:"):
62
+ values["sha256"] = line.split(":", 1)[1].strip()
63
+ elif line.startswith("size "):
64
+ values["size"] = int(line.split(" ", 1)[1].strip())
65
+ assert values.keys() == {"sha256", "size"}
66
+ return values
67
+
68
+
69
  def _graph_contract_counts() -> dict[str, int]:
70
  flags = _flag_values(GRAPH_VALIDATE_ARGS[1:])
71
  return {
 
115
  assert steps[stats_index]["run"] == "python src/update_repo_stats.py --check"
116
 
117
 
118
+ def test_graph_release_metadata_matches_committed_lfs_pointers() -> None:
119
+ full = _head_lfs_pointer("graph/wiki-graph.tar.gz")
120
+ runtime = _head_lfs_pointer("graph/wiki-graph-runtime.tar.gz")
121
+ stats = json.loads(Path("graph/wiki-graph-stats.json").read_text(encoding="utf-8"))
122
+
123
+ assert stats["artifact"] == {"path": "graph/wiki-graph.tar.gz", **full}
124
+
125
+ for workflow_path in (
126
+ ".github/workflows/test.yml",
127
+ ".github/workflows/publish.yml",
128
+ ".github/workflows/huggingface-sync.yml",
129
+ ):
130
+ workflow = Path(workflow_path).read_text(encoding="utf-8")
131
+ for pointer in (full, runtime):
132
+ assert f'"sha256": "{pointer["sha256"]}"' in workflow
133
+ assert f'"size": {pointer["size"]}' in workflow
134
+
135
+
136
  def test_public_docs_and_readmes_expose_current_graph_counts() -> None:
137
  counts = _graph_contract_counts()
138
  core_nodes = counts["nodes"] - counts["body_backed_skills"]
src/tests/test_review_findings.py ADDED
@@ -0,0 +1,682 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import sys
5
+ import tarfile
6
+ from contextlib import nullcontext
7
+ from hashlib import sha256
8
+ from io import BytesIO
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import pytest
13
+
14
+ ROOT = Path(__file__).resolve().parents[2]
15
+ SRC = ROOT / "src"
16
+ SCRIPTS = ROOT / "scripts"
17
+ for path in (SRC, SCRIPTS):
18
+ if str(path) not in sys.path:
19
+ sys.path.insert(0, str(path))
20
+
21
+ import backup_config as bc # noqa: E402
22
+ import ci_preflight # noqa: E402
23
+ import ci_no_test_policy # noqa: E402
24
+ import pack_full_wiki_tar # noqa: E402
25
+ import sync_huggingface # noqa: E402
26
+ import validate_graph_artifacts as vga # noqa: E402
27
+ from ctx import dashboard_entities # noqa: E402
28
+ from ctx.core.wiki import wiki_queue_worker # noqa: E402
29
+ from ctx.utils._secret_scan import find_inline_secret_arg # noqa: E402
30
+
31
+
32
+ class _FakeCommitInfo:
33
+ commit_url = "https://huggingface.co/datasets/Stevesolun/ctx/commit/card"
34
+
35
+
36
+ class _FakeHfApi:
37
+ def __init__(self) -> None:
38
+ self.calls: list[tuple[str, dict[str, Any]]] = []
39
+
40
+ def upload_folder(self, **kwargs: Any) -> _FakeCommitInfo:
41
+ self.calls.append(("upload_folder", kwargs))
42
+ return _FakeCommitInfo()
43
+
44
+
45
+ def _add_tar_text(tf: tarfile.TarFile, name: str, text: str) -> None:
46
+ payload = text.encode("utf-8")
47
+ info = tarfile.TarInfo(name)
48
+ info.size = len(payload)
49
+ tf.addfile(info, BytesIO(payload))
50
+
51
+
52
+ def test_artifact_promotion_retry_allows_completed_promotion_recovery(tmp_path: Path) -> None:
53
+ wiki = tmp_path / "wiki"
54
+ target = wiki / "graphify-out" / "graph.json"
55
+ target.parent.mkdir(parents=True)
56
+ payload = b'{"nodes":[],"edges":[],"graph":{}}\n'
57
+ target.write_bytes(payload)
58
+ staged = target.with_name(f"{target.name}.staged")
59
+ metadata = target.with_name(f"{target.name}.promotion.json")
60
+ metadata.write_text(
61
+ json.dumps(
62
+ {
63
+ "schema_version": 1,
64
+ "status": "staged",
65
+ "target": str(target),
66
+ "previous": {},
67
+ "candidate": {"sha256": sha256(payload).hexdigest()},
68
+ }
69
+ ),
70
+ encoding="utf-8",
71
+ )
72
+
73
+ message = wiki_queue_worker._handle_artifact_promotion(
74
+ wiki,
75
+ {
76
+ "staged_path": staged.name,
77
+ "target_path": "graphify-out/graph.json",
78
+ },
79
+ )
80
+
81
+ assert message == f"promoted artifact to {target}"
82
+ assert json.loads(metadata.read_text(encoding="utf-8"))["status"] == "promoted"
83
+
84
+
85
+ def test_from_ctx_config_ignores_malformed_user_top_files(
86
+ monkeypatch: Any,
87
+ tmp_path: Path,
88
+ capsys: Any,
89
+ ) -> None:
90
+ monkeypatch.setenv("HOME", str(tmp_path))
91
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
92
+ claude_dir = tmp_path / ".claude"
93
+ claude_dir.mkdir()
94
+ (claude_dir / "backup-config.json").write_text(
95
+ json.dumps({"top_files": ["safe.json", "../secret.json", "nested/file.json"]}),
96
+ encoding="utf-8",
97
+ )
98
+
99
+ cfg = bc.from_ctx_config()
100
+
101
+ assert cfg.top_files == ("safe.json",)
102
+ assert "ignoring top_files entry" in capsys.readouterr().err
103
+
104
+
105
+ def test_from_ctx_config_fails_closed_when_user_top_files_all_invalid(
106
+ monkeypatch: Any,
107
+ tmp_path: Path,
108
+ ) -> None:
109
+ monkeypatch.setenv("HOME", str(tmp_path))
110
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
111
+ claude_dir = tmp_path / ".claude"
112
+ claude_dir.mkdir()
113
+ (claude_dir / "backup-config.json").write_text(
114
+ json.dumps({"top_files": ["../secret.json", "nested/file.json"]}),
115
+ encoding="utf-8",
116
+ )
117
+
118
+ cfg = bc.from_ctx_config()
119
+
120
+ assert cfg.top_files == bc.BackupConfig().top_files
121
+
122
+
123
+ def test_host_user_path_redaction_covers_paths_with_spaces() -> None:
124
+ text = (
125
+ "POSIX `/Users/steves/My Project/wiki page.md`\n"
126
+ "Windows C:\\Users\\steves\\My Project\\wiki page.md\n"
127
+ )
128
+
129
+ redacted = pack_full_wiki_tar._redact_host_user_paths(text)
130
+
131
+ assert "/Users/" not in redacted
132
+ assert "C:\\Users" not in redacted
133
+ assert "My Project" not in redacted
134
+ assert redacted.count("<host-user-path>") == 2
135
+
136
+
137
+ def test_host_user_path_redaction_covers_terminal_spaced_component() -> None:
138
+ text = (
139
+ "/Users/steves/My Project\n"
140
+ "/Users/steves/my project\n"
141
+ "/home/steves/lower case dir\n"
142
+ "`/Users/steves/lower case dir`\n"
143
+ )
144
+
145
+ redacted = pack_full_wiki_tar._redact_host_user_paths(text)
146
+
147
+ assert redacted == (
148
+ "<host-user-path>\n<host-user-path>\n<host-user-path>\n`<host-user-path>`\n"
149
+ )
150
+
151
+
152
+ def test_host_user_path_redaction_preserves_trailing_prose() -> None:
153
+ redacted = pack_full_wiki_tar._redact_host_user_paths(
154
+ "/Users/steves/ctx generated by worker\n"
155
+ "/Users/steves/ctx for details\n"
156
+ "/Users/steves/my project, generated by worker\n"
157
+ )
158
+
159
+ assert redacted == (
160
+ "<host-user-path> generated by worker\n"
161
+ "<host-user-path> for details\n"
162
+ "<host-user-path>, generated by worker\n"
163
+ )
164
+
165
+
166
+ def test_secret_arg_indirection_validates_env_reference_values() -> None:
167
+ assert find_inline_secret_arg(["--token-env=secret-value"]) == "--token-env"
168
+ assert (
169
+ find_inline_secret_arg(["--token-env=ghp_abcdefghijklmnopqrstuvwxyz123456"])
170
+ == "--token-env"
171
+ )
172
+ assert find_inline_secret_arg(["--token-env", "secret-value"]) == "--token-env"
173
+ assert find_inline_secret_arg(["--token-env=ABCDEF1234567890"]) == "--token-env"
174
+ assert find_inline_secret_arg(["--token_env=GITHUB_TOKEN"]) is None
175
+ assert find_inline_secret_arg(["--api_key_path=/run/secrets/openai"]) is None
176
+ assert find_inline_secret_arg(["--api-key-path", "hunter2"]) == "--api-key-path"
177
+ assert find_inline_secret_arg(["--api-key-file=secret-value"]) == "--api-key-file"
178
+ assert find_inline_secret_arg(["--api_key_path=./secrets/openai"]) is None
179
+ assert find_inline_secret_arg(["--api-key-path=${OPENAI_API_KEY_PATH}"]) is None
180
+
181
+
182
+ def test_no_test_policy_treats_no_mistakes_config_as_contract_file() -> None:
183
+ result = ci_no_test_policy.evaluate_policy(
184
+ [".no-mistakes.yaml"],
185
+ (),
186
+ {".no-mistakes.yaml": "+commands: changed\n"},
187
+ )
188
+
189
+ assert result.passed is False
190
+ assert result.contract_files == (".no-mistakes.yaml",)
191
+
192
+
193
+ def test_host_user_path_redaction_covers_key_value_delimiters() -> None:
194
+ text = (
195
+ "cwd=/Users/steves/ctx\nsource:/home/steves/wiki\nurl=https://example.com/home/user-guide\n"
196
+ "User: /validate /home/user/webapp --vuln-type command_injection\n"
197
+ "Binary: /home/user/binary_app/build/vuln\n"
198
+ "Rule: No `/home/` hardcoded path prefixes\n"
199
+ )
200
+
201
+ redacted = pack_full_wiki_tar._redact_host_user_paths(text)
202
+
203
+ assert "/Users/" not in redacted
204
+ assert "/home/steves" not in redacted
205
+ assert "/home/user/" not in redacted
206
+ assert "`/home/`" not in redacted
207
+ assert "https://example.com/home/user-guide" in redacted
208
+ assert redacted.count("<host-user-path>") == 5
209
+
210
+
211
+ @pytest.mark.parametrize(
212
+ "payload",
213
+ [
214
+ b"cwd=/Users/steves/ctx\n",
215
+ b"source:/home/steves/wiki\n",
216
+ b"path,C:\\Users\\steves\\ctx\n",
217
+ b"path,C:\\users\\steves\\ctx\n",
218
+ b"path,C:/users/steves/ctx\n",
219
+ b"url=file:///C:/Users/alice/ctx\n",
220
+ ],
221
+ )
222
+ def test_graph_markdown_host_path_scan_covers_key_value_delimiters(payload: bytes) -> None:
223
+ with pytest.raises(vga.GraphArtifactError, match="archive markdown contains host path"):
224
+ vga._validate_archive_markdown_payload("log.md", payload, context="archive")
225
+
226
+
227
+ @pytest.mark.parametrize(
228
+ "workflow_path",
229
+ [
230
+ ".github/workflows/huggingface-sync.yml",
231
+ ".github/workflows/publish.yml",
232
+ ".github/workflows/test.yml",
233
+ ],
234
+ )
235
+ def test_graph_workflow_searches_release_cache_before_lfs_fallback(
236
+ workflow_path: str,
237
+ ) -> None:
238
+ workflow = (ROOT / workflow_path).read_text(encoding="utf-8")
239
+ resolve_script = workflow[workflow.index("def hydrate_from_release") :]
240
+
241
+ release_search = resolve_script.index("for release in load_releases():")
242
+ lfs_fallback = resolve_script.rindex(
243
+ "hydrate_from_lfs(path_name, expected_oid, expected_size, hydrated_min_size)"
244
+ )
245
+
246
+ assert release_search < lfs_fallback
247
+ assert (
248
+ "hydrate_from_lfs(path_name, expected_oid, expected_size, hydrated_min_size)"
249
+ not in resolve_script[:release_search]
250
+ )
251
+ assert 'if expected_oid != fallback["sha256"]' not in resolve_script
252
+
253
+
254
+ def test_preflight_refuses_oversized_graph_lfs_pointer_before_pull(
255
+ monkeypatch: Any,
256
+ tmp_path: Path,
257
+ capsys: Any,
258
+ ) -> None:
259
+ monkeypatch.setattr(ci_preflight, "REPO_ROOT", tmp_path)
260
+ artifact = tmp_path / "graph" / "wiki-graph.tar.gz"
261
+ artifact.parent.mkdir()
262
+ max_size = ci_preflight.GRAPH_LFS_MAX_FALLBACK_SIZES["graph/wiki-graph.tar.gz"]
263
+ artifact.write_text(
264
+ f"version https://git-lfs.github.com/spec/v1\noid sha256:{'a' * 64}\nsize {max_size + 1}\n",
265
+ encoding="utf-8",
266
+ )
267
+ monkeypatch.setattr(ci_preflight.shutil, "which", lambda _name: "/usr/bin/git")
268
+
269
+ def fail_run(*_args: Any, **_kwargs: Any) -> None:
270
+ raise AssertionError("git lfs pull should not run")
271
+
272
+ monkeypatch.setattr(ci_preflight.subprocess, "run", fail_run)
273
+
274
+ assert ci_preflight.hydrate_graph_lfs_artifacts() == 1
275
+ assert "exceeds cap" in capsys.readouterr().err
276
+
277
+
278
+ def test_hf_card_export_uploads_docs_and_changelog(
279
+ monkeypatch: Any,
280
+ tmp_path: Path,
281
+ ) -> None:
282
+ repo = tmp_path / "repo"
283
+ export_dir = tmp_path / "export"
284
+ (repo / "docs").mkdir(parents=True)
285
+ export_dir.mkdir()
286
+ (repo / "README.md").write_text("# ctx\n", encoding="utf-8")
287
+ (repo / "CHANGELOG.md").write_text("# Changelog\n", encoding="utf-8")
288
+ (repo / "docs" / "guide.md").write_text("# Guide\n", encoding="utf-8")
289
+ monkeypatch.setattr(
290
+ sync_huggingface,
291
+ "_iter_tracked_files",
292
+ lambda _repo: [
293
+ Path("README.md"),
294
+ Path("CHANGELOG.md"),
295
+ Path("docs/guide.md"),
296
+ Path("src/not-card.py"),
297
+ ],
298
+ )
299
+
300
+ sync_huggingface._export_card_inputs(repo, export_dir)
301
+
302
+ assert (export_dir / "README.md").read_text(encoding="utf-8").startswith("---\nlicense: mit\n")
303
+ assert (export_dir / "CHANGELOG.md").read_text(encoding="utf-8") == "# Changelog\n"
304
+ assert (export_dir / "docs" / "guide.md").read_text(encoding="utf-8") == "# Guide\n"
305
+ assert not (export_dir / "src").exists()
306
+
307
+ api = _FakeHfApi()
308
+ url = sync_huggingface._upload_card_inputs(
309
+ api=api,
310
+ export_dir=export_dir,
311
+ repo_id="Stevesolun/ctx",
312
+ repo_type="dataset",
313
+ head="abcdef1234567890",
314
+ )
315
+
316
+ assert url == "https://huggingface.co/datasets/Stevesolun/ctx/commit/card"
317
+ assert api.calls == [
318
+ (
319
+ "upload_folder",
320
+ {
321
+ "repo_id": "Stevesolun/ctx",
322
+ "repo_type": "dataset",
323
+ "folder_path": str(export_dir),
324
+ "commit_message": "Sync ctx card abcdef1",
325
+ "commit_description": "GitHub commit: abcdef1234567890",
326
+ "delete_patterns": list(sync_huggingface.CARD_ONLY_DELETE_PATTERNS),
327
+ },
328
+ )
329
+ ]
330
+
331
+
332
+ def test_hf_export_rejects_raw_tracked_symlink(tmp_path: Path) -> None:
333
+ repo = tmp_path / "repo"
334
+ export_dir = tmp_path / "export"
335
+ docs = repo / "docs"
336
+ docs.mkdir(parents=True)
337
+ export_dir.mkdir()
338
+ (repo / "guide-source.md").write_text("# Guide\n", encoding="utf-8")
339
+ (docs / "guide.md").symlink_to(repo / "guide-source.md")
340
+
341
+ with pytest.raises(ValueError, match="refusing to follow symlink"):
342
+ sync_huggingface._copy_export_file(
343
+ repo.resolve(),
344
+ export_dir.resolve(),
345
+ Path("docs/guide.md"),
346
+ )
347
+
348
+
349
+ def test_hf_card_sync_checks_repo_stats_before_export(
350
+ monkeypatch: Any,
351
+ tmp_path: Path,
352
+ ) -> None:
353
+ calls: list[str] = []
354
+
355
+ class FakeApi:
356
+ def __init__(self, *, token: str) -> None:
357
+ calls.append(f"api:{token}")
358
+
359
+ fake_hub = type(sys)("huggingface_hub")
360
+ setattr(fake_hub, "HfApi", FakeApi)
361
+ monkeypatch.setitem(sys.modules, "huggingface_hub", fake_hub)
362
+ monkeypatch.setattr(
363
+ sync_huggingface,
364
+ "_git",
365
+ lambda _repo, *_args: "abcdef1234567890",
366
+ )
367
+ monkeypatch.setattr(
368
+ sync_huggingface,
369
+ "_assert_repo_stats_current",
370
+ lambda _repo: calls.append("stats"),
371
+ )
372
+
373
+ def fake_export(_repo: Path, _export_dir: Path) -> None:
374
+ calls.append("export")
375
+
376
+ monkeypatch.setattr(sync_huggingface, "_export_card_inputs", fake_export)
377
+ monkeypatch.setattr(
378
+ sync_huggingface,
379
+ "_ensure_hf_repo_exists",
380
+ lambda **_kwargs: calls.append("ensure"),
381
+ )
382
+
383
+ def fake_upload(**_kwargs: Any) -> str:
384
+ calls.append("upload")
385
+ return "https://example.test/commit"
386
+
387
+ monkeypatch.setattr(
388
+ sync_huggingface,
389
+ "_upload_card_inputs",
390
+ fake_upload,
391
+ )
392
+
393
+ url = sync_huggingface.sync_card_to_huggingface(
394
+ repo=tmp_path,
395
+ repo_id="Stevesolun/ctx",
396
+ repo_type="dataset",
397
+ token="hf-token",
398
+ )
399
+
400
+ assert url == "https://example.test/commit"
401
+ assert calls == ["stats", "export", "api:hf-token", "ensure", "upload"]
402
+
403
+
404
+ def test_mcp_env_placeholders_do_not_expand_credentials_into_argv_by_default(
405
+ monkeypatch: Any,
406
+ ) -> None:
407
+ from ctx.adapters.generic.tools import McpServerConfig, mcp_router
408
+
409
+ monkeypatch.setenv("MCP_API_KEY", "argv-only-secret")
410
+ cfg = McpServerConfig(
411
+ name="argvserver",
412
+ command="server",
413
+ args=("--api-key", "${MCP_API_KEY}", "--header=Bearer $MCP_API_KEY"),
414
+ credential_env=("MCP_API_KEY",),
415
+ )
416
+
417
+ env = mcp_router._child_env_for_config(cfg)
418
+
419
+ assert mcp_router._expand_config_args(cfg, env) == (
420
+ "--api-key",
421
+ "${MCP_API_KEY}",
422
+ "--header=Bearer $MCP_API_KEY",
423
+ )
424
+ assert cfg.args[1] == "${MCP_API_KEY}"
425
+
426
+
427
+ def test_mcp_env_placeholder_expansion_checks_option_context() -> None:
428
+ from ctx.adapters.generic.tools import McpServerConfig, mcp_router
429
+
430
+ cfg = McpServerConfig(
431
+ name="argvserver",
432
+ command="server",
433
+ args=("--api-key", "${OPENAI_KEY}"),
434
+ env={"OPENAI_KEY": "argv-only-secret"},
435
+ expand_argv_env=True,
436
+ )
437
+
438
+ with pytest.raises(ValueError, match="secret-looking argument '--api-key'"):
439
+ mcp_router._expand_config_args(cfg, mcp_router._child_env_for_config(cfg))
440
+
441
+
442
+ def test_mcp_env_placeholder_expansion_rejects_bearer_header() -> None:
443
+ from ctx.adapters.generic.tools import McpServerConfig, mcp_router
444
+
445
+ cfg = McpServerConfig(
446
+ name="argvserver",
447
+ command="server",
448
+ args=("--header=Bearer ${MCP_AUTH}",),
449
+ env={"MCP_AUTH": "headersecret"},
450
+ expand_argv_env=True,
451
+ )
452
+
453
+ with pytest.raises(ValueError, match="secret-looking argument 'Bearer'"):
454
+ mcp_router._expand_config_args(cfg, mcp_router._child_env_for_config(cfg))
455
+
456
+
457
+ def test_artifact_promotion_rejects_repo_graph_target_from_untrusted_project(
458
+ monkeypatch: Any,
459
+ tmp_path: Path,
460
+ ) -> None:
461
+ host_project = tmp_path / "host-project"
462
+ wiki = tmp_path / "wiki"
463
+ target = host_project / "graph" / "wiki-graph-stats.json"
464
+ staged = target.with_name(f"{target.name}.staged")
465
+ installed_worker = host_project / ".venv" / "site-packages" / "ctx" / "core" / "wiki"
466
+ target.parent.mkdir(parents=True)
467
+ installed_worker.mkdir(parents=True)
468
+ staged.write_text("{}", encoding="utf-8")
469
+ (host_project / "pyproject.toml").write_text(
470
+ '[project]\nname = "not-ctx"\n',
471
+ encoding="utf-8",
472
+ )
473
+ fake_source = installed_worker / "wiki_queue_worker.py"
474
+ fake_source.write_text("# installed worker\n", encoding="utf-8")
475
+ monkeypatch.setattr(wiki_queue_worker, "__file__", str(fake_source))
476
+
477
+ assert wiki_queue_worker._source_root() is None
478
+
479
+ with pytest.raises(ValueError, match="not an allowed artifact target"):
480
+ wiki_queue_worker._resolve_artifact_promotion_paths(
481
+ wiki,
482
+ str(staged),
483
+ str(target),
484
+ )
485
+
486
+
487
+ def test_repack_full_wiki_tar_redacts_graph_json_host_paths(tmp_path: Path) -> None:
488
+ source = tmp_path / "wiki-graph.tar.gz"
489
+ target = tmp_path / "wiki-graph-packed.tar.gz"
490
+ with tarfile.open(source, "w:gz") as tf:
491
+ _add_tar_text(tf, "index.md", "# Wiki\n")
492
+ _add_tar_text(
493
+ tf,
494
+ "entities/skills/example.md",
495
+ "# Example\n",
496
+ )
497
+ _add_tar_text(
498
+ tf,
499
+ "graphify-out/graph-export-manifest.json",
500
+ json.dumps({"export_id": "test-export"}),
501
+ )
502
+ _add_tar_text(
503
+ tf,
504
+ "graphify-out/graph.json",
505
+ json.dumps(
506
+ {
507
+ "graph": {"export_id": "test-export"},
508
+ "nodes": [
509
+ {
510
+ "id": "skill:example",
511
+ "source_keys": ["/Users/steves/ctx/entities/skills/example.md"],
512
+ }
513
+ ],
514
+ "edges": [],
515
+ }
516
+ ),
517
+ )
518
+
519
+ pack_full_wiki_tar.repack_full_wiki_tar(source, target)
520
+
521
+ with tarfile.open(target, "r:gz") as tf:
522
+ graph_payload = tf.extractfile("graphify-out/graph.json")
523
+ assert graph_payload is not None
524
+ graph_json = graph_payload.read().decode("utf-8")
525
+ assert "/Users/" not in graph_json
526
+ assert "<host-user-path>" in graph_json
527
+
528
+
529
+ def test_graph_validation_rejects_host_paths_in_graph_json() -> None:
530
+ payload = json.dumps(
531
+ {
532
+ "graph": {"export_id": "test-export"},
533
+ "nodes": [
534
+ {
535
+ "id": "skill:example",
536
+ "source_keys": ["/Users/steves/ctx/entities/skills/example.md"],
537
+ }
538
+ ],
539
+ "edges": [],
540
+ }
541
+ ).encode("utf-8")
542
+
543
+ with pytest.raises(vga.GraphArtifactError, match="graph.json contains host path"):
544
+ vga._scan_graph_json(BytesIO(payload))
545
+
546
+
547
+ def test_full_archive_contract_requires_wiki_pack_and_rejects_expanded_markdown(
548
+ tmp_path: Path,
549
+ ) -> None:
550
+ with pytest.raises(vga.GraphArtifactError, match="missing wiki-packs"):
551
+ vga._validate_wiki_pack_payload(set(), tmp_path, expected_export_id="test-export")
552
+
553
+ with pytest.raises(vga.GraphArtifactError, match="expanded markdown member"):
554
+ vga._validate_archive_markdown_payload(
555
+ "entities/skills/example.md",
556
+ b"# Example\n",
557
+ context="archive",
558
+ )
559
+
560
+
561
+ def test_artifact_promotion_uses_target_validator_for_json_without_payload_validator(
562
+ tmp_path: Path,
563
+ ) -> None:
564
+ wiki = tmp_path / "wiki"
565
+ target = wiki / "graphify-out" / "graph.json"
566
+ staged = target.with_name("graph.json.staged")
567
+ target.parent.mkdir(parents=True)
568
+ target.write_text('{"nodes":[],"edges":[],"graph":{}}\n', encoding="utf-8")
569
+ staged.write_text("not-json\n", encoding="utf-8")
570
+
571
+ with pytest.raises(ValueError, match="invalid JSON artifact"):
572
+ wiki_queue_worker._handle_artifact_promotion(
573
+ wiki,
574
+ {
575
+ "staged_path": "graphify-out/graph.json.staged",
576
+ "target_path": "graphify-out/graph.json",
577
+ "validator": "none",
578
+ },
579
+ )
580
+ assert target.read_text(encoding="utf-8") == '{"nodes":[],"edges":[],"graph":{}}\n'
581
+ assert staged.exists()
582
+
583
+
584
+ def test_artifact_promotion_uses_target_validator_for_tar_without_payload_validator(
585
+ monkeypatch: Any,
586
+ tmp_path: Path,
587
+ ) -> None:
588
+ repo = tmp_path / "repo"
589
+ target = repo / "graph" / "wiki-graph-runtime.tar.gz"
590
+ staged = target.with_name("wiki-graph-runtime.tar.gz.staged")
591
+ target.parent.mkdir(parents=True)
592
+ target.write_bytes(b"old-tar")
593
+ staged.write_bytes(b"not-a-tar")
594
+ monkeypatch.setattr(wiki_queue_worker, "_source_root", lambda: repo.resolve())
595
+
596
+ with pytest.raises(ValueError, match="invalid tar.gz artifact"):
597
+ wiki_queue_worker._handle_artifact_promotion(
598
+ tmp_path / "wiki",
599
+ {
600
+ "staged_path": str(staged),
601
+ "target_path": str(target),
602
+ },
603
+ )
604
+ assert target.read_bytes() == b"old-tar"
605
+ assert staged.exists()
606
+
607
+
608
+ def test_artifact_promotion_rejects_incomplete_runtime_tar_without_payload_validator(
609
+ monkeypatch: Any,
610
+ tmp_path: Path,
611
+ ) -> None:
612
+ repo = tmp_path / "repo"
613
+ target = repo / "graph" / "wiki-graph-runtime.tar.gz"
614
+ staged = target.with_name("wiki-graph-runtime.tar.gz.staged")
615
+ target.parent.mkdir(parents=True)
616
+ target.write_bytes(b"old-tar")
617
+ payload = b'{"graph":{"export_id":"export-test"},"nodes":[],"edges":[]}'
618
+ info = tarfile.TarInfo("graphify-out/graph.json")
619
+ info.size = len(payload)
620
+ with tarfile.open(staged, "w:gz") as tf:
621
+ tf.addfile(info, BytesIO(payload))
622
+ monkeypatch.setattr(wiki_queue_worker, "_source_root", lambda: repo.resolve())
623
+
624
+ with pytest.raises(ValueError, match="invalid runtime graph artifact"):
625
+ wiki_queue_worker._handle_artifact_promotion(
626
+ tmp_path / "wiki",
627
+ {
628
+ "staged_path": str(staged),
629
+ "target_path": str(target),
630
+ },
631
+ )
632
+ assert target.read_bytes() == b"old-tar"
633
+ assert staged.exists()
634
+
635
+
636
+ def test_entity_search_fallback_returns_wiki_relative_path(tmp_path: Path) -> None:
637
+ wiki = tmp_path / "wiki"
638
+ entity_path = wiki / "entities" / "skills" / "python-patterns.md"
639
+ entity_path.parent.mkdir(parents=True)
640
+ entity_path.write_text("# Python Patterns\n", encoding="utf-8")
641
+ deps = dashboard_entities.EntityCrudDeps(
642
+ is_safe_slug=lambda _value: True,
643
+ normalize_entity_type=lambda value: "skill" if value in (None, "skill") else None,
644
+ wiki_entity_detail=lambda _slug, _etype: None,
645
+ wiki_entity_target_path=lambda slug, _etype: wiki / f"{slug}.md",
646
+ wiki_entity_path=lambda _slug, _etype: entity_path,
647
+ iter_wiki_entity_paths=lambda _etype: [("python-patterns", "skill", entity_path)],
648
+ wiki_relative_path=lambda path: path.relative_to(wiki).as_posix(),
649
+ read_manifest=lambda: {"load": []},
650
+ perform_unload=lambda _slug, _etype: (True, "unloaded"),
651
+ queue_entity_refresh=lambda *_args: None,
652
+ file_lock=lambda _path: nullcontext(),
653
+ write_entity_text=lambda _path, _content: None,
654
+ parse_frontmatter=lambda text: ({}, text),
655
+ frontmatter_tags=lambda _value: [],
656
+ frontmatter_text=lambda value: str(value or ""),
657
+ display_slug=lambda value: value,
658
+ display_label=lambda value: str(value),
659
+ entity_wiki_href=lambda slug, _etype: f"/wiki/{slug}?type=skill",
660
+ scan_skill_content=lambda _slug, _content: (True, "ok"),
661
+ )
662
+
663
+ results = dashboard_entities.search_wiki_entities("patterns", "skill", deps=deps)
664
+
665
+ assert results[0]["path"] == "entities/skills/python-patterns.md"
666
+ assert str(tmp_path) not in results[0]["path"]
667
+
668
+
669
+ def test_lfs_pointer_probe_does_not_full_read_hydrated_artifact(
670
+ monkeypatch: Any,
671
+ tmp_path: Path,
672
+ ) -> None:
673
+ artifact = tmp_path / "graph" / "wiki-graph.tar.gz"
674
+ artifact.parent.mkdir()
675
+ artifact.write_bytes(b"hydrated graph payload")
676
+
677
+ def fail_read_bytes(_path: Path) -> bytes:
678
+ raise AssertionError("read_bytes should not be used for prefix probing")
679
+
680
+ monkeypatch.setattr(Path, "read_bytes", fail_read_bytes)
681
+
682
+ assert ci_preflight._read_lfs_pointer(artifact) is None
src/tests/test_secret_scan.py CHANGED
@@ -47,6 +47,13 @@ def test_find_inline_secret_arg_allows_env_references() -> None:
47
  assert find_inline_secret_arg(["GITHUB_TOKEN=${GITHUB_TOKEN}"]) is None
48
 
49
 
 
 
 
 
 
 
 
50
  def test_redact_secret_text_masks_assignment_and_token_shapes() -> None:
51
  text = (
52
  "OPENAI_API_KEY=sk-abcdefghijklmnopqrstuvwxyz123456 "
 
47
  assert find_inline_secret_arg(["GITHUB_TOKEN=${GITHUB_TOKEN}"]) is None
48
 
49
 
50
+ def test_find_inline_secret_arg_allows_secret_indirection_flags() -> None:
51
+ assert find_inline_secret_arg(["--token-file", "/run/secrets/github"]) is None
52
+ assert find_inline_secret_arg(["--credential-env", "GITHUB_TOKEN"]) is None
53
+ assert find_inline_secret_arg(["--api-key-path=/run/secrets/openai"]) is None
54
+ assert find_inline_secret_arg(["--client-secret-var=CLIENT_SECRET"]) is None
55
+
56
+
57
  def test_redact_secret_text_masks_assignment_and_token_shapes() -> None:
58
  text = (
59
  "OPENAI_API_KEY=sk-abcdefghijklmnopqrstuvwxyz123456 "
src/tests/test_validate_graph_artifacts.py CHANGED
@@ -13,6 +13,7 @@ import pytest
13
  import yaml # type: ignore[import-untyped]
14
  import networkx as nx
15
 
 
16
  from ctx.core.graph.graph_packs import build_pack_manifest, write_base_pack, write_pack_manifest
17
  from ctx.core.wiki.wiki_packs import write_wiki_base_pack
18
  from scripts.ci_preflight import GRAPH_VALIDATE_ARGS
@@ -27,6 +28,7 @@ from validate_graph_artifacts import (
27
  _safe_tar_name,
28
  _scan_graph_json,
29
  validate_graph_artifacts,
 
30
  )
31
 
32
  _PREVIEW_HTML_FILES = (
@@ -287,17 +289,18 @@ def _write_runtime_archive(
287
  def _write_archive(
288
  graph_dir: Path,
289
  *,
290
- include_converted: bool = True,
291
  converted_skill_text: str = "# Example\n",
292
  include_graph: bool = True,
293
  graph_artifact: str = "graph.json",
294
  graph_pack_dir: Path | None = None,
295
- include_expanded_entity_pages: bool = True,
296
  include_wiki_pack: bool = True,
297
  wiki_pack_dir: Path | None = None,
298
  include_original: bool = False,
299
  include_lock: bool = False,
300
  include_queue: bool = False,
 
301
  include_delta: bool = True,
302
  include_report: bool = True,
303
  include_manifest: bool = True,
@@ -333,6 +336,8 @@ def _write_archive(
333
  wiki_pack_dir = _write_test_wiki_pack(graph_dir, export_id=manifest_export_id)
334
  with tarfile.open(graph_dir / "wiki-graph.tar.gz", "w:gz") as tf:
335
  _add_text(tf, "./index.md", "# Wiki\n")
 
 
336
  if include_wiki_pack and wiki_pack_dir is not None:
337
  for path in sorted(wiki_pack_dir.rglob("*")):
338
  if path.is_file():
@@ -985,6 +990,39 @@ def test_validate_graph_artifacts_rejects_artifact_export_id_mismatch(
985
  validate_graph_artifacts(tmp_path, expected_harnesses={"langgraph"})
986
 
987
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
988
  def test_validate_graph_artifacts_rejects_missing_converted_catalog_path(
989
  tmp_path: Path,
990
  ) -> None:
@@ -993,7 +1031,18 @@ def test_validate_graph_artifacts_rejects_missing_converted_catalog_path(
993
  converted_path="converted/skills-sh-example-skill/SKILL.md",
994
  )
995
  (tmp_path / "communities.json").write_text("{}", encoding="utf-8")
996
- _write_archive(tmp_path, include_converted=False, include_wiki_pack=False)
 
 
 
 
 
 
 
 
 
 
 
997
 
998
  with pytest.raises(GraphArtifactError, match="missing converted Skills.sh body"):
999
  validate_graph_artifacts(tmp_path)
@@ -1007,12 +1056,21 @@ def test_validate_graph_artifacts_rejects_missing_skill_bundle_reference(
1007
  converted_path="converted/skills-sh-example-skill/SKILL.md",
1008
  )
1009
  (tmp_path / "communities.json").write_text("{}", encoding="utf-8")
1010
- _write_archive(
1011
- tmp_path,
1012
- converted_skill_text=(
1013
- "# Example\n\nUse `resources/implementation-playbook.md` for the implementation flow.\n"
1014
- ),
 
 
 
 
 
 
 
 
1015
  )
 
1016
 
1017
  with pytest.raises(GraphArtifactError, match="missing bundled skill file"):
1018
  validate_graph_artifacts(tmp_path, expected_harnesses={"langgraph"})
@@ -1094,6 +1152,35 @@ def test_validate_graph_artifacts_rejects_corrupt_graph_pack(tmp_path: Path) ->
1094
  validate_graph_artifacts(tmp_path, expected_harnesses={"langgraph"})
1095
 
1096
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1097
  def test_validate_graph_artifacts_rejects_original_backup_members(tmp_path: Path) -> None:
1098
  _write_catalog(
1099
  tmp_path,
@@ -1118,6 +1205,50 @@ def test_validate_graph_artifacts_rejects_lock_members(tmp_path: Path) -> None:
1118
  validate_graph_artifacts(tmp_path)
1119
 
1120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1121
  def test_validate_graph_artifacts_rejects_transient_queue_state(tmp_path: Path) -> None:
1122
  _write_catalog(
1123
  tmp_path,
@@ -1536,11 +1667,13 @@ def test_validator_default_floors_match_preflight_contract() -> None:
1536
  assert values["--min-semantic-edges"] == str(DEFAULT_MIN_SEMANTIC_EDGES)
1537
 
1538
 
1539
- def test_graph_only_workflow_waits_for_release_asset_upload() -> None:
1540
  workflow = yaml.safe_load(Path(".github/workflows/test.yml").read_text(encoding="utf-8"))
1541
  steps = workflow["jobs"]["graph-check"]["steps"]
1542
  resolve_step = next(
1543
- step for step in steps if step.get("name") == "Resolve graph artifacts from release assets"
 
 
1544
  )
1545
  script = resolve_step["run"]
1546
 
@@ -1548,3 +1681,6 @@ def test_graph_only_workflow_waits_for_release_asset_upload() -> None:
1548
  assert "while True:" in script
1549
  assert "Waiting for matching release asset" in script
1550
  assert "time.sleep(release_asset_poll_seconds)" in script
 
 
 
 
13
  import yaml # type: ignore[import-untyped]
14
  import networkx as nx
15
 
16
+ import validate_graph_artifacts as graph_validator
17
  from ctx.core.graph.graph_packs import build_pack_manifest, write_base_pack, write_pack_manifest
18
  from ctx.core.wiki.wiki_packs import write_wiki_base_pack
19
  from scripts.ci_preflight import GRAPH_VALIDATE_ARGS
 
28
  _safe_tar_name,
29
  _scan_graph_json,
30
  validate_graph_artifacts,
31
+ validate_runtime_graph_archive,
32
  )
33
 
34
  _PREVIEW_HTML_FILES = (
 
289
  def _write_archive(
290
  graph_dir: Path,
291
  *,
292
+ include_converted: bool = False,
293
  converted_skill_text: str = "# Example\n",
294
  include_graph: bool = True,
295
  graph_artifact: str = "graph.json",
296
  graph_pack_dir: Path | None = None,
297
+ include_expanded_entity_pages: bool = False,
298
  include_wiki_pack: bool = True,
299
  wiki_pack_dir: Path | None = None,
300
  include_original: bool = False,
301
  include_lock: bool = False,
302
  include_queue: bool = False,
303
+ top_level_log: str | None = None,
304
  include_delta: bool = True,
305
  include_report: bool = True,
306
  include_manifest: bool = True,
 
336
  wiki_pack_dir = _write_test_wiki_pack(graph_dir, export_id=manifest_export_id)
337
  with tarfile.open(graph_dir / "wiki-graph.tar.gz", "w:gz") as tf:
338
  _add_text(tf, "./index.md", "# Wiki\n")
339
+ if top_level_log is not None:
340
+ _add_text(tf, "./log.md", top_level_log)
341
  if include_wiki_pack and wiki_pack_dir is not None:
342
  for path in sorted(wiki_pack_dir.rglob("*")):
343
  if path.is_file():
 
990
  validate_graph_artifacts(tmp_path, expected_harnesses={"langgraph"})
991
 
992
 
993
+ def test_validate_graph_artifacts_rejects_runtime_graph_json_host_path(
994
+ tmp_path: Path,
995
+ ) -> None:
996
+ _write_catalog(
997
+ tmp_path,
998
+ converted_path="converted/skills-sh-example-skill/SKILL.md",
999
+ )
1000
+ _write_archive(tmp_path)
1001
+ graph = {
1002
+ "graph": {"export_id": "export-test"},
1003
+ "nodes": [
1004
+ {
1005
+ "id": "skill:skills-sh-example-skill",
1006
+ "type": "skill",
1007
+ "source_catalog": "skills.sh",
1008
+ "metadata": {"source_path": "/Users/alice/private-notes.md"},
1009
+ },
1010
+ {"id": "harness:langgraph", "type": "harness"},
1011
+ ],
1012
+ "edges": [
1013
+ {
1014
+ "source": "skill:skills-sh-example-skill",
1015
+ "target": "harness:langgraph",
1016
+ "semantic_sim": 0.91,
1017
+ },
1018
+ ],
1019
+ }
1020
+ _write_runtime_archive(tmp_path, graph=graph)
1021
+
1022
+ with pytest.raises(GraphArtifactError, match="host path"):
1023
+ validate_graph_artifacts(tmp_path, expected_harnesses={"langgraph"})
1024
+
1025
+
1026
  def test_validate_graph_artifacts_rejects_missing_converted_catalog_path(
1027
  tmp_path: Path,
1028
  ) -> None:
 
1031
  converted_path="converted/skills-sh-example-skill/SKILL.md",
1032
  )
1033
  (tmp_path / "communities.json").write_text("{}", encoding="utf-8")
1034
+ pack_root = tmp_path / "wiki-pack-missing-converted"
1035
+ write_wiki_base_pack(
1036
+ pack_dir=pack_root / "base-export-test",
1037
+ pack_id="base-export-test",
1038
+ base_export_id="export-test",
1039
+ pages={
1040
+ "index.md": "# Wiki\n",
1041
+ "entities/skills/skills-sh-example-skill.md": "# Example\n",
1042
+ "entities/harnesses/langgraph.md": "# LangGraph\n",
1043
+ },
1044
+ )
1045
+ _write_archive(tmp_path, wiki_pack_dir=pack_root)
1046
 
1047
  with pytest.raises(GraphArtifactError, match="missing converted Skills.sh body"):
1048
  validate_graph_artifacts(tmp_path)
 
1056
  converted_path="converted/skills-sh-example-skill/SKILL.md",
1057
  )
1058
  (tmp_path / "communities.json").write_text("{}", encoding="utf-8")
1059
+ pack_root = tmp_path / "wiki-pack-missing-bundle"
1060
+ write_wiki_base_pack(
1061
+ pack_dir=pack_root / "base-export-test",
1062
+ pack_id="base-export-test",
1063
+ base_export_id="export-test",
1064
+ pages={
1065
+ "index.md": "# Wiki\n",
1066
+ "entities/skills/skills-sh-example-skill.md": "# Example\n",
1067
+ "entities/harnesses/langgraph.md": "# LangGraph\n",
1068
+ "converted/skills-sh-example-skill/SKILL.md": (
1069
+ "# Example\n\nUse `resources/implementation-playbook.md` for the implementation flow.\n"
1070
+ ),
1071
+ },
1072
  )
1073
+ _write_archive(tmp_path, wiki_pack_dir=pack_root)
1074
 
1075
  with pytest.raises(GraphArtifactError, match="missing bundled skill file"):
1076
  validate_graph_artifacts(tmp_path, expected_harnesses={"langgraph"})
 
1152
  validate_graph_artifacts(tmp_path, expected_harnesses={"langgraph"})
1153
 
1154
 
1155
+ def test_validate_runtime_graph_archive_rejects_host_path_graph_pack_node_id(
1156
+ tmp_path: Path,
1157
+ ) -> None:
1158
+ graph = nx.Graph()
1159
+ graph.add_node("/Users/steves/private", type="skill")
1160
+ pack_root = tmp_path / "graph-pack-source-export-test"
1161
+ write_base_pack(
1162
+ pack_dir=pack_root / "base-export-test",
1163
+ pack_id="base-export-test",
1164
+ base_export_id="export-test",
1165
+ config_hash="config-sha",
1166
+ model_id="bge-small-en-v1.5",
1167
+ graph=graph,
1168
+ )
1169
+ _write_runtime_archive(
1170
+ tmp_path,
1171
+ graph={},
1172
+ include_graph=False,
1173
+ graph_artifact="packs",
1174
+ graph_pack_dir=pack_root,
1175
+ )
1176
+
1177
+ with pytest.raises(GraphArtifactError, match="host path"):
1178
+ validate_runtime_graph_archive(
1179
+ tmp_path / "wiki-graph-runtime.tar.gz",
1180
+ expected_harnesses=set(),
1181
+ )
1182
+
1183
+
1184
  def test_validate_graph_artifacts_rejects_original_backup_members(tmp_path: Path) -> None:
1185
  _write_catalog(
1186
  tmp_path,
 
1205
  validate_graph_artifacts(tmp_path)
1206
 
1207
 
1208
+ @pytest.mark.parametrize(
1209
+ "host_path",
1210
+ [
1211
+ "/Users/steves/ctx/graph",
1212
+ "file:///Users/steves/ctx/graph",
1213
+ "file:///home/steves/ctx/graph",
1214
+ "C:\\Users\\steves\\ctx\\graph",
1215
+ ],
1216
+ )
1217
+ def test_validate_graph_artifacts_rejects_host_paths_in_tar_markdown(
1218
+ tmp_path: Path,
1219
+ host_path: str,
1220
+ ) -> None:
1221
+ _write_catalog(
1222
+ tmp_path,
1223
+ converted_path="converted/skills-sh-example-skill/SKILL.md",
1224
+ )
1225
+ _write_archive(tmp_path, top_level_log=f"export log: {host_path}\n")
1226
+
1227
+ with pytest.raises(
1228
+ GraphArtifactError,
1229
+ match=r"archive markdown contains host path: log\.md",
1230
+ ):
1231
+ validate_graph_artifacts(tmp_path, expected_harnesses={"langgraph"})
1232
+
1233
+
1234
+ def test_validate_graph_artifacts_rejects_oversized_tar_markdown(
1235
+ tmp_path: Path,
1236
+ monkeypatch: pytest.MonkeyPatch,
1237
+ ) -> None:
1238
+ _write_catalog(
1239
+ tmp_path,
1240
+ converted_path="converted/skills-sh-example-skill/SKILL.md",
1241
+ )
1242
+ monkeypatch.setattr(graph_validator, "_MAX_MARKDOWN_MEMBER_BYTES", 1024)
1243
+ _write_archive(tmp_path, include_converted=True, converted_skill_text="x" * 1025)
1244
+
1245
+ with pytest.raises(
1246
+ GraphArtifactError,
1247
+ match=r"archive markdown member too large: converted/skills-sh-example-skill/SKILL\.md",
1248
+ ):
1249
+ validate_graph_artifacts(tmp_path, expected_harnesses={"langgraph"})
1250
+
1251
+
1252
  def test_validate_graph_artifacts_rejects_transient_queue_state(tmp_path: Path) -> None:
1253
  _write_catalog(
1254
  tmp_path,
 
1667
  assert values["--min-semantic-edges"] == str(DEFAULT_MIN_SEMANTIC_EDGES)
1668
 
1669
 
1670
+ def test_graph_only_workflow_uses_release_cache_or_targeted_lfs() -> None:
1671
  workflow = yaml.safe_load(Path(".github/workflows/test.yml").read_text(encoding="utf-8"))
1672
  steps = workflow["jobs"]["graph-check"]["steps"]
1673
  resolve_step = next(
1674
+ step
1675
+ for step in steps
1676
+ if step.get("name") == "Resolve graph artifacts from release assets or targeted LFS"
1677
  )
1678
  script = resolve_step["run"]
1679
 
 
1681
  assert "while True:" in script
1682
  assert "Waiting for matching release asset" in script
1683
  assert "time.sleep(release_asset_poll_seconds)" in script
1684
+ assert "Pointer for {path_name} is not in release cache" in script
1685
+ assert '"git", "lfs", "pull", "--include", path_name' in script
1686
+ assert "verify_hydrated_file(graph_tar, expected_oid, expected_size)" in script
src/tests/test_wiki_queue_worker.py CHANGED
@@ -1256,6 +1256,137 @@ def test_process_next_maintenance_job_retries_handler_failure(
1256
  assert "tar refresh failed" in str(current.last_error)
1257
 
1258
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1259
  def test_tar_refresh_handler_uses_from_catalog_for_catalog_payload(
1260
  tmp_path: Path,
1261
  monkeypatch: Any,
 
1256
  assert "tar refresh failed" in str(current.last_error)
1257
 
1258
 
1259
+ def test_process_next_artifact_promotion_rejects_outside_target_before_move(
1260
+ tmp_path: Path,
1261
+ ) -> None:
1262
+ wiki = tmp_path / "wiki"
1263
+ staged = wiki / "graphify-out" / "graph.json.staged"
1264
+ staged.parent.mkdir(parents=True)
1265
+ staged.write_text('{"nodes":[],"edges":[],"graph":{}}\n', encoding="utf-8")
1266
+ outside = tmp_path / "outside.txt"
1267
+ outside.write_text("old\n", encoding="utf-8")
1268
+ queued = wiki_queue.enqueue_maintenance_job(
1269
+ wiki,
1270
+ kind=wiki_queue.ARTIFACT_PROMOTION_JOB,
1271
+ payload={
1272
+ "staged_path": str(staged),
1273
+ "target_path": str(outside),
1274
+ },
1275
+ source="test",
1276
+ now=10.0,
1277
+ )
1278
+
1279
+ result = wiki_queue_worker.process_next(wiki, worker_id="worker-a", now=20.0)
1280
+
1281
+ assert result is not None
1282
+ assert result.job_id == queued.id
1283
+ assert result.kind == wiki_queue.ARTIFACT_PROMOTION_JOB
1284
+ assert result.status == wiki_queue.STATUS_PENDING
1285
+ assert "target_path is not an allowed artifact target" in result.message
1286
+ assert outside.read_text(encoding="utf-8") == "old\n"
1287
+ assert staged.read_text(encoding="utf-8") == '{"nodes":[],"edges":[],"graph":{}}\n'
1288
+ assert not outside.with_name("outside.txt.promotion.json").exists()
1289
+
1290
+
1291
+ def test_process_next_artifact_promotion_allows_known_graph_target(
1292
+ tmp_path: Path,
1293
+ ) -> None:
1294
+ wiki = tmp_path / "wiki"
1295
+ target = wiki / "graphify-out" / "graph.json"
1296
+ staged = target.with_name("graph.json.staged")
1297
+ target.parent.mkdir(parents=True)
1298
+ target.write_text('{"nodes":["old"],"edges":[],"graph":{}}\n', encoding="utf-8")
1299
+ staged.write_text('{"nodes":[],"edges":[],"graph":{}}\n', encoding="utf-8")
1300
+ queued = wiki_queue.enqueue_maintenance_job(
1301
+ wiki,
1302
+ kind=wiki_queue.ARTIFACT_PROMOTION_JOB,
1303
+ payload={
1304
+ "staged_path": "graphify-out/graph.json.staged",
1305
+ "target_path": "graphify-out/graph.json",
1306
+ },
1307
+ source="test",
1308
+ now=10.0,
1309
+ )
1310
+
1311
+ result = wiki_queue_worker.process_next(wiki, worker_id="worker-a", now=20.0)
1312
+
1313
+ assert result is not None
1314
+ assert result.job_id == queued.id
1315
+ assert result.kind == wiki_queue.ARTIFACT_PROMOTION_JOB
1316
+ assert result.status == wiki_queue.STATUS_SUCCEEDED
1317
+ assert result.message == f"promoted artifact to {target.resolve()}"
1318
+ assert target.read_text(encoding="utf-8") == '{"nodes":[],"edges":[],"graph":{}}\n'
1319
+ assert not staged.exists()
1320
+ assert target.with_name("graph.json.promotion.json").exists()
1321
+
1322
+
1323
+ @pytest.mark.parametrize(
1324
+ ("name", "payload", "message"),
1325
+ (
1326
+ ("graph.json", {"nodes": [], "graph": {}}, "missing edges list"),
1327
+ (
1328
+ "graph-delta.json",
1329
+ {"version": 1, "full_rebuild": False, "export_id": "export-test"},
1330
+ "missing nodes list",
1331
+ ),
1332
+ ("communities.json", {"export_id": "export-test"}, "missing communities object"),
1333
+ (
1334
+ "graph-export-manifest.json",
1335
+ {
1336
+ "version": 1,
1337
+ "export_id": "export-test",
1338
+ "artifacts": {"graph": "graph.json"},
1339
+ "counts": {"nodes": 1, "edges": 0, "communities": 0},
1340
+ },
1341
+ "invalid artifacts map",
1342
+ ),
1343
+ ),
1344
+ )
1345
+ def test_artifact_promotion_uses_target_specific_graph_json_validators(
1346
+ tmp_path: Path,
1347
+ name: str,
1348
+ payload: dict[str, Any],
1349
+ message: str,
1350
+ ) -> None:
1351
+ target = tmp_path / "wiki" / "graphify-out" / name
1352
+ target.parent.mkdir(parents=True)
1353
+ staged = target.with_name(f"{target.name}.staged")
1354
+ staged.write_text(json.dumps(payload), encoding="utf-8")
1355
+ validator = wiki_queue_worker._artifact_validator_for_target(target)
1356
+
1357
+ assert validator is not None
1358
+ with pytest.raises(ValueError, match=message):
1359
+ validator(staged)
1360
+
1361
+
1362
+ def test_artifact_promotion_manifest_validator_accepts_graph_packs(
1363
+ tmp_path: Path,
1364
+ ) -> None:
1365
+ target = tmp_path / "wiki" / "graphify-out" / "graph-export-manifest.json"
1366
+ target.parent.mkdir(parents=True)
1367
+ staged = target.with_name(f"{target.name}.staged")
1368
+ staged.write_text(
1369
+ json.dumps(
1370
+ {
1371
+ "version": 1,
1372
+ "export_id": "export-test",
1373
+ "artifacts": {
1374
+ "graph": "packs",
1375
+ "delta": "graph-delta.json",
1376
+ "communities": "communities.json",
1377
+ "report": "graph-report.md",
1378
+ },
1379
+ "counts": {"nodes": 1, "edges": 0, "communities": 0},
1380
+ }
1381
+ ),
1382
+ encoding="utf-8",
1383
+ )
1384
+ validator = wiki_queue_worker._artifact_validator_for_target(target)
1385
+
1386
+ assert validator is not None
1387
+ validator(staged)
1388
+
1389
+
1390
  def test_tar_refresh_handler_uses_from_catalog_for_catalog_payload(
1391
  tmp_path: Path,
1392
  monkeypatch: Any,
src/tests/test_workflow_lfs_caps.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ import pytest
6
+
7
+ ROOT = Path(__file__).resolve().parents[2]
8
+
9
+
10
+ def _resolve_script(workflow_path: str) -> str:
11
+ workflow = (ROOT / workflow_path).read_text(encoding="utf-8")
12
+ start = workflow.index("def hydrate_from_lfs")
13
+ end = workflow.index(" PY", start)
14
+ return workflow[start:end]
15
+
16
+
17
+ @pytest.mark.parametrize(
18
+ "workflow_path",
19
+ [
20
+ ".github/workflows/huggingface-sync.yml",
21
+ ".github/workflows/publish.yml",
22
+ ".github/workflows/test.yml",
23
+ ],
24
+ )
25
+ def test_targeted_lfs_fallback_checks_pointer_size_before_pull(workflow_path: str) -> None:
26
+ workflow = (ROOT / workflow_path).read_text(encoding="utf-8")
27
+ script = _resolve_script(workflow_path)
28
+
29
+ assert '"graph/wiki-graph.tar.gz": 350_000_000' in workflow
30
+ assert '"graph/wiki-graph-runtime.tar.gz": 150_000_000' in workflow
31
+ size_check = script.index("if expected_size > max_size:")
32
+ lfs_pull = script.index('["git", "lfs", "pull", "--include", path_name, "--exclude", ""]')
33
+ missing_cap_check = script.index("no size cap configured")
34
+
35
+ assert "max_size = max_lfs_fallback_sizes.get(path_name)" in script
36
+ assert missing_cap_check < lfs_pull
37
+ assert "pointer size {expected_size} exceeds cap {max_size}" in script
38
+ assert size_check < lfs_pull
39
+
40
+
41
+ def test_huggingface_sync_catalog_lfs_fallback_has_explicit_cap() -> None:
42
+ workflow = (ROOT / ".github" / "workflows" / "huggingface-sync.yml").read_text(encoding="utf-8")
43
+
44
+ assert '"graph/skills-sh-catalog.json.gz": 15_000_000' in workflow
45
+ assert workflow.index('"graph/skills-sh-catalog.json.gz": 15_000_000') < workflow.index(
46
+ 'hydrate_from_release("graph/skills-sh-catalog.json.gz", 1_000_000)'
47
+ )
src/validate_graph_artifacts.py CHANGED
@@ -99,6 +99,21 @@ _EDGE_SCORE_FIELDS = (
99
  "token_sim",
100
  )
101
  _WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  _PREVIEW_HTML_FILES = (
103
  "sample-top60.html",
104
  "viz-ai-agents.html",
@@ -310,7 +325,7 @@ def _validate_wiki_pack_payload(
310
  expected_export_id: str,
311
  ) -> dict[str, str]:
312
  if not any(name.startswith(_WIKI_PACK_PREFIX) for name in names):
313
- return {}
314
  try:
315
  entries = discover_wiki_pack_manifests(packs_dir)
316
  pages = load_merged_wiki_pages(packs_dir)
@@ -374,6 +389,7 @@ def _scan_graph_pack_payload(
374
  export_id = graph.graph.get("export_id") or graph.graph.get("ctx_pack_base_export_id")
375
  if not isinstance(export_id, str) or not export_id.strip():
376
  export_id = None
 
377
  if not deep:
378
  return 0, 0, 0, 0, 0, export_id
379
  return _scan_graph_object(graph, export_id=export_id)
@@ -514,6 +530,87 @@ def _safe_tar_name(raw_name: str) -> str:
514
  return "/".join(parts)
515
 
516
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
517
  def _count_lines(payload: bytes) -> int:
518
  return len(payload.decode("utf-8", errors="replace").splitlines())
519
 
@@ -570,6 +667,11 @@ def _scan_graph_json(stream: IO[bytes]) -> tuple[int, int, int, int, int, str |
570
  while chunk := stream.read(1024 * 1024):
571
  old_tail = tail
572
  data = tail + chunk
 
 
 
 
 
573
  _validate_graph_edge_score_fields(data)
574
  _validate_graph_edge_weight_drift(data)
575
  if export_id is None:
@@ -590,9 +692,24 @@ def _scan_graph_json(stream: IO[bytes]) -> tuple[int, int, int, int, int, str |
590
  return nodes, edges, semantic_edges, skills_sh_nodes, harness_nodes, export_id
591
 
592
 
593
- def _scan_graph_export_id(stream: IO[bytes], *, max_bytes: int = 1024 * 1024) -> str | None:
594
- payload = stream.read(max_bytes)
595
- return _extract_graph_export_id(payload)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
596
 
597
 
598
  def _extract_graph_export_id(payload: bytes) -> str | None:
@@ -876,11 +993,20 @@ def validate_graph_artifacts(
876
  raise GraphArtifactError(
877
  f"archive contains transient queue state: {member.name}",
878
  )
 
 
 
 
 
 
 
 
879
  if member.isfile() and _is_converted_skill_page(name):
880
- f = tf.extractfile(member)
881
- if f is None:
882
- raise GraphArtifactError(f"{member.name} could not be read")
883
- payload = f.read()
 
884
  for ref in _iter_skill_bundle_refs(payload):
885
  skill_bundle_refs.append((name, ref, _skill_bundle_target_name(name, ref)))
886
  if deep and name.startswith("converted/skills-sh-"):
@@ -925,10 +1051,12 @@ def validate_graph_artifacts(
925
  raise GraphArtifactError(f"{name} did not contain a JSON object")
926
  manifest = data
927
  elif member.isfile() and name == "graphify-out/graph-report.md":
928
- f = tf.extractfile(member)
929
- if f is None:
930
- raise GraphArtifactError(f"{member.name} could not be read")
931
- _record_export_id(export_ids, name, _export_id_from_report(f.read()))
 
 
932
  elif member.isfile() and name == "graphify-out/dashboard-neighborhoods.sqlite3":
933
  tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".sqlite3")
934
  tmp.close()
@@ -940,10 +1068,12 @@ def validate_graph_artifacts(
940
  _copy_wiki_pack_tar_member(tf, member, name, wiki_packs_dir)
941
  elif member.isfile() and deep and name.startswith("converted/skills-sh-"):
942
  if name.endswith("/SKILL.md") or "/references/" in name:
943
- f = tf.extractfile(member)
944
- if f is None:
945
- raise GraphArtifactError(f"{member.name} could not be read")
946
- lines = _count_lines(f.read())
 
 
947
  limit = line_threshold if name.endswith("/SKILL.md") else max_stage_lines
948
  if lines > limit:
949
  raise GraphArtifactError(
@@ -1000,6 +1130,8 @@ def validate_graph_artifacts(
1000
  wiki_pack_tmp.cleanup()
1001
  for page_name, text in wiki_pack_pages.items():
1002
  payload = text.encode("utf-8")
 
 
1003
  if _is_converted_skill_page(page_name):
1004
  for ref in _iter_skill_bundle_refs(payload):
1005
  skill_bundle_refs.append(
@@ -1136,6 +1268,20 @@ def _validate_graph_packs(packs_dir: Path) -> None:
1136
  raise GraphArtifactError(f"graph pack validation failed: {exc}") from exc
1137
 
1138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1139
  def _validate_runtime_graph_archive(
1140
  tarball: Path,
1141
  *,
@@ -1168,6 +1314,14 @@ def _validate_runtime_graph_archive(
1168
  raise GraphArtifactError(
1169
  f"runtime archive contains transient queue state: {member.name}",
1170
  )
 
 
 
 
 
 
 
 
1171
  if member.isfile() and name == "graphify-out/graph.json":
1172
  f = tf.extractfile(member)
1173
  if f is None:
@@ -1185,10 +1339,12 @@ def _validate_runtime_graph_archive(
1185
  raise GraphArtifactError(f"{name} did not contain a JSON object")
1186
  manifest = data
1187
  elif member.isfile() and name == "graphify-out/graph-report.md":
1188
- f = tf.extractfile(member)
1189
- if f is None:
1190
- raise GraphArtifactError(f"{member.name} could not be read")
1191
- _record_export_id(export_ids, name, _export_id_from_report(f.read()))
 
 
1192
  elif member.isfile() and name == "graphify-out/dashboard-neighborhoods.sqlite3":
1193
  tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".sqlite3")
1194
  tmp.close()
@@ -1304,8 +1460,10 @@ def _read_tar_json(tf: tarfile.TarFile, member: tarfile.TarInfo, name: str) -> A
1304
  f = tf.extractfile(member)
1305
  if f is None:
1306
  raise GraphArtifactError(f"{member.name} could not be read")
 
 
1307
  try:
1308
- return json.loads(f.read().decode("utf-8"))
1309
  except json.JSONDecodeError as exc:
1310
  raise GraphArtifactError(f"{name} is not valid JSON: {exc}") from exc
1311
 
 
99
  "token_sim",
100
  )
101
  _WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:")
102
+ _HOST_USER_PATH_RE = re.compile(
103
+ rb"(?:^|(?<=[`\"'(<\[\s=,:]))"
104
+ rb"(?:(?i:file:///(?:[A-Z]:[\\/]+Users[\\/]|(?:Users|home)/))"
105
+ rb"|(?i:[A-Z]:[\\/]+Users[\\/])|/(?:Users|home)/)"
106
+ )
107
+ _LOCAL_GENERATED_MARKDOWN = frozenset(
108
+ {
109
+ "catalog.md",
110
+ "converted-index.md",
111
+ "log.md",
112
+ "versions-catalog.md",
113
+ }
114
+ )
115
+ _REQUIRED_EXPANDED_MARKDOWN = frozenset({"graphify-out/graph-report.md"})
116
+ _MAX_MARKDOWN_MEMBER_BYTES = 10 * 1024 * 1024
117
  _PREVIEW_HTML_FILES = (
118
  "sample-top60.html",
119
  "viz-ai-agents.html",
 
325
  expected_export_id: str,
326
  ) -> dict[str, str]:
327
  if not any(name.startswith(_WIKI_PACK_PREFIX) for name in names):
328
+ raise GraphArtifactError("wiki graph archive is missing wiki-packs/")
329
  try:
330
  entries = discover_wiki_pack_manifests(packs_dir)
331
  pages = load_merged_wiki_pages(packs_dir)
 
389
  export_id = graph.graph.get("export_id") or graph.graph.get("ctx_pack_base_export_id")
390
  if not isinstance(export_id, str) or not export_id.strip():
391
  export_id = None
392
+ _validate_graph_object_no_host_paths(graph, context=context)
393
  if not deep:
394
  return 0, 0, 0, 0, 0, export_id
395
  return _scan_graph_object(graph, export_id=export_id)
 
530
  return "/".join(parts)
531
 
532
 
533
+ def _read_tar_member_bytes(tf: tarfile.TarFile, member: tarfile.TarInfo) -> bytes:
534
+ f = tf.extractfile(member)
535
+ if f is None:
536
+ raise GraphArtifactError(f"{member.name} could not be read")
537
+ with f:
538
+ return f.read()
539
+
540
+
541
+ def _validate_archive_markdown_payload(name: str, payload: bytes, *, context: str) -> None:
542
+ if len(payload) > _MAX_MARKDOWN_MEMBER_BYTES:
543
+ raise GraphArtifactError(
544
+ f"{context} markdown member too large: {name} ({len(payload)} bytes)",
545
+ )
546
+ if _HOST_USER_PATH_RE.search(payload):
547
+ raise GraphArtifactError(f"{context} markdown contains host path: {name}")
548
+ if name in _LOCAL_GENERATED_MARKDOWN:
549
+ raise GraphArtifactError(f"{context} contains local generated markdown: {name}")
550
+ if context == "archive" and _is_expanded_full_archive_markdown(name):
551
+ raise GraphArtifactError(f"{context} contains expanded markdown member: {name}")
552
+
553
+
554
+ def _is_expanded_full_archive_markdown(name: str) -> bool:
555
+ return (
556
+ name.endswith(".md")
557
+ and name not in _REQUIRED_EXPANDED_MARKDOWN
558
+ and "/" in name
559
+ and not name.startswith("entities/harnesses/")
560
+ )
561
+
562
+
563
+ def _validate_no_host_user_path_bytes(name: str, payload: bytes, *, context: str) -> None:
564
+ if _HOST_USER_PATH_RE.search(payload):
565
+ raise GraphArtifactError(f"{context} contains host path: {name}")
566
+
567
+
568
+ def _validate_no_host_user_path_value(value: Any, *, context: str) -> None:
569
+ if isinstance(value, str):
570
+ if _HOST_USER_PATH_RE.search(value.encode("utf-8", errors="replace")):
571
+ raise GraphArtifactError(f"{context} contains host path")
572
+ elif isinstance(value, dict):
573
+ for child in value.values():
574
+ _validate_no_host_user_path_value(child, context=context)
575
+ elif isinstance(value, list):
576
+ for child in value:
577
+ _validate_no_host_user_path_value(child, context=context)
578
+
579
+
580
+ def _validate_graph_object_no_host_paths(graph: Any, *, context: str) -> None:
581
+ graph_meta = getattr(graph, "graph", None)
582
+ if isinstance(graph_meta, dict):
583
+ _validate_no_host_user_path_value(graph_meta, context=f"{context} graph metadata")
584
+ for node_id, attrs in graph.nodes(data=True):
585
+ _validate_no_host_user_path_value(node_id, context=f"{context} graph node id")
586
+ if isinstance(attrs, dict):
587
+ _validate_no_host_user_path_value(attrs, context=f"{context} graph node {node_id!r}")
588
+ for source, target, attrs in graph.edges(data=True):
589
+ _validate_no_host_user_path_value(source, context=f"{context} graph edge source")
590
+ _validate_no_host_user_path_value(target, context=f"{context} graph edge target")
591
+ if isinstance(attrs, dict):
592
+ _validate_no_host_user_path_value(
593
+ attrs,
594
+ context=f"{context} graph edge {source!r}->{target!r}",
595
+ )
596
+
597
+
598
+ def _read_archive_markdown_payload(
599
+ tf: tarfile.TarFile,
600
+ member: tarfile.TarInfo,
601
+ name: str,
602
+ *,
603
+ context: str,
604
+ ) -> bytes:
605
+ if member.size > _MAX_MARKDOWN_MEMBER_BYTES:
606
+ raise GraphArtifactError(
607
+ f"{context} markdown member too large: {name} ({member.size} bytes)",
608
+ )
609
+ payload = _read_tar_member_bytes(tf, member)
610
+ _validate_archive_markdown_payload(name, payload, context=context)
611
+ return payload
612
+
613
+
614
  def _count_lines(payload: bytes) -> int:
615
  return len(payload.decode("utf-8", errors="replace").splitlines())
616
 
 
667
  while chunk := stream.read(1024 * 1024):
668
  old_tail = tail
669
  data = tail + chunk
670
+ _validate_no_host_user_path_bytes(
671
+ "graphify-out/graph.json",
672
+ data,
673
+ context="graph.json",
674
+ )
675
  _validate_graph_edge_score_fields(data)
676
  _validate_graph_edge_weight_drift(data)
677
  if export_id is None:
 
692
  return nodes, edges, semantic_edges, skills_sh_nodes, harness_nodes, export_id
693
 
694
 
695
+ def _scan_graph_export_id(
696
+ stream: IO[bytes],
697
+ *,
698
+ max_bytes: int = 1024 * 1024,
699
+ name: str = "graphify-out/graph.json",
700
+ context: str = "graph.json",
701
+ ) -> str | None:
702
+ export_id: str | None = None
703
+ probe = b""
704
+ tail = b""
705
+ while chunk := stream.read(1024 * 1024):
706
+ data = tail + chunk
707
+ _validate_no_host_user_path_bytes(name, data, context=context)
708
+ if export_id is None and len(probe) < max_bytes:
709
+ probe += chunk[: max_bytes - len(probe)]
710
+ export_id = _extract_graph_export_id(probe)
711
+ tail = data[-65536:]
712
+ return export_id
713
 
714
 
715
  def _extract_graph_export_id(payload: bytes) -> str | None:
 
993
  raise GraphArtifactError(
994
  f"archive contains transient queue state: {member.name}",
995
  )
996
+ markdown_payload: bytes | None = None
997
+ if member.isfile() and name.endswith(".md"):
998
+ markdown_payload = _read_archive_markdown_payload(
999
+ tf,
1000
+ member,
1001
+ name,
1002
+ context="archive",
1003
+ )
1004
  if member.isfile() and _is_converted_skill_page(name):
1005
+ payload = (
1006
+ markdown_payload
1007
+ if markdown_payload is not None
1008
+ else _read_tar_member_bytes(tf, member)
1009
+ )
1010
  for ref in _iter_skill_bundle_refs(payload):
1011
  skill_bundle_refs.append((name, ref, _skill_bundle_target_name(name, ref)))
1012
  if deep and name.startswith("converted/skills-sh-"):
 
1051
  raise GraphArtifactError(f"{name} did not contain a JSON object")
1052
  manifest = data
1053
  elif member.isfile() and name == "graphify-out/graph-report.md":
1054
+ payload = (
1055
+ markdown_payload
1056
+ if markdown_payload is not None
1057
+ else _read_tar_member_bytes(tf, member)
1058
+ )
1059
+ _record_export_id(export_ids, name, _export_id_from_report(payload))
1060
  elif member.isfile() and name == "graphify-out/dashboard-neighborhoods.sqlite3":
1061
  tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".sqlite3")
1062
  tmp.close()
 
1068
  _copy_wiki_pack_tar_member(tf, member, name, wiki_packs_dir)
1069
  elif member.isfile() and deep and name.startswith("converted/skills-sh-"):
1070
  if name.endswith("/SKILL.md") or "/references/" in name:
1071
+ payload = (
1072
+ markdown_payload
1073
+ if markdown_payload is not None
1074
+ else _read_tar_member_bytes(tf, member)
1075
+ )
1076
+ lines = _count_lines(payload)
1077
  limit = line_threshold if name.endswith("/SKILL.md") else max_stage_lines
1078
  if lines > limit:
1079
  raise GraphArtifactError(
 
1130
  wiki_pack_tmp.cleanup()
1131
  for page_name, text in wiki_pack_pages.items():
1132
  payload = text.encode("utf-8")
1133
+ if page_name.endswith(".md"):
1134
+ _validate_archive_markdown_payload(page_name, payload, context="wiki pack")
1135
  if _is_converted_skill_page(page_name):
1136
  for ref in _iter_skill_bundle_refs(payload):
1137
  skill_bundle_refs.append(
 
1268
  raise GraphArtifactError(f"graph pack validation failed: {exc}") from exc
1269
 
1270
 
1271
+ def validate_runtime_graph_archive(
1272
+ tarball: Path,
1273
+ *,
1274
+ expected_harnesses: set[str] | None = None,
1275
+ expected_export_id: str | None = None,
1276
+ ) -> str:
1277
+ """Validate a runtime graph tarball and return its shared export ID."""
1278
+ return _validate_runtime_graph_archive(
1279
+ tarball,
1280
+ expected_harnesses=DEFAULT_HARNESSES if expected_harnesses is None else expected_harnesses,
1281
+ expected_export_id=expected_export_id,
1282
+ )
1283
+
1284
+
1285
  def _validate_runtime_graph_archive(
1286
  tarball: Path,
1287
  *,
 
1314
  raise GraphArtifactError(
1315
  f"runtime archive contains transient queue state: {member.name}",
1316
  )
1317
+ markdown_payload: bytes | None = None
1318
+ if member.isfile() and name.endswith(".md"):
1319
+ markdown_payload = _read_archive_markdown_payload(
1320
+ tf,
1321
+ member,
1322
+ name,
1323
+ context="runtime archive",
1324
+ )
1325
  if member.isfile() and name == "graphify-out/graph.json":
1326
  f = tf.extractfile(member)
1327
  if f is None:
 
1339
  raise GraphArtifactError(f"{name} did not contain a JSON object")
1340
  manifest = data
1341
  elif member.isfile() and name == "graphify-out/graph-report.md":
1342
+ payload = (
1343
+ markdown_payload
1344
+ if markdown_payload is not None
1345
+ else _read_tar_member_bytes(tf, member)
1346
+ )
1347
+ _record_export_id(export_ids, name, _export_id_from_report(payload))
1348
  elif member.isfile() and name == "graphify-out/dashboard-neighborhoods.sqlite3":
1349
  tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".sqlite3")
1350
  tmp.close()
 
1460
  f = tf.extractfile(member)
1461
  if f is None:
1462
  raise GraphArtifactError(f"{member.name} could not be read")
1463
+ payload = f.read()
1464
+ _validate_no_host_user_path_bytes(name, payload, context="archive JSON")
1465
  try:
1466
+ return json.loads(payload.decode("utf-8"))
1467
  except json.JSONDecodeError as exc:
1468
  raise GraphArtifactError(f"{name} is not valid JSON: {exc}") from exc
1469