Stevesolun commited on
Commit
ea9e3bc
·
verified ·
1 Parent(s): c970469

Sync ctx c73ce1f (part 5)

Browse files

GitHub commit: c73ce1f87c822871e4c164ca70b41134ed6f9c14

src/tests/test_source_registry.py CHANGED
@@ -1,7 +1,11 @@
1
  from __future__ import annotations
2
 
 
3
  import json
 
 
4
  from pathlib import Path
 
5
 
6
  import pytest
7
 
@@ -9,31 +13,81 @@ from ctx.core.source_registry import (
9
  BUILTIN_EXTERNAL_SOURCES,
10
  ExternalSourceRecord,
11
  LicenseGateError,
 
 
 
12
  load_source_registry,
 
 
13
  validate_import_plan,
 
14
  )
15
 
 
 
 
 
 
16
 
17
- def test_license_gate_allows_full_body_for_permissive_license() -> None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  record = ExternalSourceRecord(
19
  name="optillm",
20
  url="https://github.com/algorithmicsuperintelligence/optillm",
21
- revision="df018d6",
22
- license="Apache-2.0",
 
 
 
 
 
23
  source_kind="harness",
24
  import_mode="full",
25
  permission_status="license",
26
  )
27
 
28
- assert validate_import_plan(record) is record
29
 
30
 
31
  def test_license_gate_blocks_noncommercial_full_body_without_permission() -> None:
32
  record = ExternalSourceRecord(
33
  name="academic-research-skills",
34
  url="https://github.com/Imbad0202/academic-research-skills",
35
- revision="153203d",
36
  license="CC BY-NC 4.0",
 
37
  source_kind="skill-suite",
38
  import_mode="full",
39
  permission_status="license",
@@ -49,27 +103,41 @@ def test_license_gate_allows_metadata_only_for_restricted_license() -> None:
49
  url="https://github.com/Imbad0202/academic-research-skills",
50
  revision="153203d",
51
  license="CC BY-NC 4.0",
 
52
  source_kind="skill-suite",
53
  import_mode="metadata-only",
54
  permission_status="license",
55
  )
56
 
57
- assert validate_import_plan(record) is record
58
 
59
 
60
- def test_license_gate_allows_full_body_when_permission_is_recorded() -> None:
 
 
 
 
 
 
 
 
 
 
61
  record = ExternalSourceRecord(
62
  name="academic-research-skills",
63
  url="https://github.com/Imbad0202/academic-research-skills",
64
- revision="153203d",
65
- license="CC BY-NC 4.0",
66
  source_kind="skill-suite",
67
  import_mode="full",
68
  permission_status="explicit-permission",
69
- permission_reference="author email 2026-05-13",
 
 
 
70
  )
71
 
72
- assert validate_import_plan(record) is record
73
 
74
 
75
  def test_builtin_registry_records_requested_sources() -> None:
@@ -82,12 +150,633 @@ def test_builtin_registry_records_requested_sources() -> None:
82
  "lat-md",
83
  "optillm",
84
  "julius-caveman",
 
 
 
 
85
  } <= names
86
 
87
 
88
- def test_builtin_registry_records_full_git_revisions() -> None:
 
89
  for source in BUILTIN_EXTERNAL_SOURCES:
90
- assert len(source.revision) == 40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
 
93
  def test_load_source_registry_validates_json_records(tmp_path: Path) -> None:
@@ -97,12 +786,14 @@ def test_load_source_registry_validates_json_records(tmp_path: Path) -> None:
97
  [
98
  {
99
  "name": "lat-md",
100
- "url": "https://github.com/1st1/lat.md",
101
  "revision": "bf8d95c",
102
  "license": "MIT",
 
103
  "source_kind": "knowledge-protocol",
104
- "import_mode": "metadata-only",
105
- "permission_status": "license",
 
106
  }
107
  ],
108
  ),
@@ -112,3 +803,8 @@ def test_load_source_registry_validates_json_records(tmp_path: Path) -> None:
112
  records = load_source_registry(registry_path)
113
 
114
  assert [record.name for record in records] == ["lat-md"]
 
 
 
 
 
 
1
  from __future__ import annotations
2
 
3
+ import hashlib
4
  import json
5
+ import subprocess
6
+ from dataclasses import replace
7
  from pathlib import Path
8
+ from typing import Any
9
 
10
  import pytest
11
 
 
13
  BUILTIN_EXTERNAL_SOURCES,
14
  ExternalSourceRecord,
15
  LicenseGateError,
16
+ canonical_ingestion_manifest_sha256,
17
+ entity_provenance,
18
+ get_external_source,
19
  load_source_registry,
20
+ render_third_party_notice,
21
+ validate_ingestion_manifest,
22
  validate_import_plan,
23
+ validate_source_registry,
24
  )
25
 
26
+ REPO_ROOT = Path(__file__).resolve().parents[2]
27
+ MATT_REVISION = "e74f0061bb67222181640effa98c675bdb2fdaa7"
28
+ MATT_LICENSE_PATH = "imported-skills/mattpocock/LICENSE"
29
+ MATT_LICENSE_SHA256 = "0e7ac423bf2c6e223b7c5b156f8cf72da49d748e56a1641402c31f22ad07dbb5"
30
+ RETAIN_MIT = ("retain-copyright-notice", "retain-license-notice")
31
 
32
+
33
+ def _manifest_entry(
34
+ *,
35
+ slug: str = "example",
36
+ source_path: str = "skills/example.md",
37
+ sha256: str = "d" * 64,
38
+ ) -> dict[str, Any]:
39
+ return {
40
+ "name": "Example",
41
+ "author": "Fixture Author",
42
+ "tags": ["fixture"],
43
+ "slug": slug,
44
+ "source_path": source_path,
45
+ "sha256": sha256,
46
+ }
47
+
48
+
49
+ def _ingestion_manifest(
50
+ *,
51
+ revision: str = "b" * 40,
52
+ entries: list[dict[str, Any]] | None = None,
53
+ ) -> dict[str, Any]:
54
+ return {
55
+ "upstream": "https://example.test/source",
56
+ "upstream_revision": revision,
57
+ "fetched_on": "2026-07-11",
58
+ "license": "MIT",
59
+ "license_url": f"https://example.test/{revision}/LICENSE",
60
+ "license_evidence_sha256": MATT_LICENSE_SHA256,
61
+ "entries": entries if entries is not None else [_manifest_entry()],
62
+ }
63
+
64
+
65
+ def test_license_gate_allows_full_body_for_policy_allowlisted_license() -> None:
66
  record = ExternalSourceRecord(
67
  name="optillm",
68
  url="https://github.com/algorithmicsuperintelligence/optillm",
69
+ revision=MATT_REVISION,
70
+ license="MIT",
71
+ license_url=f"https://example.test/{MATT_REVISION}/LICENSE",
72
+ license_evidence_sha256=MATT_LICENSE_SHA256,
73
+ license_evidence_path=MATT_LICENSE_PATH,
74
+ redistribution_obligations=RETAIN_MIT,
75
+ notice_reference=f"https://example.test/{MATT_REVISION}/LICENSE",
76
  source_kind="harness",
77
  import_mode="full",
78
  permission_status="license",
79
  )
80
 
81
+ assert validate_import_plan(record) == record
82
 
83
 
84
  def test_license_gate_blocks_noncommercial_full_body_without_permission() -> None:
85
  record = ExternalSourceRecord(
86
  name="academic-research-skills",
87
  url="https://github.com/Imbad0202/academic-research-skills",
88
+ revision="a" * 40,
89
  license="CC BY-NC 4.0",
90
+ license_url="https://example.test/academic/LICENSE",
91
  source_kind="skill-suite",
92
  import_mode="full",
93
  permission_status="license",
 
103
  url="https://github.com/Imbad0202/academic-research-skills",
104
  revision="153203d",
105
  license="CC BY-NC 4.0",
106
+ license_url="https://example.test/academic/LICENSE",
107
  source_kind="skill-suite",
108
  import_mode="metadata-only",
109
  permission_status="license",
110
  )
111
 
112
+ assert validate_import_plan(record) == record
113
 
114
 
115
+ def test_license_gate_allows_full_body_when_permission_is_recorded(
116
+ tmp_path: Path,
117
+ monkeypatch: pytest.MonkeyPatch,
118
+ ) -> None:
119
+ permission_payload = b"Permission granted for redistribution of this fixture.\n"
120
+ permission_path = tmp_path / "imported-skills" / "fixture" / "permission.txt"
121
+ permission_path.parent.mkdir(parents=True)
122
+ permission_path.write_bytes(permission_payload)
123
+ permission_digest = hashlib.sha256(permission_payload).hexdigest()
124
+ permission_reference = "imported-skills/fixture/permission.txt"
125
+ monkeypatch.setattr("ctx.core.source_registry.REPO_ROOT", tmp_path)
126
  record = ExternalSourceRecord(
127
  name="academic-research-skills",
128
  url="https://github.com/Imbad0202/academic-research-skills",
129
+ revision="a" * 40,
130
+ license="unknown",
131
  source_kind="skill-suite",
132
  import_mode="full",
133
  permission_status="explicit-permission",
134
+ permission_reference=permission_reference,
135
+ permission_evidence_sha256=permission_digest,
136
+ redistribution_obligations=("preserve-attribution",),
137
+ notice_reference=permission_reference,
138
  )
139
 
140
+ assert validate_import_plan(record) == record
141
 
142
 
143
  def test_builtin_registry_records_requested_sources() -> None:
 
150
  "lat-md",
151
  "optillm",
152
  "julius-caveman",
153
+ "strix",
154
+ "no-mistakes",
155
+ "designdotmd",
156
+ "skills-sh",
157
  } <= names
158
 
159
 
160
+ def test_builtin_registry_records_are_valid_and_full_body_sources_are_pinned() -> None:
161
+ assert validate_source_registry(BUILTIN_EXTERNAL_SOURCES) == BUILTIN_EXTERNAL_SOURCES
162
  for source in BUILTIN_EXTERNAL_SOURCES:
163
+ if source.import_mode in {"full", "full-body"}:
164
+ assert len(source.revision) == 40
165
+ assert source.license_url
166
+ assert source.license_evidence_path
167
+ assert source.license_evidence_sha256
168
+ assert source.redistribution_obligations
169
+ assert source.notice_reference
170
+
171
+
172
+ def test_full_body_evidence_files_are_checked_in() -> None:
173
+ full_body_sources = [
174
+ source for source in BUILTIN_EXTERNAL_SOURCES if source.import_mode in {"full", "full-body"}
175
+ ]
176
+ evidence_paths = [
177
+ source.license_evidence_path
178
+ for source in full_body_sources
179
+ if source.license_evidence_path is not None
180
+ ]
181
+ assert len(evidence_paths) == len(full_body_sources)
182
+
183
+ subprocess.run(
184
+ ["git", "ls-files", "--error-unmatch", *evidence_paths],
185
+ cwd=REPO_ROOT,
186
+ check=True,
187
+ capture_output=True,
188
+ text=True,
189
+ )
190
+
191
+
192
+ def test_license_gate_blocks_unknown_full_body() -> None:
193
+ source = ExternalSourceRecord(
194
+ name="unknown-source",
195
+ url="https://example.test/source",
196
+ revision="a" * 40,
197
+ license="unknown",
198
+ source_kind="skill-suite",
199
+ import_mode="full-body",
200
+ permission_status="unknown",
201
+ )
202
+
203
+ with pytest.raises(LicenseGateError, match="unknown license"):
204
+ validate_import_plan(source)
205
+
206
+
207
+ def test_license_gate_requires_evidence_url_for_known_license() -> None:
208
+ source = ExternalSourceRecord(
209
+ name="missing-evidence",
210
+ url="https://example.test/source",
211
+ revision="a" * 40,
212
+ license="MIT",
213
+ source_kind="skill-suite",
214
+ import_mode="full-body",
215
+ permission_status="license",
216
+ )
217
+
218
+ with pytest.raises(ValueError, match="requires license_url"):
219
+ validate_import_plan(source)
220
+
221
+
222
+ def test_metadata_only_keeps_legacy_registry_compatibility_without_license_url() -> None:
223
+ source = ExternalSourceRecord(
224
+ name="legacy-metadata",
225
+ url="https://example.test/source",
226
+ revision="snapshot",
227
+ license="MIT",
228
+ source_kind="external-catalog",
229
+ import_mode="metadata-only",
230
+ permission_status="license",
231
+ )
232
+
233
+ assert validate_import_plan(source) == source
234
+
235
+
236
+ def test_validation_normalizes_urls_modes_status_and_optional_strings() -> None:
237
+ source = ExternalSourceRecord(
238
+ name="normalized",
239
+ url=" HTTPS://Example.TEST:443/source/ ",
240
+ revision=" snapshot ",
241
+ license=" MIT ",
242
+ license_url=" HTTPS://EXAMPLE.TEST/LICENSE/ ",
243
+ source_kind=" catalog ",
244
+ import_mode=" Metadata-Only ",
245
+ permission_status=" LICENSE ",
246
+ permission_reference=" ",
247
+ notes=" review upstream ",
248
+ )
249
+
250
+ validated = validate_import_plan(source)
251
+
252
+ assert validated.url == "https://example.test/source"
253
+ assert validated.license_url == "https://example.test/LICENSE"
254
+ assert validated.import_mode == "metadata-only"
255
+ assert validated.permission_status == "license"
256
+ assert validated.permission_reference is None
257
+ assert validated.notes == "review upstream"
258
+
259
+
260
+ def test_whitespace_permission_reference_fails_for_explicit_permission() -> None:
261
+ source = ExternalSourceRecord(
262
+ name="missing-permission-evidence",
263
+ url="https://example.test/source",
264
+ revision="snapshot",
265
+ license="unknown",
266
+ source_kind="catalog",
267
+ import_mode="metadata-only",
268
+ permission_status="explicit-permission",
269
+ permission_reference=" \t ",
270
+ )
271
+
272
+ with pytest.raises(ValueError, match="requires permission_reference"):
273
+ validate_import_plan(source)
274
+
275
+
276
+ @pytest.mark.parametrize(
277
+ ("license_name", "permission_status", "permission_reference", "message"),
278
+ [
279
+ ("unknown", "license", None, "unknown license cannot use"),
280
+ ("MIT", "unknown", None, "known license cannot use"),
281
+ ("MIT", "license", "author email", "canonical checked-in path"),
282
+ ],
283
+ )
284
+ def test_license_permission_matrix_rejects_contradictions(
285
+ license_name: str,
286
+ permission_status: str,
287
+ permission_reference: str | None,
288
+ message: str,
289
+ ) -> None:
290
+ source = ExternalSourceRecord(
291
+ name="contradictory",
292
+ url="https://example.test/source",
293
+ revision="snapshot",
294
+ license=license_name,
295
+ source_kind="catalog",
296
+ import_mode="metadata-only",
297
+ permission_status=permission_status,
298
+ permission_reference=permission_reference,
299
+ )
300
+
301
+ with pytest.raises(ValueError, match=message):
302
+ validate_import_plan(source)
303
+
304
+
305
+ @pytest.mark.parametrize(
306
+ "url",
307
+ [
308
+ "https://",
309
+ "https://user@example.test/source",
310
+ "https://example.test/source?download=1",
311
+ "https://example.test/source#license",
312
+ "https://example.test/source%0Ainjected",
313
+ ],
314
+ )
315
+ def test_source_url_validation_rejects_ambiguous_or_unsafe_https_urls(url: str) -> None:
316
+ source = ExternalSourceRecord(
317
+ name="unsafe-url",
318
+ url=url,
319
+ revision="snapshot",
320
+ license="MIT",
321
+ source_kind="catalog",
322
+ import_mode="metadata-only",
323
+ permission_status="license",
324
+ )
325
+
326
+ with pytest.raises(ValueError, match="URL"):
327
+ validate_import_plan(source)
328
+
329
+
330
+ def test_license_url_uses_the_same_strict_https_validation() -> None:
331
+ source = ExternalSourceRecord(
332
+ name="unsafe-license-url",
333
+ url="https://example.test/source",
334
+ revision="snapshot",
335
+ license="MIT",
336
+ license_url="https://user@example.test/LICENSE",
337
+ source_kind="catalog",
338
+ import_mode="metadata-only",
339
+ permission_status="license",
340
+ )
341
+
342
+ with pytest.raises(ValueError, match="credentials are not allowed"):
343
+ validate_import_plan(source)
344
+
345
+
346
+ def test_registry_rejects_duplicate_canonical_source_urls() -> None:
347
+ first = ExternalSourceRecord(
348
+ name="first",
349
+ url="https://example.test/catalog/~tool/",
350
+ revision="one",
351
+ license="MIT",
352
+ source_kind="catalog",
353
+ import_mode="metadata-only",
354
+ permission_status="license",
355
+ )
356
+ second = replace(
357
+ first,
358
+ name="second",
359
+ url="HTTPS://EXAMPLE.TEST:443/catalog/%7etool",
360
+ revision="two",
361
+ )
362
+
363
+ with pytest.raises(ValueError, match="duplicate canonical source URL"):
364
+ validate_source_registry((first, second))
365
+
366
+
367
+ def test_full_body_requires_immutable_license_evidence() -> None:
368
+ source = ExternalSourceRecord(
369
+ name="mutable-evidence",
370
+ url="https://example.test/source",
371
+ revision=MATT_REVISION,
372
+ license="MIT",
373
+ license_url=f"https://example.test/{MATT_REVISION}/LICENSE",
374
+ source_kind="skill-suite",
375
+ import_mode="full-body",
376
+ permission_status="license",
377
+ redistribution_obligations=RETAIN_MIT,
378
+ notice_reference=f"https://example.test/{MATT_REVISION}/LICENSE",
379
+ )
380
+
381
+ with pytest.raises(LicenseGateError, match="checked-in license evidence"):
382
+ validate_import_plan(source)
383
+
384
+ permitted = replace(
385
+ source,
386
+ license_evidence_sha256=MATT_LICENSE_SHA256.upper(),
387
+ license_evidence_path=MATT_LICENSE_PATH,
388
+ )
389
+ assert validate_import_plan(permitted).license_evidence_sha256 == MATT_LICENSE_SHA256
390
+
391
+
392
+ @pytest.mark.parametrize("license_name", ["CC-BY-4.0", "CC0-1.0", "MPL-2.0"])
393
+ def test_cc_and_mpl_are_not_unconditionally_allowed_for_full_body(
394
+ license_name: str,
395
+ ) -> None:
396
+ source = ExternalSourceRecord(
397
+ name="review-required",
398
+ url="https://example.test/source",
399
+ revision="a" * 40,
400
+ license=license_name,
401
+ license_url=f"https://example.test/{'a' * 40}/LICENSE",
402
+ source_kind="skill-suite",
403
+ import_mode="full-body",
404
+ permission_status="license",
405
+ redistribution_obligations=("Review source-specific obligations.",),
406
+ notice_reference="https://example.test/NOTICE",
407
+ )
408
+
409
+ with pytest.raises(LicenseGateError, match="unapproved license"):
410
+ validate_import_plan(source)
411
+
412
+
413
+ def test_manifest_binding_rejects_license_drift() -> None:
414
+ source = get_external_source("designdotmd")
415
+ manifest: dict[str, Any] = {
416
+ "upstream": source.url,
417
+ "fetched_on": source.revision,
418
+ "license": "MIT",
419
+ "license_url": "https://example.test/LICENSE",
420
+ }
421
+
422
+ with pytest.raises(ValueError, match="manifest license does not match"):
423
+ validate_ingestion_manifest(source, manifest, import_mode="full-body")
424
+
425
+
426
+ def test_manifest_binding_requires_registered_license_evidence_digest() -> None:
427
+ revision = "b" * 40
428
+ manifest = _ingestion_manifest(revision=revision)
429
+ source = ExternalSourceRecord(
430
+ name="future-source",
431
+ url="https://example.test/source",
432
+ revision=revision,
433
+ license="MIT",
434
+ license_url=f"https://example.test/{revision}/LICENSE",
435
+ license_evidence_sha256=MATT_LICENSE_SHA256,
436
+ license_evidence_path=MATT_LICENSE_PATH,
437
+ manifest_sha256=canonical_ingestion_manifest_sha256(manifest),
438
+ redistribution_obligations=RETAIN_MIT,
439
+ notice_reference=f"https://example.test/{revision}/LICENSE",
440
+ source_kind="skill-suite",
441
+ import_mode="metadata-only",
442
+ permission_status="license",
443
+ )
444
+
445
+ validated = validate_ingestion_manifest(source, manifest, import_mode=" FULL-BODY ")
446
+
447
+ assert validated.import_mode == "full-body"
448
+ assert validated.license_evidence_sha256 == MATT_LICENSE_SHA256
449
+
450
+ manifest["license_evidence_sha256"] = "e" * 64
451
+ with pytest.raises(ValueError, match="license evidence digest does not match"):
452
+ validate_ingestion_manifest(source, manifest, import_mode="full-body")
453
+
454
+
455
+ def test_full_manifest_binding_rejects_body_and_entry_digest_rewrite() -> None:
456
+ revision = "b" * 40
457
+ manifest = _ingestion_manifest(
458
+ revision=revision,
459
+ entries=[_manifest_entry(source_path="skill.md", sha256="1" * 64)],
460
+ )
461
+ source = ExternalSourceRecord(
462
+ name="bound-source",
463
+ url=manifest["upstream"],
464
+ revision=revision,
465
+ license="MIT",
466
+ license_url=manifest["license_url"],
467
+ license_evidence_sha256=MATT_LICENSE_SHA256,
468
+ license_evidence_path=MATT_LICENSE_PATH,
469
+ manifest_sha256=canonical_ingestion_manifest_sha256(manifest),
470
+ redistribution_obligations=RETAIN_MIT,
471
+ notice_reference=manifest["license_url"],
472
+ source_kind="skill-suite",
473
+ import_mode="metadata-only",
474
+ permission_status="license",
475
+ )
476
+
477
+ manifest["entries"][0]["sha256"] = "2" * 64
478
+
479
+ with pytest.raises(LicenseGateError, match="full-manifest binding mismatch"):
480
+ validate_ingestion_manifest(source, manifest, import_mode="full-body")
481
+
482
+
483
+ @pytest.mark.parametrize(
484
+ ("source_path", "message"),
485
+ [
486
+ (" skill.md", "canonical repository-relative POSIX path"),
487
+ ("skill.md ", "canonical repository-relative POSIX path"),
488
+ ("../skill.md", "canonical repository-relative POSIX path"),
489
+ ("/skill.md", "canonical repository-relative POSIX path"),
490
+ (r"skills\skill.md", "canonical repository-relative POSIX path"),
491
+ ("skills//skill.md", "canonical repository-relative POSIX path"),
492
+ (".", "canonical repository-relative POSIX path"),
493
+ ("skills/e\u0301.md", "NFC-normalized"),
494
+ ("skills/safe\u202eexe.md", "Unicode control, format"),
495
+ ("skills/zero\u200dwidth.md", "Unicode control, format"),
496
+ ("skills/\x00skill.md", "Unicode control, format"),
497
+ ("skills/file.md:payload", "NTFS alternate data streams"),
498
+ ("C:/skills/file.md", "NTFS alternate data streams"),
499
+ ("skills/CON", "Windows-reserved"),
500
+ ("skills/nul.txt", "Windows-reserved"),
501
+ ("skills/COM1.md", "Windows-reserved"),
502
+ ("skills/LPT\u00b2.log", "Windows-reserved"),
503
+ ("skills/file./body.md", "trailing dots"),
504
+ ("skills /body.md", "surrounding whitespace"),
505
+ ("skills/file?.md", "Windows-unsafe"),
506
+ ],
507
+ )
508
+ def test_full_manifest_binding_rejects_nonportable_source_paths(
509
+ source_path: str,
510
+ message: str,
511
+ ) -> None:
512
+ manifest = _ingestion_manifest(
513
+ entries=[_manifest_entry(source_path=source_path)],
514
+ )
515
+
516
+ with pytest.raises(ValueError, match=message):
517
+ canonical_ingestion_manifest_sha256(manifest)
518
+
519
+
520
+ @pytest.mark.parametrize(
521
+ "source_path",
522
+ [
523
+ "skills/design.md",
524
+ "skills/\u00e9clair.md",
525
+ "skills/\u8bbe\u8ba1.md",
526
+ ".well-known/design.md",
527
+ "skills/COM10.md",
528
+ "skills/auxiliary.md",
529
+ "skills/file name.md",
530
+ ],
531
+ )
532
+ def test_full_manifest_binding_accepts_safe_portable_source_paths(
533
+ source_path: str,
534
+ ) -> None:
535
+ manifest = _ingestion_manifest(
536
+ entries=[_manifest_entry(source_path=source_path)],
537
+ )
538
+
539
+ assert len(canonical_ingestion_manifest_sha256(manifest)) == 64
540
+
541
+
542
+ def test_full_manifest_binding_rejects_casefold_duplicate_source_paths() -> None:
543
+ manifest = _ingestion_manifest(
544
+ entries=[
545
+ _manifest_entry(slug="first", source_path="skill.md", sha256="1" * 64),
546
+ _manifest_entry(
547
+ slug="second",
548
+ source_path="SKILL.md",
549
+ sha256="2" * 64,
550
+ ),
551
+ ],
552
+ )
553
+
554
+ with pytest.raises(ValueError, match="duplicate source path"):
555
+ canonical_ingestion_manifest_sha256(manifest)
556
+
557
+
558
+ def test_full_manifest_binding_is_deterministic_across_object_key_order() -> None:
559
+ manifest = _ingestion_manifest()
560
+ reordered = dict(reversed(list(manifest.items())))
561
+ reordered["entries"] = [dict(reversed(list(entry.items()))) for entry in manifest["entries"]]
562
+
563
+ assert canonical_ingestion_manifest_sha256(reordered) == (
564
+ canonical_ingestion_manifest_sha256(manifest)
565
+ )
566
+
567
+
568
+ @pytest.mark.parametrize(
569
+ ("permission_reference", "permission_digest", "message"),
570
+ [
571
+ ("trust me", "1" * 64, "canonical checked-in path"),
572
+ (f"https://example.test/{'a' * 40}/permission.txt", "0" * 64, "all-zero"),
573
+ (
574
+ f"https://example.test/{'a' * 40}/{'1' * 64}/permission.txt",
575
+ "1" * 64,
576
+ "checked-in",
577
+ ),
578
+ ],
579
+ )
580
+ def test_explicit_permission_rejects_unverifiable_evidence(
581
+ permission_reference: str,
582
+ permission_digest: str,
583
+ message: str,
584
+ ) -> None:
585
+ source = ExternalSourceRecord(
586
+ name="unverified-permission",
587
+ url="https://example.test/source",
588
+ revision="a" * 40,
589
+ license="unknown",
590
+ source_kind="skill-suite",
591
+ import_mode="full-body",
592
+ permission_status="explicit-permission",
593
+ permission_reference=permission_reference,
594
+ permission_evidence_sha256=permission_digest,
595
+ redistribution_obligations=("preserve-attribution",),
596
+ notice_reference=(
597
+ permission_reference if permission_reference.startswith("https://") else None
598
+ ),
599
+ )
600
+
601
+ with pytest.raises((ValueError, LicenseGateError), match=message):
602
+ validate_import_plan(source)
603
+
604
+
605
+ def test_checked_in_license_evidence_must_match_digest_and_declared_license() -> None:
606
+ base = ExternalSourceRecord(
607
+ name="evidence-mismatch",
608
+ url="https://example.test/source",
609
+ revision=MATT_REVISION,
610
+ license="MIT",
611
+ license_url=f"https://example.test/{MATT_REVISION}/LICENSE",
612
+ license_evidence_sha256="f" * 64,
613
+ license_evidence_path=MATT_LICENSE_PATH,
614
+ redistribution_obligations=RETAIN_MIT,
615
+ notice_reference=f"https://example.test/{MATT_REVISION}/LICENSE",
616
+ source_kind="skill-suite",
617
+ import_mode="full-body",
618
+ permission_status="license",
619
+ )
620
+ with pytest.raises(LicenseGateError, match="evidence sha256 mismatch"):
621
+ validate_import_plan(base)
622
+
623
+ wrong_identity = replace(
624
+ base,
625
+ license="Apache-2.0",
626
+ license_evidence_sha256=MATT_LICENSE_SHA256,
627
+ redistribution_obligations=("retain-license-notice",),
628
+ )
629
+ with pytest.raises(LicenseGateError, match="does not identify declared license"):
630
+ validate_import_plan(wrong_identity)
631
+
632
+
633
+ def test_full_body_rejects_free_form_redistribution_obligations() -> None:
634
+ source = ExternalSourceRecord(
635
+ name="free-form-obligation",
636
+ url="https://example.test/source",
637
+ revision=MATT_REVISION,
638
+ license="MIT",
639
+ license_url=f"https://example.test/{MATT_REVISION}/LICENSE",
640
+ license_evidence_sha256=MATT_LICENSE_SHA256,
641
+ license_evidence_path=MATT_LICENSE_PATH,
642
+ redistribution_obligations=("anything",),
643
+ notice_reference=f"https://example.test/{MATT_REVISION}/LICENSE",
644
+ source_kind="skill-suite",
645
+ import_mode="full-body",
646
+ permission_status="license",
647
+ )
648
+
649
+ with pytest.raises(LicenseGateError, match="registered control identifiers"):
650
+ validate_import_plan(source)
651
+
652
+
653
+ @pytest.mark.parametrize(
654
+ "license_name",
655
+ ["Unlicense", "The Unlicense", "no-explicit-license"],
656
+ )
657
+ def test_license_normalization_preserves_unlicense_identities(license_name: str) -> None:
658
+ source = ExternalSourceRecord(
659
+ name="license-identity",
660
+ url="https://example.test/license-identity",
661
+ revision="snapshot",
662
+ license=license_name,
663
+ source_kind="catalog",
664
+ import_mode="metadata-only",
665
+ permission_status=("unknown" if license_name == "no-explicit-license" else "license"),
666
+ )
667
+
668
+ assert validate_import_plan(source).license == license_name
669
+
670
+
671
+ @pytest.mark.parametrize(
672
+ ("registered_license", "manifest_license", "permission_status"),
673
+ [
674
+ ("Apache-2.0", "Apache License 2.0", "license"),
675
+ ("Unlicense", "The Unlicense", "license"),
676
+ ("no-explicit-license", "No Explicit License", "unknown"),
677
+ ],
678
+ )
679
+ def test_manifest_license_aliases_share_a_canonical_identity(
680
+ registered_license: str,
681
+ manifest_license: str,
682
+ permission_status: str,
683
+ ) -> None:
684
+ source = ExternalSourceRecord(
685
+ name="license-alias",
686
+ url="https://example.test/license-alias",
687
+ revision="snapshot",
688
+ license=registered_license,
689
+ source_kind="catalog",
690
+ import_mode="metadata-only",
691
+ permission_status=permission_status,
692
+ )
693
+ manifest = {
694
+ "upstream": source.url,
695
+ "upstream_revision": source.revision,
696
+ "license": manifest_license,
697
+ }
698
+
699
+ assert (
700
+ validate_ingestion_manifest(source, manifest, import_mode="metadata-only").license
701
+ == registered_license
702
+ )
703
+
704
+
705
+ @pytest.mark.parametrize("name", ["Tool", "tool_name", "tool--name", "tool]"])
706
+ def test_source_names_must_be_canonical_lowercase_slugs(name: str) -> None:
707
+ source = ExternalSourceRecord(
708
+ name=name,
709
+ url="https://example.test/source",
710
+ revision="snapshot",
711
+ license="MIT",
712
+ source_kind="catalog",
713
+ import_mode="metadata-only",
714
+ permission_status="license",
715
+ )
716
+
717
+ with pytest.raises(ValueError, match="canonical lowercase slug"):
718
+ validate_import_plan(source)
719
+
720
+
721
+ def test_notice_escapes_markdown_labels_and_link_destinations() -> None:
722
+ source = ExternalSourceRecord(
723
+ name="safe-source",
724
+ url="https://example.test/catalog/(stable)",
725
+ revision="<snapshot>",
726
+ license="<script>alert(1)</script> MIT](https://attacker.invalid",
727
+ source_kind="catalog",
728
+ import_mode="metadata-only",
729
+ permission_status="license",
730
+ notes="<img src=x onerror=alert(1)> safe ](https://attacker.invalid) text & more",
731
+ )
732
+
733
+ notice = render_third_party_notice((source,))
734
+
735
+ assert "&lt;script&gt;alert(1)&lt;/script&gt; MIT\\](https://attacker.invalid" in notice
736
+ assert (
737
+ "&lt;img src=x onerror=alert(1)&gt; safe \\](https://attacker.invalid) text &amp; more"
738
+ ) in notice
739
+ assert "&lt;snapshot&gt;" in notice
740
+ assert "catalog/%28stable%29" in notice
741
+ assert "<script>" not in notice
742
+ assert "<img " not in notice
743
+ assert "| MIT](https://attacker.invalid" not in notice
744
+ assert "| safe ](https://attacker.invalid)" not in notice
745
+
746
+
747
+ def test_entity_provenance_is_complete_and_explicit() -> None:
748
+ source = get_external_source("mattpocock-skills")
749
+
750
+ assert entity_provenance(source) == {
751
+ "source": source.name,
752
+ "source_url": source.url,
753
+ "source_revision": source.revision,
754
+ "license": source.license,
755
+ "license_url": source.license_url,
756
+ "import_mode": source.import_mode,
757
+ "permission_status": source.permission_status,
758
+ "permission_reference": source.permission_reference,
759
+ "permission_evidence_sha256": source.permission_evidence_sha256,
760
+ "license_evidence_sha256": source.license_evidence_sha256,
761
+ "license_evidence_path": source.license_evidence_path,
762
+ "manifest_sha256": source.manifest_sha256,
763
+ "redistribution_obligations": list(source.redistribution_obligations),
764
+ "notice_reference": source.notice_reference,
765
+ }
766
+
767
+
768
+ def test_checked_in_notice_is_generated_from_registry() -> None:
769
+ notice = (REPO_ROOT / "NOTICE").read_text(encoding="utf-8")
770
+
771
+ assert notice == render_third_party_notice(BUILTIN_EXTERNAL_SOURCES)
772
+ assert "fail-closed engineering provenance inventory, not legal advice" in notice
773
+ assert "does not prove" in notice
774
+ assert "minimum engineering safeguards, not exhaustive legal" in notice
775
+ assert "Permission evidence" in notice
776
+ assert "Manifest SHA-256" in notice
777
+ assert "Redistribution controls" in notice
778
+ assert "| [designdotmd]" in notice
779
+ assert "Existing unresolved corpus remains blocked" in notice
780
 
781
 
782
  def test_load_source_registry_validates_json_records(tmp_path: Path) -> None:
 
786
  [
787
  {
788
  "name": "lat-md",
789
+ "url": "HTTPS://GITHUB.COM:443/1st1/lat.md/",
790
  "revision": "bf8d95c",
791
  "license": "MIT",
792
+ "license_url": "https://example.test/lat-md/LICENSE/",
793
  "source_kind": "knowledge-protocol",
794
+ "import_mode": " Metadata-Only ",
795
+ "permission_status": " License ",
796
+ "permission_reference": " ",
797
  }
798
  ],
799
  ),
 
803
  records = load_source_registry(registry_path)
804
 
805
  assert [record.name for record in records] == ["lat-md"]
806
+ assert records[0].url == "https://github.com/1st1/lat.md"
807
+ assert records[0].license_url == "https://example.test/lat-md/LICENSE"
808
+ assert records[0].import_mode == "metadata-only"
809
+ assert records[0].permission_status == "license"
810
+ assert records[0].permission_reference is None
src/tests/test_tag_backfill.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Behavior tests for the ctx-tag-backfill user story."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections import Counter
7
+ from pathlib import Path
8
+
9
+ from ctx.core.quality import tag_backfill
10
+
11
+
12
+ def _entity_text(
13
+ name: str,
14
+ *,
15
+ tags: str = "tags: []",
16
+ body: str = "Build a FastAPI service with reliable testing.",
17
+ attribution: str = "",
18
+ ) -> str:
19
+ return (
20
+ f"{attribution}"
21
+ "---\n"
22
+ f"name: {name}\n"
23
+ "description: A focused development helper.\n"
24
+ f"{tags}\n"
25
+ "---\n"
26
+ f"# {name}\n\n"
27
+ f"{body}\n"
28
+ )
29
+
30
+
31
+ def _write_skill(home: Path, slug: str, text: str) -> Path:
32
+ path = home / ".claude" / "skills" / slug / "SKILL.md"
33
+ path.parent.mkdir(parents=True, exist_ok=True)
34
+ path.write_text(text, encoding="utf-8")
35
+ return path
36
+
37
+
38
+ def _write_agent(home: Path, slug: str, text: str) -> Path:
39
+ path = home / ".claude" / "agents" / f"{slug}.md"
40
+ path.parent.mkdir(parents=True, exist_ok=True)
41
+ path.write_text(text, encoding="utf-8")
42
+ return path
43
+
44
+
45
+ def test_split_frontmatter_supports_import_attribution_header() -> None:
46
+ attribution = (
47
+ "<!-- strix-import: upstream=https://example.test rev=0123456789ab "
48
+ "license=Apache-2.0 category=coordination -->\n"
49
+ )
50
+ text = _entity_text(
51
+ "imported-skill",
52
+ attribution=attribution,
53
+ )
54
+
55
+ prefix, body, frontmatter = tag_backfill._split_frontmatter(text)
56
+
57
+ assert prefix == attribution
58
+ assert "name: imported-skill" in frontmatter
59
+ assert body.startswith("# imported-skill")
60
+
61
+
62
+ def test_split_frontmatter_leaves_malformed_sources_untouched() -> None:
63
+ for text in (
64
+ "# No frontmatter\n",
65
+ "---\nname: unclosed\n",
66
+ "# Body\n\n---\ntags: []\n---\nTrailing body\n",
67
+ "<!-- unknown-import: upstream=https://example.test -->\n---\nname: helper\n---\n",
68
+ "<!-- strix-import: upstream=https://example.test -->\n---\nname: helper\n---\n",
69
+ "----\nname: helper\n----\n",
70
+ ):
71
+ assert tag_backfill._split_frontmatter(text) == (text, "", "")
72
+
73
+
74
+ def test_apply_does_not_treat_body_thematic_breaks_as_frontmatter(tmp_path: Path) -> None:
75
+ source = tmp_path / "SKILL.md"
76
+ original = "# Helper\n\nIntro\n\n---\ntags: []\n---\nClosing text\n"
77
+ source.write_text(original, encoding="utf-8")
78
+ proposal = tag_backfill.TagProposal(
79
+ entity_type="skill",
80
+ slug="helper",
81
+ path=source,
82
+ current_tags=[],
83
+ proposed_add=["python"],
84
+ )
85
+
86
+ assert tag_backfill.apply_proposals([proposal]) == 0
87
+ assert source.read_text(encoding="utf-8") == original
88
+
89
+
90
+ def test_render_frontmatter_merges_tags_without_removing_curated_values() -> None:
91
+ frontmatter = "name: helper\ntags:\n - curated\ndescription: Keep this field"
92
+
93
+ rendered = tag_backfill._render_frontmatter_with_added_tags(
94
+ frontmatter,
95
+ ["python", "curated"],
96
+ )
97
+ tags, present = tag_backfill._parse_frontmatter_tags(rendered)
98
+
99
+ assert present is True
100
+ assert tags == ["curated", "python"]
101
+ assert "description: Keep this field" in rendered
102
+
103
+
104
+ def test_proposal_prioritizes_slug_tokens_then_known_body_keywords(tmp_path: Path) -> None:
105
+ source = tmp_path / "service-helper.md"
106
+ source.write_text(_entity_text("service-helper"), encoding="utf-8")
107
+
108
+ proposal = tag_backfill._propose(
109
+ source,
110
+ "skill",
111
+ "service-helper",
112
+ vocab=Counter({"python": 10, "fastapi": 8, "testing": 3}),
113
+ max_tags=4,
114
+ )
115
+
116
+ assert proposal.proposed_add[:2] == ["service", "helper"]
117
+ assert proposal.proposed_add[2:] == ["python", "fastapi"]
118
+ assert proposal.sources["body_keyword"]
119
+
120
+
121
+ def test_discovery_finds_empty_skills_and_agents_but_skips_curated(
122
+ tmp_path: Path,
123
+ monkeypatch,
124
+ ) -> None:
125
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: tmp_path))
126
+ empty_skill = _write_skill(tmp_path, "empty-skill", _entity_text("empty-skill"))
127
+ _write_skill(
128
+ tmp_path,
129
+ "curated-skill",
130
+ _entity_text("curated-skill", tags="tags: [curated]"),
131
+ )
132
+ empty_agent = _write_agent(tmp_path, "empty-agent", _entity_text("empty-agent"))
133
+
134
+ discovered = tag_backfill.discover_empty_tag_entities(tmp_path / "wiki")
135
+
136
+ assert discovered == [
137
+ ("skill", "empty-skill", empty_skill),
138
+ ("agent", "empty-agent", empty_agent),
139
+ ]
140
+
141
+
142
+ def test_run_and_apply_backfill_preserves_body_and_becomes_idempotent(
143
+ tmp_path: Path,
144
+ monkeypatch,
145
+ ) -> None:
146
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: tmp_path))
147
+ source = _write_skill(
148
+ tmp_path,
149
+ "python-fastapi",
150
+ _entity_text("python-fastapi", body="Build a FastAPI service."),
151
+ )
152
+
153
+ report = tag_backfill.run_backfill(wiki_dir=tmp_path / "wiki", max_tags_per_entity=3)
154
+ assert report.total_entities_scanned == 1
155
+ assert report.entities_with_empty_tags == 1
156
+ assert report.proposals[0].proposed_add[:2] == ["python", "fastapi"]
157
+
158
+ assert tag_backfill.apply_proposals(report.proposals) == 1
159
+ updated = source.read_text(encoding="utf-8")
160
+ assert "# python-fastapi\n\nBuild a FastAPI service." in updated
161
+ assert tag_backfill.discover_empty_tag_entities(tmp_path / "wiki") == []
162
+
163
+
164
+ def test_report_renderers_expose_proposals_without_losing_sources(tmp_path: Path) -> None:
165
+ proposal = tag_backfill.TagProposal(
166
+ entity_type="skill",
167
+ slug="python-helper",
168
+ path=tmp_path / "SKILL.md",
169
+ current_tags=[],
170
+ proposed_add=["python"],
171
+ sources={"slug_token": ["python"]},
172
+ )
173
+ report = tag_backfill.TagReport(1, 1, [proposal])
174
+
175
+ markdown = tag_backfill.render_markdown(report)
176
+ payload = json.loads(tag_backfill.render_json(report))
177
+
178
+ assert "skill: `python-helper`" in markdown
179
+ assert payload["proposals"][0]["sources"] == {"slug_token": ["python"]}
180
+
181
+
182
+ def test_main_report_only_writes_reports_without_mutating_entities(
183
+ tmp_path: Path,
184
+ monkeypatch,
185
+ capsys,
186
+ ) -> None:
187
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: tmp_path))
188
+ source = _write_skill(tmp_path, "python-helper", _entity_text("python-helper"))
189
+ before = source.read_text(encoding="utf-8")
190
+ markdown_report = tmp_path / "reports" / "tags.md"
191
+ json_report = tmp_path / "reports" / "tags.json"
192
+
193
+ result = tag_backfill.main(
194
+ [
195
+ "--report",
196
+ str(markdown_report),
197
+ "--report-json",
198
+ str(json_report),
199
+ ]
200
+ )
201
+
202
+ assert result == 0
203
+ assert "report-only" in capsys.readouterr().out
204
+ assert markdown_report.is_file()
205
+ assert json_report.is_file()
206
+ assert source.read_text(encoding="utf-8") == before
207
+
208
+
209
+ def test_main_wiki_option_uses_entity_cards_as_fallbacks(
210
+ tmp_path: Path,
211
+ monkeypatch,
212
+ ) -> None:
213
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: tmp_path))
214
+ wiki = tmp_path / "custom-wiki"
215
+ wiki_skills = wiki / "entities" / "skills"
216
+ wiki_skills.mkdir(parents=True)
217
+ wiki_only = wiki_skills / "wiki-only.md"
218
+ wiki_only.write_text(_entity_text("wiki-only"), encoding="utf-8")
219
+ wiki_shadow = wiki_skills / "installed-skill.md"
220
+ wiki_shadow.write_text(
221
+ _entity_text("installed-skill"),
222
+ encoding="utf-8",
223
+ )
224
+ installed = _write_skill(
225
+ tmp_path,
226
+ "installed-skill",
227
+ _entity_text("installed-skill", tags="tags: [curated]"),
228
+ )
229
+ json_report = tmp_path / "tags.json"
230
+
231
+ result = tag_backfill.main(
232
+ [
233
+ "--wiki",
234
+ str(wiki),
235
+ "--report",
236
+ str(tmp_path / "tags.md"),
237
+ "--report-json",
238
+ str(json_report),
239
+ "--apply",
240
+ ]
241
+ )
242
+
243
+ assert result == 0
244
+ payload = json.loads(json_report.read_text(encoding="utf-8"))
245
+ assert payload["total_entities_scanned"] == 2
246
+ assert [proposal["path"] for proposal in payload["proposals"]] == [str(wiki_only)]
247
+ assert " - wiki" in wiki_only.read_text(encoding="utf-8")
248
+ assert "tags: [curated]" in installed.read_text(encoding="utf-8")
249
+ assert "tags: []" in wiki_shadow.read_text(encoding="utf-8")
250
+
251
+
252
+ def test_main_apply_updates_empty_tags(tmp_path: Path, monkeypatch, capsys) -> None:
253
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: tmp_path))
254
+ source = _write_agent(tmp_path, "security-agent", _entity_text("security-agent"))
255
+
256
+ result = tag_backfill.main(
257
+ [
258
+ "--apply",
259
+ "--report",
260
+ str(tmp_path / "tags.md"),
261
+ "--report-json",
262
+ str(tmp_path / "tags.json"),
263
+ ]
264
+ )
265
+
266
+ assert result == 0
267
+ assert "APPLIED 1 files" in capsys.readouterr().out
268
+ assert " - security" in source.read_text(encoding="utf-8")
src/tests/test_threat_model_docs.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+ from pathlib import Path
5
+ from types import SimpleNamespace
6
+ import tomllib
7
+ from typing import Any, cast
8
+
9
+ import harness_install
10
+
11
+ from ctx.monitor.pages.loaded import render_loaded
12
+ from ctx.monitor.security import (
13
+ MAX_POST_BODY_BYTES,
14
+ READ_TOKEN_COOKIE,
15
+ host_allows_mutations,
16
+ origin_host_name,
17
+ origin_matches_http_host,
18
+ read_token_cookie,
19
+ request_host_name,
20
+ )
21
+ from ctx.monitor.server import MonitorHandlerDeps, build_monitor_handler
22
+
23
+
24
+ ROOT = Path(__file__).resolve().parents[2]
25
+
26
+
27
+ def _read(path: str) -> str:
28
+ return (ROOT / path).read_text(encoding="utf-8")
29
+
30
+
31
+ def test_threat_model_is_public_and_links_security_policy() -> None:
32
+ threat_model = _read("docs/threat-model.md")
33
+ mkdocs = _read("mkdocs.yml")
34
+ security = _read("SECURITY.md")
35
+
36
+ assert "- Threat model: threat-model.md" in mkdocs
37
+ assert "- Enterprise readiness: enterprise-readiness-review.md" in mkdocs
38
+ assert "[SECURITY.md policy]" in threat_model
39
+ assert "github.com/stevesolun/ctx/blob/main/SECURITY.md" in threat_model
40
+ assert "[threat model](docs/threat-model.md)" in security
41
+
42
+
43
+ def test_governance_docs_distinguish_ci_protection_from_independent_review() -> None:
44
+ enterprise = " ".join(_read("docs/enterprise-readiness-review.md").split())
45
+ security = " ".join(_read("SECURITY.md").split())
46
+ codeowners = " ".join(_read(".github/CODEOWNERS").split())
47
+
48
+ assert "GitHub `main` was unprotected" not in enterprise
49
+ assert "ruleset 15907020" in enterprise
50
+ assert "strictly requires the `CI required` status" in enterprise
51
+ assert "ruleset 15907020" in security
52
+ assert "does not require pull-request review or CODEOWNER approval" in security
53
+ assert "only one human" in security
54
+ assert "ruleset 15907020" in codeowners
55
+ assert "already protects main with strict required CI" in codeowners
56
+ assert "could deadlock merges" in codeowners
57
+
58
+
59
+ def test_monitor_docs_match_runtime_exposure_contract() -> None:
60
+ security = _read("SECURITY.md")
61
+ dashboard = _read("docs/dashboard.md")
62
+
63
+ assert "--allow-non-loopback" in security
64
+ assert "--allow-non-loopback" in dashboard
65
+ assert "including the effective port" in security
66
+ assert "including the effective" in dashboard
67
+ assert "only with the mutation token" in dashboard
68
+ non_loopback_commands = [
69
+ line
70
+ for line in dashboard.splitlines()
71
+ if "ctx-monitor serve" in line and ("--host 0.0.0.0" in line or "--host ::" in line)
72
+ ]
73
+ assert non_loopback_commands
74
+ assert all("--allow-non-loopback" in line for line in non_loopback_commands)
75
+
76
+
77
+ def test_threat_model_distinguishes_advice_execution_and_isolation() -> None:
78
+ threat_model = _read("docs/threat-model.md")
79
+
80
+ assert "Recommendation Is Not Execution" in threat_model
81
+ assert "A recommendation does not run an `install_command`" in threat_model
82
+ assert "does **not** provide process isolation or network isolation" in threat_model
83
+ assert "recommendations, not current ctx features" in threat_model
84
+ assert "does not perform an equivalent post-check of a remotely" in threat_model
85
+
86
+
87
+ def test_threat_model_records_critical_unimplemented_boundaries() -> None:
88
+ threat_model = _read("docs/threat-model.md")
89
+
90
+ assert "not a universal ingestion gate" in threat_model
91
+ assert "compares the canonical hostname and" in threat_model
92
+ assert "reads are available to loopback clients without authentication" in threat_model
93
+ assert "embed the token in rendered JavaScript" in threat_model
94
+ assert "not isolation from another" in threat_model
95
+ assert "does not prevent SSRF or DNS rebinding" in threat_model
96
+ assert "does **not** provide process isolation or network isolation" in threat_model
97
+
98
+
99
+ def test_threat_model_records_provenance_and_ephemeral_wiki_contracts() -> None:
100
+ threat_model = _read("docs/threat-model.md")
101
+
102
+ assert "binds the complete canonical" in threat_model
103
+ assert "Permission evidence must be a digest-verified checked-in file" in threat_model
104
+ assert "inherited Design.md corpus remains blocked" in threat_model
105
+ assert "raw `ctx__wiki_get` call and result to one" in threat_model
106
+ assert "blocks compaction while raw wiki" in threat_model
107
+ assert "model independently quotes or summarizes" in threat_model
108
+
109
+
110
+ def _monitor_handler(
111
+ *,
112
+ host: str,
113
+ origin: str | None,
114
+ token: str = "monitor-secret",
115
+ mutations_enabled: bool = True,
116
+ ) -> Any:
117
+ deps = MonitorHandlerDeps(
118
+ monitor_token=lambda: token,
119
+ mutations_enabled_default=lambda: mutations_enabled,
120
+ host_allows_mutations=host_allows_mutations,
121
+ request_host_name=request_host_name,
122
+ origin_host_name=origin_host_name,
123
+ origin_matches_http_host=origin_matches_http_host,
124
+ read_token_cookie=read_token_cookie,
125
+ read_token_cookie_name=READ_TOKEN_COOKIE,
126
+ max_post_body_bytes=MAX_POST_BODY_BYTES,
127
+ audit_log_path=lambda: ROOT / ".unused-monitor-audit.jsonl",
128
+ handle_get_route=lambda _handler, _route, _query: None,
129
+ handle_post_route=lambda _handler, _route, _body, _path: None,
130
+ )
131
+ handler_type = build_monitor_handler(deps)
132
+ handler = cast(Any, object.__new__(handler_type))
133
+ handler.server = SimpleNamespace(_ctx_mutations_enabled=mutations_enabled)
134
+ handler.headers = {"Host": host}
135
+ if origin is not None:
136
+ handler.headers["Origin"] = origin
137
+ return handler
138
+
139
+
140
+ def test_monitor_origin_gate_requires_exact_http_authority() -> None:
141
+ assert (
142
+ _monitor_handler(
143
+ host="localhost:8765",
144
+ origin="http://localhost:8765",
145
+ )._same_origin()
146
+ is True
147
+ )
148
+ assert (
149
+ _monitor_handler(
150
+ host="localhost:8765",
151
+ origin="https://localhost:8765",
152
+ )._same_origin()
153
+ is False
154
+ )
155
+ assert (
156
+ _monitor_handler(
157
+ host="localhost:8765",
158
+ origin="http://localhost:9443",
159
+ )._same_origin()
160
+ is False
161
+ )
162
+
163
+
164
+ def test_loopback_reads_need_no_token_and_mutation_ui_embeds_token() -> None:
165
+ handler = _monitor_handler(host="127.0.0.1:8765", origin=None)
166
+
167
+ assert handler._read_authorized({}) is True
168
+
169
+ rendered = render_loaded(
170
+ {"load": [], "unload": []},
171
+ mutations_enabled=True,
172
+ monitor_token="rendered-secret",
173
+ layout=lambda _title, body: body,
174
+ )
175
+ assert 'const CTX_MONITOR_TOKEN = "rendered-secret"' in rendered
176
+
177
+
178
+ def test_remote_harness_url_validation_allows_private_network_hosts() -> None:
179
+ for url in (
180
+ "https://127.0.0.1/repository",
181
+ "https://10.0.0.8/repository",
182
+ "https://169.254.169.254/repository",
183
+ "https://rebind.example/repository",
184
+ ):
185
+ harness_install._validate_remote_repo_url(url)
186
+
187
+
188
+ def test_source_registry_is_wired_only_to_designmd_full_body_import() -> None:
189
+ pyproject = tomllib.loads(_read("pyproject.toml"))
190
+ assert pyproject["project"]["scripts"]["ctx-source-registry"] == "ctx.core.source_registry:main"
191
+
192
+ consumers: list[str] = []
193
+ source_root = ROOT / "src"
194
+ registry_path = source_root / "ctx" / "core" / "source_registry.py"
195
+ for path in source_root.rglob("*.py"):
196
+ relative = path.relative_to(source_root)
197
+ if relative.parts[0] == "tests" or path == registry_path:
198
+ continue
199
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
200
+ for node in ast.walk(tree):
201
+ if isinstance(node, ast.Import) and any(
202
+ alias.name == "ctx.core.source_registry" for alias in node.names
203
+ ):
204
+ consumers.append(str(relative))
205
+ if isinstance(node, ast.ImportFrom) and (node.module or "").endswith("source_registry"):
206
+ consumers.append(str(relative))
207
+
208
+ assert consumers == ["import_designdotmd_skills.py"]
src/tests/test_wiki_batch_entities.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Behavior tests for batch-generating skill and agent wiki pages."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from collections.abc import Callable
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ import pytest
11
+
12
+ import wiki_batch_entities as batch
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class EntityCase:
17
+ name: str
18
+ page: Path
19
+ entity_type: str
20
+ generate: Callable[[bool], int]
21
+
22
+
23
+ @pytest.fixture()
24
+ def entity_cases(
25
+ tmp_path: Path,
26
+ monkeypatch: pytest.MonkeyPatch,
27
+ ) -> dict[str, EntityCase]:
28
+ skills_dir = tmp_path / "installed-skills"
29
+ agents_dir = tmp_path / "installed-agents"
30
+ wiki_dir = tmp_path / "wiki"
31
+ skill_entities = wiki_dir / "entities" / "skills"
32
+ agent_entities = wiki_dir / "entities" / "agents"
33
+
34
+ skill_name = "demo-skill"
35
+ skill_source = skills_dir / skill_name / "SKILL.md"
36
+ skill_source.parent.mkdir(parents=True)
37
+ skill_source.write_text(
38
+ "---\ndescription: Demo skill.\n---\n\n# Demo Skill\n",
39
+ encoding="utf-8",
40
+ )
41
+
42
+ agent_name = "demo-agent"
43
+ agents_dir.mkdir(parents=True)
44
+ (agents_dir / f"{agent_name}.md").write_text(
45
+ "---\ndescription: Demo agent.\nmodel: sonnet\n---\n\n# Demo Agent\n",
46
+ encoding="utf-8",
47
+ )
48
+
49
+ monkeypatch.setattr(batch, "SKILLS_DIR", skills_dir)
50
+ monkeypatch.setattr(batch, "AGENTS_DIR", agents_dir)
51
+ monkeypatch.setattr(batch, "WIKI_DIR", wiki_dir)
52
+ monkeypatch.setattr(batch, "SKILL_ENTITIES", skill_entities)
53
+ monkeypatch.setattr(batch, "AGENT_ENTITIES", agent_entities)
54
+
55
+ return {
56
+ "skills": EntityCase(
57
+ name=skill_name,
58
+ page=skill_entities / f"{skill_name}.md",
59
+ entity_type="skill",
60
+ generate=batch.generate_missing_skills,
61
+ ),
62
+ "agents": EntityCase(
63
+ name=agent_name,
64
+ page=agent_entities / f"{agent_name}.md",
65
+ entity_type="agent",
66
+ generate=batch.generate_missing_agents,
67
+ ),
68
+ }
69
+
70
+
71
+ @pytest.mark.parametrize("kind", ["skills", "agents"])
72
+ def test_dry_run_reports_without_writing(
73
+ kind: str,
74
+ entity_cases: dict[str, EntityCase],
75
+ capsys: pytest.CaptureFixture[str],
76
+ ) -> None:
77
+ case = entity_cases[kind]
78
+ assert not case.page.parent.exists()
79
+
80
+ assert case.generate(True) == 0
81
+
82
+ assert not case.page.parent.exists()
83
+ assert not case.page.exists()
84
+ assert f"[DRY RUN] Would create: {case.name}.md" in capsys.readouterr().out
85
+
86
+
87
+ @pytest.mark.parametrize("kind", ["skills", "agents"])
88
+ def test_apply_creates_missing_page(
89
+ kind: str,
90
+ entity_cases: dict[str, EntityCase],
91
+ ) -> None:
92
+ case = entity_cases[kind]
93
+
94
+ assert case.generate(False) == 1
95
+
96
+ content = case.page.read_text(encoding="utf-8")
97
+ assert f"type: {case.entity_type}" in content
98
+ assert f"# {case.name}" in content
99
+
100
+
101
+ @pytest.mark.parametrize("kind", ["skills", "agents"])
102
+ def test_apply_uses_safe_atomic_writer(
103
+ kind: str,
104
+ entity_cases: dict[str, EntityCase],
105
+ monkeypatch: pytest.MonkeyPatch,
106
+ ) -> None:
107
+ case = entity_cases[kind]
108
+ writes: list[tuple[Path, str, str]] = []
109
+
110
+ def record_write(path: Path, text: str, encoding: str = "utf-8") -> None:
111
+ writes.append((path, text, encoding))
112
+
113
+ monkeypatch.setattr(batch, "safe_atomic_write_text", record_write)
114
+
115
+ assert case.generate(False) == 1
116
+ assert len(writes) == 1
117
+ path, content, encoding = writes[0]
118
+ assert path == case.page
119
+ assert f"type: {case.entity_type}" in content
120
+ assert encoding == "utf-8"
121
+
122
+
123
+ @pytest.mark.parametrize("kind", ["skills", "agents"])
124
+ def test_existing_page_is_skipped(
125
+ kind: str,
126
+ entity_cases: dict[str, EntityCase],
127
+ ) -> None:
128
+ case = entity_cases[kind]
129
+ original = "# Existing page\n\nPreserve this content.\n"
130
+ case.page.parent.mkdir(parents=True)
131
+ case.page.write_text(original, encoding="utf-8")
132
+
133
+ assert case.generate(False) == 0
134
+ assert case.page.read_text(encoding="utf-8") == original
135
+
136
+
137
+ @pytest.mark.parametrize("kind", ["skills", "agents"])
138
+ def test_rerun_is_idempotent(
139
+ kind: str,
140
+ entity_cases: dict[str, EntityCase],
141
+ monkeypatch: pytest.MonkeyPatch,
142
+ ) -> None:
143
+ case = entity_cases[kind]
144
+ assert case.generate(False) == 1
145
+ original = case.page.read_bytes()
146
+
147
+ def unexpected_write(*args: object, **kwargs: object) -> None:
148
+ pytest.fail("rerun attempted to rewrite an existing entity page")
149
+
150
+ monkeypatch.setattr(batch, "safe_atomic_write_text", unexpected_write)
151
+
152
+ assert case.generate(False) == 0
153
+ assert case.page.read_bytes() == original
154
+
155
+
156
+ def test_cli_all_generates_skills_and_agents(
157
+ entity_cases: dict[str, EntityCase],
158
+ monkeypatch: pytest.MonkeyPatch,
159
+ capsys: pytest.CaptureFixture[str],
160
+ ) -> None:
161
+ monkeypatch.setattr(sys, "argv", ["wiki_batch_entities.py", "--all"])
162
+
163
+ batch.main()
164
+
165
+ assert entity_cases["skills"].page.exists()
166
+ assert entity_cases["agents"].page.exists()
167
+ assert "Total: 2 entity pages generated" in capsys.readouterr().out
168
+
169
+
170
+ def test_cli_without_mode_exits_one(
171
+ entity_cases: dict[str, EntityCase],
172
+ monkeypatch: pytest.MonkeyPatch,
173
+ capsys: pytest.CaptureFixture[str],
174
+ ) -> None:
175
+ monkeypatch.setattr(sys, "argv", ["wiki_batch_entities.py"])
176
+
177
+ with pytest.raises(SystemExit) as exit_info:
178
+ batch.main()
179
+
180
+ assert exit_info.value.code == 1
181
+ assert "usage:" in capsys.readouterr().out
182
+ assert not entity_cases["skills"].page.parent.exists()
183
+ assert not entity_cases["agents"].page.parent.exists()
src/tests/test_wiki_packs.py CHANGED
@@ -36,6 +36,8 @@ def test_wiki_base_pack_manifest_round_trips(tmp_path: Path) -> None:
36
  assert manifest.page_count == 2
37
  assert manifest.tombstone_count == 0
38
  assert read_wiki_pack_manifest(pack_dir / "wiki-pack-manifest.json") == manifest
 
 
39
  assert (
40
  json.loads((pack_dir / "pages.jsonl").read_text(encoding="utf-8").splitlines()[0])["path"]
41
  == "entities/skills/python.md"
 
36
  assert manifest.page_count == 2
37
  assert manifest.tombstone_count == 0
38
  assert read_wiki_pack_manifest(pack_dir / "wiki-pack-manifest.json") == manifest
39
+ assert discover_wiki_pack_manifests(pack_dir.parent)[0].manifest == manifest
40
+ assert b"\r\n" not in (pack_dir / "pages.jsonl").read_bytes()
41
  assert (
42
  json.loads((pack_dir / "pages.jsonl").read_text(encoding="utf-8").splitlines()[0])["path"]
43
  == "entities/skills/python.md"
src/tests/test_wiki_queue_worker_cli.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CLI contract tests for the durable wiki queue worker."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import pytest
9
+
10
+ from ctx.core.wiki import wiki_queue_worker
11
+
12
+
13
+ def test_once_forwards_limit_one(
14
+ tmp_path: Path,
15
+ monkeypatch: pytest.MonkeyPatch,
16
+ capsys: pytest.CaptureFixture[str],
17
+ ) -> None:
18
+ observed: dict[str, Any] = {}
19
+
20
+ def fake_drain_queue(wiki_path: Path, **kwargs: Any) -> list[object]:
21
+ observed["wiki_path"] = wiki_path
22
+ observed.update(kwargs)
23
+ return []
24
+
25
+ monkeypatch.setattr(wiki_queue_worker, "drain_queue", fake_drain_queue)
26
+
27
+ wiki_queue_worker.main(["--wiki", str(tmp_path), "--worker-id", "test-worker", "--once"])
28
+
29
+ assert observed["wiki_path"] == tmp_path
30
+ assert observed["worker_id"] == "test-worker"
31
+ assert observed["limit"] == 1
32
+ assert capsys.readouterr().out == "No ready wiki queue jobs.\n"
33
+
34
+
35
+ def test_once_and_limit_are_mutually_exclusive(
36
+ capsys: pytest.CaptureFixture[str],
37
+ ) -> None:
38
+ with pytest.raises(SystemExit) as exc_info:
39
+ wiki_queue_worker.main(["--once", "--limit", "1"])
40
+
41
+ assert exc_info.value.code == 2
42
+ assert "use either --once or --limit, not both" in capsys.readouterr().err
src/tests/test_wiki_visualize.py CHANGED
@@ -1,8 +1,8 @@
1
  """
2
- test_wiki_visualize.py -- Regression tests for XSS hardening in wiki_visualize.
3
 
4
  Covers the three Strix-validated XSS sinks:
5
- 1. CLI-derived ``--title`` interpolated into ``<title>`` and ``<div id="title">``
6
  2. Untrusted graph tag names interpolated into filter-button HTML
7
  3. Untrusted node labels embedded in a raw ``<script>`` block via ``json.dumps``
8
  (``</script>`` breakout)
@@ -16,7 +16,10 @@ from __future__ import annotations
16
  import builtins
17
  import importlib
18
  import json
 
 
19
  import sys
 
20
  from pathlib import Path
21
 
22
  import networkx as nx
@@ -27,12 +30,36 @@ if str(_SRC) not in sys.path:
27
  sys.path.insert(0, str(_SRC))
28
 
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  @pytest.fixture()
31
  def graph_with_hostile_labels() -> tuple[nx.Graph, dict]:
32
  G = nx.Graph()
33
  G.add_node(
34
  "skill:evil",
35
- label="</script><script>window.__pwn=1</script>",
36
  type="skill",
37
  tags=['"><img src=x onerror="window.__tagpwn=1">'],
38
  )
@@ -42,6 +69,95 @@ def graph_with_hostile_labels() -> tuple[nx.Graph, dict]:
42
  return G, pos
43
 
44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  def test_html_visualizer_imports_without_optional_plotly(monkeypatch):
46
  previous = sys.modules.pop("wiki_visualize", None)
47
  real_import = builtins.__import__
@@ -96,17 +212,33 @@ def test_script_breakout_via_node_label_is_neutralized(graph_with_hostile_labels
96
  import wiki_visualize as wv
97
 
98
  G, pos = graph_with_hostile_labels
99
- html = wv.build_html_with_filters(G, pos, title="safe")
100
- # The literal closing tag must not survive anywhere in the embedded NODES
101
- # JSON, because any </script> inside a raw <script> block ends the block.
102
- # Count occurrences outside actual </script> close tags: there should be
103
- # exactly one </script> (the end of our embedded-data script).
104
- close_tags = html.count("</script>")
105
- # Page has 2 real </script> tags: one after the plotly CDN <script>, one
106
- # closing the inline data+render block. Any further </script> = breakout.
107
- assert close_tags <= 2, f"unexpected </script> sequences: {close_tags}"
108
- # Escaped form should appear instead
109
- assert r"<\/script>" in html or "&lt;/script&gt;" in html
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
 
112
  def test_benign_render_still_works():
@@ -135,6 +267,123 @@ def test_default_min_weight_preserves_fractional_semantic_edges():
135
  assert sub.number_of_edges() == 1
136
 
137
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  def test_visualizer_renders_mcp_and_harness_type_filters():
139
  import wiki_visualize as wv
140
 
@@ -212,3 +461,311 @@ def test_visualizer_embeds_export_metadata_for_preview_freshness():
212
  assert '"export_id": "ctx-graph-test-2-1"' in html
213
  assert '"nodes": 2' in html
214
  assert '"edges": 1' in html
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """
2
+ test_wiki_visualize.py -- User-behavior and security tests for wiki_visualize.
3
 
4
  Covers the three Strix-validated XSS sinks:
5
+ 1. Caller-provided titles interpolated into ``<title>`` and ``<div id="title">``
6
  2. Untrusted graph tag names interpolated into filter-button HTML
7
  3. Untrusted node labels embedded in a raw ``<script>`` block via ``json.dumps``
8
  (``</script>`` breakout)
 
16
  import builtins
17
  import importlib
18
  import json
19
+ import os
20
+ import subprocess
21
  import sys
22
+ from html.parser import HTMLParser
23
  from pathlib import Path
24
 
25
  import networkx as nx
 
30
  sys.path.insert(0, str(_SRC))
31
 
32
 
33
+ class _ScriptParser(HTMLParser):
34
+ def __init__(self) -> None:
35
+ super().__init__(convert_charrefs=False)
36
+ self.start_count = 0
37
+ self.end_count = 0
38
+ self.scripts: list[tuple[dict[str, str | None], list[str]]] = []
39
+ self._current_data: list[str] | None = None
40
+
41
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
42
+ if tag == "script":
43
+ self.start_count += 1
44
+ self._current_data = []
45
+ self.scripts.append((dict(attrs), self._current_data))
46
+
47
+ def handle_endtag(self, tag: str) -> None:
48
+ if tag == "script":
49
+ self.end_count += 1
50
+ self._current_data = None
51
+
52
+ def handle_data(self, data: str) -> None:
53
+ if self._current_data is not None:
54
+ self._current_data.append(data)
55
+
56
+
57
  @pytest.fixture()
58
  def graph_with_hostile_labels() -> tuple[nx.Graph, dict]:
59
  G = nx.Graph()
60
  G.add_node(
61
  "skill:evil",
62
+ label="</script><script>window.__pwn=1</script><!--<script>",
63
  type="skill",
64
  tags=['"><img src=x onerror="window.__tagpwn=1">'],
65
  )
 
69
  return G, pos
70
 
71
 
72
+ @pytest.fixture()
73
+ def cli_graph_files(tmp_path: Path) -> tuple[Path, Path]:
74
+ graph_path = tmp_path / "graph.json"
75
+ communities_path = tmp_path / "communities.json"
76
+ graph_path.write_text(
77
+ json.dumps(
78
+ {
79
+ "directed": False,
80
+ "multigraph": False,
81
+ "graph": {"export_id": "ctx-cli-test-1"},
82
+ "nodes": [
83
+ {
84
+ "id": "skill:alpha",
85
+ "label": "alpha",
86
+ "type": "skill",
87
+ "tags": ["security", "python"],
88
+ },
89
+ {
90
+ "id": "agent:beta",
91
+ "label": "beta",
92
+ "type": "agent",
93
+ "tags": ["security"],
94
+ },
95
+ {
96
+ "id": "harness:gamma",
97
+ "label": "gamma",
98
+ "type": "harness",
99
+ "tags": ["security"],
100
+ },
101
+ {
102
+ "id": "mcp-server:delta",
103
+ "label": "delta",
104
+ "type": "mcp-server",
105
+ "tags": ["external"],
106
+ },
107
+ ],
108
+ "edges": [
109
+ {"source": "skill:alpha", "target": "agent:beta", "weight": 3},
110
+ {"source": "skill:alpha", "target": "harness:gamma", "weight": 1},
111
+ {"source": "skill:alpha", "target": "mcp-server:delta", "weight": 4},
112
+ ],
113
+ }
114
+ ),
115
+ encoding="utf-8",
116
+ )
117
+ communities_path.write_text(
118
+ json.dumps(
119
+ {
120
+ "communities": {
121
+ "7": {
122
+ "label": "secure automation",
123
+ "members": ["skill:alpha", "agent:beta"],
124
+ }
125
+ }
126
+ }
127
+ ),
128
+ encoding="utf-8",
129
+ )
130
+ return graph_path, communities_path
131
+
132
+
133
+ def _run_main(monkeypatch: pytest.MonkeyPatch, *args: object) -> None:
134
+ import wiki_visualize as wv
135
+
136
+ monkeypatch.setattr(sys, "argv", ["wiki_visualize.py", *(str(arg) for arg in args)])
137
+ wv.main()
138
+
139
+
140
+ def _render_cli_graph(
141
+ monkeypatch: pytest.MonkeyPatch,
142
+ cli_graph_files: tuple[Path, Path],
143
+ tmp_path: Path,
144
+ *filters: object,
145
+ ) -> str:
146
+ graph_path, communities_path = cli_graph_files
147
+ output_path = tmp_path / "orthogonal-filter.html"
148
+ _run_main(
149
+ monkeypatch,
150
+ "--graph-json",
151
+ graph_path,
152
+ "--communities-json",
153
+ communities_path,
154
+ *filters,
155
+ "--output",
156
+ output_path,
157
+ )
158
+ return output_path.read_text(encoding="utf-8")
159
+
160
+
161
  def test_html_visualizer_imports_without_optional_plotly(monkeypatch):
162
  previous = sys.modules.pop("wiki_visualize", None)
163
  real_import = builtins.__import__
 
212
  import wiki_visualize as wv
213
 
214
  G, pos = graph_with_hostile_labels
215
+ rendered = wv.build_html_with_filters(G, pos, title="safe")
216
+ parser = _ScriptParser()
217
+ parser.feed(rendered)
218
+ parser.close()
219
+
220
+ assert parser.start_count == 2
221
+ assert parser.end_count == 2
222
+ assert len(parser.scripts) == 2
223
+ assert parser.scripts[0][0]["src"] == "https://cdn.plot.ly/plotly-2.35.2.min.js"
224
+ assert "src" not in parser.scripts[1][0]
225
+
226
+ inline_script = "".join(parser.scripts[1][1])
227
+ assert "</script>" not in inline_script.lower()
228
+
229
+ nodes_line = next(
230
+ line for line in inline_script.splitlines() if line.startswith("const NODES = ")
231
+ )
232
+ assert nodes_line.endswith(";")
233
+ nodes_json = nodes_line.removeprefix("const NODES = ").removesuffix(";")
234
+ assert "<" not in nodes_json
235
+ assert r"\u003c/script>" in nodes_json
236
+ assert r"\u003c!--\u003cscript>" in nodes_json
237
+
238
+ nodes = json.loads(nodes_json)
239
+ nodes_by_id = {node["id"]: node for node in nodes}
240
+ assert nodes_by_id["skill:evil"]["label"] == G.nodes["skill:evil"]["label"]
241
+ assert nodes_by_id["skill:evil"]["tags"] == G.nodes["skill:evil"]["tags"]
242
 
243
 
244
  def test_benign_render_still_works():
 
267
  assert sub.number_of_edges() == 1
268
 
269
 
270
+ def test_cli_seed_filter_selects_only_the_seed_neighborhood(
271
+ cli_graph_files: tuple[Path, Path], tmp_path: Path, monkeypatch: pytest.MonkeyPatch
272
+ ):
273
+ rendered = _render_cli_graph(monkeypatch, cli_graph_files, tmp_path, "--seed", "beta")
274
+
275
+ assert '"view_nodes": 2' in rendered
276
+ assert '"view_edges": 1' in rendered
277
+ assert '"label": "alpha"' in rendered
278
+ assert '"label": "beta"' in rendered
279
+ assert '"label": "gamma"' not in rendered
280
+ assert '"label": "delta"' not in rendered
281
+
282
+
283
+ def test_cli_zero_hops_keeps_the_matched_seed(
284
+ cli_graph_files: tuple[Path, Path], tmp_path: Path, monkeypatch: pytest.MonkeyPatch
285
+ ):
286
+ rendered = _render_cli_graph(
287
+ monkeypatch, cli_graph_files, tmp_path, "--seed", "beta", "--hops", 0
288
+ )
289
+
290
+ assert '"view_nodes": 1' in rendered
291
+ assert '"view_edges": 0' in rendered
292
+ assert '"label": "beta"' in rendered
293
+ assert '"label": "alpha"' not in rendered
294
+
295
+
296
+ def test_cli_tag_filter_selects_only_tagged_nodes(
297
+ cli_graph_files: tuple[Path, Path], tmp_path: Path, monkeypatch: pytest.MonkeyPatch
298
+ ):
299
+ rendered = _render_cli_graph(monkeypatch, cli_graph_files, tmp_path, "--tag", "security")
300
+
301
+ assert '"view_nodes": 3' in rendered
302
+ assert '"view_edges": 2' in rendered
303
+ assert '"label": "alpha"' in rendered
304
+ assert '"label": "beta"' in rendered
305
+ assert '"label": "gamma"' in rendered
306
+ assert '"label": "delta"' not in rendered
307
+
308
+
309
+ def test_cli_top_filter_keeps_the_selected_singleton(
310
+ cli_graph_files: tuple[Path, Path], tmp_path: Path, monkeypatch: pytest.MonkeyPatch
311
+ ):
312
+ rendered = _render_cli_graph(monkeypatch, cli_graph_files, tmp_path, "--top", 1)
313
+
314
+ assert '"view_nodes": 1' in rendered
315
+ assert '"view_edges": 0' in rendered
316
+ assert '"label": "alpha"' in rendered
317
+ assert '"label": "beta"' not in rendered
318
+ assert '"label": "gamma"' not in rendered
319
+ assert '"label": "delta"' not in rendered
320
+
321
+
322
+ def test_min_weight_blocks_seed_bfs_at_a_weak_bridge():
323
+ import wiki_visualize as wv
324
+
325
+ G = nx.Graph()
326
+ for label in ("seed", "kept", "bridge", "hidden"):
327
+ G.add_node(f"skill:{label}", label=label)
328
+ G.add_edge("skill:seed", "skill:kept", weight=3)
329
+ G.add_edge("skill:seed", "skill:bridge", weight=1)
330
+ G.add_edge("skill:bridge", "skill:hidden", weight=3)
331
+
332
+ sub = wv.extract_subgraph(G, seeds=["seed"], hops=2, min_weight=2)
333
+
334
+ assert set(sub) == {"skill:seed", "skill:kept"}
335
+ assert sub.number_of_edges() == 1
336
+ assert sub.has_edge("skill:seed", "skill:kept")
337
+
338
+
339
+ @pytest.mark.parametrize("primary_filter", ["tag", "community"])
340
+ def test_min_weight_filters_edges_after_non_seed_selection(primary_filter: str):
341
+ import wiki_visualize as wv
342
+
343
+ G = nx.Graph()
344
+ for label in ("alpha", "beta", "gamma"):
345
+ G.add_node(f"skill:{label}", label=label, tags=["security"])
346
+ G.add_edge("skill:alpha", "skill:beta", weight=3)
347
+ G.add_edge("skill:beta", "skill:gamma", weight=1)
348
+
349
+ if primary_filter == "tag":
350
+ sub = wv.extract_subgraph(G, tag_filter="security", min_weight=2)
351
+ else:
352
+ communities = {"communities": {"7": {"members": list(G)}}}
353
+ sub = wv.extract_subgraph(G, community_id=7, communities=communities, min_weight=2)
354
+
355
+ assert set(sub) == {"skill:alpha", "skill:beta"}
356
+ assert sub.number_of_edges() == 1
357
+ assert sub.has_edge("skill:alpha", "skill:beta")
358
+
359
+
360
+ def test_tied_top_filter_is_deterministic_across_hash_seeds() -> None:
361
+ script = (
362
+ "import json, sys\n"
363
+ f"sys.path.insert(0, {str(_SRC)!r})\n"
364
+ "import networkx as nx\n"
365
+ "import wiki_visualize as wv\n"
366
+ "graph = nx.Graph()\n"
367
+ "graph.add_edges_from([('skill:a', 'skill:b'), ('skill:b', 'skill:c'), "
368
+ "('skill:c', 'skill:d'), ('skill:d', 'skill:a')])\n"
369
+ "print(json.dumps(sorted(wv.extract_subgraph(graph, top_n=2).nodes())))\n"
370
+ )
371
+ outputs: dict[str, str] = {}
372
+ for hash_seed in ("1", "2", "7", "42"):
373
+ env = os.environ.copy()
374
+ env["PYTHONHASHSEED"] = hash_seed
375
+ completed = subprocess.run(
376
+ [sys.executable, "-c", script],
377
+ check=True,
378
+ capture_output=True,
379
+ text=True,
380
+ env=env,
381
+ )
382
+ outputs[hash_seed] = completed.stdout.strip()
383
+
384
+ assert set(outputs.values()) == {'["skill:a", "skill:b"]'}, outputs
385
+
386
+
387
  def test_visualizer_renders_mcp_and_harness_type_filters():
388
  import wiki_visualize as wv
389
 
 
461
  assert '"export_id": "ctx-graph-test-2-1"' in html
462
  assert '"nodes": 2' in html
463
  assert '"edges": 1' in html
464
+
465
+
466
+ def test_cli_default_output_writes_html_and_opens_browser(
467
+ cli_graph_files: tuple[Path, Path],
468
+ tmp_path: Path,
469
+ monkeypatch: pytest.MonkeyPatch,
470
+ capsys: pytest.CaptureFixture[str],
471
+ ):
472
+ import webbrowser
473
+
474
+ graph_path, communities_path = cli_graph_files
475
+ opened: list[str] = []
476
+ monkeypatch.chdir(tmp_path)
477
+
478
+ def record_open(target: str) -> bool:
479
+ opened.append(target)
480
+ return True
481
+
482
+ monkeypatch.setattr(webbrowser, "open", record_open)
483
+
484
+ _run_main(
485
+ monkeypatch,
486
+ "--graph-json",
487
+ graph_path,
488
+ "--communities-json",
489
+ communities_path,
490
+ "--seed",
491
+ "alpha",
492
+ )
493
+
494
+ output_path = tmp_path / "graph-view.html"
495
+ assert output_path.is_file()
496
+ assert opened == [str(output_path.resolve())]
497
+ assert "Subgraph: 4 nodes, 3 edges" in capsys.readouterr().out
498
+
499
+
500
+ def test_cli_explicit_output_applies_filters_without_opening_browser(
501
+ cli_graph_files: tuple[Path, Path],
502
+ tmp_path: Path,
503
+ monkeypatch: pytest.MonkeyPatch,
504
+ ):
505
+ import webbrowser
506
+
507
+ graph_path, communities_path = cli_graph_files
508
+ output_path = tmp_path / "filtered.html"
509
+ opened: list[str] = []
510
+
511
+ def record_open(target: str) -> bool:
512
+ opened.append(target)
513
+ return True
514
+
515
+ monkeypatch.setattr(webbrowser, "open", record_open)
516
+
517
+ _run_main(
518
+ monkeypatch,
519
+ "--graph-json",
520
+ graph_path,
521
+ "--communities-json",
522
+ communities_path,
523
+ "--tag",
524
+ "security",
525
+ "--top",
526
+ 2,
527
+ "--min-weight",
528
+ 2,
529
+ "--output",
530
+ output_path,
531
+ )
532
+
533
+ rendered = output_path.read_text(encoding="utf-8")
534
+ assert opened == []
535
+ assert '"view_nodes": 2' in rendered
536
+ assert '"view_edges": 1' in rendered
537
+ assert '"label": "alpha"' in rendered
538
+ assert '"label": "beta"' in rendered
539
+ assert '"label": "gamma"' not in rendered
540
+ assert '"label": "delta"' not in rendered
541
+
542
+
543
+ def test_cli_community_filter_uses_explicit_assignments(
544
+ cli_graph_files: tuple[Path, Path],
545
+ tmp_path: Path,
546
+ monkeypatch: pytest.MonkeyPatch,
547
+ ):
548
+ graph_path, communities_path = cli_graph_files
549
+ output_path = tmp_path / "community.html"
550
+
551
+ _run_main(
552
+ monkeypatch,
553
+ "--graph-json",
554
+ graph_path,
555
+ "--communities-json",
556
+ communities_path,
557
+ "--community",
558
+ 7,
559
+ "--output",
560
+ output_path,
561
+ )
562
+
563
+ rendered = output_path.read_text(encoding="utf-8")
564
+ assert '"view_nodes": 2' in rendered
565
+ assert '"view_edges": 1' in rendered
566
+ assert "community 7" in rendered
567
+
568
+
569
+ def test_cli_stats_is_read_only(
570
+ cli_graph_files: tuple[Path, Path],
571
+ tmp_path: Path,
572
+ monkeypatch: pytest.MonkeyPatch,
573
+ capsys: pytest.CaptureFixture[str],
574
+ ):
575
+ graph_path, communities_path = cli_graph_files
576
+ monkeypatch.chdir(tmp_path)
577
+
578
+ _run_main(
579
+ monkeypatch,
580
+ "--graph-json",
581
+ graph_path,
582
+ "--communities-json",
583
+ communities_path,
584
+ "--stats",
585
+ )
586
+
587
+ output = capsys.readouterr().out
588
+ assert "Full graph: 4 nodes, 3 edges" in output
589
+ assert "Skills: 1, Agents: 1" in output
590
+ assert "Communities: 1" in output
591
+ assert not (tmp_path / "graph-view.html").exists()
592
+
593
+
594
+ def test_cli_interactive_community_uses_supplied_assignments(
595
+ cli_graph_files: tuple[Path, Path],
596
+ tmp_path: Path,
597
+ monkeypatch: pytest.MonkeyPatch,
598
+ ):
599
+ import wiki_visualize as wv
600
+
601
+ graph_path, communities_path = cli_graph_files
602
+ output_path = tmp_path / "interactive-community.html"
603
+ answers = iter(["3", "7", str(output_path)])
604
+ load_calls: list[Path | str | None] = []
605
+ figures = []
606
+ real_load_communities = wv.load_communities
607
+
608
+ class FakeFigure:
609
+ def __init__(self, data=None):
610
+ self.data = list(data or [])
611
+ self.layout = {}
612
+ figures.append(self)
613
+
614
+ def add_annotation(self, **kwargs) -> None:
615
+ self.annotation = kwargs
616
+
617
+ def update_layout(self, **kwargs) -> None:
618
+ self.layout = kwargs
619
+
620
+ def write_html(self, path: str, *, include_plotlyjs: bool) -> None:
621
+ assert include_plotlyjs is True
622
+ Path(path).write_text("rendered", encoding="utf-8")
623
+
624
+ class FakePlotly:
625
+ Figure = FakeFigure
626
+
627
+ @staticmethod
628
+ def Scatter(**kwargs):
629
+ return kwargs
630
+
631
+ def record_load_communities(path: Path | str | None = None) -> dict:
632
+ load_calls.append(path)
633
+ return real_load_communities(path)
634
+
635
+ monkeypatch.setattr(builtins, "input", lambda _prompt: next(answers))
636
+ monkeypatch.setattr(wv, "load_communities", record_load_communities)
637
+ monkeypatch.setattr(wv, "_load_plotly_graph_objects", lambda: FakePlotly)
638
+
639
+ _run_main(
640
+ monkeypatch,
641
+ "--graph-json",
642
+ graph_path,
643
+ "--communities-json",
644
+ communities_path,
645
+ )
646
+
647
+ assert load_calls == [communities_path]
648
+ assert output_path.read_text(encoding="utf-8") == "rendered"
649
+ assert len(figures) == 1
650
+ node_traces = [trace for trace in figures[0].data if trace.get("mode") == "markers+text"]
651
+ assert len(node_traces) == 2
652
+ for trace in node_traces:
653
+ assert trace["marker"]["color"] == [wv.COMMUNITY_COLORS[7]]
654
+ assert trace["hovertext"][0].endswith("Community: 7")
655
+
656
+
657
+ @pytest.mark.parametrize(
658
+ ("option", "value"),
659
+ [
660
+ ("--top", "0"),
661
+ ("--top", "-1"),
662
+ ("--hops", "-1"),
663
+ ("--min-weight", "-0.1"),
664
+ ("--min-weight", "nan"),
665
+ ("--community", "-1"),
666
+ ],
667
+ )
668
+ def test_cli_rejects_out_of_bounds_numbers_before_prompting(
669
+ option: str,
670
+ value: str,
671
+ monkeypatch: pytest.MonkeyPatch,
672
+ capsys: pytest.CaptureFixture[str],
673
+ ):
674
+ def unexpected_prompt(_prompt: str) -> None:
675
+ pytest.fail("invalid CLI input must not enter the interactive menu")
676
+
677
+ monkeypatch.setattr(builtins, "input", unexpected_prompt)
678
+
679
+ with pytest.raises(SystemExit) as exc_info:
680
+ _run_main(monkeypatch, option, value)
681
+
682
+ assert exc_info.value.code == 2
683
+ error = capsys.readouterr().err
684
+ assert "usage:" in error
685
+ assert f"argument {option}:" in error
686
+
687
+
688
+ def test_cli_rejects_conflicting_primary_filters(
689
+ cli_graph_files: tuple[Path, Path],
690
+ tmp_path: Path,
691
+ monkeypatch: pytest.MonkeyPatch,
692
+ capsys: pytest.CaptureFixture[str],
693
+ ):
694
+ graph_path, communities_path = cli_graph_files
695
+ output_path = tmp_path / "conflict.html"
696
+
697
+ with pytest.raises(SystemExit) as exc_info:
698
+ _run_main(
699
+ monkeypatch,
700
+ "--graph-json",
701
+ graph_path,
702
+ "--communities-json",
703
+ communities_path,
704
+ "--seed",
705
+ "alpha",
706
+ "--tag",
707
+ "security",
708
+ "--output",
709
+ output_path,
710
+ )
711
+
712
+ assert exc_info.value.code == 2
713
+ assert "not allowed with argument" in capsys.readouterr().err
714
+ assert not output_path.exists()
715
+
716
+
717
+ def test_cli_no_match_exits_one_without_writing_output(
718
+ cli_graph_files: tuple[Path, Path],
719
+ tmp_path: Path,
720
+ monkeypatch: pytest.MonkeyPatch,
721
+ capsys: pytest.CaptureFixture[str],
722
+ ):
723
+ graph_path, communities_path = cli_graph_files
724
+ output_path = tmp_path / "empty.html"
725
+
726
+ with pytest.raises(SystemExit) as exc_info:
727
+ _run_main(
728
+ monkeypatch,
729
+ "--graph-json",
730
+ graph_path,
731
+ "--communities-json",
732
+ communities_path,
733
+ "--tag",
734
+ "not-present",
735
+ "--output",
736
+ output_path,
737
+ )
738
+
739
+ assert exc_info.value.code == 1
740
+ assert "no nodes matched" in capsys.readouterr().err.lower()
741
+ assert not output_path.exists()
742
+
743
+
744
+ def test_interactive_plotly_error_is_concise(
745
+ cli_graph_files: tuple[Path, Path],
746
+ tmp_path: Path,
747
+ monkeypatch: pytest.MonkeyPatch,
748
+ capsys: pytest.CaptureFixture[str],
749
+ ):
750
+ import wiki_visualize as wv
751
+
752
+ graph_path, communities_path = cli_graph_files
753
+ graph = wv.load_graph(graph_path)
754
+ communities = wv.load_communities(communities_path)
755
+ output_path = tmp_path / "unrendered.html"
756
+ answers = iter(["3", "7", str(output_path)])
757
+
758
+ def unavailable_plotly() -> object:
759
+ raise RuntimeError('Plotly is optional. Install it with: pip install "claude-ctx[viz]"')
760
+
761
+ monkeypatch.setattr(builtins, "input", lambda _prompt: next(answers))
762
+ monkeypatch.setattr(wv, "_load_plotly_graph_objects", unavailable_plotly)
763
+
764
+ with pytest.raises(SystemExit) as exc_info:
765
+ wv.interactive_menu(graph, communities=communities)
766
+
767
+ assert exc_info.value.code == 1
768
+ error = capsys.readouterr().err
769
+ assert "Install it with" in error
770
+ assert "Traceback" not in error
771
+ assert not output_path.exists()
src/tests/test_workflow_action_pins.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterator
4
+ from pathlib import Path
5
+ import re
6
+ from typing import Any
7
+
8
+ import pytest
9
+ import yaml
10
+
11
+
12
+ ROOT = Path(__file__).resolve().parents[2]
13
+ WORKFLOWS = ROOT / ".github" / "workflows"
14
+ REMOTE_ACTION_RE = re.compile(
15
+ r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.@/-]+)?@[0-9a-f]{40}"
16
+ )
17
+ DOCKER_ACTION_RE = re.compile(r"docker://[^@\s]+@sha256:[0-9a-f]{64}")
18
+ PIN_COMMENT_RE = re.compile(r"\buses:\s*[^#\s]+(?:@[0-9a-f]{40}|@sha256:[0-9a-f]{64})\s+#\s+\S+")
19
+
20
+
21
+ def _uses_values(value: Any) -> Iterator[str]:
22
+ if isinstance(value, dict):
23
+ for key, child in value.items():
24
+ if key == "uses":
25
+ assert isinstance(child, str)
26
+ yield child
27
+ yield from _uses_values(child)
28
+ elif isinstance(value, list):
29
+ for child in value:
30
+ yield from _uses_values(child)
31
+
32
+
33
+ def _is_immutable_uses(value: str) -> bool:
34
+ if value.startswith("./"):
35
+ return ".." not in Path(value).parts
36
+ return (
37
+ REMOTE_ACTION_RE.fullmatch(value) is not None
38
+ or DOCKER_ACTION_RE.fullmatch(value) is not None
39
+ )
40
+
41
+
42
+ @pytest.mark.parametrize(
43
+ "value",
44
+ [
45
+ "./.github/actions/local",
46
+ "owner/action@0123456789abcdef0123456789abcdef01234567",
47
+ "owner/repo/.github/workflows/check.yml@0123456789abcdef0123456789abcdef01234567",
48
+ "docker://example/image@sha256:" + "a" * 64,
49
+ ],
50
+ )
51
+ def test_immutable_uses_classifier_accepts_supported_pins(value: str) -> None:
52
+ assert _is_immutable_uses(value)
53
+
54
+
55
+ @pytest.mark.parametrize(
56
+ "value",
57
+ [
58
+ "actions/checkout@v7",
59
+ "owner/action@main",
60
+ "owner/action@0123456",
61
+ "owner/action@${{ inputs.ref }}",
62
+ "./../outside",
63
+ "docker://example/image:latest",
64
+ ],
65
+ )
66
+ def test_immutable_uses_classifier_rejects_mutable_references(value: str) -> None:
67
+ assert not _is_immutable_uses(value)
68
+
69
+
70
+ def test_every_workflow_action_is_immutably_pinned() -> None:
71
+ workflow_paths = sorted((*WORKFLOWS.glob("*.yml"), *WORKFLOWS.glob("*.yaml")))
72
+
73
+ assert workflow_paths
74
+ for path in workflow_paths:
75
+ document = yaml.safe_load(path.read_text(encoding="utf-8"))
76
+ uses_values = list(_uses_values(document))
77
+ assert uses_values, f"{path.relative_to(ROOT)} has no action references"
78
+ assert [value for value in uses_values if not _is_immutable_uses(value)] == []
79
+
80
+ remote_lines = [
81
+ line
82
+ for line in path.read_text(encoding="utf-8").splitlines()
83
+ if "uses:" in line and not line.split("uses:", 1)[1].lstrip().startswith("./")
84
+ ]
85
+ assert remote_lines
86
+ assert [line for line in remote_lines if PIN_COMMENT_RE.search(line) is None] == []
src/wiki_batch_entities.py CHANGED
@@ -6,7 +6,7 @@ Usage:
6
  python wiki_batch_entities.py --skills # Generate missing skill pages
7
  python wiki_batch_entities.py --agents # Generate missing agent pages
8
  python wiki_batch_entities.py --all # Both
9
- python wiki_batch_entities.py --dry-run # Preview without writing
10
  """
11
 
12
  from __future__ import annotations
@@ -21,6 +21,8 @@ from typing import TYPE_CHECKING
21
 
22
  import yaml # type: ignore[import-untyped]
23
 
 
 
24
  if TYPE_CHECKING:
25
  from mcp_entity import McpRecord
26
 
@@ -330,7 +332,8 @@ def generate_mcp_page(record: McpRecord) -> str:
330
 
331
  def generate_missing_skills(dry_run: bool = False) -> int:
332
  """Generate entity pages for all skills missing from the wiki."""
333
- SKILL_ENTITIES.mkdir(parents=True, exist_ok=True)
 
334
 
335
  installed = {d.name for d in SKILLS_DIR.iterdir() if d.is_dir()}
336
  existing = {p.stem for p in SKILL_ENTITIES.glob("*.md")}
@@ -347,7 +350,7 @@ def generate_missing_skills(dry_run: bool = False) -> int:
347
  print(f" [DRY RUN] Would create: {name}.md")
348
  else:
349
  page_content = generate_skill_page(name)
350
- (SKILL_ENTITIES / f"{name}.md").write_text(page_content, encoding="utf-8")
351
  created += 1
352
  if created % 100 == 0:
353
  print(f" ... {created}/{len(missing)} created")
@@ -358,7 +361,8 @@ def generate_missing_skills(dry_run: bool = False) -> int:
358
 
359
  def generate_missing_agents(dry_run: bool = False) -> int:
360
  """Generate entity pages for all agents missing from the wiki."""
361
- AGENT_ENTITIES.mkdir(parents=True, exist_ok=True)
 
362
 
363
  # Collect all agent .md files: top-level AND nested in subdirectories
364
  agent_files: dict[str, Path] = {}
@@ -383,7 +387,7 @@ def generate_missing_agents(dry_run: bool = False) -> int:
383
  print(f" [DRY RUN] Would create: {name}.md")
384
  else:
385
  page_content = generate_agent_page(name, agent_files[name])
386
- (AGENT_ENTITIES / f"{name}.md").write_text(page_content, encoding="utf-8")
387
  created += 1
388
  if created % 50 == 0:
389
  print(f" ... {created}/{len(missing)} created")
 
6
  python wiki_batch_entities.py --skills # Generate missing skill pages
7
  python wiki_batch_entities.py --agents # Generate missing agent pages
8
  python wiki_batch_entities.py --all # Both
9
+ python wiki_batch_entities.py --all --dry-run # Preview both without writing
10
  """
11
 
12
  from __future__ import annotations
 
21
 
22
  import yaml # type: ignore[import-untyped]
23
 
24
+ from ctx.utils._fs_utils import safe_atomic_write_text
25
+
26
  if TYPE_CHECKING:
27
  from mcp_entity import McpRecord
28
 
 
332
 
333
  def generate_missing_skills(dry_run: bool = False) -> int:
334
  """Generate entity pages for all skills missing from the wiki."""
335
+ if not dry_run:
336
+ SKILL_ENTITIES.mkdir(parents=True, exist_ok=True)
337
 
338
  installed = {d.name for d in SKILLS_DIR.iterdir() if d.is_dir()}
339
  existing = {p.stem for p in SKILL_ENTITIES.glob("*.md")}
 
350
  print(f" [DRY RUN] Would create: {name}.md")
351
  else:
352
  page_content = generate_skill_page(name)
353
+ safe_atomic_write_text(SKILL_ENTITIES / f"{name}.md", page_content, encoding="utf-8")
354
  created += 1
355
  if created % 100 == 0:
356
  print(f" ... {created}/{len(missing)} created")
 
361
 
362
  def generate_missing_agents(dry_run: bool = False) -> int:
363
  """Generate entity pages for all agents missing from the wiki."""
364
+ if not dry_run:
365
+ AGENT_ENTITIES.mkdir(parents=True, exist_ok=True)
366
 
367
  # Collect all agent .md files: top-level AND nested in subdirectories
368
  agent_files: dict[str, Path] = {}
 
387
  print(f" [DRY RUN] Would create: {name}.md")
388
  else:
389
  page_content = generate_agent_page(name, agent_files[name])
390
+ safe_atomic_write_text(AGENT_ENTITIES / f"{name}.md", page_content, encoding="utf-8")
391
  created += 1
392
  if created % 50 == 0:
393
  print(f" ... {created}/{len(missing)} created")
src/wiki_orchestrator.py CHANGED
@@ -67,13 +67,19 @@ class HealthReport:
67
  index_count_wrong: bool = False
68
  skipped_modules: list[str] = field(default_factory=list)
69
  warnings: list[str] = field(default_factory=list)
 
70
 
71
  def deduct(self, points: int, reason: str) -> None:
72
  self.score = max(0, self.score - points)
73
  self.warnings.append(f"[-{points}] {reason}")
74
 
75
  def render(self) -> str:
76
- out = [f"Health Score: {self.score}/100", ""]
 
 
 
 
 
77
  if self.skipped_modules:
78
  out.append("Skipped modules (not yet installed):")
79
  out.extend(f" - {m}" for m in self.skipped_modules)
@@ -88,12 +94,37 @@ class HealthReport:
88
  # ---------------------------------------------------------------------------
89
 
90
 
91
- def _try_import(name: str, report: HealthReport) -> Any | None:
92
- """Load a sibling .py script. Returns module or None; logs skips gracefully.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
  Registers in sys.modules before exec so @dataclass decorators that inspect
95
  cls.__module__ resolve correctly.
96
  """
 
 
 
 
 
 
 
 
 
97
  if name == "wiki_lint":
98
 
99
  class _PackageWikiLint:
@@ -101,25 +132,32 @@ def _try_import(name: str, report: HealthReport) -> Any | None:
101
  def run_lint(wiki_dir: Path) -> list[str]:
102
  return _run_package_lint(Path(wiki_dir))
103
 
104
- return _PackageWikiLint
105
 
106
  path = SCRIPT_DIR / f"{name}.py"
107
  if not path.exists():
108
  report.skipped_modules.append(name)
109
- return None
110
- spec = importlib.util.spec_from_file_location(name, path)
111
- if not spec or not spec.loader:
112
- report.skipped_modules.append(name)
113
- return None
114
- mod = importlib.util.module_from_spec(spec)
115
- sys.modules[name] = mod
116
  try:
 
 
 
 
 
 
 
117
  spec.loader.exec_module(mod) # type: ignore[union-attr]
118
  except Exception as exc:
119
  sys.modules.pop(name, None)
120
- report.skipped_modules.append(f"{name} (import error: {exc})")
121
- return None
122
- return mod
 
 
 
 
 
 
123
 
124
 
125
  # ---------------------------------------------------------------------------
@@ -334,12 +372,27 @@ def run_sync(wiki_dir: Path, verbose: bool = False) -> HealthReport: # noqa: AR
334
  acc = HealthReport() # accumulates sync-phase warnings; merged into final check
335
  log = print
336
 
 
 
 
 
337
  # Step 1 — ensure wiki structure
338
  log("\nStep 1: Ensure wiki structure")
339
  ws = _try_import("wiki_sync", acc)
340
  if ws and hasattr(ws, "ensure_wiki"):
341
- ws.ensure_wiki(str(wiki_dir))
342
- log(" structure OK")
 
 
 
 
 
 
 
 
 
 
 
343
 
344
  # Step 2 — inventory skills
345
  log("\nStep 2: Scan skill directories")
@@ -358,7 +411,8 @@ def run_sync(wiki_dir: Path, verbose: bool = False) -> HealthReport: # noqa: AR
358
  continue
359
  try:
360
  n = len(skill_md.read_text(encoding="utf-8", errors="replace").splitlines())
361
- except Exception:
 
362
  continue
363
  if n > cfg.line_threshold:
364
  out = wiki_dir / "converted" / item.name
@@ -367,9 +421,10 @@ def run_sync(wiki_dir: Path, verbose: bool = False) -> HealthReport: # noqa: AR
367
  bc.convert_skill(str(skill_md), str(out))
368
  converted_count += 1
369
  except Exception as exc:
370
- acc.warnings.append(f" [convert] {item.name}: {exc}")
371
  log(f" {converted_count} converted/refreshed")
372
  else:
 
373
  log(" batch_convert unavailable — skipping")
374
 
375
  # Step 4 — upsert entity pages
@@ -385,25 +440,32 @@ def run_sync(wiki_dir: Path, verbose: bool = False) -> HealthReport: # noqa: AR
385
  if ws.upsert_skill_page(str(wiki_dir), item.name, info):
386
  new_pages.append(item.name)
387
  except Exception as exc:
388
- acc.warnings.append(f" [upsert] {item.name}: {exc}")
389
  log(f" {len(new_pages)} new entity pages")
 
 
 
390
 
391
  # Step 5 — link entity pages to converted pipelines
392
  log("\nStep 5: Link entity pages to converted pipelines")
393
  lc = _try_import("link_conversions", acc)
394
- if lc and hasattr(lc, "link_all"):
395
  try:
396
- lc.link_all(str(wiki_dir))
397
- log(" link_conversions.link_all complete")
 
 
 
398
  except Exception as exc:
399
- acc.warnings.append(f" [link_conversions] {exc}")
400
  else:
 
401
  log(" link_conversions unavailable — skipping")
402
 
403
  # Step 6 — rebuild catalog.md
404
  log("\nStep 6: Rebuild catalogs")
405
  cb = _try_import("catalog_builder", acc)
406
- if cb and hasattr(cb, "build_catalog"):
407
  try:
408
  stats = cb.build_catalog(
409
  wiki_dir=wiki_dir,
@@ -411,11 +473,13 @@ def run_sync(wiki_dir: Path, verbose: bool = False) -> HealthReport: # noqa: AR
411
  agents_dir=cfg.agents_dir,
412
  extra_dirs=cfg.extra_skill_dirs,
413
  )
414
- if hasattr(cb, "update_wiki_index"):
415
- cb.update_wiki_index(wiki_dir, stats)
416
  log(f" catalog.md: {stats.get('total', '?')} items")
417
  except Exception as exc:
418
- acc.warnings.append(f" [catalog_builder] {exc}")
 
 
 
419
  # rebuild versions-catalog.md
420
  vc = _try_import("versions_catalog", acc)
421
  if vc and hasattr(vc, "find_dual_version_skills") and hasattr(vc, "build_versions_catalog"):
@@ -430,7 +494,10 @@ def run_sync(wiki_dir: Path, verbose: bool = False) -> HealthReport: # noqa: AR
430
  else:
431
  log(" versions-catalog.md: no dual-version skills")
432
  except Exception as exc:
433
- acc.warnings.append(f" [versions_catalog] {exc}")
 
 
 
434
 
435
  # Step 7 — rebuild index.md page counts
436
  log("\nStep 7: Rebuild index.md page counts")
@@ -438,7 +505,10 @@ def run_sync(wiki_dir: Path, verbose: bool = False) -> HealthReport: # noqa: AR
438
  try:
439
  ws.update_index(str(wiki_dir), new_pages)
440
  except Exception as exc:
441
- acc.warnings.append(f" [update_index] {exc}")
 
 
 
442
  log(f" {_actual_page_count(wiki_dir)} total pages on disk")
443
 
444
  # Step 8 — lint pass
@@ -451,8 +521,9 @@ def run_sync(wiki_dir: Path, verbose: bool = False) -> HealthReport: # noqa: AR
451
  acc.warnings.append(f" [lint] {issue}")
452
  log(f" lint: {len(issues)} issues")
453
  except Exception as exc:
454
- acc.warnings.append(f" [wiki_lint] {exc}")
455
  else:
 
456
  log(" wiki_lint unavailable — skipping")
457
 
458
  # Step 9 — append log entry
@@ -470,7 +541,10 @@ def run_sync(wiki_dir: Path, verbose: bool = False) -> HealthReport: # noqa: AR
470
  ws.append_log(str(wiki_dir), "orchestrator-sync", "full-sync", details)
471
  log(" log.md updated")
472
  except Exception as exc:
473
- acc.warnings.append(f" [append_log] {exc}")
 
 
 
474
 
475
  # Step 10 — final health score
476
  log("\nStep 10: Compute final health score")
@@ -479,6 +553,9 @@ def run_sync(wiki_dir: Path, verbose: bool = False) -> HealthReport: # noqa: AR
479
  if m not in final.skipped_modules:
480
  final.skipped_modules.append(m)
481
  final.warnings = [w for w in acc.warnings if w not in final.warnings] + final.warnings
 
 
 
482
  return final
483
 
484
 
@@ -508,8 +585,12 @@ def _resolve_add_name(skill_path_or_name: str) -> str:
508
  is_path_like = "/" in raw or "\\" in raw or raw.endswith(".md") or raw.endswith(".py")
509
 
510
  if is_path_like:
511
- resolved = Path(raw).resolve()
512
- skills_dir_resolved = cfg.skills_dir.resolve()
 
 
 
 
513
  try:
514
  resolved.relative_to(skills_dir_resolved)
515
  except ValueError:
@@ -520,7 +601,7 @@ def _resolve_add_name(skill_path_or_name: str) -> str:
520
  file=sys.stderr,
521
  )
522
  sys.exit(1)
523
- raw_stem = resolved.stem
524
  else:
525
  raw_stem = raw
526
 
@@ -531,16 +612,65 @@ def _resolve_add_name(skill_path_or_name: str) -> str:
531
  sys.exit(1)
532
 
533
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
534
  def run_add(wiki_dir: Path, skill_path_or_name: str) -> None:
535
- """Delegate to skill_add, or fall back to wiki_sync upsert."""
536
- skill_name = _resolve_add_name(skill_path_or_name)
 
 
 
537
 
538
  r = HealthReport()
539
- sa = _try_import("skill_add", r)
540
- if sa and hasattr(sa, "add_skill"):
 
 
 
 
 
 
 
 
541
  try:
542
  sa.add_skill(
543
- source_path=Path(skill_path_or_name),
544
  name=skill_name,
545
  wiki_path=wiki_dir,
546
  skills_dir=cfg.skills_dir,
@@ -549,16 +679,17 @@ def run_add(wiki_dir: Path, skill_path_or_name: str) -> None:
549
  return
550
  except Exception as exc:
551
  print(f"skill_add.add_skill raised: {exc}", file=sys.stderr)
 
552
 
553
  ws = _try_import("wiki_sync", r)
554
  if not (ws and hasattr(ws, "upsert_skill_page")):
555
  print("Neither skill_add nor wiki_sync available — cannot add skill.", file=sys.stderr)
556
  sys.exit(1)
557
 
558
- info = {"path": skill_path_or_name, "reason": "manually added via orchestrator"}
559
  is_new = ws.upsert_skill_page(str(wiki_dir), skill_name, info)
560
  ws.update_index(str(wiki_dir), [skill_name] if is_new else [])
561
- ws.append_log(str(wiki_dir), "add-skill", skill_name, [f"Path: {skill_path_or_name}"])
562
  print(f"Entity page {'created' if is_new else 'updated'}: {skill_name}")
563
 
564
 
@@ -649,8 +780,8 @@ def main() -> None:
649
  sys.exit(0 if report.score >= 70 else 1)
650
  elif args.sync:
651
  report = run_sync(wiki_dir, verbose=args.verbose)
652
- print("\n" + report.render(), file=utf8_out)
653
- sys.exit(0 if report.score >= 70 else 1)
654
 
655
 
656
  if __name__ == "__main__":
 
67
  index_count_wrong: bool = False
68
  skipped_modules: list[str] = field(default_factory=list)
69
  warnings: list[str] = field(default_factory=list)
70
+ sync_failures: list[str] = field(default_factory=list)
71
 
72
  def deduct(self, points: int, reason: str) -> None:
73
  self.score = max(0, self.score - points)
74
  self.warnings.append(f"[-{points}] {reason}")
75
 
76
  def render(self) -> str:
77
+ display_score = min(self.score, 99) if self.sync_failures else self.score
78
+ out = [f"Health Score: {display_score}/100"]
79
+ if self.sync_failures:
80
+ count = len(self.sync_failures)
81
+ out.append(f"Sync Status: FAILED ({count} failure{'s' if count != 1 else ''})")
82
+ out.append("")
83
  if self.skipped_modules:
84
  out.append("Skipped modules (not yet installed):")
85
  out.extend(f" - {m}" for m in self.skipped_modules)
 
94
  # ---------------------------------------------------------------------------
95
 
96
 
97
+ @dataclass(frozen=True)
98
+ class ModuleLoadResult:
99
+ """Outcome of loading an optional orchestrator module."""
100
+
101
+ module: Any | None
102
+ error: str | None = None
103
+
104
+ @property
105
+ def absent(self) -> bool:
106
+ return self.module is None and self.error is None
107
+
108
+ @property
109
+ def failed(self) -> bool:
110
+ return self.error is not None
111
+
112
+
113
+ def _load_module(name: str, report: HealthReport) -> ModuleLoadResult:
114
+ """Load a module and distinguish absence from a failed import.
115
 
116
  Registers in sys.modules before exec so @dataclass decorators that inspect
117
  cls.__module__ resolve correctly.
118
  """
119
+ if name == "wiki_sync":
120
+ try:
121
+ from ctx.core.wiki import wiki_sync
122
+ except Exception as exc:
123
+ error = f"import error: {exc}"
124
+ report.skipped_modules.append(f"{name} ({error})")
125
+ return ModuleLoadResult(None, error)
126
+ return ModuleLoadResult(wiki_sync)
127
+
128
  if name == "wiki_lint":
129
 
130
  class _PackageWikiLint:
 
132
  def run_lint(wiki_dir: Path) -> list[str]:
133
  return _run_package_lint(Path(wiki_dir))
134
 
135
+ return ModuleLoadResult(_PackageWikiLint)
136
 
137
  path = SCRIPT_DIR / f"{name}.py"
138
  if not path.exists():
139
  report.skipped_modules.append(name)
140
+ return ModuleLoadResult(None)
 
 
 
 
 
 
141
  try:
142
+ spec = importlib.util.spec_from_file_location(name, path)
143
+ if not spec or not spec.loader:
144
+ error = "loader unavailable"
145
+ report.skipped_modules.append(f"{name} ({error})")
146
+ return ModuleLoadResult(None, error)
147
+ mod = importlib.util.module_from_spec(spec)
148
+ sys.modules[name] = mod
149
  spec.loader.exec_module(mod) # type: ignore[union-attr]
150
  except Exception as exc:
151
  sys.modules.pop(name, None)
152
+ error = f"import error: {exc}"
153
+ report.skipped_modules.append(f"{name} ({error})")
154
+ return ModuleLoadResult(None, error)
155
+ return ModuleLoadResult(mod)
156
+
157
+
158
+ def _try_import(name: str, report: HealthReport) -> Any | None:
159
+ """Compatibility wrapper returning only the loaded module, if any."""
160
+ return _load_module(name, report).module
161
 
162
 
163
  # ---------------------------------------------------------------------------
 
372
  acc = HealthReport() # accumulates sync-phase warnings; merged into final check
373
  log = print
374
 
375
+ def record_failure(message: str) -> None:
376
+ acc.sync_failures.append(message)
377
+ acc.warnings.append(f" {message}")
378
+
379
  # Step 1 — ensure wiki structure
380
  log("\nStep 1: Ensure wiki structure")
381
  ws = _try_import("wiki_sync", acc)
382
  if ws and hasattr(ws, "ensure_wiki"):
383
+ try:
384
+ ws.ensure_wiki(str(wiki_dir))
385
+ log(" structure OK")
386
+ except Exception as exc:
387
+ record_failure(f"[wiki_sync.ensure_wiki] {exc}")
388
+ log(" wiki_sync.ensure_wiki failed - aborting")
389
+ acc.score = min(acc.score, 99)
390
+ return acc
391
+ else:
392
+ record_failure("[wiki_sync.ensure_wiki] unavailable; step skipped")
393
+ log(" wiki_sync.ensure_wiki unavailable - aborting")
394
+ acc.score = min(acc.score, 99)
395
+ return acc
396
 
397
  # Step 2 — inventory skills
398
  log("\nStep 2: Scan skill directories")
 
411
  continue
412
  try:
413
  n = len(skill_md.read_text(encoding="utf-8", errors="replace").splitlines())
414
+ except Exception as exc:
415
+ record_failure(f"[scan] {skill_md}: {exc}")
416
  continue
417
  if n > cfg.line_threshold:
418
  out = wiki_dir / "converted" / item.name
 
421
  bc.convert_skill(str(skill_md), str(out))
422
  converted_count += 1
423
  except Exception as exc:
424
+ record_failure(f"[convert] {item.name}: {exc}")
425
  log(f" {converted_count} converted/refreshed")
426
  else:
427
+ record_failure("[batch_convert.convert_skill] unavailable; step skipped")
428
  log(" batch_convert unavailable — skipping")
429
 
430
  # Step 4 — upsert entity pages
 
440
  if ws.upsert_skill_page(str(wiki_dir), item.name, info):
441
  new_pages.append(item.name)
442
  except Exception as exc:
443
+ record_failure(f"[upsert] {item.name}: {exc}")
444
  log(f" {len(new_pages)} new entity pages")
445
+ else:
446
+ record_failure("[wiki_sync.upsert_skill_page] unavailable; step skipped")
447
+ log(" wiki_sync.upsert_skill_page unavailable - skipping")
448
 
449
  # Step 5 — link entity pages to converted pipelines
450
  log("\nStep 5: Link entity pages to converted pipelines")
451
  lc = _try_import("link_conversions", acc)
452
+ if lc and hasattr(lc, "run"):
453
  try:
454
+ result = lc.run(wiki_dir, cfg.skills_dir)
455
+ errors = list(getattr(result, "errors", []))
456
+ for error in errors:
457
+ record_failure(f"[link_conversions] {error}")
458
+ log(f" link_conversions.run complete ({len(errors)} errors)")
459
  except Exception as exc:
460
+ record_failure(f"[link_conversions] {exc}")
461
  else:
462
+ record_failure("[link_conversions.run] unavailable; step skipped")
463
  log(" link_conversions unavailable — skipping")
464
 
465
  # Step 6 — rebuild catalog.md
466
  log("\nStep 6: Rebuild catalogs")
467
  cb = _try_import("catalog_builder", acc)
468
+ if cb and hasattr(cb, "build_catalog") and hasattr(cb, "update_wiki_index"):
469
  try:
470
  stats = cb.build_catalog(
471
  wiki_dir=wiki_dir,
 
473
  agents_dir=cfg.agents_dir,
474
  extra_dirs=cfg.extra_skill_dirs,
475
  )
476
+ cb.update_wiki_index(wiki_dir, stats)
 
477
  log(f" catalog.md: {stats.get('total', '?')} items")
478
  except Exception as exc:
479
+ record_failure(f"[catalog_builder] {exc}")
480
+ else:
481
+ record_failure("[catalog_builder] required API unavailable; step skipped")
482
+ log(" catalog_builder unavailable - skipping")
483
  # rebuild versions-catalog.md
484
  vc = _try_import("versions_catalog", acc)
485
  if vc and hasattr(vc, "find_dual_version_skills") and hasattr(vc, "build_versions_catalog"):
 
494
  else:
495
  log(" versions-catalog.md: no dual-version skills")
496
  except Exception as exc:
497
+ record_failure(f"[versions_catalog] {exc}")
498
+ else:
499
+ record_failure("[versions_catalog] required API unavailable; step skipped")
500
+ log(" versions_catalog unavailable - skipping")
501
 
502
  # Step 7 — rebuild index.md page counts
503
  log("\nStep 7: Rebuild index.md page counts")
 
505
  try:
506
  ws.update_index(str(wiki_dir), new_pages)
507
  except Exception as exc:
508
+ record_failure(f"[update_index] {exc}")
509
+ else:
510
+ record_failure("[wiki_sync.update_index] unavailable; step skipped")
511
+ log(" wiki_sync.update_index unavailable - skipping")
512
  log(f" {_actual_page_count(wiki_dir)} total pages on disk")
513
 
514
  # Step 8 — lint pass
 
521
  acc.warnings.append(f" [lint] {issue}")
522
  log(f" lint: {len(issues)} issues")
523
  except Exception as exc:
524
+ record_failure(f"[wiki_lint] {exc}")
525
  else:
526
+ record_failure("[wiki_lint.run_lint] unavailable; step skipped")
527
  log(" wiki_lint unavailable — skipping")
528
 
529
  # Step 9 — append log entry
 
541
  ws.append_log(str(wiki_dir), "orchestrator-sync", "full-sync", details)
542
  log(" log.md updated")
543
  except Exception as exc:
544
+ record_failure(f"[append_log] {exc}")
545
+ else:
546
+ record_failure("[wiki_sync.append_log] unavailable; step skipped")
547
+ log(" wiki_sync.append_log unavailable - skipping")
548
 
549
  # Step 10 — final health score
550
  log("\nStep 10: Compute final health score")
 
553
  if m not in final.skipped_modules:
554
  final.skipped_modules.append(m)
555
  final.warnings = [w for w in acc.warnings if w not in final.warnings] + final.warnings
556
+ final.sync_failures = list(acc.sync_failures)
557
+ if final.sync_failures:
558
+ final.score = min(final.score, 99)
559
  return final
560
 
561
 
 
585
  is_path_like = "/" in raw or "\\" in raw or raw.endswith(".md") or raw.endswith(".py")
586
 
587
  if is_path_like:
588
+ try:
589
+ resolved = Path(raw).expanduser().resolve()
590
+ skills_dir_resolved = Path(cfg.skills_dir).expanduser().resolve()
591
+ except (OSError, RuntimeError) as exc:
592
+ print(f"Error: could not resolve --add path '{raw}': {exc}", file=sys.stderr)
593
+ sys.exit(1)
594
  try:
595
  resolved.relative_to(skills_dir_resolved)
596
  except ValueError:
 
601
  file=sys.stderr,
602
  )
603
  sys.exit(1)
604
+ raw_stem = resolved.parent.name if resolved.name == "SKILL.md" else resolved.stem
605
  else:
606
  raw_stem = raw
607
 
 
612
  sys.exit(1)
613
 
614
 
615
+ def _resolve_add_source(skill_path_or_name: str) -> tuple[Path, str]:
616
+ raw = skill_path_or_name
617
+ skill_name = _resolve_add_name(raw)
618
+ is_path_like = "/" in raw or "\\" in raw or raw.endswith(".md") or raw.endswith(".py")
619
+
620
+ if is_path_like:
621
+ requested = Path(raw).expanduser()
622
+ if requested.is_dir():
623
+ source_path = requested / "SKILL.md"
624
+ elif requested.name == "SKILL.md":
625
+ source_path = requested
626
+ else:
627
+ print(
628
+ f"Error: --add path '{raw}' must be an installed skill directory or SKILL.md.",
629
+ file=sys.stderr,
630
+ )
631
+ sys.exit(1)
632
+ else:
633
+ source_path = Path(cfg.skills_dir).expanduser() / skill_name / "SKILL.md"
634
+
635
+ try:
636
+ skills_dir_resolved = Path(cfg.skills_dir).expanduser().resolve()
637
+ source_resolved = source_path.resolve(strict=True)
638
+ except (OSError, RuntimeError) as exc:
639
+ print(f"Error: installed SKILL.md not found for '{raw}': {exc}", file=sys.stderr)
640
+ sys.exit(1)
641
+
642
+ expected_source = skills_dir_resolved / skill_name / "SKILL.md"
643
+ if source_resolved != expected_source or not source_resolved.is_file():
644
+ print(
645
+ f"Error: --add source '{raw}' must resolve to the installed file '{expected_source}'.",
646
+ file=sys.stderr,
647
+ )
648
+ sys.exit(1)
649
+
650
+ return source_resolved, skill_name
651
+
652
+
653
  def run_add(wiki_dir: Path, skill_path_or_name: str) -> None:
654
+ """Delegate to skill_add, falling back only when that module is absent.
655
+
656
+ Import, API, and call failures fail closed instead of invoking wiki_sync.
657
+ """
658
+ source_path, skill_name = _resolve_add_source(skill_path_or_name)
659
 
660
  r = HealthReport()
661
+ skill_add_load = _load_module("skill_add", r)
662
+ if skill_add_load.failed:
663
+ print(f"skill_add load failed: {skill_add_load.error}", file=sys.stderr)
664
+ sys.exit(1)
665
+
666
+ sa = skill_add_load.module
667
+ if sa is not None:
668
+ if not hasattr(sa, "add_skill"):
669
+ print("skill_add.add_skill unavailable; refusing legacy fallback.", file=sys.stderr)
670
+ sys.exit(1)
671
  try:
672
  sa.add_skill(
673
+ source_path=source_path,
674
  name=skill_name,
675
  wiki_path=wiki_dir,
676
  skills_dir=cfg.skills_dir,
 
679
  return
680
  except Exception as exc:
681
  print(f"skill_add.add_skill raised: {exc}", file=sys.stderr)
682
+ sys.exit(1)
683
 
684
  ws = _try_import("wiki_sync", r)
685
  if not (ws and hasattr(ws, "upsert_skill_page")):
686
  print("Neither skill_add nor wiki_sync available — cannot add skill.", file=sys.stderr)
687
  sys.exit(1)
688
 
689
+ info = {"path": str(source_path), "reason": "manually added via orchestrator"}
690
  is_new = ws.upsert_skill_page(str(wiki_dir), skill_name, info)
691
  ws.update_index(str(wiki_dir), [skill_name] if is_new else [])
692
+ ws.append_log(str(wiki_dir), "add-skill", skill_name, [f"Path: {source_path}"])
693
  print(f"Entity page {'created' if is_new else 'updated'}: {skill_name}")
694
 
695
 
 
780
  sys.exit(0 if report.score >= 70 else 1)
781
  elif args.sync:
782
  report = run_sync(wiki_dir, verbose=args.verbose)
783
+ print("\n" + report.render(), file=utf8_out, flush=True)
784
+ sys.exit(0 if report.score >= 70 and not report.sync_failures else 1)
785
 
786
 
787
  if __name__ == "__main__":
src/wiki_visualize.py CHANGED
@@ -2,7 +2,7 @@
2
  """
3
  wiki_visualize.py -- Interactive knowledge graph visualization.
4
 
5
- The full graph (2,167 nodes, 593K edges) is too large to render at once.
6
  Users MUST specify boundaries to get a feasible visualization.
7
 
8
  Usage:
@@ -39,11 +39,11 @@ from typing import Any
39
  def _safe_json_for_script(obj) -> str:
40
  """Serialize ``obj`` so it can be safely embedded inside an HTML ``<script>``.
41
 
42
- ``json.dumps`` does not escape ``</``, so a payload containing ``</script>``
43
- would terminate the script block. Replace ``</`` with ``<\\/`` (a
44
- JavaScript-legal and JSON-legal representation of the same string).
45
  """
46
- return json.dumps(obj).replace("</", "<\\/")
47
 
48
 
49
  try:
@@ -64,6 +64,36 @@ def _load_plotly_graph_objects() -> Any:
64
  return go
65
 
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  WIKI_DIR = Path(os.path.expanduser("~/.claude/skill-wiki"))
68
  GRAPH_PATH = WIKI_DIR / "graphify-out" / "graph.json"
69
  COMMUNITIES_PATH = WIKI_DIR / "graphify-out" / "communities.json"
@@ -132,10 +162,11 @@ def extract_subgraph(
132
  top_n: int | None = None,
133
  ) -> nx.Graph:
134
  """Extract a viewable subgraph based on user boundaries."""
 
 
135
  # Start with candidate nodes
136
  if seeds:
137
  # Find seed nodes by label match
138
- seed_ids: set[str] = set()
139
  for seed in seeds:
140
  for nid, data in G.nodes(data=True):
141
  if data.get("label", "") == seed or nid.endswith(f":{seed}"):
@@ -172,8 +203,8 @@ def extract_subgraph(
172
  nodes = set(G.nodes())
173
 
174
  # Apply top-N filter by degree within the candidate set
175
- if top_n and len(nodes) > top_n:
176
- ranked = sorted(nodes, key=lambda n: G.degree(n), reverse=True)
177
  nodes = set(ranked[:top_n])
178
 
179
  # Build subgraph
@@ -184,9 +215,10 @@ def extract_subgraph(
184
  weak_edges = [(u, v) for u, v, d in sub.edges(data=True) if d.get("weight", 1) < min_weight]
185
  sub.remove_edges_from(weak_edges)
186
 
187
- # Remove isolated nodes after edge filtering
188
- isolated = [n for n in sub.nodes() if sub.degree(n) == 0]
189
- sub.remove_nodes_from(isolated)
 
190
 
191
  return sub
192
 
@@ -319,9 +351,9 @@ def build_html_with_filters(
319
  {"".join(f'<label><input type="checkbox" class="type-filter" data-type="{html.escape(node_type, quote=True)}" checked onchange="applyFilters()"> {html.escape(node_type)}</label>' for node_type in TYPE_COLORS)}
320
  </div>
321
 
322
- <h2>Min Connections: <span id="deg-val">1</span></h2>
323
  <div class="filter-group">
324
- <input type="range" id="min-degree" min="1" max="50" value="1" oninput="document.getElementById('deg-val').textContent=this.value; applyFilters()">
325
  </div>
326
 
327
  <h2>Tags</h2>
@@ -457,7 +489,13 @@ applyFilters();
457
  </script></body></html>"""
458
 
459
 
460
- def build_figure(G: nx.Graph, pos: dict, title: str = "Knowledge Graph") -> Any:
 
 
 
 
 
 
461
  """Build an interactive plotly figure from the subgraph."""
462
  go = _load_plotly_graph_objects()
463
  if G.number_of_nodes() == 0:
@@ -466,7 +504,7 @@ def build_figure(G: nx.Graph, pos: dict, title: str = "Knowledge Graph") -> Any:
466
  return fig
467
 
468
  # Assign community colors
469
- communities = load_communities()
470
  node_community: dict[str, int] = {}
471
  for cid, comm_data in communities.get("communities", {}).items():
472
  for member in comm_data.get("members", []):
@@ -574,11 +612,11 @@ def get_available_tags(G: nx.Graph) -> list[tuple[str, int]]:
574
  return sorted(tag_counts.items(), key=lambda x: -x[1])
575
 
576
 
577
- def interactive_menu(G: nx.Graph) -> None:
578
  """Interactive filtering menu when no CLI args provided."""
579
  skills = sum(1 for _, d in G.nodes(data=True) if d.get("type") == "skill")
580
  agents = sum(1 for _, d in G.nodes(data=True) if d.get("type") == "agent")
581
- communities = load_communities()
582
  num_communities = len(communities.get("communities", {}))
583
  tags = get_available_tags(G)
584
 
@@ -679,6 +717,7 @@ The full graph is too large to render. Choose a view:
679
  hops=hops,
680
  min_weight=min_weight,
681
  community_id=community_id,
 
682
  tag_filter=tag_filter,
683
  top_n=top_n,
684
  )
@@ -704,7 +743,11 @@ The full graph is too large to render. Choose a view:
704
  title = f"Knowledge Graph ({sub.number_of_nodes()} nodes) - {' | '.join(parts)}"
705
 
706
  pos = compute_layout(sub)
707
- fig = build_figure(sub, pos, title=title)
 
 
 
 
708
 
709
  if output:
710
  fig.write_html(output, include_plotlyjs=True)
@@ -718,16 +761,24 @@ def main() -> None:
718
  description="Interactive knowledge graph visualization",
719
  epilog="The full graph is too large to render. Use boundaries to focus on a region.",
720
  )
721
- parser.add_argument("--seed", help="Comma-separated skill/agent names to center on")
 
 
 
 
722
  parser.add_argument(
723
- "--hops", type=int, default=1, help="Neighborhood depth from seeds (default 1)"
 
 
 
724
  )
 
 
 
 
725
  parser.add_argument(
726
- "--min-weight", type=float, default=0.0, help="Minimum edge weight to include (default 0)"
727
  )
728
- parser.add_argument("--community", type=int, help="Show a specific community by ID")
729
- parser.add_argument("--tag", help="Show only nodes with this tag")
730
- parser.add_argument("--top", type=int, help="Show only the top-N most connected nodes")
731
  parser.add_argument("--output", help="Save to HTML file instead of opening browser")
732
  parser.add_argument("--stats", action="store_true", help="Print graph stats and exit")
733
  parser.add_argument("--graph-json", type=Path, help="Load this graph.json instead of ~/.claude")
@@ -754,7 +805,7 @@ def main() -> None:
754
  return
755
 
756
  if not (args.seed or args.community is not None or args.tag or args.top):
757
- interactive_menu(G)
758
  return
759
 
760
  # Parse seeds
@@ -774,6 +825,10 @@ def main() -> None:
774
 
775
  print(f"Subgraph: {sub.number_of_nodes()} nodes, {sub.number_of_edges()} edges")
776
 
 
 
 
 
777
  if sub.number_of_nodes() > 500:
778
  print(
779
  f"Warning: {sub.number_of_nodes()} nodes is large. Consider tighter boundaries.",
 
2
  """
3
  wiki_visualize.py -- Interactive knowledge graph visualization.
4
 
5
+ The full graph is too large to render at once.
6
  Users MUST specify boundaries to get a feasible visualization.
7
 
8
  Usage:
 
39
  def _safe_json_for_script(obj) -> str:
40
  """Serialize ``obj`` so it can be safely embedded inside an HTML ``<script>``.
41
 
42
+ Escape every less-than sign as a JSON Unicode escape so untrusted values
43
+ cannot alter the HTML parser's script-data state. JSON and JavaScript decode
44
+ the escape back to the original character.
45
  """
46
+ return json.dumps(obj).replace("<", "\\u003c")
47
 
48
 
49
  try:
 
64
  return go
65
 
66
 
67
+ def _positive_int(raw: str) -> int:
68
+ try:
69
+ value = int(raw)
70
+ except ValueError as exc:
71
+ raise argparse.ArgumentTypeError("must be an integer") from exc
72
+ if value < 1:
73
+ raise argparse.ArgumentTypeError("must be >= 1")
74
+ return value
75
+
76
+
77
+ def _nonnegative_int(raw: str) -> int:
78
+ try:
79
+ value = int(raw)
80
+ except ValueError as exc:
81
+ raise argparse.ArgumentTypeError("must be an integer") from exc
82
+ if value < 0:
83
+ raise argparse.ArgumentTypeError("must be >= 0")
84
+ return value
85
+
86
+
87
+ def _nonnegative_float(raw: str) -> float:
88
+ try:
89
+ value = float(raw)
90
+ except ValueError as exc:
91
+ raise argparse.ArgumentTypeError("must be a number") from exc
92
+ if not math.isfinite(value) or value < 0:
93
+ raise argparse.ArgumentTypeError("must be a finite number >= 0")
94
+ return value
95
+
96
+
97
  WIKI_DIR = Path(os.path.expanduser("~/.claude/skill-wiki"))
98
  GRAPH_PATH = WIKI_DIR / "graphify-out" / "graph.json"
99
  COMMUNITIES_PATH = WIKI_DIR / "graphify-out" / "communities.json"
 
162
  top_n: int | None = None,
163
  ) -> nx.Graph:
164
  """Extract a viewable subgraph based on user boundaries."""
165
+ seed_ids: set[str] = set()
166
+
167
  # Start with candidate nodes
168
  if seeds:
169
  # Find seed nodes by label match
 
170
  for seed in seeds:
171
  for nid, data in G.nodes(data=True):
172
  if data.get("label", "") == seed or nid.endswith(f":{seed}"):
 
203
  nodes = set(G.nodes())
204
 
205
  # Apply top-N filter by degree within the candidate set
206
+ if top_n is not None and len(nodes) > top_n:
207
+ ranked = sorted(nodes, key=lambda n: (-G.degree(n), str(n)))
208
  nodes = set(ranked[:top_n])
209
 
210
  # Build subgraph
 
215
  weak_edges = [(u, v) for u, v, d in sub.edges(data=True) if d.get("weight", 1) < min_weight]
216
  sub.remove_edges_from(weak_edges)
217
 
218
+ # Explicit seeds and a top-1 view are intentional singleton selections.
219
+ if top_n != 1:
220
+ isolated = [n for n in sub.nodes() if sub.degree(n) == 0 and n not in seed_ids]
221
+ sub.remove_nodes_from(isolated)
222
 
223
  return sub
224
 
 
351
  {"".join(f'<label><input type="checkbox" class="type-filter" data-type="{html.escape(node_type, quote=True)}" checked onchange="applyFilters()"> {html.escape(node_type)}</label>' for node_type in TYPE_COLORS)}
352
  </div>
353
 
354
+ <h2>Min Connections: <span id="deg-val">0</span></h2>
355
  <div class="filter-group">
356
+ <input type="range" id="min-degree" min="0" max="50" value="0" oninput="document.getElementById('deg-val').textContent=this.value; applyFilters()">
357
  </div>
358
 
359
  <h2>Tags</h2>
 
489
  </script></body></html>"""
490
 
491
 
492
+ def build_figure(
493
+ G: nx.Graph,
494
+ pos: dict,
495
+ title: str = "Knowledge Graph",
496
+ *,
497
+ communities: dict | None = None,
498
+ ) -> Any:
499
  """Build an interactive plotly figure from the subgraph."""
500
  go = _load_plotly_graph_objects()
501
  if G.number_of_nodes() == 0:
 
504
  return fig
505
 
506
  # Assign community colors
507
+ communities = communities if communities is not None else load_communities()
508
  node_community: dict[str, int] = {}
509
  for cid, comm_data in communities.get("communities", {}).items():
510
  for member in comm_data.get("members", []):
 
612
  return sorted(tag_counts.items(), key=lambda x: -x[1])
613
 
614
 
615
+ def interactive_menu(G: nx.Graph, communities: dict | None = None) -> None:
616
  """Interactive filtering menu when no CLI args provided."""
617
  skills = sum(1 for _, d in G.nodes(data=True) if d.get("type") == "skill")
618
  agents = sum(1 for _, d in G.nodes(data=True) if d.get("type") == "agent")
619
+ communities = communities if communities is not None else load_communities()
620
  num_communities = len(communities.get("communities", {}))
621
  tags = get_available_tags(G)
622
 
 
717
  hops=hops,
718
  min_weight=min_weight,
719
  community_id=community_id,
720
+ communities=communities,
721
  tag_filter=tag_filter,
722
  top_n=top_n,
723
  )
 
743
  title = f"Knowledge Graph ({sub.number_of_nodes()} nodes) - {' | '.join(parts)}"
744
 
745
  pos = compute_layout(sub)
746
+ try:
747
+ fig = build_figure(sub, pos, title=title, communities=communities)
748
+ except RuntimeError as exc:
749
+ print(f"Error: {exc}", file=sys.stderr)
750
+ raise SystemExit(1) from None
751
 
752
  if output:
753
  fig.write_html(output, include_plotlyjs=True)
 
761
  description="Interactive knowledge graph visualization",
762
  epilog="The full graph is too large to render. Use boundaries to focus on a region.",
763
  )
764
+ primary_filter = parser.add_mutually_exclusive_group()
765
+ primary_filter.add_argument("--seed", help="Comma-separated skill/agent names to center on")
766
+ parser.add_argument(
767
+ "--hops", type=_nonnegative_int, default=1, help="Neighborhood depth from seeds (default 1)"
768
+ )
769
  parser.add_argument(
770
+ "--min-weight",
771
+ type=_nonnegative_float,
772
+ default=0.0,
773
+ help="Minimum edge weight to include (default 0)",
774
  )
775
+ primary_filter.add_argument(
776
+ "--community", type=_nonnegative_int, help="Show a specific community by ID"
777
+ )
778
+ primary_filter.add_argument("--tag", help="Show only nodes with this tag")
779
  parser.add_argument(
780
+ "--top", type=_positive_int, help="Show only the top-N most connected nodes"
781
  )
 
 
 
782
  parser.add_argument("--output", help="Save to HTML file instead of opening browser")
783
  parser.add_argument("--stats", action="store_true", help="Print graph stats and exit")
784
  parser.add_argument("--graph-json", type=Path, help="Load this graph.json instead of ~/.claude")
 
805
  return
806
 
807
  if not (args.seed or args.community is not None or args.tag or args.top):
808
+ interactive_menu(G, communities=communities)
809
  return
810
 
811
  # Parse seeds
 
825
 
826
  print(f"Subgraph: {sub.number_of_nodes()} nodes, {sub.number_of_edges()} edges")
827
 
828
+ if sub.number_of_nodes() == 0:
829
+ print("Error: no nodes matched the requested filters", file=sys.stderr)
830
+ raise SystemExit(1)
831
+
832
  if sub.number_of_nodes() > 500:
833
  print(
834
  f"Warning: {sub.number_of_nodes()} nodes is large. Consider tighter boundaries.",