Stevesolun commited on
Commit
fdb72a5
·
verified ·
1 Parent(s): 7d77f3a

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. scripts/ci_classifier.py +7 -3
  2. scripts/ci_preflight.py +13 -13
  3. scripts/ci_required.py +10 -1
  4. scripts/graph_artifact_guard.py +21 -4
  5. scripts/overlay_wiki_entities.py +540 -524
  6. src/__init__.py +1 -1
  7. src/agent_add.py +162 -131
  8. src/backup_mirror.py +4 -0
  9. src/ctx/__init__.py +1 -1
  10. src/ctx/adapters/claude_code/hooks/context_monitor.py +1 -1
  11. src/ctx/adapters/claude_code/inject_hooks.py +51 -21
  12. src/ctx/adapters/claude_code/install/install_utils.py +95 -76
  13. src/ctx/adapters/claude_code/install/mcp_install.py +88 -10
  14. src/ctx/adapters/claude_code/install/skill_install.py +21 -18
  15. src/ctx/adapters/claude_code/install/skill_unload.py +4 -3
  16. src/ctx/adapters/claude_code/skill_health.py +11 -12
  17. src/ctx/adapters/claude_code/skill_loader.py +6 -6
  18. src/ctx/adapters/generic/ctx_core_tools.py +26 -10
  19. src/ctx/core/graph/entity_overlays.py +64 -4
  20. src/ctx/core/graph/incremental_attach.py +70 -10
  21. src/ctx/core/graph/resolve_graph.py +51 -6
  22. src/ctx/core/graph/semantic_edges.py +67 -23
  23. src/ctx/core/resolve/recommendations.py +13 -5
  24. src/ctx/core/wiki/wiki_queue.py +1 -0
  25. src/ctx/core/wiki/wiki_queue_worker.py +7 -1
  26. src/ctx_init.py +41 -9
  27. src/ctx_monitor.py +551 -88
  28. src/harness_install.py +19 -5
  29. src/import_skills_sh_catalog.py +83 -8
  30. src/kpi_dashboard.py +162 -32
  31. src/mcp_add.py +55 -7
  32. src/skill_add.py +206 -152
  33. src/tests/test_agent_add.py +217 -162
  34. src/tests/test_backup_mirror.py +21 -0
  35. src/tests/test_ci_classifier.py +46 -0
  36. src/tests/test_config.py +19 -0
  37. src/tests/test_ctx_init.py +81 -0
  38. src/tests/test_ctx_monitor.py +417 -9
  39. src/tests/test_graph_artifact_guard.py +59 -1
  40. src/tests/test_harness_install.py +28 -0
  41. src/tests/test_harness_recommendations.py +1 -0
  42. src/tests/test_import_skills_sh_catalog.py +32 -3
  43. src/tests/test_incremental_attach_calibration.py +40 -2
  44. src/tests/test_inject_hooks_security.py +49 -26
  45. src/tests/test_kpi_dashboard.py +60 -0
  46. src/tests/test_mcp_add.py +2 -0
  47. src/tests/test_mcp_install.py +166 -1
  48. src/tests/test_overlay_wiki_entities.py +172 -119
  49. src/update_repo_stats.py +253 -14
  50. src/validate_graph_artifacts.py +295 -2
scripts/ci_classifier.py CHANGED
@@ -86,6 +86,12 @@ def _normalize_path(path: str) -> str:
86
  return path.strip().lstrip("\ufeff").replace("\\", "/")
87
 
88
 
 
 
 
 
 
 
89
  def classify_paths(paths: Iterable[str]) -> dict[str, bool]:
90
  files = [
91
  normalized
@@ -94,9 +100,7 @@ def classify_paths(paths: Iterable[str]) -> dict[str, bool]:
94
  ]
95
  ci_changed = any(_matches(path, (".github/workflows/**",)) for path in files)
96
  docs_changed = any(_matches(path, DOCS_PATTERNS) for path in files)
97
- graph_artifact_changed = any(
98
- _matches(path, GRAPH_ARTIFACT_PATTERNS) for path in files
99
- )
100
  graph_only = bool(files) and all(_matches(path, ("graph/**",)) for path in files)
101
  return {
102
  "browser_changed": ci_changed
 
86
  return path.strip().lstrip("\ufeff").replace("\\", "/")
87
 
88
 
89
+ def _is_graph_artifact_path(path: str) -> bool:
90
+ if _matches(path, GRAPH_ARTIFACT_PATTERNS):
91
+ return True
92
+ return _matches(path, ("graph/**",)) and path != "graph/README.md"
93
+
94
+
95
  def classify_paths(paths: Iterable[str]) -> dict[str, bool]:
96
  files = [
97
  normalized
 
100
  ]
101
  ci_changed = any(_matches(path, (".github/workflows/**",)) for path in files)
102
  docs_changed = any(_matches(path, DOCS_PATTERNS) for path in files)
103
+ graph_artifact_changed = any(_is_graph_artifact_path(path) for path in files)
 
 
104
  graph_only = bool(files) and all(_matches(path, ("graph/**",)) for path in files)
105
  return {
106
  "browser_changed": ci_changed
scripts/ci_preflight.py CHANGED
@@ -36,28 +36,28 @@ GRAPH_VALIDATE_ARGS = (
36
  "89000",
37
  "--min-semantic-edges",
38
  "1000000",
39
- "--expected-nodes",
40
- "102925",
41
- "--expected-edges",
42
- "2913930",
43
  "--expected-semantic-edges",
44
- "1683163",
45
- "--expected-harness-nodes",
46
- "207",
47
  "--expected-skills-sh-nodes",
48
  "89471",
49
  "--expected-skills-sh-catalog-entries",
50
  "89465",
51
  "--expected-skills-sh-converted",
52
  "89465",
53
- "--expected-skill-pages",
54
- "91463",
55
  "--expected-agent-pages",
56
  "467",
57
- "--expected-mcp-pages",
58
- "10788",
59
- "--expected-harness-pages",
60
- "207",
61
  "--line-threshold",
62
  "180",
63
  "--max-stage-lines",
 
36
  "89000",
37
  "--min-semantic-edges",
38
  "1000000",
39
+ "--expected-nodes",
40
+ "102928",
41
+ "--expected-edges",
42
+ "2913960",
43
  "--expected-semantic-edges",
44
+ "1683193",
45
+ "--expected-harness-nodes",
46
+ "207",
47
  "--expected-skills-sh-nodes",
48
  "89471",
49
  "--expected-skills-sh-catalog-entries",
50
  "89465",
51
  "--expected-skills-sh-converted",
52
  "89465",
53
+ "--expected-skill-pages",
54
+ "91464",
55
  "--expected-agent-pages",
56
  "467",
57
+ "--expected-mcp-pages",
58
+ "10790",
59
+ "--expected-harness-pages",
60
+ "207",
61
  "--line-threshold",
62
  "180",
63
  "--max-stage-lines",
scripts/ci_required.py CHANGED
@@ -71,6 +71,10 @@ def failed_required_jobs(
71
  event_name == "pull_request"
72
  and _job_output(needs, "classify", "graph_artifact_changed") == "true"
73
  )
 
 
 
 
74
  cheap_pr = docs_only_pr or graph_only_pr
75
  for name, details in sorted(needs.items()):
76
  result = details.get("result")
@@ -82,7 +86,12 @@ def failed_required_jobs(
82
  and result == "skipped"
83
  ):
84
  continue
85
- if cheap_pr and name in CHEAP_PR_SKIPPABLE_JOBS and result == "skipped":
 
 
 
 
 
86
  continue
87
  if (
88
  event_name == "pull_request"
 
71
  event_name == "pull_request"
72
  and _job_output(needs, "classify", "graph_artifact_changed") == "true"
73
  )
74
+ similarity_changed_pr = (
75
+ event_name == "pull_request"
76
+ and _job_output(needs, "classify", "similarity_changed") == "true"
77
+ )
78
  cheap_pr = docs_only_pr or graph_only_pr
79
  for name, details in sorted(needs.items()):
80
  result = details.get("result")
 
86
  and result == "skipped"
87
  ):
88
  continue
89
+ if (
90
+ cheap_pr
91
+ and name in CHEAP_PR_SKIPPABLE_JOBS
92
+ and not (name == "similarity-integration" and similarity_changed_pr)
93
+ and result == "skipped"
94
+ ):
95
  continue
96
  if (
97
  event_name == "pull_request"
scripts/graph_artifact_guard.py CHANGED
@@ -10,6 +10,8 @@ DEFAULT_ARTIFACTS = (
10
  "graph/wiki-graph.tar.gz",
11
  "graph/wiki-graph-runtime.tar.gz",
12
  "graph/skills-sh-catalog.json.gz",
 
 
13
  )
14
 
15
  STALE_GRAPH_PATTERNS = (
@@ -80,12 +82,15 @@ def _print_status(repo: Path, artifacts: list[str]) -> None:
80
  _run_git(repo, ["count-objects", "-vH"])
81
 
82
 
83
- def _prune(repo: Path, *, include_lfs: bool) -> None:
84
- _run_git(repo, ["prune", "--expire=now", "--verbose"])
 
85
  if include_lfs:
86
  result = _run_git(repo, ["lfs", "prune", "--verbose"], check=False)
87
  if result.returncode != 0:
88
  raise SystemExit(result.returncode)
 
 
89
 
90
 
91
  def _clean_stale_graph_files(repo: Path, *, dry_run: bool) -> None:
@@ -125,7 +130,7 @@ def _parser() -> argparse.ArgumentParser:
125
  help=(
126
  "status shows skip-worktree state; park hides generated archives from "
127
  "normal Git status/stage scans; unpark re-enables release staging; "
128
- "prune removes unreachable local Git/LFS objects; clean-stale "
129
  "removes interrupted graph promotion leftovers."
130
  ),
131
  )
@@ -149,6 +154,14 @@ def _parser() -> argparse.ArgumentParser:
149
  action="store_true",
150
  help="For prune only: skip git lfs prune.",
151
  )
 
 
 
 
 
 
 
 
152
  parser.add_argument(
153
  "--dry-run",
154
  action="store_true",
@@ -169,7 +182,11 @@ def main(argv: list[str] | None = None) -> int:
169
  elif args.command == "unpark":
170
  _set_skip_worktree(repo, artifacts, enabled=False)
171
  elif args.command == "prune":
172
- _prune(repo, include_lfs=not args.skip_lfs)
 
 
 
 
173
  elif args.command == "clean-stale":
174
  _clean_stale_graph_files(repo, dry_run=args.dry_run)
175
  return 0
 
10
  "graph/wiki-graph.tar.gz",
11
  "graph/wiki-graph-runtime.tar.gz",
12
  "graph/skills-sh-catalog.json.gz",
13
+ "graph/communities.json",
14
+ "graph/entity-overlays.jsonl",
15
  )
16
 
17
  STALE_GRAPH_PATTERNS = (
 
82
  _run_git(repo, ["count-objects", "-vH"])
83
 
84
 
85
+ def _prune(repo: Path, *, include_lfs: bool, include_git_prune: bool) -> None:
86
+ if include_git_prune:
87
+ _run_git(repo, ["prune", "--expire=now", "--verbose"])
88
  if include_lfs:
89
  result = _run_git(repo, ["lfs", "prune", "--verbose"], check=False)
90
  if result.returncode != 0:
91
  raise SystemExit(result.returncode)
92
+ if not include_lfs and not include_git_prune:
93
+ print("No prune action selected.")
94
 
95
 
96
  def _clean_stale_graph_files(repo: Path, *, dry_run: bool) -> None:
 
130
  help=(
131
  "status shows skip-worktree state; park hides generated archives from "
132
  "normal Git status/stage scans; unpark re-enables release staging; "
133
+ "prune removes prunable local LFS cache entries; clean-stale "
134
  "removes interrupted graph promotion leftovers."
135
  ),
136
  )
 
154
  action="store_true",
155
  help="For prune only: skip git lfs prune.",
156
  )
157
+ parser.add_argument(
158
+ "--include-git-prune",
159
+ action="store_true",
160
+ help=(
161
+ "For prune only: also run repo-wide git prune --expire=now. "
162
+ "This can discard unrelated dangling recovery objects."
163
+ ),
164
+ )
165
  parser.add_argument(
166
  "--dry-run",
167
  action="store_true",
 
182
  elif args.command == "unpark":
183
  _set_skip_worktree(repo, artifacts, enabled=False)
184
  elif args.command == "prune":
185
+ _prune(
186
+ repo,
187
+ include_lfs=not args.skip_lfs,
188
+ include_git_prune=args.include_git_prune,
189
+ )
190
  elif args.command == "clean-stale":
191
  _clean_stale_graph_files(repo, dry_run=args.dry_run)
192
  return 0
scripts/overlay_wiki_entities.py CHANGED
@@ -1,524 +1,540 @@
1
- """Overlay explicit local wiki entities onto shipped graph tarballs.
2
-
3
- This is a narrow release-maintenance tool. It starts from the current shipped
4
- tarball, copies every existing member except graph export files and explicit
5
- page replacements, then appends selected nodes/pages from a local wiki graph.
6
- It deliberately does not rebuild Skills.sh semantic topology.
7
- """
8
-
9
- from __future__ import annotations
10
-
11
- import argparse
12
- import json
13
- import tarfile
14
- import tempfile
15
- from collections import Counter
16
- from dataclasses import dataclass
17
- from datetime import datetime, timezone
18
- from pathlib import Path
19
- from typing import Any
20
-
21
- from ctx.core.wiki.artifact_promotion import promote_staged_artifact
22
- from ctx.utils._fs_utils import atomic_write_text, reject_symlink_path
23
- from scripts.build_dashboard_graph_index import build_dashboard_index
24
-
25
- GRAPH_EXPORT_NAMES = {
26
- "graphify-out/graph.json",
27
- "graphify-out/graph-delta.json",
28
- "graphify-out/communities.json",
29
- "graphify-out/graph-report.md",
30
- "graphify-out/graph-export-manifest.json",
31
- }
32
- OVERLAY_GZIP_COMPRESSLEVEL = 3
33
-
34
-
35
- @dataclass(frozen=True)
36
- class OverlayStats:
37
- node_count: int
38
- edge_count: int
39
- added_nodes: int
40
- added_edges: int
41
- export_id: str
42
-
43
-
44
- def overlay_entities(
45
- *,
46
- source_wiki: Path,
47
- tarball: Path,
48
- entity_ids: list[str],
49
- skills_root: Path | None = None,
50
- root_communities: Path | None = None,
51
- runtime: bool = False,
52
- now: datetime | None = None,
53
- ) -> OverlayStats:
54
- if not entity_ids:
55
- raise ValueError("at least one entity id is required")
56
- source_graph = _read_json(source_wiki / "graphify-out" / "graph.json")
57
- source_nodes = _nodes_by_id(source_graph)
58
- selected = list(dict.fromkeys(entity_ids))
59
- missing = [node_id for node_id in selected if node_id not in source_nodes]
60
- if missing:
61
- raise ValueError(f"source graph is missing selected nodes: {missing}")
62
-
63
- graph, communities = _read_tar_graph_artifacts(tarball)
64
- graph, added_nodes, added_edges = _merge_graph(graph, source_graph, selected)
65
- timestamp = _timestamp(now)
66
- export_id = f"ctx-graph-overlay-{timestamp}-{len(graph['nodes'])}-{len(graph['edges'])}"
67
- graph.setdefault("graph", {})["export_id"] = export_id
68
- graph["graph"]["generated"] = timestamp
69
- graph["graph"]["overlay_entities"] = selected
70
- communities = _merge_communities(
71
- communities,
72
- graph=graph,
73
- selected=selected,
74
- export_id=export_id,
75
- generated=timestamp,
76
- )
77
- if root_communities is not None:
78
- atomic_write_text(root_communities, json.dumps(communities, indent=2) + "\n")
79
-
80
- replacements = _collect_replacements(
81
- source_wiki=source_wiki,
82
- entity_ids=selected,
83
- skills_root=skills_root,
84
- runtime=runtime,
85
- )
86
- replacements.update({
87
- "graphify-out/graph.json": _json_bytes(graph, compact=True),
88
- "graphify-out/dashboard-neighborhoods.sqlite3": _dashboard_index_bytes(graph),
89
- "graphify-out/graph-delta.json": _json_bytes(
90
- _render_delta(graph, selected, export_id=export_id, generated=timestamp),
91
- compact=False,
92
- ),
93
- "graphify-out/communities.json": _json_bytes(communities, compact=False),
94
- "graphify-out/graph-report.md": _render_report(
95
- graph,
96
- communities,
97
- selected=selected,
98
- export_id=export_id,
99
- generated=timestamp,
100
- ).encode("utf-8"),
101
- "graphify-out/graph-export-manifest.json": _json_bytes(
102
- _render_manifest(graph, communities, export_id=export_id, generated=timestamp),
103
- compact=False,
104
- ),
105
- })
106
- _rewrite_tarball(tarball, replacements)
107
- return OverlayStats(
108
- node_count=len(graph["nodes"]),
109
- edge_count=len(graph["edges"]),
110
- added_nodes=added_nodes,
111
- added_edges=added_edges,
112
- export_id=export_id,
113
- )
114
-
115
-
116
- def _merge_graph(
117
- graph: dict[str, Any],
118
- source_graph: dict[str, Any],
119
- selected: list[str],
120
- ) -> tuple[dict[str, Any], int, int]:
121
- nodes = _list_field(graph, "nodes")
122
- edges = _list_field(graph, "edges")
123
- source_nodes = _nodes_by_id(source_graph)
124
- dest_ids = {str(node.get("id")) for node in nodes if isinstance(node, dict)}
125
- by_id = {
126
- str(node.get("id")): index
127
- for index, node in enumerate(nodes)
128
- if isinstance(node, dict) and node.get("id")
129
- }
130
- added_nodes = 0
131
- for node_id in selected:
132
- node = dict(source_nodes[node_id])
133
- if node_id in by_id:
134
- nodes[by_id[node_id]] = node
135
- else:
136
- nodes.append(node)
137
- dest_ids.add(node_id)
138
- added_nodes += 1
139
-
140
- edge_keys = {_edge_key(edge) for edge in edges if isinstance(edge, dict)}
141
- added_edges = 0
142
- for edge in _list_field(source_graph, "edges"):
143
- if not isinstance(edge, dict):
144
- continue
145
- source = str(edge.get("source") or "")
146
- target = str(edge.get("target") or "")
147
- if source not in selected and target not in selected:
148
- continue
149
- if source not in dest_ids or target not in dest_ids:
150
- continue
151
- key = _edge_key(edge)
152
- if key in edge_keys:
153
- continue
154
- edges.append(dict(edge))
155
- edge_keys.add(key)
156
- added_edges += 1
157
- graph["nodes"] = nodes
158
- graph["edges"] = edges
159
- return graph, added_nodes, added_edges
160
-
161
-
162
- def _merge_communities(
163
- communities: dict[str, Any],
164
- *,
165
- graph: dict[str, Any],
166
- selected: list[str],
167
- export_id: str,
168
- generated: str,
169
- ) -> dict[str, Any]:
170
- raw = communities.get("communities")
171
- if not isinstance(raw, dict) or not raw:
172
- raw = {"0": {"label": "Overlay", "members": []}}
173
- node_to_community: dict[str, str] = {}
174
- for cid, payload in raw.items():
175
- members = payload.get("members") if isinstance(payload, dict) else []
176
- if not isinstance(members, list):
177
- continue
178
- for member in members:
179
- node_to_community[str(member)] = str(cid)
180
- edge_pairs = [
181
- (str(edge.get("source") or ""), str(edge.get("target") or ""))
182
- for edge in _list_field(graph, "edges")
183
- if isinstance(edge, dict)
184
- ]
185
- for node_id in selected:
186
- if node_id in node_to_community:
187
- continue
188
- counts: Counter[str] = Counter()
189
- for source, target in edge_pairs:
190
- other = target if source == node_id else source if target == node_id else ""
191
- if other and other in node_to_community:
192
- counts[node_to_community[other]] += 1
193
- cid = counts.most_common(1)[0][0] if counts else sorted(raw)[0]
194
- payload = raw.setdefault(cid, {"label": "Overlay", "members": []})
195
- members = payload.setdefault("members", [])
196
- if isinstance(members, list):
197
- members.append(node_id)
198
- node_to_community[node_id] = cid
199
- communities["export_id"] = export_id
200
- communities["generated"] = generated
201
- communities["total_communities"] = len(raw)
202
- communities["communities"] = raw
203
- return communities
204
-
205
-
206
- def _collect_replacements(
207
- *,
208
- source_wiki: Path,
209
- entity_ids: list[str],
210
- skills_root: Path | None,
211
- runtime: bool,
212
- ) -> dict[str, bytes]:
213
- replacements: dict[str, bytes] = {}
214
- for node_id in entity_ids:
215
- entity_type, slug = _split_node_id(node_id)
216
- page = _entity_page(source_wiki, entity_type, slug)
217
- if page is not None and (not runtime or entity_type == "harness"):
218
- replacements[page.relative_to(source_wiki).as_posix()] = page.read_bytes()
219
- if not runtime and entity_type == "skill":
220
- replacements.update(_skill_replacements(source_wiki, slug, skills_root=skills_root))
221
- return replacements
222
-
223
-
224
- def _dashboard_index_bytes(graph: dict[str, Any]) -> bytes:
225
- with tempfile.TemporaryDirectory(prefix="ctx-overlay-index-") as tmp:
226
- tmp_path = Path(tmp)
227
- graph_path = tmp_path / "graph.json"
228
- index_path = tmp_path / "dashboard-neighborhoods.sqlite3"
229
- graph_path.write_bytes(_json_bytes(graph, compact=True))
230
- build_dashboard_index(graph_path, index_path)
231
- return index_path.read_bytes()
232
-
233
-
234
- def _entity_page(source_wiki: Path, entity_type: str, slug: str) -> Path | None:
235
- candidates = {
236
- "skill": [source_wiki / "entities" / "skills" / f"{slug}.md"],
237
- "agent": [source_wiki / "entities" / "agents" / f"{slug}.md"],
238
- "harness": [source_wiki / "entities" / "harnesses" / f"{slug}.md"],
239
- "mcp-server": [
240
- source_wiki / "entities" / "mcp-servers" / slug[:1].lower() / f"{slug}.md",
241
- ],
242
- }.get(entity_type, [])
243
- for candidate in candidates:
244
- if candidate.is_file():
245
- return candidate
246
- if entity_type == "mcp-server":
247
- matches = list((source_wiki / "entities" / "mcp-servers").rglob(f"{slug}.md"))
248
- if matches:
249
- return matches[0]
250
- return None
251
-
252
-
253
- def _skill_replacements(source_wiki: Path, slug: str, *, skills_root: Path | None) -> dict[str, bytes]:
254
- root = skills_root or Path.home() / ".claude" / "skills"
255
- candidates = [
256
- source_wiki / "converted" / slug / "SKILL.md",
257
- root / slug / "SKILL.md",
258
- ]
259
- for candidate in candidates:
260
- if candidate.is_file():
261
- skill_dir = candidate.parent
262
- return {
263
- f"converted/{slug}/{path.relative_to(skill_dir).as_posix()}": path.read_bytes()
264
- for path in sorted(skill_dir.rglob("*"))
265
- if path.is_file() and not path.name.endswith((".original", ".lock"))
266
- }
267
- return {}
268
-
269
-
270
- def _rewrite_tarball(tarball: Path, replacements: dict[str, bytes]) -> None:
271
- reject_symlink_path(tarball)
272
- staged = tarball.with_name(f"{tarball.name}.staged")
273
- reject_symlink_path(staged)
274
- skip_names = set(replacements)
275
- with tarfile.open(tarball, "r:gz") as src, tarfile.open(
276
- staged,
277
- "w:gz",
278
- compresslevel=OVERLAY_GZIP_COMPRESSLEVEL,
279
- ) as dst:
280
- for member in src:
281
- safe_name = _safe_tar_name(member.name)
282
- if safe_name is None:
283
- continue
284
- if safe_name in GRAPH_EXPORT_NAMES or safe_name in skip_names:
285
- continue
286
- if safe_name.endswith(".original") or safe_name.endswith(".lock"):
287
- continue
288
- if member.isfile():
289
- f = src.extractfile(member)
290
- if f is not None:
291
- dst.addfile(member, f)
292
- elif member.isdir():
293
- dst.addfile(member)
294
- for name, payload in sorted(replacements.items()):
295
- _add_bytes(dst, name=f"./{name}", payload=payload)
296
- promote_staged_artifact(staged, tarball, validate=_validate_tarball)
297
-
298
-
299
- def _validate_tarball(candidate: Path) -> None:
300
- seen: set[str] = set()
301
- with tarfile.open(candidate, "r:gz") as tf:
302
- for member in tf:
303
- safe_name = _safe_tar_name(member.name)
304
- if safe_name is None:
305
- raise ValueError(f"unsafe tar member: {member.name}")
306
- if safe_name.endswith(".original") or safe_name.endswith(".lock"):
307
- raise ValueError(f"transient member leaked: {safe_name}")
308
- seen.add(safe_name)
309
- missing = sorted(GRAPH_EXPORT_NAMES - seen)
310
- if missing:
311
- raise ValueError(f"candidate tarball missing graph exports: {missing}")
312
-
313
-
314
- def _read_tar_graph_artifacts(tarball: Path) -> tuple[dict[str, Any], dict[str, Any]]:
315
- graph: dict[str, Any] | None = None
316
- communities: dict[str, Any] | None = None
317
- with tarfile.open(tarball, "r:gz") as tf:
318
- for member in tf:
319
- safe_name = _safe_tar_name(member.name)
320
- if safe_name not in {"graphify-out/graph.json", "graphify-out/communities.json"}:
321
- continue
322
- f = tf.extractfile(member)
323
- if f is None:
324
- continue
325
- data = json.loads(f.read().decode("utf-8"))
326
- if safe_name.endswith("graph.json"):
327
- graph = data
328
- else:
329
- communities = data
330
- if graph is None or communities is None:
331
- raise ValueError("tarball is missing graph.json or communities.json")
332
- return graph, communities
333
-
334
-
335
- def _render_delta(
336
- graph: dict[str, Any],
337
- selected: list[str],
338
- *,
339
- export_id: str,
340
- generated: str,
341
- ) -> dict[str, Any]:
342
- selected_set = set(selected)
343
- nodes = [
344
- node for node in _list_field(graph, "nodes")
345
- if isinstance(node, dict) and node.get("id") in selected_set
346
- ]
347
- edges = [
348
- edge for edge in _list_field(graph, "edges")
349
- if isinstance(edge, dict)
350
- and (edge.get("source") in selected_set or edge.get("target") in selected_set)
351
- ]
352
- return {
353
- "version": 1,
354
- "full_rebuild": False,
355
- "export_id": export_id,
356
- "generated": generated,
357
- "node_count": len(graph["nodes"]),
358
- "edge_count": len(graph["edges"]),
359
- "delta_node_count": len(nodes),
360
- "delta_edge_count": len(edges),
361
- "nodes": nodes,
362
- "edges": edges,
363
- }
364
-
365
-
366
- def _render_manifest(
367
- graph: dict[str, Any],
368
- communities: dict[str, Any],
369
- *,
370
- export_id: str,
371
- generated: str,
372
- ) -> dict[str, Any]:
373
- return {
374
- "version": 1,
375
- "export_id": export_id,
376
- "generated": generated,
377
- "artifacts": {
378
- "graph": "graph.json",
379
- "delta": "graph-delta.json",
380
- "communities": "communities.json",
381
- "report": "graph-report.md",
382
- },
383
- "counts": {
384
- "nodes": len(graph["nodes"]),
385
- "edges": len(graph["edges"]),
386
- "communities": communities.get("total_communities", 0),
387
- },
388
- }
389
-
390
-
391
- def _render_report(
392
- graph: dict[str, Any],
393
- communities: dict[str, Any],
394
- *,
395
- selected: list[str],
396
- export_id: str,
397
- generated: str,
398
- ) -> str:
399
- degree: Counter[str] = Counter()
400
- for edge in _list_field(graph, "edges"):
401
- if not isinstance(edge, dict):
402
- continue
403
- degree[str(edge.get("source") or "")] += 1
404
- degree[str(edge.get("target") or "")] += 1
405
- node_by_id = _nodes_by_id(graph)
406
- lines = [
407
- "# Graph Report",
408
- "",
409
- f"> Generated: {generated}",
410
- f"> Export ID: {export_id}",
411
- (
412
- f"> Nodes: {len(graph['nodes'])} | Edges: {len(graph['edges'])} | "
413
- f"Communities: {communities.get('total_communities', 0)}"
414
- ),
415
- "",
416
- "## Overlay Entities",
417
- "",
418
- ]
419
- for node_id in selected:
420
- node = node_by_id.get(node_id, {})
421
- lines.append(f"- **{node.get('label', node_id)}** ({node_id})")
422
- lines.extend(["", "## Most Connected Nodes", ""])
423
- for node_id, count in degree.most_common(20):
424
- if not node_id:
425
- continue
426
- node = node_by_id.get(node_id, {})
427
- lines.append(f"- **{node.get('label', node_id)}** ({count} connections)")
428
- return "\n".join(lines) + "\n"
429
-
430
-
431
- def _read_json(path: Path) -> dict[str, Any]:
432
- data = json.loads(path.read_text(encoding="utf-8"))
433
- if not isinstance(data, dict):
434
- raise ValueError(f"{path} must contain a JSON object")
435
- return data
436
-
437
-
438
- def _nodes_by_id(graph: dict[str, Any]) -> dict[str, dict[str, Any]]:
439
- return {
440
- str(node.get("id")): node
441
- for node in _list_field(graph, "nodes")
442
- if isinstance(node, dict) and node.get("id")
443
- }
444
-
445
-
446
- def _list_field(data: dict[str, Any], key: str) -> list[Any]:
447
- value = data.get(key)
448
- if not isinstance(value, list):
449
- raise ValueError(f"graph field {key!r} must be a list")
450
- return value
451
-
452
-
453
- def _edge_key(edge: dict[str, Any]) -> tuple[str, str]:
454
- source = str(edge.get("source") or "")
455
- target = str(edge.get("target") or "")
456
- return (source, target) if source <= target else (target, source)
457
-
458
-
459
- def _split_node_id(node_id: str) -> tuple[str, str]:
460
- if ":" not in node_id:
461
- raise ValueError(f"invalid node id: {node_id}")
462
- entity_type, slug = node_id.split(":", 1)
463
- return entity_type, slug
464
-
465
-
466
- def _safe_tar_name(name: str) -> str | None:
467
- normalized = name.replace("\\", "/")
468
- while normalized.startswith("./"):
469
- normalized = normalized[2:]
470
- if not normalized or normalized.startswith("/") or normalized.startswith("../"):
471
- return None
472
- if "/../" in normalized or normalized == "..":
473
- return None
474
- return normalized
475
-
476
-
477
- def _add_bytes(
478
- tf: tarfile.TarFile,
479
- *,
480
- name: str,
481
- payload: bytes,
482
- mode: int = 0o644,
483
- ) -> None:
484
- import io
485
-
486
- info = tarfile.TarInfo(name)
487
- info.size = len(payload)
488
- info.mode = mode
489
- info.mtime = 0
490
- tf.addfile(info, io.BytesIO(payload))
491
-
492
-
493
- def _json_bytes(data: dict[str, Any], *, compact: bool) -> bytes:
494
- if compact:
495
- return json.dumps(data, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
496
- return (json.dumps(data, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
497
-
498
-
499
- def _timestamp(now: datetime | None = None) -> str:
500
- value = now or datetime.now(timezone.utc)
501
- return value.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
502
-
503
-
504
- def main() -> None:
505
- parser = argparse.ArgumentParser(description=__doc__)
506
- parser.add_argument("--source-wiki", type=Path, default=Path.home() / ".claude" / "skill-wiki")
507
- parser.add_argument("--tarball", type=Path, required=True)
508
- parser.add_argument("--entity", action="append", required=True, help="Node id, e.g. skill:foo")
509
- parser.add_argument("--root-communities", type=Path)
510
- parser.add_argument("--runtime", action="store_true")
511
- args = parser.parse_args()
512
- stats = overlay_entities(
513
- source_wiki=args.source_wiki,
514
- tarball=args.tarball,
515
- entity_ids=args.entity,
516
- skills_root=Path.home() / ".claude" / "skills",
517
- root_communities=args.root_communities,
518
- runtime=args.runtime,
519
- )
520
- print(json.dumps(stats.__dict__, indent=2))
521
-
522
-
523
- if __name__ == "__main__":
524
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Overlay explicit local wiki entities onto shipped graph tarballs.
2
+
3
+ This is a narrow release-maintenance tool. It starts from the current shipped
4
+ tarball, copies every existing member except graph export files and explicit
5
+ page replacements, then appends selected nodes/pages from a local wiki graph.
6
+ It deliberately does not rebuild Skills.sh semantic topology.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import sys
14
+ import tarfile
15
+ import tempfile
16
+ from collections import Counter
17
+ from dataclasses import dataclass
18
+ from datetime import datetime, timezone
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ REPO_ROOT = Path(__file__).resolve().parent.parent
23
+ if str(REPO_ROOT) not in sys.path:
24
+ sys.path.insert(0, str(REPO_ROOT))
25
+
26
+ from ctx.core.wiki.artifact_promotion import promote_staged_artifact # noqa: E402
27
+ from ctx.utils._fs_utils import atomic_write_text, reject_symlink_path # noqa: E402
28
+ from scripts.build_dashboard_graph_index import build_dashboard_index # noqa: E402
29
+
30
+ GRAPH_EXPORT_NAMES = {
31
+ "graphify-out/graph.json",
32
+ "graphify-out/graph-delta.json",
33
+ "graphify-out/communities.json",
34
+ "graphify-out/graph-report.md",
35
+ "graphify-out/graph-export-manifest.json",
36
+ }
37
+ OVERLAY_GZIP_COMPRESSLEVEL = 3
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class OverlayStats:
42
+ node_count: int
43
+ edge_count: int
44
+ added_nodes: int
45
+ added_edges: int
46
+ export_id: str
47
+
48
+
49
+ def overlay_entities(
50
+ *,
51
+ source_wiki: Path,
52
+ tarball: Path,
53
+ entity_ids: list[str],
54
+ skills_root: Path | None = None,
55
+ root_communities: Path | None = None,
56
+ runtime: bool = False,
57
+ now: datetime | None = None,
58
+ ) -> OverlayStats:
59
+ if not entity_ids:
60
+ raise ValueError("at least one entity id is required")
61
+ source_graph = _read_json(source_wiki / "graphify-out" / "graph.json")
62
+ source_nodes = _nodes_by_id(source_graph)
63
+ selected = list(dict.fromkeys(entity_ids))
64
+ missing = [node_id for node_id in selected if node_id not in source_nodes]
65
+ if missing:
66
+ raise ValueError(f"source graph is missing selected nodes: {missing}")
67
+
68
+ graph, communities = _read_tar_graph_artifacts(tarball)
69
+ graph, added_nodes, added_edges = _merge_graph(graph, source_graph, selected)
70
+ timestamp = _timestamp(now)
71
+ export_id = f"ctx-graph-overlay-{timestamp}-{len(graph['nodes'])}-{len(graph['edges'])}"
72
+ graph.setdefault("graph", {})["export_id"] = export_id
73
+ graph["graph"]["generated"] = timestamp
74
+ graph["graph"]["overlay_entities"] = selected
75
+ communities = _merge_communities(
76
+ communities,
77
+ graph=graph,
78
+ selected=selected,
79
+ export_id=export_id,
80
+ generated=timestamp,
81
+ )
82
+ if root_communities is not None:
83
+ atomic_write_text(root_communities, json.dumps(communities, indent=2) + "\n")
84
+
85
+ replacements = _collect_replacements(
86
+ source_wiki=source_wiki,
87
+ entity_ids=selected,
88
+ skills_root=skills_root,
89
+ runtime=runtime,
90
+ )
91
+ replacements.update({
92
+ "graphify-out/graph.json": _json_bytes(graph, compact=True),
93
+ "graphify-out/dashboard-neighborhoods.sqlite3": _dashboard_index_bytes(graph),
94
+ "graphify-out/graph-delta.json": _json_bytes(
95
+ _render_delta(graph, selected, export_id=export_id, generated=timestamp),
96
+ compact=False,
97
+ ),
98
+ "graphify-out/communities.json": _json_bytes(communities, compact=False),
99
+ "graphify-out/graph-report.md": _render_report(
100
+ graph,
101
+ communities,
102
+ selected=selected,
103
+ export_id=export_id,
104
+ generated=timestamp,
105
+ ).encode("utf-8"),
106
+ "graphify-out/graph-export-manifest.json": _json_bytes(
107
+ _render_manifest(graph, communities, export_id=export_id, generated=timestamp),
108
+ compact=False,
109
+ ),
110
+ })
111
+ _rewrite_tarball(tarball, replacements)
112
+ return OverlayStats(
113
+ node_count=len(graph["nodes"]),
114
+ edge_count=len(graph["edges"]),
115
+ added_nodes=added_nodes,
116
+ added_edges=added_edges,
117
+ export_id=export_id,
118
+ )
119
+
120
+
121
+ def _merge_graph(
122
+ graph: dict[str, Any],
123
+ source_graph: dict[str, Any],
124
+ selected: list[str],
125
+ ) -> tuple[dict[str, Any], int, int]:
126
+ nodes = _list_field(graph, "nodes")
127
+ edges = _list_field(graph, "edges")
128
+ source_nodes = _nodes_by_id(source_graph)
129
+ dest_ids = {str(node.get("id")) for node in nodes if isinstance(node, dict)}
130
+ by_id = {
131
+ str(node.get("id")): index
132
+ for index, node in enumerate(nodes)
133
+ if isinstance(node, dict) and node.get("id")
134
+ }
135
+ added_nodes = 0
136
+ for node_id in selected:
137
+ node = dict(source_nodes[node_id])
138
+ if node_id in by_id:
139
+ nodes[by_id[node_id]] = node
140
+ else:
141
+ nodes.append(node)
142
+ dest_ids.add(node_id)
143
+ added_nodes += 1
144
+
145
+ edge_keys = {_edge_key(edge) for edge in edges if isinstance(edge, dict)}
146
+ added_edges = 0
147
+ for edge in _list_field(source_graph, "edges"):
148
+ if not isinstance(edge, dict):
149
+ continue
150
+ source = str(edge.get("source") or "")
151
+ target = str(edge.get("target") or "")
152
+ if source not in selected and target not in selected:
153
+ continue
154
+ if source not in dest_ids or target not in dest_ids:
155
+ continue
156
+ key = _edge_key(edge)
157
+ if key in edge_keys:
158
+ continue
159
+ edges.append(dict(edge))
160
+ edge_keys.add(key)
161
+ added_edges += 1
162
+ graph["nodes"] = nodes
163
+ graph["edges"] = edges
164
+ return graph, added_nodes, added_edges
165
+
166
+
167
+ def _merge_communities(
168
+ communities: dict[str, Any],
169
+ *,
170
+ graph: dict[str, Any],
171
+ selected: list[str],
172
+ export_id: str,
173
+ generated: str,
174
+ ) -> dict[str, Any]:
175
+ raw = communities.get("communities")
176
+ if not isinstance(raw, dict) or not raw:
177
+ raw = {"0": {"label": "Overlay", "members": []}}
178
+ node_to_community: dict[str, str] = {}
179
+ for cid, payload in raw.items():
180
+ members = payload.get("members") if isinstance(payload, dict) else []
181
+ if not isinstance(members, list):
182
+ continue
183
+ for member in members:
184
+ node_to_community[str(member)] = str(cid)
185
+ edge_pairs = [
186
+ (str(edge.get("source") or ""), str(edge.get("target") or ""))
187
+ for edge in _list_field(graph, "edges")
188
+ if isinstance(edge, dict)
189
+ ]
190
+ for node_id in selected:
191
+ if node_id in node_to_community:
192
+ continue
193
+ counts: Counter[str] = Counter()
194
+ for source, target in edge_pairs:
195
+ other = target if source == node_id else source if target == node_id else ""
196
+ if other and other in node_to_community:
197
+ counts[node_to_community[other]] += 1
198
+ cid = counts.most_common(1)[0][0] if counts else sorted(raw)[0]
199
+ payload = raw.setdefault(cid, {"label": "Overlay", "members": []})
200
+ members = payload.setdefault("members", [])
201
+ if isinstance(members, list):
202
+ members.append(node_id)
203
+ node_to_community[node_id] = cid
204
+ communities["export_id"] = export_id
205
+ communities["generated"] = generated
206
+ communities["total_communities"] = len(raw)
207
+ communities["communities"] = raw
208
+ return communities
209
+
210
+
211
+ def _collect_replacements(
212
+ *,
213
+ source_wiki: Path,
214
+ entity_ids: list[str],
215
+ skills_root: Path | None,
216
+ runtime: bool,
217
+ ) -> dict[str, bytes]:
218
+ replacements: dict[str, bytes] = {}
219
+ for node_id in entity_ids:
220
+ entity_type, slug = _split_node_id(node_id)
221
+ page = _entity_page(source_wiki, entity_type, slug)
222
+ if page is not None and (not runtime or entity_type == "harness"):
223
+ replacements[page.relative_to(source_wiki).as_posix()] = _read_safe_bytes(page)
224
+ if not runtime and entity_type == "skill":
225
+ replacements.update(_skill_replacements(source_wiki, slug, skills_root=skills_root))
226
+ return replacements
227
+
228
+
229
+ def _dashboard_index_bytes(graph: dict[str, Any]) -> bytes:
230
+ with tempfile.TemporaryDirectory(prefix="ctx-overlay-index-") as tmp:
231
+ tmp_path = Path(tmp)
232
+ graph_path = tmp_path / "graph.json"
233
+ index_path = tmp_path / "dashboard-neighborhoods.sqlite3"
234
+ graph_path.write_bytes(_json_bytes(graph, compact=True))
235
+ build_dashboard_index(graph_path, index_path)
236
+ return index_path.read_bytes()
237
+
238
+
239
+ def _entity_page(source_wiki: Path, entity_type: str, slug: str) -> Path | None:
240
+ candidates = {
241
+ "skill": [source_wiki / "entities" / "skills" / f"{slug}.md"],
242
+ "agent": [source_wiki / "entities" / "agents" / f"{slug}.md"],
243
+ "harness": [source_wiki / "entities" / "harnesses" / f"{slug}.md"],
244
+ "mcp-server": [
245
+ source_wiki / "entities" / "mcp-servers" / slug[:1].lower() / f"{slug}.md",
246
+ ],
247
+ }.get(entity_type, [])
248
+ for candidate in candidates:
249
+ if _is_safe_file(candidate):
250
+ return candidate
251
+ if entity_type == "mcp-server":
252
+ matches = list((source_wiki / "entities" / "mcp-servers").rglob(f"{slug}.md"))
253
+ for match in matches:
254
+ if _is_safe_file(match):
255
+ return match
256
+ return None
257
+
258
+
259
+ def _skill_replacements(source_wiki: Path, slug: str, *, skills_root: Path | None) -> dict[str, bytes]:
260
+ root = skills_root or Path.home() / ".claude" / "skills"
261
+ candidates = [
262
+ source_wiki / "converted" / slug / "SKILL.md",
263
+ root / slug / "SKILL.md",
264
+ ]
265
+ for candidate in candidates:
266
+ if _is_safe_file(candidate):
267
+ skill_dir = candidate.parent
268
+ return {
269
+ f"converted/{slug}/{path.relative_to(skill_dir).as_posix()}": _read_safe_bytes(path)
270
+ for path in sorted(skill_dir.rglob("*"))
271
+ if _is_safe_file(path) and not path.name.endswith((".original", ".lock"))
272
+ }
273
+ return {}
274
+
275
+
276
+ def _is_safe_file(path: Path) -> bool:
277
+ reject_symlink_path(path)
278
+ return path.is_file()
279
+
280
+
281
+ def _read_safe_bytes(path: Path) -> bytes:
282
+ reject_symlink_path(path)
283
+ return path.read_bytes()
284
+
285
+
286
+ def _rewrite_tarball(tarball: Path, replacements: dict[str, bytes]) -> None:
287
+ reject_symlink_path(tarball)
288
+ staged = tarball.with_name(f"{tarball.name}.staged")
289
+ reject_symlink_path(staged)
290
+ skip_names = set(replacements)
291
+ with tarfile.open(tarball, "r:gz") as src, tarfile.open(
292
+ staged,
293
+ "w:gz",
294
+ compresslevel=OVERLAY_GZIP_COMPRESSLEVEL,
295
+ ) as dst:
296
+ for member in src:
297
+ safe_name = _safe_tar_name(member.name)
298
+ if safe_name is None:
299
+ continue
300
+ if safe_name in GRAPH_EXPORT_NAMES or safe_name in skip_names:
301
+ continue
302
+ if safe_name.endswith(".original") or safe_name.endswith(".lock"):
303
+ continue
304
+ if member.isfile():
305
+ f = src.extractfile(member)
306
+ if f is not None:
307
+ dst.addfile(member, f)
308
+ elif member.isdir():
309
+ dst.addfile(member)
310
+ for name, payload in sorted(replacements.items()):
311
+ _add_bytes(dst, name=f"./{name}", payload=payload)
312
+ promote_staged_artifact(staged, tarball, validate=_validate_tarball)
313
+
314
+
315
+ def _validate_tarball(candidate: Path) -> None:
316
+ seen: set[str] = set()
317
+ with tarfile.open(candidate, "r:gz") as tf:
318
+ for member in tf:
319
+ safe_name = _safe_tar_name(member.name)
320
+ if safe_name is None:
321
+ raise ValueError(f"unsafe tar member: {member.name}")
322
+ if safe_name.endswith(".original") or safe_name.endswith(".lock"):
323
+ raise ValueError(f"transient member leaked: {safe_name}")
324
+ seen.add(safe_name)
325
+ missing = sorted(GRAPH_EXPORT_NAMES - seen)
326
+ if missing:
327
+ raise ValueError(f"candidate tarball missing graph exports: {missing}")
328
+
329
+
330
+ def _read_tar_graph_artifacts(tarball: Path) -> tuple[dict[str, Any], dict[str, Any]]:
331
+ graph: dict[str, Any] | None = None
332
+ communities: dict[str, Any] | None = None
333
+ with tarfile.open(tarball, "r:gz") as tf:
334
+ for member in tf:
335
+ safe_name = _safe_tar_name(member.name)
336
+ if safe_name not in {"graphify-out/graph.json", "graphify-out/communities.json"}:
337
+ continue
338
+ f = tf.extractfile(member)
339
+ if f is None:
340
+ continue
341
+ data = json.loads(f.read().decode("utf-8"))
342
+ if safe_name.endswith("graph.json"):
343
+ graph = data
344
+ else:
345
+ communities = data
346
+ if graph is None or communities is None:
347
+ raise ValueError("tarball is missing graph.json or communities.json")
348
+ return graph, communities
349
+
350
+
351
+ def _render_delta(
352
+ graph: dict[str, Any],
353
+ selected: list[str],
354
+ *,
355
+ export_id: str,
356
+ generated: str,
357
+ ) -> dict[str, Any]:
358
+ selected_set = set(selected)
359
+ nodes = [
360
+ node for node in _list_field(graph, "nodes")
361
+ if isinstance(node, dict) and node.get("id") in selected_set
362
+ ]
363
+ edges = [
364
+ edge for edge in _list_field(graph, "edges")
365
+ if isinstance(edge, dict)
366
+ and (edge.get("source") in selected_set or edge.get("target") in selected_set)
367
+ ]
368
+ return {
369
+ "version": 1,
370
+ "full_rebuild": False,
371
+ "export_id": export_id,
372
+ "generated": generated,
373
+ "node_count": len(graph["nodes"]),
374
+ "edge_count": len(graph["edges"]),
375
+ "delta_node_count": len(nodes),
376
+ "delta_edge_count": len(edges),
377
+ "nodes": nodes,
378
+ "edges": edges,
379
+ }
380
+
381
+
382
+ def _render_manifest(
383
+ graph: dict[str, Any],
384
+ communities: dict[str, Any],
385
+ *,
386
+ export_id: str,
387
+ generated: str,
388
+ ) -> dict[str, Any]:
389
+ return {
390
+ "version": 1,
391
+ "export_id": export_id,
392
+ "generated": generated,
393
+ "artifacts": {
394
+ "graph": "graph.json",
395
+ "delta": "graph-delta.json",
396
+ "communities": "communities.json",
397
+ "report": "graph-report.md",
398
+ },
399
+ "counts": {
400
+ "nodes": len(graph["nodes"]),
401
+ "edges": len(graph["edges"]),
402
+ "communities": communities.get("total_communities", 0),
403
+ },
404
+ }
405
+
406
+
407
+ def _render_report(
408
+ graph: dict[str, Any],
409
+ communities: dict[str, Any],
410
+ *,
411
+ selected: list[str],
412
+ export_id: str,
413
+ generated: str,
414
+ ) -> str:
415
+ degree: Counter[str] = Counter()
416
+ for edge in _list_field(graph, "edges"):
417
+ if not isinstance(edge, dict):
418
+ continue
419
+ degree[str(edge.get("source") or "")] += 1
420
+ degree[str(edge.get("target") or "")] += 1
421
+ node_by_id = _nodes_by_id(graph)
422
+ lines = [
423
+ "# Graph Report",
424
+ "",
425
+ f"> Generated: {generated}",
426
+ f"> Export ID: {export_id}",
427
+ (
428
+ f"> Nodes: {len(graph['nodes'])} | Edges: {len(graph['edges'])} | "
429
+ f"Communities: {communities.get('total_communities', 0)}"
430
+ ),
431
+ "",
432
+ "## Overlay Entities",
433
+ "",
434
+ ]
435
+ for node_id in selected:
436
+ node = node_by_id.get(node_id, {})
437
+ lines.append(f"- **{node.get('label', node_id)}** ({node_id})")
438
+ lines.extend(["", "## Most Connected Nodes", ""])
439
+ for node_id, count in degree.most_common(20):
440
+ if not node_id:
441
+ continue
442
+ node = node_by_id.get(node_id, {})
443
+ lines.append(f"- **{node.get('label', node_id)}** ({count} connections)")
444
+ return "\n".join(lines) + "\n"
445
+
446
+
447
+ def _read_json(path: Path) -> dict[str, Any]:
448
+ data = json.loads(path.read_text(encoding="utf-8"))
449
+ if not isinstance(data, dict):
450
+ raise ValueError(f"{path} must contain a JSON object")
451
+ return data
452
+
453
+
454
+ def _nodes_by_id(graph: dict[str, Any]) -> dict[str, dict[str, Any]]:
455
+ return {
456
+ str(node.get("id")): node
457
+ for node in _list_field(graph, "nodes")
458
+ if isinstance(node, dict) and node.get("id")
459
+ }
460
+
461
+
462
+ def _list_field(data: dict[str, Any], key: str) -> list[Any]:
463
+ value = data.get(key)
464
+ if not isinstance(value, list):
465
+ raise ValueError(f"graph field {key!r} must be a list")
466
+ return value
467
+
468
+
469
+ def _edge_key(edge: dict[str, Any]) -> tuple[str, str]:
470
+ source = str(edge.get("source") or "")
471
+ target = str(edge.get("target") or "")
472
+ return (source, target) if source <= target else (target, source)
473
+
474
+
475
+ def _split_node_id(node_id: str) -> tuple[str, str]:
476
+ if ":" not in node_id:
477
+ raise ValueError(f"invalid node id: {node_id}")
478
+ entity_type, slug = node_id.split(":", 1)
479
+ return entity_type, slug
480
+
481
+
482
+ def _safe_tar_name(name: str) -> str | None:
483
+ normalized = name.replace("\\", "/")
484
+ while normalized.startswith("./"):
485
+ normalized = normalized[2:]
486
+ if not normalized or normalized.startswith("/") or normalized.startswith("../"):
487
+ return None
488
+ if "/../" in normalized or normalized == "..":
489
+ return None
490
+ return normalized
491
+
492
+
493
+ def _add_bytes(
494
+ tf: tarfile.TarFile,
495
+ *,
496
+ name: str,
497
+ payload: bytes,
498
+ mode: int = 0o644,
499
+ ) -> None:
500
+ import io
501
+
502
+ info = tarfile.TarInfo(name)
503
+ info.size = len(payload)
504
+ info.mode = mode
505
+ info.mtime = 0
506
+ tf.addfile(info, io.BytesIO(payload))
507
+
508
+
509
+ def _json_bytes(data: dict[str, Any], *, compact: bool) -> bytes:
510
+ if compact:
511
+ return json.dumps(data, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
512
+ return (json.dumps(data, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
513
+
514
+
515
+ def _timestamp(now: datetime | None = None) -> str:
516
+ value = now or datetime.now(timezone.utc)
517
+ return value.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
518
+
519
+
520
+ def main() -> None:
521
+ parser = argparse.ArgumentParser(description=__doc__)
522
+ parser.add_argument("--source-wiki", type=Path, default=Path.home() / ".claude" / "skill-wiki")
523
+ parser.add_argument("--tarball", type=Path, required=True)
524
+ parser.add_argument("--entity", action="append", required=True, help="Node id, e.g. skill:foo")
525
+ parser.add_argument("--root-communities", type=Path)
526
+ parser.add_argument("--runtime", action="store_true")
527
+ args = parser.parse_args()
528
+ stats = overlay_entities(
529
+ source_wiki=args.source_wiki,
530
+ tarball=args.tarball,
531
+ entity_ids=args.entity,
532
+ skills_root=Path.home() / ".claude" / "skills",
533
+ root_communities=args.root_communities,
534
+ runtime=args.runtime,
535
+ )
536
+ print(json.dumps(stats.__dict__, indent=2))
537
+
538
+
539
+ if __name__ == "__main__":
540
+ main()
src/__init__.py CHANGED
@@ -1,3 +1,3 @@
1
  """ctx — skill and agent recommendation for Claude Code."""
2
 
3
- __version__ = "1.0.9"
 
1
  """ctx — skill and agent recommendation for Claude Code."""
2
 
3
+ __version__ = "1.0.11"
src/agent_add.py CHANGED
@@ -24,17 +24,17 @@ import argparse
24
  import os
25
  import sys
26
  from datetime import datetime, timezone
27
- from pathlib import Path
28
-
29
- from ctx.core.entity_update import build_update_review, render_update_review
30
- from ctx_config import cfg
31
- from ctx.adapters.claude_code.install.install_utils import safe_copy_file
32
- from intake_pipeline import IntakeRejected, check_intake, record_embedding
33
- from wiki_batch_entities import generate_agent_page
34
- from ctx.core.wiki.wiki_queue import enqueue_entity_upsert
35
- from ctx.core.wiki.wiki_sync import append_log, ensure_wiki, update_index
36
- from ctx.core.wiki.wiki_utils import validate_skill_name
37
- from ctx.utils._fs_utils import reject_symlink_path, safe_atomic_write_text
38
 
39
  TODAY = datetime.now(timezone.utc).strftime("%Y-%m-%d")
40
 
@@ -53,24 +53,52 @@ def install_agent(source: Path, agents_dir: Path, name: str) -> Path:
53
  return dest
54
 
55
 
56
- def write_entity_page(wiki_path: Path, name: str, content: str) -> bool:
57
- """Write agent entity page. Returns True if newly created."""
58
- page = wiki_path / "entities" / "agents" / f"{name}.md"
59
- reject_symlink_path(page)
60
- is_new = not page.exists()
61
- safe_atomic_write_text(page, content, encoding="utf-8")
62
- return is_new
63
-
64
-
65
- def add_agent(
66
- *,
67
- source_path: Path,
68
- name: str,
69
- wiki_path: Path,
70
- agents_dir: Path,
71
- review_existing: bool = False,
72
- update_existing: bool = False,
73
- ) -> dict:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  """Add a single agent: validate, gate, install, ingest, log.
75
 
76
  Returns a result dict with keys: name, installed, is_new_page.
@@ -83,48 +111,51 @@ def add_agent(
83
  f"agent file too large ({file_size:,} bytes). Max "
84
  f"{_MAX_AGENT_BYTES:,}. Trim before ingestion."
85
  )
86
-
87
- content = source_path.read_text(encoding="utf-8", errors="replace")
88
- line_count = len(content.splitlines())
89
-
90
- installed_path = agents_dir / f"{name}.md"
91
- entity_page = wiki_path / "entities" / "agents" / f"{name}.md"
92
- existing_path = (
93
- installed_path
94
- if installed_path.exists()
95
- else entity_page if entity_page.exists() else None
96
- )
97
- has_existing = existing_path is not None
98
-
99
- if review_existing and has_existing and not update_existing:
100
- assert existing_path is not None
101
- existing_text = existing_path.read_text(encoding="utf-8", errors="replace")
102
- review = build_update_review(
103
- entity_type="agent",
104
- slug=name,
105
- existing_text=existing_text,
106
- proposed_text=content,
107
- )
108
- return {
109
- "name": name,
110
- "installed": str(installed_path),
111
- "is_new_page": False,
112
- "skipped": True,
113
- "update_required": True,
114
- "update_review": render_update_review(review),
115
- }
116
-
117
- decision = None
118
- if not has_existing:
119
- # Intake gate: reject broken/duplicate agents before we install.
120
- # Existing updates bypass similarity intake because they compare
121
- # against their own cached embedding.
122
- decision = check_intake(content, "agents")
123
- if not decision.allow:
124
- raise IntakeRejected(decision)
125
-
126
- # 1. Install into agents-dir.
127
- installed_path = install_agent(source_path, agents_dir, name)
 
 
 
128
 
129
  # 2. Record embedding. Non-fatal on failure — install already
130
  # succeeded and a missing vector only weakens the next check.
@@ -150,30 +181,30 @@ def add_agent(
150
  f"Installed: {installed_path}",
151
  f"Lines: {line_count}",
152
  ]
153
- warnings = decision.warnings if decision is not None else ()
154
- if warnings:
155
- log_details.append(
156
- "Warnings: " + "; ".join(f"{w.code}:{w.message}" for w in warnings)
157
- )
158
- append_log(str(wiki_path), "add-agent", name, log_details)
159
- queue_job = enqueue_entity_upsert(
160
- wiki_path,
161
- entity_type="agent",
162
- slug=name,
163
- entity_path=wiki_path / "entities" / "agents" / f"{name}.md",
164
- content=page_content,
165
- action="created" if is_new else "updated",
166
- source="agent_add",
167
- )
168
-
169
- return {
170
- "name": name,
171
- "installed": str(installed_path),
172
- "is_new_page": is_new,
173
- "skipped": False,
174
- "update_required": False,
175
- "queued_job_id": queue_job.id,
176
- }
177
 
178
 
179
  # ── CLI ───────────────────────────────────────────────────────────────
@@ -186,16 +217,16 @@ def main() -> None:
186
  "--scan-dir",
187
  help="Directory of agent .md files to batch-add (non-recursive)",
188
  )
189
- parser.add_argument(
190
- "--skip-existing",
191
- action="store_true",
192
- help="Skip agents already installed (prevents overwrites)",
193
- )
194
- parser.add_argument(
195
- "--update-existing",
196
- action="store_true",
197
- help="Apply the reviewed replacement when an agent already exists",
198
- )
199
  parser.add_argument("--wiki", default=str(cfg.wiki_dir), help="Wiki path")
200
  parser.add_argument(
201
  "--agents-dir",
@@ -245,7 +276,7 @@ def main() -> None:
245
  print(f"No agent .md files found under {scan_root}.", file=sys.stderr)
246
  sys.exit(0)
247
 
248
- added = updated = skipped = rejected = errors = 0
249
  total = len(candidates)
250
  for i, (source_path, name) in enumerate(candidates, 1):
251
  if args.skip_existing and (agents_dir / f"{name}.md").exists():
@@ -254,27 +285,27 @@ def main() -> None:
254
  print(f" [{i}/{total}] [skipped] {name}")
255
  continue
256
  try:
257
- result = add_agent(
258
- source_path=source_path,
259
- name=name,
260
- wiki_path=wiki_path,
261
- agents_dir=agents_dir,
262
- review_existing=True,
263
- update_existing=args.update_existing,
264
- )
265
- if result.get("skipped"):
266
- skipped += 1
267
- if result.get("update_review"):
268
- print(result["update_review"])
269
- print(f" [{i}/{total}] [update-review] {name}")
270
- continue
271
- if result["is_new_page"]:
272
- added += 1
273
- status = "installed"
274
- else:
275
- updated += 1
276
- status = "updated"
277
- print(f" [{i}/{total}] [{status}] {name}")
278
  except IntakeRejected as exc:
279
  rejected += 1
280
  codes = ", ".join(f.code for f in exc.decision.failures) or "unknown"
@@ -283,10 +314,10 @@ def main() -> None:
283
  errors += 1
284
  print(f" [{i}/{total}] ERROR: {name}: {exc}", file=sys.stderr)
285
 
286
- print(
287
- f"\nDone: {added} added, {updated} updated, {skipped} skipped, "
288
- f"{rejected} rejected, {errors} errors"
289
- )
290
 
291
 
292
  if __name__ == "__main__":
 
24
  import os
25
  import sys
26
  from datetime import datetime, timezone
27
+ from pathlib import Path
28
+
29
+ from ctx.core.entity_update import build_update_review, render_update_review
30
+ from ctx_config import cfg
31
+ from ctx.adapters.claude_code.install.install_utils import safe_copy_file
32
+ from intake_pipeline import IntakeRejected, check_intake, record_embedding
33
+ from wiki_batch_entities import generate_agent_page
34
+ from ctx.core.wiki.wiki_queue import enqueue_entity_upsert
35
+ from ctx.core.wiki.wiki_sync import append_log, ensure_wiki, update_index
36
+ from ctx.core.wiki.wiki_utils import validate_skill_name
37
+ from ctx.utils._fs_utils import reject_symlink_path, safe_atomic_write_text
38
 
39
  TODAY = datetime.now(timezone.utc).strftime("%Y-%m-%d")
40
 
 
53
  return dest
54
 
55
 
56
+ def mirror_agent_body(installed_path: Path, wiki_path: Path, name: str) -> Path:
57
+ """Mirror the installed agent body into the wiki install source tree."""
58
+ mirror_root = wiki_path / "converted-agents"
59
+ dest = mirror_root / f"{name}.md"
60
+ safe_copy_file(installed_path, dest, dest_root=mirror_root)
61
+ return dest
62
+
63
+
64
+ def write_entity_page(wiki_path: Path, name: str, content: str) -> bool:
65
+ """Write agent entity page. Returns True if newly created."""
66
+ page = wiki_path / "entities" / "agents" / f"{name}.md"
67
+ reject_symlink_path(page)
68
+ is_new = not page.exists()
69
+ safe_atomic_write_text(page, content, encoding="utf-8")
70
+ return is_new
71
+
72
+
73
+ def _existing_agent_review_text(entity_page: Path, installed_path: Path) -> str:
74
+ if entity_page.exists():
75
+ existing = entity_page.read_text(encoding="utf-8", errors="replace")
76
+ if installed_path.exists():
77
+ installed = installed_path.read_text(encoding="utf-8", errors="replace")
78
+ existing += f"\n\n## Installed agent definition\n\n{installed}"
79
+ return existing
80
+ return installed_path.read_text(encoding="utf-8", errors="replace")
81
+
82
+
83
+ def _proposed_agent_review_text(
84
+ *,
85
+ name: str,
86
+ source_path: Path,
87
+ source_content: str,
88
+ ) -> str:
89
+ page_content = generate_agent_page(name, source_path)
90
+ return f"{page_content}\n\n## Proposed agent definition\n\n{source_content}"
91
+
92
+
93
+ def add_agent(
94
+ *,
95
+ source_path: Path,
96
+ name: str,
97
+ wiki_path: Path,
98
+ agents_dir: Path,
99
+ review_existing: bool = False,
100
+ update_existing: bool = False,
101
+ ) -> dict:
102
  """Add a single agent: validate, gate, install, ingest, log.
103
 
104
  Returns a result dict with keys: name, installed, is_new_page.
 
111
  f"agent file too large ({file_size:,} bytes). Max "
112
  f"{_MAX_AGENT_BYTES:,}. Trim before ingestion."
113
  )
114
+
115
+ content = source_path.read_text(encoding="utf-8", errors="replace")
116
+ line_count = len(content.splitlines())
117
+
118
+ installed_path = agents_dir / f"{name}.md"
119
+ entity_page = wiki_path / "entities" / "agents" / f"{name}.md"
120
+ existing_path = (
121
+ installed_path
122
+ if installed_path.exists()
123
+ else entity_page if entity_page.exists() else None
124
+ )
125
+ has_existing = existing_path is not None
126
+
127
+ if review_existing and has_existing and not update_existing:
128
+ review = build_update_review(
129
+ entity_type="agent",
130
+ slug=name,
131
+ existing_text=_existing_agent_review_text(entity_page, installed_path),
132
+ proposed_text=_proposed_agent_review_text(
133
+ name=name,
134
+ source_path=source_path,
135
+ source_content=content,
136
+ ),
137
+ )
138
+ return {
139
+ "name": name,
140
+ "installed": str(installed_path),
141
+ "is_new_page": False,
142
+ "skipped": True,
143
+ "update_required": True,
144
+ "update_review": render_update_review(review),
145
+ }
146
+
147
+ decision = None
148
+ if not has_existing:
149
+ # Intake gate: reject broken/duplicate agents before we install.
150
+ # Existing updates bypass similarity intake because they compare
151
+ # against their own cached embedding.
152
+ decision = check_intake(content, "agents")
153
+ if not decision.allow:
154
+ raise IntakeRejected(decision)
155
+
156
+ # 1. Install into agents-dir.
157
+ installed_path = install_agent(source_path, agents_dir, name)
158
+ mirror_agent_body(installed_path, wiki_path, name)
159
 
160
  # 2. Record embedding. Non-fatal on failure — install already
161
  # succeeded and a missing vector only weakens the next check.
 
181
  f"Installed: {installed_path}",
182
  f"Lines: {line_count}",
183
  ]
184
+ warnings = decision.warnings if decision is not None else ()
185
+ if warnings:
186
+ log_details.append(
187
+ "Warnings: " + "; ".join(f"{w.code}:{w.message}" for w in warnings)
188
+ )
189
+ append_log(str(wiki_path), "add-agent", name, log_details)
190
+ queue_job = enqueue_entity_upsert(
191
+ wiki_path,
192
+ entity_type="agent",
193
+ slug=name,
194
+ entity_path=wiki_path / "entities" / "agents" / f"{name}.md",
195
+ content=page_content,
196
+ action="created" if is_new else "updated",
197
+ source="agent_add",
198
+ )
199
+
200
+ return {
201
+ "name": name,
202
+ "installed": str(installed_path),
203
+ "is_new_page": is_new,
204
+ "skipped": False,
205
+ "update_required": False,
206
+ "queued_job_id": queue_job.id,
207
+ }
208
 
209
 
210
  # ── CLI ───────────────────────────────────────────────────────────────
 
217
  "--scan-dir",
218
  help="Directory of agent .md files to batch-add (non-recursive)",
219
  )
220
+ parser.add_argument(
221
+ "--skip-existing",
222
+ action="store_true",
223
+ help="Skip agents already installed (prevents overwrites)",
224
+ )
225
+ parser.add_argument(
226
+ "--update-existing",
227
+ action="store_true",
228
+ help="Apply the reviewed replacement when an agent already exists",
229
+ )
230
  parser.add_argument("--wiki", default=str(cfg.wiki_dir), help="Wiki path")
231
  parser.add_argument(
232
  "--agents-dir",
 
276
  print(f"No agent .md files found under {scan_root}.", file=sys.stderr)
277
  sys.exit(0)
278
 
279
+ added = updated = skipped = rejected = errors = 0
280
  total = len(candidates)
281
  for i, (source_path, name) in enumerate(candidates, 1):
282
  if args.skip_existing and (agents_dir / f"{name}.md").exists():
 
285
  print(f" [{i}/{total}] [skipped] {name}")
286
  continue
287
  try:
288
+ result = add_agent(
289
+ source_path=source_path,
290
+ name=name,
291
+ wiki_path=wiki_path,
292
+ agents_dir=agents_dir,
293
+ review_existing=True,
294
+ update_existing=args.update_existing,
295
+ )
296
+ if result.get("skipped"):
297
+ skipped += 1
298
+ if result.get("update_review"):
299
+ print(result["update_review"])
300
+ print(f" [{i}/{total}] [update-review] {name}")
301
+ continue
302
+ if result["is_new_page"]:
303
+ added += 1
304
+ status = "installed"
305
+ else:
306
+ updated += 1
307
+ status = "updated"
308
+ print(f" [{i}/{total}] [{status}] {name}")
309
  except IntakeRejected as exc:
310
  rejected += 1
311
  codes = ", ".join(f.code for f in exc.decision.failures) or "unknown"
 
314
  errors += 1
315
  print(f" [{i}/{total}] ERROR: {name}: {exc}", file=sys.stderr)
316
 
317
+ print(
318
+ f"\nDone: {added} added, {updated} updated, {skipped} skipped, "
319
+ f"{rejected} rejected, {errors} errors"
320
+ )
321
 
322
 
323
  if __name__ == "__main__":
src/backup_mirror.py CHANGED
@@ -370,12 +370,16 @@ def create_snapshot(backups_dir: Path | None = None,
370
  for src in _iter_tree(src_rel):
371
  rel = src.relative_to(root)
372
  dest_rel_path = Path(dest_rel) / rel
 
 
373
  entries.append(_capture_file(src, tmp_path, dest_rel_path.as_posix()))
374
 
375
  for slug, src in _iter_memory_files():
376
  memory_root = claude_home / "projects" / slug / "memory"
377
  rel = src.relative_to(memory_root)
378
  dest_rel_path = Path("memory") / slug / rel
 
 
379
  entries.append(_capture_file(src, tmp_path, dest_rel_path.as_posix()))
380
 
381
  manifest = {
 
370
  for src in _iter_tree(src_rel):
371
  rel = src.relative_to(root)
372
  dest_rel_path = Path(dest_rel) / rel
373
+ if _CFG.is_excluded(dest_rel_path.as_posix()):
374
+ continue
375
  entries.append(_capture_file(src, tmp_path, dest_rel_path.as_posix()))
376
 
377
  for slug, src in _iter_memory_files():
378
  memory_root = claude_home / "projects" / slug / "memory"
379
  rel = src.relative_to(memory_root)
380
  dest_rel_path = Path("memory") / slug / rel
381
+ if _CFG.is_excluded(dest_rel_path.as_posix()):
382
+ continue
383
  entries.append(_capture_file(src, tmp_path, dest_rel_path.as_posix()))
384
 
385
  manifest = {
src/ctx/__init__.py CHANGED
@@ -30,7 +30,7 @@ Package layout:
30
  ctx.utils - low-level primitives (safe names, atomic IO)
31
  """
32
 
33
- __version__ = "1.0.9"
34
 
35
 
36
  # Public library surface — anything listed here is safe for third-
 
30
  ctx.utils - low-level primitives (safe names, atomic IO)
31
  """
32
 
33
+ __version__ = "1.0.11"
34
 
35
 
36
  # Public library surface — anything listed here is safe for third-
src/ctx/adapters/claude_code/hooks/context_monitor.py CHANGED
@@ -250,7 +250,7 @@ def graph_suggest(
250
  query=" ".join(unmatched_tags),
251
  entity_types=("skill", "agent", "mcp-server"),
252
  min_normalized_score=min_score,
253
- use_semantic_query=True,
254
  )
255
  except Exception as exc:
256
  print(f"Warning: graph suggest error: {exc}", file=sys.stderr)
 
250
  query=" ".join(unmatched_tags),
251
  entity_types=("skill", "agent", "mcp-server"),
252
  min_normalized_score=min_score,
253
+ use_semantic_query=False,
254
  )
255
  except Exception as exc:
256
  print(f"Warning: graph suggest error: {exc}", file=sys.stderr)
src/ctx/adapters/claude_code/inject_hooks.py CHANGED
@@ -12,13 +12,13 @@ Usage:
12
  """
13
 
14
  import argparse
15
- import json
16
- import os
17
- import shlex
18
- import subprocess
19
- import sys
20
- import tempfile
21
- from pathlib import Path
22
 
23
 
24
  def load_settings(path: Path) -> dict:
@@ -31,11 +31,11 @@ def load_settings(path: Path) -> dict:
31
  return {}
32
 
33
 
34
- def make_hooks(ctx_dir: str) -> dict:
35
- """Return the hooks config block for this installation."""
36
- _ = ctx_dir # Kept for CLI/API compatibility; commands now use modules.
37
- # Commands are quoted for the host OS so Python paths with spaces do not
38
- # break the hook shell/command runner.
39
  # Tool input is delivered by Claude Code on stdin as JSON; --from-stdin reads it
40
  # from there instead of interpolating $CLAUDE_TOOL_INPUT into argv (which would
41
  # allow shell injection via malicious tool-input blobs).
@@ -113,12 +113,12 @@ def make_hooks(ctx_dir: str) -> dict:
113
 
114
 
115
  # Old filenames that were renamed — remove stale hook entries referencing them
116
- def _module_cmd(module: str, *args: str) -> str:
117
- """Return a hook command that targets an installed Python module."""
118
- parts = [sys.executable, "-m", module, *args]
119
- if os.name == "nt":
120
- return subprocess.list2cmdline(parts)
121
- return " ".join(shlex.quote(part) for part in parts)
122
 
123
 
124
  _STALE_PATTERNS = ["context-monitor.py", "usage-tracker.py", "skill-transformer.py"]
@@ -173,10 +173,40 @@ def merge_hooks(existing: dict, new_hooks: dict) -> dict:
173
  new_cmd = new_entry.get("command", "")
174
  new_hooks_list = new_entry.get("hooks", [])
175
 
176
- # Check if any command in this entry already exists
177
- new_cmds = {new_cmd} if new_cmd else {h.get("command", "") for h in new_hooks_list}
178
- if not new_cmds.intersection(existing_commands):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  existing_list.append(new_entry)
 
180
 
181
  return existing
182
 
 
12
  """
13
 
14
  import argparse
15
+ import json
16
+ import os
17
+ import shlex
18
+ import subprocess
19
+ import sys
20
+ import tempfile
21
+ from pathlib import Path
22
 
23
 
24
  def load_settings(path: Path) -> dict:
 
31
  return {}
32
 
33
 
34
+ def make_hooks(ctx_dir: str) -> dict:
35
+ """Return the hooks config block for this installation."""
36
+ _ = ctx_dir # Kept for CLI/API compatibility; commands now use modules.
37
+ # Commands are quoted for the host OS so Python paths with spaces do not
38
+ # break the hook shell/command runner.
39
  # Tool input is delivered by Claude Code on stdin as JSON; --from-stdin reads it
40
  # from there instead of interpolating $CLAUDE_TOOL_INPUT into argv (which would
41
  # allow shell injection via malicious tool-input blobs).
 
113
 
114
 
115
  # Old filenames that were renamed — remove stale hook entries referencing them
116
+ def _module_cmd(module: str, *args: str) -> str:
117
+ """Return a hook command that targets an installed Python module."""
118
+ parts = [sys.executable, "-m", module, *args]
119
+ if os.name == "nt":
120
+ return subprocess.list2cmdline(parts)
121
+ return " ".join(shlex.quote(part) for part in parts)
122
 
123
 
124
  _STALE_PATTERNS = ["context-monitor.py", "usage-tracker.py", "skill-transformer.py"]
 
173
  new_cmd = new_entry.get("command", "")
174
  new_hooks_list = new_entry.get("hooks", [])
175
 
176
+ if isinstance(new_hooks_list, list) and new_hooks_list:
177
+ missing_hooks = [
178
+ hook for hook in new_hooks_list
179
+ if isinstance(hook, dict)
180
+ and hook.get("command")
181
+ and hook.get("command") not in existing_commands
182
+ ]
183
+ if not missing_hooks:
184
+ continue
185
+ matcher = new_entry.get("matcher")
186
+ target_entry = next(
187
+ (
188
+ entry for entry in existing_list
189
+ if isinstance(entry, dict)
190
+ and entry.get("matcher") == matcher
191
+ and isinstance(entry.get("hooks"), list)
192
+ ),
193
+ None,
194
+ )
195
+ if target_entry is not None:
196
+ target_entry["hooks"].extend(missing_hooks)
197
+ else:
198
+ entry = dict(new_entry)
199
+ entry["hooks"] = missing_hooks
200
+ existing_list.append(entry)
201
+ existing_commands.update(
202
+ hook["command"] for hook in missing_hooks
203
+ if isinstance(hook.get("command"), str)
204
+ )
205
+ continue
206
+
207
+ if new_cmd and new_cmd not in existing_commands:
208
  existing_list.append(new_entry)
209
+ existing_commands.add(new_cmd)
210
 
211
  return existing
212
 
src/ctx/adapters/claude_code/install/install_utils.py CHANGED
@@ -29,12 +29,12 @@ from __future__ import annotations
29
 
30
  import json
31
  import logging
32
- import os
33
  import re
34
  import shutil
35
  from pathlib import Path
36
  from typing import Callable, Literal
37
 
 
38
  from ctx.utils._fs_utils import atomic_write_text as _atomic_write_text
39
  from ctx.utils._file_lock import file_lock
40
 
@@ -42,19 +42,19 @@ _logger = logging.getLogger(__name__)
42
 
43
  EntityType = Literal["skill", "agent", "mcp-server"]
44
 
45
- MANIFEST_PATH = Path(os.path.expanduser("~/.claude/skill-manifest.json"))
46
-
47
- _FRONTMATTER_HEAD_RE = re.compile(r"^---\n(.*?)\n---\n", re.DOTALL)
48
-
49
-
50
- def _has_symlink_in_path(path: Path) -> bool:
51
- return any(candidate.is_symlink() for candidate in (path, *path.parents))
52
-
53
-
54
- def safe_copy_file(source: Path, dest: Path, *, dest_root: Path) -> None:
55
- """Copy one file while refusing symlink write-through paths."""
56
- if _has_symlink_in_path(source):
57
- raise ValueError(f"refusing to copy symlinked source: {source}")
58
  if not source.is_file():
59
  raise FileNotFoundError(f"copy source missing: {source}")
60
  if dest_root.exists() and dest_root.is_symlink():
@@ -134,18 +134,37 @@ def record_install(
134
  when an agent with the same slug already existed.)
135
  """
136
  def mutate(manifest: dict) -> None:
137
- loaded: set[tuple[str, str]] = {
138
- (e.get("skill"), e.get("entity_type", "skill"))
139
- for e in manifest["load"]
 
140
  }
141
- if (slug, entity_type) not in loaded:
142
- entry: dict = {
143
- "skill": slug,
144
- "entity_type": entity_type,
145
- "source": source,
146
- }
147
- if extra:
148
- entry.update(extra)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  manifest["load"].append(entry)
150
 
151
  manifest["unload"] = [
@@ -159,59 +178,59 @@ def record_install(
159
  _update_manifest(mutate)
160
 
161
 
162
- def record_uninstall(slug: str, *, entity_type: EntityType, source: str) -> None:
163
  """Drop the load entry for ``(slug, entity_type)`` and record an unload.
164
 
165
  The unload dedup also keys on (slug, entity_type); re-unloading
166
- the same pair doesn't produce duplicates.
167
- """
168
- def mutate(manifest: dict) -> None:
169
- removed_entry: dict | None = next(
170
- (
171
- e for e in manifest["load"]
172
- if (
173
- e.get("skill") == slug
174
- and e.get("entity_type", "skill") == entity_type
175
- )
176
- ),
177
- None,
178
- )
179
- manifest["load"] = [
180
- e for e in manifest["load"]
181
- if not (
182
- e.get("skill") == slug
183
- and e.get("entity_type", "skill") == entity_type
184
  )
185
  ]
186
- unloaded: set[tuple[str, str]] = {
187
- (e.get("skill"), e.get("entity_type", "skill"))
188
- for e in manifest["unload"]
189
- }
190
- preserved: dict[str, object] = {}
191
- if removed_entry:
192
- for field in ("command", "json_config", "priority", "reason"):
193
- value = removed_entry.get(field)
194
- if value not in (None, ""):
195
- preserved[field] = value
196
- if (slug, entity_type) not in unloaded:
197
- entry: dict[str, object] = {
198
- "skill": slug,
199
- "entity_type": entity_type,
200
- "source": source,
201
- }
202
- entry.update(preserved)
203
- manifest["unload"].append(entry)
204
- elif preserved:
205
- for entry in manifest["unload"]:
206
- if (
207
- entry.get("skill") == slug
208
- and entry.get("entity_type", "skill") == entity_type
209
- ):
210
- for field, value in preserved.items():
211
- entry.setdefault(field, value)
212
- break
213
-
214
- _update_manifest(mutate)
215
 
216
 
217
  # ── Entity status frontmatter ────────────────────────────────────────────────
@@ -297,9 +316,9 @@ def _render_scalar(value: object) -> str:
297
  # The full set mirrors the YAML 1.1 reserved-indicator table:
298
  # flow indicators (,[]{}), block/map indicators (:?-), anchor/
299
  # alias (&*), tag (!), pipe/fold (|>), comment (#), directive (%),
300
- # reserved (@`), both quote marks, and ``<`` so bare ``<<`` is
301
- # never resolved as YAML's merge tag.
302
- yaml_structural = set(",[]{}:?#&*!|>%@`=\"'\\<")
303
  needs_quote = (
304
  any(ch in safe for ch in yaml_structural)
305
  or (safe and (safe[0] == "-" or safe[0].isspace() or safe[-1].isspace()))
 
29
 
30
  import json
31
  import logging
 
32
  import re
33
  import shutil
34
  from pathlib import Path
35
  from typing import Callable, Literal
36
 
37
+ from ctx_config import cfg
38
  from ctx.utils._fs_utils import atomic_write_text as _atomic_write_text
39
  from ctx.utils._file_lock import file_lock
40
 
 
42
 
43
  EntityType = Literal["skill", "agent", "mcp-server"]
44
 
45
+ MANIFEST_PATH = cfg.skill_manifest
46
+
47
+ _FRONTMATTER_HEAD_RE = re.compile(r"^---\n(.*?)\n---\n", re.DOTALL)
48
+
49
+
50
+ def _has_symlink_in_path(path: Path) -> bool:
51
+ return any(candidate.is_symlink() for candidate in (path, *path.parents))
52
+
53
+
54
+ def safe_copy_file(source: Path, dest: Path, *, dest_root: Path) -> None:
55
+ """Copy one file while refusing symlink write-through paths."""
56
+ if _has_symlink_in_path(source):
57
+ raise ValueError(f"refusing to copy symlinked source: {source}")
58
  if not source.is_file():
59
  raise FileNotFoundError(f"copy source missing: {source}")
60
  if dest_root.exists() and dest_root.is_symlink():
 
134
  when an agent with the same slug already existed.)
135
  """
136
  def mutate(manifest: dict) -> None:
137
+ entry: dict = {
138
+ "skill": slug,
139
+ "entity_type": entity_type,
140
+ "source": source,
141
  }
142
+ if extra:
143
+ entry.update(extra)
144
+
145
+ replaced = False
146
+ stale_extra_fields = {
147
+ "command",
148
+ "json_config_sha256",
149
+ "json_config_keys",
150
+ "json_config_command",
151
+ "json_config_args_count",
152
+ "json_config_env_keys",
153
+ "priority",
154
+ "reason",
155
+ }
156
+ for existing in manifest["load"]:
157
+ if (
158
+ existing.get("skill") == slug
159
+ and existing.get("entity_type", "skill") == entity_type
160
+ ):
161
+ for field in stale_extra_fields - set(entry):
162
+ existing.pop(field, None)
163
+ existing.update(entry)
164
+ replaced = True
165
+ break
166
+
167
+ if not replaced:
168
  manifest["load"].append(entry)
169
 
170
  manifest["unload"] = [
 
178
  _update_manifest(mutate)
179
 
180
 
181
+ def record_uninstall(slug: str, *, entity_type: EntityType, source: str) -> None:
182
  """Drop the load entry for ``(slug, entity_type)`` and record an unload.
183
 
184
  The unload dedup also keys on (slug, entity_type); re-unloading
185
+ the same pair doesn't produce duplicates.
186
+ """
187
+ def mutate(manifest: dict) -> None:
188
+ removed_entry: dict | None = next(
189
+ (
190
+ e for e in manifest["load"]
191
+ if (
192
+ e.get("skill") == slug
193
+ and e.get("entity_type", "skill") == entity_type
194
+ )
195
+ ),
196
+ None,
197
+ )
198
+ manifest["load"] = [
199
+ e for e in manifest["load"]
200
+ if not (
201
+ e.get("skill") == slug
202
+ and e.get("entity_type", "skill") == entity_type
203
  )
204
  ]
205
+ unloaded: set[tuple[str, str]] = {
206
+ (e.get("skill"), e.get("entity_type", "skill"))
207
+ for e in manifest["unload"]
208
+ }
209
+ preserved: dict[str, object] = {}
210
+ if removed_entry:
211
+ for field in ("command", "json_config", "priority", "reason"):
212
+ value = removed_entry.get(field)
213
+ if value not in (None, ""):
214
+ preserved[field] = value
215
+ if (slug, entity_type) not in unloaded:
216
+ entry: dict[str, object] = {
217
+ "skill": slug,
218
+ "entity_type": entity_type,
219
+ "source": source,
220
+ }
221
+ entry.update(preserved)
222
+ manifest["unload"].append(entry)
223
+ elif preserved:
224
+ for entry in manifest["unload"]:
225
+ if (
226
+ entry.get("skill") == slug
227
+ and entry.get("entity_type", "skill") == entity_type
228
+ ):
229
+ for field, value in preserved.items():
230
+ entry.setdefault(field, value)
231
+ break
232
+
233
+ _update_manifest(mutate)
234
 
235
 
236
  # ── Entity status frontmatter ────────────────────────────────────────────────
 
316
  # The full set mirrors the YAML 1.1 reserved-indicator table:
317
  # flow indicators (,[]{}), block/map indicators (:?-), anchor/
318
  # alias (&*), tag (!), pipe/fold (|>), comment (#), directive (%),
319
+ # reserved (@`), both quote marks, and ``<`` so bare ``<<`` is
320
+ # never resolved as YAML's merge tag.
321
+ yaml_structural = set(",[]{}:?#&*!|>%@`=\"'\\<")
322
  needs_quote = (
323
  any(ch in safe for ch in yaml_structural)
324
  or (safe and (safe[0] == "-" or safe[0].isspace() or safe[-1].isspace()))
src/ctx/adapters/claude_code/install/mcp_install.py CHANGED
@@ -59,6 +59,7 @@ from pathlib import Path
59
  from ctx_config import cfg
60
  from ctx.adapters.claude_code.install.install_utils import (
61
  bump_entity_status,
 
62
  record_install,
63
  record_uninstall,
64
  )
@@ -103,6 +104,7 @@ _BANNED_INTERPRETER_ARGS: dict[str, frozenset[str]] = {
103
  # npx / uvx / bunx intentionally unrestricted — they ARE the
104
  # package-launcher pattern MCP servers are expected to use.
105
  }
 
106
 
107
  _SECRET_KEY_MARKERS: tuple[str, ...] = (
108
  "token",
@@ -141,7 +143,7 @@ def _rejects_banned_args(tokens: list[str]) -> str | None:
141
  for the rest."""
142
  if not tokens:
143
  return None
144
- exe = tokens[0]
145
  banned = _BANNED_INTERPRETER_ARGS.get(exe)
146
  if banned is None:
147
  return None
@@ -208,6 +210,42 @@ def _find_inline_secret(obj: object, *, path: str = "") -> str | None:
208
  return None
209
 
210
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
  def _redact_output(text: str) -> str:
212
  if not text:
213
  return text
@@ -427,6 +465,16 @@ def install_mcp(
427
  existing_status = fm.get("status", "")
428
 
429
  if existing_status == "installed" and not force:
 
 
 
 
 
 
 
 
 
 
430
  return InstallResult(
431
  slug=slug, status="skipped-existing", command=None,
432
  message="already installed; pass --force to reinstall",
@@ -469,6 +517,25 @@ def install_mcp(
469
  ),
470
  )
471
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
472
  card = render_card(fm, slug, command=effective_cmd)
473
  print(card)
474
 
@@ -489,13 +556,7 @@ def install_mcp(
489
  rc, stdout, stderr = _run_claude_mcp(["add-json", slug, json_config])
490
  else:
491
  assert effective_cmd is not None # narrowed by dry_run branch above
492
- try:
493
- tokens = _split_install_command(effective_cmd)
494
- except ValueError as exc:
495
- return InstallResult(
496
- slug=slug, status="invalid-cmd", command=effective_cmd,
497
- message=f"could not parse --cmd/install_cmd: {exc}",
498
- )
499
  if not tokens:
500
  return InstallResult(
501
  slug=slug, status="invalid-cmd", command=effective_cmd,
@@ -505,7 +566,8 @@ def install_mcp(
505
  # (which is under entity-file control); treat it as untrusted.
506
  # Only known MCP-runtime launchers are allowed — if your
507
  # server needs a bespoke runtime, add-json is the right path.
508
- if tokens[0] not in _ALLOWED_CMD_EXECS:
 
509
  return InstallResult(
510
  slug=slug, status="invalid-cmd", command=effective_cmd,
511
  message=(
@@ -592,9 +654,14 @@ def uninstall_mcp(
592
  )
593
 
594
  entity = _entity_path(wiki_dir, slug)
 
595
  if entity.is_file():
596
  fm = _parse_entity_frontmatter(entity)
597
- if fm.get("status", "") != "installed" and not force:
 
 
 
 
598
  return UninstallResult(
599
  slug=slug, status="not-installed",
600
  message="entity status is not 'installed'; pass --force to run claude mcp remove anyway",
@@ -628,6 +695,17 @@ def uninstall_mcp(
628
  )
629
 
630
 
 
 
 
 
 
 
 
 
 
 
 
631
  # ── CLIs ─────────────────────────────────────────────────────────────────────
632
 
633
 
 
59
  from ctx_config import cfg
60
  from ctx.adapters.claude_code.install.install_utils import (
61
  bump_entity_status,
62
+ load_manifest,
63
  record_install,
64
  record_uninstall,
65
  )
 
104
  # npx / uvx / bunx intentionally unrestricted — they ARE the
105
  # package-launcher pattern MCP servers are expected to use.
106
  }
107
+ _WINDOWS_EXEC_SUFFIXES = (".exe", ".cmd", ".bat", ".ps1")
108
 
109
  _SECRET_KEY_MARKERS: tuple[str, ...] = (
110
  "token",
 
143
  for the rest."""
144
  if not tokens:
145
  return None
146
+ exe = _normalized_executable(tokens[0])
147
  banned = _BANNED_INTERPRETER_ARGS.get(exe)
148
  if banned is None:
149
  return None
 
210
  return None
211
 
212
 
213
+ def _normalized_executable(value: str) -> str:
214
+ name = Path(value).name.lower()
215
+ for suffix in _WINDOWS_EXEC_SUFFIXES:
216
+ if name.endswith(suffix):
217
+ return name[: -len(suffix)]
218
+ return name
219
+
220
+
221
+ def _find_inline_secret_arg(tokens: list[str]) -> str | None:
222
+ for token in tokens:
223
+ assignment = _SECRET_ASSIGNMENT_RE.search(token)
224
+ if assignment and not _placeholder_secret_value(assignment.group(2)):
225
+ return assignment.group(1)
226
+ for pattern in _TOKEN_VALUE_PATTERNS:
227
+ if pattern.search(token):
228
+ return token
229
+ if token.startswith("--") and "=" in token:
230
+ key, value = token.split("=", 1)
231
+ if _secret_key_like(key) and not _placeholder_secret_value(value):
232
+ return key
233
+
234
+ for index, token in enumerate(tokens[:-1]):
235
+ if not token.startswith("-"):
236
+ continue
237
+ key = token.lstrip("-").replace("-", "_")
238
+ value = tokens[index + 1]
239
+ if (
240
+ _secret_key_like(key)
241
+ and value
242
+ and not value.startswith("-")
243
+ and not _placeholder_secret_value(value)
244
+ ):
245
+ return token
246
+ return None
247
+
248
+
249
  def _redact_output(text: str) -> str:
250
  if not text:
251
  return text
 
465
  existing_status = fm.get("status", "")
466
 
467
  if existing_status == "installed" and not force:
468
+ skipped_extra: dict[str, str] = {}
469
+ install_cmd = fm.get("install_cmd")
470
+ if isinstance(install_cmd, str) and install_cmd:
471
+ skipped_extra["command"] = install_cmd
472
+ record_install(
473
+ slug,
474
+ entity_type="mcp-server",
475
+ source="ctx-mcp-install",
476
+ extra=skipped_extra,
477
+ )
478
  return InstallResult(
479
  slug=slug, status="skipped-existing", command=None,
480
  message="already installed; pass --force to reinstall",
 
517
  ),
518
  )
519
 
520
+ command_tokens: list[str] | None = None
521
+ if effective_cmd:
522
+ try:
523
+ command_tokens = _split_install_command(effective_cmd)
524
+ except ValueError as exc:
525
+ return InstallResult(
526
+ slug=slug, status="invalid-cmd", command=effective_cmd,
527
+ message=f"could not parse --cmd/install_cmd: {exc}",
528
+ )
529
+ inline_secret_arg = _find_inline_secret_arg(command_tokens)
530
+ if inline_secret_arg is not None:
531
+ return InstallResult(
532
+ slug=slug, status="invalid-cmd", command=None,
533
+ message=(
534
+ f"--cmd/install_cmd argument {inline_secret_arg!r} looks like "
535
+ "an inline secret; pass an environment variable reference instead."
536
+ ),
537
+ )
538
+
539
  card = render_card(fm, slug, command=effective_cmd)
540
  print(card)
541
 
 
556
  rc, stdout, stderr = _run_claude_mcp(["add-json", slug, json_config])
557
  else:
558
  assert effective_cmd is not None # narrowed by dry_run branch above
559
+ tokens = command_tokens if command_tokens is not None else _split_install_command(effective_cmd)
 
 
 
 
 
 
560
  if not tokens:
561
  return InstallResult(
562
  slug=slug, status="invalid-cmd", command=effective_cmd,
 
566
  # (which is under entity-file control); treat it as untrusted.
567
  # Only known MCP-runtime launchers are allowed — if your
568
  # server needs a bespoke runtime, add-json is the right path.
569
+ executable = _normalized_executable(tokens[0])
570
+ if executable not in _ALLOWED_CMD_EXECS:
571
  return InstallResult(
572
  slug=slug, status="invalid-cmd", command=effective_cmd,
573
  message=(
 
654
  )
655
 
656
  entity = _entity_path(wiki_dir, slug)
657
+ manifest_entry = _manifest_load_entry(slug)
658
  if entity.is_file():
659
  fm = _parse_entity_frontmatter(entity)
660
+ if (
661
+ fm.get("status", "") != "installed"
662
+ and manifest_entry is None
663
+ and not force
664
+ ):
665
  return UninstallResult(
666
  slug=slug, status="not-installed",
667
  message="entity status is not 'installed'; pass --force to run claude mcp remove anyway",
 
695
  )
696
 
697
 
698
+ def _manifest_load_entry(slug: str) -> dict | None:
699
+ manifest = load_manifest()
700
+ for entry in manifest.get("load", []):
701
+ if (
702
+ entry.get("skill") == slug
703
+ and entry.get("entity_type", "skill") == "mcp-server"
704
+ ):
705
+ return entry
706
+ return None
707
+
708
+
709
  # ── CLIs ─────────────────────────────────────────────────────────────────────
710
 
711
 
src/ctx/adapters/claude_code/install/skill_install.py CHANGED
@@ -140,20 +140,26 @@ def _ensure_micro_converted(
140
  # ── Copy logic ───────────────────────────────────────────────────────────────
141
 
142
 
143
- def _copy_references(src_dir: Path, dest_dir: Path) -> int:
144
- """Copy every .md in ``src_dir/references/`` to ``dest_dir/references/``.
145
 
146
- Returns the number of reference files copied. Skips silently when no
147
- references dir exists in the wiki.
148
- """
149
- src_refs = src_dir / "references"
150
- if not src_refs.is_dir():
151
- return 0
152
- dest_refs = dest_dir / "references"
 
 
 
 
 
 
 
 
153
  copied = 0
154
- for md_file in sorted(src_refs.glob("*.md")):
155
- dest = dest_refs / md_file.name
156
- safe_copy_file(md_file, dest, dest_root=dest_dir)
157
  copied += 1
158
  return copied
159
 
@@ -174,7 +180,7 @@ def install_skill(
174
  1. Validated (slug passes ``validate_skill_name``).
175
  2. Sourced from the wiki (``converted/<slug>/SKILL.md``, with
176
  ``.original`` as fallback).
177
- 3. Copied to ``<skills_dir>/<slug>/SKILL.md`` plus any references.
178
  4. Mirrored into the skill manifest and the wiki entity's status
179
  frontmatter.
180
 
@@ -232,10 +238,7 @@ def install_skill(
232
  )
233
 
234
  if dry_run:
235
- refs_count = 0
236
- refs_dir = converted / "references"
237
- if refs_dir.is_dir():
238
- refs_count = sum(1 for _ in refs_dir.glob("*.md"))
239
  message = "dry-run: no files written"
240
  try:
241
  if _line_count(source) > cfg.line_threshold:
@@ -262,7 +265,7 @@ def install_skill(
262
 
263
  try:
264
  safe_copy_file(source, dest, dest_root=skills_dir)
265
- refs_copied = _copy_references(converted, dest_dir)
266
  except (OSError, ValueError) as exc:
267
  return InstallResult(
268
  slug=slug, status="failed", installed_path=None,
 
140
  # ── Copy logic ───────────────────────────────────────────────────────────────
141
 
142
 
143
+ _BUNDLE_DIR_NAMES = ("references", "reference", "resources", "scripts", "assets")
 
144
 
145
+
146
+ def _iter_bundle_files(src_dir: Path) -> list[tuple[Path, Path]]:
147
+ """Return ``(source, relative_destination)`` pairs for skill bundle files."""
148
+ files: list[tuple[Path, Path]] = []
149
+ for dirname in _BUNDLE_DIR_NAMES:
150
+ bundle_dir = src_dir / dirname
151
+ if not bundle_dir.is_dir():
152
+ continue
153
+ for source in sorted(path for path in bundle_dir.rglob("*") if path.is_file()):
154
+ files.append((source, source.relative_to(src_dir)))
155
+ return files
156
+
157
+
158
+ def _copy_bundle_files(src_dir: Path, dest_dir: Path) -> int:
159
+ """Copy bundled references/resources/scripts/assets into an install dir."""
160
  copied = 0
161
+ for source, relative in _iter_bundle_files(src_dir):
162
+ safe_copy_file(source, dest_dir / relative, dest_root=dest_dir)
 
163
  copied += 1
164
  return copied
165
 
 
180
  1. Validated (slug passes ``validate_skill_name``).
181
  2. Sourced from the wiki (``converted/<slug>/SKILL.md``, with
182
  ``.original`` as fallback).
183
+ 3. Copied to ``<skills_dir>/<slug>/SKILL.md`` plus bundled resources.
184
  4. Mirrored into the skill manifest and the wiki entity's status
185
  frontmatter.
186
 
 
238
  )
239
 
240
  if dry_run:
241
+ refs_count = len(_iter_bundle_files(converted))
 
 
 
242
  message = "dry-run: no files written"
243
  try:
244
  if _line_count(source) > cfg.line_threshold:
 
265
 
266
  try:
267
  safe_copy_file(source, dest, dest_root=skills_dir)
268
+ refs_copied = _copy_bundle_files(converted, dest_dir)
269
  except (OSError, ValueError) as exc:
270
  return InstallResult(
271
  slug=slug, status="failed", installed_path=None,
src/ctx/adapters/claude_code/install/skill_unload.py CHANGED
@@ -22,11 +22,12 @@ from pathlib import Path
22
  from ctx.core.wiki.wiki_utils import validate_skill_name
23
  from ctx.utils._file_lock import file_lock
24
  from ctx.utils._fs_utils import atomic_write_text as _atomic_write_text
 
25
 
26
- CLAUDE_DIR = Path(os.path.expanduser("~/.claude"))
27
- MANIFEST_PATH = CLAUDE_DIR / "skill-manifest.json"
28
  PENDING_UNLOAD = CLAUDE_DIR / "pending-unload.json"
29
- WIKI_DIR = CLAUDE_DIR / "skill-wiki"
30
  SKILL_ENTITIES = WIKI_DIR / "entities" / "skills"
31
  AGENT_ENTITIES = WIKI_DIR / "entities" / "agents"
32
 
 
22
  from ctx.core.wiki.wiki_utils import validate_skill_name
23
  from ctx.utils._file_lock import file_lock
24
  from ctx.utils._fs_utils import atomic_write_text as _atomic_write_text
25
+ from ctx_config import cfg
26
 
27
+ CLAUDE_DIR = cfg.claude_dir
28
+ MANIFEST_PATH = cfg.skill_manifest
29
  PENDING_UNLOAD = CLAUDE_DIR / "pending-unload.json"
30
+ WIKI_DIR = cfg.wiki_dir
31
  SKILL_ENTITIES = WIKI_DIR / "entities" / "skills"
32
  AGENT_ENTITIES = WIKI_DIR / "entities" / "agents"
33
 
src/ctx/adapters/claude_code/skill_health.py CHANGED
@@ -32,27 +32,26 @@ from __future__ import annotations
32
 
33
  import argparse
34
  import json
35
- import os
36
  import sys
37
  import time
38
  from dataclasses import asdict, dataclass, field
39
  from pathlib import Path
40
- from typing import Iterable, Sequence
41
-
42
- from ctx_config import cfg
43
- from ctx.utils._file_lock import file_lock
44
- from ctx.utils._fs_utils import atomic_write_text as _atomic_write
45
 
46
 
47
  # ── Paths & config defaults ────────────────────────────────────────────────
48
 
49
 
50
- SKILLS_DIR = Path(os.path.expanduser("~/.claude/skills"))
51
- AGENTS_DIR = Path(os.path.expanduser("~/.claude/agents"))
52
- MANIFEST_PATH = Path(os.path.expanduser("~/.claude/skill-manifest.json"))
53
- PENDING_PATH = Path(os.path.expanduser("~/.claude/pending-skills.json"))
54
-
55
- DEFAULT_LINE_THRESHOLD = cfg.line_threshold
56
  DEFAULT_MIN_BODY_LINES = 5
57
  ERROR_SEVERITIES = frozenset({"error"})
58
  _SEVERITY_RANK = {"ok": 0, "warning": 1, "error": 2}
 
32
 
33
  import argparse
34
  import json
 
35
  import sys
36
  import time
37
  from dataclasses import asdict, dataclass, field
38
  from pathlib import Path
39
+ from typing import Iterable, Sequence
40
+
41
+ from ctx_config import cfg
42
+ from ctx.utils._file_lock import file_lock
43
+ from ctx.utils._fs_utils import atomic_write_text as _atomic_write
44
 
45
 
46
  # ── Paths & config defaults ────────────────────────────────────────────────
47
 
48
 
49
+ SKILLS_DIR = cfg.skills_dir
50
+ AGENTS_DIR = cfg.agents_dir
51
+ MANIFEST_PATH = cfg.skill_manifest
52
+ PENDING_PATH = cfg.pending_skills
53
+
54
+ DEFAULT_LINE_THRESHOLD = cfg.line_threshold
55
  DEFAULT_MIN_BODY_LINES = 5
56
  ERROR_SEVERITIES = frozenset({"error"})
57
  _SEVERITY_RANK = {"ok": 0, "warning": 1, "error": 2}
src/ctx/adapters/claude_code/skill_loader.py CHANGED
@@ -16,12 +16,12 @@ Outputs the skill/agent content path so Claude can read and apply it.
16
  import argparse
17
  import json
18
  import logging
19
- import os
20
  import sys
21
  import uuid
22
  from pathlib import Path
23
  from typing import Any
24
 
 
25
  from ctx.core.wiki.wiki_utils import validate_skill_name
26
  from ctx.utils._file_lock import file_lock
27
  from ctx.utils._fs_utils import atomic_write_text as _atomic_write_text
@@ -32,11 +32,11 @@ _logger = logging.getLogger(__name__)
32
  _SESSION_ID: str = uuid.uuid4().hex
33
 
34
 
35
- SKILLS_DIR = Path(os.path.expanduser("~/.claude/skills"))
36
- AGENTS_DIR = Path(os.path.expanduser("~/.claude/agents"))
37
- WIKI_DIR = Path(os.path.expanduser("~/.claude/skill-wiki"))
38
- PENDING_SKILLS = Path(os.path.expanduser("~/.claude/pending-skills.json"))
39
- MANIFEST_PATH = Path(os.path.expanduser("~/.claude/skill-manifest.json"))
40
 
41
 
42
  def _resolved_under(candidate: Path, base: Path) -> bool:
 
16
  import argparse
17
  import json
18
  import logging
 
19
  import sys
20
  import uuid
21
  from pathlib import Path
22
  from typing import Any
23
 
24
+ from ctx_config import cfg
25
  from ctx.core.wiki.wiki_utils import validate_skill_name
26
  from ctx.utils._file_lock import file_lock
27
  from ctx.utils._fs_utils import atomic_write_text as _atomic_write_text
 
32
  _SESSION_ID: str = uuid.uuid4().hex
33
 
34
 
35
+ SKILLS_DIR = cfg.skills_dir
36
+ AGENTS_DIR = cfg.agents_dir
37
+ WIKI_DIR = cfg.wiki_dir
38
+ PENDING_SKILLS = cfg.pending_skills
39
+ MANIFEST_PATH = cfg.skill_manifest
40
 
41
 
42
  def _resolved_under(candidate: Path, base: Path) -> bool:
src/ctx/adapters/generic/ctx_core_tools.py CHANGED
@@ -159,6 +159,13 @@ class CtxCoreToolbox:
159
  "harness recommendations."
160
  ),
161
  },
 
 
 
 
 
 
 
162
  },
163
  "required": ["query"],
164
  },
@@ -313,7 +320,8 @@ class CtxCoreToolbox:
313
  )
314
 
315
  tags = _query_to_tags(query)
316
- if not tags:
 
317
  return json.dumps({
318
  "error": "query produced no usable tags",
319
  "results": [],
@@ -328,10 +336,10 @@ class CtxCoreToolbox:
328
 
329
  from ctx.core.resolve.recommendations import recommend_by_tags # noqa: PLC0415
330
 
331
- # Pass the original query through so the recommender can apply
332
- # semantic-similarity scoring (in addition to tag/slug-token).
333
- # Falls through silently if the embedding cache is missing.
334
- self._refresh_semantic_cache_signature()
335
  raw = recommend_by_tags(
336
  graph,
337
  tags,
@@ -339,7 +347,8 @@ class CtxCoreToolbox:
339
  query=query,
340
  entity_types=("skill", "agent", "mcp-server"),
341
  min_normalized_score=cfg.recommendation_min_normalized_score,
342
- use_semantic_query=True,
 
343
  )
344
  results = [
345
  {
@@ -722,6 +731,16 @@ def _wiki_pages_signature(wiki: Path) -> tuple[int, int, int]:
722
  def _semantic_cache_signature(
723
  wiki: Path | None,
724
  ) -> tuple[FileSignature | None, ...] | None:
 
 
 
 
 
 
 
 
 
 
725
  try:
726
  from ctx_config import cfg # noqa: PLC0415
727
 
@@ -734,10 +753,7 @@ def _semantic_cache_signature(
734
  default_cache = Path("~/.claude/skill-wiki/.embedding-cache/graph").expanduser()
735
  if wiki is not None and cache_dir == default_cache:
736
  cache_dir = wiki / ".embedding-cache" / "graph"
737
- return (
738
- _file_signature(cache_dir / "embeddings.npz"),
739
- _file_signature(cache_dir / "topk-state.json"),
740
- )
741
 
742
 
743
  def _query_to_tags(query: str) -> list[str]:
 
159
  "harness recommendations."
160
  ),
161
  },
162
+ "use_semantic_query": {
163
+ "type": "boolean",
164
+ "description": (
165
+ "Opt in to local embedding-based query scoring. "
166
+ "Default false keeps recommendations latency-safe."
167
+ ),
168
+ },
169
  },
170
  "required": ["query"],
171
  },
 
320
  )
321
 
322
  tags = _query_to_tags(query)
323
+ use_semantic_query = bool(args.get("use_semantic_query"))
324
+ if not tags and not use_semantic_query:
325
  return json.dumps({
326
  "error": "query produced no usable tags",
327
  "results": [],
 
336
 
337
  from ctx.core.resolve.recommendations import recommend_by_tags # noqa: PLC0415
338
 
339
+ semantic_cache_dir = None
340
+ if use_semantic_query:
341
+ self._refresh_semantic_cache_signature()
342
+ semantic_cache_dir = _semantic_cache_dir(self._wiki_dir_resolved())
343
  raw = recommend_by_tags(
344
  graph,
345
  tags,
 
347
  query=query,
348
  entity_types=("skill", "agent", "mcp-server"),
349
  min_normalized_score=cfg.recommendation_min_normalized_score,
350
+ use_semantic_query=use_semantic_query,
351
+ semantic_cache_dir=semantic_cache_dir,
352
  )
353
  results = [
354
  {
 
731
  def _semantic_cache_signature(
732
  wiki: Path | None,
733
  ) -> tuple[FileSignature | None, ...] | None:
734
+ cache_dir = _semantic_cache_dir(wiki)
735
+ if cache_dir is None:
736
+ return None
737
+ return (
738
+ _file_signature(cache_dir / "embeddings.npz"),
739
+ _file_signature(cache_dir / "topk-state.json"),
740
+ )
741
+
742
+
743
+ def _semantic_cache_dir(wiki: Path | None) -> Path | None:
744
  try:
745
  from ctx_config import cfg # noqa: PLC0415
746
 
 
753
  default_cache = Path("~/.claude/skill-wiki/.embedding-cache/graph").expanduser()
754
  if wiki is not None and cache_dir == default_cache:
755
  cache_dir = wiki / ".embedding-cache" / "graph"
756
+ return cache_dir
 
 
 
757
 
758
 
759
  def _query_to_tags(query: str) -> list[str]:
src/ctx/core/graph/entity_overlays.py CHANGED
@@ -36,19 +36,60 @@ _LIST_EDGE_ATTRS = frozenset(
36
  def active_overlay_records(records: Iterable[Mapping[str, Any]]) -> list[Mapping[str, Any]]:
37
  """Return deduped active records, superseding stale rows by scope."""
38
  by_attach_key: dict[str, Mapping[str, Any]] = {}
 
39
  for index, record in enumerate(records):
40
  if record.get("superseded_at"):
41
  continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  attach_key = overlay_attach_key(record, fallback_index=index)
43
- if attach_key not in by_attach_key:
44
- by_attach_key[attach_key] = record
 
45
 
46
- by_scope: dict[str, Mapping[str, Any]] = {}
47
- for index, record in enumerate(by_attach_key.values()):
48
  by_scope[overlay_replace_scope(record, fallback_index=index)] = record
49
  return list(by_scope.values())
50
 
51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  def overlay_attach_key(record: Mapping[str, Any], *, fallback_index: int = 0) -> str:
53
  for key in ("attach_key", "idempotency_key", "overlay_id"):
54
  value = record.get(key)
@@ -83,6 +124,16 @@ def merge_node_attrs(existing: Mapping[str, Any], incoming: Mapping[str, Any]) -
83
  return merged
84
 
85
 
 
 
 
 
 
 
 
 
 
 
86
  def merge_edge_attrs(existing: Mapping[str, Any], incoming: Mapping[str, Any]) -> dict[str, Any]:
87
  merged = dict(existing)
88
  for key, value in incoming.items():
@@ -99,6 +150,15 @@ def merge_edge_attrs(existing: Mapping[str, Any], incoming: Mapping[str, Any]) -
99
  return merged
100
 
101
 
 
 
 
 
 
 
 
 
 
102
  def load_overlay_records(path: Path) -> list[dict[str, Any]]:
103
  """Load JSONL overlay records for writer paths.
104
 
 
36
  def active_overlay_records(records: Iterable[Mapping[str, Any]]) -> list[Mapping[str, Any]]:
37
  """Return deduped active records, superseding stale rows by scope."""
38
  by_attach_key: dict[str, Mapping[str, Any]] = {}
39
+ by_scope: dict[str, Mapping[str, Any]] = {}
40
  for index, record in enumerate(records):
41
  if record.get("superseded_at"):
42
  continue
43
+ node_id = _record_node_id(record)
44
+ if _is_delete_record(record):
45
+ if node_id:
46
+ by_attach_key = {
47
+ key: value
48
+ for key, value in by_attach_key.items()
49
+ if _record_node_id(value) != node_id
50
+ }
51
+ by_scope = {
52
+ key: value
53
+ for key, value in by_scope.items()
54
+ if _record_node_id(value) != node_id
55
+ }
56
+ continue
57
  attach_key = overlay_attach_key(record, fallback_index=index)
58
+ if attach_key in by_attach_key:
59
+ continue
60
+ by_attach_key[attach_key] = record
61
 
 
 
62
  by_scope[overlay_replace_scope(record, fallback_index=index)] = record
63
  return list(by_scope.values())
64
 
65
 
66
+ def append_overlay_tombstone(path: Path, *, node_id: str, source: str) -> str:
67
+ """Append a delete tombstone so stale overlay nodes stay removed."""
68
+ if not node_id:
69
+ raise ValueError("node_id must be non-empty")
70
+ if not source:
71
+ raise ValueError("source must be non-empty")
72
+ with file_lock(path):
73
+ records = load_overlay_records(path)
74
+ if not records:
75
+ return "skipped"
76
+ records.append({
77
+ "action": "delete",
78
+ "node_id": node_id,
79
+ "source": source,
80
+ "deleted_at": _utc_now(),
81
+ })
82
+ write_overlay_records_atomic(path, records)
83
+ return "inserted"
84
+
85
+
86
+ def _is_delete_record(record: Mapping[str, Any]) -> bool:
87
+ action = record.get("action")
88
+ if isinstance(action, str) and action.strip().lower() in {"delete", "tombstone"}:
89
+ return True
90
+ return bool(record.get("tombstone"))
91
+
92
+
93
  def overlay_attach_key(record: Mapping[str, Any], *, fallback_index: int = 0) -> str:
94
  for key in ("attach_key", "idempotency_key", "overlay_id"):
95
  value = record.get(key)
 
124
  return merged
125
 
126
 
127
+ def replace_node_attrs(existing: Mapping[str, Any], incoming: Mapping[str, Any]) -> dict[str, Any]:
128
+ """Overlay incoming non-empty node attrs onto an existing node."""
129
+ merged = dict(existing)
130
+ for key, value in incoming.items():
131
+ if key == "id" or value in _EMPTY_VALUES:
132
+ continue
133
+ merged[key] = value
134
+ return merged
135
+
136
+
137
  def merge_edge_attrs(existing: Mapping[str, Any], incoming: Mapping[str, Any]) -> dict[str, Any]:
138
  merged = dict(existing)
139
  for key, value in incoming.items():
 
150
  return merged
151
 
152
 
153
+ def replace_edge_attrs(incoming: Mapping[str, Any]) -> dict[str, Any]:
154
+ """Return only the current non-empty edge attrs from an authoritative overlay."""
155
+ return {
156
+ key: value
157
+ for key, value in incoming.items()
158
+ if key not in {"source", "target"} and value not in _EMPTY_VALUES
159
+ }
160
+
161
+
162
  def load_overlay_records(path: Path) -> list[dict[str, Any]]:
163
  """Load JSONL overlay records for writer paths.
164
 
src/ctx/core/graph/incremental_attach.py CHANGED
@@ -15,11 +15,13 @@ from typing import Any, Iterable
15
  import networkx as nx
16
  import numpy as np
17
 
 
18
  from ctx.core.graph.entity_overlays import upsert_overlay_record
19
  from ctx.core.graph.vector_index import load_vector_index
20
 
21
  _PERCENTILES = (50, 60, 75, 90, 95)
22
- _DEFAULT_MIN_SEMANTIC_SCORE = 0.75
 
23
  _DEFAULT_MIN_FINAL_WEIGHT = 0.03
24
  _ATTACH_METHOD = "ann_attach_v1"
25
 
@@ -177,6 +179,7 @@ def attach_entity(
177
  model_id=resolved_model_id,
178
  created_at=now,
179
  candidates_considered=len(neighbors),
 
180
  neighbors=[
181
  {
182
  "node_id": neighbor.node_id,
@@ -184,7 +187,6 @@ def attach_entity(
184
  "rank": rank,
185
  }
186
  for rank, neighbor in enumerate(neighbors, 1)
187
- if float(neighbor.score) >= min_final_weight
188
  ],
189
  )
190
  status = "dry-run" if dry_run else upsert_overlay_record(overlay_path, record)
@@ -217,7 +219,7 @@ def main(argv: list[str] | None = None) -> int:
217
  attach.add_argument("--embedding-backend", default="sentence-transformers")
218
  attach.add_argument("--embedding-model")
219
  attach.add_argument("--top-k", type=int, default=20)
220
- attach.add_argument("--min-score", type=float, default=_DEFAULT_MIN_SEMANTIC_SCORE)
221
  attach.add_argument("--min-final-weight", type=float, default=_DEFAULT_MIN_FINAL_WEIGHT)
222
  attach.add_argument("--dry-run", action="store_true", help="Print the overlay record without writing")
223
  attach.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
@@ -245,7 +247,11 @@ def main(argv: list[str] | None = None) -> int:
245
  vector_json=args.vector_json,
246
  model_id=args.model_id,
247
  top_k=args.top_k,
248
- min_score=args.min_score,
 
 
 
 
249
  min_final_weight=args.min_final_weight,
250
  dry_run=args.dry_run,
251
  embedding_backend=args.embedding_backend,
@@ -274,6 +280,15 @@ def _resolve_text_input(text: str | None, text_file: str | None) -> str | None:
274
  raise ValueError(f"cannot read --text-file {path}") from exc
275
 
276
 
 
 
 
 
 
 
 
 
 
277
  def _read_index_meta(index_dir: Path) -> dict[str, Any]:
278
  meta_path = index_dir / "vector-index.meta.json"
279
  try:
@@ -340,25 +355,43 @@ def _build_attach_record(
340
  model_id: str,
341
  created_at: str,
342
  candidates_considered: int,
 
343
  neighbors: list[dict[str, Any]],
344
  ) -> dict[str, Any]:
345
  attach_key = f"ann:v1:{model_id}:{node_id}:{content_hash}"
346
  edges: list[dict[str, Any]] = []
347
  for neighbor in neighbors:
348
- score = float(neighbor["score"])
 
 
 
 
 
 
 
 
349
  edges.append(
350
  {
351
  "source": node_id,
352
  "target": neighbor["node_id"],
353
- "weight": score,
354
- "final_weight": score,
355
- "semantic_sim": score,
356
- "similarity_score": score,
 
 
357
  "method": _ATTACH_METHOD,
358
  "provenance": _ATTACH_METHOD,
359
  "rank": int(neighbor["rank"]),
360
  "candidates_considered": candidates_considered,
361
- "edge_reasons": ["semantic-ann"],
 
 
 
 
 
 
 
362
  "created_at": created_at,
363
  }
364
  )
@@ -398,6 +431,33 @@ def _slug_label(node_id: str) -> str:
398
  return node_id.split(":", 1)[-1]
399
 
400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
401
  def _utc_now() -> str:
402
  return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
403
 
 
15
  import networkx as nx
16
  import numpy as np
17
 
18
+ from ctx.core.graph.edge_scoring import type_affinity_score
19
  from ctx.core.graph.entity_overlays import upsert_overlay_record
20
  from ctx.core.graph.vector_index import load_vector_index
21
 
22
  _PERCENTILES = (50, 60, 75, 90, 95)
23
+ _DEFAULT_MIN_SEMANTIC_SCORE = 0.80
24
+ _DEFAULT_SEMANTIC_BUILD_FLOOR = 0.50
25
  _DEFAULT_MIN_FINAL_WEIGHT = 0.03
26
  _ATTACH_METHOD = "ann_attach_v1"
27
 
 
179
  model_id=resolved_model_id,
180
  created_at=now,
181
  candidates_considered=len(neighbors),
182
+ min_final_weight=min_final_weight,
183
  neighbors=[
184
  {
185
  "node_id": neighbor.node_id,
 
187
  "rank": rank,
188
  }
189
  for rank, neighbor in enumerate(neighbors, 1)
 
190
  ],
191
  )
192
  status = "dry-run" if dry_run else upsert_overlay_record(overlay_path, record)
 
219
  attach.add_argument("--embedding-backend", default="sentence-transformers")
220
  attach.add_argument("--embedding-model")
221
  attach.add_argument("--top-k", type=int, default=20)
222
+ attach.add_argument("--min-score", type=float)
223
  attach.add_argument("--min-final-weight", type=float, default=_DEFAULT_MIN_FINAL_WEIGHT)
224
  attach.add_argument("--dry-run", action="store_true", help="Print the overlay record without writing")
225
  attach.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
 
247
  vector_json=args.vector_json,
248
  model_id=args.model_id,
249
  top_k=args.top_k,
250
+ min_score=(
251
+ args.min_score
252
+ if args.min_score is not None
253
+ else _default_min_semantic_score()
254
+ ),
255
  min_final_weight=args.min_final_weight,
256
  dry_run=args.dry_run,
257
  embedding_backend=args.embedding_backend,
 
280
  raise ValueError(f"cannot read --text-file {path}") from exc
281
 
282
 
283
+ def _default_min_semantic_score() -> float:
284
+ try:
285
+ from ctx_config import cfg # noqa: PLC0415
286
+
287
+ return float(cfg.graph_semantic_build_floor)
288
+ except Exception: # pragma: no cover - standalone CLI fallback.
289
+ return _DEFAULT_SEMANTIC_BUILD_FLOOR
290
+
291
+
292
  def _read_index_meta(index_dir: Path) -> dict[str, Any]:
293
  meta_path = index_dir / "vector-index.meta.json"
294
  try:
 
355
  model_id: str,
356
  created_at: str,
357
  candidates_considered: int,
358
+ min_final_weight: float,
359
  neighbors: list[dict[str, Any]],
360
  ) -> dict[str, Any]:
361
  attach_key = f"ann:v1:{model_id}:{node_id}:{content_hash}"
362
  edges: list[dict[str, Any]] = []
363
  for neighbor in neighbors:
364
+ semantic = float(neighbor["score"])
365
+ target_type = _node_type_from_id(str(neighbor["node_id"]))
366
+ type_affinity = type_affinity_score(entity_type, target_type)
367
+ final, components = _blend_ann_score(
368
+ semantic=semantic,
369
+ type_affinity=type_affinity,
370
+ )
371
+ if final < min_final_weight:
372
+ continue
373
  edges.append(
374
  {
375
  "source": node_id,
376
  "target": neighbor["node_id"],
377
+ "weight": final,
378
+ "final_weight": final,
379
+ "semantic_sim": semantic,
380
+ "similarity_score": semantic,
381
+ "type_affinity": type_affinity,
382
+ "score_components": components,
383
  "method": _ATTACH_METHOD,
384
  "provenance": _ATTACH_METHOD,
385
  "rank": int(neighbor["rank"]),
386
  "candidates_considered": candidates_considered,
387
+ "edge_reasons": [
388
+ reason
389
+ for reason, enabled in (
390
+ ("semantic-ann", semantic > 0.0),
391
+ ("type-affinity", type_affinity > 0.0),
392
+ )
393
+ if enabled
394
+ ],
395
  "created_at": created_at,
396
  }
397
  )
 
431
  return node_id.split(":", 1)[-1]
432
 
433
 
434
+ def _node_type_from_id(node_id: str) -> str:
435
+ return node_id.split(":", 1)[0] if ":" in node_id else ""
436
+
437
+
438
+ def _blend_ann_score(
439
+ *,
440
+ semantic: float,
441
+ type_affinity: float,
442
+ ) -> tuple[float, dict[str, float]]:
443
+ try:
444
+ from ctx_config import cfg # noqa: PLC0415
445
+
446
+ semantic_weight = float(cfg.graph_edge_weight_semantic)
447
+ type_weight = float(cfg.graph_edge_boost_type_affinity)
448
+ except Exception: # pragma: no cover - defensive fallback for standalone CLI use.
449
+ semantic_weight = 0.70
450
+ type_weight = 0.03
451
+ components = {
452
+ "semantic": round(semantic_weight * semantic, 4),
453
+ "type_affinity": round(type_weight * type_affinity, 4),
454
+ }
455
+ final = min(sum(components.values()), 1.0)
456
+ return round(final, 4), {
457
+ key: value for key, value in components.items() if value > 0.0
458
+ }
459
+
460
+
461
  def _utc_now() -> str:
462
  return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
463
 
src/ctx/core/graph/resolve_graph.py CHANGED
@@ -18,7 +18,9 @@ import math
18
  import os
19
  import sys
20
  from collections import defaultdict
 
21
  from pathlib import Path
 
22
 
23
  import networkx as nx
24
  from networkx.readwrite import node_link_graph
@@ -27,6 +29,8 @@ from ctx.core.graph.entity_overlays import (
27
  active_overlay_records,
28
  merge_edge_attrs,
29
  merge_node_attrs,
 
 
30
  )
31
 
32
  logger = logging.getLogger(__name__)
@@ -189,18 +193,27 @@ def _apply_entity_overlays(G: nx.Graph, graph_path: Path) -> nx.Graph:
189
  records.append(payload)
190
 
191
  for payload in active_overlay_records(records):
 
 
 
 
192
  nodes = payload.get("nodes", [])
193
  if isinstance(nodes, list):
194
  for node in nodes:
195
  if not isinstance(node, dict):
196
  continue
197
- node_id = node.get("id")
198
- if not isinstance(node_id, str) or not node_id:
199
  continue
 
200
  attrs = {key: value for key, value in node.items() if key != "id"}
201
- if node_id in G:
202
- attrs = merge_node_attrs(G.nodes[node_id], attrs)
203
- G.add_node(node_id, **attrs)
 
 
 
 
204
  applied_nodes += 1
205
 
206
  edges = payload.get("edges", [])
@@ -219,7 +232,12 @@ def _apply_entity_overlays(G: nx.Graph, graph_path: Path) -> nx.Graph:
219
  for key, value in edge.items()
220
  if key not in {"source", "target"}
221
  }
222
- if G.has_edge(source, target):
 
 
 
 
 
223
  attrs = merge_edge_attrs(G.edges[source, target], attrs)
224
  G.add_edge(source, target, **attrs)
225
  applied_edges += 1
@@ -230,6 +248,33 @@ def _apply_entity_overlays(G: nx.Graph, graph_path: Path) -> nx.Graph:
230
  return G
231
 
232
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
  def load_graph(
234
  path: Path | None = None,
235
  *,
 
18
  import os
19
  import sys
20
  from collections import defaultdict
21
+ from collections.abc import Mapping
22
  from pathlib import Path
23
+ from typing import Any
24
 
25
  import networkx as nx
26
  from networkx.readwrite import node_link_graph
 
29
  active_overlay_records,
30
  merge_edge_attrs,
31
  merge_node_attrs,
32
+ replace_edge_attrs,
33
+ replace_node_attrs,
34
  )
35
 
36
  logger = logging.getLogger(__name__)
 
193
  records.append(payload)
194
 
195
  for payload in active_overlay_records(records):
196
+ authoritative_nodes = _authoritative_overlay_nodes(payload)
197
+ for node_id in authoritative_nodes:
198
+ if node_id in G:
199
+ G.remove_edges_from(list(G.edges(node_id)))
200
  nodes = payload.get("nodes", [])
201
  if isinstance(nodes, list):
202
  for node in nodes:
203
  if not isinstance(node, dict):
204
  continue
205
+ incoming_node_id = node.get("id")
206
+ if not isinstance(incoming_node_id, str) or not incoming_node_id:
207
  continue
208
+ overlay_node_id: str = incoming_node_id
209
  attrs = {key: value for key, value in node.items() if key != "id"}
210
+ if overlay_node_id in G:
211
+ attrs = (
212
+ replace_node_attrs(G.nodes[overlay_node_id], attrs)
213
+ if overlay_node_id in authoritative_nodes
214
+ else merge_node_attrs(G.nodes[overlay_node_id], attrs)
215
+ )
216
+ G.add_node(overlay_node_id, **attrs)
217
  applied_nodes += 1
218
 
219
  edges = payload.get("edges", [])
 
232
  for key, value in edge.items()
233
  if key not in {"source", "target"}
234
  }
235
+ authoritative_edge = source in authoritative_nodes or target in authoritative_nodes
236
+ if authoritative_edge:
237
+ attrs = replace_edge_attrs(edge)
238
+ if G.has_edge(source, target):
239
+ G.remove_edge(source, target)
240
+ elif G.has_edge(source, target):
241
  attrs = merge_edge_attrs(G.edges[source, target], attrs)
242
  G.add_edge(source, target, **attrs)
243
  applied_edges += 1
 
248
  return G
249
 
250
 
251
+ def _authoritative_overlay_nodes(payload: Mapping[str, Any]) -> set[str]:
252
+ """Return node IDs whose overlay rows should replace current ANN scores."""
253
+ kind = payload.get("kind")
254
+ attach_key = payload.get("attach_key")
255
+ replace_scope = payload.get("replace_scope")
256
+ is_ann_record = (
257
+ kind == "ann_attach"
258
+ or (isinstance(attach_key, str) and attach_key.startswith("ann:v1:"))
259
+ or (isinstance(replace_scope, str) and replace_scope.startswith("ann:v1:"))
260
+ )
261
+ if not is_ann_record:
262
+ return set()
263
+
264
+ node_ids: set[str] = set()
265
+ node_id = payload.get("node_id")
266
+ if isinstance(node_id, str) and node_id:
267
+ node_ids.add(node_id)
268
+ nodes = payload.get("nodes")
269
+ if isinstance(nodes, list):
270
+ for node in nodes:
271
+ if isinstance(node, dict):
272
+ nested_id = node.get("id")
273
+ if isinstance(nested_id, str) and nested_id:
274
+ node_ids.add(nested_id)
275
+ return node_ids
276
+
277
+
278
  def load_graph(
279
  path: Path | None = None,
280
  *,
src/ctx/core/graph/semantic_edges.py CHANGED
@@ -210,6 +210,13 @@ def _partition_for_incremental(
210
  removed = prior_ids - current_ids
211
  overlap = current_ids & prior_ids
212
 
 
 
 
 
 
 
 
213
  changed: set[str] = set()
214
  for nid in overlap:
215
  cached_hash = prior.nodes[nid].get("content_hash", "")
@@ -524,6 +531,9 @@ def _topk_pairs(
524
  n = vecs.shape[0]
525
  out: dict[tuple[str, str], float] = {}
526
 
 
 
 
527
  # top_k + 1 because argpartition returns the node itself (cosine=1.0)
528
  # as its own nearest neighbor. We mask self below, but asking for
529
  # one extra is defensive against ties.
@@ -542,17 +552,16 @@ def _topk_pairs(
542
  idx_unsorted = np.argpartition(-sims, effective_k - 1, axis=1)[:, :effective_k]
543
  for i in range(end - start):
544
  src_id = node_ids[start + i]
545
- for j in idx_unsorted[i]:
546
- if j == start + i:
547
- continue
548
- score = float(sims[i, j])
549
- if score < min_cosine:
550
- continue
551
- dst_id = node_ids[int(j)]
552
- pair = (src_id, dst_id) if src_id < dst_id else (dst_id, src_id)
553
- existing = out.get(pair)
554
- if existing is None or score > existing:
555
- out[pair] = score
556
  if end == n or (start // chunk_size + 1) % 10 == 0:
557
  print(
558
  "semantic_edges: top-k rows "
@@ -848,6 +857,8 @@ def _topk_pairs_subset(
848
 
849
  if not subset_indices:
850
  return {}
 
 
851
 
852
  out: dict[tuple[str, str], float] = {}
853
  effective_k = min(top_k + 1, vecs.shape[0])
@@ -867,18 +878,16 @@ def _topk_pairs_subset(
867
  idx_unsorted = np.argpartition(-sims, effective_k - 1, axis=1)[:, :effective_k]
868
  for i, abs_i in enumerate(chunk_indices):
869
  src_id = node_ids[abs_i]
870
- for j in idx_unsorted[i]:
871
- j = int(j)
872
- if j == abs_i:
873
- continue
874
- score = float(sims[i, j])
875
- if score < min_cosine:
876
- continue
877
- dst_id = node_ids[j]
878
- pair = (src_id, dst_id) if src_id < dst_id else (dst_id, src_id)
879
- existing = out.get(pair)
880
- if existing is None or score > existing:
881
- out[pair] = score
882
  return out
883
 
884
 
@@ -989,6 +998,41 @@ def _merge_neighbor_rows(
989
  break
990
 
991
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
992
  def _reuse_prior_pairs(
993
  prior: TopKState,
994
  unchanged: set[str],
 
210
  removed = prior_ids - current_ids
211
  overlap = current_ids & prior_ids
212
 
213
+ if new:
214
+ # A new node can displace any existing node's prior top-K even when
215
+ # no prior row could reference it. Interactive single-entity adds use
216
+ # the ANN overlay attach path; the semantic graph builder must preserve
217
+ # parity with a full top-K rebuild.
218
+ return current_ids, set()
219
+
220
  changed: set[str] = set()
221
  for nid in overlap:
222
  cached_hash = prior.nodes[nid].get("content_hash", "")
 
531
  n = vecs.shape[0]
532
  out: dict[tuple[str, str], float] = {}
533
 
534
+ if top_k <= 0 or n <= 1:
535
+ return {}
536
+
537
  # top_k + 1 because argpartition returns the node itself (cosine=1.0)
538
  # as its own nearest neighbor. We mask self below, but asking for
539
  # one extra is defensive against ties.
 
552
  idx_unsorted = np.argpartition(-sims, effective_k - 1, axis=1)[:, :effective_k]
553
  for i in range(end - start):
554
  src_id = node_ids[start + i]
555
+ _merge_exact_topk_row(
556
+ out,
557
+ src_id=src_id,
558
+ src_index=start + i,
559
+ node_ids=node_ids,
560
+ scores=sims[i],
561
+ candidate_indices=idx_unsorted[i],
562
+ top_k=top_k,
563
+ min_cosine=min_cosine,
564
+ )
 
565
  if end == n or (start // chunk_size + 1) % 10 == 0:
566
  print(
567
  "semantic_edges: top-k rows "
 
857
 
858
  if not subset_indices:
859
  return {}
860
+ if top_k <= 0 or vecs.shape[0] <= 1:
861
+ return {}
862
 
863
  out: dict[tuple[str, str], float] = {}
864
  effective_k = min(top_k + 1, vecs.shape[0])
 
878
  idx_unsorted = np.argpartition(-sims, effective_k - 1, axis=1)[:, :effective_k]
879
  for i, abs_i in enumerate(chunk_indices):
880
  src_id = node_ids[abs_i]
881
+ _merge_exact_topk_row(
882
+ out,
883
+ src_id=src_id,
884
+ src_index=abs_i,
885
+ node_ids=node_ids,
886
+ scores=sims[i],
887
+ candidate_indices=idx_unsorted[i],
888
+ top_k=top_k,
889
+ min_cosine=min_cosine,
890
+ )
 
 
891
  return out
892
 
893
 
 
998
  break
999
 
1000
 
1001
+ def _merge_exact_topk_row(
1002
+ out: dict[tuple[str, str], float],
1003
+ *,
1004
+ src_id: str,
1005
+ src_index: int,
1006
+ node_ids: Sequence[str],
1007
+ scores: "np.ndarray",
1008
+ candidate_indices: Sequence[int],
1009
+ top_k: int,
1010
+ min_cosine: float,
1011
+ ) -> None:
1012
+ if top_k <= 0:
1013
+ return
1014
+ ordered = sorted(
1015
+ (int(index) for index in candidate_indices),
1016
+ key=lambda index: float(scores[index]),
1017
+ reverse=True,
1018
+ )
1019
+ emitted = 0
1020
+ for j in ordered:
1021
+ if j == src_index:
1022
+ continue
1023
+ score = float(scores[j])
1024
+ if score < min_cosine:
1025
+ continue
1026
+ dst_id = node_ids[j]
1027
+ pair = (src_id, dst_id) if src_id < dst_id else (dst_id, src_id)
1028
+ existing = out.get(pair)
1029
+ if existing is None or score > existing:
1030
+ out[pair] = score
1031
+ emitted += 1
1032
+ if emitted >= top_k:
1033
+ break
1034
+
1035
+
1036
  def _reuse_prior_pairs(
1037
  prior: TopKState,
1038
  unchanged: set[str],
src/ctx/core/resolve/recommendations.py CHANGED
@@ -224,15 +224,23 @@ def _token_idf(graph: Any) -> dict[str, float]:
224
 
225
  def query_to_tags(query: str) -> list[str]:
226
  """Extract tag-shaped signals from a free-text query."""
227
- tokens = re.findall(r"[A-Za-z0-9_\-]+", query.lower())
228
  seen: dict[str, None] = {}
229
- for token in tokens:
230
- if len(token) < 3 or token in _TAG_STOPWORDS:
231
- continue
232
- seen.setdefault(token, None)
 
 
 
 
233
  return list(seen.keys())
234
 
235
 
 
 
 
 
236
  def recommend_by_tags(
237
  graph: Any,
238
  tags: list[str],
 
224
 
225
  def query_to_tags(query: str) -> list[str]:
226
  """Extract tag-shaped signals from a free-text query."""
227
+ tokens = re.findall(r"[A-Za-z0-9_/\-]+", query.lower())
228
  seen: dict[str, None] = {}
229
+ for raw_token in tokens:
230
+ if "/" not in raw_token and _SLUG_TOKEN_RE.search(raw_token):
231
+ if len(raw_token) >= 3 and raw_token not in _TAG_STOPWORDS:
232
+ seen.setdefault(raw_token, None)
233
+ for token in _slug_token_parts(raw_token):
234
+ if len(token) < 3 or token in _TAG_STOPWORDS:
235
+ continue
236
+ seen.setdefault(token, None)
237
  return list(seen.keys())
238
 
239
 
240
+ def _slug_token_parts(label: str) -> list[str]:
241
+ return [tok for tok in _SLUG_TOKEN_RE.split(label.lower()) if tok]
242
+
243
+
244
  def recommend_by_tags(
245
  graph: Any,
246
  tags: list[str],
src/ctx/core/wiki/wiki_queue.py CHANGED
@@ -137,6 +137,7 @@ def enqueue_entity_upsert(
137
  payload=payload,
138
  idempotency_key=f"{ENTITY_UPSERT_JOB}:{entity_type}:{slug}:{content_hash}",
139
  content_hash=content_hash,
 
140
  now=now,
141
  )
142
 
 
137
  payload=payload,
138
  idempotency_key=f"{ENTITY_UPSERT_JOB}:{entity_type}:{slug}:{content_hash}",
139
  content_hash=content_hash,
140
+ reuse_terminal=action != "delete",
141
  now=now,
142
  )
143
 
src/ctx/core/wiki/wiki_queue_worker.py CHANGED
@@ -12,6 +12,7 @@ from hashlib import sha256
12
  from pathlib import Path
13
  from typing import Any, Callable
14
 
 
15
  from ctx.core.graph.incremental_attach import attach_entity
16
  from ctx.core.wiki.artifact_promotion import promote_staged_artifact
17
  from ctx.core.wiki import wiki_queue
@@ -132,6 +133,11 @@ def _process_entity_upsert(wiki_path: Path, payload: dict[str, Any]) -> str:
132
 
133
  entity_path = _resolve_entity_path(wiki_path, _required_string(payload, "entity_path"))
134
  if action == "delete":
 
 
 
 
 
135
  wiki_queue.enqueue_maintenance_job(
136
  wiki_path,
137
  kind=wiki_queue.GRAPH_EXPORT_JOB,
@@ -200,7 +206,7 @@ def _try_incremental_attach(
200
  vector_json=None,
201
  model_id=None,
202
  top_k=int(cfg.graph_semantic_top_k),
203
- min_score=float(cfg.graph_semantic_min_cosine),
204
  min_final_weight=_DEFAULT_ATTACH_MIN_FINAL_WEIGHT,
205
  )
206
  except Exception as exc: # noqa: BLE001 - attach is derived, not source of truth.
 
12
  from pathlib import Path
13
  from typing import Any, Callable
14
 
15
+ from ctx.core.graph.entity_overlays import append_overlay_tombstone
16
  from ctx.core.graph.incremental_attach import attach_entity
17
  from ctx.core.wiki.artifact_promotion import promote_staged_artifact
18
  from ctx.core.wiki import wiki_queue
 
133
 
134
  entity_path = _resolve_entity_path(wiki_path, _required_string(payload, "entity_path"))
135
  if action == "delete":
136
+ append_overlay_tombstone(
137
+ wiki_path / "graphify-out" / "entity-overlays.jsonl",
138
+ node_id=f"{entity_type}:{slug}",
139
+ source="entity-delete",
140
+ )
141
  wiki_queue.enqueue_maintenance_job(
142
  wiki_path,
143
  kind=wiki_queue.GRAPH_EXPORT_JOB,
 
206
  vector_json=None,
207
  model_id=None,
208
  top_k=int(cfg.graph_semantic_top_k),
209
+ min_score=float(cfg.graph_semantic_build_floor),
210
  min_final_weight=_DEFAULT_ATTACH_MIN_FINAL_WEIGHT,
211
  )
212
  except Exception as exc: # noqa: BLE001 - attach is derived, not source of truth.
src/ctx_init.py CHANGED
@@ -218,17 +218,25 @@ def _resolve_ctx_src_dir() -> Path:
218
  _GRAPH_ARCHIVE_NAME = "wiki-graph.tar.gz"
219
  _GRAPH_RUNTIME_ARCHIVE_NAME = "wiki-graph-runtime.tar.gz"
220
  _GRAPH_ENTITY_OVERLAY_NAME = "entity-overlays.jsonl"
 
 
 
 
 
 
 
 
221
  _GRAPH_ENTITY_OVERLAY_SHA256 = (
222
- "12556f40a8f86fdb10b87bb656a1ef03cb5bd1e5e24dd03a6c5d5eb452bf01cc"
223
  )
224
  _GRAPH_ARCHIVE_NAMES = {
225
  "runtime": _GRAPH_RUNTIME_ARCHIVE_NAME,
226
  "full": _GRAPH_ARCHIVE_NAME,
227
  }
228
- _GRAPH_ARCHIVE_SHA256 = {
229
- "runtime": "d00d34d995e0d55bdaba9957b2d8fcf1938bfeca0d0e755874e4ea990360775d",
230
- "full": "502fd22c570259d47c3aa5874a728fc533bd11d404ff43a611f3d1e1224db250",
231
- }
232
  _GRAPH_RELEASE_URL = (
233
  "https://github.com/stevesolun/ctx/releases/download/"
234
  "v{version}/{archive_name}"
@@ -257,6 +265,9 @@ _GRAPH_MANAGED_PATHS = (
257
  "versions-catalog.md",
258
  ".obsidian",
259
  )
 
 
 
260
  _GRAPH_JSON_OUTLINE_BYTES = 1024 * 1024
261
  _GRAPH_INSTALL_MODES = ("runtime", "full")
262
  _GRAPH_RUNTIME_PREFIXES = ("graphify-out/", "external-catalogs/", "entities/harnesses/")
@@ -433,7 +444,8 @@ def _validate_graph_entity_overlay(path: Path) -> None:
433
  raise ValueError(
434
  f"{path} line {lineno} edge {index} must contain source/target"
435
  )
436
- for field in ("weight", "final_weight", "similarity_score"):
 
437
  value = edge.get(field)
438
  if value is None:
439
  continue
@@ -441,6 +453,15 @@ def _validate_graph_entity_overlay(path: Path) -> None:
441
  raise ValueError(
442
  f"{path} line {lineno} edge {index} {field} must be 0..1"
443
  )
 
 
 
 
 
 
 
 
 
444
 
445
 
446
  def _release_graph_url(install_mode: str = "runtime") -> str:
@@ -554,7 +575,7 @@ def _extract_graph_archive(
554
  install_mode=install_mode,
555
  )
556
  _validate_graph_install_tree(staging_dir)
557
- _promote_graph_tree(staging_dir, target_dir)
558
 
559
 
560
  def _extract_graph_archive_to_dir(
@@ -712,10 +733,20 @@ def _read_json_file(path: Path) -> Any:
712
  return json.load(f)
713
 
714
 
715
- def _promote_graph_tree(staging_dir: Path, target_dir: Path) -> None:
 
 
 
 
 
716
  target_dir.mkdir(parents=True, exist_ok=True)
717
  target_root = target_dir.resolve()
718
- for name in _GRAPH_MANAGED_PATHS:
 
 
 
 
 
719
  source = staging_dir / name
720
  destination = target_dir / name
721
  _ensure_path_under_root(destination.parent, target_root)
@@ -860,6 +891,7 @@ _HARNESS_SOFT_REQUIREMENT_SIGNALS = frozenset({
860
  "linux",
861
  "mac",
862
  "macos",
 
863
  "mcp",
864
  "npm",
865
  "pytest",
 
218
  _GRAPH_ARCHIVE_NAME = "wiki-graph.tar.gz"
219
  _GRAPH_RUNTIME_ARCHIVE_NAME = "wiki-graph-runtime.tar.gz"
220
  _GRAPH_ENTITY_OVERLAY_NAME = "entity-overlays.jsonl"
221
+ _GRAPH_ENTITY_OVERLAY_SCORE_FIELDS = (
222
+ "weight",
223
+ "final_weight",
224
+ "similarity_score",
225
+ "semantic_sim",
226
+ "tag_sim",
227
+ "token_sim",
228
+ )
229
  _GRAPH_ENTITY_OVERLAY_SHA256 = (
230
+ "cc1a69d3452d2018bec1e049fc4ab1fa8f933adecfdcae4802a815be03f8611c"
231
  )
232
  _GRAPH_ARCHIVE_NAMES = {
233
  "runtime": _GRAPH_RUNTIME_ARCHIVE_NAME,
234
  "full": _GRAPH_ARCHIVE_NAME,
235
  }
236
+ _GRAPH_ARCHIVE_SHA256 = {
237
+ "runtime": "334fb19bace3fd6e4b92087850f17297fb248032957d123f3f1432dfde2e36c0",
238
+ "full": "91b30795e7d200cf31a62a8749969d12658f5f74636d2de06d6b2b24b393c12f",
239
+ }
240
  _GRAPH_RELEASE_URL = (
241
  "https://github.com/stevesolun/ctx/releases/download/"
242
  "v{version}/{archive_name}"
 
265
  "versions-catalog.md",
266
  ".obsidian",
267
  )
268
+ _GRAPH_RUNTIME_MANAGED_PATHS = tuple(
269
+ name for name in _GRAPH_MANAGED_PATHS if name != "entities"
270
+ ) + ("entities/harnesses",)
271
  _GRAPH_JSON_OUTLINE_BYTES = 1024 * 1024
272
  _GRAPH_INSTALL_MODES = ("runtime", "full")
273
  _GRAPH_RUNTIME_PREFIXES = ("graphify-out/", "external-catalogs/", "entities/harnesses/")
 
444
  raise ValueError(
445
  f"{path} line {lineno} edge {index} must contain source/target"
446
  )
447
+ numeric_scores: dict[str, float] = {}
448
+ for field in _GRAPH_ENTITY_OVERLAY_SCORE_FIELDS:
449
  value = edge.get(field)
450
  if value is None:
451
  continue
 
453
  raise ValueError(
454
  f"{path} line {lineno} edge {index} {field} must be 0..1"
455
  )
456
+ numeric_scores[field] = float(value)
457
+ if (
458
+ "weight" in numeric_scores
459
+ and "final_weight" in numeric_scores
460
+ and abs(numeric_scores["weight"] - numeric_scores["final_weight"]) > 1e-9
461
+ ):
462
+ raise ValueError(
463
+ f"{path} line {lineno} edge {index} weight must equal final_weight"
464
+ )
465
 
466
 
467
  def _release_graph_url(install_mode: str = "runtime") -> str:
 
575
  install_mode=install_mode,
576
  )
577
  _validate_graph_install_tree(staging_dir)
578
+ _promote_graph_tree(staging_dir, target_dir, install_mode=install_mode)
579
 
580
 
581
  def _extract_graph_archive_to_dir(
 
733
  return json.load(f)
734
 
735
 
736
+ def _promote_graph_tree(
737
+ staging_dir: Path,
738
+ target_dir: Path,
739
+ *,
740
+ install_mode: str,
741
+ ) -> None:
742
  target_dir.mkdir(parents=True, exist_ok=True)
743
  target_root = target_dir.resolve()
744
+ managed_paths = (
745
+ _GRAPH_MANAGED_PATHS
746
+ if install_mode == "full"
747
+ else _GRAPH_RUNTIME_MANAGED_PATHS
748
+ )
749
+ for name in managed_paths:
750
  source = staging_dir / name
751
  destination = target_dir / name
752
  _ensure_path_under_root(destination.parent, target_root)
 
891
  "linux",
892
  "mac",
893
  "macos",
894
+ "gpt",
895
  "mcp",
896
  "npm",
897
  "pytest",
src/ctx_monitor.py CHANGED
@@ -66,16 +66,18 @@ import os
66
  import re
67
  import secrets
68
  import sqlite3
 
69
  import sys
70
  import tarfile
71
  import threading
72
  import time
73
  import zlib
74
  from collections import defaultdict, deque
 
75
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
76
  from pathlib import Path, PurePosixPath
77
  from typing import Any
78
- from urllib.parse import quote, unquote
79
 
80
  from ctx.core.wiki import wiki_queue
81
  from ctx.core.wiki.wiki_utils import parse_frontmatter_and_body
@@ -89,14 +91,24 @@ _MONITOR_TOKEN = ""
89
  _MONITOR_MUTATIONS_ENABLED = True
90
  _GRAPH_CACHE_KEY: tuple[Any, ...] | None = None
91
  _GRAPH_CACHE_VALUE: Any | None = None
 
92
  _OVERLAY_INDEX_COVERAGE_CACHE_KEY: tuple[Any, ...] | None = None
93
  _OVERLAY_INDEX_COVERAGE_CACHE_VALUE: bool | None = None
94
  _SIDECAR_INDEX_CACHE_KEY: tuple[tuple[Path, float, int], ...] | None = None
95
  _SIDECAR_INDEX_CACHE_VALUE: dict[tuple[str, str], dict] | None = None
 
 
 
 
 
96
  _WIKI_INDEX_LIMIT_PER_TYPE = 500
 
 
 
97
  _GRAPH_REPORT_RE = re.compile(r"Nodes:\s*([\d,]+)\s*\|\s*Edges:\s*([\d,]+)")
98
  _MAX_POST_BODY_BYTES = 64 * 1024
99
  _DASHBOARD_INDEX_MEMBER = "graphify-out/dashboard-neighborhoods.sqlite3"
 
100
 
101
 
102
  # ─── Data sources ────────────────────────────────────────────────────────────
@@ -112,6 +124,38 @@ def _host_allows_mutations(host: str) -> bool:
112
  return False
113
 
114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  def _claude_dir() -> Path:
116
  return Path(os.path.expanduser("~/.claude"))
117
 
@@ -508,6 +552,20 @@ def _upsert_wiki_entity(payload: dict[str, Any]) -> tuple[bool, str]:
508
  return True, f"saved {entity_type}:{slug} and queued graph refresh"
509
 
510
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
511
  def _delete_wiki_entity(slug: str, entity_type: str) -> tuple[bool, str]:
512
  try:
513
  normalized = _normalize_dashboard_entity_type(entity_type)
@@ -518,6 +576,14 @@ def _delete_wiki_entity(slug: str, entity_type: str) -> tuple[bool, str]:
518
  path = _wiki_entity_path(slug, entity_type=normalized)
519
  if path is None:
520
  return False, f"no wiki entity found for {normalized}:{slug}"
 
 
 
 
 
 
 
 
521
  with file_lock(path):
522
  path.unlink()
523
  _queue_entity_refresh(
@@ -608,6 +674,8 @@ def _markdown_link_href(target: str) -> str | None:
608
  cleaned = target.strip()
609
  if not cleaned:
610
  return None
 
 
611
  if cleaned.startswith(("/", "#")):
612
  return cleaned
613
  if re.match(r"^https?://", cleaned, re.IGNORECASE):
@@ -1713,6 +1781,231 @@ def _all_sidecars() -> list[dict]:
1713
  return list(_sidecar_index().values())
1714
 
1715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1716
  # ─── Aggregations ────────────────────────────────────────────────────────────
1717
 
1718
 
@@ -2564,6 +2857,30 @@ def _dashboard_graph_index_archives() -> list[Path]:
2564
  return archives
2565
 
2566
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2567
  def _archive_graph_export_id(archive: Path) -> str | None:
2568
  try:
2569
  with tarfile.open(archive, "r:gz") as tar:
@@ -2593,13 +2910,20 @@ def _ensure_dashboard_graph_index() -> Path | None:
2593
  target.unlink()
2594
  except OSError:
2595
  return None
2596
- if (_wiki_dir() / "graphify-out" / "graph-report.md").is_file():
 
 
 
 
 
 
 
2597
  return None
2598
 
2599
  archives = _dashboard_graph_index_archives()
2600
  if not archives:
2601
  return None
2602
- if _dashboard_graph_manifest_export_id() is None:
2603
  return None
2604
 
2605
  target.parent.mkdir(parents=True, exist_ok=True)
@@ -2613,8 +2937,7 @@ def _ensure_dashboard_graph_index() -> Path | None:
2613
  except OSError:
2614
  return None
2615
  for archive in archives:
2616
- archive_export_id = _archive_graph_export_id(archive)
2617
- manifest_export_id = _dashboard_graph_manifest_export_id()
2618
  if manifest_export_id and archive_export_id and archive_export_id != manifest_export_id:
2619
  continue
2620
  try:
@@ -3359,17 +3682,9 @@ def _render_session_detail(session_id: str) -> str:
3359
  return _layout(f"Session {session_id}", body)
3360
 
3361
 
3362
- def _render_skills() -> str:
3363
- sidecars = _all_sidecars()
3364
- sidecars.sort(key=lambda s: (s.get("grade", "F"), -s.get("raw_score", 0.0)))
3365
-
3366
- # Sidebar stats for the filter UI.
3367
- grade_counts = {"A": 0, "B": 0, "C": 0, "D": 0, "F": 0}
3368
- type_counts = {entity_type: 0 for entity_type in _DASHBOARD_ENTITY_TYPES}
3369
- for sc in sidecars:
3370
- grade_counts[sc.get("grade", "F")] = grade_counts.get(sc.get("grade", "F"), 0) + 1
3371
- st = _sidecar_entity_type(sc)
3372
- type_counts[st] = type_counts.get(st, 0) + 1
3373
 
3374
  cards = "".join(
3375
  f"<div class='skill-card' data-slug='{html.escape(s.get('slug', ''))}' "
@@ -3383,7 +3698,7 @@ def _render_skills() -> str:
3383
  f"<span class='pill grade-{html.escape(s.get('grade', 'F'))}'>{html.escape(s.get('grade', 'F'))}</span>"
3384
  f"</div>"
3385
  f"<div class='muted' style='font-size:0.78rem;'>"
3386
- f"score {s.get('raw_score', 0.0):.3f} · {html.escape(s.get('subject_type', 'skill'))}"
3387
  f"{' · ' + html.escape(s.get('hard_floor','')) if s.get('hard_floor') else ''}"
3388
  f"</div>"
3389
  f"<div style='display:flex; gap:0.4rem; margin-top:0.2rem;'>"
@@ -3395,45 +3710,92 @@ def _render_skills() -> str:
3395
  for s in sidecars
3396
  )
3397
 
3398
- grade_checkboxes = "".join(
3399
- f"<label style='display:flex; justify-content:space-between; "
3400
- f"padding:0.25rem 0;'>"
3401
- f"<span><input type='checkbox' class='grade-filter' value='{g}' checked> "
3402
- f"<span class='pill grade-{g}'>{g}</span></span>"
3403
- f"<span class='muted' style='font-size:0.78rem;'>{grade_counts[g]}</span>"
3404
- f"</label>"
3405
- for g in ("A", "B", "C", "D", "F")
3406
  )
3407
- type_checkboxes = "".join(
3408
- f"<label style='display:flex; justify-content:space-between; "
3409
- f"padding:0.25rem 0;'>"
3410
- f"<span><input type='checkbox' class='type-filter' value='{t}' checked> {t}</span>"
3411
- f"<span class='muted' style='font-size:0.78rem;'>{type_counts.get(t, 0)}</span>"
3412
- f"</label>"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3413
  for t in _DASHBOARD_ENTITY_TYPES
3414
  )
 
 
 
 
 
 
 
 
 
3415
 
3416
  body = (
3417
  "<h1>Quality sidecars</h1>"
3418
- f"<p class='muted'>{len(sidecars)} sidecars · click any card to drill in.</p>"
3419
- "<div style='display:grid; grid-template-columns:220px 1fr; gap:1.25rem; align-items:start;'>"
 
3420
  # ── Left filter sidebar ──────────────────────────────────────
3421
  "<aside style='position:sticky; top:1rem;'>"
3422
- "<div class='card'><strong>Search</strong>"
3423
- "<input type='text' id='skill-search' placeholder='filter by slug…' "
 
3424
  "style='width:100%; margin-top:0.4rem; padding:0.35rem 0.5rem; "
3425
- "border:1px solid #ccc; border-radius:4px;'></div>"
3426
- "<div class='card'><strong>Grade</strong>"
3427
- + grade_checkboxes
3428
- + "</div>"
3429
- "<div class='card'><strong>Type</strong>"
3430
- + type_checkboxes
3431
- + "</div>"
3432
- "<div class='card'><strong>Hard floor</strong>"
3433
- "<label style='display:block; padding:0.25rem 0;'>"
3434
- "<input type='checkbox' id='hide-floor'> hide floored</label>"
3435
- "</div>"
3436
- "<div class='card'><span id='match-count' class='muted'></span></div>"
 
 
3437
  "</aside>"
3438
  # ── Card grid ────────────────────────────────────────────────
3439
  "<div id='card-grid' style='display:grid; "
@@ -3442,30 +3804,9 @@ def _render_skills() -> str:
3442
  + "</div>"
3443
  "</div>"
3444
  "<script>\n"
3445
- "const cards = document.querySelectorAll('.skill-card');\n"
3446
- "const search = document.getElementById('skill-search');\n"
3447
- "const hideFloor = document.getElementById('hide-floor');\n"
3448
- "function activeGrades() { return Array.from(document.querySelectorAll('.grade-filter:checked')).map(x => x.value); }\n"
3449
- "function activeTypes() { return Array.from(document.querySelectorAll('.type-filter:checked')).map(x => x.value); }\n"
3450
- "function apply() {\n"
3451
- " const q = search.value.trim().toLowerCase();\n"
3452
- " const grades = new Set(activeGrades());\n"
3453
- " const types = new Set(activeTypes());\n"
3454
- " const hideF = hideFloor.checked;\n"
3455
- " let shown = 0;\n"
3456
- " cards.forEach(c => {\n"
3457
- " const ok = grades.has(c.dataset.grade) && types.has(c.dataset.type)\n"
3458
- " && (!q || c.dataset.slug.toLowerCase().includes(q))\n"
3459
- " && (!hideF || !c.dataset.floor);\n"
3460
- " c.style.display = ok ? '' : 'none';\n"
3461
- " if (ok) shown++;\n"
3462
- " });\n"
3463
- " document.getElementById('match-count').textContent = shown + ' of ' + cards.length + ' match';\n"
3464
- "}\n"
3465
- "search.addEventListener('input', apply);\n"
3466
- "hideFloor.addEventListener('change', apply);\n"
3467
- "document.querySelectorAll('.grade-filter, .type-filter').forEach(el => el.addEventListener('change', apply));\n"
3468
- "apply();\n"
3469
  "</script>"
3470
  )
3471
  return _layout("Skills", body)
@@ -4280,7 +4621,8 @@ def _render_runtime_entity_load_script(
4280
  " body: JSON.stringify({slug: CTX_RUNTIME_ENTITY_SLUG, entity_type: CTX_RUNTIME_ENTITY_TYPE})\n"
4281
  " });\n"
4282
  " const payload = await response.json();\n"
4283
- " if (result) result.textContent = (payload.ok ? 'loaded: ' : 'not loaded: ') + (payload.msg || response.status);\n"
 
4284
  " } catch (error) {\n"
4285
  " if (result) result.textContent = 'load failed: ' + error;\n"
4286
  " } finally {\n"
@@ -4952,7 +5294,7 @@ def _render_docs_markdown(markdown_text: str, page_anchor: str) -> str:
4952
  try:
4953
  import markdown as markdown_lib # type: ignore[import-untyped]
4954
 
4955
- return str(markdown_lib.markdown(
4956
  markdown_text,
4957
  extensions=[
4958
  "admonition",
@@ -4979,14 +5321,75 @@ def _render_docs_markdown(markdown_text: str, page_anchor: str) -> str:
4979
  },
4980
  output_format="html5",
4981
  ))
 
4982
  except Exception:
4983
  return _render_wiki_markdown(markdown_text)
4984
 
4985
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4986
  def _docs_search_text(entry: dict[str, str]) -> str:
4987
  text = f"{entry['title']} {entry['path']} {entry['summary']} {entry['body']}"
4988
  text = re.sub(r"```.*?```", " ", text, flags=re.DOTALL)
4989
  text = re.sub(r"!!!\s+\w+(?:\s+\"[^\"]+\")?", " ", text)
 
4990
  text = re.sub(r"[*_`#>\[\]().!:-]+", " ", text)
4991
  return re.sub(r"\s+", " ", text).strip().lower()
4992
 
@@ -5624,6 +6027,17 @@ def _render_harness_wizard() -> str:
5624
  return _layout("Harness Setup", body)
5625
 
5626
 
 
 
 
 
 
 
 
 
 
 
 
5627
  def _kpi_summary():
5628
  """Compute the KPI DashboardSummary using the default source layout.
5629
 
@@ -5639,6 +6053,14 @@ def _kpi_summary():
5639
  sidecar_dir = _sidecar_dir()
5640
  if not sidecar_dir.is_dir():
5641
  return None
 
 
 
 
 
 
 
 
5642
  try:
5643
  from ctx_config import cfg # type: ignore
5644
  sources = LifecycleSources(
@@ -5653,9 +6075,13 @@ def _kpi_summary():
5653
  sidecar_dir=sidecar_dir,
5654
  )
5655
  try:
5656
- return generate(sources=sources, top_n=25)
5657
  except Exception: # noqa: BLE001
5658
  return None
 
 
 
 
5659
 
5660
 
5661
  def _render_kpi() -> str:
@@ -6361,11 +6787,12 @@ class _MonitorHandler(BaseHTTPRequestHandler):
6361
  # require same-origin POSTs plus a per-process token injected into the
6362
  # served dashboard page.
6363
  def _same_origin(self) -> bool:
 
 
 
6364
  origin = self.headers.get("Origin") or ""
6365
  if origin:
6366
- host_header = self.headers.get("Host", "")
6367
- expected = f"http://{host_header}"
6368
- return origin == expected
6369
  # No Origin header (curl, direct tool calls) is acceptable only
6370
  # when the mutation token below is also present.
6371
  return True
@@ -6387,15 +6814,26 @@ class _MonitorHandler(BaseHTTPRequestHandler):
6387
  return self._mutations_enabled()
6388
 
6389
  def _read_authorized(self, qs: dict[str, str]) -> bool:
 
6390
  if self._mutations_enabled():
6391
- return True
6392
- token = self.headers.get("X-CTX-Monitor-Token") or qs.get("token", "")
 
 
 
 
6393
  return bool(_MONITOR_TOKEN) and secrets.compare_digest(token, _MONITOR_TOKEN)
6394
 
6395
  def _send_security_headers(self, *, html_response: bool = False) -> None:
6396
  self.send_header("X-Content-Type-Options", "nosniff")
6397
  self.send_header("Referrer-Policy", "no-referrer")
6398
  self.send_header("X-Frame-Options", "DENY")
 
 
 
 
 
 
6399
  if html_response:
6400
  self.send_header(
6401
  "Content-Security-Policy",
@@ -6460,6 +6898,7 @@ class _MonitorHandler(BaseHTTPRequestHandler):
6460
  from urllib.parse import parse_qs
6461
  qs = {k: v[0] for k, v in parse_qs(raw_query).items()}
6462
  try:
 
6463
  read_authorized = getattr(self, "_read_authorized", lambda _qs: True)
6464
  if not read_authorized(qs):
6465
  if path.startswith("/api/"):
@@ -6474,6 +6913,13 @@ class _MonitorHandler(BaseHTTPRequestHandler):
6474
  "<p>monitor read token required on non-loopback bind</p>",
6475
  )
6476
  return
 
 
 
 
 
 
 
6477
  if path == "/":
6478
  self._send_html(_render_home())
6479
  elif path == "/sessions":
@@ -6481,7 +6927,7 @@ class _MonitorHandler(BaseHTTPRequestHandler):
6481
  elif path.startswith("/session/"):
6482
  self._send_html(_render_session_detail(path.split("/session/", 1)[1]))
6483
  elif path == "/skills":
6484
- self._send_html(_render_skills())
6485
  elif path.startswith("/skill/"):
6486
  self._send_html(_render_skill_detail(
6487
  path.split("/skill/", 1)[1],
@@ -6533,6 +6979,8 @@ class _MonitorHandler(BaseHTTPRequestHandler):
6533
  })
6534
  elif path == "/api/grades.json":
6535
  self._send_json(_grade_distribution_payload())
 
 
6536
  elif path == "/api/runtime.json":
6537
  self._send_json(_runtime_lifecycle_summary())
6538
  elif path == "/api/config.json":
@@ -6811,16 +7259,16 @@ def serve(host: str = "127.0.0.1", port: int = 8765) -> None:
6811
  """Run the monitor. Blocks until Ctrl+C."""
6812
  global _MONITOR_TOKEN
6813
  server = _make_monitor_server(host, port)
6814
- _MONITOR_TOKEN = (
6815
- secrets.token_urlsafe(32)
6816
- if bool(getattr(server, "_ctx_mutations_enabled", False))
6817
- else ""
6818
- )
6819
- url = f"http://{host}:{port}/"
6820
  print(f"ctx-monitor serving at {url} (Ctrl+C to stop)", flush=True)
6821
- if not bool(getattr(server, "_ctx_mutations_enabled", False)):
6822
  print(
6823
- "ctx-monitor: non-loopback bind; load/unload mutations disabled",
 
6824
  flush=True,
6825
  )
6826
  try:
@@ -6831,6 +7279,21 @@ def serve(host: str = "127.0.0.1", port: int = 8765) -> None:
6831
  server.server_close()
6832
 
6833
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6834
  def main(argv: list[str] | None = None) -> int:
6835
  parser = argparse.ArgumentParser(
6836
  prog="ctx-monitor",
 
66
  import re
67
  import secrets
68
  import sqlite3
69
+ import socket
70
  import sys
71
  import tarfile
72
  import threading
73
  import time
74
  import zlib
75
  from collections import defaultdict, deque
76
+ from http.cookies import CookieError, SimpleCookie
77
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
78
  from pathlib import Path, PurePosixPath
79
  from typing import Any
80
+ from urllib.parse import quote, unquote, urlsplit
81
 
82
  from ctx.core.wiki import wiki_queue
83
  from ctx.core.wiki.wiki_utils import parse_frontmatter_and_body
 
91
  _MONITOR_MUTATIONS_ENABLED = True
92
  _GRAPH_CACHE_KEY: tuple[Any, ...] | None = None
93
  _GRAPH_CACHE_VALUE: Any | None = None
94
+ _PACKAGED_GRAPH_EXPORT_ID_CACHE: str | None | bool = None
95
  _OVERLAY_INDEX_COVERAGE_CACHE_KEY: tuple[Any, ...] | None = None
96
  _OVERLAY_INDEX_COVERAGE_CACHE_VALUE: bool | None = None
97
  _SIDECAR_INDEX_CACHE_KEY: tuple[tuple[Path, float, int], ...] | None = None
98
  _SIDECAR_INDEX_CACHE_VALUE: dict[tuple[str, str], dict] | None = None
99
+ _SIDECAR_FILTER_CACHE_SIGNATURE: tuple[Any, ...] | None = None
100
+ _SIDECAR_FILTER_CACHE_VALUE: dict[tuple[Any, ...], list[dict[str, Any]]] = {}
101
+ _KPI_SUMMARY_CACHE_KEY: tuple[Any, ...] | None = None
102
+ _KPI_SUMMARY_CACHE_VALUE: Any | None = None
103
+ _KPI_SUMMARY_CACHE_AT = 0.0
104
  _WIKI_INDEX_LIMIT_PER_TYPE = 500
105
+ _SKILLS_PAGE_DEFAULT_LIMIT = 100
106
+ _SKILLS_PAGE_MAX_LIMIT = 500
107
+ _KPI_SUMMARY_CACHE_SECONDS = 30
108
  _GRAPH_REPORT_RE = re.compile(r"Nodes:\s*([\d,]+)\s*\|\s*Edges:\s*([\d,]+)")
109
  _MAX_POST_BODY_BYTES = 64 * 1024
110
  _DASHBOARD_INDEX_MEMBER = "graphify-out/dashboard-neighborhoods.sqlite3"
111
+ _READ_TOKEN_COOKIE = "ctx_monitor_read_token"
112
 
113
 
114
  # ─── Data sources ────────────────────────────────────────────────────────────
 
124
  return False
125
 
126
 
127
+ def _request_host_name(host_header: str) -> str:
128
+ value = (host_header or "").strip()
129
+ if not value:
130
+ return ""
131
+ if value.startswith("["):
132
+ end = value.find("]")
133
+ return value[1:end].rstrip(".").lower() if end != -1 else ""
134
+ return value.rsplit(":", 1)[0].rstrip(".").lower()
135
+
136
+
137
+ def _origin_host_name(origin: str) -> str:
138
+ try:
139
+ parsed = urlsplit(origin)
140
+ except ValueError:
141
+ return ""
142
+ if parsed.scheme not in {"http", "https"}:
143
+ return ""
144
+ return (parsed.hostname or "").rstrip(".").lower()
145
+
146
+
147
+ def _read_token_cookie(cookie_header: str) -> str:
148
+ if not cookie_header:
149
+ return ""
150
+ try:
151
+ cookie = SimpleCookie()
152
+ cookie.load(cookie_header)
153
+ except CookieError:
154
+ return ""
155
+ morsel = cookie.get(_READ_TOKEN_COOKIE)
156
+ return morsel.value if morsel is not None else ""
157
+
158
+
159
  def _claude_dir() -> Path:
160
  return Path(os.path.expanduser("~/.claude"))
161
 
 
552
  return True, f"saved {entity_type}:{slug} and queued graph refresh"
553
 
554
 
555
+ def _entity_live_in_manifest(slug: str, entity_type: str) -> bool:
556
+ manifest = _read_manifest()
557
+ for entry in manifest.get("load", []):
558
+ if not isinstance(entry, dict):
559
+ continue
560
+ entry_slug = str(entry.get("skill") or entry.get("slug") or "")
561
+ entry_type = _normalize_dashboard_entity_type(
562
+ str(entry.get("entity_type") or entry.get("type") or "skill"),
563
+ )
564
+ if entry_slug == slug and entry_type == entity_type:
565
+ return True
566
+ return False
567
+
568
+
569
  def _delete_wiki_entity(slug: str, entity_type: str) -> tuple[bool, str]:
570
  try:
571
  normalized = _normalize_dashboard_entity_type(entity_type)
 
576
  path = _wiki_entity_path(slug, entity_type=normalized)
577
  if path is None:
578
  return False, f"no wiki entity found for {normalized}:{slug}"
579
+ if _entity_live_in_manifest(slug, normalized):
580
+ unloaded, unload_detail = _perform_unload(slug, normalized)
581
+ if not unloaded:
582
+ return (
583
+ False,
584
+ f"{normalized}:{slug} is loaded; unload before delete failed: "
585
+ f"{unload_detail}",
586
+ )
587
  with file_lock(path):
588
  path.unlink()
589
  _queue_entity_refresh(
 
674
  cleaned = target.strip()
675
  if not cleaned:
676
  return None
677
+ if cleaned.startswith("//"):
678
+ return None
679
  if cleaned.startswith(("/", "#")):
680
  return cleaned
681
  if re.match(r"^https?://", cleaned, re.IGNORECASE):
 
1781
  return list(_sidecar_index().values())
1782
 
1783
 
1784
+ def _skills_page_int(
1785
+ value: str | None,
1786
+ *,
1787
+ default: int,
1788
+ minimum: int = 1,
1789
+ maximum: int | None = None,
1790
+ ) -> int:
1791
+ try:
1792
+ parsed = int(str(value or "").strip())
1793
+ except ValueError:
1794
+ parsed = default
1795
+ parsed = max(minimum, parsed)
1796
+ if maximum is not None:
1797
+ parsed = min(maximum, parsed)
1798
+ return parsed
1799
+
1800
+
1801
+ def _skills_query_values(raw: str | None, allowed: set[str]) -> set[str]:
1802
+ values = {
1803
+ item.strip()
1804
+ for item in str(raw or "").split(",")
1805
+ if item.strip()
1806
+ }
1807
+ return {item for item in values if item in allowed}
1808
+
1809
+
1810
+ def _sidecar_sort_key(sidecar: dict) -> tuple[str, float, str]:
1811
+ return (
1812
+ str(sidecar.get("grade") or "F"),
1813
+ -float(sidecar.get("raw_score") or sidecar.get("score") or 0.0),
1814
+ str(sidecar.get("slug") or ""),
1815
+ )
1816
+
1817
+
1818
+ def _sidecar_card_payload(sidecar: dict) -> dict[str, Any]:
1819
+ slug = str(sidecar.get("slug") or "")
1820
+ entity_type = _sidecar_entity_type(sidecar)
1821
+ return {
1822
+ "slug": slug,
1823
+ "grade": str(sidecar.get("grade") or "F"),
1824
+ "type": entity_type,
1825
+ "hard_floor": str(sidecar.get("hard_floor") or ""),
1826
+ "raw_score": float(sidecar.get("raw_score") or sidecar.get("score") or 0.0),
1827
+ "sidecar_href": f"/skill/{quote(slug)}?type={quote(entity_type)}",
1828
+ "wiki_href": f"/wiki/{quote(slug)}?type={quote(entity_type)}",
1829
+ "graph_href": f"/graph?slug={quote(slug)}&type={quote(entity_type)}",
1830
+ }
1831
+
1832
+
1833
+ def _sidecar_filter_signature(files: list[Path]) -> tuple[Any, ...]:
1834
+ roots = (_sidecar_dir(), _sidecar_dir() / "mcp")
1835
+ root_counts = {
1836
+ root.resolve(): sum(1 for path in files if path.parent == root)
1837
+ for root in roots
1838
+ }
1839
+ signature: list[tuple[str, int, int]] = []
1840
+ for root in roots:
1841
+ if not root.is_dir():
1842
+ signature.append((str(root.resolve()), 0, 0))
1843
+ continue
1844
+ stat = root.stat()
1845
+ signature.append((
1846
+ str(root.resolve()),
1847
+ int(getattr(stat, "st_mtime_ns", int(stat.st_mtime * 1_000_000_000))),
1848
+ root_counts.get(root.resolve(), 0),
1849
+ ))
1850
+ return tuple(signature)
1851
+
1852
+
1853
+ def _sidecar_candidate_files(
1854
+ files: list[Path],
1855
+ *,
1856
+ q: str,
1857
+ types: set[str],
1858
+ ) -> list[Path]:
1859
+ q_lower = q.lower()
1860
+ candidates = [
1861
+ path for path in files
1862
+ if not q_lower or q_lower in path.stem.lower()
1863
+ ]
1864
+ if not types:
1865
+ return candidates
1866
+ if types == {"mcp-server"}:
1867
+ return [path for path in candidates if path.parent.name == "mcp"]
1868
+ if "mcp-server" not in types:
1869
+ return [path for path in candidates if path.parent.name != "mcp"]
1870
+ return candidates
1871
+
1872
+
1873
+ def _filtered_sidecar_records(
1874
+ files: list[Path],
1875
+ *,
1876
+ q: str,
1877
+ types: set[str],
1878
+ grades: set[str],
1879
+ hide_floor: bool,
1880
+ ) -> list[dict[str, Any]]:
1881
+ """Return cached filtered sidecar card records for /skills search."""
1882
+ global _SIDECAR_FILTER_CACHE_SIGNATURE, _SIDECAR_FILTER_CACHE_VALUE
1883
+
1884
+ signature = _sidecar_filter_signature(files)
1885
+ if _SIDECAR_FILTER_CACHE_SIGNATURE != signature:
1886
+ _SIDECAR_FILTER_CACHE_SIGNATURE = signature
1887
+ _SIDECAR_FILTER_CACHE_VALUE = {}
1888
+ cache_key = (
1889
+ q.lower(),
1890
+ tuple(sorted(types)),
1891
+ tuple(sorted(grades)),
1892
+ hide_floor,
1893
+ )
1894
+ cached = _SIDECAR_FILTER_CACHE_VALUE.get(cache_key)
1895
+ if cached is not None:
1896
+ return cached
1897
+
1898
+ records: list[dict[str, Any]] = []
1899
+ for path in _sidecar_candidate_files(files, q=q, types=types):
1900
+ sidecar = _read_sidecar_file(path)
1901
+ if sidecar is None:
1902
+ continue
1903
+ if not _sidecar_matches_filters(
1904
+ sidecar,
1905
+ q=q,
1906
+ types=types,
1907
+ grades=grades,
1908
+ hide_floor=hide_floor,
1909
+ ):
1910
+ continue
1911
+ records.append(_sidecar_card_payload(sidecar))
1912
+ records.sort(key=_sidecar_sort_key)
1913
+ if len(_SIDECAR_FILTER_CACHE_VALUE) >= 32:
1914
+ _SIDECAR_FILTER_CACHE_VALUE.clear()
1915
+ _SIDECAR_FILTER_CACHE_VALUE[cache_key] = records
1916
+ return records
1917
+
1918
+
1919
+ def _sidecar_matches_filters(
1920
+ sidecar: dict,
1921
+ *,
1922
+ q: str,
1923
+ types: set[str],
1924
+ grades: set[str],
1925
+ hide_floor: bool,
1926
+ ) -> bool:
1927
+ entity_type = _sidecar_entity_type(sidecar)
1928
+ grade = str(sidecar.get("grade") or "F")
1929
+ floor = str(sidecar.get("hard_floor") or "")
1930
+ if types and entity_type not in types:
1931
+ return False
1932
+ if grades and grade not in grades:
1933
+ return False
1934
+ if hide_floor and floor:
1935
+ return False
1936
+ if q:
1937
+ return q.lower() in str(sidecar.get("slug") or "").lower()
1938
+ return True
1939
+
1940
+
1941
+ def _sidecar_page_payload(qs: dict[str, str] | None = None) -> dict[str, Any]:
1942
+ """Return a paginated sidecar payload for /skills and its JSON API."""
1943
+ qs = qs or {}
1944
+ page = _skills_page_int(qs.get("page"), default=1)
1945
+ limit = _skills_page_int(
1946
+ qs.get("limit"),
1947
+ default=_SKILLS_PAGE_DEFAULT_LIMIT,
1948
+ maximum=_SKILLS_PAGE_MAX_LIMIT,
1949
+ )
1950
+ q = str(qs.get("q") or "").strip()
1951
+ types = _skills_query_values(qs.get("type"), set(_DASHBOARD_ENTITY_TYPES))
1952
+ grades = _skills_query_values(qs.get("grade"), {"A", "B", "C", "D", "F"})
1953
+ hide_floor = str(qs.get("hide_floor") or "").strip().lower() in {
1954
+ "1", "true", "yes", "on",
1955
+ }
1956
+
1957
+ files = _sidecar_files()
1958
+ catalog_total = len(files)
1959
+ has_filters = bool(q or types or grades or hide_floor)
1960
+ if has_filters:
1961
+ sidecars = _filtered_sidecar_records(
1962
+ files,
1963
+ q=q,
1964
+ types=types,
1965
+ grades=grades,
1966
+ hide_floor=hide_floor,
1967
+ )
1968
+ total = len(sidecars)
1969
+ start = (page - 1) * limit
1970
+ page_sidecars = sidecars[start:start + limit]
1971
+ else:
1972
+ total = catalog_total
1973
+ start = (page - 1) * limit
1974
+ selected_files = files[start:start + limit]
1975
+ page_sidecars = [
1976
+ sidecar
1977
+ for path in selected_files
1978
+ if (sidecar := _read_sidecar_file(path)) is not None
1979
+ ]
1980
+ if catalog_total <= limit:
1981
+ page_sidecars.sort(key=_sidecar_sort_key)
1982
+
1983
+ pages = max(1, math.ceil(total / limit)) if total else 1
1984
+ if page > pages:
1985
+ page = pages
1986
+ return _sidecar_page_payload({
1987
+ **qs,
1988
+ "page": str(page),
1989
+ "limit": str(limit),
1990
+ })
1991
+
1992
+ return {
1993
+ "items": [_sidecar_card_payload(sidecar) for sidecar in page_sidecars],
1994
+ "total": total,
1995
+ "catalog_total": catalog_total,
1996
+ "page": page,
1997
+ "limit": limit,
1998
+ "pages": pages,
1999
+ "has_next": page < pages,
2000
+ "has_prev": page > 1,
2001
+ "filtered": has_filters,
2002
+ "q": q,
2003
+ "types": sorted(types),
2004
+ "grades": sorted(grades),
2005
+ "hide_floor": hide_floor,
2006
+ }
2007
+
2008
+
2009
  # ─── Aggregations ────────────────────────────────────────────────────────────
2010
 
2011
 
 
2857
  return archives
2858
 
2859
 
2860
+ def _packaged_graph_export_id() -> str | None:
2861
+ global _PACKAGED_GRAPH_EXPORT_ID_CACHE
2862
+ if isinstance(_PACKAGED_GRAPH_EXPORT_ID_CACHE, bool):
2863
+ return None
2864
+ if isinstance(_PACKAGED_GRAPH_EXPORT_ID_CACHE, str):
2865
+ return _PACKAGED_GRAPH_EXPORT_ID_CACHE
2866
+ module_root = Path(__file__).resolve().parent.parent
2867
+ try:
2868
+ data = json.loads(
2869
+ (module_root / "graph" / "communities.json").read_text(
2870
+ encoding="utf-8",
2871
+ )
2872
+ )
2873
+ except (OSError, json.JSONDecodeError):
2874
+ _PACKAGED_GRAPH_EXPORT_ID_CACHE = False
2875
+ return None
2876
+ export_id = data.get("export_id") if isinstance(data, dict) else None
2877
+ if isinstance(export_id, str) and export_id.strip():
2878
+ _PACKAGED_GRAPH_EXPORT_ID_CACHE = export_id.strip()
2879
+ return export_id.strip()
2880
+ _PACKAGED_GRAPH_EXPORT_ID_CACHE = False
2881
+ return None
2882
+
2883
+
2884
  def _archive_graph_export_id(archive: Path) -> str | None:
2885
  try:
2886
  with tarfile.open(archive, "r:gz") as tar:
 
2910
  target.unlink()
2911
  except OSError:
2912
  return None
2913
+
2914
+ manifest_export_id = _dashboard_graph_manifest_export_id()
2915
+ packaged_export_id = _packaged_graph_export_id()
2916
+ if (
2917
+ manifest_export_id is not None
2918
+ and packaged_export_id is not None
2919
+ and manifest_export_id != packaged_export_id
2920
+ ):
2921
  return None
2922
 
2923
  archives = _dashboard_graph_index_archives()
2924
  if not archives:
2925
  return None
2926
+ if manifest_export_id is None:
2927
  return None
2928
 
2929
  target.parent.mkdir(parents=True, exist_ok=True)
 
2937
  except OSError:
2938
  return None
2939
  for archive in archives:
2940
+ archive_export_id = packaged_export_id or _archive_graph_export_id(archive)
 
2941
  if manifest_export_id and archive_export_id and archive_export_id != manifest_export_id:
2942
  continue
2943
  try:
 
3682
  return _layout(f"Session {session_id}", body)
3683
 
3684
 
3685
+ def _render_skills(qs: dict[str, str] | None = None) -> str:
3686
+ payload = _sidecar_page_payload(qs)
3687
+ sidecars = payload["items"]
 
 
 
 
 
 
 
 
3688
 
3689
  cards = "".join(
3690
  f"<div class='skill-card' data-slug='{html.escape(s.get('slug', ''))}' "
 
3698
  f"<span class='pill grade-{html.escape(s.get('grade', 'F'))}'>{html.escape(s.get('grade', 'F'))}</span>"
3699
  f"</div>"
3700
  f"<div class='muted' style='font-size:0.78rem;'>"
3701
+ f"score {s.get('raw_score', 0.0):.3f} · {html.escape(s.get('type', s.get('subject_type', 'skill')))}"
3702
  f"{' · ' + html.escape(s.get('hard_floor','')) if s.get('hard_floor') else ''}"
3703
  f"</div>"
3704
  f"<div style='display:flex; gap:0.4rem; margin-top:0.2rem;'>"
 
3710
  for s in sidecars
3711
  )
3712
 
3713
+ start_index = ((payload["page"] - 1) * payload["limit"]) + 1 if payload["total"] else 0
3714
+ end_index = min(payload["page"] * payload["limit"], payload["total"])
3715
+ summary = (
3716
+ f"Showing {start_index}-{end_index} of {payload['total']} matching sidecars"
3717
+ if payload["filtered"]
3718
+ else f"Showing {start_index}-{end_index} of {payload['catalog_total']} sidecars"
 
 
3719
  )
3720
+ query_base = {
3721
+ key: value
3722
+ for key, value in (qs or {}).items()
3723
+ if key not in {"page"}
3724
+ }
3725
+
3726
+ def page_href(page: int) -> str:
3727
+ params = {
3728
+ **query_base,
3729
+ "page": str(max(1, page)),
3730
+ "limit": str(payload["limit"]),
3731
+ }
3732
+ query = "&".join(
3733
+ f"{quote(str(key))}={quote(str(value))}"
3734
+ for key, value in params.items()
3735
+ if str(value).strip()
3736
+ )
3737
+ return "/skills" + (f"?{query}" if query else "")
3738
+
3739
+ prev_link = (
3740
+ f"<a href='{html.escape(page_href(payload['page'] - 1))}'>previous</a>"
3741
+ if payload["has_prev"]
3742
+ else "<span class='muted'>previous</span>"
3743
+ )
3744
+ next_link = (
3745
+ f"<a href='{html.escape(page_href(payload['page'] + 1))}'>next</a>"
3746
+ if payload["has_next"]
3747
+ else "<span class='muted'>next</span>"
3748
+ )
3749
+ pagination = (
3750
+ "<div class='card' style='display:flex; justify-content:space-between; "
3751
+ "align-items:center; gap:1rem;'>"
3752
+ f"<span id='match-count' class='muted'>{html.escape(summary)} · page "
3753
+ f"{payload['page']} of {payload['pages']}</span>"
3754
+ f"<span>{prev_link} · {next_link}</span>"
3755
+ "</div>"
3756
+ )
3757
+ selected_type = ",".join(payload["types"])
3758
+ selected_grade = ",".join(payload["grades"])
3759
+ type_options = "<option value=''>all types</option>" + "".join(
3760
+ f"<option value='{html.escape(t)}'"
3761
+ f"{' selected' if selected_type == t else ''}>{html.escape(t)}</option>"
3762
  for t in _DASHBOARD_ENTITY_TYPES
3763
  )
3764
+ grade_options = "<option value=''>all grades</option>" + "".join(
3765
+ f"<option value='{g}'{' selected' if selected_grade == g else ''}>{g}</option>"
3766
+ for g in ("A", "B", "C", "D", "F")
3767
+ )
3768
+ limit_options = "".join(
3769
+ f"<option value='{n}'{' selected' if payload['limit'] == n else ''}>{n}</option>"
3770
+ for n in (50, 100, 200, 500)
3771
+ )
3772
+ hide_checked = " checked" if payload["hide_floor"] else ""
3773
 
3774
  body = (
3775
  "<h1>Quality sidecars</h1>"
3776
+ f"<p class='muted'>{payload['catalog_total']} sidecars · click any card to drill in.</p>"
3777
+ + pagination
3778
+ + "<div style='display:grid; grid-template-columns:220px 1fr; gap:1.25rem; align-items:start;'>"
3779
  # ── Left filter sidebar ──────────────────────────────────────
3780
  "<aside style='position:sticky; top:1rem;'>"
3781
+ "<form class='card' id='skills-filter-form' method='get' action='/skills'>"
3782
+ "<strong>Search</strong>"
3783
+ f"<input type='text' id='skill-search' name='q' value='{html.escape(payload['q'])}' placeholder='filter by slug...' "
3784
  "style='width:100%; margin-top:0.4rem; padding:0.35rem 0.5rem; "
3785
+ "border:1px solid #ccc; border-radius:4px;'>"
3786
+ "<label style='display:block; margin-top:0.6rem; font-size:0.82rem;'>Type"
3787
+ f"<select class='type-filter' name='type' style='width:100%; margin-top:0.25rem;'>{type_options}</select>"
3788
+ "</label>"
3789
+ "<label style='display:block; margin-top:0.6rem; font-size:0.82rem;'>Grade"
3790
+ f"<select class='grade-filter' name='grade' style='width:100%; margin-top:0.25rem;'>{grade_options}</select>"
3791
+ "</label>"
3792
+ "<label style='display:block; margin-top:0.6rem; font-size:0.82rem;'>Limit"
3793
+ f"<select name='limit' style='width:100%; margin-top:0.25rem;'>{limit_options}</select>"
3794
+ "</label>"
3795
+ "<label style='display:block; padding:0.55rem 0 0.35rem;'>"
3796
+ f"<input type='checkbox' id='hide-floor' name='hide_floor' value='1'{hide_checked}> hide floored</label>"
3797
+ "<button type='submit' style='width:100%;'>apply</button>"
3798
+ "</form>"
3799
  "</aside>"
3800
  # ── Card grid ────────────────────────────────────────────────
3801
  "<div id='card-grid' style='display:grid; "
 
3804
  + "</div>"
3805
  "</div>"
3806
  "<script>\n"
3807
+ "document.querySelectorAll('#skills-filter-form select').forEach(el => {\n"
3808
+ " el.addEventListener('change', () => el.form.submit());\n"
3809
+ "});\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3810
  "</script>"
3811
  )
3812
  return _layout("Skills", body)
 
4621
  " body: JSON.stringify({slug: CTX_RUNTIME_ENTITY_SLUG, entity_type: CTX_RUNTIME_ENTITY_TYPE})\n"
4622
  " });\n"
4623
  " const payload = await response.json();\n"
4624
+ " const message = payload.detail || payload.msg || response.status;\n"
4625
+ " if (result) result.textContent = (payload.ok ? 'loaded: ' : 'not loaded: ') + message;\n"
4626
  " } catch (error) {\n"
4627
  " if (result) result.textContent = 'load failed: ' + error;\n"
4628
  " } finally {\n"
 
5294
  try:
5295
  import markdown as markdown_lib # type: ignore[import-untyped]
5296
 
5297
+ rendered = str(markdown_lib.markdown(
5298
  markdown_text,
5299
  extensions=[
5300
  "admonition",
 
5321
  },
5322
  output_format="html5",
5323
  ))
5324
+ return _sanitize_docs_html(rendered)
5325
  except Exception:
5326
  return _render_wiki_markdown(markdown_text)
5327
 
5328
 
5329
+ def _sanitize_docs_html(rendered_html: str) -> str:
5330
+ """Remove active HTML from local docs before embedding in the dashboard."""
5331
+ dangerous_blocks = (
5332
+ "script",
5333
+ "style",
5334
+ "iframe",
5335
+ "object",
5336
+ "embed",
5337
+ "form",
5338
+ "textarea",
5339
+ "select",
5340
+ )
5341
+ dangerous_tags = (
5342
+ "base",
5343
+ "button",
5344
+ "input",
5345
+ "link",
5346
+ "meta",
5347
+ )
5348
+
5349
+ def escape_match(match: re.Match[str]) -> str:
5350
+ return html.escape(match.group(0))
5351
+
5352
+ for tag in dangerous_blocks:
5353
+ rendered_html = re.sub(
5354
+ rf"<\s*{tag}\b[^>]*>.*?<\s*/\s*{tag}\s*>",
5355
+ escape_match,
5356
+ rendered_html,
5357
+ flags=re.IGNORECASE | re.DOTALL,
5358
+ )
5359
+ rendered_html = re.sub(
5360
+ rf"<\s*/?\s*{tag}\b[^>]*>",
5361
+ escape_match,
5362
+ rendered_html,
5363
+ flags=re.IGNORECASE,
5364
+ )
5365
+ for tag in dangerous_tags:
5366
+ rendered_html = re.sub(
5367
+ rf"<\s*/?\s*{tag}\b[^>]*>",
5368
+ escape_match,
5369
+ rendered_html,
5370
+ flags=re.IGNORECASE,
5371
+ )
5372
+
5373
+ rendered_html = re.sub(
5374
+ r"\s+on[a-zA-Z0-9_-]+\s*=\s*(\"[^\"]*\"|'[^']*'|[^\s>]+)",
5375
+ "",
5376
+ rendered_html,
5377
+ flags=re.IGNORECASE,
5378
+ )
5379
+ rendered_html = re.sub(
5380
+ r"\s+(href|src)\s*=\s*([\"'])\s*(javascript:|data:text/html)",
5381
+ r" \1=\2#",
5382
+ rendered_html,
5383
+ flags=re.IGNORECASE,
5384
+ )
5385
+ return rendered_html
5386
+
5387
+
5388
  def _docs_search_text(entry: dict[str, str]) -> str:
5389
  text = f"{entry['title']} {entry['path']} {entry['summary']} {entry['body']}"
5390
  text = re.sub(r"```.*?```", " ", text, flags=re.DOTALL)
5391
  text = re.sub(r"!!!\s+\w+(?:\s+\"[^\"]+\")?", " ", text)
5392
+ text = re.sub(r"<[^>]+>", " ", text)
5393
  text = re.sub(r"[*_`#>\[\]().!:-]+", " ", text)
5394
  return re.sub(r"\s+", " ", text).strip().lower()
5395
 
 
6027
  return _layout("Harness Setup", body)
6028
 
6029
 
6030
+ def _kpi_summary_cache_key(sidecar_dir: Path) -> tuple[Any, ...]:
6031
+ parts: list[Any] = []
6032
+ for path in (sidecar_dir, sidecar_dir / "mcp"):
6033
+ try:
6034
+ stat = path.stat()
6035
+ parts.extend((path.resolve(), stat.st_mtime_ns, stat.st_size))
6036
+ except OSError:
6037
+ parts.extend((path.resolve(), None, None))
6038
+ return tuple(parts)
6039
+
6040
+
6041
  def _kpi_summary():
6042
  """Compute the KPI DashboardSummary using the default source layout.
6043
 
 
6053
  sidecar_dir = _sidecar_dir()
6054
  if not sidecar_dir.is_dir():
6055
  return None
6056
+ cache_key = _kpi_summary_cache_key(sidecar_dir)
6057
+ global _KPI_SUMMARY_CACHE_AT, _KPI_SUMMARY_CACHE_KEY, _KPI_SUMMARY_CACHE_VALUE
6058
+ if (
6059
+ _KPI_SUMMARY_CACHE_KEY == cache_key
6060
+ and _KPI_SUMMARY_CACHE_VALUE is not None
6061
+ and time.monotonic() - _KPI_SUMMARY_CACHE_AT < _KPI_SUMMARY_CACHE_SECONDS
6062
+ ):
6063
+ return _KPI_SUMMARY_CACHE_VALUE
6064
  try:
6065
  from ctx_config import cfg # type: ignore
6066
  sources = LifecycleSources(
 
6075
  sidecar_dir=sidecar_dir,
6076
  )
6077
  try:
6078
+ summary = generate(sources=sources, top_n=25)
6079
  except Exception: # noqa: BLE001
6080
  return None
6081
+ _KPI_SUMMARY_CACHE_KEY = cache_key
6082
+ _KPI_SUMMARY_CACHE_VALUE = summary
6083
+ _KPI_SUMMARY_CACHE_AT = time.monotonic()
6084
+ return summary
6085
 
6086
 
6087
  def _render_kpi() -> str:
 
6787
  # require same-origin POSTs plus a per-process token injected into the
6788
  # served dashboard page.
6789
  def _same_origin(self) -> bool:
6790
+ request_host = _request_host_name(self.headers.get("Host", ""))
6791
+ if not _host_allows_mutations(request_host):
6792
+ return False
6793
  origin = self.headers.get("Origin") or ""
6794
  if origin:
6795
+ return _origin_host_name(origin) == request_host
 
 
6796
  # No Origin header (curl, direct tool calls) is acceptable only
6797
  # when the mutation token below is also present.
6798
  return True
 
6814
  return self._mutations_enabled()
6815
 
6816
  def _read_authorized(self, qs: dict[str, str]) -> bool:
6817
+ request_host = _request_host_name(self.headers.get("Host", ""))
6818
  if self._mutations_enabled():
6819
+ return _host_allows_mutations(request_host)
6820
+ token = (
6821
+ self.headers.get("X-CTX-Monitor-Token")
6822
+ or qs.get("token", "")
6823
+ or _read_token_cookie(self.headers.get("Cookie", ""))
6824
+ )
6825
  return bool(_MONITOR_TOKEN) and secrets.compare_digest(token, _MONITOR_TOKEN)
6826
 
6827
  def _send_security_headers(self, *, html_response: bool = False) -> None:
6828
  self.send_header("X-Content-Type-Options", "nosniff")
6829
  self.send_header("Referrer-Policy", "no-referrer")
6830
  self.send_header("X-Frame-Options", "DENY")
6831
+ if getattr(self, "_ctx_set_read_cookie", False):
6832
+ self.send_header(
6833
+ "Set-Cookie",
6834
+ f"{_READ_TOKEN_COOKIE}={_MONITOR_TOKEN}; Path=/; "
6835
+ "HttpOnly; SameSite=Strict",
6836
+ )
6837
  if html_response:
6838
  self.send_header(
6839
  "Content-Security-Policy",
 
6898
  from urllib.parse import parse_qs
6899
  qs = {k: v[0] for k, v in parse_qs(raw_query).items()}
6900
  try:
6901
+ self._ctx_set_read_cookie = False
6902
  read_authorized = getattr(self, "_read_authorized", lambda _qs: True)
6903
  if not read_authorized(qs):
6904
  if path.startswith("/api/"):
 
6913
  "<p>monitor read token required on non-loopback bind</p>",
6914
  )
6915
  return
6916
+ query_token = qs.get("token", "")
6917
+ self._ctx_set_read_cookie = (
6918
+ not self._mutations_enabled()
6919
+ and bool(query_token)
6920
+ and bool(_MONITOR_TOKEN)
6921
+ and secrets.compare_digest(query_token, _MONITOR_TOKEN)
6922
+ )
6923
  if path == "/":
6924
  self._send_html(_render_home())
6925
  elif path == "/sessions":
 
6927
  elif path.startswith("/session/"):
6928
  self._send_html(_render_session_detail(path.split("/session/", 1)[1]))
6929
  elif path == "/skills":
6930
+ self._send_html(_render_skills(qs))
6931
  elif path.startswith("/skill/"):
6932
  self._send_html(_render_skill_detail(
6933
  path.split("/skill/", 1)[1],
 
6979
  })
6980
  elif path == "/api/grades.json":
6981
  self._send_json(_grade_distribution_payload())
6982
+ elif path == "/api/sidecars.json":
6983
+ self._send_json(_sidecar_page_payload(qs))
6984
  elif path == "/api/runtime.json":
6985
  self._send_json(_runtime_lifecycle_summary())
6986
  elif path == "/api/config.json":
 
7259
  """Run the monitor. Blocks until Ctrl+C."""
7260
  global _MONITOR_TOKEN
7261
  server = _make_monitor_server(host, port)
7262
+ _MONITOR_TOKEN = secrets.token_urlsafe(32)
7263
+ mutations_enabled = bool(getattr(server, "_ctx_mutations_enabled", False))
7264
+ url = f"http://{_monitor_display_host(host)}:{port}/"
7265
+ if not mutations_enabled:
7266
+ url = f"{url}?token={_MONITOR_TOKEN}"
 
7267
  print(f"ctx-monitor serving at {url} (Ctrl+C to stop)", flush=True)
7268
+ if not mutations_enabled:
7269
  print(
7270
+ "ctx-monitor: non-loopback bind; read token required and "
7271
+ "load/unload mutations disabled",
7272
  flush=True,
7273
  )
7274
  try:
 
7279
  server.server_close()
7280
 
7281
 
7282
+ def _monitor_display_host(host: str) -> str:
7283
+ """Return a URL host users can paste into a browser."""
7284
+ if host in {"0.0.0.0", "::"}:
7285
+ try:
7286
+ candidate = socket.gethostbyname(socket.gethostname())
7287
+ except OSError:
7288
+ candidate = ""
7289
+ if candidate and not candidate.startswith("127."):
7290
+ return candidate
7291
+ return "localhost"
7292
+ if ":" in host and not host.startswith("["):
7293
+ return f"[{host}]"
7294
+ return host
7295
+
7296
+
7297
  def main(argv: list[str] | None = None) -> int:
7298
  parser = argparse.ArgumentParser(
7299
  prog="ctx-monitor",
src/harness_install.py CHANGED
@@ -252,6 +252,16 @@ def _local_source_from_repo_url(repo_url: str) -> Path | None:
252
  return candidate if candidate.exists() else None
253
 
254
 
 
 
 
 
 
 
 
 
 
 
255
  def _reject_symlink_tree(root: Path) -> None:
256
  if root.is_symlink():
257
  raise ValueError(f"refusing symlinked harness source: {root}")
@@ -265,9 +275,11 @@ def _is_full_commit_sha(value: str | None) -> bool:
265
 
266
 
267
  def _run_git(args: list[str], *, timeout: int = 300) -> subprocess.CompletedProcess[str]:
 
 
268
  return subprocess.run(
269
  ["git", *args],
270
- env=_command_env(),
271
  capture_output=True,
272
  text=True,
273
  check=False,
@@ -296,7 +308,7 @@ def _materialize_source(
296
  if not allow_local_sources:
297
  raise ValueError(
298
  "local harness repo_url requires --allow-local-source; "
299
- "cataloged harnesses should normally use https:// repositories"
300
  )
301
  local_source = local_source.expanduser().resolve()
302
  if not local_source.is_dir():
@@ -305,6 +317,8 @@ def _materialize_source(
305
  shutil.copytree(local_source, target)
306
  return {"source_type": "local"}
307
 
 
 
308
  if record.repo_ref and not _is_full_commit_sha(record.repo_ref):
309
  raise ValueError(
310
  "harness repo_ref/commit_sha must be a full commit SHA; "
@@ -314,10 +328,10 @@ def _materialize_source(
314
  raise ValueError(
315
  "remote harness repo_url is not pinned to a commit; add commit_sha "
316
  "to the catalog page or pass --allow-mutable-repo-head explicitly"
317
- )
318
 
319
  if record.repo_ref:
320
- proc = _run_git(["clone", "--no-checkout", record.repo_url, str(target)])
321
  if proc.returncode != 0:
322
  stderr = proc.stderr.strip() or proc.stdout.strip()
323
  raise RuntimeError(f"git clone failed: {stderr}")
@@ -337,7 +351,7 @@ def _materialize_source(
337
  "resolved_commit": _git_resolved_commit(target) or "",
338
  }
339
 
340
- proc = _run_git(["clone", "--depth", "1", record.repo_url, str(target)])
341
  if proc.returncode != 0:
342
  stderr = proc.stderr.strip() or proc.stdout.strip()
343
  raise RuntimeError(f"git clone failed: {stderr}")
 
252
  return candidate if candidate.exists() else None
253
 
254
 
255
+ def _validate_remote_repo_url(repo_url: str) -> None:
256
+ parsed = urlparse(repo_url)
257
+ if repo_url.startswith("-"):
258
+ raise ValueError("remote harness repo_url must not start with '-'")
259
+ if parsed.scheme != "https" or not parsed.netloc:
260
+ raise ValueError("remote harness repo_url must be an https:// URL")
261
+ if parsed.username or parsed.password:
262
+ raise ValueError("remote harness repo_url must not include credentials")
263
+
264
+
265
  def _reject_symlink_tree(root: Path) -> None:
266
  if root.is_symlink():
267
  raise ValueError(f"refusing symlinked harness source: {root}")
 
275
 
276
 
277
  def _run_git(args: list[str], *, timeout: int = 300) -> subprocess.CompletedProcess[str]:
278
+ env = _command_env()
279
+ env["GIT_ALLOW_PROTOCOL"] = "https"
280
  return subprocess.run(
281
  ["git", *args],
282
+ env=env,
283
  capture_output=True,
284
  text=True,
285
  check=False,
 
308
  if not allow_local_sources:
309
  raise ValueError(
310
  "local harness repo_url requires --allow-local-source; "
311
+ "cataloged harnesses should normally use https:// repositories"
312
  )
313
  local_source = local_source.expanduser().resolve()
314
  if not local_source.is_dir():
 
317
  shutil.copytree(local_source, target)
318
  return {"source_type": "local"}
319
 
320
+ _validate_remote_repo_url(record.repo_url)
321
+
322
  if record.repo_ref and not _is_full_commit_sha(record.repo_ref):
323
  raise ValueError(
324
  "harness repo_ref/commit_sha must be a full commit SHA; "
 
328
  raise ValueError(
329
  "remote harness repo_url is not pinned to a commit; add commit_sha "
330
  "to the catalog page or pass --allow-mutable-repo-head explicitly"
331
+ )
332
 
333
  if record.repo_ref:
334
+ proc = _run_git(["clone", "--no-checkout", "--", record.repo_url, str(target)])
335
  if proc.returncode != 0:
336
  stderr = proc.stderr.strip() or proc.stdout.strip()
337
  raise RuntimeError(f"git clone failed: {stderr}")
 
351
  "resolved_commit": _git_resolved_commit(target) or "",
352
  }
353
 
354
+ proc = _run_git(["clone", "--depth", "1", "--", record.repo_url, str(target)])
355
  if proc.returncode != 0:
356
  stderr = proc.stderr.strip() or proc.stdout.strip()
357
  raise RuntimeError(f"git clone failed: {stderr}")
src/import_skills_sh_catalog.py CHANGED
@@ -68,6 +68,8 @@ CONVERTED_SKILL_ROOT = "converted"
68
  DEFAULT_DETAIL_MAX_BYTES = 2_000_000
69
  DEFAULT_SKILL_BODY_MAX_CHARS = 120_000
70
  GITHUB_RAW_HOST = "raw.githubusercontent.com"
 
 
71
  _HYDRATION_CHECKPOINT_FIELDS = (
72
  "id",
73
  "ctx_slug",
@@ -376,18 +378,23 @@ def _fetch_detail_html(
376
  return payload.decode("utf-8", errors="replace"), None
377
 
378
 
379
- def _github_raw_skill_urls(source: str, skill_id: str) -> list[str]:
380
  if (
381
  "/" not in source
382
  or source.startswith(("http://", "https://"))
383
- or not skill_id.strip()
384
  ):
385
- return []
386
  owner, repo = source.split("/", 1)
387
  if not owner or not repo:
 
 
 
 
 
 
 
388
  return []
389
- owner_q = urllib.parse.quote(owner, safe="")
390
- repo_q = urllib.parse.quote(repo, safe=".-_")
391
  skill_q = urllib.parse.quote(skill_id.strip("/"), safe="")
392
  filenames = ("SKILL.md", "Skill.md", "skill.md")
393
  candidate_paths = [
@@ -403,11 +410,79 @@ def _github_raw_skill_urls(source: str, skill_id: str) -> list[str]:
403
  ]
404
  if _slugify(repo) == _slugify(skill_id):
405
  candidate_paths.extend(filenames)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
406
  urls: list[str] = []
407
  for branch in ("main", "master"):
 
 
 
 
 
 
 
 
408
  for path in candidate_paths:
409
  urls.append(
410
- f"https://{GITHUB_RAW_HOST}/{owner_q}/{repo_q}/{branch}/{path}",
411
  )
412
  return urls
413
 
@@ -421,7 +496,7 @@ def _fetch_github_raw_skill_body(
421
  source = str(item.get("source") or "")
422
  skill_id = str(item.get("skill_id") or item.get("skillId") or "")
423
  raw_timeout = min(timeout, 12)
424
- for url in _github_raw_skill_urls(source, skill_id):
425
  req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
426
  try:
427
  with urllib.request.urlopen(req, timeout=raw_timeout) as response:
@@ -433,7 +508,7 @@ def _fetch_github_raw_skill_body(
433
  body = _normalize_skill_body_text(payload.decode("utf-8", errors="replace"))
434
  if body:
435
  return body, url, None
436
- return None, None, "GitHub raw fallback found no SKILL.md candidates"
437
 
438
 
439
  def _refresh_body_summary(catalog: dict[str, Any]) -> dict[str, Any]:
 
68
  DEFAULT_DETAIL_MAX_BYTES = 2_000_000
69
  DEFAULT_SKILL_BODY_MAX_CHARS = 120_000
70
  GITHUB_RAW_HOST = "raw.githubusercontent.com"
71
+ GITHUB_API_HOST = "api.github.com"
72
+ _GITHUB_COMMIT_SHA_RE = re.compile(r"^[0-9a-f]{40}$", re.IGNORECASE)
73
  _HYDRATION_CHECKPOINT_FIELDS = (
74
  "id",
75
  "ctx_slug",
 
378
  return payload.decode("utf-8", errors="replace"), None
379
 
380
 
381
+ def _github_repo_parts(source: str) -> tuple[str, str] | None:
382
  if (
383
  "/" not in source
384
  or source.startswith(("http://", "https://"))
 
385
  ):
386
+ return None
387
  owner, repo = source.split("/", 1)
388
  if not owner or not repo:
389
+ return None
390
+ return owner, repo
391
+
392
+
393
+ def _github_raw_skill_candidate_paths(source: str, skill_id: str) -> list[str]:
394
+ repo_parts = _github_repo_parts(source)
395
+ if repo_parts is None or not skill_id.strip():
396
  return []
397
+ _, repo = repo_parts
 
398
  skill_q = urllib.parse.quote(skill_id.strip("/"), safe="")
399
  filenames = ("SKILL.md", "Skill.md", "skill.md")
400
  candidate_paths = [
 
410
  ]
411
  if _slugify(repo) == _slugify(skill_id):
412
  candidate_paths.extend(filenames)
413
+ seen: set[str] = set()
414
+ deduped: list[str] = []
415
+ for path in candidate_paths:
416
+ if path not in seen:
417
+ seen.add(path)
418
+ deduped.append(path)
419
+ return deduped
420
+
421
+
422
+ def _resolve_github_branch_sha(
423
+ owner: str,
424
+ repo: str,
425
+ branch: str,
426
+ *,
427
+ timeout: int,
428
+ ) -> str | None:
429
+ owner_q = urllib.parse.quote(owner, safe="")
430
+ repo_q = urllib.parse.quote(repo, safe="")
431
+ branch_q = urllib.parse.quote(branch, safe="")
432
+ url = f"https://{GITHUB_API_HOST}/repos/{owner_q}/{repo_q}/branches/{branch_q}"
433
+ req = urllib.request.Request(
434
+ url,
435
+ headers={
436
+ "User-Agent": USER_AGENT,
437
+ "Accept": "application/vnd.github+json",
438
+ },
439
+ )
440
+ try:
441
+ with urllib.request.urlopen(req, timeout=timeout) as response:
442
+ payload = response.read(32_768)
443
+ except Exception:
444
+ return None
445
+ try:
446
+ data = json.loads(payload.decode("utf-8", errors="replace"))
447
+ except json.JSONDecodeError:
448
+ return None
449
+ if not isinstance(data, dict):
450
+ return None
451
+ commit = data.get("commit")
452
+ sha = commit.get("sha") if isinstance(commit, dict) else None
453
+ if isinstance(sha, str) and _GITHUB_COMMIT_SHA_RE.fullmatch(sha):
454
+ return sha
455
+ return None
456
+
457
+
458
+ def _github_raw_skill_urls(
459
+ source: str,
460
+ skill_id: str,
461
+ *,
462
+ timeout: int = 12,
463
+ ) -> list[str]:
464
+ repo_parts = _github_repo_parts(source)
465
+ if repo_parts is None:
466
+ return []
467
+ owner, repo = repo_parts
468
+ candidate_paths = _github_raw_skill_candidate_paths(source, skill_id)
469
+ if not candidate_paths:
470
+ return []
471
+ owner_q = urllib.parse.quote(owner, safe="")
472
+ repo_q = urllib.parse.quote(repo, safe=".-_")
473
  urls: list[str] = []
474
  for branch in ("main", "master"):
475
+ branch_sha = _resolve_github_branch_sha(
476
+ owner,
477
+ repo,
478
+ branch,
479
+ timeout=timeout,
480
+ )
481
+ if branch_sha is None:
482
+ continue
483
  for path in candidate_paths:
484
  urls.append(
485
+ f"https://{GITHUB_RAW_HOST}/{owner_q}/{repo_q}/{branch_sha}/{path}",
486
  )
487
  return urls
488
 
 
496
  source = str(item.get("source") or "")
497
  skill_id = str(item.get("skill_id") or item.get("skillId") or "")
498
  raw_timeout = min(timeout, 12)
499
+ for url in _github_raw_skill_urls(source, skill_id, timeout=raw_timeout):
500
  req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
501
  try:
502
  with urllib.request.urlopen(req, timeout=raw_timeout) as response:
 
508
  body = _normalize_skill_body_text(payload.decode("utf-8", errors="replace"))
509
  if body:
510
  return body, url, None
511
+ return None, None, "GitHub raw fallback found no pinned SKILL.md candidates"
512
 
513
 
514
  def _refresh_body_summary(catalog: dict[str, Any]) -> dict[str, Any]:
src/kpi_dashboard.py CHANGED
@@ -26,6 +26,7 @@ Design notes:
26
  from __future__ import annotations
27
 
28
  import argparse
 
29
  import json
30
  import logging
31
  import sys
@@ -35,15 +36,15 @@ from pathlib import Path
35
  from typing import Any, Iterable
36
 
37
  from ctx_lifecycle import (
 
38
  LifecycleSources,
39
  STATE_ACTIVE,
40
  STATE_ARCHIVE,
41
  STATE_DEMOTE,
42
  STATE_WATCH,
43
- load_lifecycle_state,
44
  )
45
  from skill_category import CATEGORIES, infer_category, read_existing_category
46
- from skill_quality import QualityScore, load_quality
47
  from ctx.core.wiki.wiki_utils import parse_frontmatter_and_body
48
 
49
  _logger = logging.getLogger(__name__)
@@ -53,6 +54,8 @@ _UNCATEGORIZED = "uncategorized"
53
  _LIFECYCLE_STATES: tuple[str, ...] = (
54
  STATE_ACTIVE, STATE_WATCH, STATE_DEMOTE, STATE_ARCHIVE,
55
  )
 
 
56
 
57
 
58
  # ────────────────────────────────────────────────────────────────────
@@ -108,19 +111,33 @@ class DashboardSummary:
108
  # ────────────────────────────────────────────────────────────────────
109
 
110
 
111
- def _skill_source_path(slug: str, sources: LifecycleSources) -> Path | None:
112
- skill_path = sources.skills_dir / slug / "SKILL.md"
113
- if skill_path.is_file():
114
- return skill_path
115
- agent_path = sources.agents_dir / f"{slug}.md"
116
- if agent_path.is_file():
117
- return agent_path
 
 
 
 
 
 
 
118
  return None
119
 
120
 
121
- def _resolve_category(slug: str, sources: LifecycleSources) -> str:
 
 
 
 
 
122
  """Read existing category, else infer from tags, else uncategorized."""
123
- path = _skill_source_path(slug, sources)
 
 
124
  if path is None:
125
  return _UNCATEGORIZED
126
  try:
@@ -164,18 +181,40 @@ def _iter_quality_slugs(sidecar_dir: Path) -> list[str]:
164
  return out
165
 
166
 
167
- def _quality_sources(sidecar_dir: Path) -> list[tuple[str, Path]]:
168
- out: list[tuple[str, Path]] = [
169
- (slug, sidecar_dir)
170
  for slug in _iter_quality_slugs(sidecar_dir)
171
  ]
172
  mcp_dir = sidecar_dir / "mcp"
173
  if mcp_dir.is_dir():
174
  for slug in _iter_quality_slugs(mcp_dir):
175
- out.append((slug, mcp_dir))
176
  return out
177
 
178
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  def _iter_lifecycle_slugs(sidecar_dir: Path) -> list[str]:
180
  if not sidecar_dir.is_dir():
181
  return []
@@ -183,19 +222,62 @@ def _iter_lifecycle_slugs(sidecar_dir: Path) -> list[str]:
183
  return sorted(p.name[: -len(suffix)] for p in sidecar_dir.glob(f"*{suffix}"))
184
 
185
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  def _build_row(
187
  slug: str,
188
  *,
189
  score: QualityScore | None,
 
190
  lifecycle_state: str,
191
  consecutive_d_count: int,
192
  sources: LifecycleSources,
193
  ) -> EntityRow:
194
- subject = score.subject_type if score is not None else _guess_subject(slug, sources)
 
 
 
 
195
  return EntityRow(
196
  slug=slug,
197
  subject_type=subject,
198
- category=_resolve_category(slug, sources),
199
  grade=(score.grade if score is not None else ""),
200
  score=(score.score if score is not None else 0.0),
201
  hard_floor=(score.hard_floor if score is not None else None),
@@ -218,35 +300,83 @@ def collect_rows(
218
  *, sources: LifecycleSources,
219
  ) -> list[EntityRow]:
220
  """Walk both sinks and return one row per known slug (union)."""
221
- quality_sources = _quality_sources(sources.sidecar_dir)
222
- quality_keys = set(quality_sources)
223
- quality_slugs = {slug for slug, _sidecar_dir in quality_sources}
224
- lifecycle_slugs = set(_iter_lifecycle_slugs(sources.sidecar_dir))
225
- row_sources = sorted(quality_keys, key=lambda item: (item[0], str(item[1]))) + [
226
- (slug, sources.sidecar_dir)
227
- for slug in sorted(lifecycle_slugs - quality_slugs)
228
- ]
229
- rows: list[EntityRow] = []
230
- for slug, sidecar_dir in row_sources:
 
231
  try:
232
- score = load_quality(
233
- slug,
234
- sidecar_dir=sidecar_dir,
 
 
235
  )
236
- except (json.JSONDecodeError, ValueError, OSError) as exc:
237
  _logger.warning("kpi_dashboard: skipping %s: %s", slug, exc)
238
  score = None
239
- lc = load_lifecycle_state(slug, sidecar_dir=sidecar_dir)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
  if lc is not None:
241
  state = lc.state
242
  streak = lc.consecutive_d_count
 
243
  else:
244
  state = STATE_ACTIVE
245
  streak = 0
 
246
  rows.append(
247
  _build_row(
248
  slug,
249
  score=score,
 
250
  lifecycle_state=state,
251
  consecutive_d_count=streak,
252
  sources=sources,
 
26
  from __future__ import annotations
27
 
28
  import argparse
29
+ import concurrent.futures
30
  import json
31
  import logging
32
  import sys
 
36
  from typing import Any, Iterable
37
 
38
  from ctx_lifecycle import (
39
+ LifecycleState,
40
  LifecycleSources,
41
  STATE_ACTIVE,
42
  STATE_ARCHIVE,
43
  STATE_DEMOTE,
44
  STATE_WATCH,
 
45
  )
46
  from skill_category import CATEGORIES, infer_category, read_existing_category
47
+ from skill_quality import QualityScore
48
  from ctx.core.wiki.wiki_utils import parse_frontmatter_and_body
49
 
50
  _logger = logging.getLogger(__name__)
 
54
  _LIFECYCLE_STATES: tuple[str, ...] = (
55
  STATE_ACTIVE, STATE_WATCH, STATE_DEMOTE, STATE_ARCHIVE,
56
  )
57
+ _PARALLEL_QUALITY_READ_THRESHOLD = 512
58
+ _QUALITY_READ_WORKERS = 8
59
 
60
 
61
  # ────────────────────────────────────────────────────────────────────
 
111
  # ────────────────────────────────────────────────────────────────────
112
 
113
 
114
+ def _skill_source_path(
115
+ slug: str,
116
+ sources: LifecycleSources,
117
+ *,
118
+ subject_type: str | None = None,
119
+ ) -> Path | None:
120
+ if subject_type in (None, "skill"):
121
+ skill_path = sources.skills_dir / slug / "SKILL.md"
122
+ if skill_path.is_file():
123
+ return skill_path
124
+ if subject_type in (None, "agent"):
125
+ agent_path = sources.agents_dir / f"{slug}.md"
126
+ if agent_path.is_file():
127
+ return agent_path
128
  return None
129
 
130
 
131
+ def _resolve_category(
132
+ slug: str,
133
+ sources: LifecycleSources,
134
+ *,
135
+ subject_type: str | None = None,
136
+ ) -> str:
137
  """Read existing category, else infer from tags, else uncategorized."""
138
+ if subject_type not in (None, "skill", "agent"):
139
+ return _UNCATEGORIZED
140
+ path = _skill_source_path(slug, sources, subject_type=subject_type)
141
  if path is None:
142
  return _UNCATEGORIZED
143
  try:
 
181
  return out
182
 
183
 
184
+ def _quality_sources(sidecar_dir: Path) -> list[tuple[str, Path, Path]]:
185
+ out: list[tuple[str, Path, Path]] = [
186
+ (slug, sidecar_dir, sidecar_dir / f"{slug}.json")
187
  for slug in _iter_quality_slugs(sidecar_dir)
188
  ]
189
  mcp_dir = sidecar_dir / "mcp"
190
  if mcp_dir.is_dir():
191
  for slug in _iter_quality_slugs(mcp_dir):
192
+ out.append((slug, mcp_dir, mcp_dir / f"{slug}.json"))
193
  return out
194
 
195
 
196
+ def _read_quality_file(
197
+ path: Path,
198
+ *,
199
+ subject_type_override: str | None = None,
200
+ ) -> QualityScore | None:
201
+ data = json.loads(path.read_text(encoding="utf-8"))
202
+ if not isinstance(data, dict):
203
+ raise ValueError(f"quality sidecar must be a JSON object: {path}")
204
+ subject_type = subject_type_override or str(data.get("subject_type") or "skill")
205
+ return QualityScore(
206
+ slug=str(data["slug"]),
207
+ subject_type=subject_type,
208
+ raw_score=float(data.get("raw_score", 0.0)),
209
+ score=float(data.get("score", 0.0)),
210
+ grade=str(data.get("grade") or "D"),
211
+ hard_floor=data.get("hard_floor"),
212
+ signals={},
213
+ weights={},
214
+ computed_at=str(data.get("computed_at") or ""),
215
+ )
216
+
217
+
218
  def _iter_lifecycle_slugs(sidecar_dir: Path) -> list[str]:
219
  if not sidecar_dir.is_dir():
220
  return []
 
222
  return sorted(p.name[: -len(suffix)] for p in sidecar_dir.glob(f"*{suffix}"))
223
 
224
 
225
+ def _read_lifecycle_file(path: Path) -> LifecycleState | None:
226
+ try:
227
+ data = json.loads(path.read_text(encoding="utf-8"))
228
+ except (json.JSONDecodeError, OSError):
229
+ return None
230
+ if not isinstance(data, dict):
231
+ return None
232
+ history_raw = data.get("history", [])
233
+ history = tuple(
234
+ dict(e) for e in history_raw if isinstance(e, dict)
235
+ )
236
+ try:
237
+ streak = int(data.get("consecutive_d_count", 0))
238
+ except (TypeError, ValueError):
239
+ streak = 0
240
+ return LifecycleState(
241
+ slug=str(data.get("slug") or path.name.removesuffix(".lifecycle.json")),
242
+ subject_type=str(data.get("subject_type") or "skill"),
243
+ state=str(data.get("state") or STATE_ACTIVE),
244
+ state_since=str(data.get("state_since") or ""),
245
+ consecutive_d_count=streak,
246
+ last_grade=str(data.get("last_grade") or ""),
247
+ last_seen_computed_at=str(data.get("last_seen_computed_at") or ""),
248
+ history=history,
249
+ )
250
+
251
+
252
+ def _load_lifecycle_states(sidecar_dir: Path) -> dict[str, LifecycleState]:
253
+ if not sidecar_dir.is_dir():
254
+ return {}
255
+ states: dict[str, LifecycleState] = {}
256
+ for path in sorted(sidecar_dir.glob("*.lifecycle.json")):
257
+ state = _read_lifecycle_file(path)
258
+ if state is not None:
259
+ states[state.slug] = state
260
+ return states
261
+
262
+
263
  def _build_row(
264
  slug: str,
265
  *,
266
  score: QualityScore | None,
267
+ lifecycle_subject_type: str | None = None,
268
  lifecycle_state: str,
269
  consecutive_d_count: int,
270
  sources: LifecycleSources,
271
  ) -> EntityRow:
272
+ subject = (
273
+ score.subject_type
274
+ if score is not None
275
+ else lifecycle_subject_type or _guess_subject(slug, sources)
276
+ )
277
  return EntityRow(
278
  slug=slug,
279
  subject_type=subject,
280
+ category=_resolve_category(slug, sources, subject_type=subject),
281
  grade=(score.grade if score is not None else ""),
282
  score=(score.score if score is not None else 0.0),
283
  hard_floor=(score.hard_floor if score is not None else None),
 
300
  *, sources: LifecycleSources,
301
  ) -> list[EntityRow]:
302
  """Walk both sinks and return one row per known slug (union)."""
303
+ lifecycle_cache: dict[Path, dict[str, LifecycleState]] = {}
304
+
305
+ def lifecycle_states(sidecar_dir: Path) -> dict[str, LifecycleState]:
306
+ if sidecar_dir not in lifecycle_cache:
307
+ lifecycle_cache[sidecar_dir] = _load_lifecycle_states(sidecar_dir)
308
+ return lifecycle_cache[sidecar_dir]
309
+
310
+ def load_quality_source(
311
+ source: tuple[str, Path, Path],
312
+ ) -> tuple[str, Path, QualityScore | None]:
313
+ slug, sidecar_dir, sidecar_path = source
314
  try:
315
+ score = _read_quality_file(
316
+ sidecar_path,
317
+ subject_type_override=(
318
+ "mcp-server" if sidecar_dir.name == "mcp" else None
319
+ ),
320
  )
321
+ except (json.JSONDecodeError, ValueError, OSError, KeyError, TypeError) as exc:
322
  _logger.warning("kpi_dashboard: skipping %s: %s", slug, exc)
323
  score = None
324
+ return slug, sidecar_dir, score
325
+
326
+ quality_sources = _quality_sources(sources.sidecar_dir)
327
+ if len(quality_sources) >= _PARALLEL_QUALITY_READ_THRESHOLD:
328
+ with concurrent.futures.ThreadPoolExecutor(
329
+ max_workers=_QUALITY_READ_WORKERS,
330
+ ) as pool:
331
+ quality_results = list(pool.map(load_quality_source, quality_sources))
332
+ else:
333
+ quality_results = [load_quality_source(source) for source in quality_sources]
334
+
335
+ quality_rows: list[tuple[str, Path, QualityScore | None, LifecycleState | None]] = []
336
+ quality_subjects: set[tuple[str, str]] = set()
337
+ for slug, sidecar_dir, score in quality_results:
338
+ if score is not None:
339
+ quality_subjects.add((slug, score.subject_type))
340
+ quality_rows.append((slug, sidecar_dir, score, None))
341
+
342
+ lifecycle_rows: list[tuple[str, Path, QualityScore | None, LifecycleState | None]] = []
343
+ for lifecycle_slug, lifecycle_state in lifecycle_states(sources.sidecar_dir).items():
344
+ if (lifecycle_slug, lifecycle_state.subject_type) not in quality_subjects:
345
+ lifecycle_rows.append(
346
+ (lifecycle_slug, sources.sidecar_dir, None, lifecycle_state)
347
+ )
348
+
349
+ row_sources = sorted(
350
+ quality_rows + lifecycle_rows,
351
+ key=lambda item: (item[0], str(item[1]), item[3].subject_type if item[3] else ""),
352
+ )
353
+ rows: list[EntityRow] = []
354
+ for slug, sidecar_dir, score, lifecycle_override in row_sources:
355
+ lc = lifecycle_override
356
+ if lc is None and score is not None:
357
+ candidates = [sidecar_dir]
358
+ if sidecar_dir != sources.sidecar_dir:
359
+ candidates.append(sources.sidecar_dir)
360
+ for candidate_dir in candidates:
361
+ candidate = lifecycle_states(candidate_dir).get(slug)
362
+ if candidate is not None and candidate.subject_type == score.subject_type:
363
+ lc = candidate
364
+ break
365
+ elif lc is None:
366
+ lc = lifecycle_states(sidecar_dir).get(slug)
367
  if lc is not None:
368
  state = lc.state
369
  streak = lc.consecutive_d_count
370
+ lifecycle_subject_type = lc.subject_type
371
  else:
372
  state = STATE_ACTIVE
373
  streak = 0
374
+ lifecycle_subject_type = None
375
  rows.append(
376
  _build_row(
377
  slug,
378
  score=score,
379
+ lifecycle_subject_type=lifecycle_subject_type,
380
  lifecycle_state=state,
381
  consecutive_d_count=streak,
382
  sources=sources,
src/mcp_add.py CHANGED
@@ -25,6 +25,7 @@ import json
25
  import os
26
  import re
27
  import sys
 
28
  from datetime import datetime, timezone
29
  from pathlib import Path
30
  from typing import Any
@@ -128,6 +129,54 @@ def _rewrite_frontmatter(page_text: str, new_fm: dict[str, Any]) -> str:
128
  return f"---\n{fm_str}---\n{body}"
129
 
130
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  def _normalize_github_url(url: str | None) -> str | None:
132
  """Return the canonical lowercase GitHub URL, or None for non-GitHub inputs.
133
 
@@ -333,13 +382,12 @@ def add_mcp(
333
  if is_new_page:
334
  final_text = generate_mcp_page(record)
335
  else:
336
- updated_fm = {
337
- **existing_fm,
338
- "sources": merged_sources,
339
- "description": kept_description,
340
- "updated": TODAY,
341
- }
342
- final_text = _rewrite_frontmatter(existing_text, updated_fm)
343
 
344
  if review_existing and not is_new_page and not update_existing:
345
  review = build_update_review(
 
25
  import os
26
  import re
27
  import sys
28
+ from dataclasses import replace
29
  from datetime import datetime, timezone
30
  from pathlib import Path
31
  from typing import Any
 
129
  return f"---\n{fm_str}---\n{body}"
130
 
131
 
132
+ def _tuple_from_frontmatter(raw: object, fallback: tuple[str, ...]) -> tuple[str, ...]:
133
+ if isinstance(raw, str):
134
+ return tuple(item.strip() for item in raw.split(",") if item.strip())
135
+ if isinstance(raw, (list, tuple, set, frozenset)):
136
+ return tuple(str(item).strip() for item in raw if str(item).strip())
137
+ return fallback
138
+
139
+
140
+ def _optional_text_from_frontmatter(raw: object, fallback: str | None) -> str | None:
141
+ if raw is None:
142
+ return fallback
143
+ text = str(raw).strip()
144
+ return text or fallback
145
+
146
+
147
+ def _render_existing_update_page(
148
+ *,
149
+ existing_fm: dict[str, Any],
150
+ record: McpRecord,
151
+ merged_sources: list[str],
152
+ kept_description: str,
153
+ ) -> str:
154
+ updated_fm = {
155
+ **existing_fm,
156
+ "sources": merged_sources,
157
+ "description": kept_description,
158
+ "updated": TODAY,
159
+ }
160
+ render_record = replace(
161
+ record,
162
+ name=str(updated_fm.get("name") or record.name),
163
+ description=kept_description,
164
+ sources=tuple(merged_sources),
165
+ github_url=_optional_text_from_frontmatter(
166
+ updated_fm.get("github_url"), record.github_url
167
+ ),
168
+ homepage_url=_optional_text_from_frontmatter(
169
+ updated_fm.get("homepage_url"), record.homepage_url
170
+ ),
171
+ tags=_tuple_from_frontmatter(updated_fm.get("tags"), record.tags),
172
+ transports=_tuple_from_frontmatter(
173
+ updated_fm.get("transports"), record.transports
174
+ ),
175
+ )
176
+ rendered_text = generate_mcp_page(render_record)
177
+ return _rewrite_frontmatter(rendered_text, updated_fm)
178
+
179
+
180
  def _normalize_github_url(url: str | None) -> str | None:
181
  """Return the canonical lowercase GitHub URL, or None for non-GitHub inputs.
182
 
 
382
  if is_new_page:
383
  final_text = generate_mcp_page(record)
384
  else:
385
+ final_text = _render_existing_update_page(
386
+ existing_fm=existing_fm,
387
+ record=record,
388
+ merged_sources=merged_sources,
389
+ kept_description=kept_description,
390
+ )
 
391
 
392
  if review_existing and not is_new_page and not update_existing:
393
  review = build_update_review(
src/skill_add.py CHANGED
@@ -20,15 +20,15 @@ import yaml # type: ignore[import-untyped]
20
  from datetime import datetime, timezone
21
  from pathlib import Path
22
 
23
- from batch_convert import convert_skill
24
- from ctx.core.entity_update import build_update_review, render_update_review
25
- from ctx_config import cfg
26
- from intake_pipeline import IntakeRejected, check_intake, record_embedding
27
- from ctx.adapters.claude_code.install.install_utils import safe_copy_file
28
- from ctx.core.wiki.wiki_queue import enqueue_entity_upsert
29
- from ctx.core.wiki.wiki_sync import append_log, ensure_wiki, update_index
30
- from ctx.core.wiki.wiki_utils import validate_skill_name
31
- from ctx.utils._fs_utils import reject_symlink_path, safe_atomic_write_text
32
 
33
  TODAY = datetime.now(timezone.utc).strftime("%Y-%m-%d")
34
 
@@ -52,6 +52,13 @@ def install_skill(source: Path, skills_dir: Path, name: str) -> Path:
52
  return dest
53
 
54
 
 
 
 
 
 
 
 
55
  # ── Conversion ────────────────────────────────────────────────────────────────
56
 
57
  def maybe_convert(
@@ -92,12 +99,12 @@ def build_entity_page(
92
  *,
93
  name: str,
94
  tags: list[str],
95
- line_count: int,
96
- has_pipeline: bool,
97
- original_path: Path,
98
- related: list[str],
99
- scan_sources: list[str],
100
- ) -> str:
101
  """Render the full entity page markdown for a skill."""
102
  pipeline_path_str = (
103
  f"converted/{name}/" if has_pipeline else "null"
@@ -162,17 +169,61 @@ def build_entity_page(
162
  """
163
 
164
 
165
- def write_entity_page(wiki_path: Path, name: str, content: str) -> bool:
166
- """Write entity page. Returns True if newly created."""
167
- page = wiki_path / "entities" / "skills" / f"{name}.md"
168
- reject_symlink_path(page)
169
- is_new = not page.exists()
170
- safe_atomic_write_text(page, content, encoding="utf-8")
171
- return is_new
172
 
173
 
174
  # ── Wikilink backfill ─────────────────────────────────────────────────────────
175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  def find_related_skills(wiki_path: Path, name: str, tags: list[str]) -> list[str]:
177
  """Scan existing entity pages for skills that share at least one tag."""
178
  skills_dir = wiki_path / "entities" / "skills"
@@ -183,22 +234,19 @@ def find_related_skills(wiki_path: Path, name: str, tags: list[str]) -> list[str
183
  if page.stem == name:
184
  continue
185
  content = page.read_text(encoding="utf-8", errors="replace")
186
- m = re.search(r"^tags:\s*\[([^\]]*)\]", content, re.MULTILINE)
187
- if not m:
188
- continue
189
- page_tags = {t.strip() for t in m.group(1).split(",")}
190
  if tag_set & page_tags:
191
  related.append(page.stem)
192
 
193
  return related
194
 
195
 
196
- def _add_backlink(wiki_path: Path, target_name: str, source_name: str) -> None:
197
- """Add a [[wikilink]] from target page back to source if not already present."""
198
- page = wiki_path / "entities" / "skills" / f"{target_name}.md"
199
- reject_symlink_path(page)
200
- if not page.exists():
201
- return
202
  content = page.read_text(encoding="utf-8", errors="replace")
203
  link = f"[[entities/skills/{source_name}]]"
204
  if link in content:
@@ -212,7 +260,7 @@ def _add_backlink(wiki_path: Path, target_name: str, source_name: str) -> None:
212
  )
213
  else:
214
  content = content.rstrip() + f"\n\n- {link}\n"
215
- safe_atomic_write_text(page, content, encoding="utf-8")
216
 
217
 
218
  def wire_backlinks(wiki_path: Path, name: str, related: list[str]) -> None:
@@ -241,15 +289,15 @@ def detect_scan_sources(wiki_path: Path, name: str) -> list[str]:
241
 
242
  # ── Core orchestration ────────────────────────────────────────────────────────
243
 
244
- def add_skill(
245
- *,
246
- source_path: Path,
247
- name: str,
248
- wiki_path: Path,
249
- skills_dir: Path,
250
- review_existing: bool = False,
251
- update_existing: bool = False,
252
- ) -> dict:
253
  """Add a single skill: install, convert if needed, ingest into wiki.
254
 
255
  Returns a result dict with keys: name, installed, converted, is_new_page.
@@ -263,49 +311,53 @@ def add_skill(
263
  f"SKILL.md too large ({file_size:,} bytes). Max 1 MB. "
264
  f"Split the skill or trim content before ingestion."
265
  )
266
-
267
- content = source_path.read_text(encoding="utf-8", errors="replace")
268
- line_count = len(content.splitlines())
269
-
270
- installed_path = skills_dir / name / "SKILL.md"
271
- entity_page = wiki_path / "entities" / "skills" / f"{name}.md"
272
- existing_path = (
273
- installed_path
274
- if installed_path.exists()
275
- else entity_page if entity_page.exists() else None
276
- )
277
- has_existing = existing_path is not None
278
-
279
- if review_existing and has_existing and not update_existing:
280
- assert existing_path is not None
281
- existing_text = existing_path.read_text(encoding="utf-8", errors="replace")
282
- review = build_update_review(
283
- entity_type="skill",
284
- slug=name,
285
- existing_text=existing_text,
286
- proposed_text=content,
287
- )
288
- return {
289
- "name": name,
290
- "installed": str(installed_path),
291
- "converted": False,
292
- "is_new_page": False,
293
- "skipped": True,
294
- "update_required": True,
295
- "update_review": render_update_review(review),
296
- }
297
-
298
- if not has_existing:
299
- # Intake gate: reject broken/duplicate candidates before we touch
300
- # skills-dir. Existing updates bypass similarity intake because
301
- # they compare against their own cached embedding.
302
- decision = check_intake(content, "skills")
303
- if not decision.allow:
304
- raise IntakeRejected(decision)
305
-
306
- tags = infer_tags(name, content)
307
-
308
- # 1. Install original into skills-dir (never modified after this)
 
 
 
 
309
  installed_path = install_skill(source_path, skills_dir, name)
310
 
311
  # Record the candidate's embedding so future intake checks can
@@ -323,6 +375,8 @@ def add_skill(
323
  # 2. Convert if above threshold
324
  converted_root = wiki_path / "converted"
325
  converted, pipeline_path = maybe_convert(installed_path, name, converted_root, line_count)
 
 
326
 
327
  # 3. Detect related skills and scan sources (before writing new page)
328
  related = find_related_skills(wiki_path, name, tags)
@@ -341,12 +395,12 @@ def add_skill(
341
  page_content = build_entity_page(
342
  name=name,
343
  tags=tags,
344
- line_count=line_count,
345
- has_pipeline=converted,
346
- original_path=installed_path,
347
- related=related,
348
- scan_sources=scan_sources,
349
- )
350
  is_new = write_entity_page(wiki_path, name, page_content)
351
 
352
  # 5. Bidirectional wikilinks
@@ -364,21 +418,21 @@ def add_skill(
364
  f"Converted: {converted}",
365
  f"Related: {', '.join(related) if related else 'none'}",
366
  ]
367
- if converted and pipeline_path:
368
- log_details.append(f"Pipeline: {pipeline_path}")
369
- append_log(str(wiki_path), "add-skill", name, log_details)
370
- queue_job = enqueue_entity_upsert(
371
- wiki_path,
372
- entity_type="skill",
373
- slug=name,
374
- entity_path=wiki_path / "entities" / "skills" / f"{name}.md",
375
- content=page_content,
376
- action="created" if is_new else "updated",
377
- source="skill_add",
378
- )
379
-
380
- # Append to the unified audit log so post-hoc investigations can
381
- # reconstruct every add/convert/install event without mining
382
  # per-subsystem log files. See src/ctx_audit_log.py.
383
  try:
384
  from ctx_audit_log import log_skill_event
@@ -403,15 +457,15 @@ def add_skill(
403
  except Exception: # noqa: BLE001 — audit is best-effort
404
  pass
405
 
406
- return {
407
- "name": name,
408
- "installed": str(installed_path),
409
- "converted": converted,
410
- "is_new_page": is_new,
411
- "skipped": False,
412
- "update_required": False,
413
- "queued_job_id": queue_job.id,
414
- }
415
 
416
 
417
  # ── CLI ───────────────────────────────────────────────────────────────────────
@@ -420,14 +474,14 @@ def main() -> None:
420
  parser = argparse.ArgumentParser(description="Add new skills with wiki ingestion")
421
  parser.add_argument("--skill-path", help="Path to a single SKILL.md to add")
422
  parser.add_argument("--name", help="Skill name (required with --skill-path)")
423
- parser.add_argument("--scan-dir", help="Directory of skills to batch-add (each subdir with SKILL.md)")
424
- parser.add_argument("--skip-existing", action="store_true", help="Skip skills already installed (prevents overwrites)")
425
- parser.add_argument(
426
- "--update-existing",
427
- action="store_true",
428
- help="Apply the reviewed replacement when a skill already exists",
429
- )
430
- parser.add_argument("--wiki", default=str(cfg.wiki_dir), help="Wiki path")
431
  parser.add_argument("--skills-dir", default=str(cfg.skills_dir), help="Skills install path")
432
  args = parser.parse_args()
433
 
@@ -471,7 +525,7 @@ def main() -> None:
471
  print(f"No SKILL.md files found under {scan_root}.", file=sys.stderr)
472
  sys.exit(0)
473
 
474
- added = updated = converted = skipped = errors = 0
475
  total = len(candidates)
476
  for i, (source_path, name) in enumerate(candidates, 1):
477
  # Skip if already installed and --skip-existing is set
@@ -483,38 +537,38 @@ def main() -> None:
483
  try:
484
  result = add_skill(
485
  source_path=source_path,
486
- name=name,
487
- wiki_path=wiki_path,
488
- skills_dir=skills_dir,
489
- review_existing=True,
490
- update_existing=args.update_existing,
491
- )
492
- if result.get("skipped"):
493
- skipped += 1
494
- if result.get("update_review"):
495
- print(result["update_review"])
496
- print(f" [{i}/{total}] [update-review] {name}")
497
- continue
498
- if result["is_new_page"]:
499
- added += 1
500
- else:
501
- updated += 1
502
- if result["converted"]:
503
- converted += 1
504
- status = (
505
- "updated"
506
- if not result["is_new_page"]
507
- else "converted" if result["converted"] else "installed"
508
- )
509
- print(f" [{i}/{total}] [{status}] {name}")
510
  except Exception as exc:
511
  errors += 1
512
  print(f" [{i}/{total}] ERROR: {name}: {exc}", file=sys.stderr)
513
 
514
- print(
515
- f"\nDone: {added} added, {updated} updated, {converted} converted, "
516
- f"{skipped} skipped, {errors} errors"
517
- )
518
 
519
 
520
  if __name__ == "__main__":
 
20
  from datetime import datetime, timezone
21
  from pathlib import Path
22
 
23
+ from batch_convert import convert_skill
24
+ from ctx.core.entity_update import build_update_review, render_update_review
25
+ from ctx_config import cfg
26
+ from intake_pipeline import IntakeRejected, check_intake, record_embedding
27
+ from ctx.adapters.claude_code.install.install_utils import safe_copy_file
28
+ from ctx.core.wiki.wiki_queue import enqueue_entity_upsert
29
+ from ctx.core.wiki.wiki_sync import append_log, ensure_wiki, update_index
30
+ from ctx.core.wiki.wiki_utils import parse_frontmatter, validate_skill_name
31
+ from ctx.utils._fs_utils import reject_symlink_path, safe_atomic_write_text
32
 
33
  TODAY = datetime.now(timezone.utc).strftime("%Y-%m-%d")
34
 
 
52
  return dest
53
 
54
 
55
+ def mirror_install_body(installed_path: Path, name: str, converted_root: Path) -> Path:
56
+ """Mirror a short installed SKILL.md into the wiki install source tree."""
57
+ dest = converted_root / name / "SKILL.md"
58
+ safe_copy_file(installed_path, dest, dest_root=converted_root)
59
+ return dest
60
+
61
+
62
  # ── Conversion ────────────────────────────────────────────────────────────────
63
 
64
  def maybe_convert(
 
99
  *,
100
  name: str,
101
  tags: list[str],
102
+ line_count: int,
103
+ has_pipeline: bool,
104
+ original_path: Path,
105
+ related: list[str],
106
+ scan_sources: list[str],
107
+ ) -> str:
108
  """Render the full entity page markdown for a skill."""
109
  pipeline_path_str = (
110
  f"converted/{name}/" if has_pipeline else "null"
 
169
  """
170
 
171
 
172
+ def write_entity_page(wiki_path: Path, name: str, content: str) -> bool:
173
+ """Write entity page. Returns True if newly created."""
174
+ page = wiki_path / "entities" / "skills" / f"{name}.md"
175
+ reject_symlink_path(page)
176
+ is_new = not page.exists()
177
+ safe_atomic_write_text(page, content, encoding="utf-8")
178
+ return is_new
179
 
180
 
181
  # ── Wikilink backfill ─────────────────────────────────────────────────────────
182
 
183
+ def _tag_set_from_frontmatter(raw: object) -> set[str]:
184
+ if raw is None:
185
+ return set()
186
+ if isinstance(raw, str):
187
+ values = raw.strip()
188
+ if values.startswith("[") and values.endswith("]"):
189
+ values = values[1:-1]
190
+ return {item.strip().strip("'\"") for item in values.split(",") if item.strip()}
191
+ if isinstance(raw, (list, tuple, set, frozenset)):
192
+ return {str(item).strip().strip("'\"") for item in raw if str(item).strip()}
193
+ return {str(raw).strip().strip("'\"")} if str(raw).strip() else set()
194
+
195
+
196
+ def _existing_skill_review_text(entity_page: Path, installed_path: Path) -> str:
197
+ if entity_page.exists():
198
+ existing = entity_page.read_text(encoding="utf-8", errors="replace")
199
+ if installed_path.exists():
200
+ installed = installed_path.read_text(encoding="utf-8", errors="replace")
201
+ existing += f"\n\n## Installed SKILL.md\n\n{installed}"
202
+ return existing
203
+ return installed_path.read_text(encoding="utf-8", errors="replace")
204
+
205
+
206
+ def _proposed_skill_review_text(
207
+ *,
208
+ name: str,
209
+ tags: list[str],
210
+ line_count: int,
211
+ source_content: str,
212
+ installed_path: Path,
213
+ wiki_path: Path,
214
+ ) -> str:
215
+ page_content = build_entity_page(
216
+ name=name,
217
+ tags=tags,
218
+ line_count=line_count,
219
+ has_pipeline=line_count > cfg.line_threshold,
220
+ original_path=installed_path,
221
+ related=find_related_skills(wiki_path, name, tags),
222
+ scan_sources=detect_scan_sources(wiki_path, name),
223
+ )
224
+ return f"{page_content}\n\n## Proposed SKILL.md\n\n{source_content}"
225
+
226
+
227
  def find_related_skills(wiki_path: Path, name: str, tags: list[str]) -> list[str]:
228
  """Scan existing entity pages for skills that share at least one tag."""
229
  skills_dir = wiki_path / "entities" / "skills"
 
234
  if page.stem == name:
235
  continue
236
  content = page.read_text(encoding="utf-8", errors="replace")
237
+ page_tags = _tag_set_from_frontmatter(parse_frontmatter(content).get("tags"))
 
 
 
238
  if tag_set & page_tags:
239
  related.append(page.stem)
240
 
241
  return related
242
 
243
 
244
+ def _add_backlink(wiki_path: Path, target_name: str, source_name: str) -> None:
245
+ """Add a [[wikilink]] from target page back to source if not already present."""
246
+ page = wiki_path / "entities" / "skills" / f"{target_name}.md"
247
+ reject_symlink_path(page)
248
+ if not page.exists():
249
+ return
250
  content = page.read_text(encoding="utf-8", errors="replace")
251
  link = f"[[entities/skills/{source_name}]]"
252
  if link in content:
 
260
  )
261
  else:
262
  content = content.rstrip() + f"\n\n- {link}\n"
263
+ safe_atomic_write_text(page, content, encoding="utf-8")
264
 
265
 
266
  def wire_backlinks(wiki_path: Path, name: str, related: list[str]) -> None:
 
289
 
290
  # ── Core orchestration ────────────────────────────────────────────────────────
291
 
292
+ def add_skill(
293
+ *,
294
+ source_path: Path,
295
+ name: str,
296
+ wiki_path: Path,
297
+ skills_dir: Path,
298
+ review_existing: bool = False,
299
+ update_existing: bool = False,
300
+ ) -> dict:
301
  """Add a single skill: install, convert if needed, ingest into wiki.
302
 
303
  Returns a result dict with keys: name, installed, converted, is_new_page.
 
311
  f"SKILL.md too large ({file_size:,} bytes). Max 1 MB. "
312
  f"Split the skill or trim content before ingestion."
313
  )
314
+
315
+ content = source_path.read_text(encoding="utf-8", errors="replace")
316
+ line_count = len(content.splitlines())
317
+
318
+ installed_path = skills_dir / name / "SKILL.md"
319
+ entity_page = wiki_path / "entities" / "skills" / f"{name}.md"
320
+ existing_path = (
321
+ installed_path
322
+ if installed_path.exists()
323
+ else entity_page if entity_page.exists() else None
324
+ )
325
+ has_existing = existing_path is not None
326
+ tags = infer_tags(name, content)
327
+
328
+ if review_existing and has_existing and not update_existing:
329
+ review = build_update_review(
330
+ entity_type="skill",
331
+ slug=name,
332
+ existing_text=_existing_skill_review_text(entity_page, installed_path),
333
+ proposed_text=_proposed_skill_review_text(
334
+ name=name,
335
+ tags=tags,
336
+ line_count=line_count,
337
+ source_content=content,
338
+ installed_path=installed_path,
339
+ wiki_path=wiki_path,
340
+ ),
341
+ )
342
+ return {
343
+ "name": name,
344
+ "installed": str(installed_path),
345
+ "converted": False,
346
+ "is_new_page": False,
347
+ "skipped": True,
348
+ "update_required": True,
349
+ "update_review": render_update_review(review),
350
+ }
351
+
352
+ if not has_existing:
353
+ # Intake gate: reject broken/duplicate candidates before we touch
354
+ # skills-dir. Existing updates bypass similarity intake because
355
+ # they compare against their own cached embedding.
356
+ decision = check_intake(content, "skills")
357
+ if not decision.allow:
358
+ raise IntakeRejected(decision)
359
+
360
+ # 1. Install original into skills-dir (never modified after this)
361
  installed_path = install_skill(source_path, skills_dir, name)
362
 
363
  # Record the candidate's embedding so future intake checks can
 
375
  # 2. Convert if above threshold
376
  converted_root = wiki_path / "converted"
377
  converted, pipeline_path = maybe_convert(installed_path, name, converted_root, line_count)
378
+ if not converted:
379
+ mirror_install_body(installed_path, name, converted_root)
380
 
381
  # 3. Detect related skills and scan sources (before writing new page)
382
  related = find_related_skills(wiki_path, name, tags)
 
395
  page_content = build_entity_page(
396
  name=name,
397
  tags=tags,
398
+ line_count=line_count,
399
+ has_pipeline=converted,
400
+ original_path=installed_path,
401
+ related=related,
402
+ scan_sources=scan_sources,
403
+ )
404
  is_new = write_entity_page(wiki_path, name, page_content)
405
 
406
  # 5. Bidirectional wikilinks
 
418
  f"Converted: {converted}",
419
  f"Related: {', '.join(related) if related else 'none'}",
420
  ]
421
+ if converted and pipeline_path:
422
+ log_details.append(f"Pipeline: {pipeline_path}")
423
+ append_log(str(wiki_path), "add-skill", name, log_details)
424
+ queue_job = enqueue_entity_upsert(
425
+ wiki_path,
426
+ entity_type="skill",
427
+ slug=name,
428
+ entity_path=wiki_path / "entities" / "skills" / f"{name}.md",
429
+ content=page_content,
430
+ action="created" if is_new else "updated",
431
+ source="skill_add",
432
+ )
433
+
434
+ # Append to the unified audit log so post-hoc investigations can
435
+ # reconstruct every add/convert/install event without mining
436
  # per-subsystem log files. See src/ctx_audit_log.py.
437
  try:
438
  from ctx_audit_log import log_skill_event
 
457
  except Exception: # noqa: BLE001 — audit is best-effort
458
  pass
459
 
460
+ return {
461
+ "name": name,
462
+ "installed": str(installed_path),
463
+ "converted": converted,
464
+ "is_new_page": is_new,
465
+ "skipped": False,
466
+ "update_required": False,
467
+ "queued_job_id": queue_job.id,
468
+ }
469
 
470
 
471
  # ── CLI ───────────────────────────────────────────────────────────────────────
 
474
  parser = argparse.ArgumentParser(description="Add new skills with wiki ingestion")
475
  parser.add_argument("--skill-path", help="Path to a single SKILL.md to add")
476
  parser.add_argument("--name", help="Skill name (required with --skill-path)")
477
+ parser.add_argument("--scan-dir", help="Directory of skills to batch-add (each subdir with SKILL.md)")
478
+ parser.add_argument("--skip-existing", action="store_true", help="Skip skills already installed (prevents overwrites)")
479
+ parser.add_argument(
480
+ "--update-existing",
481
+ action="store_true",
482
+ help="Apply the reviewed replacement when a skill already exists",
483
+ )
484
+ parser.add_argument("--wiki", default=str(cfg.wiki_dir), help="Wiki path")
485
  parser.add_argument("--skills-dir", default=str(cfg.skills_dir), help="Skills install path")
486
  args = parser.parse_args()
487
 
 
525
  print(f"No SKILL.md files found under {scan_root}.", file=sys.stderr)
526
  sys.exit(0)
527
 
528
+ added = updated = converted = skipped = errors = 0
529
  total = len(candidates)
530
  for i, (source_path, name) in enumerate(candidates, 1):
531
  # Skip if already installed and --skip-existing is set
 
537
  try:
538
  result = add_skill(
539
  source_path=source_path,
540
+ name=name,
541
+ wiki_path=wiki_path,
542
+ skills_dir=skills_dir,
543
+ review_existing=True,
544
+ update_existing=args.update_existing,
545
+ )
546
+ if result.get("skipped"):
547
+ skipped += 1
548
+ if result.get("update_review"):
549
+ print(result["update_review"])
550
+ print(f" [{i}/{total}] [update-review] {name}")
551
+ continue
552
+ if result["is_new_page"]:
553
+ added += 1
554
+ else:
555
+ updated += 1
556
+ if result["converted"]:
557
+ converted += 1
558
+ status = (
559
+ "updated"
560
+ if not result["is_new_page"]
561
+ else "converted" if result["converted"] else "installed"
562
+ )
563
+ print(f" [{i}/{total}] [{status}] {name}")
564
  except Exception as exc:
565
  errors += 1
566
  print(f" [{i}/{total}] ERROR: {name}: {exc}", file=sys.stderr)
567
 
568
+ print(
569
+ f"\nDone: {added} added, {updated} updated, {converted} converted, "
570
+ f"{skipped} skipped, {errors} errors"
571
+ )
572
 
573
 
574
  if __name__ == "__main__":
src/tests/test_agent_add.py CHANGED
@@ -1,162 +1,217 @@
1
- """Tests for agent_add existing-update review behavior."""
2
-
3
- from __future__ import annotations
4
-
5
- import sys
6
- from pathlib import Path
7
- from typing import Any
8
- from unittest.mock import MagicMock
9
-
10
- SRC_DIR = Path(__file__).resolve().parents[1]
11
- if str(SRC_DIR) not in sys.path:
12
- sys.path.insert(0, str(SRC_DIR))
13
-
14
- import agent_add # noqa: E402
15
-
16
-
17
- class _Decision:
18
- allow = True
19
- warnings: tuple[Any, ...] = ()
20
-
21
-
22
- def _agent_text(
23
- *,
24
- description: str = "Agent that reviews code changes with clear findings.",
25
- model: str = "inherit",
26
- body: str | None = None,
27
- ) -> str:
28
- body = body or (
29
- "This agent reviews code and reports concrete risks.\n\n"
30
- "## Review Process\n\n"
31
- "Read the diff, identify regressions, and return prioritized findings."
32
- )
33
- return "\n".join(
34
- [
35
- "---",
36
- "name: reviewer-agent",
37
- f"description: {description}",
38
- f"model: {model}",
39
- "---",
40
- "# reviewer-agent",
41
- "",
42
- body,
43
- ]
44
- )
45
-
46
-
47
- def _setup_paths(tmp_path: Path) -> tuple[Path, Path, Path]:
48
- wiki = tmp_path / "wiki"
49
- agents_dir = tmp_path / "agents"
50
- source = tmp_path / "reviewer-agent.md"
51
- (wiki / "entities" / "agents").mkdir(parents=True)
52
- agents_dir.mkdir(parents=True)
53
- return wiki, agents_dir, source
54
-
55
-
56
- def _patch_side_effects(monkeypatch: Any) -> MagicMock:
57
- check = MagicMock(return_value=_Decision())
58
- monkeypatch.setattr(agent_add, "check_intake", check)
59
- monkeypatch.setattr(agent_add, "record_embedding", MagicMock())
60
- monkeypatch.setattr(agent_add, "update_index", MagicMock())
61
- monkeypatch.setattr(agent_add, "append_log", MagicMock())
62
- monkeypatch.setattr(agent_add, "ensure_wiki", MagicMock())
63
- return check
64
-
65
-
66
- def test_existing_agent_review_skips_without_mutating_files(
67
- tmp_path: Path,
68
- monkeypatch: Any,
69
- ) -> None:
70
- wiki, agents_dir, source = _setup_paths(tmp_path)
71
- installed = agents_dir / "reviewer-agent.md"
72
- existing_text = _agent_text(
73
- description="Detailed agent with a conservative review process.",
74
- model="sonnet",
75
- )
76
- installed.write_text(existing_text, encoding="utf-8")
77
- entity = wiki / "entities" / "agents" / "reviewer-agent.md"
78
- entity.write_text("# existing entity\n", encoding="utf-8")
79
- entity_text = entity.read_text(encoding="utf-8")
80
- source.write_text(
81
- _agent_text(description="Short agent.", model="haiku"),
82
- encoding="utf-8",
83
- )
84
- check = _patch_side_effects(monkeypatch)
85
-
86
- result = agent_add.add_agent(
87
- source_path=source,
88
- name="reviewer-agent",
89
- wiki_path=wiki,
90
- agents_dir=agents_dir,
91
- review_existing=True,
92
- )
93
-
94
- assert result["skipped"] is True
95
- assert result["update_required"] is True
96
- assert "Existing agent already exists: reviewer-agent" in result["update_review"]
97
- assert installed.read_text(encoding="utf-8") == existing_text
98
- assert entity.read_text(encoding="utf-8") == entity_text
99
- check.assert_not_called()
100
-
101
-
102
- def test_existing_agent_update_existing_applies_change(
103
- tmp_path: Path,
104
- monkeypatch: Any,
105
- ) -> None:
106
- wiki, agents_dir, source = _setup_paths(tmp_path)
107
- installed = agents_dir / "reviewer-agent.md"
108
- installed.write_text(_agent_text(), encoding="utf-8")
109
- entity = wiki / "entities" / "agents" / "reviewer-agent.md"
110
- entity.write_text("# existing entity\n", encoding="utf-8")
111
- updated_text = _agent_text(
112
- description="Updated agent with stronger review coverage.",
113
- model="opus",
114
- )
115
- source.write_text(updated_text, encoding="utf-8")
116
- _patch_side_effects(monkeypatch)
117
-
118
- result = agent_add.add_agent(
119
- source_path=source,
120
- name="reviewer-agent",
121
- wiki_path=wiki,
122
- agents_dir=agents_dir,
123
- review_existing=True,
124
- update_existing=True,
125
- )
126
-
127
- assert result["skipped"] is False
128
- assert result["update_required"] is False
129
- assert result["is_new_page"] is False
130
- assert installed.read_text(encoding="utf-8") == updated_text
131
- assert "Updated agent with stronger review coverage" in entity.read_text(
132
- encoding="utf-8"
133
- )
134
-
135
-
136
- def test_main_existing_agent_prints_update_review(
137
- tmp_path: Path,
138
- monkeypatch: Any,
139
- capsys: Any,
140
- ) -> None:
141
- wiki, agents_dir, source = _setup_paths(tmp_path)
142
- installed = agents_dir / "reviewer-agent.md"
143
- installed.write_text(_agent_text(), encoding="utf-8")
144
- source.write_text(
145
- _agent_text(description="Replacement agent."),
146
- encoding="utf-8",
147
- )
148
- _patch_side_effects(monkeypatch)
149
- monkeypatch.setattr(sys, "argv", [
150
- "agent_add.py",
151
- "--agent-path", str(source),
152
- "--name", "reviewer-agent",
153
- "--wiki", str(wiki),
154
- "--agents-dir", str(agents_dir),
155
- ])
156
-
157
- agent_add.main()
158
-
159
- out = capsys.readouterr().out
160
- assert "Existing agent already exists: reviewer-agent" in out
161
- assert "Use the explicit update flag" in out
162
- assert "Replacement agent." not in installed.read_text(encoding="utf-8")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for agent_add existing-update review behavior."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from pathlib import Path
7
+ from typing import Any
8
+ from unittest.mock import MagicMock
9
+
10
+ SRC_DIR = Path(__file__).resolve().parents[1]
11
+ if str(SRC_DIR) not in sys.path:
12
+ sys.path.insert(0, str(SRC_DIR))
13
+
14
+ import agent_add # noqa: E402
15
+
16
+
17
+ class _Decision:
18
+ allow = True
19
+ warnings: tuple[Any, ...] = ()
20
+
21
+
22
+ def _agent_text(
23
+ *,
24
+ description: str = "Agent that reviews code changes with clear findings.",
25
+ model: str = "inherit",
26
+ body: str | None = None,
27
+ ) -> str:
28
+ body = body or (
29
+ "This agent reviews code and reports concrete risks.\n\n"
30
+ "## Review Process\n\n"
31
+ "Read the diff, identify regressions, and return prioritized findings."
32
+ )
33
+ return "\n".join(
34
+ [
35
+ "---",
36
+ "name: reviewer-agent",
37
+ f"description: {description}",
38
+ f"model: {model}",
39
+ "---",
40
+ "# reviewer-agent",
41
+ "",
42
+ body,
43
+ ]
44
+ )
45
+
46
+
47
+ def _setup_paths(tmp_path: Path) -> tuple[Path, Path, Path]:
48
+ wiki = tmp_path / "wiki"
49
+ agents_dir = tmp_path / "agents"
50
+ source = tmp_path / "reviewer-agent.md"
51
+ (wiki / "entities" / "agents").mkdir(parents=True)
52
+ agents_dir.mkdir(parents=True)
53
+ return wiki, agents_dir, source
54
+
55
+
56
+ def _patch_side_effects(monkeypatch: Any) -> MagicMock:
57
+ check = MagicMock(return_value=_Decision())
58
+ monkeypatch.setattr(agent_add, "check_intake", check)
59
+ monkeypatch.setattr(agent_add, "record_embedding", MagicMock())
60
+ monkeypatch.setattr(agent_add, "update_index", MagicMock())
61
+ monkeypatch.setattr(agent_add, "append_log", MagicMock())
62
+ monkeypatch.setattr(agent_add, "ensure_wiki", MagicMock())
63
+ return check
64
+
65
+
66
+ def test_existing_agent_review_skips_without_mutating_files(
67
+ tmp_path: Path,
68
+ monkeypatch: Any,
69
+ ) -> None:
70
+ wiki, agents_dir, source = _setup_paths(tmp_path)
71
+ installed = agents_dir / "reviewer-agent.md"
72
+ existing_text = _agent_text(
73
+ description="Detailed agent with a conservative review process.",
74
+ model="sonnet",
75
+ )
76
+ installed.write_text(existing_text, encoding="utf-8")
77
+ entity = wiki / "entities" / "agents" / "reviewer-agent.md"
78
+ entity.write_text(
79
+ agent_add.generate_agent_page("reviewer-agent", installed),
80
+ encoding="utf-8",
81
+ )
82
+ entity_text = entity.read_text(encoding="utf-8")
83
+ source.write_text(
84
+ _agent_text(description="Short agent.", model="haiku"),
85
+ encoding="utf-8",
86
+ )
87
+ check = _patch_side_effects(monkeypatch)
88
+
89
+ result = agent_add.add_agent(
90
+ source_path=source,
91
+ name="reviewer-agent",
92
+ wiki_path=wiki,
93
+ agents_dir=agents_dir,
94
+ review_existing=True,
95
+ )
96
+
97
+ assert result["skipped"] is True
98
+ assert result["update_required"] is True
99
+ assert "Existing agent already exists: reviewer-agent" in result["update_review"]
100
+ assert "Changed frontmatter fields:" in result["update_review"]
101
+ assert "model" in result["update_review"]
102
+ assert installed.read_text(encoding="utf-8") == existing_text
103
+ assert entity.read_text(encoding="utf-8") == entity_text
104
+ check.assert_not_called()
105
+
106
+
107
+ def test_existing_agent_update_existing_applies_change(
108
+ tmp_path: Path,
109
+ monkeypatch: Any,
110
+ ) -> None:
111
+ wiki, agents_dir, source = _setup_paths(tmp_path)
112
+ installed = agents_dir / "reviewer-agent.md"
113
+ installed.write_text(_agent_text(), encoding="utf-8")
114
+ entity = wiki / "entities" / "agents" / "reviewer-agent.md"
115
+ entity.write_text("# existing entity\n", encoding="utf-8")
116
+ updated_text = _agent_text(
117
+ description="Updated agent with stronger review coverage.",
118
+ model="opus",
119
+ )
120
+ source.write_text(updated_text, encoding="utf-8")
121
+ _patch_side_effects(monkeypatch)
122
+
123
+ result = agent_add.add_agent(
124
+ source_path=source,
125
+ name="reviewer-agent",
126
+ wiki_path=wiki,
127
+ agents_dir=agents_dir,
128
+ review_existing=True,
129
+ update_existing=True,
130
+ )
131
+
132
+ assert result["skipped"] is False
133
+ assert result["update_required"] is False
134
+ assert result["is_new_page"] is False
135
+ assert installed.read_text(encoding="utf-8") == updated_text
136
+ assert "Updated agent with stronger review coverage" in entity.read_text(
137
+ encoding="utf-8"
138
+ )
139
+
140
+
141
+ def test_new_agent_add_writes_converted_agent_mirror(
142
+ tmp_path: Path,
143
+ monkeypatch: Any,
144
+ ) -> None:
145
+ wiki, agents_dir, source = _setup_paths(tmp_path)
146
+ source_text = _agent_text(description="Installable mirrored agent.")
147
+ source.write_text(source_text, encoding="utf-8")
148
+ _patch_side_effects(monkeypatch)
149
+
150
+ result = agent_add.add_agent(
151
+ source_path=source,
152
+ name="reviewer-agent",
153
+ wiki_path=wiki,
154
+ agents_dir=agents_dir,
155
+ )
156
+
157
+ mirror = wiki / "converted-agents" / "reviewer-agent.md"
158
+ assert result["is_new_page"] is True
159
+ assert mirror.read_text(encoding="utf-8") == source_text
160
+
161
+
162
+ def test_existing_agent_update_refreshes_converted_agent_mirror(
163
+ tmp_path: Path,
164
+ monkeypatch: Any,
165
+ ) -> None:
166
+ wiki, agents_dir, source = _setup_paths(tmp_path)
167
+ installed = agents_dir / "reviewer-agent.md"
168
+ installed.write_text(_agent_text(), encoding="utf-8")
169
+ mirror = wiki / "converted-agents" / "reviewer-agent.md"
170
+ mirror.parent.mkdir(parents=True)
171
+ mirror.write_text("old mirror\n", encoding="utf-8")
172
+ entity = wiki / "entities" / "agents" / "reviewer-agent.md"
173
+ entity.write_text("# existing entity\n", encoding="utf-8")
174
+ updated_text = _agent_text(description="Updated mirrored agent.")
175
+ source.write_text(updated_text, encoding="utf-8")
176
+ _patch_side_effects(monkeypatch)
177
+
178
+ result = agent_add.add_agent(
179
+ source_path=source,
180
+ name="reviewer-agent",
181
+ wiki_path=wiki,
182
+ agents_dir=agents_dir,
183
+ review_existing=True,
184
+ update_existing=True,
185
+ )
186
+
187
+ assert result["is_new_page"] is False
188
+ assert mirror.read_text(encoding="utf-8") == updated_text
189
+
190
+
191
+ def test_main_existing_agent_prints_update_review(
192
+ tmp_path: Path,
193
+ monkeypatch: Any,
194
+ capsys: Any,
195
+ ) -> None:
196
+ wiki, agents_dir, source = _setup_paths(tmp_path)
197
+ installed = agents_dir / "reviewer-agent.md"
198
+ installed.write_text(_agent_text(), encoding="utf-8")
199
+ source.write_text(
200
+ _agent_text(description="Replacement agent."),
201
+ encoding="utf-8",
202
+ )
203
+ _patch_side_effects(monkeypatch)
204
+ monkeypatch.setattr(sys, "argv", [
205
+ "agent_add.py",
206
+ "--agent-path", str(source),
207
+ "--name", "reviewer-agent",
208
+ "--wiki", str(wiki),
209
+ "--agents-dir", str(agents_dir),
210
+ ])
211
+
212
+ agent_add.main()
213
+
214
+ out = capsys.readouterr().out
215
+ assert "Existing agent already exists: reviewer-agent" in out
216
+ assert "Use the explicit update flag" in out
217
+ assert "Replacement agent." not in installed.read_text(encoding="utf-8")
src/tests/test_backup_mirror.py CHANGED
@@ -77,6 +77,27 @@ def test_create_captures_all_expected_files(fake_home):
77
  assert "memory/demo-slug/MEMORY.md" in dests
78
 
79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  def test_create_hashes_every_non_skipped_file(fake_home):
81
  _seed_home(fake_home)
82
  snap = bm.create_snapshot()
 
77
  assert "memory/demo-slug/MEMORY.md" in dests
78
 
79
 
80
+ def test_create_snapshot_does_not_copy_always_excluded_names_inside_trees(fake_home):
81
+ _seed_home(fake_home)
82
+ (fake_home / "skills" / "brainstorming" / ".credentials.json").write_text(
83
+ '{"token":"leaked"}',
84
+ encoding="utf-8",
85
+ )
86
+ (fake_home / "projects" / "demo-slug" / "memory" / "claude.json").write_text(
87
+ '{"token":"leaked"}',
88
+ encoding="utf-8",
89
+ )
90
+
91
+ snap = bm.create_snapshot()
92
+ manifest = json.loads((snap / "manifest.json").read_text())
93
+ dests = {entry["dest"] for entry in manifest["entries"]}
94
+
95
+ assert "skills/brainstorming/.credentials.json" not in dests
96
+ assert "memory/demo-slug/claude.json" not in dests
97
+ assert not (snap / "skills" / "brainstorming" / ".credentials.json").exists()
98
+ assert not (snap / "memory" / "demo-slug" / "claude.json").exists()
99
+
100
+
101
  def test_create_hashes_every_non_skipped_file(fake_home):
102
  _seed_home(fake_home)
103
  snap = bm.create_snapshot()
src/tests/test_ci_classifier.py CHANGED
@@ -70,6 +70,16 @@ def test_graph_preview_html_is_graph_artifact() -> None:
70
  assert flags["graph_only"] is True
71
 
72
 
 
 
 
 
 
 
 
 
 
 
73
  def test_graph_readme_is_docs_not_graph_artifact() -> None:
74
  flags = classify_paths(["graph/README.md"])
75
 
@@ -534,6 +544,23 @@ def test_ci_required_rejects_missing_graph_check_on_graph_only_pr() -> None:
534
  }
535
 
536
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
537
  def test_ci_required_allows_browser_skip_for_unrelated_pr_only() -> None:
538
  needs = _required_needs(
539
  classify={"result": "success", "outputs": {"browser_changed": "false"}},
@@ -564,6 +591,25 @@ def test_ci_required_rejects_missing_similarity_gate_on_source_pr() -> None:
564
  }
565
 
566
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
567
  def test_ci_required_allows_similarity_skip_for_unrelated_source_pr() -> None:
568
  needs = _required_needs(
569
  classify={
 
70
  assert flags["graph_only"] is True
71
 
72
 
73
+ def test_unknown_graph_file_is_graph_artifact() -> None:
74
+ flags = classify_paths(["graph/notes.json"])
75
+
76
+ assert flags["docs_changed"] is False
77
+ assert flags["docs_only"] is False
78
+ assert flags["graph_artifact_changed"] is True
79
+ assert flags["graph_changed"] is True
80
+ assert flags["graph_only"] is True
81
+
82
+
83
  def test_graph_readme_is_docs_not_graph_artifact() -> None:
84
  flags = classify_paths(["graph/README.md"])
85
 
 
544
  }
545
 
546
 
547
+ def test_ci_required_allows_graph_check_skip_for_nonartifact_graph_change() -> None:
548
+ needs = _required_needs(
549
+ classify={
550
+ "result": "success",
551
+ "outputs": {
552
+ "docs_only": "false",
553
+ "graph_artifact_changed": "false",
554
+ "graph_changed": "true",
555
+ "graph_only": "true",
556
+ },
557
+ },
558
+ **{"graph-check": {"result": "skipped"}},
559
+ )
560
+
561
+ assert failed_required_jobs(needs, event_name="pull_request") == {}
562
+
563
+
564
  def test_ci_required_allows_browser_skip_for_unrelated_pr_only() -> None:
565
  needs = _required_needs(
566
  classify={"result": "success", "outputs": {"browser_changed": "false"}},
 
591
  }
592
 
593
 
594
+ def test_ci_required_rejects_missing_similarity_gate_on_graph_only_pr() -> None:
595
+ needs = _required_needs(
596
+ classify={
597
+ "result": "success",
598
+ "outputs": {
599
+ "docs_only": "false",
600
+ "graph_only": "true",
601
+ "graph_artifact_changed": "true",
602
+ "similarity_changed": "true",
603
+ },
604
+ },
605
+ **{"similarity-integration": {"result": "skipped"}},
606
+ )
607
+
608
+ assert failed_required_jobs(needs, event_name="pull_request") == {
609
+ "similarity-integration": "skipped",
610
+ }
611
+
612
+
613
  def test_ci_required_allows_similarity_skip_for_unrelated_source_pr() -> None:
614
  needs = _required_needs(
615
  classify={
src/tests/test_config.py CHANGED
@@ -162,6 +162,25 @@ class TestConfigExpandTilde:
162
  assert cfg.wiki_dir.is_absolute()
163
 
164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  class TestConfigReload:
166
  """test_config_reload -- reload() picks up changes to the raw config."""
167
 
 
162
  assert cfg.wiki_dir.is_absolute()
163
 
164
 
165
+ def test_claude_adapter_modules_use_cfg_paths() -> None:
166
+ from ctx.adapters.claude_code import skill_health, skill_loader
167
+ from ctx.adapters.claude_code.install import install_utils, skill_unload
168
+
169
+ assert install_utils.MANIFEST_PATH == ctx_config.cfg.skill_manifest
170
+ assert skill_loader.SKILLS_DIR == ctx_config.cfg.skills_dir
171
+ assert skill_loader.AGENTS_DIR == ctx_config.cfg.agents_dir
172
+ assert skill_loader.WIKI_DIR == ctx_config.cfg.wiki_dir
173
+ assert skill_loader.PENDING_SKILLS == ctx_config.cfg.pending_skills
174
+ assert skill_loader.MANIFEST_PATH == ctx_config.cfg.skill_manifest
175
+ assert skill_unload.CLAUDE_DIR == ctx_config.cfg.claude_dir
176
+ assert skill_unload.WIKI_DIR == ctx_config.cfg.wiki_dir
177
+ assert skill_unload.MANIFEST_PATH == ctx_config.cfg.skill_manifest
178
+ assert skill_health.SKILLS_DIR == ctx_config.cfg.skills_dir
179
+ assert skill_health.AGENTS_DIR == ctx_config.cfg.agents_dir
180
+ assert skill_health.PENDING_PATH == ctx_config.cfg.pending_skills
181
+ assert skill_health.MANIFEST_PATH == ctx_config.cfg.skill_manifest
182
+
183
+
184
  class TestConfigReload:
185
  """test_config_reload -- reload() picks up changes to the raw config."""
186
 
src/tests/test_ctx_init.py CHANGED
@@ -571,6 +571,57 @@ def test_graph_install_copies_local_entity_overlay(
571
  assert payload["edges"][0]["method"] == "manual_direct_overlay_v1"
572
 
573
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
574
  def test_runtime_graph_install_extracts_harness_pages_after_required_files(
575
  tmp_path: Path,
576
  monkeypatch,
@@ -640,6 +691,36 @@ def test_runtime_graph_install_extracts_harness_pages_after_required_files(
640
  ).exists()
641
 
642
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
643
  def test_graph_install_rejects_incomplete_archive(
644
  tmp_path: Path,
645
  monkeypatch,
 
571
  assert payload["edges"][0]["method"] == "manual_direct_overlay_v1"
572
 
573
 
574
+ @pytest.mark.parametrize("field", ["semantic_sim", "tag_sim", "token_sim"])
575
+ def test_graph_overlay_validation_rejects_out_of_range_similarity_fields(
576
+ tmp_path: Path,
577
+ field: str,
578
+ ) -> None:
579
+ overlay = tmp_path / "entity-overlays.jsonl"
580
+ overlay.write_text(
581
+ json.dumps({
582
+ "nodes": [{"id": "skill:a"}],
583
+ "edges": [
584
+ {
585
+ "source": "skill:a",
586
+ "target": "skill:b",
587
+ "weight": 0.5,
588
+ "final_weight": 0.5,
589
+ field: 2.0,
590
+ },
591
+ ],
592
+ })
593
+ + "\n",
594
+ encoding="utf-8",
595
+ )
596
+
597
+ with pytest.raises(ValueError, match=f"{field} must be 0..1"):
598
+ ci._validate_graph_entity_overlay(overlay)
599
+
600
+
601
+ def test_graph_overlay_validation_rejects_weight_final_weight_drift(
602
+ tmp_path: Path,
603
+ ) -> None:
604
+ overlay = tmp_path / "entity-overlays.jsonl"
605
+ overlay.write_text(
606
+ json.dumps({
607
+ "nodes": [{"id": "skill:a"}],
608
+ "edges": [
609
+ {
610
+ "source": "skill:a",
611
+ "target": "skill:b",
612
+ "weight": 0.7,
613
+ "final_weight": 0.5,
614
+ },
615
+ ],
616
+ })
617
+ + "\n",
618
+ encoding="utf-8",
619
+ )
620
+
621
+ with pytest.raises(ValueError, match="weight must equal final_weight"):
622
+ ci._validate_graph_entity_overlay(overlay)
623
+
624
+
625
  def test_runtime_graph_install_extracts_harness_pages_after_required_files(
626
  tmp_path: Path,
627
  monkeypatch,
 
691
  ).exists()
692
 
693
 
694
+ def test_runtime_graph_install_preserves_existing_non_harness_entities(
695
+ tmp_path: Path,
696
+ monkeypatch,
697
+ ) -> None:
698
+ archive = _write_graph_archive(tmp_path)
699
+ claude = tmp_path / "home"
700
+ local_skill = claude / "skill-wiki" / "entities" / "skills" / "private.md"
701
+ local_agent = claude / "skill-wiki" / "entities" / "agents" / "private.md"
702
+ local_mcp = claude / "skill-wiki" / "entities" / "mcp-servers" / "p" / "private.md"
703
+ local_harness = claude / "skill-wiki" / "entities" / "harnesses" / "old.md"
704
+ for path in (local_skill, local_agent, local_mcp, local_harness):
705
+ path.parent.mkdir(parents=True, exist_ok=True)
706
+ path.write_text(f"# {path.stem}\n", encoding="utf-8")
707
+
708
+ monkeypatch.setattr(
709
+ ci,
710
+ "_find_local_graph_archive",
711
+ lambda _install_mode="runtime": archive,
712
+ )
713
+ monkeypatch.setattr(ci, "_verify_local_graph_archive", lambda *_a, **_k: None)
714
+ monkeypatch.setattr(ci, "_install_graph_entity_overlay", lambda *_a, **_k: None)
715
+
716
+ assert ci.build_graph(claude, force=True, install_mode="runtime") == 0
717
+
718
+ assert local_skill.is_file()
719
+ assert local_agent.is_file()
720
+ assert local_mcp.is_file()
721
+ assert not local_harness.exists()
722
+
723
+
724
  def test_graph_install_rejects_incomplete_archive(
725
  tmp_path: Path,
726
  monkeypatch,
src/tests/test_ctx_monitor.py CHANGED
@@ -29,6 +29,13 @@ def fake_claude(tmp_path: Path, monkeypatch) -> Path:
29
  (claude / "skill-quality").mkdir(parents=True)
30
  monkeypatch.setattr(cm, "_claude_dir", lambda: claude)
31
  monkeypatch.setattr(cm, "_dashboard_graph_index_archives", lambda: [])
 
 
 
 
 
 
 
32
  return claude
33
 
34
 
@@ -127,6 +134,25 @@ def _get_json(port: int, path: str) -> tuple[int, dict]:
127
  return exc.code, json.loads(exc.read().decode("utf-8"))
128
 
129
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  def _post_raw(
131
  port: int,
132
  path: str,
@@ -136,7 +162,9 @@ def _post_raw(
136
  ) -> tuple[int, dict]:
137
  conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
138
  try:
139
- conn.putrequest("POST", path)
 
 
140
  for key, value in headers.items():
141
  conn.putheader(key, value)
142
  conn.endheaders()
@@ -279,7 +307,8 @@ def test_render_skills_includes_harness_filter_and_typed_links(fake_claude: Path
279
 
280
  html = cm._render_skills()
281
 
282
- assert "class='type-filter' value='harness'" in html
 
283
  assert "/skill/langgraph?type=harness" in html
284
  assert "/wiki/langgraph?type=harness" in html
285
  assert "/graph?slug=langgraph&amp;type=harness" in html
@@ -780,6 +809,59 @@ def test_monitor_post_rejects_cross_origin_with_valid_token(
780
  thread.join(timeout=2)
781
 
782
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
783
  @pytest.mark.parametrize(
784
  ("length", "status", "detail"),
785
  [
@@ -869,9 +951,11 @@ def test_monitor_non_loopback_bind_is_read_only(
869
  ) as response:
870
  loaded_html = response.read().decode("utf-8")
871
  csp = response.headers.get("Content-Security-Policy", "")
 
872
  assert "browser-token" not in loaded_html
873
  assert "Read-only mode" in loaded_html
874
  assert "script-src 'self' 'unsafe-inline'" in csp
 
875
 
876
  with pytest.raises(urllib.error.HTTPError) as excinfo:
877
  urllib.request.urlopen(
@@ -882,6 +966,17 @@ def test_monitor_non_loopback_bind_is_read_only(
882
  body = json.loads(excinfo.value.read().decode("utf-8"))
883
  assert "read token required" in body["detail"]
884
 
 
 
 
 
 
 
 
 
 
 
 
885
  status, body = _post_json(
886
  port,
887
  "/api/load",
@@ -897,6 +992,34 @@ def test_monitor_non_loopback_bind_is_read_only(
897
  thread.join(timeout=2)
898
 
899
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
900
  def test_host_allows_mutations_only_for_loopback() -> None:
901
  assert cm._host_allows_mutations("127.0.0.1")
902
  assert cm._host_allows_mutations("::1")
@@ -1076,6 +1199,7 @@ def test_render_wiki_entity_renders_markdown_and_wikilinks(fake_claude: Path) ->
1076
  "Use `pytest` with [[entities/skills/find-skills]].\n\n"
1077
  "Source: [Homepage](https://example.com/docs).\n\n"
1078
  "Unsafe: [bad](javascript:alert(1)).\n\n"
 
1079
  "- first item\n"
1080
  "- [[entities/agents/reviewer|reviewer agent]]\n",
1081
  encoding="utf-8",
@@ -1089,6 +1213,7 @@ def test_render_wiki_entity_renders_markdown_and_wikilinks(fake_claude: Path) ->
1089
  assert "href='/wiki/reviewer?type=agent'" in html_out
1090
  assert "<a href='https://example.com/docs'>Homepage</a>" in html_out
1091
  assert "href='javascript:alert(1)'" not in html_out
 
1092
  assert "<li>first item</li>" in html_out
1093
  assert "<pre style=" not in html_out
1094
 
@@ -1275,6 +1400,7 @@ def test_render_wiki_entity_falls_back_to_runtime_graph_metadata(
1275
  assert "data-testid='runtime-entity-load'" in html_out
1276
  assert "/api/load" in html_out
1277
  assert "X-CTX-Monitor-Token" in html_out
 
1278
 
1279
 
1280
  def test_render_runtime_harness_entity_shows_install_commands(
@@ -1949,6 +2075,7 @@ def test_graph_neighborhood_extracts_missing_dashboard_index_from_archive(
1949
  tar.add(seed, arcname="./graphify-out/dashboard-neighborhoods.sqlite3")
1950
 
1951
  monkeypatch.setattr(cm, "_dashboard_graph_index_archives", lambda: [archive])
 
1952
  monkeypatch.setattr(
1953
  cm,
1954
  "_load_dashboard_graph",
@@ -1985,6 +2112,7 @@ def test_dashboard_index_extraction_skips_archive_export_mismatch(
1985
  tar.add(seed, arcname="./graphify-out/dashboard-neighborhoods.sqlite3")
1986
 
1987
  monkeypatch.setattr(cm, "_dashboard_graph_index_archives", lambda: [archive])
 
1988
  monkeypatch.setattr(
1989
  cm,
1990
  "_dashboard_index_matches_manifest",
@@ -1997,20 +2125,17 @@ def test_dashboard_index_extraction_skips_archive_export_mismatch(
1997
  assert not (graph_dir / "dashboard-neighborhoods.sqlite3").exists()
1998
 
1999
 
2000
- def test_dashboard_index_extraction_skips_installed_graph_report(
2001
  fake_claude: Path,
2002
  monkeypatch: pytest.MonkeyPatch,
2003
  ) -> None:
2004
  graph_dir = fake_claude / "skill-wiki" / "graphify-out"
2005
  graph_dir.mkdir(parents=True)
2006
  (graph_dir / "graph-export-manifest.json").write_text(
2007
- json.dumps({"version": 1, "export_id": "local-export"}),
2008
- encoding="utf-8",
2009
- )
2010
- (graph_dir / "graph-report.md").write_text(
2011
- "> Nodes: 12 | Edges: 34 | Communities: 2\n",
2012
  encoding="utf-8",
2013
  )
 
2014
  monkeypatch.setattr(
2015
  cm,
2016
  "_dashboard_graph_index_archives",
@@ -2020,6 +2145,66 @@ def test_dashboard_index_extraction_skips_installed_graph_report(
2020
  assert cm._ensure_dashboard_graph_index() is None
2021
 
2022
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2023
  def test_graph_neighborhood_bypasses_archive_index_when_runtime_overlays_exist(
2024
  fake_claude: Path,
2025
  monkeypatch: pytest.MonkeyPatch,
@@ -2075,6 +2260,7 @@ def test_graph_neighborhood_rejects_stale_dashboard_index(
2075
 
2076
  G = nx.Graph()
2077
  G.add_node("skill:fallback", label="fallback", type="skill", tags=[])
 
2078
  monkeypatch.setattr(cm, "_load_dashboard_graph", lambda: G)
2079
 
2080
  result = cm._graph_neighborhood("fallback", entity_type="skill")
@@ -2227,7 +2413,7 @@ def test_render_skills_emits_sidebar_filters(fake_claude: Path) -> None:
2227
  "subject_type": "agent",
2228
  "hard_floor": "intake_fail"})
2229
  html_out = cm._render_skills()
2230
- # Sidebar must expose a text search + grade checkboxes + type checkboxes.
2231
  assert "id='skill-search'" in html_out
2232
  assert "class='grade-filter'" in html_out
2233
  assert "class='type-filter'" in html_out
@@ -2239,6 +2425,113 @@ def test_render_skills_emits_sidebar_filters(fake_claude: Path) -> None:
2239
  assert ">graph</a>" in html_out
2240
 
2241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2242
  def test_render_wiki_index_lists_entities(fake_claude: Path) -> None:
2243
  skills_dir = fake_claude / "skill-wiki" / "entities" / "skills"
2244
  agents_dir = fake_claude / "skill-wiki" / "entities" / "agents"
@@ -2535,6 +2828,67 @@ def test_entity_delete_api_removes_wiki_page_and_queues_graph_refresh(
2535
  server.server_close()
2536
 
2537
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2538
  def test_sidecar_cache_invalidates_on_file_rewrite(fake_claude: Path) -> None:
2539
  cm._SIDECAR_INDEX_CACHE_KEY = None
2540
  cm._SIDECAR_INDEX_CACHE_VALUE = None
@@ -2618,6 +2972,33 @@ def test_api_kpi_summary_shape(fake_claude: Path) -> None:
2618
  assert d["grade_counts"].get("A", 0) == 1
2619
 
2620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2621
  def test_layout_nav_includes_wiki_and_kpi() -> None:
2622
  """Every rendered page must include the new Wiki + KPI tabs in the
2623
  top nav — the user explicitly asked for them to be accessible."""
@@ -2750,6 +3131,31 @@ def test_render_docs_lists_repo_docs(
2750
  assert "doc-card" not in html_out
2751
 
2752
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2753
  def test_render_docs_falls_back_to_public_docs(
2754
  monkeypatch: pytest.MonkeyPatch,
2755
  ) -> None:
@@ -2964,6 +3370,7 @@ def test_render_graph_landing_does_not_cold_load_graph_for_seed_chips(
2964
  "available": True,
2965
  })
2966
  monkeypatch.setattr(cm, "_load_dashboard_graph", fake_load_graph)
 
2967
  monkeypatch.setattr(cm, "_GRAPH_CACHE_VALUE", None)
2968
 
2969
  html_out = cm._render_graph(None)
@@ -2986,6 +3393,7 @@ def test_render_graph_landing_hides_seeds_when_graph_absent(monkeypatch) -> None
2986
  # braces in case a downstream path still routes through it.
2987
  monkeypatch.setitem(sys.modules, "ctx.core.graph.resolve_graph", fake)
2988
  monkeypatch.setitem(sys.modules, "resolve_graph", fake)
 
2989
  monkeypatch.setattr(cm, "_GRAPH_CACHE_VALUE", None)
2990
  monkeypatch.setattr(cm, "_GRAPH_CACHE_KEY", None)
2991
  html_out = cm._render_graph(None)
 
29
  (claude / "skill-quality").mkdir(parents=True)
30
  monkeypatch.setattr(cm, "_claude_dir", lambda: claude)
31
  monkeypatch.setattr(cm, "_dashboard_graph_index_archives", lambda: [])
32
+ monkeypatch.setattr(cm, "_SIDECAR_INDEX_CACHE_KEY", None)
33
+ monkeypatch.setattr(cm, "_SIDECAR_INDEX_CACHE_VALUE", None)
34
+ monkeypatch.setattr(cm, "_SIDECAR_FILTER_CACHE_SIGNATURE", None)
35
+ monkeypatch.setattr(cm, "_SIDECAR_FILTER_CACHE_VALUE", {})
36
+ monkeypatch.setattr(cm, "_KPI_SUMMARY_CACHE_KEY", None)
37
+ monkeypatch.setattr(cm, "_KPI_SUMMARY_CACHE_VALUE", None)
38
+ monkeypatch.setattr(cm, "_KPI_SUMMARY_CACHE_AT", 0.0)
39
  return claude
40
 
41
 
 
134
  return exc.code, json.loads(exc.read().decode("utf-8"))
135
 
136
 
137
+ def _get_raw(
138
+ port: int,
139
+ path: str,
140
+ *,
141
+ headers: dict[str, str],
142
+ ) -> tuple[int, dict]:
143
+ conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
144
+ try:
145
+ conn.putrequest("GET", path, skip_host=True)
146
+ for key, value in headers.items():
147
+ conn.putheader(key, value)
148
+ conn.endheaders()
149
+ response = conn.getresponse()
150
+ payload = json.loads(response.read().decode("utf-8"))
151
+ return response.status, payload
152
+ finally:
153
+ conn.close()
154
+
155
+
156
  def _post_raw(
157
  port: int,
158
  path: str,
 
162
  ) -> tuple[int, dict]:
163
  conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
164
  try:
165
+ conn.putrequest("POST", path, skip_host=True)
166
+ if "Host" not in headers:
167
+ conn.putheader("Host", f"127.0.0.1:{port}")
168
  for key, value in headers.items():
169
  conn.putheader(key, value)
170
  conn.endheaders()
 
307
 
308
  html = cm._render_skills()
309
 
310
+ assert "class='type-filter'" in html
311
+ assert "value='harness'" in html
312
  assert "/skill/langgraph?type=harness" in html
313
  assert "/wiki/langgraph?type=harness" in html
314
  assert "/graph?slug=langgraph&amp;type=harness" in html
 
809
  thread.join(timeout=2)
810
 
811
 
812
+ def test_monitor_post_rejects_rebound_host_with_valid_token(
813
+ fake_claude: Path, monkeypatch: pytest.MonkeyPatch,
814
+ ) -> None:
815
+ calls: list[str] = []
816
+
817
+ def fake_load(slug: str, entity_type: str = "skill") -> tuple[bool, str]:
818
+ calls.append(slug)
819
+ return True, f"loaded {entity_type}"
820
+
821
+ monkeypatch.setattr(cm, "_perform_load", fake_load)
822
+ server, thread, port = _serve_monitor(monkeypatch)
823
+ body = json.dumps({"slug": "python-patterns"}).encode("utf-8")
824
+ try:
825
+ status, payload = _post_raw(
826
+ port,
827
+ "/api/load",
828
+ headers={
829
+ "Host": "evil.example",
830
+ "Content-Type": "application/json",
831
+ "Content-Length": str(len(body)),
832
+ "X-CTX-Monitor-Token": "test-token",
833
+ "Origin": "http://evil.example",
834
+ },
835
+ body=body,
836
+ )
837
+ assert status == 403
838
+ assert "cross-origin" in payload["detail"]
839
+ assert calls == []
840
+ finally:
841
+ server.shutdown()
842
+ server.server_close()
843
+ thread.join(timeout=2)
844
+
845
+
846
+ def test_monitor_get_rejects_rebound_host_in_loopback_mode(
847
+ fake_claude: Path,
848
+ monkeypatch: pytest.MonkeyPatch,
849
+ ) -> None:
850
+ server, thread, port = _serve_monitor(monkeypatch)
851
+ try:
852
+ status, payload = _get_raw(
853
+ port,
854
+ "/api/status.json",
855
+ headers={"Host": "evil.example"},
856
+ )
857
+ assert status == 403
858
+ assert "monitor read" in payload["detail"]
859
+ finally:
860
+ server.shutdown()
861
+ server.server_close()
862
+ thread.join(timeout=2)
863
+
864
+
865
  @pytest.mark.parametrize(
866
  ("length", "status", "detail"),
867
  [
 
951
  ) as response:
952
  loaded_html = response.read().decode("utf-8")
953
  csp = response.headers.get("Content-Security-Policy", "")
954
+ cookie = response.headers.get("Set-Cookie", "")
955
  assert "browser-token" not in loaded_html
956
  assert "Read-only mode" in loaded_html
957
  assert "script-src 'self' 'unsafe-inline'" in csp
958
+ assert "ctx_monitor_read_token=browser-token" in cookie
959
 
960
  with pytest.raises(urllib.error.HTTPError) as excinfo:
961
  urllib.request.urlopen(
 
966
  body = json.loads(excinfo.value.read().decode("utf-8"))
967
  assert "read token required" in body["detail"]
968
 
969
+ status, body = _get_raw(
970
+ port,
971
+ "/api/manifest.json",
972
+ headers={
973
+ "Host": f"127.0.0.1:{port}",
974
+ "Cookie": "ctx_monitor_read_token=browser-token",
975
+ },
976
+ )
977
+ assert status == 200
978
+ assert body["load"] == []
979
+
980
  status, body = _post_json(
981
  port,
982
  "/api/load",
 
992
  thread.join(timeout=2)
993
 
994
 
995
+ def test_serve_generates_read_token_for_non_loopback(
996
+ monkeypatch: pytest.MonkeyPatch,
997
+ capsys: pytest.CaptureFixture[str],
998
+ ) -> None:
999
+ class FakeServer:
1000
+ _ctx_mutations_enabled = False
1001
+
1002
+ def serve_forever(self) -> None:
1003
+ raise KeyboardInterrupt
1004
+
1005
+ def server_close(self) -> None:
1006
+ return None
1007
+
1008
+ monkeypatch.setattr(cm, "_MONITOR_TOKEN", "")
1009
+ monkeypatch.setattr(cm, "_make_monitor_server", lambda _host, _port: FakeServer())
1010
+ monkeypatch.setattr(cm.secrets, "token_urlsafe", lambda _size: "lan-token")
1011
+ monkeypatch.setattr(cm.socket, "gethostname", lambda: "devbox")
1012
+ monkeypatch.setattr(cm.socket, "gethostbyname", lambda _name: "192.168.1.50")
1013
+
1014
+ cm.serve(host="0.0.0.0", port=8765)
1015
+
1016
+ assert cm._MONITOR_TOKEN == "lan-token"
1017
+ out = capsys.readouterr().out
1018
+ assert "http://192.168.1.50:8765/?token=lan-token" in out
1019
+ assert "http://0.0.0.0:8765" not in out
1020
+ assert "read token required" in out
1021
+
1022
+
1023
  def test_host_allows_mutations_only_for_loopback() -> None:
1024
  assert cm._host_allows_mutations("127.0.0.1")
1025
  assert cm._host_allows_mutations("::1")
 
1199
  "Use `pytest` with [[entities/skills/find-skills]].\n\n"
1200
  "Source: [Homepage](https://example.com/docs).\n\n"
1201
  "Unsafe: [bad](javascript:alert(1)).\n\n"
1202
+ "Protocol relative: [offsite](//evil.example/x).\n\n"
1203
  "- first item\n"
1204
  "- [[entities/agents/reviewer|reviewer agent]]\n",
1205
  encoding="utf-8",
 
1213
  assert "href='/wiki/reviewer?type=agent'" in html_out
1214
  assert "<a href='https://example.com/docs'>Homepage</a>" in html_out
1215
  assert "href='javascript:alert(1)'" not in html_out
1216
+ assert "href='//evil.example/x'" not in html_out
1217
  assert "<li>first item</li>" in html_out
1218
  assert "<pre style=" not in html_out
1219
 
 
1400
  assert "data-testid='runtime-entity-load'" in html_out
1401
  assert "/api/load" in html_out
1402
  assert "X-CTX-Monitor-Token" in html_out
1403
+ assert "payload.detail || payload.msg || response.status" in html_out
1404
 
1405
 
1406
  def test_render_runtime_harness_entity_shows_install_commands(
 
2075
  tar.add(seed, arcname="./graphify-out/dashboard-neighborhoods.sqlite3")
2076
 
2077
  monkeypatch.setattr(cm, "_dashboard_graph_index_archives", lambda: [archive])
2078
+ monkeypatch.setattr(cm, "_packaged_graph_export_id", lambda: "archive-export")
2079
  monkeypatch.setattr(
2080
  cm,
2081
  "_load_dashboard_graph",
 
2112
  tar.add(seed, arcname="./graphify-out/dashboard-neighborhoods.sqlite3")
2113
 
2114
  monkeypatch.setattr(cm, "_dashboard_graph_index_archives", lambda: [archive])
2115
+ monkeypatch.setattr(cm, "_packaged_graph_export_id", lambda: None)
2116
  monkeypatch.setattr(
2117
  cm,
2118
  "_dashboard_index_matches_manifest",
 
2125
  assert not (graph_dir / "dashboard-neighborhoods.sqlite3").exists()
2126
 
2127
 
2128
+ def test_dashboard_index_extraction_skips_packaged_export_mismatch(
2129
  fake_claude: Path,
2130
  monkeypatch: pytest.MonkeyPatch,
2131
  ) -> None:
2132
  graph_dir = fake_claude / "skill-wiki" / "graphify-out"
2133
  graph_dir.mkdir(parents=True)
2134
  (graph_dir / "graph-export-manifest.json").write_text(
2135
+ json.dumps({"version": 1, "export_id": "old-local-export"}),
 
 
 
 
2136
  encoding="utf-8",
2137
  )
2138
+ monkeypatch.setattr(cm, "_packaged_graph_export_id", lambda: "new-packaged-export")
2139
  monkeypatch.setattr(
2140
  cm,
2141
  "_dashboard_graph_index_archives",
 
2145
  assert cm._ensure_dashboard_graph_index() is None
2146
 
2147
 
2148
+ def test_graph_neighborhood_uses_local_graph_on_packaged_export_mismatch(
2149
+ fake_claude: Path,
2150
+ monkeypatch: pytest.MonkeyPatch,
2151
+ ) -> None:
2152
+ import networkx as nx
2153
+
2154
+ graph_dir = fake_claude / "skill-wiki" / "graphify-out"
2155
+ graph_dir.mkdir(parents=True)
2156
+ (graph_dir / "graph-export-manifest.json").write_text(
2157
+ json.dumps({"version": 1, "export_id": "old-local-export"}),
2158
+ encoding="utf-8",
2159
+ )
2160
+ monkeypatch.setattr(cm, "_packaged_graph_export_id", lambda: "new-packaged-export")
2161
+ G = nx.Graph()
2162
+ G.add_node("mcp-server:github", label="GitHub", type="mcp-server", tags=["git"])
2163
+ monkeypatch.setattr(cm, "_load_dashboard_graph", lambda: G)
2164
+
2165
+ result = cm._graph_neighborhood("github", entity_type="mcp-server")
2166
+ assert result["center"] == "mcp-server:github"
2167
+ assert result["nodes"][0]["data"]["type"] == "mcp-server"
2168
+
2169
+
2170
+ def test_dashboard_index_extraction_works_with_installed_graph_report(
2171
+ fake_claude: Path,
2172
+ tmp_path: Path,
2173
+ monkeypatch: pytest.MonkeyPatch,
2174
+ ) -> None:
2175
+ graph_dir = fake_claude / "skill-wiki" / "graphify-out"
2176
+ graph_dir.mkdir(parents=True)
2177
+ (graph_dir / "graph-export-manifest.json").write_text(
2178
+ json.dumps({"version": 1, "export_id": "local-export"}),
2179
+ encoding="utf-8",
2180
+ )
2181
+ (graph_dir / "graph-report.md").write_text(
2182
+ "> Nodes: 12 | Edges: 34 | Communities: 2\n",
2183
+ encoding="utf-8",
2184
+ )
2185
+ seed = tmp_path / "dashboard-neighborhoods.sqlite3"
2186
+ conn = sqlite3.connect(seed)
2187
+ try:
2188
+ conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
2189
+ conn.execute("INSERT INTO meta VALUES(?,?)", ("export_id", json.dumps("local-export")))
2190
+ conn.commit()
2191
+ finally:
2192
+ conn.close()
2193
+ archive_manifest = tmp_path / "graph-export-manifest.json"
2194
+ archive_manifest.write_text(
2195
+ json.dumps({"version": 1, "export_id": "local-export"}),
2196
+ encoding="utf-8",
2197
+ )
2198
+ archive = tmp_path / "wiki-graph-runtime.tar.gz"
2199
+ with tarfile.open(archive, "w:gz") as tar:
2200
+ tar.add(archive_manifest, arcname="./graphify-out/graph-export-manifest.json")
2201
+ tar.add(seed, arcname="./graphify-out/dashboard-neighborhoods.sqlite3")
2202
+ monkeypatch.setattr(cm, "_dashboard_graph_index_archives", lambda: [archive])
2203
+ monkeypatch.setattr(cm, "_packaged_graph_export_id", lambda: "local-export")
2204
+
2205
+ assert cm._ensure_dashboard_graph_index() == graph_dir / "dashboard-neighborhoods.sqlite3"
2206
+
2207
+
2208
  def test_graph_neighborhood_bypasses_archive_index_when_runtime_overlays_exist(
2209
  fake_claude: Path,
2210
  monkeypatch: pytest.MonkeyPatch,
 
2260
 
2261
  G = nx.Graph()
2262
  G.add_node("skill:fallback", label="fallback", type="skill", tags=[])
2263
+ monkeypatch.setattr(cm, "_packaged_graph_export_id", lambda: None)
2264
  monkeypatch.setattr(cm, "_load_dashboard_graph", lambda: G)
2265
 
2266
  result = cm._graph_neighborhood("fallback", entity_type="skill")
 
2413
  "subject_type": "agent",
2414
  "hard_floor": "intake_fail"})
2415
  html_out = cm._render_skills()
2416
+ # Sidebar must expose text search plus grade/type filters.
2417
  assert "id='skill-search'" in html_out
2418
  assert "class='grade-filter'" in html_out
2419
  assert "class='type-filter'" in html_out
 
2425
  assert ">graph</a>" in html_out
2426
 
2427
 
2428
+ def test_render_skills_paginates_sidecar_page(fake_claude: Path) -> None:
2429
+ for slug in ("a", "b", "c"):
2430
+ _write_sidecar(fake_claude, slug, {
2431
+ "slug": slug,
2432
+ "grade": "A",
2433
+ "raw_score": 0.9,
2434
+ "subject_type": "skill",
2435
+ })
2436
+
2437
+ html_out = cm._render_skills({"limit": "2"})
2438
+
2439
+ assert "Showing 1-2 of 3 sidecars" in html_out
2440
+ assert "next</a>" in html_out
2441
+ assert "a</code>" in html_out
2442
+ assert "b</code>" in html_out
2443
+ assert "c</code>" not in html_out
2444
+
2445
+
2446
+ def test_sidecar_page_payload_searches_full_catalog(fake_claude: Path) -> None:
2447
+ for slug in ("alpha-review", "beta-build", "gamma-review"):
2448
+ _write_sidecar(fake_claude, slug, {
2449
+ "slug": slug,
2450
+ "grade": "A",
2451
+ "raw_score": 0.9,
2452
+ "subject_type": "skill",
2453
+ })
2454
+
2455
+ payload = cm._sidecar_page_payload({"q": "review", "limit": "1"})
2456
+
2457
+ assert payload["total"] == 2
2458
+ assert payload["pages"] == 2
2459
+ assert [item["slug"] for item in payload["items"]] == ["alpha-review"]
2460
+
2461
+
2462
+ def test_sidecar_page_payload_filters_type_grade_and_floor(fake_claude: Path) -> None:
2463
+ _write_sidecar(fake_claude, "agent-a", {
2464
+ "slug": "agent-a",
2465
+ "grade": "A",
2466
+ "raw_score": 0.9,
2467
+ "subject_type": "agent",
2468
+ })
2469
+ _write_sidecar(fake_claude, "skill-a", {
2470
+ "slug": "skill-a",
2471
+ "grade": "A",
2472
+ "raw_score": 0.9,
2473
+ "subject_type": "skill",
2474
+ })
2475
+ _write_sidecar(fake_claude, "agent-floored", {
2476
+ "slug": "agent-floored",
2477
+ "grade": "A",
2478
+ "raw_score": 0.9,
2479
+ "subject_type": "agent",
2480
+ "hard_floor": "intake_fail",
2481
+ })
2482
+
2483
+ payload = cm._sidecar_page_payload({
2484
+ "type": "agent",
2485
+ "grade": "A",
2486
+ "hide_floor": "1",
2487
+ })
2488
+
2489
+ assert payload["total"] == 1
2490
+ assert payload["items"][0]["slug"] == "agent-a"
2491
+
2492
+
2493
+ def test_sidecar_page_payload_reuses_cached_search_records(
2494
+ fake_claude: Path,
2495
+ monkeypatch: pytest.MonkeyPatch,
2496
+ ) -> None:
2497
+ for slug in ("alpha-review", "beta-review"):
2498
+ _write_sidecar(fake_claude, slug, {
2499
+ "slug": slug,
2500
+ "grade": "A",
2501
+ "raw_score": 0.9,
2502
+ "subject_type": "skill",
2503
+ })
2504
+ original_read = cm._read_sidecar_file
2505
+ reads = 0
2506
+
2507
+ def counting_read(path: Path) -> dict | None:
2508
+ nonlocal reads
2509
+ reads += 1
2510
+ return original_read(path)
2511
+
2512
+ monkeypatch.setattr(cm, "_read_sidecar_file", counting_read)
2513
+
2514
+ first = cm._sidecar_page_payload({"q": "review"})
2515
+ reads_after_first_search = reads
2516
+ second = cm._sidecar_page_payload({"q": "review"})
2517
+
2518
+ assert [item["slug"] for item in first["items"]] == ["alpha-review", "beta-review"]
2519
+ assert [item["slug"] for item in second["items"]] == ["alpha-review", "beta-review"]
2520
+ assert reads_after_first_search == 2
2521
+ assert reads == reads_after_first_search
2522
+
2523
+ _write_sidecar(fake_claude, "delta-review", {
2524
+ "slug": "delta-review",
2525
+ "grade": "A",
2526
+ "raw_score": 0.8,
2527
+ "subject_type": "skill",
2528
+ })
2529
+ refreshed = cm._sidecar_page_payload({"q": "delta"})
2530
+
2531
+ assert [item["slug"] for item in refreshed["items"]] == ["delta-review"]
2532
+ assert reads > reads_after_first_search
2533
+
2534
+
2535
  def test_render_wiki_index_lists_entities(fake_claude: Path) -> None:
2536
  skills_dir = fake_claude / "skill-wiki" / "entities" / "skills"
2537
  agents_dir = fake_claude / "skill-wiki" / "entities" / "agents"
 
2828
  server.server_close()
2829
 
2830
 
2831
+ def test_entity_delete_unloads_live_entity_before_removing_page(
2832
+ fake_claude: Path,
2833
+ monkeypatch: pytest.MonkeyPatch,
2834
+ ) -> None:
2835
+ skill_dir = fake_claude / "skill-wiki" / "entities" / "skills"
2836
+ skill_dir.mkdir(parents=True)
2837
+ entity_path = skill_dir / "python-patterns.md"
2838
+ entity_path.write_text(
2839
+ "---\ntitle: Python Patterns\ntype: skill\n---\n# Python Patterns\n",
2840
+ encoding="utf-8",
2841
+ )
2842
+ calls: list[tuple[str, str]] = []
2843
+ monkeypatch.setattr(
2844
+ cm,
2845
+ "_read_manifest",
2846
+ lambda: {"load": [{"skill": "python-patterns", "entity_type": "skill"}]},
2847
+ )
2848
+
2849
+ def fake_unload(slug: str, entity_type: str = "skill") -> tuple[bool, str]:
2850
+ calls.append((slug, entity_type))
2851
+ return True, "unloaded"
2852
+
2853
+ monkeypatch.setattr(cm, "_perform_unload", fake_unload)
2854
+
2855
+ ok, detail = cm._delete_wiki_entity("python-patterns", "skill")
2856
+
2857
+ assert ok is True
2858
+ assert "deleted skill:python-patterns" in detail
2859
+ assert calls == [("python-patterns", "skill")]
2860
+ assert not entity_path.exists()
2861
+
2862
+
2863
+ def test_entity_delete_keeps_page_when_live_unload_fails(
2864
+ fake_claude: Path,
2865
+ monkeypatch: pytest.MonkeyPatch,
2866
+ ) -> None:
2867
+ harness_dir = fake_claude / "skill-wiki" / "entities" / "harnesses"
2868
+ harness_dir.mkdir(parents=True)
2869
+ entity_path = harness_dir / "local-harness.md"
2870
+ entity_path.write_text(
2871
+ "---\ntitle: Local Harness\ntype: harness\n---\n# Local Harness\n",
2872
+ encoding="utf-8",
2873
+ )
2874
+ monkeypatch.setattr(
2875
+ cm,
2876
+ "_read_manifest",
2877
+ lambda: {"load": [{"skill": "local-harness", "entity_type": "harness"}]},
2878
+ )
2879
+ monkeypatch.setattr(
2880
+ cm,
2881
+ "_perform_unload",
2882
+ lambda slug, entity_type="skill": (False, "use ctx-harness-install"),
2883
+ )
2884
+
2885
+ ok, detail = cm._delete_wiki_entity("local-harness", "harness")
2886
+
2887
+ assert ok is False
2888
+ assert "is loaded" in detail
2889
+ assert entity_path.exists()
2890
+
2891
+
2892
  def test_sidecar_cache_invalidates_on_file_rewrite(fake_claude: Path) -> None:
2893
  cm._SIDECAR_INDEX_CACHE_KEY = None
2894
  cm._SIDECAR_INDEX_CACHE_VALUE = None
 
2972
  assert d["grade_counts"].get("A", 0) == 1
2973
 
2974
 
2975
+ def test_kpi_summary_cache_reuses_recent_summary(
2976
+ fake_claude: Path, monkeypatch: pytest.MonkeyPatch,
2977
+ ) -> None:
2978
+ import kpi_dashboard as kd
2979
+
2980
+ _write_sidecar(fake_claude, "alpha", {
2981
+ "slug": "alpha", "subject_type": "skill",
2982
+ "grade": "A", "raw_score": 0.9, "score": 0.9,
2983
+ "hard_floor": None, "computed_at": "2026-04-19T10:00:00+00:00",
2984
+ })
2985
+ monkeypatch.setattr(cm, "_KPI_SUMMARY_CACHE_KEY", None)
2986
+ monkeypatch.setattr(cm, "_KPI_SUMMARY_CACHE_VALUE", None)
2987
+ real_generate = kd.generate
2988
+ calls = 0
2989
+
2990
+ def wrapped_generate(*, sources, top_n=10, now=None):
2991
+ nonlocal calls
2992
+ calls += 1
2993
+ return real_generate(sources=sources, top_n=top_n, now=now)
2994
+
2995
+ monkeypatch.setattr(kd, "generate", wrapped_generate)
2996
+
2997
+ assert cm._kpi_summary() is not None
2998
+ assert cm._kpi_summary() is not None
2999
+ assert calls == 1
3000
+
3001
+
3002
  def test_layout_nav_includes_wiki_and_kpi() -> None:
3003
  """Every rendered page must include the new Wiki + KPI tabs in the
3004
  top nav — the user explicitly asked for them to be accessible."""
 
3131
  assert "doc-card" not in html_out
3132
 
3133
 
3134
+ def test_render_docs_sanitizes_active_html(
3135
+ tmp_path: Path,
3136
+ monkeypatch: pytest.MonkeyPatch,
3137
+ ) -> None:
3138
+ (tmp_path / "docs").mkdir()
3139
+ (tmp_path / "mkdocs.yml").write_text(
3140
+ "site_name: ctx\nnav:\n - Home: index.md\n",
3141
+ encoding="utf-8",
3142
+ )
3143
+ (tmp_path / "docs" / "index.md").write_text(
3144
+ "# Home\n\n"
3145
+ "<script>alert('x')</script>\n\n"
3146
+ "<a href=\"javascript:alert('x')\" onclick=\"alert('x')\">bad</a>\n",
3147
+ encoding="utf-8",
3148
+ )
3149
+ monkeypatch.setattr(cm, "_docs_roots", lambda: [tmp_path])
3150
+
3151
+ html_out = cm._render_docs()
3152
+
3153
+ assert "<script>alert('x')</script>" not in html_out
3154
+ assert "&lt;script" in html_out
3155
+ assert "onclick=" not in html_out
3156
+ assert "href=\"javascript:" not in html_out
3157
+
3158
+
3159
  def test_render_docs_falls_back_to_public_docs(
3160
  monkeypatch: pytest.MonkeyPatch,
3161
  ) -> None:
 
3370
  "available": True,
3371
  })
3372
  monkeypatch.setattr(cm, "_load_dashboard_graph", fake_load_graph)
3373
+ monkeypatch.setattr(cm, "_top_degree_seeds_from_index", lambda _limit=18: [])
3374
  monkeypatch.setattr(cm, "_GRAPH_CACHE_VALUE", None)
3375
 
3376
  html_out = cm._render_graph(None)
 
3393
  # braces in case a downstream path still routes through it.
3394
  monkeypatch.setitem(sys.modules, "ctx.core.graph.resolve_graph", fake)
3395
  monkeypatch.setitem(sys.modules, "resolve_graph", fake)
3396
+ monkeypatch.setattr(cm, "_graph_stats", lambda: {"available": False})
3397
  monkeypatch.setattr(cm, "_GRAPH_CACHE_VALUE", None)
3398
  monkeypatch.setattr(cm, "_GRAPH_CACHE_KEY", None)
3399
  html_out = cm._render_graph(None)
src/tests/test_graph_artifact_guard.py CHANGED
@@ -40,17 +40,23 @@ def test_graph_artifact_guard_parks_and_unparks_tracked_artifacts(
40
  _git(repo, "config", "user.name", "ctx test")
41
 
42
  artifact = graph / "wiki-graph.tar.gz"
 
43
  artifact.write_bytes(b"fake graph artifact")
44
- _git(repo, "add", "graph/wiki-graph.tar.gz")
 
45
  _git(repo, "commit", "-m", "track graph artifact")
46
 
47
  assert guard.main(["--repo", str(repo), "park"]) == 0
48
  assert _git(repo, "ls-files", "-v", "graph/wiki-graph.tar.gz").startswith("S ")
 
49
 
50
  assert guard.main(["--repo", str(repo), "unpark"]) == 0
51
  assert not _git(repo, "ls-files", "-v", "graph/wiki-graph.tar.gz").startswith(
52
  "S "
53
  )
 
 
 
54
 
55
 
56
  def test_graph_artifact_guard_removes_only_stale_graph_files(
@@ -79,3 +85,55 @@ def test_graph_artifact_guard_removes_only_stale_graph_files(
79
  assert not staged.exists()
80
  assert not partial.exists()
81
  assert outside.exists()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  _git(repo, "config", "user.name", "ctx test")
41
 
42
  artifact = graph / "wiki-graph.tar.gz"
43
+ overlay = graph / "entity-overlays.jsonl"
44
  artifact.write_bytes(b"fake graph artifact")
45
+ overlay.write_text('{"nodes":[],"edges":[]}\n', encoding="utf-8")
46
+ _git(repo, "add", "graph/wiki-graph.tar.gz", "graph/entity-overlays.jsonl")
47
  _git(repo, "commit", "-m", "track graph artifact")
48
 
49
  assert guard.main(["--repo", str(repo), "park"]) == 0
50
  assert _git(repo, "ls-files", "-v", "graph/wiki-graph.tar.gz").startswith("S ")
51
+ assert _git(repo, "ls-files", "-v", "graph/entity-overlays.jsonl").startswith("S ")
52
 
53
  assert guard.main(["--repo", str(repo), "unpark"]) == 0
54
  assert not _git(repo, "ls-files", "-v", "graph/wiki-graph.tar.gz").startswith(
55
  "S "
56
  )
57
+ assert not _git(repo, "ls-files", "-v", "graph/entity-overlays.jsonl").startswith(
58
+ "S "
59
+ )
60
 
61
 
62
  def test_graph_artifact_guard_removes_only_stale_graph_files(
 
85
  assert not staged.exists()
86
  assert not partial.exists()
87
  assert outside.exists()
88
+
89
+
90
+ def test_graph_artifact_guard_prune_is_lfs_only_by_default(
91
+ tmp_path: Path,
92
+ monkeypatch,
93
+ ) -> None:
94
+ repo_root = Path(__file__).resolve().parents[2]
95
+ guard = _load_guard(repo_root)
96
+ calls: list[tuple[str, ...]] = []
97
+
98
+ def fake_run_git(
99
+ _repo: Path,
100
+ args: list[str],
101
+ *,
102
+ check: bool = True,
103
+ capture: bool = False,
104
+ ) -> subprocess.CompletedProcess[str]:
105
+ calls.append(tuple(args))
106
+ return subprocess.CompletedProcess(args, 0, stdout="", stderr="")
107
+
108
+ monkeypatch.setattr(guard, "_run_git", fake_run_git)
109
+
110
+ guard._prune(tmp_path, include_lfs=True, include_git_prune=False)
111
+
112
+ assert ("lfs", "prune", "--verbose") in calls
113
+ assert not any(call[:1] == ("prune",) for call in calls)
114
+
115
+
116
+ def test_graph_artifact_guard_prune_requires_explicit_git_prune(
117
+ tmp_path: Path,
118
+ monkeypatch,
119
+ ) -> None:
120
+ repo_root = Path(__file__).resolve().parents[2]
121
+ guard = _load_guard(repo_root)
122
+ calls: list[tuple[str, ...]] = []
123
+
124
+ def fake_run_git(
125
+ _repo: Path,
126
+ args: list[str],
127
+ *,
128
+ check: bool = True,
129
+ capture: bool = False,
130
+ ) -> subprocess.CompletedProcess[str]:
131
+ calls.append(tuple(args))
132
+ return subprocess.CompletedProcess(args, 0, stdout="", stderr="")
133
+
134
+ monkeypatch.setattr(guard, "_run_git", fake_run_git)
135
+
136
+ guard._prune(tmp_path, include_lfs=False, include_git_prune=True)
137
+
138
+ assert ("prune", "--expire=now", "--verbose") in calls
139
+ assert not any(call[:2] == ("lfs", "prune") for call in calls)
src/tests/test_harness_install.py CHANGED
@@ -258,6 +258,33 @@ def test_remote_install_requires_pinned_commit_by_default(tmp_path: Path) -> Non
258
  assert not (tmp_path / "installs" / "text-to-cad").exists()
259
 
260
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
261
  def test_remote_install_fetches_pinned_commit_and_records_manifest(
262
  tmp_path: Path,
263
  monkeypatch: Any,
@@ -288,6 +315,7 @@ def test_remote_install_fetches_pinned_commit_and_records_manifest(
288
 
289
  assert result.status == "installed"
290
  assert git_calls[0][:2] == ["clone", "--no-checkout"]
 
291
  assert any(
292
  call[0] == "-C"
293
  and call[2:6] == ["fetch", "--depth", "1", "origin"]
 
258
  assert not (tmp_path / "installs" / "text-to-cad").exists()
259
 
260
 
261
+ @pytest.mark.parametrize(
262
+ "repo_url",
263
+ [
264
+ "ssh://github.com/earthtojake/text-to-cad",
265
+ "https://token@example.test/private/repo",
266
+ "-c.helper=!calc",
267
+ ],
268
+ )
269
+ def test_remote_install_rejects_unsafe_repo_urls(
270
+ tmp_path: Path,
271
+ repo_url: str,
272
+ ) -> None:
273
+ wiki = tmp_path / "wiki"
274
+ _write_harness_page(wiki, repo_url=repo_url, commit_sha="a" * 40)
275
+
276
+ result = harness_install.install_harness(
277
+ "text-to-cad",
278
+ wiki_path=wiki,
279
+ installs_root=tmp_path / "installs",
280
+ manifest_dir=tmp_path / "manifests",
281
+ )
282
+
283
+ assert result.status == "install-failed"
284
+ assert "repo_url" in result.message
285
+ assert not (tmp_path / "installs" / "text-to-cad").exists()
286
+
287
+
288
  def test_remote_install_fetches_pinned_commit_and_records_manifest(
289
  tmp_path: Path,
290
  monkeypatch: Any,
 
315
 
316
  assert result.status == "installed"
317
  assert git_calls[0][:2] == ["clone", "--no-checkout"]
318
+ assert git_calls[0][2] == "--"
319
  assert any(
320
  call[0] == "-C"
321
  and call[2:6] == ["fetch", "--depth", "1", "origin"]
src/tests/test_harness_recommendations.py CHANGED
@@ -258,6 +258,7 @@ def test_ctx_init_keeps_domain_goal_strong_with_install_requirements(
258
  }
259
  assert "windows" not in results[0]["missing_signals"]
260
  assert "mcp" not in results[0]["missing_signals"]
 
261
  assert "gpt-5" not in results[0]["fit_signals"]
262
 
263
 
 
258
  }
259
  assert "windows" not in results[0]["missing_signals"]
260
  assert "mcp" not in results[0]["missing_signals"]
261
+ assert "gpt" not in results[0]["missing_signals"]
262
  assert "gpt-5" not in results[0]["fit_signals"]
263
 
264
 
src/tests/test_import_skills_sh_catalog.py CHANGED
@@ -1160,8 +1160,12 @@ def test_hydration_falls_back_to_github_raw_skill_md(monkeypatch) -> None:
1160
  ),
1161
  )
1162
  fetched_urls: list[str] = []
 
1163
 
1164
  class FakeResponse:
 
 
 
1165
  def __enter__(self) -> "FakeResponse":
1166
  return self
1167
 
@@ -1169,14 +1173,17 @@ def test_hydration_falls_back_to_github_raw_skill_md(monkeypatch) -> None:
1169
  return None
1170
 
1171
  def read(self, size: int = -1) -> bytes:
1172
- return b"# Brand Identity\n\nUse this skill for brand strategy.\n"
1173
 
1174
  def fake_urlopen(req: object, timeout: int) -> FakeResponse:
1175
  url = req.full_url # type: ignore[attr-defined]
1176
  fetched_urls.append(url)
 
 
1177
  if "/skills/brand-identity/" not in url:
1178
  raise OSError("not found")
1179
- return FakeResponse()
 
1180
 
1181
  monkeypatch.setattr(importer.urllib.request, "urlopen", fake_urlopen)
1182
  catalog: dict[str, Any] = {
@@ -1199,11 +1206,33 @@ def test_hydration_falls_back_to_github_raw_skill_md(monkeypatch) -> None:
1199
  assert skill["skill_body"].startswith("# Brand Identity")
1200
  assert skill["body_source_url"] == (
1201
  "https://raw.githubusercontent.com/travisjneuman/.claude/"
1202
- "main/skills/brand-identity/SKILL.md"
1203
  )
1204
  assert fetched_urls[-1] == skill["body_source_url"]
1205
 
1206
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1207
  def test_hydration_rejects_non_skills_sh_detail_urls(monkeypatch) -> None:
1208
  def fail_fetch(url: str, timeout: int = 30) -> tuple[str | None, str | None]:
1209
  raise AssertionError(f"unexpected fetch for {url}")
 
1160
  ),
1161
  )
1162
  fetched_urls: list[str] = []
1163
+ branch_sha = "0123456789abcdef0123456789abcdef01234567"
1164
 
1165
  class FakeResponse:
1166
+ def __init__(self, payload: bytes) -> None:
1167
+ self._payload = payload
1168
+
1169
  def __enter__(self) -> "FakeResponse":
1170
  return self
1171
 
 
1173
  return None
1174
 
1175
  def read(self, size: int = -1) -> bytes:
1176
+ return self._payload
1177
 
1178
  def fake_urlopen(req: object, timeout: int) -> FakeResponse:
1179
  url = req.full_url # type: ignore[attr-defined]
1180
  fetched_urls.append(url)
1181
+ if url.endswith("/repos/travisjneuman/.claude/branches/main"):
1182
+ return FakeResponse(json.dumps({"commit": {"sha": branch_sha}}).encode())
1183
  if "/skills/brand-identity/" not in url:
1184
  raise OSError("not found")
1185
+ assert f"/{branch_sha}/" in url
1186
+ return FakeResponse(b"# Brand Identity\n\nUse this skill for brand strategy.\n")
1187
 
1188
  monkeypatch.setattr(importer.urllib.request, "urlopen", fake_urlopen)
1189
  catalog: dict[str, Any] = {
 
1206
  assert skill["skill_body"].startswith("# Brand Identity")
1207
  assert skill["body_source_url"] == (
1208
  "https://raw.githubusercontent.com/travisjneuman/.claude/"
1209
+ f"{branch_sha}/skills/brand-identity/SKILL.md"
1210
  )
1211
  assert fetched_urls[-1] == skill["body_source_url"]
1212
 
1213
 
1214
+ def test_github_raw_fallback_requires_pinned_branch_sha(monkeypatch) -> None:
1215
+ fetched_urls: list[str] = []
1216
+
1217
+ def fake_urlopen(req: object, timeout: int) -> object:
1218
+ fetched_urls.append(req.full_url) # type: ignore[attr-defined]
1219
+ raise OSError("branch lookup failed")
1220
+
1221
+ monkeypatch.setattr(importer.urllib.request, "urlopen", fake_urlopen)
1222
+
1223
+ body, url, error = importer._fetch_github_raw_skill_body(
1224
+ {
1225
+ "source": "owner/repo",
1226
+ "skill_id": "danger",
1227
+ },
1228
+ )
1229
+
1230
+ assert body is None
1231
+ assert url is None
1232
+ assert "found no pinned SKILL.md candidates" in str(error)
1233
+ assert all("raw.githubusercontent.com" not in candidate for candidate in fetched_urls)
1234
+
1235
+
1236
  def test_hydration_rejects_non_skills_sh_detail_urls(monkeypatch) -> None:
1237
  def fail_fetch(url: str, timeout: int = 30) -> tuple[str | None, str | None]:
1238
  raise AssertionError(f"unexpected fetch for {url}")
src/tests/test_incremental_attach_calibration.py CHANGED
@@ -1,5 +1,7 @@
1
  from __future__ import annotations
2
 
 
 
3
  import networkx as nx
4
  import numpy as np
5
  import pytest
@@ -47,7 +49,7 @@ def test_calibrate_attach_defaults_ignores_missing_semantic_scores() -> None:
47
 
48
  assert summary.semantic_score_percentiles == {}
49
  assert summary.final_weight_percentiles[50] == pytest.approx(0.4)
50
- assert summary.recommended_min_semantic_score == pytest.approx(0.75)
51
  assert summary.recommended_max_edges_per_node == 1
52
 
53
 
@@ -172,7 +174,14 @@ def test_main_attach_writes_idempotent_overlay_used_by_resolver(tmp_path) -> Non
172
 
173
  assert overlay.read_text(encoding="utf-8").count("\n") == 1
174
  assert loaded.has_edge("skill:new-python", "skill:python-testing")
175
- assert loaded.edges["skill:new-python", "skill:python-testing"]["semantic_sim"] == pytest.approx(1.0)
 
 
 
 
 
 
 
176
 
177
  changed_args = [
178
  "attach",
@@ -194,3 +203,32 @@ def test_main_attach_writes_idempotent_overlay_used_by_resolver(tmp_path) -> Non
194
  assert overlay.read_text(encoding="utf-8").count("\n") == 2
195
  assert loaded_after_change.has_edge("skill:new-python", "skill:ruby-testing")
196
  assert not loaded_after_change.has_edge("skill:new-python", "skill:python-testing")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from __future__ import annotations
2
 
3
+ import json
4
+
5
  import networkx as nx
6
  import numpy as np
7
  import pytest
 
49
 
50
  assert summary.semantic_score_percentiles == {}
51
  assert summary.final_weight_percentiles[50] == pytest.approx(0.4)
52
+ assert summary.recommended_min_semantic_score == pytest.approx(0.80)
53
  assert summary.recommended_max_edges_per_node == 1
54
 
55
 
 
174
 
175
  assert overlay.read_text(encoding="utf-8").count("\n") == 1
176
  assert loaded.has_edge("skill:new-python", "skill:python-testing")
177
+ edge = loaded.edges["skill:new-python", "skill:python-testing"]
178
+ assert edge["semantic_sim"] == pytest.approx(1.0)
179
+ assert edge["type_affinity"] == pytest.approx(0.35)
180
+ assert edge["score_components"] == {
181
+ "semantic": pytest.approx(0.7),
182
+ "type_affinity": pytest.approx(0.0105),
183
+ }
184
+ assert edge["final_weight"] == pytest.approx(0.7105)
185
 
186
  changed_args = [
187
  "attach",
 
203
  assert overlay.read_text(encoding="utf-8").count("\n") == 2
204
  assert loaded_after_change.has_edge("skill:new-python", "skill:ruby-testing")
205
  assert not loaded_after_change.has_edge("skill:new-python", "skill:python-testing")
206
+
207
+
208
+ def test_main_attach_default_min_score_matches_build_floor(tmp_path) -> None:
209
+ index_dir = tmp_path / "vector-index"
210
+ build_vector_index(
211
+ kind="numpy-flat",
212
+ model_id="model-a",
213
+ node_ids=["skill:almost-python"],
214
+ content_hashes=["ha"],
215
+ vectors=np.asarray([[0.76, 0.65]], dtype="float32"),
216
+ ).save(index_dir)
217
+ overlay = tmp_path / "entity-overlays.jsonl"
218
+
219
+ assert main([
220
+ "attach",
221
+ "--index-dir", str(index_dir),
222
+ "--overlay", str(overlay),
223
+ "--node-id", "skill:new-python",
224
+ "--label", "new-python",
225
+ "--type", "skill",
226
+ "--text", "new python testing helper",
227
+ "--model-id", "model-a",
228
+ "--vector-json", "[1.0, 0.0]",
229
+ "--top-k", "1",
230
+ ]) == 0
231
+
232
+ payload = json.loads(overlay.read_text(encoding="utf-8"))
233
+ assert payload["edges"][0]["target"] == "skill:almost-python"
234
+ assert payload["edges"][0]["semantic_sim"] == pytest.approx(0.76, abs=0.001)
src/tests/test_inject_hooks_security.py CHANGED
@@ -21,8 +21,8 @@ _SRC = Path(__file__).resolve().parent.parent
21
  if str(_SRC) not in sys.path:
22
  sys.path.insert(0, str(_SRC))
23
 
24
- from ctx.adapters.claude_code import inject_hooks # noqa: E402
25
- from ctx.adapters.claude_code.inject_hooks import make_hooks, merge_hooks, write_settings_atomic # noqa: E402
26
 
27
 
28
  # ---------------------------------------------------------------------------
@@ -128,6 +128,29 @@ class TestNoShellInjectionVars:
128
  f"{cmds_with_stdin}"
129
  )
130
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
  # ---------------------------------------------------------------------------
133
  # Fix 2 — Stop array contains both usage_tracker and quality_on_session_end
@@ -199,7 +222,7 @@ class TestStopHooks:
199
  # ---------------------------------------------------------------------------
200
 
201
 
202
- class TestCtxDirQuoting:
203
  def test_path_with_spaces_is_quoted(self, tmp_path: Path) -> None:
204
  ctx_dir = str(tmp_path / "my ctx dir")
205
  hooks = make_hooks(ctx_dir)
@@ -213,35 +236,35 @@ class TestCtxDirQuoting:
213
  f"Path with space is not quoted in: {cmd!r}"
214
  )
215
 
216
- def test_path_with_dollar_is_safe(self, tmp_path: Path) -> None:
217
- """A ctx_dir with a literal $ must be quoted so the shell doesn't expand it."""
218
- import shlex as _shlex
219
- ctx_dir = "/home/user/$HOME/ctx"
220
  hooks = make_hooks(ctx_dir)
221
  cmds = _all_commands(hooks)
222
  quoted = _shlex.quote(ctx_dir)
223
  for cmd in cmds:
224
  if ctx_dir in cmd or quoted in cmd:
225
  # The raw unquoted path must not appear unless it's the quoted form
226
- assert f" {ctx_dir}/" not in cmd, (
227
- f"Unquoted $ path found in: {cmd!r}"
228
- )
229
-
230
- def test_windows_python_path_with_spaces_uses_windows_quoting(
231
- self,
232
- monkeypatch: pytest.MonkeyPatch,
233
- ) -> None:
234
- monkeypatch.setattr(
235
- inject_hooks.sys,
236
- "executable",
237
- r"C:\Program Files\Python311\python.exe",
238
- )
239
- monkeypatch.setattr(inject_hooks.os, "name", "nt")
240
-
241
- cmd = inject_hooks._module_cmd("usage_tracker", "--sync")
242
-
243
- assert cmd == r'"C:\Program Files\Python311\python.exe" -m usage_tracker --sync'
244
- assert "'" not in cmd
245
 
246
 
247
  class TestPackagedHookCommands:
 
21
  if str(_SRC) not in sys.path:
22
  sys.path.insert(0, str(_SRC))
23
 
24
+ from ctx.adapters.claude_code import inject_hooks # noqa: E402
25
+ from ctx.adapters.claude_code.inject_hooks import make_hooks, merge_hooks, write_settings_atomic # noqa: E402
26
 
27
 
28
  # ---------------------------------------------------------------------------
 
128
  f"{cmds_with_stdin}"
129
  )
130
 
131
+ def test_merge_hooks_repairs_partial_posttooluse_matcher(
132
+ self,
133
+ tmp_path: Path,
134
+ ) -> None:
135
+ new_hooks = make_hooks(str(tmp_path / "ctx"))
136
+ existing = {
137
+ "hooks": {
138
+ "PostToolUse": [
139
+ {
140
+ "matcher": ".*",
141
+ "hooks": [new_hooks["PostToolUse"][0]["hooks"][0]],
142
+ },
143
+ ],
144
+ },
145
+ }
146
+
147
+ merged = merge_hooks(existing, new_hooks)
148
+
149
+ commands = _all_commands({"PostToolUse": merged["hooks"]["PostToolUse"]})
150
+ assert any("context_monitor" in command for command in commands)
151
+ assert any("skill_add_detector" in command for command in commands)
152
+ assert any("bundle_orchestrator" in command for command in commands)
153
+
154
 
155
  # ---------------------------------------------------------------------------
156
  # Fix 2 — Stop array contains both usage_tracker and quality_on_session_end
 
222
  # ---------------------------------------------------------------------------
223
 
224
 
225
+ class TestCtxDirQuoting:
226
  def test_path_with_spaces_is_quoted(self, tmp_path: Path) -> None:
227
  ctx_dir = str(tmp_path / "my ctx dir")
228
  hooks = make_hooks(ctx_dir)
 
236
  f"Path with space is not quoted in: {cmd!r}"
237
  )
238
 
239
+ def test_path_with_dollar_is_safe(self, tmp_path: Path) -> None:
240
+ """A ctx_dir with a literal $ must be quoted so the shell doesn't expand it."""
241
+ import shlex as _shlex
242
+ ctx_dir = "/home/user/$HOME/ctx"
243
  hooks = make_hooks(ctx_dir)
244
  cmds = _all_commands(hooks)
245
  quoted = _shlex.quote(ctx_dir)
246
  for cmd in cmds:
247
  if ctx_dir in cmd or quoted in cmd:
248
  # The raw unquoted path must not appear unless it's the quoted form
249
+ assert f" {ctx_dir}/" not in cmd, (
250
+ f"Unquoted $ path found in: {cmd!r}"
251
+ )
252
+
253
+ def test_windows_python_path_with_spaces_uses_windows_quoting(
254
+ self,
255
+ monkeypatch: pytest.MonkeyPatch,
256
+ ) -> None:
257
+ monkeypatch.setattr(
258
+ inject_hooks.sys,
259
+ "executable",
260
+ r"C:\Program Files\Python311\python.exe",
261
+ )
262
+ monkeypatch.setattr(inject_hooks.os, "name", "nt")
263
+
264
+ cmd = inject_hooks._module_cmd("usage_tracker", "--sync")
265
+
266
+ assert cmd == r'"C:\Program Files\Python311\python.exe" -m usage_tracker --sync'
267
+ assert "'" not in cmd
268
 
269
 
270
  class TestPackagedHookCommands:
src/tests/test_kpi_dashboard.py CHANGED
@@ -193,6 +193,66 @@ class TestCollectRows:
193
  ("filesystem", "mcp-server")
194
  ]
195
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  def test_duplicate_skill_and_mcp_slugs_are_distinct_rows(
197
  self, sources: cl.LifecycleSources,
198
  ) -> None:
 
193
  ("filesystem", "mcp-server")
194
  ]
195
 
196
+ def test_mcp_rows_do_not_probe_skill_or_agent_sources(
197
+ self, sources: cl.LifecycleSources, monkeypatch: pytest.MonkeyPatch,
198
+ ) -> None:
199
+ _write_quality(
200
+ sources.sidecar_dir / "mcp",
201
+ "filesystem",
202
+ subject_type="mcp-server",
203
+ grade="A",
204
+ score=0.88,
205
+ )
206
+
207
+ def fail_source_probe(*args: object, **kwargs: object) -> Path | None:
208
+ raise AssertionError("MCP rows should not stat skill/agent source paths")
209
+
210
+ monkeypatch.setattr(kd, "_skill_source_path", fail_source_probe)
211
+
212
+ rows = kd.collect_rows(sources=sources)
213
+
214
+ assert rows[0].category == "uncategorized"
215
+
216
+ def test_lifecycle_only_mcp_keeps_subject_type(
217
+ self, sources: cl.LifecycleSources,
218
+ ) -> None:
219
+ _write_lifecycle(
220
+ sources.sidecar_dir,
221
+ "filesystem",
222
+ subject_type="mcp-server",
223
+ state=cl.STATE_ARCHIVE,
224
+ )
225
+
226
+ rows = kd.collect_rows(sources=sources)
227
+
228
+ assert [(r.slug, r.subject_type, r.lifecycle_state) for r in rows] == [
229
+ ("filesystem", "mcp-server", cl.STATE_ARCHIVE)
230
+ ]
231
+
232
+ def test_lifecycle_only_mcp_is_not_dropped_by_same_slug_skill_quality(
233
+ self, sources: cl.LifecycleSources,
234
+ ) -> None:
235
+ _write_quality(
236
+ sources.sidecar_dir,
237
+ "langgraph",
238
+ subject_type="skill",
239
+ grade="B",
240
+ score=0.65,
241
+ )
242
+ _write_lifecycle(
243
+ sources.sidecar_dir,
244
+ "langgraph",
245
+ subject_type="mcp-server",
246
+ state=cl.STATE_ARCHIVE,
247
+ )
248
+
249
+ rows = kd.collect_rows(sources=sources)
250
+
251
+ assert sorted((r.slug, r.subject_type, r.grade, r.lifecycle_state) for r in rows) == [
252
+ ("langgraph", "mcp-server", "", cl.STATE_ARCHIVE),
253
+ ("langgraph", "skill", "B", cl.STATE_ACTIVE),
254
+ ]
255
+
256
  def test_duplicate_skill_and_mcp_slugs_are_distinct_rows(
257
  self, sources: cl.LifecycleSources,
258
  ) -> None:
src/tests/test_mcp_add.py CHANGED
@@ -272,6 +272,8 @@ class TestAddMcpExistingReview:
272
  assert result["merged_sources"] == ["awesome-mcp", "pulsemcp"]
273
  assert fm["sources"] == ["awesome-mcp", "pulsemcp"]
274
  assert fm["description"] == record_b.description
 
 
275
 
276
 
277
  # ---------------------------------------------------------------------------
 
272
  assert result["merged_sources"] == ["awesome-mcp", "pulsemcp"]
273
  assert fm["sources"] == ["awesome-mcp", "pulsemcp"]
274
  assert fm["description"] == record_b.description
275
+ assert record_b.description in text
276
+ assert "- pulsemcp" in text
277
 
278
 
279
  # ---------------------------------------------------------------------------
src/tests/test_mcp_install.py CHANGED
@@ -274,6 +274,28 @@ class TestInstallMcp:
274
  )
275
  assert r.status == "skipped-existing"
276
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
  def test_force_overrides_skip(
278
  self,
279
  wiki_dir: Path,
@@ -287,6 +309,41 @@ class TestInstallMcp:
287
  )
288
  assert r.status == "installed"
289
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290
  def test_no_command_no_json(self, wiki_dir: Path) -> None:
291
  _write_entity(wiki_dir, "gh", {"status": "cataloged"})
292
  r = mcp_install.install_mcp("gh", wiki_dir=wiki_dir, auto=True)
@@ -395,6 +452,38 @@ class TestInstallMcp:
395
  "two words",
396
  ]
397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
398
  # Strix vuln-0002 regression: even when the first token is allowlisted,
399
  # code-execution argument forms must be rejected. A tampered frontmatter
400
  # install_cmd could otherwise invoke arbitrary interpreter-controlled
@@ -451,6 +540,47 @@ class TestInstallMcp:
451
  f"legitimate launcher {cmd!r} falsely rejected (msg={r.message})"
452
  )
453
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
454
  def test_empty_command_tokens_rejected(
455
  self, wiki_dir: Path, fake_claude: dict[str, Any], isolated_manifest: Path
456
  ) -> None:
@@ -620,13 +750,47 @@ class TestUninstallMcp:
620
  assert r.status == "not-installed"
621
 
622
  def test_not_installed_short_circuits(
623
- self, wiki_dir: Path, fake_claude: dict[str, Any]
 
 
 
624
  ) -> None:
625
  _write_entity(wiki_dir, "gh", {"status": "cataloged"})
626
  r = mcp_install.uninstall_mcp("gh", wiki_dir=wiki_dir)
627
  assert r.status == "not-installed"
628
  assert fake_claude["calls"] == []
629
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
630
  def test_dry_run(
631
  self, wiki_dir: Path, fake_claude: dict[str, Any]
632
  ) -> None:
@@ -847,6 +1011,7 @@ class TestInstallMain:
847
  self,
848
  wiki_dir: Path,
849
  fake_claude: dict[str, Any],
 
850
  monkeypatch: pytest.MonkeyPatch,
851
  ) -> None:
852
  _write_entity(wiki_dir, "gh", {"status": "cataloged"})
 
274
  )
275
  assert r.status == "skipped-existing"
276
 
277
+ def test_already_installed_reconciles_missing_manifest(
278
+ self,
279
+ wiki_dir: Path,
280
+ isolated_manifest: Path,
281
+ ) -> None:
282
+ _write_entity(
283
+ wiki_dir,
284
+ "gh",
285
+ {"status": "installed", "install_cmd": "npx -y old-pkg"},
286
+ )
287
+
288
+ r = mcp_install.install_mcp("gh", wiki_dir=wiki_dir, auto=True)
289
+
290
+ assert r.status == "skipped-existing"
291
+ manifest = install_utils.load_manifest()
292
+ assert manifest["load"] == [{
293
+ "skill": "gh",
294
+ "entity_type": "mcp-server",
295
+ "source": "ctx-mcp-install",
296
+ "command": "npx -y old-pkg",
297
+ }]
298
+
299
  def test_force_overrides_skip(
300
  self,
301
  wiki_dir: Path,
 
309
  )
310
  assert r.status == "installed"
311
 
312
+ def test_force_reinstall_updates_existing_manifest_command(
313
+ self,
314
+ wiki_dir: Path,
315
+ fake_claude: dict[str, Any],
316
+ isolated_manifest: Path,
317
+ ) -> None:
318
+ _write_entity(
319
+ wiki_dir,
320
+ "gh",
321
+ {"status": "installed", "install_cmd": "npx -y old-pkg"},
322
+ )
323
+ install_utils.record_install(
324
+ "gh",
325
+ entity_type="mcp-server",
326
+ source="ctx-mcp-install",
327
+ extra={"command": "npx -y old-pkg"},
328
+ )
329
+
330
+ r = mcp_install.install_mcp(
331
+ "gh",
332
+ wiki_dir=wiki_dir,
333
+ command="npx -y new-pkg",
334
+ auto=True,
335
+ force=True,
336
+ )
337
+
338
+ assert r.status == "installed"
339
+ manifest = install_utils.load_manifest()
340
+ assert manifest["load"] == [{
341
+ "skill": "gh",
342
+ "entity_type": "mcp-server",
343
+ "source": "ctx-mcp-install",
344
+ "command": "npx -y new-pkg",
345
+ }]
346
+
347
  def test_no_command_no_json(self, wiki_dir: Path) -> None:
348
  _write_entity(wiki_dir, "gh", {"status": "cataloged"})
349
  r = mcp_install.install_mcp("gh", wiki_dir=wiki_dir, auto=True)
 
452
  "two words",
453
  ]
454
 
455
+ @pytest.mark.parametrize("cmd", ["npx.cmd -y pkg", "python.exe server.py"])
456
+ def test_windows_wrapper_executables_are_allowlisted(
457
+ self,
458
+ wiki_dir: Path,
459
+ fake_claude: dict[str, Any],
460
+ isolated_manifest: Path,
461
+ cmd: str,
462
+ ) -> None:
463
+ _write_entity(wiki_dir, "srv", {"status": "cataloged"})
464
+
465
+ r = mcp_install.install_mcp("srv", wiki_dir=wiki_dir, command=cmd, auto=True)
466
+
467
+ assert r.status == "installed"
468
+
469
+ def test_windows_wrapper_still_rejects_code_execution_args(
470
+ self,
471
+ wiki_dir: Path,
472
+ fake_claude: dict[str, Any],
473
+ isolated_manifest: Path,
474
+ ) -> None:
475
+ _write_entity(wiki_dir, "srv", {"status": "cataloged"})
476
+
477
+ r = mcp_install.install_mcp(
478
+ "srv",
479
+ wiki_dir=wiki_dir,
480
+ command='python.exe -c "print(1)"',
481
+ auto=True,
482
+ )
483
+
484
+ assert r.status == "invalid-cmd"
485
+ assert fake_claude["calls"] == []
486
+
487
  # Strix vuln-0002 regression: even when the first token is allowlisted,
488
  # code-execution argument forms must be rejected. A tampered frontmatter
489
  # install_cmd could otherwise invoke arbitrary interpreter-controlled
 
540
  f"legitimate launcher {cmd!r} falsely rejected (msg={r.message})"
541
  )
542
 
543
+ @pytest.mark.parametrize(
544
+ "cmd",
545
+ [
546
+ "npx -y pkg GITHUB_TOKEN=ghp_supersecret123456789012345",
547
+ "npx -y pkg --api-key sk-supersecret123456789012345",
548
+ "npx -y pkg --client-secret=plain-secret-value",
549
+ ],
550
+ )
551
+ def test_install_cmd_rejects_inline_secret_arguments(
552
+ self,
553
+ wiki_dir: Path,
554
+ fake_claude: dict[str, Any],
555
+ isolated_manifest: Path,
556
+ cmd: str,
557
+ ) -> None:
558
+ _write_entity(wiki_dir, "srv", {"status": "cataloged"})
559
+
560
+ r = mcp_install.install_mcp("srv", wiki_dir=wiki_dir, command=cmd, auto=True)
561
+
562
+ assert r.status == "invalid-cmd"
563
+ assert "inline secret" in r.message
564
+ assert fake_claude["calls"] == []
565
+
566
+ def test_install_cmd_allows_secret_env_reference(
567
+ self,
568
+ wiki_dir: Path,
569
+ fake_claude: dict[str, Any],
570
+ isolated_manifest: Path,
571
+ ) -> None:
572
+ _write_entity(wiki_dir, "srv", {"status": "cataloged"})
573
+
574
+ r = mcp_install.install_mcp(
575
+ "srv",
576
+ wiki_dir=wiki_dir,
577
+ command="npx -y pkg --api-key $API_KEY",
578
+ auto=True,
579
+ )
580
+
581
+ assert r.status == "installed"
582
+ assert fake_claude["calls"]
583
+
584
  def test_empty_command_tokens_rejected(
585
  self, wiki_dir: Path, fake_claude: dict[str, Any], isolated_manifest: Path
586
  ) -> None:
 
750
  assert r.status == "not-installed"
751
 
752
  def test_not_installed_short_circuits(
753
+ self,
754
+ wiki_dir: Path,
755
+ fake_claude: dict[str, Any],
756
+ isolated_manifest: Path,
757
  ) -> None:
758
  _write_entity(wiki_dir, "gh", {"status": "cataloged"})
759
  r = mcp_install.uninstall_mcp("gh", wiki_dir=wiki_dir)
760
  assert r.status == "not-installed"
761
  assert fake_claude["calls"] == []
762
 
763
+ def test_manifest_loaded_cataloged_entity_can_uninstall(
764
+ self,
765
+ wiki_dir: Path,
766
+ fake_claude: dict[str, Any],
767
+ isolated_manifest: Path,
768
+ ) -> None:
769
+ entity = _write_entity(
770
+ wiki_dir,
771
+ "gh",
772
+ {"status": "cataloged", "install_cmd": "npx -y pkg"},
773
+ )
774
+ install_utils.record_install(
775
+ "gh",
776
+ entity_type="mcp-server",
777
+ source="ctx-mcp-install",
778
+ extra={"command": "npx -y pkg"},
779
+ )
780
+
781
+ result = mcp_install.uninstall_mcp("gh", wiki_dir=wiki_dir)
782
+
783
+ assert result.status == "uninstalled"
784
+ assert "status: cataloged" in entity.read_text(encoding="utf-8")
785
+ manifest = install_utils.load_manifest()
786
+ assert manifest["load"] == []
787
+ assert manifest["unload"] == [{
788
+ "skill": "gh",
789
+ "entity_type": "mcp-server",
790
+ "source": "ctx-mcp-uninstall",
791
+ "command": "npx -y pkg",
792
+ }]
793
+
794
  def test_dry_run(
795
  self, wiki_dir: Path, fake_claude: dict[str, Any]
796
  ) -> None:
 
1011
  self,
1012
  wiki_dir: Path,
1013
  fake_claude: dict[str, Any],
1014
+ isolated_manifest: Path,
1015
  monkeypatch: pytest.MonkeyPatch,
1016
  ) -> None:
1017
  _write_entity(wiki_dir, "gh", {"status": "cataloged"})
src/tests/test_overlay_wiki_entities.py CHANGED
@@ -1,119 +1,172 @@
1
- from __future__ import annotations
2
-
3
- import json
4
- import sqlite3
5
- import tarfile
6
- from datetime import datetime, timezone
7
- from pathlib import Path
8
-
9
- from scripts.overlay_wiki_entities import overlay_entities
10
-
11
-
12
- def _add_text(tf: tarfile.TarFile, name: str, text: str) -> None:
13
- data = text.encode("utf-8")
14
- info = tarfile.TarInfo(name)
15
- info.size = len(data)
16
- info.mtime = 0
17
- tf.addfile(info, __import__("io").BytesIO(data))
18
-
19
-
20
- def _read_json(tf: tarfile.TarFile, name: str) -> dict:
21
- member = tf.getmember(name)
22
- f = tf.extractfile(member)
23
- assert f is not None
24
- return json.loads(f.read().decode("utf-8"))
25
-
26
-
27
- def test_overlay_entities_preserves_existing_graph_and_adds_selected_pages(tmp_path: Path) -> None:
28
- source_wiki = tmp_path / "wiki"
29
- (source_wiki / "graphify-out").mkdir(parents=True)
30
- (source_wiki / "entities" / "skills").mkdir(parents=True)
31
- (source_wiki / "entities" / "harnesses").mkdir(parents=True)
32
- skills_root = tmp_path / "skills"
33
- (skills_root / "new-skill" / "references").mkdir(parents=True)
34
- (source_wiki / "entities" / "skills" / "new-skill.md").write_text("# New skill\n")
35
- (source_wiki / "entities" / "harnesses" / "new-harness.md").write_text("# Harness\n")
36
- body = skills_root / "new-skill" / "SKILL.md"
37
- body.write_text("# body\n", encoding="utf-8")
38
- (skills_root / "new-skill" / "references" / "guide.md").write_text("# guide\n", encoding="utf-8")
39
- source_graph = {
40
- "graph": {"export_id": "source"},
41
- "nodes": [
42
- {"id": "skill:old", "label": "old", "type": "skill"},
43
- {"id": "skill:new-skill", "label": "new", "type": "skill"},
44
- {"id": "harness:new-harness", "label": "harness", "type": "harness"},
45
- ],
46
- "edges": [
47
- {"source": "skill:old", "target": "skill:new-skill", "weight": 0.5},
48
- {"source": "skill:old", "target": "harness:new-harness", "weight": 0.7},
49
- ],
50
- }
51
- (source_wiki / "graphify-out" / "graph.json").write_text(json.dumps(source_graph))
52
-
53
- tarball = tmp_path / "wiki-graph.tar.gz"
54
- graph = {
55
- "graph": {"export_id": "old"},
56
- "nodes": [{"id": "skill:old", "label": "old", "type": "skill"}],
57
- "edges": [{"source": "skill:old", "target": "skill:other", "weight": 0.1}],
58
- }
59
- communities = {
60
- "export_id": "old",
61
- "communities": {"0": {"label": "Core", "members": ["skill:old"]}},
62
- "total_communities": 1,
63
- "generated": "old",
64
- }
65
- manifest = {
66
- "version": 1,
67
- "export_id": "old",
68
- "artifacts": {
69
- "graph": "graph.json",
70
- "delta": "graph-delta.json",
71
- "communities": "communities.json",
72
- "report": "graph-report.md",
73
- },
74
- "counts": {"nodes": 1, "edges": 1, "communities": 1},
75
- }
76
- with tarfile.open(tarball, "w:gz") as tf:
77
- _add_text(tf, "./graphify-out/graph.json", json.dumps(graph))
78
- _add_text(tf, "./graphify-out/communities.json", json.dumps(communities))
79
- _add_text(tf, "./graphify-out/graph-delta.json", json.dumps({"version": 1, "export_id": "old"}))
80
- _add_text(tf, "./graphify-out/graph-report.md", "> Export ID: old\n")
81
- _add_text(tf, "./graphify-out/graph-export-manifest.json", json.dumps(manifest))
82
- _add_text(tf, "./keep.md", "keep")
83
-
84
- root_communities = tmp_path / "communities.json"
85
- stats = overlay_entities(
86
- source_wiki=source_wiki,
87
- tarball=tarball,
88
- entity_ids=["skill:new-skill", "harness:new-harness"],
89
- skills_root=skills_root,
90
- root_communities=root_communities,
91
- now=datetime(2026, 5, 13, tzinfo=timezone.utc),
92
- )
93
-
94
- assert stats.node_count == 3
95
- assert stats.edge_count == 3
96
- assert stats.added_nodes == 2
97
- assert stats.added_edges == 2
98
- with tarfile.open(tarball, "r:gz") as tf:
99
- graph_out = _read_json(tf, "./graphify-out/graph.json")
100
- manifest_out = _read_json(tf, "./graphify-out/graph-export-manifest.json")
101
- communities_out = _read_json(tf, "./graphify-out/communities.json")
102
- assert graph_out["graph"]["export_id"] == stats.export_id
103
- assert manifest_out["export_id"] == stats.export_id
104
- assert communities_out["export_id"] == stats.export_id
105
- assert tf.extractfile("./keep.md") is not None
106
- assert tf.extractfile("./entities/skills/new-skill.md") is not None
107
- assert tf.extractfile("./entities/harnesses/new-harness.md") is not None
108
- assert tf.extractfile("./converted/new-skill/SKILL.md") is not None
109
- assert tf.extractfile("./converted/new-skill/references/guide.md") is not None
110
- index_member = tf.extractfile("./graphify-out/dashboard-neighborhoods.sqlite3")
111
- assert index_member is not None
112
- index_path = tmp_path / "dashboard-neighborhoods.sqlite3"
113
- index_path.write_bytes(index_member.read())
114
- with sqlite3.connect(index_path) as conn:
115
- assert conn.execute(
116
- "SELECT node_id FROM slug_index WHERE slug = ?",
117
- ("new-skill",),
118
- ).fetchone() == ("skill:new-skill",)
119
- assert json.loads(root_communities.read_text())["export_id"] == stats.export_id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import sqlite3
5
+ import subprocess
6
+ import sys
7
+ import tarfile
8
+ from datetime import datetime, timezone
9
+ from pathlib import Path
10
+
11
+ import pytest
12
+
13
+ from scripts.overlay_wiki_entities import _entity_page, _skill_replacements, overlay_entities
14
+
15
+ ROOT = Path(__file__).resolve().parents[2]
16
+
17
+
18
+ def _add_text(tf: tarfile.TarFile, name: str, text: str) -> None:
19
+ data = text.encode("utf-8")
20
+ info = tarfile.TarInfo(name)
21
+ info.size = len(data)
22
+ info.mtime = 0
23
+ tf.addfile(info, __import__("io").BytesIO(data))
24
+
25
+
26
+ def _read_json(tf: tarfile.TarFile, name: str) -> dict:
27
+ member = tf.getmember(name)
28
+ f = tf.extractfile(member)
29
+ assert f is not None
30
+ return json.loads(f.read().decode("utf-8"))
31
+
32
+
33
+ def test_overlay_entities_preserves_existing_graph_and_adds_selected_pages(tmp_path: Path) -> None:
34
+ source_wiki = tmp_path / "wiki"
35
+ (source_wiki / "graphify-out").mkdir(parents=True)
36
+ (source_wiki / "entities" / "skills").mkdir(parents=True)
37
+ (source_wiki / "entities" / "harnesses").mkdir(parents=True)
38
+ skills_root = tmp_path / "skills"
39
+ (skills_root / "new-skill" / "references").mkdir(parents=True)
40
+ (source_wiki / "entities" / "skills" / "new-skill.md").write_text("# New skill\n")
41
+ (source_wiki / "entities" / "harnesses" / "new-harness.md").write_text("# Harness\n")
42
+ body = skills_root / "new-skill" / "SKILL.md"
43
+ body.write_text("# body\n", encoding="utf-8")
44
+ (skills_root / "new-skill" / "references" / "guide.md").write_text("# guide\n", encoding="utf-8")
45
+ source_graph = {
46
+ "graph": {"export_id": "source"},
47
+ "nodes": [
48
+ {"id": "skill:old", "label": "old", "type": "skill"},
49
+ {"id": "skill:new-skill", "label": "new", "type": "skill"},
50
+ {"id": "harness:new-harness", "label": "harness", "type": "harness"},
51
+ ],
52
+ "edges": [
53
+ {"source": "skill:old", "target": "skill:new-skill", "weight": 0.5},
54
+ {"source": "skill:old", "target": "harness:new-harness", "weight": 0.7},
55
+ ],
56
+ }
57
+ (source_wiki / "graphify-out" / "graph.json").write_text(json.dumps(source_graph))
58
+
59
+ tarball = tmp_path / "wiki-graph.tar.gz"
60
+ graph = {
61
+ "graph": {"export_id": "old"},
62
+ "nodes": [{"id": "skill:old", "label": "old", "type": "skill"}],
63
+ "edges": [{"source": "skill:old", "target": "skill:other", "weight": 0.1}],
64
+ }
65
+ communities = {
66
+ "export_id": "old",
67
+ "communities": {"0": {"label": "Core", "members": ["skill:old"]}},
68
+ "total_communities": 1,
69
+ "generated": "old",
70
+ }
71
+ manifest = {
72
+ "version": 1,
73
+ "export_id": "old",
74
+ "artifacts": {
75
+ "graph": "graph.json",
76
+ "delta": "graph-delta.json",
77
+ "communities": "communities.json",
78
+ "report": "graph-report.md",
79
+ },
80
+ "counts": {"nodes": 1, "edges": 1, "communities": 1},
81
+ }
82
+ with tarfile.open(tarball, "w:gz") as tf:
83
+ _add_text(tf, "./graphify-out/graph.json", json.dumps(graph))
84
+ _add_text(tf, "./graphify-out/communities.json", json.dumps(communities))
85
+ _add_text(tf, "./graphify-out/graph-delta.json", json.dumps({"version": 1, "export_id": "old"}))
86
+ _add_text(tf, "./graphify-out/graph-report.md", "> Export ID: old\n")
87
+ _add_text(tf, "./graphify-out/graph-export-manifest.json", json.dumps(manifest))
88
+ _add_text(tf, "./keep.md", "keep")
89
+
90
+ root_communities = tmp_path / "communities.json"
91
+ stats = overlay_entities(
92
+ source_wiki=source_wiki,
93
+ tarball=tarball,
94
+ entity_ids=["skill:new-skill", "harness:new-harness"],
95
+ skills_root=skills_root,
96
+ root_communities=root_communities,
97
+ now=datetime(2026, 5, 13, tzinfo=timezone.utc),
98
+ )
99
+
100
+ assert stats.node_count == 3
101
+ assert stats.edge_count == 3
102
+ assert stats.added_nodes == 2
103
+ assert stats.added_edges == 2
104
+ with tarfile.open(tarball, "r:gz") as tf:
105
+ graph_out = _read_json(tf, "./graphify-out/graph.json")
106
+ manifest_out = _read_json(tf, "./graphify-out/graph-export-manifest.json")
107
+ communities_out = _read_json(tf, "./graphify-out/communities.json")
108
+ assert graph_out["graph"]["export_id"] == stats.export_id
109
+ assert manifest_out["export_id"] == stats.export_id
110
+ assert communities_out["export_id"] == stats.export_id
111
+ assert tf.extractfile("./keep.md") is not None
112
+ assert tf.extractfile("./entities/skills/new-skill.md") is not None
113
+ assert tf.extractfile("./entities/harnesses/new-harness.md") is not None
114
+ assert tf.extractfile("./converted/new-skill/SKILL.md") is not None
115
+ assert tf.extractfile("./converted/new-skill/references/guide.md") is not None
116
+ index_member = tf.extractfile("./graphify-out/dashboard-neighborhoods.sqlite3")
117
+ assert index_member is not None
118
+ index_path = tmp_path / "dashboard-neighborhoods.sqlite3"
119
+ index_path.write_bytes(index_member.read())
120
+ with sqlite3.connect(index_path) as conn:
121
+ assert conn.execute(
122
+ "SELECT node_id FROM slug_index WHERE slug = ?",
123
+ ("new-skill",),
124
+ ).fetchone() == ("skill:new-skill",)
125
+ assert json.loads(root_communities.read_text())["export_id"] == stats.export_id
126
+
127
+
128
+ def test_script_direct_invocation_help_works() -> None:
129
+ proc = subprocess.run(
130
+ [sys.executable, str(ROOT / "scripts" / "overlay_wiki_entities.py"), "--help"],
131
+ cwd=str(ROOT),
132
+ capture_output=True,
133
+ text=True,
134
+ check=False,
135
+ timeout=30,
136
+ )
137
+
138
+ assert proc.returncode == 0
139
+ assert "Overlay explicit local wiki entities" in proc.stdout
140
+
141
+
142
+ def test_overlay_rejects_symlinked_entity_page(tmp_path: Path) -> None:
143
+ source_wiki = tmp_path / "wiki"
144
+ (source_wiki / "entities" / "skills").mkdir(parents=True)
145
+ outside = tmp_path / "outside.md"
146
+ outside.write_text("secret", encoding="utf-8")
147
+ link = source_wiki / "entities" / "skills" / "new-skill.md"
148
+ try:
149
+ link.symlink_to(outside)
150
+ except OSError as exc:
151
+ pytest.skip(f"symlinks unavailable in this environment: {exc}")
152
+
153
+ with pytest.raises(ValueError, match="symlinked path"):
154
+ _entity_page(source_wiki, "skill", "new-skill")
155
+
156
+
157
+ def test_overlay_rejects_symlinked_skill_reference(tmp_path: Path) -> None:
158
+ source_wiki = tmp_path / "wiki"
159
+ skills_root = tmp_path / "skills"
160
+ skill_dir = skills_root / "new-skill"
161
+ (skill_dir / "references").mkdir(parents=True)
162
+ (skill_dir / "SKILL.md").write_text("# body\n", encoding="utf-8")
163
+ outside = tmp_path / "outside.md"
164
+ outside.write_text("secret", encoding="utf-8")
165
+ link = skill_dir / "references" / "leak.md"
166
+ try:
167
+ link.symlink_to(outside)
168
+ except OSError as exc:
169
+ pytest.skip(f"symlinks unavailable in this environment: {exc}")
170
+
171
+ with pytest.raises(ValueError, match="symlinked path"):
172
+ _skill_replacements(source_wiki, "new-skill", skills_root=skills_root)
src/update_repo_stats.py CHANGED
@@ -6,10 +6,11 @@ Run by the pre-commit hook so README/docs badges and inline counts never drift
6
  from reality. Reads only committed files and a live pytest collection.
7
 
8
  Sources of truth:
9
- - graph/communities.json -> total_communities
10
- - ~/.claude/skill-wiki/graphify-out/graph.json -> nodes, edges, skill/agent counts
11
- - ~/.claude/skill-wiki/entities/{skills,agents}/ -> fallback entity counts
12
- - pytest --collect-only -q -> collected test count
 
13
 
14
  Usage:
15
  python src/update_repo_stats.py # patch README/docs in place
@@ -25,11 +26,13 @@ import re
25
  import subprocess
26
  import sys
27
  import tarfile
 
28
  from pathlib import Path
29
 
30
  REPO_ROOT = Path(__file__).resolve().parent.parent
31
  README = REPO_ROOT / "README.md"
32
  DOCS_INDEX = REPO_ROOT / "docs" / "index.md"
 
33
  _MAX_TAR_JSON_BYTES = 512 * 1024 * 1024
34
  _MAX_TAR_TEXT_BYTES = 2 * 1024 * 1024
35
  _GRAPH_JSON_MEMBER = "graphify-out/graph.json"
@@ -115,6 +118,63 @@ def _parse_graph_report(text: str) -> dict[str, int]:
115
  }
116
 
117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  def _read_skills_sh_catalog_stats() -> dict[str, int]:
119
  catalog_path = REPO_ROOT / "graph" / "skills-sh-catalog.json.gz"
120
  if not catalog_path.exists():
@@ -233,6 +293,7 @@ def _read_graph_from_tarball() -> dict[str, int | None] | None:
233
  for key in ("nodes", "edges", "communities"):
234
  if key in parsed:
235
  stats[key] = parsed[key]
 
236
 
237
  if stats["nodes"] is None or stats["edges"] is None:
238
  body = _read_json_member(tf, _GRAPH_JSON_MEMBER)
@@ -425,7 +486,11 @@ def format_edges(n: int) -> str:
425
  return str(n)
426
 
427
 
428
- def build_replacements(stats: dict, tests: int | None, converted: int | None) -> list[tuple[re.Pattern, str]]:
 
 
 
 
429
  """Return (regex, replacement) pairs for every stat."""
430
  reps: list[tuple[re.Pattern, str]] = []
431
 
@@ -446,6 +511,16 @@ def build_replacements(stats: dict, tests: int | None, converted: int | None) ->
446
  f"{stats['mcps']:,} MCP servers, and "
447
  f"{stats['harnesses']:,} harnesses**",
448
  ))
 
 
 
 
 
 
 
 
 
 
449
  # 3-type pattern: "1,789 skills, 464 agents, and 10,786 MCP servers"
450
  # Order matters — this regex is more specific than the 2-type one
451
  # below, so match it first. Handles the MCP-aware tagline that
@@ -491,6 +566,10 @@ def build_replacements(stats: dict, tests: int | None, converted: int | None) ->
491
  re.compile(r"\*\*[\d,]+-node\*\*\s+graph"),
492
  f"**{n:,}-node** graph",
493
  ))
 
 
 
 
494
  # "A pre-built knowledge graph of 2,211 nodes and 642K edges"
495
  # style phrasing. Caught a stale v0.6.0 README sentence that
496
  # the older regex only matched on "nodes, edges, communities".
@@ -498,11 +577,23 @@ def build_replacements(stats: dict, tests: int | None, converted: int | None) ->
498
  re.compile(r"([\d,]+)\s+nodes\s+and\s+[\d,.]+[KM]?\s+edges"),
499
  f"{n:,} nodes and {e_fmt} edges",
500
  ))
 
 
 
 
 
 
 
 
501
  # Graph.json inline Python example: "# 2,211 nodes, 642,468 edges"
502
  reps.append((
503
  re.compile(r"#\s*([\d,]+)\s+nodes,\s*([\d,]+)\s+edges"),
504
  f"# {n:,} nodes, {e:,} edges",
505
  ))
 
 
 
 
506
  # "2,211 nodes, 642K edges, 865 communities"
507
  reps.append((re.compile(r"([\d,]+)\s+nodes,\s+[\w.]+\s+edges,\s+([\d,]+)\s+communities"),
508
  f"{n:,} nodes, {e_fmt} edges, {stats['communities']:,} communities"))
@@ -520,9 +611,151 @@ def build_replacements(stats: dict, tests: int | None, converted: int | None) ->
520
  f"**{n:,} entity pages** ({stats['skills']:,} skills + {stats['agents']:,} agents)",
521
  ))
522
 
523
- if stats.get("skills_sh_entries") and stats.get("skills_sh_bodies"):
524
- entries = int(stats["skills_sh_entries"])
525
- bodies = int(stats["skills_sh_bodies"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
526
  reps.append((
527
  re.compile(
528
  r"The shipped wiki includes [\d,]+(?: Skills\.sh)? entries, "
@@ -560,13 +793,19 @@ def build_replacements(stats: dict, tests: int | None, converted: int | None) ->
560
  return reps
561
 
562
 
563
- def build_docs_replacements(tests: int | None) -> list[tuple[re.Pattern[str], str]]:
 
 
 
 
 
564
  if tests is None:
565
- return []
566
- return [(
567
  re.compile(r"[\d,]+\s+tests collected"),
568
  f"{tests:,} tests collected",
569
- )]
 
570
 
571
 
572
  def patch_readme(check_only: bool = False) -> int:
@@ -579,12 +818,12 @@ def patch_readme(check_only: bool = False) -> int:
579
  print(f"warning: could not resolve {missing}; those fields will be left untouched", file=sys.stderr)
580
 
581
  changes: list[tuple[Path, str, str]] = []
582
- for target in (README, DOCS_INDEX):
583
  if not target.exists():
584
  continue
585
  replacements = (
586
  build_replacements(stats, tests, converted)
587
- if target == README else build_docs_replacements(tests)
588
  )
589
  original = target.read_text(encoding="utf-8")
590
  patched = original
 
6
  from reality. Reads only committed files and a live pytest collection.
7
 
8
  Sources of truth:
9
+ - graph/wiki-graph.tar.gz -> graph/report/entity counts
10
+ - graph/wiki-graph-runtime.tar.gz -> runtime graph/report counts
11
+ - graph/communities.json -> current community export
12
+ - graph/skills-sh-catalog.json.gz -> hydrated skill body counts
13
+ - pytest --collect-only -q -> collected test count
14
 
15
  Usage:
16
  python src/update_repo_stats.py # patch README/docs in place
 
26
  import subprocess
27
  import sys
28
  import tarfile
29
+ from collections.abc import Mapping
30
  from pathlib import Path
31
 
32
  REPO_ROOT = Path(__file__).resolve().parent.parent
33
  README = REPO_ROOT / "README.md"
34
  DOCS_INDEX = REPO_ROOT / "docs" / "index.md"
35
+ DOCS_KNOWLEDGE_GRAPH = REPO_ROOT / "docs" / "knowledge-graph.md"
36
  _MAX_TAR_JSON_BYTES = 512 * 1024 * 1024
37
  _MAX_TAR_TEXT_BYTES = 2 * 1024 * 1024
38
  _GRAPH_JSON_MEMBER = "graphify-out/graph.json"
 
118
  }
119
 
120
 
121
+ def _read_edge_source_stats(tf: tarfile.TarFile) -> dict[str, int]:
122
+ matches = [
123
+ member for member in tf.getmembers() if _safe_tar_name(member.name) == _GRAPH_JSON_MEMBER
124
+ ]
125
+ if len(matches) != 1 or not matches[0].isfile():
126
+ return {}
127
+ graph_stream = tf.extractfile(matches[0])
128
+ if graph_stream is None:
129
+ return {}
130
+ try:
131
+ graph = json.load(graph_stream)
132
+ except json.JSONDecodeError:
133
+ return {}
134
+ finally:
135
+ graph_stream.close()
136
+ edges = graph.get("edges", []) if isinstance(graph, dict) else []
137
+ totals = {
138
+ "semantic_edges": 0,
139
+ "tag_edges": 0,
140
+ "token_edges": 0,
141
+ "hydrated_incident_edges": 0,
142
+ "hydrated_semantic_incident_edges": 0,
143
+ "cross_skill_agent_edges": 0,
144
+ "cross_skill_mcp_edges": 0,
145
+ "cross_agent_mcp_edges": 0,
146
+ "harness_edges": 0,
147
+ }
148
+ for edge in edges:
149
+ if not isinstance(edge, dict):
150
+ continue
151
+ source = str(edge.get("source") or "")
152
+ target = str(edge.get("target") or "")
153
+ semantic = float(edge.get("semantic_sim") or 0.0) != 0.0
154
+ if semantic:
155
+ totals["semantic_edges"] += 1
156
+ if float(edge.get("tag_sim") or 0.0) != 0.0:
157
+ totals["tag_edges"] += 1
158
+ if float(edge.get("token_sim") or 0.0) != 0.0:
159
+ totals["token_edges"] += 1
160
+ if "skills-sh-" in source or "skills-sh-" in target:
161
+ totals["hydrated_incident_edges"] += 1
162
+ if semantic:
163
+ totals["hydrated_semantic_incident_edges"] += 1
164
+ source_type = source.split(":", 1)[0]
165
+ target_type = target.split(":", 1)[0]
166
+ edge_types = {source_type, target_type}
167
+ if edge_types == {"skill", "agent"}:
168
+ totals["cross_skill_agent_edges"] += 1
169
+ elif edge_types == {"skill", "mcp-server"}:
170
+ totals["cross_skill_mcp_edges"] += 1
171
+ elif edge_types == {"agent", "mcp-server"}:
172
+ totals["cross_agent_mcp_edges"] += 1
173
+ if source_type == "harness" or target_type == "harness":
174
+ totals["harness_edges"] += 1
175
+ return totals
176
+
177
+
178
  def _read_skills_sh_catalog_stats() -> dict[str, int]:
179
  catalog_path = REPO_ROOT / "graph" / "skills-sh-catalog.json.gz"
180
  if not catalog_path.exists():
 
293
  for key in ("nodes", "edges", "communities"):
294
  if key in parsed:
295
  stats[key] = parsed[key]
296
+ stats.update(_read_edge_source_stats(tf))
297
 
298
  if stats["nodes"] is None or stats["edges"] is None:
299
  body = _read_json_member(tf, _GRAPH_JSON_MEMBER)
 
486
  return str(n)
487
 
488
 
489
+ def build_replacements(
490
+ stats: Mapping[str, int | None],
491
+ tests: int | None,
492
+ converted: int | None,
493
+ ) -> list[tuple[re.Pattern, str]]:
494
  """Return (regex, replacement) pairs for every stat."""
495
  reps: list[tuple[re.Pattern, str]] = []
496
 
 
511
  f"{stats['mcps']:,} MCP servers, and "
512
  f"{stats['harnesses']:,} harnesses**",
513
  ))
514
+ reps.append((
515
+ re.compile(
516
+ r"\*\*[\d,]+\s+skill pages,\s+[\d,]+\s+agents,\s+"
517
+ r"[\d,]+\s+MCP\s+servers,\s+and\s+[\d,]+\s+"
518
+ r"(?:cataloged\s+)?harnesses\*\*"
519
+ ),
520
+ f"**{s:,} skill pages, {stats['agents']:,} agents, "
521
+ f"{stats['mcps']:,} MCP servers, and "
522
+ f"{stats['harnesses']:,} cataloged harnesses**",
523
+ ))
524
  # 3-type pattern: "1,789 skills, 464 agents, and 10,786 MCP servers"
525
  # Order matters — this regex is more specific than the 2-type one
526
  # below, so match it first. Handles the MCP-aware tagline that
 
566
  re.compile(r"\*\*[\d,]+-node\*\*\s+graph"),
567
  f"**{n:,}-node** graph",
568
  ))
569
+ reps.append((
570
+ re.compile(r"\*\*[\d,]+\s+graph nodes\*\*"),
571
+ f"**{n:,} graph nodes**",
572
+ ))
573
  # "A pre-built knowledge graph of 2,211 nodes and 642K edges"
574
  # style phrasing. Caught a stale v0.6.0 README sentence that
575
  # the older regex only matched on "nodes, edges, communities".
 
577
  re.compile(r"([\d,]+)\s+nodes\s+and\s+[\d,.]+[KM]?\s+edges"),
578
  f"{n:,} nodes and {e_fmt} edges",
579
  ))
580
+ reps.append((
581
+ re.compile(r"\(([\d,]+)\s+nodes,\s+[\d,]+\s+edges\)"),
582
+ f"({n:,} nodes, {e:,} edges)",
583
+ ))
584
+ reps.append((
585
+ re.compile(r"\*\*[\d,]+\s+nodes\s*/\s*[\d,]+\s+edges\s*/\s*[\d,]+\s+Louvain communities\*\*"),
586
+ f"**{n:,} nodes / {e:,} edges / {stats['communities']:,} Louvain communities**",
587
+ ))
588
  # Graph.json inline Python example: "# 2,211 nodes, 642,468 edges"
589
  reps.append((
590
  re.compile(r"#\s*([\d,]+)\s+nodes,\s*([\d,]+)\s+edges"),
591
  f"# {n:,} nodes, {e:,} edges",
592
  ))
593
+ reps.append((
594
+ re.compile(r"[\d,]+ weighted edges and [\d,]+ Louvain communities"),
595
+ f"{e:,} weighted edges and {stats['communities']:,} Louvain communities",
596
+ ))
597
  # "2,211 nodes, 642K edges, 865 communities"
598
  reps.append((re.compile(r"([\d,]+)\s+nodes,\s+[\w.]+\s+edges,\s+([\d,]+)\s+communities"),
599
  f"{n:,} nodes, {e_fmt} edges, {stats['communities']:,} communities"))
 
611
  f"**{n:,} entity pages** ({stats['skills']:,} skills + {stats['agents']:,} agents)",
612
  ))
613
 
614
+ bodies_for_core = stats.get("skills_sh_bodies")
615
+ if (
616
+ bodies_for_core is not None
617
+ and stats.get("skills")
618
+ and stats.get("agents")
619
+ and stats.get("mcps")
620
+ and stats.get("harnesses")
621
+ ):
622
+ core_nodes = int(n) - int(bodies_for_core)
623
+ curated_skills = int(stats["skills"] or 0) - int(bodies_for_core)
624
+ reps.append((
625
+ re.compile(
626
+ r"[\d,]+-node core plus [\d,]+ body-backed skill nodes"
627
+ ),
628
+ f"{core_nodes:,}-node core plus {int(bodies_for_core):,} "
629
+ "body-backed skill nodes",
630
+ ))
631
+ reps.append((
632
+ re.compile(
633
+ r"[\d,]+ shipped graph nodes: [\d,]+ curated "
634
+ r"skill/agent/MCP/harness\s+nodes plus [\d,]+ "
635
+ r"body-backed skill nodes"
636
+ ),
637
+ f"{n:,} shipped graph nodes: {core_nodes:,} curated "
638
+ "skill/agent/MCP/harness nodes plus "
639
+ f"{int(bodies_for_core):,} body-backed skill nodes",
640
+ ))
641
+ reps.append((
642
+ re.compile(
643
+ r"\*\*[\d,]+\*\* \([\d,]+ skills \+ [\d,]+ agents "
644
+ r"\+ [\d,]+ MCP servers \+ [\d,]+ harnesses\)"
645
+ ),
646
+ f"**{core_nodes:,}** ({curated_skills:,} skills + "
647
+ f"{stats['agents']:,} agents + {stats['mcps']:,} MCP servers "
648
+ f"+ {stats['harnesses']:,} harnesses)",
649
+ ))
650
+ reps.append((
651
+ re.compile(r"including [\d,]+ skill pages"),
652
+ f"including {stats['skills']:,} skill pages",
653
+ ))
654
+ reps.append((
655
+ re.compile(
656
+ r"is \*\*[\d,]+ nodes\*\* \([\d,]+ curated skills "
657
+ r"\+ [\d,]+ agents \+ [\d,]+ MCP servers\s+\+ "
658
+ r"[\d,]+ harnesses\)"
659
+ ),
660
+ f"is **{core_nodes:,} nodes** ({curated_skills:,} curated skills "
661
+ f"+ {stats['agents']:,} agents + {stats['mcps']:,} MCP servers "
662
+ f"+ {stats['harnesses']:,} harnesses)",
663
+ ))
664
+
665
+ table_values = {
666
+ "Total nodes": n,
667
+ "Total edges": e,
668
+ "Harness edges": stats.get("harness_edges"),
669
+ }
670
+ for label, value in table_values.items():
671
+ if value is not None:
672
+ reps.append((
673
+ re.compile(rf"\| {re.escape(label)} \| \*\*[\d,]+\*\* \|"),
674
+ f"| {label} | **{int(value):,}** |",
675
+ ))
676
+
677
+ if stats.get("semantic_edges") and stats.get("tag_edges") and stats.get("token_edges"):
678
+ reps.append((
679
+ re.compile(
680
+ r"semantic [\d,]+ - tag [\d,]+ - token [\d,]+"
681
+ ),
682
+ f"semantic {stats['semantic_edges']:,} - "
683
+ f"tag {stats['tag_edges']:,} - token {stats['token_edges']:,}",
684
+ ))
685
+
686
+ for label, key in (
687
+ ("Hydrated skill incident edges", "hydrated_incident_edges"),
688
+ ("Hydrated skill semantic incident edges", "hydrated_semantic_incident_edges"),
689
+ ):
690
+ value = stats.get(key)
691
+ if value is not None:
692
+ reps.append((
693
+ re.compile(rf"\| {re.escape(label)} \| \*\*?[\d,]+\*?\*? \|"),
694
+ f"| {label} | **{int(value):,}** |",
695
+ ))
696
+
697
+ for label, key in (
698
+ ("Cross-type edges \\(skill <-> agent\\)", "cross_skill_agent_edges"),
699
+ ("Cross-type edges \\(skill <-> MCP\\)", "cross_skill_mcp_edges"),
700
+ ("Cross-type edges \\(agent <-> MCP\\)", "cross_agent_mcp_edges"),
701
+ ):
702
+ value = stats.get(key)
703
+ if value is not None:
704
+ display_label = label.replace("\\", "")
705
+ reps.append((
706
+ re.compile(rf"\| {label} \| ~?[\d,.]+[KM]? \|"),
707
+ f"| {display_label} | ~{int(value):,} |",
708
+ ))
709
+
710
+ skills_sh_entries = stats.get("skills_sh_entries")
711
+ skills_sh_bodies = stats.get("skills_sh_bodies")
712
+ if skills_sh_entries is not None and skills_sh_bodies is not None:
713
+ entries = int(skills_sh_entries)
714
+ bodies = int(skills_sh_bodies)
715
+ skill_pages = int(stats.get("skills") or entries)
716
+ reps.append((
717
+ re.compile(
718
+ r"\*\*[\d,]+\s+(?:skills|skill entity pages)\*\*"
719
+ r"(?:,\s+with\s+\*\*[\d,]+\*\*)?\s+hydrated installable "
720
+ r"`SKILL\.md` bodies\."
721
+ ),
722
+ f"**{skill_pages:,} skill entity pages**, with **{bodies:,}** "
723
+ "hydrated installable `SKILL.md` bodies.",
724
+ ))
725
+ reps.append((
726
+ re.compile(
727
+ r"[\d,]+ skill entity pages under `entities/skills/`, "
728
+ r"[\d,]+ hydrated"
729
+ ),
730
+ f"{skill_pages:,} skill entity pages under `entities/skills/`, "
731
+ f"{bodies:,} hydrated",
732
+ ))
733
+ reps.append((
734
+ re.compile(r"\*\*[\d,]+ skill pages\*\*; \*\*[\d,]+\*\*"),
735
+ f"**{skill_pages:,} skill pages**; **{bodies:,}**",
736
+ ))
737
+ reps.append((
738
+ re.compile(
739
+ r"\*\*[\d,]+\*\*\s+hydrated installable skill entries"
740
+ ),
741
+ f"**{bodies:,}** hydrated installable skill entries",
742
+ ))
743
+ reps.append((
744
+ re.compile(
745
+ r"\| Body-backed skill nodes \| \*\*[\d,]+\*\* "
746
+ r"hydrated installable skill entries \|"
747
+ ),
748
+ f"| Body-backed skill nodes | **{bodies:,}** "
749
+ "hydrated installable skill entries |",
750
+ ))
751
+ reps.append((
752
+ re.compile(r"\*\*[\d,]+\*\*\s+observed body-backed skill entries"),
753
+ f"**{bodies:,}** observed body-backed skill entries",
754
+ ))
755
+ reps.append((
756
+ re.compile(r"\*\*[\d,]+\*\*\s+have hydrated catalog bodies"),
757
+ f"**{bodies:,}** have hydrated catalog bodies",
758
+ ))
759
  reps.append((
760
  re.compile(
761
  r"The shipped wiki includes [\d,]+(?: Skills\.sh)? entries, "
 
793
  return reps
794
 
795
 
796
+ def build_docs_replacements(
797
+ stats: Mapping[str, int | None],
798
+ tests: int | None,
799
+ converted: int | None,
800
+ ) -> list[tuple[re.Pattern[str], str]]:
801
+ reps = build_replacements(stats, tests, converted)
802
  if tests is None:
803
+ return reps
804
+ reps.append((
805
  re.compile(r"[\d,]+\s+tests collected"),
806
  f"{tests:,} tests collected",
807
+ ))
808
+ return reps
809
 
810
 
811
  def patch_readme(check_only: bool = False) -> int:
 
818
  print(f"warning: could not resolve {missing}; those fields will be left untouched", file=sys.stderr)
819
 
820
  changes: list[tuple[Path, str, str]] = []
821
+ for target in (README, DOCS_INDEX, DOCS_KNOWLEDGE_GRAPH):
822
  if not target.exists():
823
  continue
824
  replacements = (
825
  build_replacements(stats, tests, converted)
826
+ if target == README else build_docs_replacements(stats, tests, converted)
827
  )
828
  original = target.read_text(encoding="utf-8")
829
  patched = original
src/validate_graph_artifacts.py CHANGED
@@ -6,6 +6,7 @@ from __future__ import annotations
6
  import argparse
7
  import gzip
8
  import json
 
9
  import re
10
  import sqlite3
11
  import tarfile
@@ -43,9 +44,45 @@ _PREVIEW_EXPORT_ID_RE = re.compile(
43
  r'<meta\s+name=["\']ctx-graph-export-id["\']\s+content=["\']([^"\']+)["\']',
44
  re.IGNORECASE,
45
  )
 
 
 
 
 
 
 
 
 
 
 
 
46
  _SEMANTIC_SIM_RE = re.compile(
47
  rb'"semantic_sim"\s*:\s*(-?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)',
48
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  _WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:")
50
  _PREVIEW_HTML_FILES = (
51
  "sample-top60.html",
@@ -54,6 +91,7 @@ _PREVIEW_HTML_FILES = (
54
  "viz-python.html",
55
  "viz-security.html",
56
  )
 
57
  _GRAPH_RUNTIME_REQUIRED_NAMES = {
58
  "index.md",
59
  "graphify-out/graph.json",
@@ -122,6 +160,78 @@ def _load_gzip_json(path: Path) -> dict[str, Any]:
122
  return data
123
 
124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  def _require_real_file(path: Path) -> None:
126
  if not path.is_file() or path.stat().st_size == 0:
127
  raise GraphArtifactError(f"missing or empty graph artifact: {path}")
@@ -230,6 +340,29 @@ def _count_lines(payload: bytes) -> int:
230
  return len(payload.decode("utf-8", errors="replace").splitlines())
231
 
232
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
  def _scan_graph_json(stream: IO[bytes]) -> tuple[int, int, int, int, int, str | None]:
234
  nodes = edges = semantic_edges = skills_sh_nodes = harness_nodes = 0
235
  export_id: str | None = None
@@ -238,6 +371,8 @@ def _scan_graph_json(stream: IO[bytes]) -> tuple[int, int, int, int, int, str |
238
  while chunk := stream.read(1024 * 1024):
239
  old_tail = tail
240
  data = tail + chunk
 
 
241
  if export_id is None:
242
  graph_probe = (graph_probe + chunk)[-1024 * 1024:]
243
  export_id = _extract_graph_export_id(graph_probe)
@@ -255,7 +390,7 @@ def _scan_graph_json(stream: IO[bytes]) -> tuple[int, int, int, int, int, str |
255
  len(_HARNESS_TYPE_RE.findall(data))
256
  - len(_HARNESS_TYPE_RE.findall(old_tail))
257
  )
258
- tail = data[-512:]
259
  return nodes, edges, semantic_edges, skills_sh_nodes, harness_nodes, export_id
260
 
261
 
@@ -322,6 +457,135 @@ def _count_nonzero_semantic_matches(data: bytes) -> int:
322
  return count
323
 
324
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
325
  def _catalog_skills(catalog: dict[str, Any]) -> list[dict[str, Any]]:
326
  raw = catalog.get("skills", [])
327
  return [item for item in raw if isinstance(item, dict)]
@@ -355,7 +619,8 @@ def validate_graph_artifacts(
355
  runtime_tarball = graph_dir / "wiki-graph-runtime.tar.gz"
356
  catalog_path = graph_dir / "skills-sh-catalog.json.gz"
357
  communities_path = graph_dir / "communities.json"
358
- for path in (tarball, runtime_tarball, catalog_path, communities_path):
 
359
  _require_real_file(path)
360
 
361
  expected_harnesses = DEFAULT_HARNESSES if expected_harnesses is None else expected_harnesses
@@ -363,6 +628,7 @@ def validate_graph_artifacts(
363
  runtime_tarball,
364
  expected_harnesses=expected_harnesses,
365
  )
 
366
  catalog = _load_gzip_json(catalog_path)
367
  root_communities = _load_json(communities_path)
368
  if not isinstance(root_communities, dict):
@@ -397,6 +663,7 @@ def validate_graph_artifacts(
397
  manifest: dict[str, Any] | None = None
398
  archive_communities: dict[str, Any] | None = None
399
  dashboard_index_path: Path | None = None
 
400
 
401
  with tarfile.open(tarball, "r:gz") as tf:
402
  for member in tf:
@@ -422,6 +689,20 @@ def validate_graph_artifacts(
422
  harness_pages += 1
423
  if name.startswith("converted/skills-sh-") and name.endswith("/SKILL.md"):
424
  skills_sh_converted += 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
425
  if member.isfile() and name == "graphify-out/graph.json":
426
  f = tf.extractfile(member)
427
  if f is None:
@@ -478,6 +759,18 @@ def validate_graph_artifacts(
478
  f"{member.name} has {lines} lines, above limit {limit}",
479
  )
480
 
 
 
 
 
 
 
 
 
 
 
 
 
481
  required_names = _GRAPH_RUNTIME_REQUIRED_NAMES
482
  missing_required = sorted(required_names - names)
483
  if missing_required:
 
6
  import argparse
7
  import gzip
8
  import json
9
+ import math
10
  import re
11
  import sqlite3
12
  import tarfile
 
44
  r'<meta\s+name=["\']ctx-graph-export-id["\']\s+content=["\']([^"\']+)["\']',
45
  re.IGNORECASE,
46
  )
47
+ _SKILL_BUNDLE_REF_RE = re.compile(
48
+ r"""(?:^|[\s`'"\[(])(?:\./)?"""
49
+ r"""((?:references|reference|resources|scripts|assets)/[^\s`'"\])<>]+)""",
50
+ re.IGNORECASE,
51
+ )
52
+ _SKILL_BUNDLE_REF_MARKERS = (
53
+ b"references/",
54
+ b"reference/",
55
+ b"resources/",
56
+ b"scripts/",
57
+ b"assets/",
58
+ )
59
  _SEMANTIC_SIM_RE = re.compile(
60
  rb'"semantic_sim"\s*:\s*(-?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)',
61
  )
62
+ _EDGE_SCORE_VALUE_RE = re.compile(
63
+ rb'"(weight|final_weight|similarity_score|semantic_sim|tag_sim|token_sim)"'
64
+ rb'\s*:\s*("[^"]*"|-?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)',
65
+ )
66
+ _SCORE_COMPONENTS_RE = re.compile(
67
+ rb'"score_components"\s*:\s*\{(?P<body>[^{}]*)\}',
68
+ re.DOTALL,
69
+ )
70
+ _SCORE_COMPONENT_VALUE_RE = re.compile(
71
+ rb'"[^"]+"\s*:\s*("[^"]*"|-?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)',
72
+ )
73
+ _EDGE_SEGMENT_RE = re.compile(
74
+ rb'"source"\s*:\s*"[^"]+"\s*,\s*"target"\s*:\s*"[^"]+"'
75
+ rb'(?P<body>.*?)(?=(?:\{\s*"source"\s*:)|(?:\]\s*(?:,|\})))',
76
+ re.DOTALL,
77
+ )
78
+ _EDGE_SCORE_FIELDS = (
79
+ "weight",
80
+ "final_weight",
81
+ "similarity_score",
82
+ "semantic_sim",
83
+ "tag_sim",
84
+ "token_sim",
85
+ )
86
  _WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:")
87
  _PREVIEW_HTML_FILES = (
88
  "sample-top60.html",
 
91
  "viz-python.html",
92
  "viz-security.html",
93
  )
94
+ _SCORE_COMPONENT_TOLERANCE = 0.001
95
  _GRAPH_RUNTIME_REQUIRED_NAMES = {
96
  "index.md",
97
  "graphify-out/graph.json",
 
160
  return data
161
 
162
 
163
+ def _validate_root_entity_overlay(path: Path) -> None:
164
+ records = 0
165
+ for lineno, raw_line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
166
+ line = raw_line.strip()
167
+ if not line:
168
+ continue
169
+ try:
170
+ payload = json.loads(line)
171
+ except json.JSONDecodeError as exc:
172
+ raise GraphArtifactError(
173
+ f"graph/entity-overlays.jsonl line {lineno} is invalid JSON: {exc}",
174
+ ) from exc
175
+ if not isinstance(payload, dict):
176
+ raise GraphArtifactError(
177
+ f"graph/entity-overlays.jsonl line {lineno} must be a JSON object",
178
+ )
179
+ nodes = payload.get("nodes", [])
180
+ edges = payload.get("edges", [])
181
+ if not isinstance(nodes, list) or not isinstance(edges, list):
182
+ raise GraphArtifactError(
183
+ f"graph/entity-overlays.jsonl line {lineno} must contain nodes/edges lists",
184
+ )
185
+ for index, node in enumerate(nodes, 1):
186
+ if not isinstance(node, dict) or not isinstance(node.get("id"), str):
187
+ raise GraphArtifactError(
188
+ f"graph/entity-overlays.jsonl line {lineno} node {index} "
189
+ "must contain id",
190
+ )
191
+ for index, edge in enumerate(edges, 1):
192
+ if not isinstance(edge, dict):
193
+ raise GraphArtifactError(
194
+ f"graph/entity-overlays.jsonl line {lineno} edge {index} "
195
+ "must be an object",
196
+ )
197
+ if not isinstance(edge.get("source"), str) or not isinstance(
198
+ edge.get("target"), str
199
+ ):
200
+ raise GraphArtifactError(
201
+ f"graph/entity-overlays.jsonl line {lineno} edge {index} "
202
+ "must contain source/target",
203
+ )
204
+ numeric_scores: dict[str, float] = {}
205
+ for field in _EDGE_SCORE_FIELDS:
206
+ value = edge.get(field)
207
+ if value is not None and (
208
+ not isinstance(value, int | float) or not 0 <= float(value) <= 1
209
+ ):
210
+ raise GraphArtifactError(
211
+ f"graph/entity-overlays.jsonl line {lineno} edge {index} "
212
+ f"{field} must be 0..1",
213
+ )
214
+ if value is not None:
215
+ numeric_scores[field] = float(value)
216
+ if (
217
+ "weight" in numeric_scores
218
+ and "final_weight" in numeric_scores
219
+ and abs(numeric_scores["weight"] - numeric_scores["final_weight"]) > 1e-9
220
+ ):
221
+ raise GraphArtifactError(
222
+ f"graph/entity-overlays.jsonl line {lineno} edge {index} "
223
+ "weight must equal final_weight",
224
+ )
225
+ _validate_score_component_mapping(
226
+ edge.get("final_weight"),
227
+ edge.get("score_components"),
228
+ context=f"graph/entity-overlays.jsonl line {lineno} edge {index}",
229
+ )
230
+ records += 1
231
+ if records == 0:
232
+ raise GraphArtifactError("graph/entity-overlays.jsonl has no overlay records")
233
+
234
+
235
  def _require_real_file(path: Path) -> None:
236
  if not path.is_file() or path.stat().st_size == 0:
237
  raise GraphArtifactError(f"missing or empty graph artifact: {path}")
 
340
  return len(payload.decode("utf-8", errors="replace").splitlines())
341
 
342
 
343
+ def _is_converted_skill_page(name: str) -> bool:
344
+ return name.startswith("converted/") and name.endswith("/SKILL.md")
345
+
346
+
347
+ def _iter_skill_bundle_refs(payload: bytes) -> list[str]:
348
+ lower_payload = payload.lower()
349
+ if not any(marker in lower_payload for marker in _SKILL_BUNDLE_REF_MARKERS):
350
+ return []
351
+ text = payload.decode("utf-8", errors="replace")
352
+ refs: set[str] = set()
353
+ for match in _SKILL_BUNDLE_REF_RE.finditer(text):
354
+ ref = match.group(1).replace("\\", "/")
355
+ ref = ref.split("#", 1)[0].split("?", 1)[0].rstrip(".,;:")
356
+ parts = ref.split("/")
357
+ if ref and all(part not in ("", ".", "..") for part in parts):
358
+ refs.add(ref)
359
+ return sorted(refs)
360
+
361
+
362
+ def _skill_bundle_target_name(skill_page: str, ref: str) -> str:
363
+ return f"{skill_page.rsplit('/', 1)[0]}/{ref}"
364
+
365
+
366
  def _scan_graph_json(stream: IO[bytes]) -> tuple[int, int, int, int, int, str | None]:
367
  nodes = edges = semantic_edges = skills_sh_nodes = harness_nodes = 0
368
  export_id: str | None = None
 
371
  while chunk := stream.read(1024 * 1024):
372
  old_tail = tail
373
  data = tail + chunk
374
+ _validate_graph_edge_score_fields(data)
375
+ _validate_graph_edge_weight_drift(data)
376
  if export_id is None:
377
  graph_probe = (graph_probe + chunk)[-1024 * 1024:]
378
  export_id = _extract_graph_export_id(graph_probe)
 
390
  len(_HARNESS_TYPE_RE.findall(data))
391
  - len(_HARNESS_TYPE_RE.findall(old_tail))
392
  )
393
+ tail = data[-65536:]
394
  return nodes, edges, semantic_edges, skills_sh_nodes, harness_nodes, export_id
395
 
396
 
 
457
  return count
458
 
459
 
460
+ def _validate_graph_edge_score_fields(data: bytes) -> None:
461
+ for match in _EDGE_SCORE_VALUE_RE.finditer(data):
462
+ field = match.group(1).decode("ascii")
463
+ raw_value = match.group(2)
464
+ try:
465
+ value = float(raw_value)
466
+ except ValueError as exc:
467
+ raise GraphArtifactError(f"graph.json edge {field} must be numeric") from exc
468
+ if not math.isfinite(value):
469
+ raise GraphArtifactError(f"graph.json edge {field} must be finite")
470
+ if not 0 <= value <= 1:
471
+ raise GraphArtifactError(f"graph.json edge {field} must be 0..1")
472
+ _validate_graph_edge_score_objects(data)
473
+
474
+
475
+ def _validate_graph_edge_score_objects(data: bytes) -> None:
476
+ try:
477
+ graph = json.loads(data)
478
+ except json.JSONDecodeError:
479
+ return
480
+ edges = graph.get("edges") if isinstance(graph, dict) else None
481
+ if not isinstance(edges, list):
482
+ return
483
+ for edge in edges:
484
+ if not isinstance(edge, dict):
485
+ continue
486
+ for field in _EDGE_SCORE_FIELDS:
487
+ if field not in edge:
488
+ continue
489
+ value = edge[field]
490
+ if not isinstance(value, int | float):
491
+ raise GraphArtifactError(f"graph.json edge {field} must be numeric")
492
+ numeric = float(value)
493
+ if not math.isfinite(numeric):
494
+ raise GraphArtifactError(f"graph.json edge {field} must be finite")
495
+ if not 0 <= numeric <= 1:
496
+ raise GraphArtifactError(f"graph.json edge {field} must be 0..1")
497
+
498
+
499
+ def _validate_graph_edge_weight_drift(data: bytes) -> None:
500
+ for match in _EDGE_SEGMENT_RE.finditer(data):
501
+ edge = match.group(0)
502
+ values: dict[str, float] = {}
503
+ for field_match in _EDGE_SCORE_VALUE_RE.finditer(edge):
504
+ field = field_match.group(1).decode("ascii")
505
+ if field in {"weight", "final_weight"}:
506
+ values[field] = float(field_match.group(2))
507
+ if (
508
+ "weight" in values
509
+ and "final_weight" in values
510
+ and abs(values["weight"] - values["final_weight"]) > 1e-9
511
+ ):
512
+ raise GraphArtifactError("graph.json edge weight must equal final_weight")
513
+ if "final_weight" in values:
514
+ _validate_score_component_bytes(
515
+ edge,
516
+ final_weight=values["final_weight"],
517
+ context="graph.json edge",
518
+ )
519
+
520
+
521
+ def _validate_score_component_mapping(
522
+ final_weight: object,
523
+ components: object,
524
+ *,
525
+ context: str,
526
+ ) -> None:
527
+ if components is None:
528
+ return
529
+ if not isinstance(final_weight, int | float) or not isinstance(components, dict):
530
+ raise GraphArtifactError(f"{context} score_components must sum to final_weight")
531
+ if not math.isfinite(float(final_weight)):
532
+ raise GraphArtifactError(f"{context} final_weight must be finite")
533
+ numeric_components: list[float] = []
534
+ for value in components.values():
535
+ if not isinstance(value, int | float):
536
+ raise GraphArtifactError(f"{context} score_components must be numeric")
537
+ numeric = float(value)
538
+ if not math.isfinite(numeric):
539
+ raise GraphArtifactError(f"{context} score_components must be finite")
540
+ if numeric < 0.0 or numeric > 1.0:
541
+ raise GraphArtifactError(f"{context} score_components must be 0..1")
542
+ numeric_components.append(numeric)
543
+ _validate_score_component_sum(
544
+ float(final_weight),
545
+ numeric_components,
546
+ context=context,
547
+ )
548
+
549
+
550
+ def _validate_score_component_bytes(
551
+ edge: bytes,
552
+ *,
553
+ final_weight: float,
554
+ context: str,
555
+ ) -> None:
556
+ components_match = _SCORE_COMPONENTS_RE.search(edge)
557
+ if components_match is None:
558
+ return
559
+ raw_components = components_match.group("body")
560
+ component_values: list[float] = []
561
+ for field_match in _SCORE_COMPONENT_VALUE_RE.finditer(raw_components):
562
+ try:
563
+ component = float(field_match.group(1))
564
+ except ValueError as exc:
565
+ raise GraphArtifactError(f"{context} score_components must be numeric") from exc
566
+ if not math.isfinite(component):
567
+ raise GraphArtifactError(f"{context} score_components must be finite")
568
+ if component < 0.0 or component > 1.0:
569
+ raise GraphArtifactError(f"{context} score_components must be 0..1")
570
+ component_values.append(component)
571
+ if not component_values:
572
+ raise GraphArtifactError(f"{context} score_components must sum to final_weight")
573
+ _validate_score_component_sum(final_weight, component_values, context=context)
574
+
575
+
576
+ def _validate_score_component_sum(
577
+ final_weight: float,
578
+ component_values: list[float],
579
+ *,
580
+ context: str,
581
+ ) -> None:
582
+ if not math.isfinite(final_weight):
583
+ raise GraphArtifactError(f"{context} final_weight must be finite")
584
+ component_total = min(sum(component_values), 1.0)
585
+ if abs(component_total - final_weight) > _SCORE_COMPONENT_TOLERANCE:
586
+ raise GraphArtifactError(f"{context} score_components must sum to final_weight")
587
+
588
+
589
  def _catalog_skills(catalog: dict[str, Any]) -> list[dict[str, Any]]:
590
  raw = catalog.get("skills", [])
591
  return [item for item in raw if isinstance(item, dict)]
 
619
  runtime_tarball = graph_dir / "wiki-graph-runtime.tar.gz"
620
  catalog_path = graph_dir / "skills-sh-catalog.json.gz"
621
  communities_path = graph_dir / "communities.json"
622
+ overlay_path = graph_dir / "entity-overlays.jsonl"
623
+ for path in (tarball, runtime_tarball, catalog_path, communities_path, overlay_path):
624
  _require_real_file(path)
625
 
626
  expected_harnesses = DEFAULT_HARNESSES if expected_harnesses is None else expected_harnesses
 
628
  runtime_tarball,
629
  expected_harnesses=expected_harnesses,
630
  )
631
+ _validate_root_entity_overlay(overlay_path)
632
  catalog = _load_gzip_json(catalog_path)
633
  root_communities = _load_json(communities_path)
634
  if not isinstance(root_communities, dict):
 
663
  manifest: dict[str, Any] | None = None
664
  archive_communities: dict[str, Any] | None = None
665
  dashboard_index_path: Path | None = None
666
+ skill_bundle_refs: list[tuple[str, str, str]] = []
667
 
668
  with tarfile.open(tarball, "r:gz") as tf:
669
  for member in tf:
 
689
  harness_pages += 1
690
  if name.startswith("converted/skills-sh-") and name.endswith("/SKILL.md"):
691
  skills_sh_converted += 1
692
+ if member.isfile() and _is_converted_skill_page(name):
693
+ f = tf.extractfile(member)
694
+ if f is None:
695
+ raise GraphArtifactError(f"{member.name} could not be read")
696
+ payload = f.read()
697
+ for ref in _iter_skill_bundle_refs(payload):
698
+ skill_bundle_refs.append((name, ref, _skill_bundle_target_name(name, ref)))
699
+ if deep and name.startswith("converted/skills-sh-"):
700
+ lines = _count_lines(payload)
701
+ if lines > line_threshold:
702
+ raise GraphArtifactError(
703
+ f"{member.name} has {lines} lines, above limit {line_threshold}",
704
+ )
705
+ continue
706
  if member.isfile() and name == "graphify-out/graph.json":
707
  f = tf.extractfile(member)
708
  if f is None:
 
759
  f"{member.name} has {lines} lines, above limit {limit}",
760
  )
761
 
762
+ missing_bundle_refs = [
763
+ (skill_page, ref, target)
764
+ for skill_page, ref, target in skill_bundle_refs
765
+ if target not in names
766
+ ]
767
+ if missing_bundle_refs:
768
+ sample = "; ".join(
769
+ f"{skill_page} references {ref} but {target} is absent"
770
+ for skill_page, ref, target in missing_bundle_refs[:5]
771
+ )
772
+ raise GraphArtifactError(f"missing bundled skill file: {sample}")
773
+
774
  required_names = _GRAPH_RUNTIME_REQUIRED_NAMES
775
  missing_required = sorted(required_names - names)
776
  if missing_required: