Stevesolun commited on
Commit
1b56ed2
·
verified ·
1 Parent(s): aa20be6

Sync ctx 6f02987

Browse files

GitHub commit: 6f029879196b75d112d71b975be0411821897d4d

Files changed (48) hide show
  1. .github/workflows/publish.yml +6 -6
  2. .github/workflows/test.yml +6 -6
  3. CHANGELOG.md +25 -0
  4. README.md +8 -8
  5. docs/huggingface-publish.md +1 -1
  6. docs/index.md +12 -12
  7. docs/knowledge-graph.md +14 -12
  8. graph/README.md +12 -11
  9. graph/communities.json +6 -7
  10. graph/sample-top60.html +0 -0
  11. graph/skills-sh-catalog.json.gz +2 -2
  12. graph/viz-ai-agents.html +0 -0
  13. graph/viz-overview.html +0 -0
  14. graph/viz-python.html +0 -0
  15. graph/viz-security.html +0 -0
  16. graph/wiki-graph-runtime.tar.gz +2 -2
  17. graph/wiki-graph.tar.gz +2 -2
  18. imported-skills/mattpocock/ATTRIBUTION.md +110 -116
  19. imported-skills/mattpocock/MANIFEST.json +2 -32
  20. imported-skills/mattpocock/README.md +49 -55
  21. imported-skills/mattpocock/UPSTREAM_REVISION +1 -1
  22. imported-skills/mattpocock/domain-model/ADR-FORMAT.md +0 -47
  23. imported-skills/mattpocock/domain-model/CONTEXT-FORMAT.md +0 -77
  24. imported-skills/mattpocock/domain-model/SKILL.md +0 -81
  25. imported-skills/mattpocock/github-triage/AGENT-BRIEF.md +0 -168
  26. imported-skills/mattpocock/github-triage/OUT-OF-SCOPE.md +0 -101
  27. imported-skills/mattpocock/github-triage/SKILL.md +0 -168
  28. imported-skills/mattpocock/grill-with-docs/SKILL.md +1 -1
  29. imported-skills/mattpocock/triage-issue/SKILL.md +0 -102
  30. pyproject.toml +1 -1
  31. scripts/build_dashboard_graph_index.py +169 -0
  32. src/__init__.py +1 -1
  33. src/ctx/__init__.py +1 -1
  34. src/ctx/core/graph/resolve_graph.py +8 -2
  35. src/ctx/core/source_registry.py +228 -228
  36. src/ctx/core/wiki/wiki_queue_worker.py +10 -0
  37. src/ctx_init.py +77 -5
  38. src/ctx_monitor.py +586 -22
  39. src/mcp_add.py +144 -143
  40. src/tests/test_ctx_init.py +103 -0
  41. src/tests/test_ctx_monitor.py +582 -8
  42. src/tests/test_ctx_monitor_3type.py +2 -0
  43. src/tests/test_ctx_monitor_browser.py +1 -0
  44. src/tests/test_incremental_attach_az_flow.py +1 -0
  45. src/tests/test_mcp_add.py +82 -74
  46. src/tests/test_validate_graph_artifacts.py +236 -6
  47. src/tests/test_wiki_queue_worker.py +38 -0
  48. src/validate_graph_artifacts.py +155 -2
.github/workflows/publish.yml CHANGED
@@ -242,17 +242,17 @@ jobs:
242
  --min-edges 2000000 \
243
  --min-skills-sh-nodes 89000 \
244
  --min-semantic-edges 1000000 \
245
- --expected-nodes 102718 \
246
- --expected-edges 2911220 \
247
- --expected-semantic-edges 1683265 \
248
- --expected-harness-nodes 14 \
249
  --expected-skills-sh-nodes 89463 \
250
  --expected-skills-sh-catalog-entries 89463 \
251
  --expected-skills-sh-converted 89463 \
252
- --expected-skill-pages 91450 \
253
  --expected-agent-pages 467 \
254
  --expected-mcp-pages 10787 \
255
- --expected-harness-pages 14 \
256
  --line-threshold 180 \
257
  --max-stage-lines 40
258
 
 
242
  --min-edges 2000000 \
243
  --min-skills-sh-nodes 89000 \
244
  --min-semantic-edges 1000000 \
245
+ --expected-nodes 102717 \
246
+ --expected-edges 2911162 \
247
+ --expected-semantic-edges 1683182 \
248
+ --expected-harness-nodes 15 \
249
  --expected-skills-sh-nodes 89463 \
250
  --expected-skills-sh-catalog-entries 89463 \
251
  --expected-skills-sh-converted 89463 \
252
+ --expected-skill-pages 91448 \
253
  --expected-agent-pages 467 \
254
  --expected-mcp-pages 10787 \
255
+ --expected-harness-pages 15 \
256
  --line-threshold 180 \
257
  --max-stage-lines 40
258
 
.github/workflows/test.yml CHANGED
@@ -400,17 +400,17 @@ jobs:
400
  --min-edges 2000000 \
401
  --min-skills-sh-nodes 89000 \
402
  --min-semantic-edges 1000000 \
403
- --expected-nodes 102718 \
404
- --expected-edges 2911220 \
405
- --expected-semantic-edges 1683265 \
406
- --expected-harness-nodes 14 \
407
  --expected-skills-sh-nodes 89463 \
408
  --expected-skills-sh-catalog-entries 89463 \
409
  --expected-skills-sh-converted 89463 \
410
- --expected-skill-pages 91450 \
411
  --expected-agent-pages 467 \
412
  --expected-mcp-pages 10787 \
413
- --expected-harness-pages 14 \
414
  --line-threshold 180 \
415
  --max-stage-lines 40
416
 
 
400
  --min-edges 2000000 \
401
  --min-skills-sh-nodes 89000 \
402
  --min-semantic-edges 1000000 \
403
+ --expected-nodes 102717 \
404
+ --expected-edges 2911162 \
405
+ --expected-semantic-edges 1683182 \
406
+ --expected-harness-nodes 15 \
407
  --expected-skills-sh-nodes 89463 \
408
  --expected-skills-sh-catalog-entries 89463 \
409
  --expected-skills-sh-converted 89463 \
410
+ --expected-skill-pages 91448 \
411
  --expected-agent-pages 467 \
412
  --expected-mcp-pages 10787 \
413
+ --expected-harness-pages 15 \
414
  --line-threshold 180 \
415
  --max-stage-lines 40
416
 
CHANGELOG.md CHANGED
@@ -7,6 +7,30 @@ Format loosely follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
7
 
8
  - No unreleased changes yet.
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  ## [1.0.5] - 2026-05-14
11
 
12
  ### Fixed
@@ -1524,6 +1548,7 @@ pass. Full test suite: **1316 passed, 2 skipped**.
1524
  - 5 dead imports removed (`os`, `Mapping`, `timedelta` from
1525
  `ctx_lifecycle`; `Path` from `intake_gate`, `intake_pipeline`).
1526
 
 
1527
  [1.0.5]: https://github.com/stevesolun/ctx/releases/tag/v1.0.5
1528
  [1.0.4]: https://github.com/stevesolun/ctx/releases/tag/v1.0.4
1529
  [1.0.3]: https://github.com/stevesolun/ctx/releases/tag/v1.0.3
 
7
 
8
  - No unreleased changes yet.
9
 
10
+ ## [1.0.6] - 2026-05-14
11
+
12
+ ### Fixed
13
+
14
+ - Promoted Mirage, CodeGraph, and `codegraph-agentic-codebase-analysis` from
15
+ graph overlay-only records into first-class shipped LLM-wiki pages in
16
+ `graph/wiki-graph.tar.gz`; the fast runtime archive now carries the Mirage
17
+ harness page for custom/API/local model onboarding.
18
+ - Regenerated graph preview HTML from the refreshed graph export and updated
19
+ exact graph artifact validation counts to 102,717 nodes, 2,911,162 edges,
20
+ 91,448 skill pages, 467 agent pages, 10,787 MCP pages, and 15 harness pages.
21
+ - Added a compact dashboard neighborhood index to the shipped runtime/full
22
+ graph archives so dashboard graph lookup does not parse the 604 MB
23
+ `graph.json` on the first request.
24
+ - Fixed `ctx-init --graph --graph-url ...` so an explicit remote graph URL is
25
+ verified and downloaded instead of being silently shadowed by any local
26
+ source-checkout archive.
27
+ - Fixed dashboard entity deletion queue jobs so the worker no longer fails by
28
+ trying to read an entity page that the dashboard already removed; deletes now
29
+ queue a full graph-only refresh.
30
+ - Fixed cross-source MCP canonical merges so the queued wiki refresh and
31
+ canonical index use the existing target slug/path instead of the incoming
32
+ alias slug.
33
+
34
  ## [1.0.5] - 2026-05-14
35
 
36
  ### Fixed
 
1548
  - 5 dead imports removed (`os`, `Mapping`, `timedelta` from
1549
  `ctx_lifecycle`; `Path` from `intake_gate`, `intake_pipeline`).
1550
 
1551
+ [1.0.6]: https://github.com/stevesolun/ctx/releases/tag/v1.0.6
1552
  [1.0.5]: https://github.com/stevesolun/ctx/releases/tag/v1.0.5
1553
  [1.0.4]: https://github.com/stevesolun/ctx/releases/tag/v1.0.4
1554
  [1.0.3]: https://github.com/stevesolun/ctx/releases/tag/v1.0.3
README.md CHANGED
@@ -18,11 +18,11 @@ tags:
18
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
19
  [![Python 3.11+](https://img.shields.io/badge/Python-3.11+-green.svg)](https://python.org)
20
  [![PyPI](https://img.shields.io/pypi/v/claude-ctx.svg)](https://pypi.org/project/claude-ctx/)
21
- [![Tests](https://img.shields.io/badge/Tests-3797_collected-brightgreen.svg)](#)
22
- [![Graph](https://img.shields.io/badge/Graph-102%2C718_nodes_/_2.9M_edges-red.svg)](graph/)
23
  [![Docs](https://img.shields.io/badge/docs-MkDocs_Material-blue.svg)](https://stevesolun.github.io/ctx/)
24
 
25
- ctx watches what you are building, walks a **102,718-node** graph, and
26
  recommends a small, top-scored bundle of skills, agents, and MCP servers for
27
  the current task. If you use your own local/API model instead of Claude Code,
28
  ctx has a separate harness catalog flow: tell it the model and goal, review the
@@ -30,15 +30,15 @@ recommended harness, then install with dry-run/update/uninstall controls.
30
 
31
  Current shipped snapshot:
32
 
33
- - **91,450 skills**: 1,987 curated/imported skills plus **89,463 body-backed Skills.sh skills**.
34
- - **467 agents**, **10,787 MCP servers**, and **14 cataloged harnesses**.
35
  - **2.9M graph edges** across semantic similarity, tags, slug tokens, source overlap, direct links, quality, usage, type affinity, and graph structure.
36
  - **89,463 hydrated `SKILL.md` bodies** in the shipped LLM-wiki; long entries are converted through the micro-skill gate instead of loading raw long prompts.
37
  - Entity updates for skills, agents, MCPs, and harnesses print benefits/risks and skip replacement unless you explicitly approve the update.
38
 
39
  ## Why it exists
40
 
41
- - **Discovery** — with 91K+ skill nodes, 460+ agents, 10K+ MCP servers, and 14 cataloged harnesses, you can't possibly know which exist or which apply to your current work.
42
  - **Context budget** — loading everything wastes tokens and degrades quality. You need the right 10–15 per session.
43
  - **Skill rot** — skills you installed months ago and never used are cluttering context. Stale ones should be flagged automatically.
44
 
@@ -61,7 +61,7 @@ Graph-backed recommendations need the pre-built graph. By default, `ctx-init
61
  --graph` installs the fast runtime artifact: `graph/wiki-graph-runtime.tar.gz`
62
  in source checkouts, or the matching GitHub release asset from pip installs.
63
  It contains `graphify-out/*` plus the external Skills.sh catalog needed for
64
- recommendations and the 13 cataloged harness pages needed by
65
  `ctx-harness-install`:
66
 
67
  ```bash
@@ -78,7 +78,7 @@ ctx-init --graph --graph-install-mode full
78
  The full `wiki-graph.tar.gz` includes `external-catalogs/skills-sh/catalog.json`,
79
  89,463 body-backed Skills.sh skill pages under `entities/skills/skills-sh-*.md`,
80
  89,463 hydrated installable Skills.sh `SKILL.md` files under
81
- `converted/skills-sh-*/`, and 13 cataloged harness pages under
82
  `entities/harnesses/`.
83
 
84
  > **Windows:** PowerShell's built-in `tar.exe` does not support
 
18
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
19
  [![Python 3.11+](https://img.shields.io/badge/Python-3.11+-green.svg)](https://python.org)
20
  [![PyPI](https://img.shields.io/pypi/v/claude-ctx.svg)](https://pypi.org/project/claude-ctx/)
21
+ [![Tests](https://img.shields.io/badge/Tests-3818_collected-brightgreen.svg)](#)
22
+ [![Graph](https://img.shields.io/badge/Graph-102%2C717_nodes_/_2.9M_edges-red.svg)](graph/)
23
  [![Docs](https://img.shields.io/badge/docs-MkDocs_Material-blue.svg)](https://stevesolun.github.io/ctx/)
24
 
25
+ ctx watches what you are building, walks a **102,717-node** graph, and
26
  recommends a small, top-scored bundle of skills, agents, and MCP servers for
27
  the current task. If you use your own local/API model instead of Claude Code,
28
  ctx has a separate harness catalog flow: tell it the model and goal, review the
 
30
 
31
  Current shipped snapshot:
32
 
33
+ - **91,448 skills**: 1,985 curated/imported skills plus **89,463 body-backed Skills.sh skills**.
34
+ - **467 agents**, **10,787 MCP servers**, and **15 cataloged harnesses**.
35
  - **2.9M graph edges** across semantic similarity, tags, slug tokens, source overlap, direct links, quality, usage, type affinity, and graph structure.
36
  - **89,463 hydrated `SKILL.md` bodies** in the shipped LLM-wiki; long entries are converted through the micro-skill gate instead of loading raw long prompts.
37
  - Entity updates for skills, agents, MCPs, and harnesses print benefits/risks and skip replacement unless you explicitly approve the update.
38
 
39
  ## Why it exists
40
 
41
+ - **Discovery** — with 91K+ skill nodes, 460+ agents, 10K+ MCP servers, and 15 cataloged harnesses, you can't possibly know which exist or which apply to your current work.
42
  - **Context budget** — loading everything wastes tokens and degrades quality. You need the right 10–15 per session.
43
  - **Skill rot** — skills you installed months ago and never used are cluttering context. Stale ones should be flagged automatically.
44
 
 
61
  --graph` installs the fast runtime artifact: `graph/wiki-graph-runtime.tar.gz`
62
  in source checkouts, or the matching GitHub release asset from pip installs.
63
  It contains `graphify-out/*` plus the external Skills.sh catalog needed for
64
+ recommendations and the 15 cataloged harness pages needed by
65
  `ctx-harness-install`:
66
 
67
  ```bash
 
78
  The full `wiki-graph.tar.gz` includes `external-catalogs/skills-sh/catalog.json`,
79
  89,463 body-backed Skills.sh skill pages under `entities/skills/skills-sh-*.md`,
80
  89,463 hydrated installable Skills.sh `SKILL.md` files under
81
+ `converted/skills-sh-*/`, and 15 cataloged harness pages under
82
  `entities/harnesses/`.
83
 
84
  > **Windows:** PowerShell's built-in `tar.exe` does not support
docs/huggingface-publish.md CHANGED
@@ -36,7 +36,7 @@ current process, and clear it after the upload.
36
  ```powershell
37
  python -m pip install --upgrade huggingface_hub
38
  git lfs install
39
- git lfs pull --include="graph/wiki-graph.tar.gz,graph/wiki-graph-runtime.tar.gz,graph/skills-sh-catalog.json.gz"
40
 
41
  $secureToken = Read-Host "HF write token" -AsSecureString
42
  $tokenPtr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureToken)
 
36
  ```powershell
37
  python -m pip install --upgrade huggingface_hub
38
  git lfs install
39
+ git lfs pull --include="graph/wiki-graph.tar.gz,graph/wiki-graph-runtime.tar.gz"
40
 
41
  $secureToken = Read-Host "HF write token" -AsSecureString
42
  $tokenPtr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureToken)
docs/index.md CHANGED
@@ -5,8 +5,8 @@ hide:
5
 
6
  # ctx — Skill, Agent, MCP & Harness Catalog
7
 
8
- Watches what you develop, walks a knowledge graph of **91,450 skills, 467
9
- agents, 10,787 MCP servers, and 14 cataloged harnesses**, and recommends the
10
  right execution bundle on the fly. The live execution bundle is skills,
11
  agents, and MCP servers only; custom/API/local model users get a separate
12
  harness-catalog recommendation based on model choice and task goal. You decide
@@ -42,7 +42,7 @@ Claude Code skills, agents, MCP servers, and model harness profiles are
42
  powerful, but at scale they become unmanageable:
43
 
44
  - **Discovery problem** — with 91K+ skills, 460+ agents, 10,000+
45
- MCP servers, and 14 cataloged harnesses, how do you know which
46
  ones exist and which are relevant to your current project?
47
  - **Context budget** — loading every installable entity wastes tokens and
48
  degrades quality. You need exactly the right skills, agents, and MCP
@@ -76,12 +76,12 @@ graph-based discovery:
76
 
77
  - A Karpathy 3-layer wiki at `~/.claude/skill-wiki/` is the single source
78
  of truth.
79
- - **102,718 entity pages/nodes** for the shipped skill/agent/MCP/harness
80
  inventory, including 89,463 body-backed Skills.sh skill pages
81
- and 13 cataloged harness pages under `entities/harnesses/`.
82
  Each page tracks tags, status, provenance, and usage where it applies.
83
- - A **knowledge graph** (102,718 nodes, 2,911,220 edges) built from a
84
- 13,233-node curated core plus 89,463 body-backed Skills.sh `skill`
85
  nodes. The graph has 52 Louvain communities and blends semantic cosine,
86
  tag overlap, and slug-token overlap; 89,463 hydrated Skills.sh bodies are
87
  shipped as installable `SKILL.md` files. Entries over the configured line
@@ -117,9 +117,9 @@ ones are flagged. New ones self-ingest.
117
 
118
  ---
119
 
120
- 102,718 shipped graph nodes: 13,255 curated skill/agent/MCP/harness
121
  nodes plus 89,463 body-backed Skills.sh skill nodes. The graph has
122
- 2,911,220 weighted edges and 52 Louvain communities.
123
  Ships pre-built in `graph/wiki-graph.tar.gz` and powers the
124
  graph-aware recommendations + the pre-ship `ctx-dedup-check` gate.
125
 
@@ -188,14 +188,14 @@ ones are flagged. New ones self-ingest.
188
 
189
  ---
190
 
191
- **v1.0.5** — MIT, CI-matrixed (Ubuntu + Windows × Python 3.11/3.12),
192
- 3,797 tests collected. Ships console scripts including `ctx-init`,
193
  `ctx-monitor` (local dashboard with graph + wiki + load/unload for
194
  skills, agents, and MCP servers, plus Harness Setup for user-owned LLMs),
195
  `ctx-incremental-attach`, `ctx-incremental-shadow`, `ctx-dedup-check`
196
  (pre-ship near-duplicate gate), and
197
  `ctx-tag-backfill` (catalog hygiene), plus a fast runtime graph artifact
198
- and the full ~334 MiB wiki tarball with **102,718 nodes / 2,911,220
199
  edges / 52 Louvain communities**.
200
 
201
  [:octicons-arrow-right-24: CHANGELOG](https://github.com/stevesolun/ctx/blob/main/CHANGELOG.md) ·
 
5
 
6
  # ctx — Skill, Agent, MCP & Harness Catalog
7
 
8
+ Watches what you develop, walks a knowledge graph of **91,448 skills, 467
9
+ agents, 10,787 MCP servers, and 15 cataloged harnesses**, and recommends the
10
  right execution bundle on the fly. The live execution bundle is skills,
11
  agents, and MCP servers only; custom/API/local model users get a separate
12
  harness-catalog recommendation based on model choice and task goal. You decide
 
42
  powerful, but at scale they become unmanageable:
43
 
44
  - **Discovery problem** — with 91K+ skills, 460+ agents, 10,000+
45
+ MCP servers, and 15 cataloged harnesses, how do you know which
46
  ones exist and which are relevant to your current project?
47
  - **Context budget** — loading every installable entity wastes tokens and
48
  degrades quality. You need exactly the right skills, agents, and MCP
 
76
 
77
  - A Karpathy 3-layer wiki at `~/.claude/skill-wiki/` is the single source
78
  of truth.
79
+ - **102,717 entity pages/nodes** for the shipped skill/agent/MCP/harness
80
  inventory, including 89,463 body-backed Skills.sh skill pages
81
+ and 15 cataloged harness pages under `entities/harnesses/`.
82
  Each page tracks tags, status, provenance, and usage where it applies.
83
+ - A **knowledge graph** (102,717 nodes, 2,911,162 edges) built from a
84
+ 13,254-node curated core plus 89,463 body-backed Skills.sh `skill`
85
  nodes. The graph has 52 Louvain communities and blends semantic cosine,
86
  tag overlap, and slug-token overlap; 89,463 hydrated Skills.sh bodies are
87
  shipped as installable `SKILL.md` files. Entries over the configured line
 
117
 
118
  ---
119
 
120
+ 102,717 shipped graph nodes: 13,254 curated skill/agent/MCP/harness
121
  nodes plus 89,463 body-backed Skills.sh skill nodes. The graph has
122
+ 2,911,162 weighted edges and 52 Louvain communities.
123
  Ships pre-built in `graph/wiki-graph.tar.gz` and powers the
124
  graph-aware recommendations + the pre-ship `ctx-dedup-check` gate.
125
 
 
188
 
189
  ---
190
 
191
+ **v1.0.6** — MIT, CI-matrixed (Ubuntu 3.12 plus Windows/macOS 3.11/3.12),
192
+ 3,818 tests collected. Ships console scripts including `ctx-init`,
193
  `ctx-monitor` (local dashboard with graph + wiki + load/unload for
194
  skills, agents, and MCP servers, plus Harness Setup for user-owned LLMs),
195
  `ctx-incremental-attach`, `ctx-incremental-shadow`, `ctx-dedup-check`
196
  (pre-ship near-duplicate gate), and
197
  `ctx-tag-backfill` (catalog hygiene), plus a fast runtime graph artifact
198
+ and the full ~390 MiB wiki tarball with **102,717 nodes / 2,911,162
199
  edges / 52 Louvain communities**.
200
 
201
  [:octicons-arrow-right-24: CHANGELOG](https://github.com/stevesolun/ctx/blob/main/CHANGELOG.md) ·
docs/knowledge-graph.md CHANGED
@@ -13,8 +13,8 @@ agents, and MCP servers.
13
  ## What's in it
14
 
15
  Authoritative numbers from the shipped tarball. The curated-core snapshot
16
- is **13,255 nodes** (1,987 curated skills + 467 agents + 10,787 MCP servers
17
- + 14 harnesses). Harness pages under `entities/harnesses/` are ingested into
18
  local rebuilds and the separate harness-catalog recommendation path. The
19
  tarball also carries **89,463 body-backed Skills.sh `skill` nodes**,
20
  matching skill pages under `entities/skills/skills-sh-*.md`. **89,463**
@@ -27,18 +27,18 @@ are omitted from the shipped tarball.
27
 
28
  | | Count |
29
  |---|---:|
30
- | Total nodes | **102,718** |
31
- | Curated core nodes | **13,255** (1,987 skills + 467 agents + 10,787 MCP servers + 14 harnesses) |
32
  | Remote-cataloged Skills.sh skill nodes | **89,463** (`skill`, `status=remote-cataloged`, body-backed) |
33
- | Total edges | **2,911,220** |
34
- | Skills.sh incident edges | **2,605,992** |
35
- | Skills.sh semantic incident edges | **1,500,706** |
36
  | Communities | **52** (Louvain) |
37
- | Edge sources (overlap-deduped) | semantic 1,682,846 - tag 891,739 - token 433,074 |
38
- | Cross-type edges (skill <-> agent) | ~65K |
39
  | Cross-type edges (skill <-> MCP) | ~41K |
40
  | Cross-type edges (agent <-> MCP) | ~223 |
41
- | Harness edges | **3,289** |
42
  | Skills.sh catalog | **89,463** observed body-backed entries (`external-catalogs/skills-sh/catalog.json` + `entities/skills/skills-sh-*.md`) |
43
 
44
  ## Install
@@ -170,7 +170,7 @@ raw = json.loads(
170
  edges_key = "links" if "links" in raw else "edges"
171
  G = node_link_graph(raw, edges=edges_key)
172
 
173
- # 102,718 nodes, 2,911,220 edges
174
  print(G.number_of_nodes(), G.number_of_edges())
175
 
176
  # Find entities related to 'fastapi-pro' by edge weight
@@ -330,8 +330,10 @@ next run rebuilds instead of trusting mixed graph files.
330
  | 2026-05-04 body-backed Skills.sh prune | **2,900,834** | Removed 1,383 Skills.sh records that had no packaged `SKILL.md` body and no parseable Skills.sh prose body. Remaining Skills.sh catalog entries, graph nodes, entity pages, and converted `SKILL.md` bodies are all **89,463**. |
331
  | 2026-05-05 artifact hygiene refresh | **2,900,834** | Repacked `graph/wiki-graph.tar.gz` to remove transient `.lock` files from the shipped LLM-wiki. Topology unchanged. |
332
  | 2026-05-10 v1.0.0 release prep | **2,900,834** | Refreshed shipped HTML previews from the current export, validated their export IDs in CI, and removed stale PNG previews. Topology unchanged. |
333
- | 2026-05-13 external source overlay | **2,911,220** | Added AGENTS.md, lat.md, OptiLLM, Matt Pocock refresh deltas, and Julius caveman entities through the safe overlay path (+21 nodes, +10,310 edges) while preserving the saturated Skills.sh topology. Current tar members: **598,192**. |
334
  | 2026-05-12 book-to-skill + queue hygiene | **2,900,910** | Added `book-to-skill` as a curated skill entity (+1 node, +76 edges), restored the missing converted Skills.sh body for `skills-sh-yaklang-hack-skills-csv-formula-injection`, and repacked `graph/wiki-graph.tar.gz` to omit `.ctx/` queue state. Tar members: **598,154**. |
 
 
 
335
 
336
  The full audit history lives in `CHANGELOG.md`. The current build is
337
  fully reproducible from the wiki content.
 
13
  ## What's in it
14
 
15
  Authoritative numbers from the shipped tarball. The curated-core snapshot
16
+ is **13,254 nodes** (1,985 curated skills + 467 agents + 10,787 MCP servers
17
+ + 15 harnesses). Harness pages under `entities/harnesses/` are ingested into
18
  local rebuilds and the separate harness-catalog recommendation path. The
19
  tarball also carries **89,463 body-backed Skills.sh `skill` nodes**,
20
  matching skill pages under `entities/skills/skills-sh-*.md`. **89,463**
 
27
 
28
  | | Count |
29
  |---|---:|
30
+ | Total nodes | **102,717** |
31
+ | Curated core nodes | **13,254** (1,985 skills + 467 agents + 10,787 MCP servers + 15 harnesses) |
32
  | Remote-cataloged Skills.sh skill nodes | **89,463** (`skill`, `status=remote-cataloged`, body-backed) |
33
+ | Total edges | **2,911,162** |
34
+ | Skills.sh incident edges | **2,605,979** |
35
+ | Skills.sh semantic incident edges | **1,500,693** |
36
  | Communities | **52** (Louvain) |
37
+ | Edge sources (overlap-deduped) | semantic 1,683,182 - tag 894,935 - token 433,252 |
38
+ | Cross-type edges (skill <-> agent) | ~67K |
39
  | Cross-type edges (skill <-> MCP) | ~41K |
40
  | Cross-type edges (agent <-> MCP) | ~223 |
41
+ | Harness edges | **3,632** |
42
  | Skills.sh catalog | **89,463** observed body-backed entries (`external-catalogs/skills-sh/catalog.json` + `entities/skills/skills-sh-*.md`) |
43
 
44
  ## Install
 
170
  edges_key = "links" if "links" in raw else "edges"
171
  G = node_link_graph(raw, edges=edges_key)
172
 
173
+ # 102,717 nodes, 2,911,162 edges
174
  print(G.number_of_nodes(), G.number_of_edges())
175
 
176
  # Find entities related to 'fastapi-pro' by edge weight
 
330
  | 2026-05-04 body-backed Skills.sh prune | **2,900,834** | Removed 1,383 Skills.sh records that had no packaged `SKILL.md` body and no parseable Skills.sh prose body. Remaining Skills.sh catalog entries, graph nodes, entity pages, and converted `SKILL.md` bodies are all **89,463**. |
331
  | 2026-05-05 artifact hygiene refresh | **2,900,834** | Repacked `graph/wiki-graph.tar.gz` to remove transient `.lock` files from the shipped LLM-wiki. Topology unchanged. |
332
  | 2026-05-10 v1.0.0 release prep | **2,900,834** | Refreshed shipped HTML previews from the current export, validated their export IDs in CI, and removed stale PNG previews. Topology unchanged. |
 
333
  | 2026-05-12 book-to-skill + queue hygiene | **2,900,910** | Added `book-to-skill` as a curated skill entity (+1 node, +76 edges), restored the missing converted Skills.sh body for `skills-sh-yaklang-hack-skills-csv-formula-injection`, and repacked `graph/wiki-graph.tar.gz` to omit `.ctx/` queue state. Tar members: **598,154**. |
334
+ | 2026-05-13 external source overlay | **2,911,220** | Added AGENTS.md, lat.md, OptiLLM, Matt Pocock refresh deltas, and Julius caveman entities through the safe overlay path (+21 nodes, +10,310 edges) while preserving the saturated Skills.sh topology. Tar members at that pass: **598,192**. |
335
+ | 2026-05-14 Matt Pocock upstream refresh | **2,911,126** | Pinned `mattpocock/skills` to `e74f0061bb67222181640effa98c675bdb2fdaa7`, removed three stale legacy alias skill pages/nodes (`mattpocock-domain-model`, `mattpocock-github-triage`, `mattpocock-triage-issue`), refreshed `mattpocock-grill-with-docs`, and pruned 94 incident edges plus stale wiki references. Current tar members: **598,189**. |
336
+ | 2026-05-14 Mirage + CodeGraph first-class wiki pass | **2,911,162** | Added Mirage as a shipped harness wiki/runtime page, added the CodeGraph MCP markdown page and `codegraph-agentic-codebase-analysis` skill page/body to the full LLM-wiki, added the compact dashboard neighborhood index, regenerated graph preview HTML from the current export, and refreshed exact validation counts. Current tar members: **598,193**. |
337
 
338
  The full audit history lives in `CHANGELOG.md`. The current build is
339
  fully reproducible from the wiki content.
graph/README.md CHANGED
@@ -4,13 +4,13 @@ This directory ships the pre-built ctx LLM-wiki and knowledge graph.
4
 
5
  Current snapshot:
6
 
7
- - **102,718 graph nodes**
8
- - **2,911,220 graph edges**
9
  - **52 Louvain communities**
10
- - **91,450 skill entity pages**: 1,987 curated/imported skills plus 89,463 body-backed Skills.sh skills
11
  - **467 agent pages**
12
  - **10,787 MCP server pages**
13
- - **14 harness pages**
14
  - **89,463 hydrated Skills.sh `SKILL.md` bodies**
15
  - **28,612 long Skills.sh bodies converted through the micro-skill gate**
16
 
@@ -23,10 +23,11 @@ The runtime recommendation paths use this graph in two ways:
23
 
24
  | File | Contents |
25
  |---|---|
26
- | `wiki-graph-runtime.tar.gz` | Fast install artifact used by default `ctx-init --graph`: `graphify-out/*`, the external Skills.sh catalog, 14 harness pages, wiki index files, and Obsidian metadata needed for recommendations and harness dry-runs without expanding every entity page |
27
  | `wiki-graph.tar.gz` | Full LLM-wiki: entity pages, converted skill bodies, mirrored agent bodies, concept pages, `graphify-out/graph.json`, `graph-delta.json`, export manifest, communities, external catalogs, and Obsidian metadata |
28
  | `skills-sh-catalog.json.gz` | Compressed Skills.sh catalog for the 89,463 body-backed entries shipped in the wiki |
29
  | `communities.json` | Current Louvain community export |
 
30
  | `viz-overview.html` | Plotly overview of the graph |
31
  | `viz-python.html` | Python-focused graph view |
32
  | `viz-security.html` | Security-focused graph view |
@@ -109,17 +110,17 @@ For release-count validation, pin the exact snapshot numbers:
109
 
110
  ```bash
111
  python src/validate_graph_artifacts.py --deep \
112
- --expected-nodes 102718 \
113
- --expected-edges 2911220 \
114
- --expected-semantic-edges 1683265 \
115
- --expected-harness-nodes 14 \
116
  --expected-skills-sh-nodes 89463 \
117
  --expected-skills-sh-catalog-entries 89463 \
118
  --expected-skills-sh-converted 89463 \
119
- --expected-skill-pages 91450 \
120
  --expected-agent-pages 467 \
121
  --expected-mcp-pages 10787 \
122
- --expected-harness-pages 14
123
  ```
124
 
125
  Manual sanity checks:
 
4
 
5
  Current snapshot:
6
 
7
+ - **102,717 graph nodes**
8
+ - **2,911,162 graph edges**
9
  - **52 Louvain communities**
10
+ - **91,448 skill entity pages**: 1,985 curated/imported skills plus 89,463 body-backed Skills.sh skills
11
  - **467 agent pages**
12
  - **10,787 MCP server pages**
13
+ - **15 harness pages**
14
  - **89,463 hydrated Skills.sh `SKILL.md` bodies**
15
  - **28,612 long Skills.sh bodies converted through the micro-skill gate**
16
 
 
23
 
24
  | File | Contents |
25
  |---|---|
26
+ | `wiki-graph-runtime.tar.gz` | Fast install artifact used by default `ctx-init --graph`: `graphify-out/*`, the external Skills.sh catalog, 15 harness pages, wiki index files, and Obsidian metadata needed for recommendations and harness dry-runs without expanding every entity page |
27
  | `wiki-graph.tar.gz` | Full LLM-wiki: entity pages, converted skill bodies, mirrored agent bodies, concept pages, `graphify-out/graph.json`, `graph-delta.json`, export manifest, communities, external catalogs, and Obsidian metadata |
28
  | `skills-sh-catalog.json.gz` | Compressed Skills.sh catalog for the 89,463 body-backed entries shipped in the wiki |
29
  | `communities.json` | Current Louvain community export |
30
+ | `graphify-out/dashboard-neighborhoods.sqlite3` inside both tarballs | Compact top-neighbor index used by `ctx-monitor` so `/api/graph/<slug>.json` does not cold-parse the 604 MB NetworkX graph |
31
  | `viz-overview.html` | Plotly overview of the graph |
32
  | `viz-python.html` | Python-focused graph view |
33
  | `viz-security.html` | Security-focused graph view |
 
110
 
111
  ```bash
112
  python src/validate_graph_artifacts.py --deep \
113
+ --expected-nodes 102717 \
114
+ --expected-edges 2911162 \
115
+ --expected-semantic-edges 1683182 \
116
+ --expected-harness-nodes 15 \
117
  --expected-skills-sh-nodes 89463 \
118
  --expected-skills-sh-catalog-entries 89463 \
119
  --expected-skills-sh-converted 89463 \
120
+ --expected-skill-pages 91448 \
121
  --expected-agent-pages 467 \
122
  --expected-mcp-pages 10787 \
123
+ --expected-harness-pages 15
124
  ```
125
 
126
  Manual sanity checks:
graph/communities.json CHANGED
@@ -15960,7 +15960,8 @@
15960
  "skill:verification-before-completion",
15961
  "skill:verification-loop",
15962
  "skill:vibe-code-auditor",
15963
- "skill:vibers-code-review"
 
15964
  ]
15965
  },
15966
  "12": {
@@ -30631,7 +30632,8 @@
30631
  "harness:optillm",
30632
  "skill:mattpocock-review",
30633
  "skill:mattpocock-setup-matt-pocock-skills",
30634
- "skill:mattpocock-triage"
 
30635
  ]
30636
  },
30637
  "16": {
@@ -50473,10 +50475,8 @@
50473
  "skill:laravel-security",
50474
  "skill:mattpocock-caveman",
50475
  "skill:mattpocock-design-an-interface",
50476
- "skill:mattpocock-domain-model",
50477
  "skill:mattpocock-edit-article",
50478
  "skill:mattpocock-git-guardrails-claude-code",
50479
- "skill:mattpocock-github-triage",
50480
  "skill:mattpocock-grill-me",
50481
  "skill:mattpocock-improve-codebase-architecture",
50482
  "skill:mattpocock-migrate-to-shoehorn",
@@ -50488,7 +50488,6 @@
50488
  "skill:mattpocock-tdd",
50489
  "skill:mattpocock-to-issues",
50490
  "skill:mattpocock-to-prd",
50491
- "skill:mattpocock-triage-issue",
50492
  "skill:mattpocock-ubiquitous-language",
50493
  "skill:mattpocock-write-a-skill",
50494
  "skill:mattpocock-zoom-out",
@@ -102980,6 +102979,6 @@
102980
  }
102981
  },
102982
  "total_communities": 52,
102983
- "generated": "20260513T150939Z",
102984
- "export_id": "ctx-graph-overlay-20260513T150939Z-102718-2911220"
102985
  }
 
15960
  "skill:verification-before-completion",
15961
  "skill:verification-loop",
15962
  "skill:vibe-code-auditor",
15963
+ "skill:vibers-code-review",
15964
+ "skill:codegraph-agentic-codebase-analysis"
15965
  ]
15966
  },
15967
  "12": {
 
30632
  "harness:optillm",
30633
  "skill:mattpocock-review",
30634
  "skill:mattpocock-setup-matt-pocock-skills",
30635
+ "skill:mattpocock-triage",
30636
+ "harness:mirage"
30637
  ]
30638
  },
30639
  "16": {
 
50475
  "skill:laravel-security",
50476
  "skill:mattpocock-caveman",
50477
  "skill:mattpocock-design-an-interface",
 
50478
  "skill:mattpocock-edit-article",
50479
  "skill:mattpocock-git-guardrails-claude-code",
 
50480
  "skill:mattpocock-grill-me",
50481
  "skill:mattpocock-improve-codebase-architecture",
50482
  "skill:mattpocock-migrate-to-shoehorn",
 
50488
  "skill:mattpocock-tdd",
50489
  "skill:mattpocock-to-issues",
50490
  "skill:mattpocock-to-prd",
 
50491
  "skill:mattpocock-ubiquitous-language",
50492
  "skill:mattpocock-write-a-skill",
50493
  "skill:mattpocock-zoom-out",
 
102979
  }
102980
  },
102981
  "total_communities": 52,
102982
+ "generated": "20260514T163846Z",
102983
+ "export_id": "ctx-graph-overlay-20260514T163846Z-102717-2911162"
102984
  }
graph/sample-top60.html CHANGED
The diff for this file is too large to render. See raw diff
 
graph/skills-sh-catalog.json.gz CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:e85a1940234667ae4f2347a3ae61fd47f22ad843e36bdffa3c47cc6def8812d5
3
- size 11656331
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8a664233f08b724d20a459a5fc7da722cab98741abaea1c36bfc2488af70b62a
3
+ size 11656727
graph/viz-ai-agents.html CHANGED
The diff for this file is too large to render. See raw diff
 
graph/viz-overview.html CHANGED
The diff for this file is too large to render. See raw diff
 
graph/viz-python.html CHANGED
The diff for this file is too large to render. See raw diff
 
graph/viz-security.html CHANGED
The diff for this file is too large to render. See raw diff
 
graph/wiki-graph-runtime.tar.gz CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:84634152dea0f7c8881bc717eaefcce5bfe1b97c4cee90b3202a2ee48b95dd8c
3
- size 74522806
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:27cd757cabaf7209d864b460d14b0755e258cc9bcf93581cacf987e1a7ef1e21
3
+ size 159737046
graph/wiki-graph.tar.gz CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:a3968445d6ef9a27d5a684d30019b5730e9c40c62ba7fcd1b66e8567baa756b6
3
- size 350655613
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:57974831189e6fa6c828f3dc2b6b54ebff50879dcc301ed749d20fa9cc495414
3
+ size 408620019
imported-skills/mattpocock/ATTRIBUTION.md CHANGED
@@ -1,116 +1,110 @@
1
- # Mattpocock Skills Import — Attribution & Usage
2
-
3
- This directory mirrors Matt Pocock's personal `.claude/` skill set — opinionated
4
- agent skills covering TDD, domain modelling, codebase architecture review,
5
- github triage, and meta-workflows for working with Claude Code.
6
-
7
- ## Provenance
8
-
9
- | Field | Value |
10
- |---|---|
11
- | Upstream repo | https://github.com/mattpocock/skills |
12
- | Revision | `f304057d61d3df3c9fd992ac2b6e3833cb9325fb` |
13
- | Revision date | 2026-05-12 |
14
- | Upstream license | MIT (see `LICENSE`) |
15
- | Imported on | 2026-04-27 |
16
- | Skill count | 31 total: 28 current upstream skills plus 3 legacy aliases preserved for compatibility |
17
-
18
- ## What's in here
19
-
20
- Each top-level directory is one skill, with `SKILL.md` as the entry point and
21
- optional supporting `.md` / `.sh` files alongside it (e.g. `tdd/deep-modules.md`,
22
- `domain-model/ADR-FORMAT.md`, `git-guardrails-claude-code/scripts/block-dangerous-git.sh`).
23
-
24
- `domain-model`, `github-triage`, and `triage-issue` are retained as legacy
25
- ctx aliases. The current upstream equivalents are `grill-with-docs` and
26
- `triage`.
27
-
28
- | Skill | Purpose |
29
- |---|---|
30
- | `tdd` | Red-green-refactor TDD discipline (with deep-modules / mocking / refactoring sidecars) |
31
- | `qa` | Interactive QA conversation that files GitHub issues using project domain language |
32
- | `caveman` | Ultra-compressed communication mode (~75% token reduction) |
33
- | `domain-model` | Stress-test plans against existing domain model + ADRs (with `ADR-FORMAT.md` + `CONTEXT-FORMAT.md`) |
34
- | `ubiquitous-language` | DDD-style shared vocabulary discipline |
35
- | `design-an-interface` | Generate multiple radically different API designs via parallel sub-agents |
36
- | `improve-codebase-architecture` | Architecture review playbook (with `DEEPENING.md`, `INTERFACE-DESIGN.md`, `LANGUAGE.md` sidecars) |
37
- | `github-triage` | Triage GitHub issues with agent-brief + out-of-scope guardrails |
38
- | `triage-issue` | Single-issue triage workflow |
39
- | `diagnose` | Disciplined reproduce/minimize/hypothesize/instrument/fix loop |
40
- | `grill-with-docs` | Plan interrogation backed by `CONTEXT.md` and ADRs |
41
- | `handoff` | Compact a session into a continuation handoff |
42
- | `prototype` | Throwaway logic/UI prototypes before committing to a design |
43
- | `review` | Standards/spec two-axis review against a fixed point |
44
- | `setup-matt-pocock-skills` | Per-repo setup for issue tracker, triage labels, and domain docs |
45
- | `to-issues` | Convert plans/notes into well-formed issues |
46
- | `to-prd` | Convert sketches into a product requirements document |
47
- | `request-refactor-plan` | Plan a refactor before touching code |
48
- | `migrate-to-shoehorn` | Migration playbook to the `shoehorn` library |
49
- | `setup-pre-commit` | Pre-commit hook bootstrap |
50
- | `scaffold-exercises` | Scaffold programming exercises |
51
- | `git-guardrails-claude-code` | Block dangerous git ops in Claude Code (with hook script) |
52
- | `obsidian-vault` | Obsidian vault management workflow |
53
- | `edit-article` | Editing pass for article drafts |
54
- | `grill-me` | Adversarial questioning to stress-test a plan |
55
- | `write-a-skill` | Meta: how to write a skill |
56
- | `writing-beats` | Build an article beat by beat from raw material |
57
- | `writing-fragments` | Capture raw article fragments through a grilling session |
58
- | `writing-shape` | Shape a pile of notes into a publishable article |
59
- | `zoom-out` | Force a higher-altitude review of current work |
60
-
61
- ## License compliance
62
-
63
- Per the MIT license:
64
- - Upstream `LICENSE` text is preserved alongside the imported files.
65
- - Files are imported verbatim. The deployed copies (under `~/.claude/skills/`) prepend
66
- an HTML-comment attribution header before the original `---` frontmatter so
67
- provenance is visible inline; the original content below is unmodified.
68
-
69
- ## How to integrate
70
-
71
- Skills are staged in this directory and **not** deployed to `~/.claude/skills/`
72
- until you run the importer:
73
-
74
- ```bash
75
- python imported-skills/mattpocock/build_manifest.py # rebuild MANIFEST.json
76
- python src/import_mattpocock_skills.py --dry-run # preview
77
- python src/import_mattpocock_skills.py --install # deploy as mattpocock-<slug>
78
- ```
79
-
80
- Each skill lands as `~/.claude/skills/mattpocock-<slug>/` with all its support
81
- files copied alongside `SKILL.md`. Directory namespacing prevents collisions
82
- with same-named skills already in the wiki (e.g. existing `tdd-orchestrator`
83
- agent + `python-testing` skill coexist with `mattpocock-tdd`).
84
-
85
- After install, refresh the wiki + graph:
86
-
87
- ```bash
88
- python src/catalog_builder.py
89
- python src/wiki_batch_entities.py --all
90
- python -m ctx.core.wiki.wiki_graphify
91
- ```
92
-
93
- ## Why this set
94
-
95
- mattpocock's skills are short, opinionated, and prose-style — closer to
96
- checklists or playbooks than reference manuals. They complement the larger
97
- catalogue (which leans dense + comprehensive) by providing crisp,
98
- single-purpose workflows for everyday engineering tasks.
99
-
100
- The `tdd`, `domain-model`, `ubiquitous-language`, and
101
- `improve-codebase-architecture` set in particular form a cohesive DDD-leaning
102
- toolkit. The `caveman`, `grill-me`, `zoom-out` set are useful behavioural
103
- modes for steering a Claude Code session.
104
-
105
- ## Limitations
106
-
107
- - **Frontmatter format** uses YAML frontmatter with `name:` + `description:`;
108
- some entries use `disable-model-invocation: true` (Claude Code reads this).
109
- The importer preserves these fields as-is.
110
- - **Tool assumptions** `git-guardrails-claude-code` ships a `block-dangerous-git.sh`
111
- hook that expects POSIX `bash` on PATH; on Windows it requires Git-Bash or
112
- WSL. The hook is copied but not wired into your Claude Code settings — wire
113
- manually if you want it active.
114
- - **Opinionated** — these reflect one engineer's workflow. Treat them as
115
- starting points; nothing here is universally correct (e.g. `grill-me`'s
116
- adversarial style isn't right for every team).
 
1
+ # Mattpocock Skills Import — Attribution & Usage
2
+
3
+ This directory mirrors Matt Pocock's personal `.claude/` skill set — opinionated
4
+ agent skills covering TDD, domain modelling, codebase architecture review,
5
+ github triage, and meta-workflows for working with Claude Code.
6
+
7
+ ## Provenance
8
+
9
+ | Field | Value |
10
+ |---|---|
11
+ | Upstream repo | https://github.com/mattpocock/skills |
12
+ | Revision | `e74f0061bb67222181640effa98c675bdb2fdaa7` |
13
+ | Revision date | 2026-05-14 |
14
+ | Upstream license | MIT (see `LICENSE`) |
15
+ | Imported on | 2026-04-27 |
16
+ | Skill count | 28 current upstream skills |
17
+
18
+ ## What's in here
19
+
20
+ Each top-level directory is one skill, with `SKILL.md` as the entry point and
21
+ optional supporting `.md` / `.sh` files alongside it (e.g. `tdd/deep-modules.md`,
22
+ `grill-with-docs/ADR-FORMAT.md`, `git-guardrails-claude-code/scripts/block-dangerous-git.sh`).
23
+
24
+ | Skill | Purpose |
25
+ |---|---|
26
+ | `tdd` | Red-green-refactor TDD discipline (with deep-modules / mocking / refactoring sidecars) |
27
+ | `qa` | Interactive QA conversation that files GitHub issues using project domain language |
28
+ | `caveman` | Ultra-compressed communication mode (~75% token reduction) |
29
+ | `ubiquitous-language` | DDD-style shared vocabulary discipline |
30
+ | `design-an-interface` | Generate multiple radically different API designs via parallel sub-agents |
31
+ | `improve-codebase-architecture` | Architecture review playbook (with `DEEPENING.md`, `INTERFACE-DESIGN.md`, `LANGUAGE.md` sidecars) |
32
+ | `triage` | Triage issues with agent-brief + out-of-scope guardrails |
33
+ | `diagnose` | Disciplined reproduce/minimize/hypothesize/instrument/fix loop |
34
+ | `grill-with-docs` | Plan interrogation backed by `CONTEXT.md` and ADRs |
35
+ | `handoff` | Compact a session into a continuation handoff |
36
+ | `prototype` | Throwaway logic/UI prototypes before committing to a design |
37
+ | `review` | Standards/spec two-axis review against a fixed point |
38
+ | `setup-matt-pocock-skills` | Per-repo setup for issue tracker, triage labels, and domain docs |
39
+ | `to-issues` | Convert plans/notes into well-formed issues |
40
+ | `to-prd` | Convert sketches into a product requirements document |
41
+ | `request-refactor-plan` | Plan a refactor before touching code |
42
+ | `migrate-to-shoehorn` | Migration playbook to the `shoehorn` library |
43
+ | `setup-pre-commit` | Pre-commit hook bootstrap |
44
+ | `scaffold-exercises` | Scaffold programming exercises |
45
+ | `git-guardrails-claude-code` | Block dangerous git ops in Claude Code (with hook script) |
46
+ | `obsidian-vault` | Obsidian vault management workflow |
47
+ | `edit-article` | Editing pass for article drafts |
48
+ | `grill-me` | Adversarial questioning to stress-test a plan |
49
+ | `write-a-skill` | Meta: how to write a skill |
50
+ | `writing-beats` | Build an article beat by beat from raw material |
51
+ | `writing-fragments` | Capture raw article fragments through a grilling session |
52
+ | `writing-shape` | Shape a pile of notes into a publishable article |
53
+ | `zoom-out` | Force a higher-altitude review of current work |
54
+
55
+ ## License compliance
56
+
57
+ Per the MIT license:
58
+ - Upstream `LICENSE` text is preserved alongside the imported files.
59
+ - Files are imported verbatim. The deployed copies (under `~/.claude/skills/`) prepend
60
+ an HTML-comment attribution header before the original `---` frontmatter so
61
+ provenance is visible inline; the original content below is unmodified.
62
+
63
+ ## How to integrate
64
+
65
+ Skills are staged in this directory and **not** deployed to `~/.claude/skills/`
66
+ until you run the importer:
67
+
68
+ ```bash
69
+ python imported-skills/mattpocock/build_manifest.py # rebuild MANIFEST.json
70
+ python src/import_mattpocock_skills.py --dry-run # preview
71
+ python src/import_mattpocock_skills.py --install # deploy as mattpocock-<slug>
72
+ ```
73
+
74
+ Each skill lands as `~/.claude/skills/mattpocock-<slug>/` with all its support
75
+ files copied alongside `SKILL.md`. Directory namespacing prevents collisions
76
+ with same-named skills already in the wiki (e.g. existing `tdd-orchestrator`
77
+ agent + `python-testing` skill coexist with `mattpocock-tdd`).
78
+
79
+ After install, refresh the wiki + graph:
80
+
81
+ ```bash
82
+ python src/catalog_builder.py
83
+ python src/wiki_batch_entities.py --all
84
+ python -m ctx.core.wiki.wiki_graphify
85
+ ```
86
+
87
+ ## Why this set
88
+
89
+ mattpocock's skills are short, opinionated, and prose-style — closer to
90
+ checklists or playbooks than reference manuals. They complement the larger
91
+ catalogue (which leans dense + comprehensive) by providing crisp,
92
+ single-purpose workflows for everyday engineering tasks.
93
+
94
+ The `tdd`, `grill-with-docs`, `ubiquitous-language`, and
95
+ `improve-codebase-architecture` set in particular form a cohesive DDD-leaning
96
+ toolkit. The `caveman`, `grill-me`, `zoom-out` set are useful behavioural
97
+ modes for steering a Claude Code session.
98
+
99
+ ## Limitations
100
+
101
+ - **Frontmatter format** uses YAML frontmatter with `name:` + `description:`;
102
+ some entries use `disable-model-invocation: true` (Claude Code reads this).
103
+ The importer preserves these fields as-is.
104
+ - **Tool assumptions** — `git-guardrails-claude-code` ships a `block-dangerous-git.sh`
105
+ hook that expects POSIX `bash` on PATH; on Windows it requires Git-Bash or
106
+ WSL. The hook is copied but not wired into your Claude Code settings — wire
107
+ manually if you want it active.
108
+ - **Opinionated** these reflect one engineer's workflow. Treat them as
109
+ starting points; nothing here is universally correct (e.g. `grill-me`'s
110
+ adversarial style isn't right for every team).
 
 
 
 
 
 
imported-skills/mattpocock/MANIFEST.json CHANGED
@@ -1,9 +1,9 @@
1
  {
2
  "upstream": "https://github.com/mattpocock/skills",
3
- "upstream_revision": "f304057d61d3df3c9fd992ac2b6e3833cb9325fb",
4
  "license": "MIT",
5
  "namespace": "mattpocock",
6
- "total": 31,
7
  "entries": [
8
  {
9
  "name": "caveman",
@@ -31,17 +31,6 @@
31
  ],
32
  "lines": 117
33
  },
34
- {
35
- "name": "domain-model",
36
- "description": "Grilling session that challenges your plan against the existing domain model, sharpens terminology, and updates documentation (CONTEXT.md, ADRs) inline as decisions crystallise. Use when user wants to stress-test a plan against their project's language and documented decisions.",
37
- "slug": "domain-model",
38
- "source_path": "domain-model/SKILL.md",
39
- "support_files": [
40
- "ADR-FORMAT.md",
41
- "CONTEXT-FORMAT.md"
42
- ],
43
- "lines": 81
44
- },
45
  {
46
  "name": "edit-article",
47
  "description": "Edit and improve articles by restructuring sections, improving clarity, and tightening prose. Use when user wants to edit, revise, or improve an article draft.",
@@ -60,17 +49,6 @@
60
  ],
61
  "lines": 95
62
  },
63
- {
64
- "name": "github-triage",
65
- "description": "Triage GitHub issues through a label-based state machine. Use when user wants to create an issue, triage issues, review incoming bugs or feature requests, prepare issues for an AFK agent, or manage issue workflow.",
66
- "slug": "github-triage",
67
- "source_path": "github-triage/SKILL.md",
68
- "support_files": [
69
- "AGENT-BRIEF.md",
70
- "OUT-OF-SCOPE.md"
71
- ],
72
- "lines": 168
73
- },
74
  {
75
  "name": "grill-me",
76
  "description": "Interview the user relentlessly about a plan or design until reaching shared understanding, resolving each branch of the decision tree. Use when user wants to stress-test a plan, get grilled on their design, or mentions \"grill me\".",
@@ -232,14 +210,6 @@
232
  ],
233
  "lines": 103
234
  },
235
- {
236
- "name": "triage-issue",
237
- "description": "Triage a bug or issue by exploring the codebase to find root cause, then create a GitHub issue with a TDD-based fix plan. Use when user reports a bug, wants to file an issue, mentions \"triage\", or wants to investigate and plan a fix for a problem.",
238
- "slug": "triage-issue",
239
- "source_path": "triage-issue/SKILL.md",
240
- "support_files": [],
241
- "lines": 102
242
- },
243
  {
244
  "name": "ubiquitous-language",
245
  "description": "Extract a DDD-style ubiquitous language glossary from the current conversation, flagging ambiguities and proposing canonical terms. Saves to UBIQUITOUS_LANGUAGE.md. Use when user wants to define domain terms, build a glossary, harden terminology, create a ubiquitous language, or mentions \"domain model\" or \"DDD\".",
 
1
  {
2
  "upstream": "https://github.com/mattpocock/skills",
3
+ "upstream_revision": "e74f0061bb67222181640effa98c675bdb2fdaa7",
4
  "license": "MIT",
5
  "namespace": "mattpocock",
6
+ "total": 28,
7
  "entries": [
8
  {
9
  "name": "caveman",
 
31
  ],
32
  "lines": 117
33
  },
 
 
 
 
 
 
 
 
 
 
 
34
  {
35
  "name": "edit-article",
36
  "description": "Edit and improve articles by restructuring sections, improving clarity, and tightening prose. Use when user wants to edit, revise, or improve an article draft.",
 
49
  ],
50
  "lines": 95
51
  },
 
 
 
 
 
 
 
 
 
 
 
52
  {
53
  "name": "grill-me",
54
  "description": "Interview the user relentlessly about a plan or design until reaching shared understanding, resolving each branch of the decision tree. Use when user wants to stress-test a plan, get grilled on their design, or mentions \"grill me\".",
 
210
  ],
211
  "lines": 103
212
  },
 
 
 
 
 
 
 
 
213
  {
214
  "name": "ubiquitous-language",
215
  "description": "Extract a DDD-style ubiquitous language glossary from the current conversation, flagging ambiguities and proposing canonical terms. Saves to UBIQUITOUS_LANGUAGE.md. Use when user wants to define domain terms, build a glossary, harden terminology, create a ubiquitous language, or mentions \"domain model\" or \"DDD\".",
imported-skills/mattpocock/README.md CHANGED
@@ -1,55 +1,49 @@
1
- # Matt Pocock Skills
2
-
3
- Local mirror of [mattpocock/skills](https://github.com/mattpocock/skills), pinned
4
- at `f304057d61d3df3c9fd992ac2b6e3833cb9325fb`.
5
-
6
- This directory contains 31 ctx-staged entries: 28 current upstream skills plus
7
- 3 legacy aliases (`domain-model`, `github-triage`, `triage-issue`) kept so older
8
- ctx graph/wiki references do not break.
9
-
10
- Run `python imported-skills/mattpocock/build_manifest.py` after edits, then
11
- `python src/import_mattpocock_skills.py --dry-run` before installing.
12
-
13
- ## Current Upstream Skills
14
-
15
- Engineering:
16
-
17
- - `diagnose`
18
- - `grill-with-docs`
19
- - `improve-codebase-architecture`
20
- - `prototype`
21
- - `setup-matt-pocock-skills`
22
- - `tdd`
23
- - `to-issues`
24
- - `to-prd`
25
- - `triage`
26
- - `zoom-out`
27
-
28
- Productivity:
29
-
30
- - `caveman`
31
- - `grill-me`
32
- - `handoff`
33
- - `write-a-skill`
34
-
35
- Writing/personal/misc:
36
-
37
- - `design-an-interface`
38
- - `edit-article`
39
- - `git-guardrails-claude-code`
40
- - `migrate-to-shoehorn`
41
- - `obsidian-vault`
42
- - `qa`
43
- - `request-refactor-plan`
44
- - `scaffold-exercises`
45
- - `setup-pre-commit`
46
- - `ubiquitous-language`
47
- - `writing-beats`
48
- - `writing-fragments`
49
- - `writing-shape`
50
-
51
- ## Legacy Aliases
52
-
53
- - `domain-model` -> superseded upstream by `grill-with-docs`
54
- - `github-triage` -> superseded upstream by `triage`
55
- - `triage-issue` -> superseded upstream by `triage`
 
1
+ # Matt Pocock Skills
2
+
3
+ Local mirror of [mattpocock/skills](https://github.com/mattpocock/skills), pinned
4
+ at `e74f0061bb67222181640effa98c675bdb2fdaa7`.
5
+
6
+ This directory contains 28 ctx-staged entries from the current upstream skill
7
+ directories. Removed upstream aliases are not retained here; ctx graph/wiki
8
+ artifacts should prune stale alias nodes during the next artifact refresh.
9
+
10
+ Run `python imported-skills/mattpocock/build_manifest.py` after edits, then
11
+ `python src/import_mattpocock_skills.py --dry-run` before installing.
12
+
13
+ ## Current Upstream Skills
14
+
15
+ Engineering:
16
+
17
+ - `diagnose`
18
+ - `grill-with-docs`
19
+ - `improve-codebase-architecture`
20
+ - `prototype`
21
+ - `setup-matt-pocock-skills`
22
+ - `tdd`
23
+ - `to-issues`
24
+ - `to-prd`
25
+ - `triage`
26
+ - `zoom-out`
27
+
28
+ Productivity:
29
+
30
+ - `caveman`
31
+ - `grill-me`
32
+ - `handoff`
33
+ - `write-a-skill`
34
+
35
+ Writing/personal/misc:
36
+
37
+ - `design-an-interface`
38
+ - `edit-article`
39
+ - `git-guardrails-claude-code`
40
+ - `migrate-to-shoehorn`
41
+ - `obsidian-vault`
42
+ - `qa`
43
+ - `request-refactor-plan`
44
+ - `scaffold-exercises`
45
+ - `setup-pre-commit`
46
+ - `ubiquitous-language`
47
+ - `writing-beats`
48
+ - `writing-fragments`
49
+ - `writing-shape`
 
 
 
 
 
 
imported-skills/mattpocock/UPSTREAM_REVISION CHANGED
@@ -1 +1 @@
1
- f304057d61d3df3c9fd992ac2b6e3833cb9325fb
 
1
+ e74f0061bb67222181640effa98c675bdb2fdaa7
imported-skills/mattpocock/domain-model/ADR-FORMAT.md DELETED
@@ -1,47 +0,0 @@
1
- # ADR Format
2
-
3
- ADRs live in `docs/adr/` and use sequential numbering: `0001-slug.md`, `0002-slug.md`, etc.
4
-
5
- Create the `docs/adr/` directory lazily — only when the first ADR is needed.
6
-
7
- ## Template
8
-
9
- ```md
10
- # {Short title of the decision}
11
-
12
- {1-3 sentences: what's the context, what did we decide, and why.}
13
- ```
14
-
15
- That's it. An ADR can be a single paragraph. The value is in recording *that* a decision was made and *why* — not in filling out sections.
16
-
17
- ## Optional sections
18
-
19
- Only include these when they add genuine value. Most ADRs won't need them.
20
-
21
- - **Status** frontmatter (`proposed | accepted | deprecated | superseded by ADR-NNNN`) — useful when decisions are revisited
22
- - **Considered Options** — only when the rejected alternatives are worth remembering
23
- - **Consequences** — only when non-obvious downstream effects need to be called out
24
-
25
- ## Numbering
26
-
27
- Scan `docs/adr/` for the highest existing number and increment by one.
28
-
29
- ## When to offer an ADR
30
-
31
- All three of these must be true:
32
-
33
- 1. **Hard to reverse** — the cost of changing your mind later is meaningful
34
- 2. **Surprising without context** — a future reader will look at the code and wonder "why on earth did they do it this way?"
35
- 3. **The result of a real trade-off** — there were genuine alternatives and you picked one for specific reasons
36
-
37
- If a decision is easy to reverse, skip it — you'll just reverse it. If it's not surprising, nobody will wonder why. If there was no real alternative, there's nothing to record beyond "we did the obvious thing."
38
-
39
- ### What qualifies
40
-
41
- - **Architectural shape.** "We're using a monorepo." "The write model is event-sourced, the read model is projected into Postgres."
42
- - **Integration patterns between contexts.** "Ordering and Billing communicate via domain events, not synchronous HTTP."
43
- - **Technology choices that carry lock-in.** Database, message bus, auth provider, deployment target. Not every library — just the ones that would take a quarter to swap out.
44
- - **Boundary and scope decisions.** "Customer data is owned by the Customer context; other contexts reference it by ID only." The explicit no-s are as valuable as the yes-s.
45
- - **Deliberate deviations from the obvious path.** "We're using manual SQL instead of an ORM because X." Anything where a reasonable reader would assume the opposite. These stop the next engineer from "fixing" something that was deliberate.
46
- - **Constraints not visible in the code.** "We can't use AWS because of compliance requirements." "Response times must be under 200ms because of the partner API contract."
47
- - **Rejected alternatives when the rejection is non-obvious.** If you considered GraphQL and picked REST for subtle reasons, record it — otherwise someone will suggest GraphQL again in six months.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
imported-skills/mattpocock/domain-model/CONTEXT-FORMAT.md DELETED
@@ -1,77 +0,0 @@
1
- # CONTEXT.md Format
2
-
3
- ## Structure
4
-
5
- ```md
6
- # {Context Name}
7
-
8
- {One or two sentence description of what this context is and why it exists.}
9
-
10
- ## Language
11
-
12
- **Order**:
13
- {A concise description of the term}
14
- _Avoid_: Purchase, transaction
15
-
16
- **Invoice**:
17
- A request for payment sent to a customer after delivery.
18
- _Avoid_: Bill, payment request
19
-
20
- **Customer**:
21
- A person or organization that places orders.
22
- _Avoid_: Client, buyer, account
23
-
24
- ## Relationships
25
-
26
- - An **Order** produces one or more **Invoices**
27
- - An **Invoice** belongs to exactly one **Customer**
28
-
29
- ## Example dialogue
30
-
31
- > **Dev:** "When a **Customer** places an **Order**, do we create the **Invoice** immediately?"
32
- > **Domain expert:** "No — an **Invoice** is only generated once a **Fulfillment** is confirmed."
33
-
34
- ## Flagged ambiguities
35
-
36
- - "account" was used to mean both **Customer** and **User** — resolved: these are distinct concepts.
37
- ```
38
-
39
- ## Rules
40
-
41
- - **Be opinionated.** When multiple words exist for the same concept, pick the best one and list the others as aliases to avoid.
42
- - **Flag conflicts explicitly.** If a term is used ambiguously, call it out in "Flagged ambiguities" with a clear resolution.
43
- - **Keep definitions tight.** One sentence max. Define what it IS, not what it does.
44
- - **Show relationships.** Use bold term names and express cardinality where obvious.
45
- - **Only include terms specific to this project's context.** General programming concepts (timeouts, error types, utility patterns) don't belong even if the project uses them extensively. Before adding a term, ask: is this a concept unique to this context, or a general programming concept? Only the former belongs.
46
- - **Group terms under subheadings** when natural clusters emerge. If all terms belong to a single cohesive area, a flat list is fine.
47
- - **Write an example dialogue.** A conversation between a dev and a domain expert that demonstrates how the terms interact naturally and clarifies boundaries between related concepts.
48
-
49
- ## Single vs multi-context repos
50
-
51
- **Single context (most repos):** One `CONTEXT.md` at the repo root.
52
-
53
- **Multiple contexts:** A `CONTEXT-MAP.md` at the repo root lists the contexts, where they live, and how they relate to each other:
54
-
55
- ```md
56
- # Context Map
57
-
58
- ## Contexts
59
-
60
- - [Ordering](./src/ordering/CONTEXT.md) — receives and tracks customer orders
61
- - [Billing](./src/billing/CONTEXT.md) — generates invoices and processes payments
62
- - [Fulfillment](./src/fulfillment/CONTEXT.md) — manages warehouse picking and shipping
63
-
64
- ## Relationships
65
-
66
- - **Ordering → Fulfillment**: Ordering emits `OrderPlaced` events; Fulfillment consumes them to start picking
67
- - **Fulfillment → Billing**: Fulfillment emits `ShipmentDispatched` events; Billing consumes them to generate invoices
68
- - **Ordering ↔ Billing**: Shared types for `CustomerId` and `Money`
69
- ```
70
-
71
- The skill infers which structure applies:
72
-
73
- - If `CONTEXT-MAP.md` exists, read it to find contexts
74
- - If only a root `CONTEXT.md` exists, single context
75
- - If neither exists, create a root `CONTEXT.md` lazily when the first term is resolved
76
-
77
- When multiple contexts exist, infer which one the current topic relates to. If unclear, ask.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
imported-skills/mattpocock/domain-model/SKILL.md DELETED
@@ -1,81 +0,0 @@
1
- ---
2
- name: domain-model
3
- description: Grilling session that challenges your plan against the existing domain model, sharpens terminology, and updates documentation (CONTEXT.md, ADRs) inline as decisions crystallise. Use when user wants to stress-test a plan against their project's language and documented decisions.
4
- disable-model-invocation: true
5
- ---
6
-
7
- Interview me relentlessly about every aspect of this plan until we reach a shared understanding. Walk down each branch of the design tree, resolving dependencies between decisions one-by-one. For each question, provide your recommended answer.
8
-
9
- Ask the questions one at a time, waiting for feedback on each question before continuing.
10
-
11
- If a question can be answered by exploring the codebase, explore the codebase instead.
12
-
13
- ## Domain awareness
14
-
15
- During codebase exploration, also look for existing documentation:
16
-
17
- ### File structure
18
-
19
- Most repos have a single context:
20
-
21
- ```
22
- /
23
- ├── CONTEXT.md
24
- ├── docs/
25
- │ └── adr/
26
- │ ├── 0001-event-sourced-orders.md
27
- │ └── 0002-postgres-for-write-model.md
28
- └── src/
29
- ```
30
-
31
- If a `CONTEXT-MAP.md` exists at the root, the repo has multiple contexts. The map points to where each one lives:
32
-
33
- ```
34
- /
35
- ├── CONTEXT-MAP.md
36
- ├── docs/
37
- │ └── adr/ ← system-wide decisions
38
- ├── src/
39
- │ ├── ordering/
40
- │ │ ├── CONTEXT.md
41
- │ │ └── docs/adr/ ← context-specific decisions
42
- │ └── billing/
43
- │ ├── CONTEXT.md
44
- │ └── docs/adr/
45
- ```
46
-
47
- Create files lazily — only when you have something to write. If no `CONTEXT.md` exists, create one when the first term is resolved. If no `docs/adr/` exists, create it when the first ADR is needed.
48
-
49
- ## During the session
50
-
51
- ### Challenge against the glossary
52
-
53
- When the user uses a term that conflicts with the existing language in `CONTEXT.md`, call it out immediately. "Your glossary defines 'cancellation' as X, but you seem to mean Y — which is it?"
54
-
55
- ### Sharpen fuzzy language
56
-
57
- When the user uses vague or overloaded terms, propose a precise canonical term. "You're saying 'account' — do you mean the Customer or the User? Those are different things."
58
-
59
- ### Discuss concrete scenarios
60
-
61
- When domain relationships are being discussed, stress-test them with specific scenarios. Invent scenarios that probe edge cases and force the user to be precise about the boundaries between concepts.
62
-
63
- ### Cross-reference with code
64
-
65
- When the user states how something works, check whether the code agrees. If you find a contradiction, surface it: "Your code cancels entire Orders, but you just said partial cancellation is possible — which is right?"
66
-
67
- ### Update CONTEXT.md inline
68
-
69
- When a term is resolved, update `CONTEXT.md` right there. Don't batch these up — capture them as they happen. Use the format in [CONTEXT-FORMAT.md](./CONTEXT-FORMAT.md).
70
-
71
- Don't couple `CONTEXT.md` to implementation details. Only include terms that are meaningful to domain experts.
72
-
73
- ### Offer ADRs sparingly
74
-
75
- Only offer to create an ADR when all three are true:
76
-
77
- 1. **Hard to reverse** — the cost of changing your mind later is meaningful
78
- 2. **Surprising without context** — a future reader will wonder "why did they do it this way?"
79
- 3. **The result of a real trade-off** — there were genuine alternatives and you picked one for specific reasons
80
-
81
- If any of the three is missing, skip the ADR. Use the format in [ADR-FORMAT.md](./ADR-FORMAT.md).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
imported-skills/mattpocock/github-triage/AGENT-BRIEF.md DELETED
@@ -1,168 +0,0 @@
1
- # Writing Agent Briefs
2
-
3
- An agent brief is a structured comment posted on a GitHub issue when it moves to `ready-for-agent`. It is the authoritative specification that an AFK agent will work from. The original issue body and discussion are context — the agent brief is the contract.
4
-
5
- ## Principles
6
-
7
- ### Durability over precision
8
-
9
- The issue may sit in `ready-for-agent` for days or weeks. The codebase will change in the meantime. Write the brief so it stays useful even as files are renamed, moved, or refactored.
10
-
11
- - **Do** describe interfaces, types, and behavioral contracts
12
- - **Do** name specific types, function signatures, or config shapes that the agent should look for or modify
13
- - **Don't** reference file paths — they go stale
14
- - **Don't** reference line numbers
15
- - **Don't** assume the current implementation structure will remain the same
16
-
17
- ### Behavioral, not procedural
18
-
19
- Describe **what** the system should do, not **how** to implement it. The agent will explore the codebase fresh and make its own implementation decisions.
20
-
21
- - **Good:** "The `SkillConfig` type should accept an optional `schedule` field of type `CronExpression`"
22
- - **Bad:** "Open src/types/skill.ts and add a schedule field on line 42"
23
- - **Good:** "When a user runs `/triage` with no arguments, they should see a summary of issues needing attention"
24
- - **Bad:** "Add a switch statement in the main handler function"
25
-
26
- ### Complete acceptance criteria
27
-
28
- The agent needs to know when it's done. Every agent brief must have concrete, testable acceptance criteria. Each criterion should be independently verifiable.
29
-
30
- - **Good:** "Running `gh issue list --label needs-triage` returns issues that have been through initial classification"
31
- - **Bad:** "Triage should work correctly"
32
-
33
- ### Explicit scope boundaries
34
-
35
- State what is out of scope. This prevents the agent from gold-plating or making assumptions about adjacent features.
36
-
37
- ## Template
38
-
39
- ```markdown
40
- ## Agent Brief
41
-
42
- **Category:** bug / enhancement
43
- **Summary:** one-line description of what needs to happen
44
-
45
- **Current behavior:**
46
- Describe what happens now. For bugs, this is the broken behavior.
47
- For enhancements, this is the status quo the feature builds on.
48
-
49
- **Desired behavior:**
50
- Describe what should happen after the agent's work is complete.
51
- Be specific about edge cases and error conditions.
52
-
53
- **Key interfaces:**
54
- - `TypeName` — what needs to change and why
55
- - `functionName()` return type — what it currently returns vs what it should return
56
- - Config shape — any new configuration options needed
57
-
58
- **Acceptance criteria:**
59
- - [ ] Specific, testable criterion 1
60
- - [ ] Specific, testable criterion 2
61
- - [ ] Specific, testable criterion 3
62
-
63
- **Out of scope:**
64
- - Thing that should NOT be changed or addressed in this issue
65
- - Adjacent feature that might seem related but is separate
66
- ```
67
-
68
- ## Examples
69
-
70
- ### Good agent brief (bug)
71
-
72
- ```markdown
73
- ## Agent Brief
74
-
75
- **Category:** bug
76
- **Summary:** Skill description truncation drops mid-word, producing broken output
77
-
78
- **Current behavior:**
79
- When a skill description exceeds 1024 characters, it is truncated at exactly
80
- 1024 characters regardless of word boundaries. This produces descriptions
81
- that end mid-word (e.g. "Use when the user wants to confi").
82
-
83
- **Desired behavior:**
84
- Truncation should break at the last word boundary before 1024 characters
85
- and append "..." to indicate truncation.
86
-
87
- **Key interfaces:**
88
- - The `SkillMetadata` type's `description` field — no type change needed,
89
- but the validation/processing logic that populates it needs to respect
90
- word boundaries
91
- - Any function that reads SKILL.md frontmatter and extracts the description
92
-
93
- **Acceptance criteria:**
94
- - [ ] Descriptions under 1024 chars are unchanged
95
- - [ ] Descriptions over 1024 chars are truncated at the last word boundary
96
- before 1024 chars
97
- - [ ] Truncated descriptions end with "..."
98
- - [ ] The total length including "..." does not exceed 1024 chars
99
-
100
- **Out of scope:**
101
- - Changing the 1024 char limit itself
102
- - Multi-line description support
103
- ```
104
-
105
- ### Good agent brief (enhancement)
106
-
107
- ```markdown
108
- ## Agent Brief
109
-
110
- **Category:** enhancement
111
- **Summary:** Add `.out-of-scope/` directory support for tracking rejected feature requests
112
-
113
- **Current behavior:**
114
- When a feature request is rejected, the issue is closed with a `wontfix` label
115
- and a comment. There is no persistent record of the decision or reasoning.
116
- Future similar requests require the maintainer to recall or search for the
117
- prior discussion.
118
-
119
- **Desired behavior:**
120
- Rejected feature requests should be documented in `.out-of-scope/<concept>.md`
121
- files that capture the decision, reasoning, and links to all issues that
122
- requested the feature. When triaging new issues, these files should be
123
- checked for matches.
124
-
125
- **Key interfaces:**
126
- - Markdown file format in `.out-of-scope/` — each file should have a
127
- `# Concept Name` heading, a `**Decision:**` line, a `**Reason:**` line,
128
- and a `**Prior requests:**` list with issue links
129
- - The triage workflow should read all `.out-of-scope/*.md` files early
130
- and match incoming issues against them by concept similarity
131
-
132
- **Acceptance criteria:**
133
- - [ ] Closing a feature as wontfix creates/updates a file in `.out-of-scope/`
134
- - [ ] The file includes the decision, reasoning, and link to the closed issue
135
- - [ ] If a matching `.out-of-scope/` file already exists, the new issue is
136
- appended to its "Prior requests" list rather than creating a duplicate
137
- - [ ] During triage, existing `.out-of-scope/` files are checked and surfaced
138
- when a new issue matches a prior rejection
139
-
140
- **Out of scope:**
141
- - Automated matching (human confirms the match)
142
- - Reopening previously rejected features
143
- - Bug reports (only enhancement rejections go to `.out-of-scope/`)
144
- ```
145
-
146
- ### Bad agent brief
147
-
148
- ```markdown
149
- ## Agent Brief
150
-
151
- **Summary:** Fix the triage bug
152
-
153
- **What to do:**
154
- The triage thing is broken. Look at the main file and fix it.
155
- The function around line 150 has the issue.
156
-
157
- **Files to change:**
158
- - src/triage/handler.ts (line 150)
159
- - src/types.ts (line 42)
160
- ```
161
-
162
- This is bad because:
163
- - No category
164
- - Vague description ("the triage thing is broken")
165
- - References file paths and line numbers that will go stale
166
- - No acceptance criteria
167
- - No scope boundaries
168
- - No description of current vs desired behavior
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
imported-skills/mattpocock/github-triage/OUT-OF-SCOPE.md DELETED
@@ -1,101 +0,0 @@
1
- # Out-of-Scope Knowledge Base
2
-
3
- The `.out-of-scope/` directory in a repo stores persistent records of rejected feature requests. It serves two purposes:
4
-
5
- 1. **Institutional memory** — why a feature was rejected, so the reasoning isn't lost when the issue is closed
6
- 2. **Deduplication** — when a new issue comes in that matches a prior rejection, the skill can surface the previous decision instead of re-litigating it
7
-
8
- ## Directory structure
9
-
10
- ```
11
- .out-of-scope/
12
- ├── dark-mode.md
13
- ├── plugin-system.md
14
- └── graphql-api.md
15
- ```
16
-
17
- One file per **concept**, not per issue. Multiple issues requesting the same thing are grouped under one file.
18
-
19
- ## File format
20
-
21
- The file should be written in a relaxed, readable style — more like a short design document than a database entry. Use paragraphs, code samples, and examples to make the reasoning clear and useful to someone encountering it for the first time.
22
-
23
- ```markdown
24
- # Dark Mode
25
-
26
- This project does not support dark mode or user-facing theming.
27
-
28
- ## Why this is out of scope
29
-
30
- The rendering pipeline assumes a single color palette defined in
31
- `ThemeConfig`. Supporting multiple themes would require:
32
-
33
- - A theme context provider wrapping the entire component tree
34
- - Per-component theme-aware style resolution
35
- - A persistence layer for user theme preferences
36
-
37
- This is a significant architectural change that doesn't align with the
38
- project's focus on content authoring. Theming is a concern for downstream
39
- consumers who embed or redistribute the output.
40
-
41
- ```ts
42
- // The current ThemeConfig interface is not designed for runtime switching:
43
- interface ThemeConfig {
44
- colors: ColorPalette; // single palette, resolved at build time
45
- fonts: FontStack;
46
- }
47
- ```
48
-
49
- ## Prior requests
50
-
51
- - #42 — "Add dark mode support"
52
- - #87 — "Night theme for accessibility"
53
- - #134 — "Dark theme option"
54
- ```
55
-
56
- ### Naming the file
57
-
58
- Use a short, descriptive kebab-case name for the concept: `dark-mode.md`, `plugin-system.md`, `graphql-api.md`. The name should be recognizable enough that someone browsing the directory understands what was rejected without opening the file.
59
-
60
- ### Writing the reason
61
-
62
- The reason should be substantive — not "we don't want this" but why. Good reasons reference:
63
-
64
- - Project scope or philosophy ("This project focuses on X; theming is a downstream concern")
65
- - Technical constraints ("Supporting this would require Y, which conflicts with our Z architecture")
66
- - Strategic decisions ("We chose to use A instead of B because...")
67
-
68
- The reason should be durable. Avoid referencing temporary circumstances ("we're too busy right now") — those aren't real rejections, they're deferrals.
69
-
70
- ## When to check `.out-of-scope/`
71
-
72
- During triage (Step 1: Gather context), read all files in `.out-of-scope/`. When evaluating a new issue:
73
-
74
- - Check if the request matches an existing out-of-scope concept
75
- - Matching is by concept similarity, not keyword — "night theme" matches `dark-mode.md`
76
- - If there's a match, surface it to the maintainer: "This is similar to `.out-of-scope/dark-mode.md` — we rejected this before because [reason]. Do you still feel the same way?"
77
-
78
- The maintainer may:
79
-
80
- - **Confirm** — the new issue gets added to the existing file's "Prior requests" list, then closed
81
- - **Reconsider** — the out-of-scope file gets deleted or updated, and the issue proceeds through normal triage
82
- - **Disagree** — the issues are related but distinct, proceed with normal triage
83
-
84
- ## When to write to `.out-of-scope/`
85
-
86
- Only when an **enhancement** (not a bug) is rejected as `wontfix`. The flow:
87
-
88
- 1. Maintainer decides a feature request is out of scope
89
- 2. Check if a matching `.out-of-scope/` file already exists
90
- 3. If yes: append the new issue to the "Prior requests" list
91
- 4. If no: create a new file with the concept name, decision, reason, and first prior request
92
- 5. Post a comment on the issue explaining the decision and mentioning the `.out-of-scope/` file
93
- 6. Close the issue with the `wontfix` label
94
-
95
- ## Updating or removing out-of-scope files
96
-
97
- If the maintainer changes their mind about a previously rejected concept:
98
-
99
- - Delete the `.out-of-scope/` file
100
- - The skill does not need to reopen old issues — they're historical records
101
- - The new issue that triggered the reconsideration proceeds through normal triage
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
imported-skills/mattpocock/github-triage/SKILL.md DELETED
@@ -1,168 +0,0 @@
1
- ---
2
- name: github-triage
3
- description: Triage GitHub issues through a label-based state machine. Use when user wants to create an issue, triage issues, review incoming bugs or feature requests, prepare issues for an AFK agent, or manage issue workflow.
4
- ---
5
-
6
- # GitHub Issue Triage
7
-
8
- Triage issues in the current repo using a label-based state machine. Infer the repo from `git remote`. Use `gh` for all GitHub operations.
9
-
10
- ## AI Disclaimer
11
-
12
- Every comment or issue posted to GitHub during triage **must** include the following disclaimer at the top of the comment body, before any other content:
13
-
14
- ```
15
- > *This was generated by AI during triage.*
16
- ```
17
-
18
- ## Reference docs
19
-
20
- - [AGENT-BRIEF.md](AGENT-BRIEF.md) — how to write durable agent briefs
21
- - [OUT-OF-SCOPE.md](OUT-OF-SCOPE.md) — how the `.out-of-scope/` knowledge base works
22
-
23
- ## Labels
24
-
25
- | Label | Type | Description |
26
- | ----------------- | -------- | ---------------------------------------- |
27
- | `bug` | Category | Something is broken |
28
- | `enhancement` | Category | New feature or improvement |
29
- | `needs-triage` | State | Maintainer needs to evaluate this issue |
30
- | `needs-info` | State | Waiting on reporter for more information |
31
- | `ready-for-agent` | State | Fully specified, ready for AFK agent |
32
- | `ready-for-human` | State | Requires human implementation |
33
- | `wontfix` | State | Will not be actioned |
34
-
35
- Every issue should have exactly **one** state label and **one** category label. If an issue has conflicting state labels (e.g. both `needs-triage` and `ready-for-agent`), flag the conflict and ask the maintainer which state is correct before doing anything else. Provide a recommendation.
36
-
37
- ## State Machine
38
-
39
- | Current State | Can transition to | Who triggers it | What happens |
40
- | -------------- | ----------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------- |
41
- | `unlabeled` | `needs-triage` | Skill (on first look) | Issue needs maintainer evaluation. Skill applies label after presenting recommendation. |
42
- | `unlabeled` | `ready-for-agent` | Maintainer (via skill) | Issue is already well-specified and agent-suitable. Skill writes agent brief comment, applies label. |
43
- | `unlabeled` | `ready-for-human` | Maintainer (via skill) | Issue requires human implementation. Skill writes a brief comment summarizing the task, applies label. |
44
- | `unlabeled` | `wontfix` | Maintainer (via skill) | Issue is spam, duplicate, or out of scope. Skill closes with comment (and writes `.out-of-scope/` for enhancements). |
45
- | `needs-triage` | `needs-info` | Maintainer (via skill) | Issue is underspecified. Skill posts triage notes capturing progress so far + questions for reporter. |
46
- | `needs-triage` | `ready-for-agent` | Maintainer (via skill) | Grilling session complete, agent-suitable. Skill writes agent brief comment, applies label. |
47
- | `needs-triage` | `ready-for-human` | Maintainer (via skill) | Grilling session complete, needs human. Skill writes a brief comment summarizing the task, applies label. |
48
- | `needs-triage` | `wontfix` | Maintainer (via skill) | Maintainer decides not to action. Skill closes with comment (and writes `.out-of-scope/` for enhancements). |
49
- | `needs-info` | `needs-triage` | Skill (detects reply) | Reporter has replied. Skill surfaces to maintainer for re-evaluation. |
50
-
51
- An issue can only move along these transitions. The maintainer can override any state directly (see Quick State Override below), but the skill should flag if the transition is unusual.
52
-
53
- ## Invocation
54
-
55
- The maintainer invokes `/github-triage` then describes what they want in natural language. The skill interprets the request and takes the appropriate action.
56
-
57
- Example requests:
58
-
59
- - "Show me anything that needs my attention"
60
- - "Let's look at #42"
61
- - "Move #42 to ready-for-agent"
62
- - "What's ready for agents to pick up?"
63
- - "Are there any unlabeled issues?"
64
-
65
- ## Workflow: Show What Needs Attention
66
-
67
- When the maintainer asks for an overview, query GitHub and present a summary grouped into three buckets:
68
-
69
- 1. **Unlabeled issues** — new, no labels at all. These have never been triaged.
70
- 2. **`needs-triage` issues** — maintainer needs to evaluate or continue evaluating.
71
- 3. **`needs-info` issues with new activity** — the reporter has commented since the last triage notes comment. Check comment timestamps to determine this.
72
-
73
- Display counts per group. Within each group, show issues oldest first (longest-waiting gets attention first). For each issue, show: number, title, age, and a one-line summary of the issue body.
74
-
75
- Let the maintainer pick which issue to dive into.
76
-
77
- ## Workflow: Triage a Specific Issue
78
-
79
- ### Step 1: Gather context
80
-
81
- Before presenting anything to the maintainer:
82
-
83
- - Read the full issue: body, all comments, all labels, who reported it, when
84
- - If there are prior triage notes comments (from previous sessions), parse them to understand what has already been established
85
- - Explore the codebase to build context — understand the domain, relevant interfaces, and existing behavior related to the issue
86
- - Read `.out-of-scope/*.md` files and check if this issue matches or is similar to a previously rejected concept
87
-
88
- ### Step 2: Present a recommendation
89
-
90
- Tell the maintainer:
91
-
92
- - **Category recommendation:** bug or enhancement, with reasoning
93
- - **State recommendation:** where this issue should go, with reasoning
94
- - If it matches a prior out-of-scope rejection, surface that: "This is similar to `.out-of-scope/concept-name.md` — we rejected this before because X. Do you still feel the same way?"
95
- - A brief summary of what you found in the codebase that's relevant
96
-
97
- Then wait for the maintainer's direction. They may:
98
-
99
- - Agree and ask you to apply labels → do it
100
- - Want to flesh it out → start a /domain-model session
101
- - Override with a different state → apply their choice
102
- - Want to discuss → have a conversation
103
-
104
- ### Step 3: Bug reproduction (bugs only)
105
-
106
- If the issue is categorized as a bug, attempt to reproduce it before starting a /domain-model session. This will vary by codebase, but do your best:
107
-
108
- - Read the reporter's reproduction steps (if provided)
109
- - Explore the codebase to understand the relevant code paths
110
- - Try to reproduce the bug: run tests, execute commands, or trace the logic to confirm the reported behavior
111
- - If reproduction succeeds, report what you found to the maintainer — include the specific behavior you observed and where in the code it originates
112
- - If reproduction fails, report that too — the bug may be environment-specific, already fixed, or the report may be inaccurate
113
- - If the report lacks enough detail to attempt reproduction, note that — this is a strong signal the issue should move to `needs-info`
114
-
115
- The reproduction attempt informs the /domain-model session and the agent brief. A confirmed reproduction with a known code path makes for a much stronger brief.
116
-
117
- ### Step 4: /domain-model session (if needed)
118
-
119
- If the issue needs to be fleshed out before it's ready for an agent, interview the maintainer to build a complete specification. Use the /domain-model skill.
120
-
121
- ### Step 5: Apply the outcome
122
-
123
- Depending on the outcome:
124
-
125
- - **ready-for-agent** — post an agent brief comment (see [AGENT-BRIEF.md](AGENT-BRIEF.md))
126
- - **ready-for-human** — post a comment summarizing the task, what was established during triage, and why it needs human implementation. Use the same structure as an agent brief but note the reason it can't be delegated to an agent (e.g. requires judgment calls, external system access, design decisions, or manual testing).
127
- - **needs-info** — post triage notes with progress so far and questions for the reporter (see Needs Info Output below)
128
- - **wontfix (bug)** — post a polite comment explaining why, then close the issue
129
- - **wontfix (enhancement)** — write to `.out-of-scope/`, post a comment linking to it, then close the issue (see [OUT-OF-SCOPE.md](OUT-OF-SCOPE.md))
130
- - **needs-triage** — apply the label. Optionally leave a comment if there's partial progress to capture.
131
-
132
- ## Workflow: Quick State Override
133
-
134
- When the maintainer explicitly tells you to move an issue to a specific state (e.g. "move #42 to ready-for-agent"), trust their judgment and apply the label directly.
135
-
136
- Still show a confirmation of what you're about to do: which labels will be added/removed, and whether you'll post a comment or close the issue. But skip the /domain-model session entirely.
137
-
138
- If moving to `ready-for-agent` without a /domain-model session, ask the maintainer if they want to write a brief agent brief comment or skip it.
139
-
140
- ## Needs Info Output
141
-
142
- When moving an issue to `needs-info`, post a comment that captures the interview progress and tells the reporter what's needed:
143
-
144
- ```markdown
145
- ## Triage Notes
146
-
147
- **What we've established so far:**
148
-
149
- - point 1
150
- - point 2
151
-
152
- **What we still need from you (@reporter):**
153
-
154
- - question 1
155
- - question 2
156
- ```
157
-
158
- Include everything resolved during the /domain-model session in "established so far" — this work should not be lost. The questions for the reporter should be specific and actionable, not vague ("please provide more info").
159
-
160
- ## Resuming Previous Sessions
161
-
162
- When triaging an issue that already has triage notes from a previous session:
163
-
164
- 1. Read all comments to find prior triage notes
165
- 2. Parse what was already established
166
- 3. Check if the reporter has answered any outstanding questions
167
- 4. Present the maintainer with an updated picture: "Here's where we left off, and here's what the reporter has said since"
168
- 5. Continue the /domain-model session from where it stopped — do not re-ask resolved questions
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
imported-skills/mattpocock/grill-with-docs/SKILL.md CHANGED
@@ -73,7 +73,7 @@ When the user states how something works, check whether the code agrees. If you
73
 
74
  When a term is resolved, update `CONTEXT.md` right there. Don't batch these up — capture them as they happen. Use the format in [CONTEXT-FORMAT.md](./CONTEXT-FORMAT.md).
75
 
76
- Don't couple `CONTEXT.md` to implementation details. Only include terms that are meaningful to domain experts.
77
 
78
  ### Offer ADRs sparingly
79
 
 
73
 
74
  When a term is resolved, update `CONTEXT.md` right there. Don't batch these up — capture them as they happen. Use the format in [CONTEXT-FORMAT.md](./CONTEXT-FORMAT.md).
75
 
76
+ `CONTEXT.md` should be totally devoid of implementation details. Do not treat `CONTEXT.md` as a spec, a scratch pad, or a repository for implementation decisions. It is a glossary and nothing else.
77
 
78
  ### Offer ADRs sparingly
79
 
imported-skills/mattpocock/triage-issue/SKILL.md DELETED
@@ -1,102 +0,0 @@
1
- ---
2
- name: triage-issue
3
- description: Triage a bug or issue by exploring the codebase to find root cause, then create a GitHub issue with a TDD-based fix plan. Use when user reports a bug, wants to file an issue, mentions "triage", or wants to investigate and plan a fix for a problem.
4
- ---
5
-
6
- # Triage Issue
7
-
8
- Investigate a reported problem, find its root cause, and create a GitHub issue with a TDD fix plan. This is a mostly hands-off workflow - minimize questions to the user.
9
-
10
- ## Process
11
-
12
- ### 1. Capture the problem
13
-
14
- Get a brief description of the issue from the user. If they haven't provided one, ask ONE question: "What's the problem you're seeing?"
15
-
16
- Do NOT ask follow-up questions yet. Start investigating immediately.
17
-
18
- ### 2. Explore and diagnose
19
-
20
- Use the Agent tool with subagent_type=Explore to deeply investigate the codebase. Your goal is to find:
21
-
22
- - **Where** the bug manifests (entry points, UI, API responses)
23
- - **What** code path is involved (trace the flow)
24
- - **Why** it fails (the root cause, not just the symptom)
25
- - **What** related code exists (similar patterns, tests, adjacent modules)
26
-
27
- Look at:
28
- - Related source files and their dependencies
29
- - Existing tests (what's tested, what's missing)
30
- - Recent changes to affected files (`git log` on relevant files)
31
- - Error handling in the code path
32
- - Similar patterns elsewhere in the codebase that work correctly
33
-
34
- ### 3. Identify the fix approach
35
-
36
- Based on your investigation, determine:
37
-
38
- - The minimal change needed to fix the root cause
39
- - Which modules/interfaces are affected
40
- - What behaviors need to be verified via tests
41
- - Whether this is a regression, missing feature, or design flaw
42
-
43
- ### 4. Design TDD fix plan
44
-
45
- Create a concrete, ordered list of RED-GREEN cycles. Each cycle is one vertical slice:
46
-
47
- - **RED**: Describe a specific test that captures the broken/missing behavior
48
- - **GREEN**: Describe the minimal code change to make that test pass
49
-
50
- Rules:
51
- - Tests verify behavior through public interfaces, not implementation details
52
- - One test at a time, vertical slices (NOT all tests first, then all code)
53
- - Each test should survive internal refactors
54
- - Include a final refactor step if needed
55
- - **Durability**: Only suggest fixes that would survive radical codebase changes. Describe behaviors and contracts, not internal structure. Tests assert on observable outcomes (API responses, UI state, user-visible effects), not internal state. A good suggestion reads like a spec; a bad one reads like a diff.
56
-
57
- ### 5. Create the GitHub issue
58
-
59
- Create a GitHub issue using `gh issue create` with the template below. Do NOT ask the user to review before creating - just create it and share the URL.
60
-
61
- <issue-template>
62
-
63
- ## Problem
64
-
65
- A clear description of the bug or issue, including:
66
- - What happens (actual behavior)
67
- - What should happen (expected behavior)
68
- - How to reproduce (if applicable)
69
-
70
- ## Root Cause Analysis
71
-
72
- Describe what you found during investigation:
73
- - The code path involved
74
- - Why the current code fails
75
- - Any contributing factors
76
-
77
- Do NOT include specific file paths, line numbers, or implementation details that couple to current code layout. Describe modules, behaviors, and contracts instead. The issue should remain useful even after major refactors.
78
-
79
- ## TDD Fix Plan
80
-
81
- A numbered list of RED-GREEN cycles:
82
-
83
- 1. **RED**: Write a test that [describes expected behavior]
84
- **GREEN**: [Minimal change to make it pass]
85
-
86
- 2. **RED**: Write a test that [describes next behavior]
87
- **GREEN**: [Minimal change to make it pass]
88
-
89
- ...
90
-
91
- **REFACTOR**: [Any cleanup needed after all tests pass]
92
-
93
- ## Acceptance Criteria
94
-
95
- - [ ] Criterion 1
96
- - [ ] Criterion 2
97
- - [ ] All new tests pass
98
- - [ ] Existing tests still pass
99
-
100
- </issue-template>
101
-
102
- After creating the issue, print the issue URL and a one-line summary of the root cause.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
pyproject.toml CHANGED
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
 
5
  [project]
6
  name = "claude-ctx"
7
- version = "1.0.5"
8
  description = "Skill and agent recommendation system for Claude Code — knowledge graph, wiki, and intake quality gates"
9
  authors = [{ name = "Steve Solun" }]
10
  license = "MIT"
 
4
 
5
  [project]
6
  name = "claude-ctx"
7
+ version = "1.0.6"
8
  description = "Skill and agent recommendation system for Claude Code — knowledge graph, wiki, and intake quality gates"
9
  authors = [{ name = "Steve Solun" }]
10
  license = "MIT"
scripts/build_dashboard_graph_index.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build the compact dashboard graph-neighborhood SQLite index."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import os
9
+ import sqlite3
10
+ import zlib
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+
15
+ def _graph_edges(data: dict[str, Any]) -> list[dict[str, Any]]:
16
+ raw = data.get("links") if "links" in data else data.get("edges", [])
17
+ if not isinstance(raw, list):
18
+ return []
19
+ return [item for item in raw if isinstance(item, dict)]
20
+
21
+
22
+ def build_dashboard_index(graph_json: Path, output: Path, *, top_k: int = 40) -> None:
23
+ data = json.loads(graph_json.read_text(encoding="utf-8"))
24
+ nodes_raw = [item for item in data.get("nodes", []) if isinstance(item, dict)]
25
+ edges_raw = _graph_edges(data)
26
+ nodes: dict[str, dict[str, Any]] = {}
27
+ slug_rows: list[tuple[str, str, str]] = []
28
+ neighbors: dict[str, list[dict[str, Any]]] = {}
29
+
30
+ for node in nodes_raw:
31
+ node_id = node.get("id")
32
+ if not isinstance(node_id, str) or not node_id:
33
+ continue
34
+ slug = node_id.split(":", 1)[-1]
35
+ node_type = str(node.get("type") or node_id.split(":", 1)[0])
36
+ raw_tags = node.get("tags")
37
+ tags = raw_tags if isinstance(raw_tags, list) else []
38
+ nodes[node_id] = {
39
+ "id": node_id,
40
+ "label": node.get("label") or slug,
41
+ "type": node_type,
42
+ "tags": tags[:8],
43
+ "description": node.get("description") or "",
44
+ "quality_score": node.get("quality_score"),
45
+ "usage_score": node.get("usage_score"),
46
+ "degree": 0,
47
+ }
48
+ slug_rows.append((slug, node_type, node_id))
49
+ neighbors[node_id] = []
50
+
51
+ for edge in edges_raw:
52
+ source = edge.get("source")
53
+ target = edge.get("target")
54
+ if not isinstance(source, str) or not isinstance(target, str):
55
+ continue
56
+ if source not in nodes or target not in nodes:
57
+ continue
58
+ weight = float(edge.get("weight", 1.0) or 0.0)
59
+ row = {
60
+ "target": target,
61
+ "weight": weight,
62
+ "shared_tags": (edge.get("shared_tags") or [])[:4],
63
+ "reasons": (edge.get("reasons") or edge.get("edge_reasons") or [])[:4],
64
+ "semantic": edge.get("semantic"),
65
+ "tag_sim": edge.get("tag_sim"),
66
+ "slug_token_sim": edge.get("slug_token_sim"),
67
+ "source_overlap": edge.get("source_overlap"),
68
+ }
69
+ neighbors[source].append(row)
70
+ reverse = dict(row)
71
+ reverse["target"] = source
72
+ neighbors[target].append(reverse)
73
+
74
+ for node_id, rows in neighbors.items():
75
+ rows.sort(key=lambda row: -float(row.get("weight") or 0.0))
76
+ nodes[node_id]["degree"] = len(rows)
77
+ del rows[top_k:]
78
+
79
+ output.parent.mkdir(parents=True, exist_ok=True)
80
+ build_path = output.with_name(f".{output.name}.{os.getpid()}.tmp")
81
+ if build_path.exists():
82
+ build_path.unlink()
83
+ try:
84
+ conn = sqlite3.connect(build_path)
85
+ try:
86
+ conn.execute("PRAGMA journal_mode=OFF")
87
+ conn.execute("PRAGMA synchronous=OFF")
88
+ conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
89
+ conn.execute(
90
+ "CREATE TABLE nodes("
91
+ "id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,description TEXT,"
92
+ "quality_score REAL,usage_score REAL,degree INTEGER)"
93
+ )
94
+ conn.execute(
95
+ "CREATE TABLE slug_index("
96
+ "slug TEXT,type TEXT,node_id TEXT,PRIMARY KEY(slug,type,node_id))"
97
+ )
98
+ conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
99
+ meta = {
100
+ "version": 1,
101
+ "export_id": data.get("graph", {}).get("export_id"),
102
+ "nodes_count": len(nodes),
103
+ "edges_count": len(edges_raw),
104
+ "max_degree": max((int(node["degree"]) for node in nodes.values()), default=1),
105
+ "top_k": top_k,
106
+ }
107
+ conn.executemany(
108
+ "INSERT INTO meta(key,value) VALUES(?,?)",
109
+ [(key, json.dumps(value)) for key, value in meta.items()],
110
+ )
111
+ conn.executemany(
112
+ "INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
113
+ [
114
+ (
115
+ node["id"],
116
+ node["label"],
117
+ node["type"],
118
+ json.dumps(node["tags"], separators=(",", ":")),
119
+ node["description"],
120
+ node["quality_score"],
121
+ node["usage_score"],
122
+ node["degree"],
123
+ )
124
+ for node in nodes.values()
125
+ ],
126
+ )
127
+ conn.executemany("INSERT OR IGNORE INTO slug_index VALUES(?,?,?)", slug_rows)
128
+ neighbor_rows = []
129
+ for source, rows in neighbors.items():
130
+ slim = [
131
+ {
132
+ key: value
133
+ for key, value in row.items()
134
+ if value not in (None, [], "")
135
+ }
136
+ for row in rows
137
+ ]
138
+ payload = zlib.compress(
139
+ json.dumps(slim, separators=(",", ":")).encode("utf-8"),
140
+ level=6,
141
+ )
142
+ neighbor_rows.append((source, payload))
143
+ if len(neighbor_rows) >= 10_000:
144
+ conn.executemany("INSERT INTO neighbors VALUES(?,?)", neighbor_rows)
145
+ neighbor_rows.clear()
146
+ if neighbor_rows:
147
+ conn.executemany("INSERT INTO neighbors VALUES(?,?)", neighbor_rows)
148
+ conn.execute("CREATE INDEX idx_slug_index_slug ON slug_index(slug)")
149
+ conn.commit()
150
+ conn.execute("VACUUM")
151
+ finally:
152
+ conn.close()
153
+ os.replace(build_path, output)
154
+ finally:
155
+ if build_path.exists():
156
+ build_path.unlink()
157
+
158
+
159
+ def main() -> None:
160
+ parser = argparse.ArgumentParser()
161
+ parser.add_argument("--graph-json", type=Path, required=True)
162
+ parser.add_argument("--output", type=Path, required=True)
163
+ parser.add_argument("--top-k", type=int, default=40)
164
+ args = parser.parse_args()
165
+ build_dashboard_index(args.graph_json, args.output, top_k=args.top_k)
166
+
167
+
168
+ if __name__ == "__main__":
169
+ main()
src/__init__.py CHANGED
@@ -1,3 +1,3 @@
1
  """ctx — skill and agent recommendation for Claude Code."""
2
 
3
- __version__ = "1.0.5"
 
1
  """ctx — skill and agent recommendation for Claude Code."""
2
 
3
+ __version__ = "1.0.6"
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.5"
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.6"
34
 
35
 
36
  # Public library surface — anything listed here is safe for third-
src/ctx/core/graph/resolve_graph.py CHANGED
@@ -230,7 +230,11 @@ def _apply_entity_overlays(G: nx.Graph, graph_path: Path) -> nx.Graph:
230
  return G
231
 
232
 
233
- def load_graph(path: Path | None = None) -> nx.Graph:
 
 
 
 
234
  """Load the knowledge graph from graph.json.
235
 
236
  Returns an empty graph on any parse or schema error rather than crashing.
@@ -260,7 +264,9 @@ def load_graph(path: Path | None = None) -> nx.Graph:
260
  graph = node_link_graph(data, edges=edges_key)
261
  graph.graph.setdefault("ctx_graph_path", str(graph_path))
262
  graph = _apply_entity_overlays(graph, graph_path)
263
- return _filter_runtime_edges(graph, _configured_semantic_min_cosine())
 
 
264
  except json.JSONDecodeError as exc:
265
  logger.warning("graph.json is not valid JSON (%s); returning empty graph", exc)
266
  except UnicodeDecodeError as exc:
 
230
  return G
231
 
232
 
233
+ def load_graph(
234
+ path: Path | None = None,
235
+ *,
236
+ apply_runtime_filter: bool = True,
237
+ ) -> nx.Graph:
238
  """Load the knowledge graph from graph.json.
239
 
240
  Returns an empty graph on any parse or schema error rather than crashing.
 
264
  graph = node_link_graph(data, edges=edges_key)
265
  graph.graph.setdefault("ctx_graph_path", str(graph_path))
266
  graph = _apply_entity_overlays(graph, graph_path)
267
+ if apply_runtime_filter:
268
+ return _filter_runtime_edges(graph, _configured_semantic_min_cosine())
269
+ return graph
270
  except json.JSONDecodeError as exc:
271
  logger.warning("graph.json is not valid JSON (%s); returning empty graph", exc)
272
  except UnicodeDecodeError as exc:
src/ctx/core/source_registry.py CHANGED
@@ -1,228 +1,228 @@
1
- """External source registry and license gate for graph/wiki ingestion."""
2
-
3
- from __future__ import annotations
4
-
5
- import argparse
6
- import json
7
- from dataclasses import asdict, dataclass
8
- from pathlib import Path
9
- from typing import Any, Iterable
10
-
11
- PERMISSIVE_LICENSES = {
12
- "apache-2.0",
13
- "bsd-2-clause",
14
- "bsd-3-clause",
15
- "cc-by-4.0",
16
- "cc0-1.0",
17
- "isc",
18
- "mit",
19
- "mpl-2.0",
20
- "unlicense",
21
- }
22
- FULL_IMPORT_MODES = {"full", "full-body"}
23
- SAFE_IMPORT_MODES = {"external-link", "metadata-only"}
24
- ALLOWED_IMPORT_MODES = FULL_IMPORT_MODES | SAFE_IMPORT_MODES
25
- EXPLICIT_PERMISSION_STATUSES = {"explicit-permission", "owner-permission"}
26
-
27
-
28
- class LicenseGateError(ValueError):
29
- """Raised when a source cannot be imported with the requested mode."""
30
-
31
-
32
- @dataclass(frozen=True)
33
- class ExternalSourceRecord:
34
- name: str
35
- url: str
36
- revision: str
37
- license: str
38
- source_kind: str
39
- import_mode: str
40
- permission_status: str
41
- permission_reference: str | None = None
42
- notes: str | None = None
43
-
44
- @classmethod
45
- def from_mapping(cls, raw: dict[str, Any]) -> "ExternalSourceRecord":
46
- required = (
47
- "name",
48
- "url",
49
- "revision",
50
- "license",
51
- "source_kind",
52
- "import_mode",
53
- "permission_status",
54
- )
55
- missing = [field for field in required if not str(raw.get(field) or "").strip()]
56
- if missing:
57
- raise ValueError(f"source record missing required field(s): {', '.join(missing)}")
58
- return cls(
59
- name=_string(raw["name"], "name"),
60
- url=_string(raw["url"], "url"),
61
- revision=_string(raw["revision"], "revision"),
62
- license=_string(raw["license"], "license"),
63
- source_kind=_string(raw["source_kind"], "source_kind"),
64
- import_mode=_string(raw["import_mode"], "import_mode"),
65
- permission_status=_string(raw["permission_status"], "permission_status"),
66
- permission_reference=_optional_string(raw.get("permission_reference")),
67
- notes=_optional_string(raw.get("notes")),
68
- )
69
-
70
- def to_dict(self) -> dict[str, Any]:
71
- return {key: value for key, value in asdict(self).items() if value is not None}
72
-
73
-
74
- BUILTIN_EXTERNAL_SOURCES: tuple[ExternalSourceRecord, ...] = (
75
- ExternalSourceRecord(
76
- name="mattpocock-skills",
77
- url="https://github.com/mattpocock/skills",
78
- revision="f304057d61d3df3c9fd992ac2b6e3833cb9325fb",
79
- license="MIT",
80
- source_kind="skill-suite",
81
- import_mode="full",
82
- permission_status="license",
83
- ),
84
- ExternalSourceRecord(
85
- name="academic-research-skills",
86
- url="https://github.com/Imbad0202/academic-research-skills",
87
- revision="153203d129b1d0e83dd65ab96340048257cd45b2",
88
- license="CC BY-NC 4.0",
89
- source_kind="skill-suite",
90
- import_mode="metadata-only",
91
- permission_status="license",
92
- notes="Full-body import requires explicit noncommercial-license permission.",
93
- ),
94
- ExternalSourceRecord(
95
- name="agents-md",
96
- url="https://github.com/agentsmd/agents.md",
97
- revision="d1ac7f063d20e70015ed6732664049ae4ba9d74e",
98
- license="MIT",
99
- source_kind="knowledge-protocol",
100
- import_mode="metadata-only",
101
- permission_status="license",
102
- ),
103
- ExternalSourceRecord(
104
- name="lat-md",
105
- url="https://github.com/1st1/lat.md",
106
- revision="bf8d95ca7ece6e1a9e4a325eddb51ddd5db038b0",
107
- license="MIT",
108
- source_kind="knowledge-protocol",
109
- import_mode="metadata-only",
110
- permission_status="license",
111
- ),
112
- ExternalSourceRecord(
113
- name="optillm",
114
- url="https://github.com/algorithmicsuperintelligence/optillm",
115
- revision="df018d64db96d07fdd338d71a35fc567f9d50c7b",
116
- license="Apache-2.0",
117
- source_kind="harness",
118
- import_mode="metadata-only",
119
- permission_status="license",
120
- ),
121
- ExternalSourceRecord(
122
- name="julius-caveman",
123
- url="https://github.com/JuliusBrussee/caveman",
124
- revision="63a91ecadbf4c4719a4602a5abb00883f9966034",
125
- license="MIT",
126
- source_kind="skill-suite",
127
- import_mode="full",
128
- permission_status="license",
129
- ),
130
- )
131
-
132
-
133
- def _string(value: object, field: str) -> str:
134
- if not isinstance(value, str) or not value.strip():
135
- raise ValueError(f"{field}: expected non-empty string")
136
- return value.strip()
137
-
138
-
139
- def _optional_string(value: object) -> str | None:
140
- if value is None:
141
- return None
142
- if not isinstance(value, str):
143
- raise ValueError("optional string field must be a string when set")
144
- return value.strip() or None
145
-
146
-
147
- def _normalize_license(value: str) -> str:
148
- return (
149
- value.lower()
150
- .replace("_", "-")
151
- .replace(" ", "-")
152
- .replace("license", "")
153
- .strip("-")
154
- )
155
-
156
-
157
- def _license_block_reason(record: ExternalSourceRecord) -> str | None:
158
- license_norm = _normalize_license(record.license)
159
- if license_norm in PERMISSIVE_LICENSES:
160
- return None
161
- if "noncommercial" in license_norm or "-nc" in license_norm:
162
- return "non-commercial license"
163
- if "unknown" in license_norm or "no-explicit" in license_norm:
164
- return "unknown license"
165
- if "gpl" in license_norm or "agpl" in license_norm or "lgpl" in license_norm:
166
- return "copyleft license"
167
- return f"unapproved license {record.license!r}"
168
-
169
-
170
- def validate_import_plan(record: ExternalSourceRecord) -> ExternalSourceRecord:
171
- """Validate whether a source may be imported into shipped graph/wiki artifacts."""
172
-
173
- import_mode = record.import_mode.strip().lower()
174
- if import_mode not in ALLOWED_IMPORT_MODES:
175
- raise ValueError(
176
- f"{record.name}: import_mode must be one of {sorted(ALLOWED_IMPORT_MODES)}",
177
- )
178
- if import_mode in SAFE_IMPORT_MODES:
179
- return record
180
-
181
- reason = _license_block_reason(record)
182
- if reason is None:
183
- return record
184
-
185
- has_permission = record.permission_status in EXPLICIT_PERMISSION_STATUSES
186
- has_reference = bool(record.permission_reference)
187
- if has_permission and has_reference:
188
- return record
189
-
190
- raise LicenseGateError(
191
- f"{record.name}: full-body import blocked by {reason}; use metadata-only "
192
- "or record explicit permission with permission_reference.",
193
- )
194
-
195
-
196
- def load_source_registry(path: Path) -> list[ExternalSourceRecord]:
197
- raw = json.loads(path.read_text(encoding="utf-8"))
198
- records_raw: Iterable[Any]
199
- if isinstance(raw, dict):
200
- records_raw = raw.get("sources", [])
201
- else:
202
- records_raw = raw
203
- if not isinstance(records_raw, list):
204
- raise ValueError("source registry must be a list or an object with a sources list")
205
- records = [ExternalSourceRecord.from_mapping(item) for item in records_raw]
206
- for record in records:
207
- validate_import_plan(record)
208
- return records
209
-
210
-
211
- def main(argv: list[str] | None = None) -> None:
212
- parser = argparse.ArgumentParser(description="Validate ctx external source import policy.")
213
- parser.add_argument("--registry", type=Path, help="Optional JSON registry path.")
214
- parser.add_argument("--json", action="store_true", help="Emit records as JSON.")
215
- args = parser.parse_args(argv)
216
-
217
- records = load_source_registry(args.registry) if args.registry else list(BUILTIN_EXTERNAL_SOURCES)
218
- for record in records:
219
- validate_import_plan(record)
220
-
221
- if args.json:
222
- print(json.dumps({"sources": [record.to_dict() for record in records]}, indent=2))
223
- else:
224
- print(f"Validated {len(records)} external source record(s).")
225
-
226
-
227
- if __name__ == "__main__":
228
- main()
 
1
+ """External source registry and license gate for graph/wiki ingestion."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ from dataclasses import asdict, dataclass
8
+ from pathlib import Path
9
+ from typing import Any, Iterable
10
+
11
+ PERMISSIVE_LICENSES = {
12
+ "apache-2.0",
13
+ "bsd-2-clause",
14
+ "bsd-3-clause",
15
+ "cc-by-4.0",
16
+ "cc0-1.0",
17
+ "isc",
18
+ "mit",
19
+ "mpl-2.0",
20
+ "unlicense",
21
+ }
22
+ FULL_IMPORT_MODES = {"full", "full-body"}
23
+ SAFE_IMPORT_MODES = {"external-link", "metadata-only"}
24
+ ALLOWED_IMPORT_MODES = FULL_IMPORT_MODES | SAFE_IMPORT_MODES
25
+ EXPLICIT_PERMISSION_STATUSES = {"explicit-permission", "owner-permission"}
26
+
27
+
28
+ class LicenseGateError(ValueError):
29
+ """Raised when a source cannot be imported with the requested mode."""
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class ExternalSourceRecord:
34
+ name: str
35
+ url: str
36
+ revision: str
37
+ license: str
38
+ source_kind: str
39
+ import_mode: str
40
+ permission_status: str
41
+ permission_reference: str | None = None
42
+ notes: str | None = None
43
+
44
+ @classmethod
45
+ def from_mapping(cls, raw: dict[str, Any]) -> "ExternalSourceRecord":
46
+ required = (
47
+ "name",
48
+ "url",
49
+ "revision",
50
+ "license",
51
+ "source_kind",
52
+ "import_mode",
53
+ "permission_status",
54
+ )
55
+ missing = [field for field in required if not str(raw.get(field) or "").strip()]
56
+ if missing:
57
+ raise ValueError(f"source record missing required field(s): {', '.join(missing)}")
58
+ return cls(
59
+ name=_string(raw["name"], "name"),
60
+ url=_string(raw["url"], "url"),
61
+ revision=_string(raw["revision"], "revision"),
62
+ license=_string(raw["license"], "license"),
63
+ source_kind=_string(raw["source_kind"], "source_kind"),
64
+ import_mode=_string(raw["import_mode"], "import_mode"),
65
+ permission_status=_string(raw["permission_status"], "permission_status"),
66
+ permission_reference=_optional_string(raw.get("permission_reference")),
67
+ notes=_optional_string(raw.get("notes")),
68
+ )
69
+
70
+ def to_dict(self) -> dict[str, Any]:
71
+ return {key: value for key, value in asdict(self).items() if value is not None}
72
+
73
+
74
+ BUILTIN_EXTERNAL_SOURCES: tuple[ExternalSourceRecord, ...] = (
75
+ ExternalSourceRecord(
76
+ name="mattpocock-skills",
77
+ url="https://github.com/mattpocock/skills",
78
+ revision="e74f0061bb67222181640effa98c675bdb2fdaa7",
79
+ license="MIT",
80
+ source_kind="skill-suite",
81
+ import_mode="full",
82
+ permission_status="license",
83
+ ),
84
+ ExternalSourceRecord(
85
+ name="academic-research-skills",
86
+ url="https://github.com/Imbad0202/academic-research-skills",
87
+ revision="153203d129b1d0e83dd65ab96340048257cd45b2",
88
+ license="CC BY-NC 4.0",
89
+ source_kind="skill-suite",
90
+ import_mode="metadata-only",
91
+ permission_status="license",
92
+ notes="Full-body import requires explicit noncommercial-license permission.",
93
+ ),
94
+ ExternalSourceRecord(
95
+ name="agents-md",
96
+ url="https://github.com/agentsmd/agents.md",
97
+ revision="d1ac7f063d20e70015ed6732664049ae4ba9d74e",
98
+ license="MIT",
99
+ source_kind="knowledge-protocol",
100
+ import_mode="metadata-only",
101
+ permission_status="license",
102
+ ),
103
+ ExternalSourceRecord(
104
+ name="lat-md",
105
+ url="https://github.com/1st1/lat.md",
106
+ revision="bf8d95ca7ece6e1a9e4a325eddb51ddd5db038b0",
107
+ license="MIT",
108
+ source_kind="knowledge-protocol",
109
+ import_mode="metadata-only",
110
+ permission_status="license",
111
+ ),
112
+ ExternalSourceRecord(
113
+ name="optillm",
114
+ url="https://github.com/algorithmicsuperintelligence/optillm",
115
+ revision="df018d64db96d07fdd338d71a35fc567f9d50c7b",
116
+ license="Apache-2.0",
117
+ source_kind="harness",
118
+ import_mode="metadata-only",
119
+ permission_status="license",
120
+ ),
121
+ ExternalSourceRecord(
122
+ name="julius-caveman",
123
+ url="https://github.com/JuliusBrussee/caveman",
124
+ revision="63a91ecadbf4c4719a4602a5abb00883f9966034",
125
+ license="MIT",
126
+ source_kind="skill-suite",
127
+ import_mode="full",
128
+ permission_status="license",
129
+ ),
130
+ )
131
+
132
+
133
+ def _string(value: object, field: str) -> str:
134
+ if not isinstance(value, str) or not value.strip():
135
+ raise ValueError(f"{field}: expected non-empty string")
136
+ return value.strip()
137
+
138
+
139
+ def _optional_string(value: object) -> str | None:
140
+ if value is None:
141
+ return None
142
+ if not isinstance(value, str):
143
+ raise ValueError("optional string field must be a string when set")
144
+ return value.strip() or None
145
+
146
+
147
+ def _normalize_license(value: str) -> str:
148
+ return (
149
+ value.lower()
150
+ .replace("_", "-")
151
+ .replace(" ", "-")
152
+ .replace("license", "")
153
+ .strip("-")
154
+ )
155
+
156
+
157
+ def _license_block_reason(record: ExternalSourceRecord) -> str | None:
158
+ license_norm = _normalize_license(record.license)
159
+ if license_norm in PERMISSIVE_LICENSES:
160
+ return None
161
+ if "noncommercial" in license_norm or "-nc" in license_norm:
162
+ return "non-commercial license"
163
+ if "unknown" in license_norm or "no-explicit" in license_norm:
164
+ return "unknown license"
165
+ if "gpl" in license_norm or "agpl" in license_norm or "lgpl" in license_norm:
166
+ return "copyleft license"
167
+ return f"unapproved license {record.license!r}"
168
+
169
+
170
+ def validate_import_plan(record: ExternalSourceRecord) -> ExternalSourceRecord:
171
+ """Validate whether a source may be imported into shipped graph/wiki artifacts."""
172
+
173
+ import_mode = record.import_mode.strip().lower()
174
+ if import_mode not in ALLOWED_IMPORT_MODES:
175
+ raise ValueError(
176
+ f"{record.name}: import_mode must be one of {sorted(ALLOWED_IMPORT_MODES)}",
177
+ )
178
+ if import_mode in SAFE_IMPORT_MODES:
179
+ return record
180
+
181
+ reason = _license_block_reason(record)
182
+ if reason is None:
183
+ return record
184
+
185
+ has_permission = record.permission_status in EXPLICIT_PERMISSION_STATUSES
186
+ has_reference = bool(record.permission_reference)
187
+ if has_permission and has_reference:
188
+ return record
189
+
190
+ raise LicenseGateError(
191
+ f"{record.name}: full-body import blocked by {reason}; use metadata-only "
192
+ "or record explicit permission with permission_reference.",
193
+ )
194
+
195
+
196
+ def load_source_registry(path: Path) -> list[ExternalSourceRecord]:
197
+ raw = json.loads(path.read_text(encoding="utf-8"))
198
+ records_raw: Iterable[Any]
199
+ if isinstance(raw, dict):
200
+ records_raw = raw.get("sources", [])
201
+ else:
202
+ records_raw = raw
203
+ if not isinstance(records_raw, list):
204
+ raise ValueError("source registry must be a list or an object with a sources list")
205
+ records = [ExternalSourceRecord.from_mapping(item) for item in records_raw]
206
+ for record in records:
207
+ validate_import_plan(record)
208
+ return records
209
+
210
+
211
+ def main(argv: list[str] | None = None) -> None:
212
+ parser = argparse.ArgumentParser(description="Validate ctx external source import policy.")
213
+ parser.add_argument("--registry", type=Path, help="Optional JSON registry path.")
214
+ parser.add_argument("--json", action="store_true", help="Emit records as JSON.")
215
+ args = parser.parse_args(argv)
216
+
217
+ records = load_source_registry(args.registry) if args.registry else list(BUILTIN_EXTERNAL_SOURCES)
218
+ for record in records:
219
+ validate_import_plan(record)
220
+
221
+ if args.json:
222
+ print(json.dumps({"sources": [record.to_dict() for record in records]}, indent=2))
223
+ else:
224
+ print(f"Validated {len(records)} external source record(s).")
225
+
226
+
227
+ if __name__ == "__main__":
228
+ main()
src/ctx/core/wiki/wiki_queue_worker.py CHANGED
@@ -124,12 +124,22 @@ def _process_job(wiki_path: Path, job: wiki_queue.QueueJob) -> str:
124
  def _process_entity_upsert(wiki_path: Path, payload: dict[str, Any]) -> str:
125
  entity_type = _required_string(payload, "entity_type")
126
  slug = _required_string(payload, "slug")
 
127
  expected_hash = _required_string(payload, "content_hash")
128
  subject_type = _ENTITY_SUBJECT_TYPES.get(entity_type)
129
  if subject_type is None:
130
  raise ValueError(f"unsupported entity_type for entity-upsert: {entity_type}")
131
 
132
  entity_path = _resolve_entity_path(wiki_path, _required_string(payload, "entity_path"))
 
 
 
 
 
 
 
 
 
133
  text = entity_path.read_text(encoding="utf-8")
134
  actual_hash = sha256(text.encode("utf-8")).hexdigest()
135
  if actual_hash != expected_hash:
 
124
  def _process_entity_upsert(wiki_path: Path, payload: dict[str, Any]) -> str:
125
  entity_type = _required_string(payload, "entity_type")
126
  slug = _required_string(payload, "slug")
127
+ action = str(payload.get("action", "upsert")).strip() or "upsert"
128
  expected_hash = _required_string(payload, "content_hash")
129
  subject_type = _ENTITY_SUBJECT_TYPES.get(entity_type)
130
  if subject_type is None:
131
  raise ValueError(f"unsupported entity_type for entity-upsert: {entity_type}")
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,
138
+ payload={"graph_only": True, "incremental": False},
139
+ source="entity-delete",
140
+ )
141
+ return f"queued full graph refresh for deleted {subject_type} entity {slug}"
142
+
143
  text = entity_path.read_text(encoding="utf-8")
144
  actual_hash = sha256(text.encode("utf-8")).hexdigest()
145
  if actual_hash != expected_hash:
src/ctx_init.py CHANGED
@@ -26,8 +26,9 @@ What it does:
26
  ``~/.claude/settings.json``.
27
  6. Optionally: installs the initial graph/wiki archive if missing.
28
  Skipped unless the wizard or ``--graph`` asks for it. Source
29
- checkouts use ``graph/wiki-graph.tar.gz``; pip installs download
30
- the matching release asset.
 
31
 
32
  Idempotent: re-running only writes what's missing. Never overwrites
33
  a user's config or hook settings without an explicit ``--force`` flag.
@@ -41,11 +42,13 @@ import json
41
  import os
42
  import re
43
  import shutil
 
44
  import subprocess
45
  import sys
46
  import tarfile
47
  import tempfile
48
  import urllib.request
 
49
  from dataclasses import dataclass
50
  from importlib.metadata import PackageNotFoundError, version as package_version
51
  from pathlib import Path
@@ -223,8 +226,8 @@ _GRAPH_ARCHIVE_NAMES = {
223
  "full": _GRAPH_ARCHIVE_NAME,
224
  }
225
  _GRAPH_ARCHIVE_SHA256 = {
226
- "runtime": "84634152dea0f7c8881bc717eaefcce5bfe1b97c4cee90b3202a2ee48b95dd8c",
227
- "full": "a3968445d6ef9a27d5a684d30019b5730e9c40c62ba7fcd1b66e8567baa756b6",
228
  }
229
  _GRAPH_RELEASE_URL = (
230
  "https://github.com/stevesolun/ctx/releases/download/"
@@ -237,6 +240,7 @@ _GRAPH_REQUIRED_FILES = frozenset({
237
  "graphify-out/communities.json",
238
  "graphify-out/graph-report.md",
239
  "graphify-out/graph-export-manifest.json",
 
240
  "external-catalogs/skills-sh/catalog.json",
241
  })
242
  _GRAPH_MANAGED_PATHS = (
@@ -302,7 +306,7 @@ def build_graph(
302
  return 0
303
 
304
  temp_dir: tempfile.TemporaryDirectory[str] | None = None
305
- archive = _find_local_graph_archive(install_mode)
306
  try:
307
  if archive is None:
308
  temp_dir = tempfile.TemporaryDirectory(prefix="ctx-graph-download-")
@@ -317,6 +321,7 @@ def build_graph(
317
  print(f"Downloading pre-built graph from {url}")
318
  _download_graph_archive(archive, url=url, expected_sha256=expected_sha256)
319
  else:
 
320
  print(f"Installing pre-built graph from {archive}")
321
  _extract_graph_archive(archive, wiki_dir, install_mode=install_mode)
322
  _install_graph_entity_overlay(
@@ -475,6 +480,25 @@ def _expected_graph_archive_sha256(
475
  )
476
 
477
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478
  def _package_version() -> str:
479
  try:
480
  return package_version("claude-ctx")
@@ -610,6 +634,10 @@ def _validate_graph_install_tree(wiki_dir: Path) -> None:
610
  }
611
  if not isinstance(artifacts, dict) or artifacts != expected_artifacts:
612
  raise ValueError("graph export manifest artifacts map is incomplete")
 
 
 
 
613
 
614
 
615
  def _validate_graph_json_outline(path: Path) -> None:
@@ -635,6 +663,50 @@ def _validate_graph_json_outline(path: Path) -> None:
635
  raise ValueError("graphify-out/graph.json is missing an edges/links list")
636
 
637
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
638
  def _read_json_file(path: Path) -> Any:
639
  with path.open("r", encoding="utf-8") as f:
640
  return json.load(f)
 
26
  ``~/.claude/settings.json``.
27
  6. Optionally: installs the initial graph/wiki archive if missing.
28
  Skipped unless the wizard or ``--graph`` asks for it. Source
29
+ checkouts use ``graph/wiki-graph-runtime.tar.gz`` by default and
30
+ fall back to the full ``graph/wiki-graph.tar.gz`` archive; pip installs
31
+ download the matching release asset.
32
 
33
  Idempotent: re-running only writes what's missing. Never overwrites
34
  a user's config or hook settings without an explicit ``--force`` flag.
 
42
  import os
43
  import re
44
  import shutil
45
+ import sqlite3
46
  import subprocess
47
  import sys
48
  import tarfile
49
  import tempfile
50
  import urllib.request
51
+ import zlib
52
  from dataclasses import dataclass
53
  from importlib.metadata import PackageNotFoundError, version as package_version
54
  from pathlib import Path
 
226
  "full": _GRAPH_ARCHIVE_NAME,
227
  }
228
  _GRAPH_ARCHIVE_SHA256 = {
229
+ "runtime": "27cd757cabaf7209d864b460d14b0755e258cc9bcf93581cacf987e1a7ef1e21",
230
+ "full": "57974831189e6fa6c828f3dc2b6b54ebff50879dcc301ed749d20fa9cc495414",
231
  }
232
  _GRAPH_RELEASE_URL = (
233
  "https://github.com/stevesolun/ctx/releases/download/"
 
240
  "graphify-out/communities.json",
241
  "graphify-out/graph-report.md",
242
  "graphify-out/graph-export-manifest.json",
243
+ "graphify-out/dashboard-neighborhoods.sqlite3",
244
  "external-catalogs/skills-sh/catalog.json",
245
  })
246
  _GRAPH_MANAGED_PATHS = (
 
306
  return 0
307
 
308
  temp_dir: tempfile.TemporaryDirectory[str] | None = None
309
+ archive = None if graph_url is not None else _find_local_graph_archive(install_mode)
310
  try:
311
  if archive is None:
312
  temp_dir = tempfile.TemporaryDirectory(prefix="ctx-graph-download-")
 
321
  print(f"Downloading pre-built graph from {url}")
322
  _download_graph_archive(archive, url=url, expected_sha256=expected_sha256)
323
  else:
324
+ _verify_local_graph_archive(archive, requested_install_mode=install_mode)
325
  print(f"Installing pre-built graph from {archive}")
326
  _extract_graph_archive(archive, wiki_dir, install_mode=install_mode)
327
  _install_graph_entity_overlay(
 
480
  )
481
 
482
 
483
+ def _verify_local_graph_archive(archive: Path, *, requested_install_mode: str) -> None:
484
+ archive_mode = (
485
+ "full" if archive.name == _GRAPH_ARCHIVE_NAME else requested_install_mode
486
+ )
487
+ expected = _GRAPH_ARCHIVE_SHA256.get(archive_mode)
488
+ if expected is None:
489
+ return
490
+ hasher = hashlib.sha256()
491
+ with archive.open("rb") as fh:
492
+ while chunk := fh.read(1024 * 1024):
493
+ hasher.update(chunk)
494
+ actual = hasher.hexdigest()
495
+ if actual.lower() != expected.lower():
496
+ raise ValueError(
497
+ "local graph archive checksum mismatch: "
498
+ f"{archive} expected {expected.lower()} got {actual.lower()}"
499
+ )
500
+
501
+
502
  def _package_version() -> str:
503
  try:
504
  return package_version("claude-ctx")
 
634
  }
635
  if not isinstance(artifacts, dict) or artifacts != expected_artifacts:
636
  raise ValueError("graph export manifest artifacts map is incomplete")
637
+ _validate_dashboard_index_file(
638
+ wiki_dir / "graphify-out" / "dashboard-neighborhoods.sqlite3",
639
+ expected_export_id=export_id.strip(),
640
+ )
641
 
642
 
643
  def _validate_graph_json_outline(path: Path) -> None:
 
663
  raise ValueError("graphify-out/graph.json is missing an edges/links list")
664
 
665
 
666
+ def _validate_dashboard_index_file(path: Path, *, expected_export_id: str) -> None:
667
+ try:
668
+ conn = sqlite3.connect(f"file:{path.as_posix()}?mode=ro", uri=True)
669
+ conn.row_factory = sqlite3.Row
670
+ except sqlite3.Error as exc:
671
+ raise ValueError(f"dashboard-neighborhoods.sqlite3 is not valid SQLite: {exc}") from exc
672
+ try:
673
+ quick = conn.execute("PRAGMA quick_check").fetchone()
674
+ if quick is None or str(quick[0]).lower() != "ok":
675
+ raise ValueError("dashboard-neighborhoods.sqlite3 failed quick_check")
676
+ tables = {
677
+ str(row["name"])
678
+ for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")
679
+ }
680
+ required = {"meta", "nodes", "slug_index", "neighbors"}
681
+ missing = sorted(required - tables)
682
+ if missing:
683
+ raise ValueError(f"dashboard-neighborhoods.sqlite3 missing tables: {missing}")
684
+ meta = {
685
+ str(row["key"]): json.loads(str(row["value"]))
686
+ for row in conn.execute("SELECT key,value FROM meta")
687
+ }
688
+ if meta.get("export_id") != expected_export_id:
689
+ raise ValueError(
690
+ "dashboard-neighborhoods.sqlite3 export_id mismatch: "
691
+ f"expected {expected_export_id}, got {meta.get('export_id') or 'missing'}",
692
+ )
693
+ nodes_count = int(meta.get("nodes_count") or 0)
694
+ actual_nodes = int(conn.execute("SELECT COUNT(*) FROM nodes").fetchone()[0])
695
+ if nodes_count != actual_nodes:
696
+ raise ValueError("dashboard-neighborhoods.sqlite3 nodes_count mismatch")
697
+ payload = conn.execute("SELECT payload FROM neighbors LIMIT 1").fetchone()
698
+ if payload is not None:
699
+ decoded = json.loads(zlib.decompress(payload["payload"]).decode("utf-8"))
700
+ if not isinstance(decoded, list):
701
+ raise ValueError("dashboard-neighborhoods.sqlite3 neighbor payload is invalid")
702
+ except (sqlite3.Error, json.JSONDecodeError, TypeError, ValueError, zlib.error) as exc:
703
+ if isinstance(exc, ValueError):
704
+ raise
705
+ raise ValueError(f"dashboard-neighborhoods.sqlite3 validation failed: {exc}") from exc
706
+ finally:
707
+ conn.close()
708
+
709
+
710
  def _read_json_file(path: Path) -> Any:
711
  with path.open("r", encoding="utf-8") as f:
712
  return json.load(f)
src/ctx_monitor.py CHANGED
@@ -64,9 +64,12 @@ import math
64
  import os
65
  import re
66
  import secrets
 
67
  import sys
 
68
  import threading
69
  import time
 
70
  from collections import defaultdict, deque
71
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
72
  from pathlib import Path, PurePosixPath
@@ -90,6 +93,7 @@ _SIDECAR_INDEX_CACHE_VALUE: dict[tuple[str, str], dict] | None = None
90
  _WIKI_INDEX_LIMIT_PER_TYPE = 500
91
  _GRAPH_REPORT_RE = re.compile(r"Nodes:\s*([\d,]+)\s*\|\s*Edges:\s*([\d,]+)")
92
  _MAX_POST_BODY_BYTES = 64 * 1024
 
93
 
94
 
95
  # ─── Data sources ────────────────────────────────────────────────────────────
@@ -163,7 +167,10 @@ def _load_dashboard_graph() -> Any:
163
  if _GRAPH_CACHE_KEY == cache_key and _GRAPH_CACHE_VALUE is not None:
164
  return _GRAPH_CACHE_VALUE
165
 
166
- graph = _lg(graph_path)
 
 
 
167
  _GRAPH_CACHE_KEY = cache_key
168
  _GRAPH_CACHE_VALUE = graph
169
  return graph
@@ -437,6 +444,8 @@ def _queue_entity_refresh(
437
  action=action,
438
  source="ctx-monitor",
439
  )
 
 
440
  wiki_queue.enqueue_maintenance_job(
441
  wiki,
442
  kind=wiki_queue.GRAPH_EXPORT_JOB,
@@ -455,6 +464,21 @@ def _upsert_wiki_entity(payload: dict[str, Any]) -> tuple[bool, str]:
455
  if isinstance(existing_detail, dict)
456
  else None
457
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
458
  slug, entity_type, content = _entity_content_from_payload(
459
  payload,
460
  existing=existing_meta if isinstance(existing_meta, dict) else None,
@@ -845,8 +869,8 @@ def _render_entity_subgraph_svg(
845
  ),
846
  })
847
 
848
- nodes_json = json.dumps(node_payload)
849
- edges_json = json.dumps(edge_payload)
850
 
851
  return (
852
  "<div data-testid='entity-subgraph-graph' "
@@ -1566,6 +1590,11 @@ def _sidecar_files() -> list[Path]:
1566
 
1567
  def _sidecar_index_cache_key() -> tuple[tuple[Path, float, int], ...]:
1568
  keys: list[tuple[Path, float, int]] = []
 
 
 
 
 
1569
  for root in (_sidecar_dir(), _sidecar_dir() / "mcp"):
1570
  if not root.is_dir():
1571
  continue
@@ -1595,12 +1624,7 @@ def _sidecar_index() -> dict[tuple[str, str], dict]:
1595
 
1596
 
1597
  def _all_sidecars() -> list[dict]:
1598
- out: list[dict] = []
1599
- for p in _sidecar_files():
1600
- sidecar = _read_sidecar_file(p)
1601
- if sidecar is not None:
1602
- out.append(sidecar)
1603
- return out
1604
 
1605
 
1606
  # ─── Aggregations ────────────────────────────────────────────────────────────
@@ -1726,6 +1750,11 @@ def _grade_distribution() -> dict[str, int]:
1726
  return dist
1727
 
1728
 
 
 
 
 
 
1729
  def _session_detail(session_id: str) -> dict:
1730
  audit = _read_jsonl(_audit_log_path())
1731
  events = _read_jsonl(_events_jsonl_path())
@@ -2257,6 +2286,407 @@ def _graph_node_size(
2257
  }
2258
 
2259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2260
  def _graph_neighborhood(
2261
  slug: str,
2262
  hops: int = 1,
@@ -2271,6 +2701,16 @@ def _graph_neighborhood(
2271
  """
2272
  if "/" in slug or "\\" in slug or ".." in slug:
2273
  return {"nodes": [], "edges": [], "center": None}
 
 
 
 
 
 
 
 
 
 
2274
  try:
2275
  G = _load_dashboard_graph()
2276
  except Exception: # noqa: BLE001 — graph is advisory; blank on error
@@ -2279,7 +2719,6 @@ def _graph_neighborhood(
2279
  return {"nodes": [], "edges": [], "center": None}
2280
 
2281
  center = None
2282
- normalized_entity_type = _normalize_dashboard_entity_type(entity_type)
2283
  if entity_type is not None and normalized_entity_type is None:
2284
  return {"nodes": [], "edges": [], "center": None}
2285
  center, resolved, suggestions = _resolve_graph_center(
@@ -2409,6 +2848,25 @@ def _graph_stats() -> dict:
2409
  }
2410
  except OSError:
2411
  pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2412
  try:
2413
  G = _load_dashboard_graph()
2414
  except Exception: # noqa: BLE001
@@ -2420,6 +2878,33 @@ def _graph_stats() -> dict:
2420
  }
2421
 
2422
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2423
  def _wiki_stats() -> dict:
2424
  """Entity counts across all dashboard-supported entity types.
2425
 
@@ -2429,7 +2914,22 @@ def _wiki_stats() -> dict:
2429
  individual counts for the dashboard entity-type detail
2430
  line.
2431
  """
 
 
 
 
2432
  base = _wiki_dir() / "entities"
 
 
 
 
 
 
 
 
 
 
 
2433
  skills = len(list((base / "skills").glob("*.md"))) if (base / "skills").is_dir() else 0
2434
  agents = len(list((base / "agents").glob("*.md"))) if (base / "agents").is_dir() else 0
2435
  mcp_dir = base / "mcp-servers"
@@ -2441,12 +2941,12 @@ def _wiki_stats() -> dict:
2441
  "mcps": mcps,
2442
  "harnesses": harnesses,
2443
  "total": skills + agents + mcps + harnesses,
 
2444
  }
2445
 
2446
 
2447
  def _render_home() -> str:
2448
  sessions = _summarize_sessions()
2449
- grades = _grade_distribution()
2450
  recent = sessions[:10]
2451
  gstats = _graph_stats()
2452
  wstats = _wiki_stats()
@@ -2455,6 +2955,13 @@ def _render_home() -> str:
2455
  if _audit_log_path().exists() else 0
2456
  manifest = _read_manifest()
2457
  recent_audit = _read_jsonl(_audit_log_path(), limit=10)
 
 
 
 
 
 
 
2458
 
2459
  rows = []
2460
  for s in recent:
@@ -2486,14 +2993,13 @@ def _render_home() -> str:
2486
  + f"<div class='card'><div class='muted' style='font-size:0.8rem;'>Currently loaded</div>"
2487
  f"<div style='font-size:1.6rem; font-weight:600;'>{len(manifest.get('load', []))}</div>"
2488
  f"<a href='/loaded'>manage →</a></div>"
2489
- + f"<div class='card'><div class='muted' style='font-size:0.8rem;'>Sidecars</div>"
2490
- f"<div style='font-size:1.6rem; font-weight:600;'>{sum(grades.values())}</div>"
2491
- f"<a href='/skills'>browse →</a></div>"
2492
  + f"<div class='card'><div class='muted' style='font-size:0.8rem;'>Wiki entities</div>"
2493
  f"<div style='font-size:1.6rem; font-weight:600;'>{wstats['total']:,}</div>"
2494
  f"<span class='muted' style='font-size:0.75rem;'>"
2495
- f"{wstats['skills']:,} skills · {wstats['agents']:,} agents · "
2496
- f"{wstats['mcps']:,} MCPs · {wstats['harnesses']:,} harnesses</span></div>"
2497
  + f"<div class='card'><div class='muted' style='font-size:0.8rem;'>Knowledge graph</div>"
2498
  f"<div style='font-size:1.6rem; font-weight:600;'>{gstats['nodes']}</div>"
2499
  f"<span class='muted' style='font-size:0.75rem;'>{gstats['edges']:,} edges</span>"
@@ -2514,11 +3020,31 @@ def _render_home() -> str:
2514
  # ── Grade distribution ────────────────────────────────────────
2515
  "<div class='card'><strong>Skill quality grades:</strong> "
2516
  + "".join(
2517
- f"<span class='pill grade-{g}'>{g}: {n}</span> "
2518
- for g, n in grades.items()
2519
  )
2520
- + f"<span class='muted'> · total {sum(grades.values())}</span>"
2521
  "</div>"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2522
  # ── Two-column: recent sessions + recent audit ────────────────
2523
  "<div style='display:grid; grid-template-columns:2fr 1fr; gap:1rem;'>"
2524
  f"<div class='card'><strong>Recent sessions</strong> ({len(sessions)} total)"
@@ -2760,6 +3286,36 @@ def _render_skill_detail(slug: str, entity_type: str | None = None) -> str:
2760
  return _layout(slug, body)
2761
 
2762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2763
  def _top_degree_seeds(limit: int = 18, *, allow_load: bool = True) -> list[dict]:
2764
  """Pick high-degree nodes from the graph as seed suggestions.
2765
 
@@ -2771,7 +3327,7 @@ def _top_degree_seeds(limit: int = 18, *, allow_load: bool = True) -> list[dict]
2771
  except Exception: # noqa: BLE001
2772
  return []
2773
  if G is None:
2774
- return []
2775
  if G.number_of_nodes() == 0:
2776
  return []
2777
  ranked = sorted(G.degree, key=lambda kv: -kv[1])[:limit]
@@ -3094,8 +3650,8 @@ def _render_config() -> str:
3094
  def _render_graph(focus: str | None = None, focus_type: str | None = None) -> str:
3095
  """Interactive graph view backed by a dependency-free SVG renderer."""
3096
  focus_slug = focus or ""
3097
- focus_js = json.dumps(focus_slug)
3098
- focus_type_js = json.dumps(focus_type or "")
3099
  gstats = _graph_stats()
3100
  seeds = (
3101
  _top_degree_seeds(allow_load=False)
@@ -4366,6 +4922,12 @@ def _render_manage(mutations_enabled: bool | None = None) -> str:
4366
  "form.addEventListener('submit', async ev => {\n"
4367
  " ev.preventDefault();\n"
4368
  " const payload = Object.fromEntries(new FormData(form).entries());\n"
 
 
 
 
 
 
4369
  " setStatus('saving...');\n"
4370
  " const data = await post('/api/entity/upsert', payload);\n"
4371
  " setStatus(data.detail || (data.ok ? 'saved' : 'save failed'));\n"
@@ -5550,6 +6112,8 @@ class _MonitorHandler(BaseHTTPRequestHandler):
5550
  self._send_json(summary.to_dict() if summary is not None else {
5551
  "total": 0, "detail": "no sidecars yet",
5552
  })
 
 
5553
  elif path == "/api/runtime.json":
5554
  self._send_json(_runtime_lifecycle_summary())
5555
  elif path == "/api/config.json":
 
64
  import os
65
  import re
66
  import secrets
67
+ import sqlite3
68
  import sys
69
+ import tarfile
70
  import threading
71
  import time
72
+ import zlib
73
  from collections import defaultdict, deque
74
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
75
  from pathlib import Path, PurePosixPath
 
93
  _WIKI_INDEX_LIMIT_PER_TYPE = 500
94
  _GRAPH_REPORT_RE = re.compile(r"Nodes:\s*([\d,]+)\s*\|\s*Edges:\s*([\d,]+)")
95
  _MAX_POST_BODY_BYTES = 64 * 1024
96
+ _DASHBOARD_INDEX_MEMBER = "graphify-out/dashboard-neighborhoods.sqlite3"
97
 
98
 
99
  # ─── Data sources ────────────────────────────────────────────────────────────
 
167
  if _GRAPH_CACHE_KEY == cache_key and _GRAPH_CACHE_VALUE is not None:
168
  return _GRAPH_CACHE_VALUE
169
 
170
+ try:
171
+ graph = _lg(graph_path, apply_runtime_filter=False)
172
+ except TypeError:
173
+ graph = _lg(graph_path)
174
  _GRAPH_CACHE_KEY = cache_key
175
  _GRAPH_CACHE_VALUE = graph
176
  return graph
 
444
  action=action,
445
  source="ctx-monitor",
446
  )
447
+ if action == "delete":
448
+ return
449
  wiki_queue.enqueue_maintenance_job(
450
  wiki,
451
  kind=wiki_queue.GRAPH_EXPORT_JOB,
 
464
  if isinstance(existing_detail, dict)
465
  else None
466
  )
467
+ confirm_update = str(payload.get("confirm_update", "")).strip().lower() in {
468
+ "1",
469
+ "true",
470
+ "yes",
471
+ "y",
472
+ "on",
473
+ }
474
+ if existing_detail is not None and not confirm_update:
475
+ return (
476
+ False,
477
+ f"existing {requested_type}:{requested_slug} found; review before "
478
+ "replacing. Benefit: keeps the catalog current. Risk: a lower-quality "
479
+ "manual edit can degrade recommendations. Resubmit with "
480
+ "confirm_update=true to apply.",
481
+ )
482
  slug, entity_type, content = _entity_content_from_payload(
483
  payload,
484
  existing=existing_meta if isinstance(existing_meta, dict) else None,
 
869
  ),
870
  })
871
 
872
+ nodes_json = _json_for_script(node_payload)
873
+ edges_json = _json_for_script(edge_payload)
874
 
875
  return (
876
  "<div data-testid='entity-subgraph-graph' "
 
1590
 
1591
  def _sidecar_index_cache_key() -> tuple[tuple[Path, float, int], ...]:
1592
  keys: list[tuple[Path, float, int]] = []
1593
+ for path in _sidecar_files():
1594
+ stat = path.stat()
1595
+ keys.append((path.resolve(), stat.st_mtime, stat.st_size))
1596
+ if keys:
1597
+ return tuple(keys)
1598
  for root in (_sidecar_dir(), _sidecar_dir() / "mcp"):
1599
  if not root.is_dir():
1600
  continue
 
1624
 
1625
 
1626
  def _all_sidecars() -> list[dict]:
1627
+ return list(_sidecar_index().values())
 
 
 
 
 
1628
 
1629
 
1630
  # ─── Aggregations ────────────────────────────────────────────────────────────
 
1750
  return dist
1751
 
1752
 
1753
+ def _grade_distribution_payload() -> dict[str, Any]:
1754
+ grades = _grade_distribution()
1755
+ return {"grades": grades, "total": sum(grades.values())}
1756
+
1757
+
1758
  def _session_detail(session_id: str) -> dict:
1759
  audit = _read_jsonl(_audit_log_path())
1760
  events = _read_jsonl(_events_jsonl_path())
 
2286
  }
2287
 
2288
 
2289
+ def _dashboard_graph_index_path() -> Path:
2290
+ return _wiki_dir() / "graphify-out" / "dashboard-neighborhoods.sqlite3"
2291
+
2292
+
2293
+ def _dashboard_graph_manifest_export_id() -> str | None:
2294
+ manifest_path = _wiki_dir() / "graphify-out" / "graph-export-manifest.json"
2295
+ try:
2296
+ data = json.loads(manifest_path.read_text(encoding="utf-8"))
2297
+ except (OSError, json.JSONDecodeError):
2298
+ return None
2299
+ export_id = data.get("export_id") if isinstance(data, dict) else None
2300
+ if not isinstance(export_id, str) or not export_id.strip():
2301
+ return None
2302
+ return export_id.strip()
2303
+
2304
+
2305
+ def _dashboard_index_meta(index_path: Path) -> dict[str, Any] | None:
2306
+ try:
2307
+ conn = sqlite3.connect(f"file:{index_path.as_posix()}?mode=ro", uri=True)
2308
+ except sqlite3.Error:
2309
+ return None
2310
+ try:
2311
+ rows = conn.execute("SELECT key,value FROM meta").fetchall()
2312
+ except sqlite3.Error:
2313
+ return None
2314
+ finally:
2315
+ conn.close()
2316
+ try:
2317
+ return {str(key): json.loads(str(value)) for key, value in rows}
2318
+ except (TypeError, ValueError, json.JSONDecodeError):
2319
+ return None
2320
+
2321
+
2322
+ def _dashboard_index_matches_manifest(index_path: Path) -> bool:
2323
+ manifest_export_id = _dashboard_graph_manifest_export_id()
2324
+ if manifest_export_id is None:
2325
+ return False
2326
+ meta = _dashboard_index_meta(index_path)
2327
+ if meta is None:
2328
+ return False
2329
+ return meta.get("export_id") == manifest_export_id
2330
+
2331
+
2332
+ def _dashboard_graph_has_runtime_overlays() -> bool:
2333
+ overlay = _wiki_dir() / "graphify-out" / "entity-overlays.jsonl"
2334
+ try:
2335
+ return overlay.is_file() and overlay.stat().st_size > 0
2336
+ except OSError:
2337
+ return False
2338
+
2339
+
2340
+ def _dashboard_graph_index_archives() -> list[Path]:
2341
+ module_root = Path(__file__).resolve().parent.parent
2342
+ roots = (module_root,)
2343
+ names = ("wiki-graph-runtime.tar.gz", "wiki-graph.tar.gz")
2344
+ seen: set[Path] = set()
2345
+ archives: list[Path] = []
2346
+ for root in roots:
2347
+ for name in names:
2348
+ candidate = (root / "graph" / name).resolve()
2349
+ if candidate in seen:
2350
+ continue
2351
+ seen.add(candidate)
2352
+ if candidate.is_file():
2353
+ archives.append(candidate)
2354
+ return archives
2355
+
2356
+
2357
+ def _archive_graph_export_id(archive: Path) -> str | None:
2358
+ try:
2359
+ with tarfile.open(archive, "r:gz") as tar:
2360
+ try:
2361
+ member = tar.getmember("./graphify-out/graph-export-manifest.json")
2362
+ except KeyError:
2363
+ member = tar.getmember("graphify-out/graph-export-manifest.json")
2364
+ source = tar.extractfile(member)
2365
+ if source is None:
2366
+ return None
2367
+ try:
2368
+ data = json.loads(source.read().decode("utf-8", errors="replace"))
2369
+ finally:
2370
+ source.close()
2371
+ except (KeyError, OSError, tarfile.TarError, json.JSONDecodeError):
2372
+ return None
2373
+ export_id = data.get("export_id") if isinstance(data, dict) else None
2374
+ return export_id.strip() if isinstance(export_id, str) and export_id.strip() else None
2375
+
2376
+
2377
+ def _ensure_dashboard_graph_index() -> Path | None:
2378
+ target = _dashboard_graph_index_path()
2379
+ if target.is_file():
2380
+ if _dashboard_index_matches_manifest(target):
2381
+ return target
2382
+ try:
2383
+ target.unlink()
2384
+ except OSError:
2385
+ return None
2386
+ if (_wiki_dir() / "graphify-out" / "graph-report.md").is_file():
2387
+ return None
2388
+
2389
+ archives = _dashboard_graph_index_archives()
2390
+ if not archives:
2391
+ return None
2392
+ if _dashboard_graph_manifest_export_id() is None:
2393
+ return None
2394
+
2395
+ target.parent.mkdir(parents=True, exist_ok=True)
2396
+ try:
2397
+ with file_lock(target):
2398
+ if target.is_file():
2399
+ if _dashboard_index_matches_manifest(target):
2400
+ return target
2401
+ try:
2402
+ target.unlink()
2403
+ except OSError:
2404
+ return None
2405
+ for archive in archives:
2406
+ archive_export_id = _archive_graph_export_id(archive)
2407
+ manifest_export_id = _dashboard_graph_manifest_export_id()
2408
+ if manifest_export_id and archive_export_id and archive_export_id != manifest_export_id:
2409
+ continue
2410
+ try:
2411
+ with tarfile.open(archive, "r:gz") as tar:
2412
+ try:
2413
+ member = tar.getmember(f"./{_DASHBOARD_INDEX_MEMBER}")
2414
+ except KeyError:
2415
+ member = tar.getmember(_DASHBOARD_INDEX_MEMBER)
2416
+ if not member.isfile():
2417
+ continue
2418
+ source = tar.extractfile(member)
2419
+ if source is None:
2420
+ continue
2421
+ tmp = target.with_name(f".{target.name}.{os.getpid()}.tmp")
2422
+ try:
2423
+ with tmp.open("wb") as out:
2424
+ for chunk in iter(lambda: source.read(1024 * 1024), b""):
2425
+ out.write(chunk)
2426
+ if not _dashboard_index_matches_manifest(tmp):
2427
+ continue
2428
+ os.replace(tmp, target)
2429
+ return target
2430
+ finally:
2431
+ source.close()
2432
+ if tmp.exists():
2433
+ tmp.unlink()
2434
+ except (KeyError, OSError, tarfile.TarError):
2435
+ continue
2436
+ except TimeoutError:
2437
+ return None
2438
+ return target if target.is_file() else None
2439
+
2440
+
2441
+ def _index_node_size(
2442
+ *,
2443
+ slug: str,
2444
+ entity_type: str,
2445
+ quality: Any,
2446
+ usage: Any,
2447
+ degree: int,
2448
+ max_degree: int,
2449
+ ) -> dict[str, Any]:
2450
+ quality_value = _unit_score(quality)
2451
+ usage_value = _unit_score(usage)
2452
+ if quality_value is None or usage_value is None:
2453
+ sidecar_quality, sidecar_usage = _sidecar_score_inputs(slug, entity_type)
2454
+ quality_value = quality_value if quality_value is not None else sidecar_quality
2455
+ usage_value = usage_value if usage_value is not None else sidecar_usage
2456
+ q = 0.35 if quality_value is None else quality_value
2457
+ u = 0.0 if usage_value is None else usage_value
2458
+ popularity = (
2459
+ math.log1p(max(0, degree)) / math.log1p(max(1, max_degree))
2460
+ if max_degree > 0
2461
+ else 0.0
2462
+ )
2463
+ signal = max(0.0, min(1.0, 0.45 * q + 0.35 * u + 0.20 * popularity))
2464
+ return {
2465
+ "node_size": round(8.0 + signal * 16.0, 2),
2466
+ "size_signal": round(signal, 4),
2467
+ "size_reason": f"quality {q:.3f}; usage {u:.3f}; popularity {popularity:.3f}",
2468
+ }
2469
+
2470
+
2471
+ def _resolve_index_center(
2472
+ conn: sqlite3.Connection,
2473
+ raw_query: str,
2474
+ entity_type: str | None,
2475
+ ) -> tuple[str | None, dict[str, str] | None, list[str]]:
2476
+ raw_query = str(raw_query or "").strip()
2477
+ if not raw_query or "/" in raw_query or "\\" in raw_query or ".." in raw_query:
2478
+ return None, None, []
2479
+ normalized_query = _slugish(raw_query)
2480
+ if not normalized_query or not _is_safe_slug(normalized_query):
2481
+ return None, None, []
2482
+
2483
+ entity_types = (
2484
+ (entity_type,)
2485
+ if entity_type is not None
2486
+ else _DASHBOARD_ENTITY_TYPES
2487
+ )
2488
+ candidates = []
2489
+ for candidate in (raw_query, normalized_query):
2490
+ if candidate and candidate not in candidates:
2491
+ candidates.append(candidate)
2492
+ for current_type in entity_types:
2493
+ for candidate_slug in candidates:
2494
+ row = conn.execute(
2495
+ "SELECT node_id FROM slug_index WHERE slug=? AND type=? LIMIT 1",
2496
+ (candidate_slug, current_type),
2497
+ ).fetchone()
2498
+ if row is not None:
2499
+ return str(row["node_id"]), None, [candidate_slug]
2500
+
2501
+ where = ""
2502
+ params: list[Any] = []
2503
+ if entity_type is not None:
2504
+ where = "WHERE s.type=?"
2505
+ params.append(entity_type)
2506
+ rows = conn.execute(
2507
+ "SELECT s.slug,s.type,s.node_id,n.label,n.tags,n.degree "
2508
+ "FROM slug_index s JOIN nodes n ON n.id=s.node_id "
2509
+ f"{where}",
2510
+ params,
2511
+ )
2512
+ matches: list[tuple[tuple[int, int, int], str, str]] = []
2513
+ query_tokens = set(normalized_query.split("-"))
2514
+ for row in rows:
2515
+ node_slug = str(row["slug"] or "")
2516
+ label = str(row["label"] or node_slug)
2517
+ haystacks = {_slugish(node_slug), _slugish(label)}
2518
+ try:
2519
+ tags = json.loads(row["tags"] or "[]")
2520
+ except (TypeError, json.JSONDecodeError):
2521
+ tags = []
2522
+ if isinstance(tags, list):
2523
+ haystacks.update(_slugish(str(tag)) for tag in tags[:12])
2524
+ rank = None
2525
+ if normalized_query in haystacks:
2526
+ rank = 0
2527
+ elif any(h.startswith(normalized_query) for h in haystacks):
2528
+ rank = 1
2529
+ elif any(normalized_query in h for h in haystacks):
2530
+ rank = 2
2531
+ elif query_tokens and all(
2532
+ any(token in h for h in haystacks) for token in query_tokens
2533
+ ):
2534
+ rank = 3
2535
+ if rank is None:
2536
+ continue
2537
+ try:
2538
+ degree = int(row["degree"] or 0)
2539
+ except (TypeError, ValueError):
2540
+ degree = 0
2541
+ matches.append(((rank, len(node_slug), -degree), str(row["node_id"]), node_slug))
2542
+
2543
+ matches.sort(key=lambda item: item[0])
2544
+ suggestions: list[str] = []
2545
+ for _, _node_id, suggestion in matches[:8]:
2546
+ if suggestion not in suggestions:
2547
+ suggestions.append(suggestion)
2548
+ if not matches:
2549
+ return None, None, suggestions
2550
+ center = matches[0][1]
2551
+ return (
2552
+ center,
2553
+ {"query": raw_query, "slug": _graph_slug_from_node_id(center), "id": center},
2554
+ suggestions,
2555
+ )
2556
+
2557
+
2558
+ def _graph_neighborhood_from_index(
2559
+ slug: str,
2560
+ *,
2561
+ hops: int,
2562
+ limit: int,
2563
+ entity_type: str | None,
2564
+ ) -> dict | None:
2565
+ index_path = _ensure_dashboard_graph_index()
2566
+ if index_path is None or not index_path.is_file():
2567
+ return None
2568
+ try:
2569
+ conn = sqlite3.connect(f"file:{index_path.as_posix()}?mode=ro", uri=True)
2570
+ except sqlite3.Error:
2571
+ return None
2572
+ conn.row_factory = sqlite3.Row
2573
+ try:
2574
+ meta = {
2575
+ row["key"]: json.loads(row["value"])
2576
+ for row in conn.execute("SELECT key,value FROM meta")
2577
+ }
2578
+ max_degree = int(meta.get("max_degree") or 1)
2579
+ top_k = int(meta.get("top_k") or 0)
2580
+ if hops > 1 or (top_k > 0 and limit > top_k):
2581
+ return None
2582
+
2583
+ center, resolved, suggestions = _resolve_index_center(conn, slug, entity_type)
2584
+ if center is None:
2585
+ return {"nodes": [], "edges": [], "center": None, "suggestions": suggestions}
2586
+
2587
+ nodes_out: dict[str, dict[str, Any]] = {}
2588
+ edges_out: list[dict[str, Any]] = []
2589
+ emitted_edges: set[tuple[str, str]] = set()
2590
+ frontier = [center]
2591
+ seen = {center}
2592
+
2593
+ def add_node(node_id: str, depth: int) -> None:
2594
+ if node_id in nodes_out:
2595
+ return
2596
+ row = conn.execute("SELECT * FROM nodes WHERE id=?", (node_id,)).fetchone()
2597
+ if row is None:
2598
+ return
2599
+ tags = json.loads(row["tags"] or "[]")
2600
+ degree = int(row["degree"] or 0)
2601
+ node_type = str(row["type"] or _graph_type_from_node_id(node_id))
2602
+ node_slug = _graph_slug_from_node_id(node_id)
2603
+ size_data = _index_node_size(
2604
+ slug=node_slug,
2605
+ entity_type=node_type,
2606
+ quality=row["quality_score"],
2607
+ usage=row["usage_score"],
2608
+ degree=degree,
2609
+ max_degree=max_degree,
2610
+ )
2611
+ nodes_out[node_id] = {
2612
+ "data": {
2613
+ "id": node_id,
2614
+ "label": row["label"] or node_slug,
2615
+ "type": node_type,
2616
+ "depth": depth,
2617
+ "degree": degree,
2618
+ "tags": tags[:6],
2619
+ "description": row["description"] or "",
2620
+ "quality_score": row["quality_score"],
2621
+ "usage_score": row["usage_score"],
2622
+ "filter_tokens": [node_id, row["label"], node_slug, *tags],
2623
+ **size_data,
2624
+ },
2625
+ }
2626
+
2627
+ add_node(center, 0)
2628
+ for depth in range(1, hops + 1):
2629
+ next_frontier: list[str] = []
2630
+ for node_id in frontier:
2631
+ row = conn.execute(
2632
+ "SELECT payload FROM neighbors WHERE source=?",
2633
+ (node_id,),
2634
+ ).fetchone()
2635
+ if row is None:
2636
+ continue
2637
+ neighbors = json.loads(zlib.decompress(row["payload"]).decode("utf-8"))
2638
+ for edge in neighbors:
2639
+ if len(nodes_out) >= limit:
2640
+ break
2641
+ other = str(edge.get("target") or "")
2642
+ if not other:
2643
+ continue
2644
+ add_node(other, depth)
2645
+ edge_a, edge_b = sorted((node_id, other))
2646
+ edge_key = (edge_a, edge_b)
2647
+ if edge_key not in emitted_edges and other in nodes_out:
2648
+ emitted_edges.add(edge_key)
2649
+ shared_tags = list(edge.get("shared_tags") or [])[:4]
2650
+ for current in (node_id, other):
2651
+ tokens = nodes_out[current]["data"].setdefault(
2652
+ "filter_tokens", []
2653
+ )
2654
+ tokens.extend(shared_tags)
2655
+ edges_out.append({
2656
+ "data": {
2657
+ "id": f"{edge_key[0]}__{edge_key[1]}",
2658
+ "source": node_id,
2659
+ "target": other,
2660
+ "weight": edge.get("weight", 1),
2661
+ "shared_tags": shared_tags,
2662
+ "reasons": edge.get("reasons", []),
2663
+ "semantic": edge.get("semantic"),
2664
+ "tag_sim": edge.get("tag_sim"),
2665
+ "slug_token_sim": edge.get("slug_token_sim"),
2666
+ "source_overlap": edge.get("source_overlap"),
2667
+ },
2668
+ })
2669
+ if other not in seen:
2670
+ seen.add(other)
2671
+ next_frontier.append(other)
2672
+ if len(nodes_out) >= limit:
2673
+ break
2674
+ frontier = next_frontier
2675
+ if len(nodes_out) >= limit:
2676
+ break
2677
+ return {
2678
+ "nodes": list(nodes_out.values()),
2679
+ "edges": edges_out,
2680
+ "center": center,
2681
+ "resolved": resolved or {"source": "dashboard-index"},
2682
+ "suggestions": [],
2683
+ }
2684
+ except (OSError, sqlite3.Error, json.JSONDecodeError, zlib.error, KeyError, TypeError):
2685
+ return None
2686
+ finally:
2687
+ conn.close()
2688
+
2689
+
2690
  def _graph_neighborhood(
2691
  slug: str,
2692
  hops: int = 1,
 
2701
  """
2702
  if "/" in slug or "\\" in slug or ".." in slug:
2703
  return {"nodes": [], "edges": [], "center": None}
2704
+ normalized_entity_type = _normalize_dashboard_entity_type(entity_type)
2705
+ if not _dashboard_graph_has_runtime_overlays():
2706
+ indexed = _graph_neighborhood_from_index(
2707
+ slug,
2708
+ hops=hops,
2709
+ limit=limit,
2710
+ entity_type=normalized_entity_type,
2711
+ )
2712
+ if indexed is not None:
2713
+ return indexed
2714
  try:
2715
  G = _load_dashboard_graph()
2716
  except Exception: # noqa: BLE001 — graph is advisory; blank on error
 
2719
  return {"nodes": [], "edges": [], "center": None}
2720
 
2721
  center = None
 
2722
  if entity_type is not None and normalized_entity_type is None:
2723
  return {"nodes": [], "edges": [], "center": None}
2724
  center, resolved, suggestions = _resolve_graph_center(
 
2848
  }
2849
  except OSError:
2850
  pass
2851
+
2852
+ index_path = _ensure_dashboard_graph_index()
2853
+ if index_path is not None and index_path.is_file():
2854
+ try:
2855
+ conn = sqlite3.connect(f"file:{index_path.as_posix()}?mode=ro", uri=True)
2856
+ try:
2857
+ meta = {
2858
+ row[0]: json.loads(row[1])
2859
+ for row in conn.execute("SELECT key,value FROM meta")
2860
+ }
2861
+ return {
2862
+ "nodes": int(meta.get("nodes_count") or 0),
2863
+ "edges": int(meta.get("edges_count") or 0),
2864
+ "available": int(meta.get("nodes_count") or 0) > 0,
2865
+ }
2866
+ finally:
2867
+ conn.close()
2868
+ except (OSError, sqlite3.Error, ValueError, TypeError, json.JSONDecodeError):
2869
+ pass
2870
  try:
2871
  G = _load_dashboard_graph()
2872
  except Exception: # noqa: BLE001
 
2878
  }
2879
 
2880
 
2881
+ def _wiki_stats_from_dashboard_index() -> dict[str, int] | None:
2882
+ index_path = _dashboard_graph_index_path()
2883
+ if not index_path.is_file() or not _dashboard_index_matches_manifest(index_path):
2884
+ return None
2885
+ try:
2886
+ conn = sqlite3.connect(f"file:{index_path.as_posix()}?mode=ro", uri=True)
2887
+ try:
2888
+ rows = {
2889
+ str(row[0]): int(row[1])
2890
+ for row in conn.execute("SELECT type,COUNT(*) FROM nodes GROUP BY type")
2891
+ }
2892
+ finally:
2893
+ conn.close()
2894
+ except (OSError, sqlite3.Error, ValueError, TypeError):
2895
+ return None
2896
+
2897
+ stats = {
2898
+ "skills": rows.get("skill", 0),
2899
+ "agents": rows.get("agent", 0),
2900
+ "mcps": rows.get("mcp-server", 0),
2901
+ "harnesses": rows.get("harness", 0),
2902
+ }
2903
+ stats["total"] = sum(stats.values())
2904
+ stats["split_known"] = True
2905
+ return stats
2906
+
2907
+
2908
  def _wiki_stats() -> dict:
2909
  """Entity counts across all dashboard-supported entity types.
2910
 
 
2914
  individual counts for the dashboard entity-type detail
2915
  line.
2916
  """
2917
+ indexed = _wiki_stats_from_dashboard_index()
2918
+ if indexed is not None:
2919
+ return indexed
2920
+
2921
  base = _wiki_dir() / "entities"
2922
+ graph_out = _wiki_dir() / "graphify-out"
2923
+ if graph_out.is_dir() and (graph_out / "graph-report.md").is_file():
2924
+ graph_stats = _graph_stats()
2925
+ return {
2926
+ "skills": 0,
2927
+ "agents": 0,
2928
+ "mcps": 0,
2929
+ "harnesses": 0,
2930
+ "total": int(graph_stats.get("nodes") or 0),
2931
+ "split_known": False,
2932
+ }
2933
  skills = len(list((base / "skills").glob("*.md"))) if (base / "skills").is_dir() else 0
2934
  agents = len(list((base / "agents").glob("*.md"))) if (base / "agents").is_dir() else 0
2935
  mcp_dir = base / "mcp-servers"
 
2941
  "mcps": mcps,
2942
  "harnesses": harnesses,
2943
  "total": skills + agents + mcps + harnesses,
2944
+ "split_known": True,
2945
  }
2946
 
2947
 
2948
  def _render_home() -> str:
2949
  sessions = _summarize_sessions()
 
2950
  recent = sessions[:10]
2951
  gstats = _graph_stats()
2952
  wstats = _wiki_stats()
 
2955
  if _audit_log_path().exists() else 0
2956
  manifest = _read_manifest()
2957
  recent_audit = _read_jsonl(_audit_log_path(), limit=10)
2958
+ if wstats.get("split_known", True):
2959
+ wiki_detail = (
2960
+ f"{wstats['skills']:,} skills · {wstats['agents']:,} agents · "
2961
+ f"{wstats['mcps']:,} MCPs · {wstats['harnesses']:,} harnesses"
2962
+ )
2963
+ else:
2964
+ wiki_detail = "entity split unavailable; install the current graph index"
2965
 
2966
  rows = []
2967
  for s in recent:
 
2993
  + f"<div class='card'><div class='muted' style='font-size:0.8rem;'>Currently loaded</div>"
2994
  f"<div style='font-size:1.6rem; font-weight:600;'>{len(manifest.get('load', []))}</div>"
2995
  f"<a href='/loaded'>manage →</a></div>"
2996
+ + "<div class='card'><div class='muted' style='font-size:0.8rem;'>Sidecars</div>"
2997
+ "<div id='home-sidecar-count' style='font-size:1.6rem; font-weight:600;'>...</div>"
2998
+ "<a href='/skills'>browse →</a></div>"
2999
  + f"<div class='card'><div class='muted' style='font-size:0.8rem;'>Wiki entities</div>"
3000
  f"<div style='font-size:1.6rem; font-weight:600;'>{wstats['total']:,}</div>"
3001
  f"<span class='muted' style='font-size:0.75rem;'>"
3002
+ f"{html.escape(wiki_detail)}</span></div>"
 
3003
  + f"<div class='card'><div class='muted' style='font-size:0.8rem;'>Knowledge graph</div>"
3004
  f"<div style='font-size:1.6rem; font-weight:600;'>{gstats['nodes']}</div>"
3005
  f"<span class='muted' style='font-size:0.75rem;'>{gstats['edges']:,} edges</span>"
 
3020
  # ── Grade distribution ────────────────────────────────────────
3021
  "<div class='card'><strong>Skill quality grades:</strong> "
3022
  + "".join(
3023
+ f"<span class='pill grade-{g}' data-home-grade='{g}'>{g}: ...</span> "
3024
+ for g in ("A", "B", "C", "D", "F")
3025
  )
3026
+ + "<span id='home-grade-total' class='muted'> · total loading</span>"
3027
  "</div>"
3028
+ "<script>"
3029
+ "(() => {"
3030
+ "const countEl = document.getElementById('home-sidecar-count');"
3031
+ "const totalEl = document.getElementById('home-grade-total');"
3032
+ "fetch('/api/grades.json').then(r => r.ok ? r.json() : Promise.reject())"
3033
+ ".then(data => {"
3034
+ "const grades = data.grades || {};"
3035
+ "['A','B','C','D','F'].forEach(g => {"
3036
+ "const el = document.querySelector(`[data-home-grade=\"${g}\"]`);"
3037
+ "if (el) el.textContent = `${g}: ${grades[g] || 0}`;"
3038
+ "});"
3039
+ "if (countEl) countEl.textContent = String(data.total || 0);"
3040
+ "if (totalEl) totalEl.textContent = ` · total ${data.total || 0}`;"
3041
+ "})"
3042
+ ".catch(() => {"
3043
+ "if (countEl) countEl.textContent = 'open';"
3044
+ "if (totalEl) totalEl.textContent = ' · open Skills for counts';"
3045
+ "});"
3046
+ "})();"
3047
+ "</script>"
3048
  # ── Two-column: recent sessions + recent audit ────────────────
3049
  "<div style='display:grid; grid-template-columns:2fr 1fr; gap:1rem;'>"
3050
  f"<div class='card'><strong>Recent sessions</strong> ({len(sessions)} total)"
 
3286
  return _layout(slug, body)
3287
 
3288
 
3289
+ def _top_degree_seeds_from_index(limit: int = 18) -> list[dict]:
3290
+ if _dashboard_graph_has_runtime_overlays():
3291
+ return []
3292
+ index_path = _ensure_dashboard_graph_index()
3293
+ if index_path is None or not index_path.is_file():
3294
+ return []
3295
+ conn: sqlite3.Connection | None = None
3296
+ try:
3297
+ conn = sqlite3.connect(f"file:{index_path.as_posix()}?mode=ro", uri=True)
3298
+ conn.row_factory = sqlite3.Row
3299
+ rows = conn.execute(
3300
+ "SELECT id,label,type,degree FROM nodes ORDER BY degree DESC,id LIMIT ?",
3301
+ (max(1, limit),),
3302
+ ).fetchall()
3303
+ except (OSError, sqlite3.Error, TimeoutError):
3304
+ return []
3305
+ finally:
3306
+ if conn is not None:
3307
+ conn.close()
3308
+ return [
3309
+ {
3310
+ "slug": _graph_slug_from_node_id(str(row["id"])),
3311
+ "type": _graph_type_from_node_id(str(row["id"]), str(row["type"] or "skill")),
3312
+ "degree": int(row["degree"] or 0),
3313
+ "label": row["label"] or _graph_slug_from_node_id(str(row["id"])),
3314
+ }
3315
+ for row in rows
3316
+ ]
3317
+
3318
+
3319
  def _top_degree_seeds(limit: int = 18, *, allow_load: bool = True) -> list[dict]:
3320
  """Pick high-degree nodes from the graph as seed suggestions.
3321
 
 
3327
  except Exception: # noqa: BLE001
3328
  return []
3329
  if G is None:
3330
+ return _top_degree_seeds_from_index(limit)
3331
  if G.number_of_nodes() == 0:
3332
  return []
3333
  ranked = sorted(G.degree, key=lambda kv: -kv[1])[:limit]
 
3650
  def _render_graph(focus: str | None = None, focus_type: str | None = None) -> str:
3651
  """Interactive graph view backed by a dependency-free SVG renderer."""
3652
  focus_slug = focus or ""
3653
+ focus_js = _json_for_script(focus_slug)
3654
+ focus_type_js = _json_for_script(focus_type or "")
3655
  gstats = _graph_stats()
3656
  seeds = (
3657
  _top_degree_seeds(allow_load=False)
 
4922
  "form.addEventListener('submit', async ev => {\n"
4923
  " ev.preventDefault();\n"
4924
  " const payload = Object.fromEntries(new FormData(form).entries());\n"
4925
+ " const isUpdate = selected && selected.slug === payload.slug && selected.type === payload.entity_type;\n"
4926
+ " if (isUpdate) {\n"
4927
+ " const ok = confirm('Update existing ' + payload.entity_type + ':' + payload.slug + '?\\n\\nBenefit: keeps the catalog current.\\nRisk: a lower-quality edit can degrade recommendations.');\n"
4928
+ " if (!ok) { setStatus('update cancelled'); return; }\n"
4929
+ " payload.confirm_update = 'true';\n"
4930
+ " }\n"
4931
  " setStatus('saving...');\n"
4932
  " const data = await post('/api/entity/upsert', payload);\n"
4933
  " setStatus(data.detail || (data.ok ? 'saved' : 'save failed'));\n"
 
6112
  self._send_json(summary.to_dict() if summary is not None else {
6113
  "total": 0, "detail": "no sidecars yet",
6114
  })
6115
+ elif path == "/api/grades.json":
6116
+ self._send_json(_grade_distribution_payload())
6117
  elif path == "/api/runtime.json":
6118
  self._send_json(_runtime_lifecycle_summary())
6119
  elif path == "/api/config.json":
src/mcp_add.py CHANGED
@@ -29,18 +29,18 @@ from datetime import datetime, timezone
29
  from pathlib import Path
30
  from typing import Any
31
 
32
- import yaml # type: ignore[import-untyped]
33
-
34
- from ctx.core.entity_update import build_update_review, render_update_review
35
- from ctx_config import cfg
36
- from intake_pipeline import IntakeRejected, check_intake, record_embedding
37
- import mcp_canonical_index
38
  from mcp_entity import McpRecord
39
- from wiki_batch_entities import generate_mcp_page
40
- from ctx.core.wiki.wiki_sync import append_log, ensure_wiki, update_index
41
- from ctx.core.wiki.wiki_queue import enqueue_entity_upsert
42
- from ctx.core.wiki.wiki_utils import validate_skill_name
43
- from ctx.utils._fs_utils import reject_symlink_path, safe_atomic_write_text
44
 
45
  TODAY = datetime.now(timezone.utc).strftime("%Y-%m-%d")
46
 
@@ -237,14 +237,14 @@ def _find_existing_by_github_url(
237
  return None
238
 
239
 
240
- def add_mcp(
241
- *,
242
- record: McpRecord,
243
- wiki_path: Path,
244
- dry_run: bool = False,
245
- review_existing: bool = False,
246
- update_existing: bool = False,
247
- ) -> dict[str, Any]:
248
  """Add (or merge sources for) one MCP record into the wiki catalog.
249
 
250
  Flow:
@@ -265,11 +265,11 @@ def add_mcp(
265
  6. update_index + append_log (only when is_new_page).
266
 
267
  Args:
268
- record: Populated McpRecord dataclass instance.
269
- wiki_path: Absolute path to the wiki root directory.
270
- dry_run: Compute everything but skip writes and embeddings.
271
- review_existing: Return an update review instead of mutating existing pages.
272
- update_existing: Apply an existing-page update after review.
273
 
274
  Returns:
275
  dict with keys: slug, is_new_page, merged_sources, path
@@ -288,12 +288,13 @@ def add_mcp(
288
  # listing-page records currently have only homepage_url (Phase 6
289
  # detail-page enrichment will populate github_url so this dedup
290
  # path becomes meaningful for them too).
291
- canonical_match = _find_existing_by_github_url(mcp_dir, record.github_url)
292
- if canonical_match is not None and canonical_match != target_path:
293
- target_path = canonical_match
294
-
295
- reject_symlink_path(target_path)
296
- target_path.parent.mkdir(parents=True, exist_ok=True)
 
297
 
298
  is_new_page: bool
299
  merged_sources: list[str]
@@ -329,52 +330,52 @@ def add_mcp(
329
  merged_sources = sorted(record.sources)
330
  kept_description = record.description
331
 
332
- if is_new_page:
333
- final_text = generate_mcp_page(record)
334
- else:
335
- updated_fm = {
336
- **existing_fm,
337
- "sources": merged_sources,
338
- "description": kept_description,
339
- "updated": TODAY,
340
- }
341
- final_text = _rewrite_frontmatter(existing_text, updated_fm)
342
-
343
- if review_existing and not is_new_page and not update_existing:
344
- review = build_update_review(
345
- entity_type="mcp-server",
346
- slug=record.slug,
347
- existing_text=existing_text,
348
- proposed_text=final_text,
349
- )
350
- return {
351
- "slug": record.slug,
352
- "is_new_page": False,
353
- "merged_sources": merged_sources,
354
- "path": str(target_path),
355
- "skipped": True,
356
- "update_required": True,
357
- "update_review": render_update_review(review),
358
- "queued_job_id": None,
359
- }
360
-
361
- queue_job = None
362
- if not dry_run:
363
- # Phase 2 of branching: render and write. Any YAML serialization
364
- # failure now is a real error, not a dry-run side-effect.
365
- safe_atomic_write_text(target_path, final_text, encoding="utf-8")
366
- queue_job = enqueue_entity_upsert(
367
- wiki_path=wiki_path,
368
- entity_type="mcp-server",
369
- slug=record.slug,
370
- entity_path=target_path,
371
- content=final_text,
372
- action="created" if is_new_page else "updated",
373
- source="mcp_add",
374
- )
375
-
376
- # Phase 6b: keep the canonical sidecar index hot. Upsert on
377
- # every successful write so the first cross-source dedup after
378
  # this add is O(1) without needing a rebuild. Applies to both
379
  # new pages AND source merges — a merge can land a github_url
380
  # from the second source when the first source lacked one.
@@ -387,7 +388,7 @@ def add_mcp(
387
  mcp_canonical_index.upsert(
388
  mcp_dir,
389
  canonical,
390
- slug=record.slug,
391
  relpath=relpath,
392
  )
393
  except (OSError, ValueError) as exc:
@@ -413,10 +414,10 @@ def add_mcp(
413
  file=sys.stderr,
414
  )
415
 
416
- update_index(str(wiki_path), [record.slug], subject_type="mcp-servers")
417
 
418
  log_details = [
419
- f"Slug: {record.slug}",
420
  f"Path: {target_path}",
421
  f"Sources: {', '.join(merged_sources) if merged_sources else 'none'}",
422
  f"Tags: {', '.join(record.tags) if record.tags else 'none'}",
@@ -431,32 +432,32 @@ def add_mcp(
431
  log_details.append(
432
  "Warnings: " + "; ".join(f"{w.code}:{w.message}" for w in warnings)
433
  )
434
- append_log(str(wiki_path), "add-mcp", record.slug, log_details)
435
 
436
  return {
437
- "slug": record.slug,
438
- "is_new_page": is_new_page,
439
- "merged_sources": merged_sources,
440
- "path": str(target_path),
441
- "skipped": False,
442
- "update_required": False,
443
- "queued_job_id": queue_job.id if queue_job is not None else None,
444
- }
445
 
446
 
447
  # ── CLI ───────────────────────────────────────────────────────────────────────
448
 
449
 
450
- def _process_batch(
451
- records: list[dict[str, Any]],
452
- wiki_path: Path,
453
- dry_run: bool,
454
- skip_existing: bool,
455
- update_existing: bool,
456
- mcp_entity_dir: Path,
457
- ) -> tuple[int, int, int, int, int]:
458
- """Process records. Returns (added, merged, reviewed, rejected, errors)."""
459
- added = merged = reviewed = rejected = errors = 0
460
  total = len(records)
461
 
462
  for i, raw in enumerate(records, 1):
@@ -476,26 +477,26 @@ def _process_batch(
476
  print(f" [{i}/{total}] [skipped] {record.slug}")
477
  continue
478
 
479
- try:
480
- result = add_mcp(
481
- record=record,
482
- wiki_path=wiki_path,
483
- dry_run=dry_run,
484
- review_existing=True,
485
- update_existing=update_existing,
486
- )
487
- if result["is_new_page"]:
488
- added += 1
489
- status = "added"
490
- elif result.get("update_required"):
491
- reviewed += 1
492
- status = "update-review"
493
- if result.get("update_review"):
494
- print(result["update_review"])
495
- else:
496
- merged += 1
497
- status = "updated" if update_existing else "merged"
498
- print(f" [{i}/{total}] [{status}] {record.slug}")
499
  except IntakeRejected as exc:
500
  rejected += 1
501
  codes = ", ".join(f.code for f in exc.decision.failures) or "unknown"
@@ -504,7 +505,7 @@ def _process_batch(
504
  errors += 1
505
  print(f" [{i}/{total}] ERROR: {record.slug}: {exc}", file=sys.stderr)
506
 
507
- return added, merged, reviewed, rejected, errors
508
 
509
 
510
  def main() -> None:
@@ -532,16 +533,16 @@ def main() -> None:
532
 
533
  parser.add_argument("--dry-run", action="store_true", help="Parse and validate but skip writes")
534
  parser.add_argument("--wiki", default=str(cfg.wiki_dir), help="Wiki root path")
535
- parser.add_argument(
536
- "--skip-existing",
537
- action="store_true",
538
- help="Skip records whose entity page already exists (no source merge)",
539
- )
540
- parser.add_argument(
541
- "--update-existing",
542
- action="store_true",
543
- help="Apply the reviewed replacement when an MCP entity already exists",
544
- )
545
  args = parser.parse_args()
546
 
547
  wiki_path = Path(os.path.expanduser(args.wiki))
@@ -591,20 +592,20 @@ def main() -> None:
591
  print("No records to process.", file=sys.stderr)
592
  sys.exit(0)
593
 
594
- added, merged, reviewed, rejected, errors = _process_batch(
595
- records=raw_records,
596
- wiki_path=wiki_path,
597
- dry_run=args.dry_run,
598
- skip_existing=args.skip_existing,
599
- update_existing=args.update_existing,
600
- mcp_entity_dir=mcp_entity_dir,
601
- )
602
-
603
- dry_label = " (dry-run)" if args.dry_run else ""
604
- print(
605
- f"\nDone{dry_label}: {added} added, {merged} updated, "
606
- f"{reviewed} reviewed, {rejected} rejected, {errors} errors"
607
- )
608
 
609
 
610
  if __name__ == "__main__":
 
29
  from pathlib import Path
30
  from typing import Any
31
 
32
+ import yaml # type: ignore[import-untyped]
33
+
34
+ from ctx.core.entity_update import build_update_review, render_update_review
35
+ from ctx_config import cfg
36
+ from intake_pipeline import IntakeRejected, check_intake, record_embedding
37
+ import mcp_canonical_index
38
  from mcp_entity import McpRecord
39
+ from wiki_batch_entities import generate_mcp_page
40
+ from ctx.core.wiki.wiki_sync import append_log, ensure_wiki, update_index
41
+ from ctx.core.wiki.wiki_queue import enqueue_entity_upsert
42
+ from ctx.core.wiki.wiki_utils import validate_skill_name
43
+ from ctx.utils._fs_utils import reject_symlink_path, safe_atomic_write_text
44
 
45
  TODAY = datetime.now(timezone.utc).strftime("%Y-%m-%d")
46
 
 
237
  return None
238
 
239
 
240
+ def add_mcp(
241
+ *,
242
+ record: McpRecord,
243
+ wiki_path: Path,
244
+ dry_run: bool = False,
245
+ review_existing: bool = False,
246
+ update_existing: bool = False,
247
+ ) -> dict[str, Any]:
248
  """Add (or merge sources for) one MCP record into the wiki catalog.
249
 
250
  Flow:
 
265
  6. update_index + append_log (only when is_new_page).
266
 
267
  Args:
268
+ record: Populated McpRecord dataclass instance.
269
+ wiki_path: Absolute path to the wiki root directory.
270
+ dry_run: Compute everything but skip writes and embeddings.
271
+ review_existing: Return an update review instead of mutating existing pages.
272
+ update_existing: Apply an existing-page update after review.
273
 
274
  Returns:
275
  dict with keys: slug, is_new_page, merged_sources, path
 
288
  # listing-page records currently have only homepage_url (Phase 6
289
  # detail-page enrichment will populate github_url so this dedup
290
  # path becomes meaningful for them too).
291
+ canonical_match = _find_existing_by_github_url(mcp_dir, record.github_url)
292
+ if canonical_match is not None and canonical_match != target_path:
293
+ target_path = canonical_match
294
+
295
+ reject_symlink_path(target_path)
296
+ target_path.parent.mkdir(parents=True, exist_ok=True)
297
+ target_slug = target_path.stem
298
 
299
  is_new_page: bool
300
  merged_sources: list[str]
 
330
  merged_sources = sorted(record.sources)
331
  kept_description = record.description
332
 
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(
346
+ entity_type="mcp-server",
347
+ slug=target_slug,
348
+ existing_text=existing_text,
349
+ proposed_text=final_text,
350
+ )
351
+ return {
352
+ "slug": target_slug,
353
+ "is_new_page": False,
354
+ "merged_sources": merged_sources,
355
+ "path": str(target_path),
356
+ "skipped": True,
357
+ "update_required": True,
358
+ "update_review": render_update_review(review),
359
+ "queued_job_id": None,
360
+ }
361
+
362
+ queue_job = None
363
+ if not dry_run:
364
+ # Phase 2 of branching: render and write. Any YAML serialization
365
+ # failure now is a real error, not a dry-run side-effect.
366
+ safe_atomic_write_text(target_path, final_text, encoding="utf-8")
367
+ queue_job = enqueue_entity_upsert(
368
+ wiki_path=wiki_path,
369
+ entity_type="mcp-server",
370
+ slug=target_slug,
371
+ entity_path=target_path,
372
+ content=final_text,
373
+ action="created" if is_new_page else "updated",
374
+ source="mcp_add",
375
+ )
376
+
377
+ # Phase 6b: keep the canonical sidecar index hot. Upsert on
378
+ # every successful write so the first cross-source dedup after
379
  # this add is O(1) without needing a rebuild. Applies to both
380
  # new pages AND source merges — a merge can land a github_url
381
  # from the second source when the first source lacked one.
 
388
  mcp_canonical_index.upsert(
389
  mcp_dir,
390
  canonical,
391
+ slug=target_slug,
392
  relpath=relpath,
393
  )
394
  except (OSError, ValueError) as exc:
 
414
  file=sys.stderr,
415
  )
416
 
417
+ update_index(str(wiki_path), [target_slug], subject_type="mcp-servers")
418
 
419
  log_details = [
420
+ f"Slug: {target_slug}",
421
  f"Path: {target_path}",
422
  f"Sources: {', '.join(merged_sources) if merged_sources else 'none'}",
423
  f"Tags: {', '.join(record.tags) if record.tags else 'none'}",
 
432
  log_details.append(
433
  "Warnings: " + "; ".join(f"{w.code}:{w.message}" for w in warnings)
434
  )
435
+ append_log(str(wiki_path), "add-mcp", target_slug, log_details)
436
 
437
  return {
438
+ "slug": target_slug,
439
+ "is_new_page": is_new_page,
440
+ "merged_sources": merged_sources,
441
+ "path": str(target_path),
442
+ "skipped": False,
443
+ "update_required": False,
444
+ "queued_job_id": queue_job.id if queue_job is not None else None,
445
+ }
446
 
447
 
448
  # ── CLI ───────────────────────────────────────────────────────────────────────
449
 
450
 
451
+ def _process_batch(
452
+ records: list[dict[str, Any]],
453
+ wiki_path: Path,
454
+ dry_run: bool,
455
+ skip_existing: bool,
456
+ update_existing: bool,
457
+ mcp_entity_dir: Path,
458
+ ) -> tuple[int, int, int, int, int]:
459
+ """Process records. Returns (added, merged, reviewed, rejected, errors)."""
460
+ added = merged = reviewed = rejected = errors = 0
461
  total = len(records)
462
 
463
  for i, raw in enumerate(records, 1):
 
477
  print(f" [{i}/{total}] [skipped] {record.slug}")
478
  continue
479
 
480
+ try:
481
+ result = add_mcp(
482
+ record=record,
483
+ wiki_path=wiki_path,
484
+ dry_run=dry_run,
485
+ review_existing=True,
486
+ update_existing=update_existing,
487
+ )
488
+ if result["is_new_page"]:
489
+ added += 1
490
+ status = "added"
491
+ elif result.get("update_required"):
492
+ reviewed += 1
493
+ status = "update-review"
494
+ if result.get("update_review"):
495
+ print(result["update_review"])
496
+ else:
497
+ merged += 1
498
+ status = "updated" if update_existing else "merged"
499
+ print(f" [{i}/{total}] [{status}] {record.slug}")
500
  except IntakeRejected as exc:
501
  rejected += 1
502
  codes = ", ".join(f.code for f in exc.decision.failures) or "unknown"
 
505
  errors += 1
506
  print(f" [{i}/{total}] ERROR: {record.slug}: {exc}", file=sys.stderr)
507
 
508
+ return added, merged, reviewed, rejected, errors
509
 
510
 
511
  def main() -> None:
 
533
 
534
  parser.add_argument("--dry-run", action="store_true", help="Parse and validate but skip writes")
535
  parser.add_argument("--wiki", default=str(cfg.wiki_dir), help="Wiki root path")
536
+ parser.add_argument(
537
+ "--skip-existing",
538
+ action="store_true",
539
+ help="Skip records whose entity page already exists (no source merge)",
540
+ )
541
+ parser.add_argument(
542
+ "--update-existing",
543
+ action="store_true",
544
+ help="Apply the reviewed replacement when an MCP entity already exists",
545
+ )
546
  args = parser.parse_args()
547
 
548
  wiki_path = Path(os.path.expanduser(args.wiki))
 
592
  print("No records to process.", file=sys.stderr)
593
  sys.exit(0)
594
 
595
+ added, merged, reviewed, rejected, errors = _process_batch(
596
+ records=raw_records,
597
+ wiki_path=wiki_path,
598
+ dry_run=args.dry_run,
599
+ skip_existing=args.skip_existing,
600
+ update_existing=args.update_existing,
601
+ mcp_entity_dir=mcp_entity_dir,
602
+ )
603
+
604
+ dry_label = " (dry-run)" if args.dry_run else ""
605
+ print(
606
+ f"\nDone{dry_label}: {added} added, {merged} updated, "
607
+ f"{reviewed} reviewed, {rejected} rejected, {errors} errors"
608
+ )
609
 
610
 
611
  if __name__ == "__main__":
src/tests/test_ctx_init.py CHANGED
@@ -6,8 +6,10 @@ import builtins
6
  import hashlib
7
  import io
8
  import json
 
9
  import sys
10
  import tarfile
 
11
  from pathlib import Path
12
  from types import SimpleNamespace
13
 
@@ -16,6 +18,40 @@ import pytest
16
  import ctx_init as ci
17
 
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  def _artifact_sha256_or_lfs_oid(path: Path, *, normalize_text: bool = False) -> str:
20
  data = path.read_bytes()
21
  if data.startswith(b"version https://git-lfs.github.com/spec/v1\n"):
@@ -299,6 +335,7 @@ def _write_graph_archive(tmp_path: Path) -> Path:
299
  }),
300
  encoding="utf-8",
301
  )
 
302
  external = source / "external-catalogs" / "skills-sh"
303
  external.mkdir(parents=True)
304
  (external / "catalog.json").write_text("{}", encoding="utf-8")
@@ -321,6 +358,12 @@ def _tar_text(tf: tarfile.TarFile, name: str, text: str) -> None:
321
  tf.addfile(info, io.BytesIO(payload))
322
 
323
 
 
 
 
 
 
 
324
  def test_download_graph_archive_verifies_sha256(
325
  tmp_path: Path,
326
  monkeypatch,
@@ -371,6 +414,14 @@ def test_graph_download_checksums_match_shipped_artifacts() -> None:
371
  )
372
 
373
 
 
 
 
 
 
 
 
 
374
  def test_custom_graph_url_requires_checksum_or_explicit_opt_out(
375
  tmp_path: Path,
376
  monkeypatch,
@@ -392,6 +443,44 @@ def test_custom_graph_url_requires_checksum_or_explicit_opt_out(
392
  assert rc == 1
393
 
394
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
395
  def test_main_with_graph_flag_installs_prebuilt_graph(
396
  tmp_path: Path,
397
  monkeypatch,
@@ -406,6 +495,7 @@ def test_main_with_graph_flag_installs_prebuilt_graph(
406
  lambda _install_mode="runtime": archive,
407
  raising=False,
408
  )
 
409
  monkeypatch.setattr(
410
  ci,
411
  "_download_graph_archive",
@@ -471,6 +561,7 @@ def test_graph_install_copies_local_entity_overlay(
471
  raising=False,
472
  )
473
  monkeypatch.setattr(ci, "_find_local_graph_entity_overlay", lambda: overlay)
 
474
 
475
  assert ci.build_graph(claude) == 0
476
 
@@ -520,6 +611,13 @@ def test_runtime_graph_install_extracts_harness_pages_after_required_files(
520
  },
521
  }),
522
  )
 
 
 
 
 
 
 
523
  _tar_text(tf, "external-catalogs/skills-sh/catalog.json", "{}")
524
  _tar_text(tf, "index.md", "# Wiki\n")
525
  _tar_text(tf, "entities/harnesses/text-to-cad.md", "# Text to CAD\n")
@@ -531,6 +629,7 @@ def test_runtime_graph_install_extracts_harness_pages_after_required_files(
531
  "_find_local_graph_archive",
532
  lambda _install_mode="runtime": archive,
533
  )
 
534
 
535
  assert ci.build_graph(claude) == 0
536
  assert (
@@ -562,6 +661,7 @@ def test_graph_install_rejects_incomplete_archive(
562
  "_find_local_graph_archive",
563
  lambda _install_mode="runtime": archive,
564
  )
 
565
 
566
  assert ci.build_graph(claude) == 1
567
  assert not (claude / "skill-wiki" / "graphify-out" / "graph.json").exists()
@@ -604,6 +704,7 @@ def test_graph_install_validation_does_not_parse_full_graph_json(
604
  }),
605
  encoding="utf-8",
606
  )
 
607
  external = wiki / "external-catalogs" / "skills-sh"
608
  external.mkdir(parents=True)
609
  (external / "catalog.json").write_text("{}", encoding="utf-8")
@@ -634,6 +735,7 @@ def test_graph_install_force_prunes_stale_generated_files(
634
  "_find_local_graph_archive",
635
  lambda _install_mode="runtime": archive,
636
  )
 
637
 
638
  assert ci.main([
639
  "--graph",
@@ -662,6 +764,7 @@ def test_graph_install_rejects_path_traversal_archive(
662
  "_find_local_graph_archive",
663
  lambda _install_mode="runtime": archive,
664
  )
 
665
 
666
  assert ci.build_graph(claude) == 1
667
  assert not (tmp_path / "evil.txt").exists()
 
6
  import hashlib
7
  import io
8
  import json
9
+ import sqlite3
10
  import sys
11
  import tarfile
12
+ import zlib
13
  from pathlib import Path
14
  from types import SimpleNamespace
15
 
 
18
  import ctx_init as ci
19
 
20
 
21
+ def _write_dashboard_index(path: Path, *, export_id: str = "test-export") -> None:
22
+ conn = sqlite3.connect(path)
23
+ try:
24
+ conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
25
+ conn.execute(
26
+ "CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
27
+ "description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
28
+ )
29
+ conn.execute(
30
+ "CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
31
+ "PRIMARY KEY(slug,type,node_id))"
32
+ )
33
+ conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
34
+ conn.executemany(
35
+ "INSERT INTO meta VALUES(?,?)",
36
+ [
37
+ ("export_id", json.dumps(export_id)),
38
+ ("nodes_count", "1"),
39
+ ("edges_count", "0"),
40
+ ("max_degree", "1"),
41
+ ("top_k", "40"),
42
+ ],
43
+ )
44
+ conn.execute(
45
+ "INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
46
+ ("skill:current", "current", "skill", "[]", "", None, None, 0),
47
+ )
48
+ conn.execute("INSERT INTO slug_index VALUES(?,?,?)", ("current", "skill", "skill:current"))
49
+ conn.execute("INSERT INTO neighbors VALUES(?,?)", ("skill:current", zlib.compress(b"[]")))
50
+ conn.commit()
51
+ finally:
52
+ conn.close()
53
+
54
+
55
  def _artifact_sha256_or_lfs_oid(path: Path, *, normalize_text: bool = False) -> str:
56
  data = path.read_bytes()
57
  if data.startswith(b"version https://git-lfs.github.com/spec/v1\n"):
 
335
  }),
336
  encoding="utf-8",
337
  )
338
+ _write_dashboard_index(graph_out / "dashboard-neighborhoods.sqlite3")
339
  external = source / "external-catalogs" / "skills-sh"
340
  external.mkdir(parents=True)
341
  (external / "catalog.json").write_text("{}", encoding="utf-8")
 
358
  tf.addfile(info, io.BytesIO(payload))
359
 
360
 
361
+ def _tar_bytes(tf: tarfile.TarFile, name: str, payload: bytes) -> None:
362
+ info = tarfile.TarInfo(name)
363
+ info.size = len(payload)
364
+ tf.addfile(info, io.BytesIO(payload))
365
+
366
+
367
  def test_download_graph_archive_verifies_sha256(
368
  tmp_path: Path,
369
  monkeypatch,
 
414
  )
415
 
416
 
417
+ def test_local_graph_archive_checksum_is_verified(tmp_path: Path) -> None:
418
+ archive = tmp_path / "wiki-graph-runtime.tar.gz"
419
+ archive.write_bytes(b"not the shipped runtime archive")
420
+
421
+ with pytest.raises(ValueError, match="local graph archive checksum mismatch"):
422
+ ci._verify_local_graph_archive(archive, requested_install_mode="runtime")
423
+
424
+
425
  def test_custom_graph_url_requires_checksum_or_explicit_opt_out(
426
  tmp_path: Path,
427
  monkeypatch,
 
443
  assert rc == 1
444
 
445
 
446
+ def test_custom_graph_url_bypasses_local_archive(
447
+ tmp_path: Path,
448
+ monkeypatch,
449
+ ) -> None:
450
+ archive = _write_graph_archive(tmp_path)
451
+ archive_bytes = archive.read_bytes()
452
+ calls: list[dict[str, object]] = []
453
+
454
+ monkeypatch.setattr(
455
+ ci,
456
+ "_find_local_graph_archive",
457
+ lambda _mode: (_ for _ in ()).throw(
458
+ AssertionError("explicit graph_url must not use local archive")
459
+ ),
460
+ )
461
+
462
+ def fake_download(destination: Path, **kwargs: object) -> None:
463
+ calls.append(dict(kwargs))
464
+ destination.write_bytes(archive_bytes)
465
+
466
+ monkeypatch.setattr(ci, "_download_graph_archive", fake_download)
467
+ monkeypatch.setattr(ci, "_install_graph_entity_overlay", lambda *_a, **_k: None)
468
+
469
+ rc = ci.build_graph(
470
+ tmp_path / "home",
471
+ graph_url="https://example.invalid/custom-wiki-graph.tar.gz",
472
+ graph_sha256=hashlib.sha256(archive_bytes).hexdigest(),
473
+ )
474
+
475
+ assert rc == 0
476
+ assert calls == [
477
+ {
478
+ "url": "https://example.invalid/custom-wiki-graph.tar.gz",
479
+ "expected_sha256": hashlib.sha256(archive_bytes).hexdigest(),
480
+ }
481
+ ]
482
+
483
+
484
  def test_main_with_graph_flag_installs_prebuilt_graph(
485
  tmp_path: Path,
486
  monkeypatch,
 
495
  lambda _install_mode="runtime": archive,
496
  raising=False,
497
  )
498
+ monkeypatch.setattr(ci, "_verify_local_graph_archive", lambda *_a, **_k: None)
499
  monkeypatch.setattr(
500
  ci,
501
  "_download_graph_archive",
 
561
  raising=False,
562
  )
563
  monkeypatch.setattr(ci, "_find_local_graph_entity_overlay", lambda: overlay)
564
+ monkeypatch.setattr(ci, "_verify_local_graph_archive", lambda *_a, **_k: None)
565
 
566
  assert ci.build_graph(claude) == 0
567
 
 
611
  },
612
  }),
613
  )
614
+ index_path = tmp_path / "runtime-dashboard-neighborhoods.sqlite3"
615
+ _write_dashboard_index(index_path)
616
+ _tar_bytes(
617
+ tf,
618
+ "graphify-out/dashboard-neighborhoods.sqlite3",
619
+ index_path.read_bytes(),
620
+ )
621
  _tar_text(tf, "external-catalogs/skills-sh/catalog.json", "{}")
622
  _tar_text(tf, "index.md", "# Wiki\n")
623
  _tar_text(tf, "entities/harnesses/text-to-cad.md", "# Text to CAD\n")
 
629
  "_find_local_graph_archive",
630
  lambda _install_mode="runtime": archive,
631
  )
632
+ monkeypatch.setattr(ci, "_verify_local_graph_archive", lambda *_a, **_k: None)
633
 
634
  assert ci.build_graph(claude) == 0
635
  assert (
 
661
  "_find_local_graph_archive",
662
  lambda _install_mode="runtime": archive,
663
  )
664
+ monkeypatch.setattr(ci, "_verify_local_graph_archive", lambda *_a, **_k: None)
665
 
666
  assert ci.build_graph(claude) == 1
667
  assert not (claude / "skill-wiki" / "graphify-out" / "graph.json").exists()
 
704
  }),
705
  encoding="utf-8",
706
  )
707
+ _write_dashboard_index(graph_out / "dashboard-neighborhoods.sqlite3")
708
  external = wiki / "external-catalogs" / "skills-sh"
709
  external.mkdir(parents=True)
710
  (external / "catalog.json").write_text("{}", encoding="utf-8")
 
735
  "_find_local_graph_archive",
736
  lambda _install_mode="runtime": archive,
737
  )
738
+ monkeypatch.setattr(ci, "_verify_local_graph_archive", lambda *_a, **_k: None)
739
 
740
  assert ci.main([
741
  "--graph",
 
764
  "_find_local_graph_archive",
765
  lambda _install_mode="runtime": archive,
766
  )
767
+ monkeypatch.setattr(ci, "_verify_local_graph_archive", lambda *_a, **_k: None)
768
 
769
  assert ci.build_graph(claude) == 1
770
  assert not (tmp_path / "evil.txt").exists()
src/tests/test_ctx_monitor.py CHANGED
@@ -4,9 +4,14 @@ from __future__ import annotations
4
 
5
  import http.client
6
  import json
 
 
 
7
  import threading
 
8
  import urllib.error
9
  import urllib.request
 
10
  from pathlib import Path
11
 
12
  import pytest
@@ -21,6 +26,7 @@ def fake_claude(tmp_path: Path, monkeypatch) -> Path:
21
  claude = tmp_path / ".claude"
22
  (claude / "skill-quality").mkdir(parents=True)
23
  monkeypatch.setattr(cm, "_claude_dir", lambda: claude)
 
24
  return claude
25
 
26
 
@@ -60,6 +66,15 @@ def _write_mcp_sidecar(claude: Path, slug: str, body: dict) -> None:
60
  (mcp_dir / f"{slug}.json").write_text(json.dumps(body), encoding="utf-8")
61
 
62
 
 
 
 
 
 
 
 
 
 
63
  def test_read_jsonl_skips_non_object_lines(tmp_path: Path) -> None:
64
  path = tmp_path / "events.jsonl"
65
  path.write_text(
@@ -1254,7 +1269,10 @@ def test_graph_neighborhood_rejects_unsafe_slug() -> None:
1254
  assert result == {"nodes": [], "edges": [], "center": None}
1255
 
1256
 
1257
- def test_graph_neighborhood_supports_mcp_nodes(monkeypatch) -> None:
 
 
 
1258
  import networkx as nx
1259
  import sys
1260
 
@@ -1274,7 +1292,10 @@ def test_graph_neighborhood_supports_mcp_nodes(monkeypatch) -> None:
1274
  assert result["nodes"][0]["data"]["type"] == "mcp-server"
1275
 
1276
 
1277
- def test_graph_neighborhood_resolves_partial_slug(monkeypatch) -> None:
 
 
 
1278
  import networkx as nx
1279
 
1280
  G = nx.Graph()
@@ -1307,6 +1328,7 @@ def test_graph_neighborhood_resolves_partial_slug(monkeypatch) -> None:
1307
 
1308
 
1309
  def test_graph_neighborhood_sizes_nodes_by_score_usage_and_popularity(
 
1310
  monkeypatch: pytest.MonkeyPatch,
1311
  ) -> None:
1312
  import networkx as nx
@@ -1430,7 +1452,474 @@ def test_graph_helpers_reuse_graph_loaded_from_same_file(
1430
  assert calls == [graph_file]
1431
 
1432
 
1433
- def test_graph_neighborhood_empty_when_graph_absent(monkeypatch) -> None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1434
  # Force load_graph to raise so the helper returns the empty shape
1435
  # deterministically, independent of whether the user's graph is built.
1436
  import ctx_monitor as cm_mod
@@ -1471,6 +1960,22 @@ def test_render_home_shows_stat_grid_even_with_no_sessions(fake_claude: Path) ->
1471
  assert "No sessions recorded" in html_out or "Recent sessions" in html_out
1472
 
1473
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1474
  def test_render_skills_emits_sidebar_filters(fake_claude: Path) -> None:
1475
  _write_sidecar(fake_claude, "a", {"slug": "a", "grade": "A", "raw_score": 0.9,
1476
  "subject_type": "skill"})
@@ -1679,6 +2184,58 @@ def test_entity_upsert_api_writes_wiki_page_and_queues_graph_refresh(
1679
  server.server_close()
1680
 
1681
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1682
  def test_entity_delete_api_removes_wiki_page_and_queues_graph_refresh(
1683
  fake_claude: Path,
1684
  monkeypatch: pytest.MonkeyPatch,
@@ -1710,17 +2267,34 @@ def test_entity_delete_api_removes_wiki_page_and_queues_graph_refresh(
1710
  wiki_queue.queue_db_path(fake_claude / "skill-wiki"),
1711
  limit=10,
1712
  )
1713
- assert [job.kind for job in jobs[:2]] == [
1714
- wiki_queue.GRAPH_EXPORT_JOB,
1715
- wiki_queue.ENTITY_UPSERT_JOB,
1716
- ]
1717
- assert jobs[1].payload["action"] == "delete"
1718
  finally:
1719
  server.shutdown()
1720
  thread.join(timeout=5)
1721
  server.server_close()
1722
 
1723
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1724
  def test_render_kpi_empty_state(fake_claude: Path) -> None:
1725
  """With no sidecars, /kpi must render a helpful empty state, not 500."""
1726
  html_out = cm._render_kpi()
 
4
 
5
  import http.client
6
  import json
7
+ import os
8
+ import sqlite3
9
+ import tarfile
10
  import threading
11
+ import time
12
  import urllib.error
13
  import urllib.request
14
+ import zlib
15
  from pathlib import Path
16
 
17
  import pytest
 
26
  claude = tmp_path / ".claude"
27
  (claude / "skill-quality").mkdir(parents=True)
28
  monkeypatch.setattr(cm, "_claude_dir", lambda: claude)
29
+ monkeypatch.setattr(cm, "_dashboard_graph_index_archives", lambda: [])
30
  return claude
31
 
32
 
 
66
  (mcp_dir / f"{slug}.json").write_text(json.dumps(body), encoding="utf-8")
67
 
68
 
69
+ def _write_graph_manifest(claude: Path, export_id: str) -> None:
70
+ graph_dir = claude / "skill-wiki" / "graphify-out"
71
+ graph_dir.mkdir(parents=True, exist_ok=True)
72
+ (graph_dir / "graph-export-manifest.json").write_text(
73
+ json.dumps({"version": 1, "export_id": export_id}),
74
+ encoding="utf-8",
75
+ )
76
+
77
+
78
  def test_read_jsonl_skips_non_object_lines(tmp_path: Path) -> None:
79
  path = tmp_path / "events.jsonl"
80
  path.write_text(
 
1269
  assert result == {"nodes": [], "edges": [], "center": None}
1270
 
1271
 
1272
+ def test_graph_neighborhood_supports_mcp_nodes(
1273
+ fake_claude: Path,
1274
+ monkeypatch,
1275
+ ) -> None:
1276
  import networkx as nx
1277
  import sys
1278
 
 
1292
  assert result["nodes"][0]["data"]["type"] == "mcp-server"
1293
 
1294
 
1295
+ def test_graph_neighborhood_resolves_partial_slug(
1296
+ fake_claude: Path,
1297
+ monkeypatch,
1298
+ ) -> None:
1299
  import networkx as nx
1300
 
1301
  G = nx.Graph()
 
1328
 
1329
 
1330
  def test_graph_neighborhood_sizes_nodes_by_score_usage_and_popularity(
1331
+ fake_claude: Path,
1332
  monkeypatch: pytest.MonkeyPatch,
1333
  ) -> None:
1334
  import networkx as nx
 
1452
  assert calls == [graph_file]
1453
 
1454
 
1455
+ def test_graph_neighborhood_uses_dashboard_index_without_full_graph_load(
1456
+ fake_claude: Path,
1457
+ monkeypatch: pytest.MonkeyPatch,
1458
+ ) -> None:
1459
+ _write_graph_manifest(fake_claude, "test-export")
1460
+ index_path = fake_claude / "skill-wiki" / "graphify-out" / "dashboard-neighborhoods.sqlite3"
1461
+ index_path.parent.mkdir(parents=True, exist_ok=True)
1462
+ conn = sqlite3.connect(index_path)
1463
+ try:
1464
+ conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
1465
+ conn.execute(
1466
+ "CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
1467
+ "description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
1468
+ )
1469
+ conn.execute(
1470
+ "CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
1471
+ "PRIMARY KEY(slug,type,node_id))"
1472
+ )
1473
+ conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
1474
+ conn.executemany(
1475
+ "INSERT INTO meta VALUES(?,?)",
1476
+ [
1477
+ ("max_degree", "10"),
1478
+ ("export_id", json.dumps("test-export")),
1479
+ ("nodes_count", "2"),
1480
+ ("edges_count", "1"),
1481
+ ],
1482
+ )
1483
+ conn.executemany(
1484
+ "INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
1485
+ [
1486
+ ("skill:python-patterns", "python-patterns", "skill", '["python"]', "", 0.9, 0.1, 10),
1487
+ ("skill:fastapi-pro", "fastapi-pro", "skill", '["python","api"]', "", 0.8, 0.0, 4),
1488
+ ],
1489
+ )
1490
+ conn.executemany(
1491
+ "INSERT INTO slug_index VALUES(?,?,?)",
1492
+ [
1493
+ ("python-patterns", "skill", "skill:python-patterns"),
1494
+ ("fastapi-pro", "skill", "skill:fastapi-pro"),
1495
+ ],
1496
+ )
1497
+ payload = zlib.compress(json.dumps([
1498
+ {
1499
+ "target": "skill:fastapi-pro",
1500
+ "weight": 0.8,
1501
+ "shared_tags": ["python"],
1502
+ "reasons": ["semantic"],
1503
+ }
1504
+ ]).encode("utf-8"))
1505
+ conn.execute("INSERT INTO neighbors VALUES(?,?)", ("skill:python-patterns", payload))
1506
+ conn.commit()
1507
+ finally:
1508
+ conn.close()
1509
+
1510
+ monkeypatch.setattr(
1511
+ cm,
1512
+ "_load_dashboard_graph",
1513
+ lambda: (_ for _ in ()).throw(AssertionError("full graph loaded")),
1514
+ )
1515
+
1516
+ result = cm._graph_neighborhood("python-patterns", entity_type="skill")
1517
+
1518
+ assert result["center"] == "skill:python-patterns"
1519
+ assert [node["data"]["id"] for node in result["nodes"]] == [
1520
+ "skill:python-patterns",
1521
+ "skill:fastapi-pro",
1522
+ ]
1523
+ assert result["edges"][0]["data"]["shared_tags"] == ["python"]
1524
+ assert cm._graph_stats() == {"nodes": 2, "edges": 1, "available": True}
1525
+ assert cm._wiki_stats() == {
1526
+ "skills": 2,
1527
+ "agents": 0,
1528
+ "mcps": 0,
1529
+ "harnesses": 0,
1530
+ "total": 2,
1531
+ "split_known": True,
1532
+ }
1533
+
1534
+
1535
+ def test_graph_index_honors_requested_type_on_exact_slug(
1536
+ fake_claude: Path,
1537
+ ) -> None:
1538
+ _write_graph_manifest(fake_claude, "test-export")
1539
+ index_path = fake_claude / "skill-wiki" / "graphify-out" / "dashboard-neighborhoods.sqlite3"
1540
+ index_path.parent.mkdir(parents=True, exist_ok=True)
1541
+ conn = sqlite3.connect(index_path)
1542
+ try:
1543
+ conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
1544
+ conn.execute(
1545
+ "CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
1546
+ "description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
1547
+ )
1548
+ conn.execute(
1549
+ "CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
1550
+ "PRIMARY KEY(slug,type,node_id))"
1551
+ )
1552
+ conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
1553
+ conn.executemany(
1554
+ "INSERT INTO meta VALUES(?,?)",
1555
+ [("max_degree", "1"), ("top_k", "40"), ("export_id", json.dumps("test-export"))],
1556
+ )
1557
+ conn.executemany(
1558
+ "INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
1559
+ [
1560
+ ("skill:github", "github", "skill", "[]", "", None, None, 0),
1561
+ ("mcp-server:github", "github", "mcp-server", "[]", "", None, None, 0),
1562
+ ],
1563
+ )
1564
+ conn.executemany(
1565
+ "INSERT INTO slug_index VALUES(?,?,?)",
1566
+ [
1567
+ ("github", "skill", "skill:github"),
1568
+ ("github", "mcp-server", "mcp-server:github"),
1569
+ ],
1570
+ )
1571
+ conn.executemany(
1572
+ "INSERT INTO neighbors VALUES(?,?)",
1573
+ [
1574
+ ("skill:github", zlib.compress(b"[]")),
1575
+ ("mcp-server:github", zlib.compress(b"[]")),
1576
+ ],
1577
+ )
1578
+ conn.commit()
1579
+ finally:
1580
+ conn.close()
1581
+
1582
+ result = cm._graph_neighborhood("github", entity_type="skill")
1583
+
1584
+ assert result["center"] == "skill:github"
1585
+
1586
+
1587
+ def test_graph_index_matches_fuzzy_slug_resolution(
1588
+ fake_claude: Path,
1589
+ ) -> None:
1590
+ _write_graph_manifest(fake_claude, "test-export")
1591
+ index_path = fake_claude / "skill-wiki" / "graphify-out" / "dashboard-neighborhoods.sqlite3"
1592
+ index_path.parent.mkdir(parents=True, exist_ok=True)
1593
+ conn = sqlite3.connect(index_path)
1594
+ try:
1595
+ conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
1596
+ conn.execute(
1597
+ "CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
1598
+ "description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
1599
+ )
1600
+ conn.execute(
1601
+ "CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
1602
+ "PRIMARY KEY(slug,type,node_id))"
1603
+ )
1604
+ conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
1605
+ conn.executemany(
1606
+ "INSERT INTO meta VALUES(?,?)",
1607
+ [("max_degree", "1"), ("top_k", "40"), ("export_id", json.dumps("test-export"))],
1608
+ )
1609
+ conn.execute(
1610
+ "INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
1611
+ ("skill:github-actions", "GitHub Actions", "skill", '["ci"]', "", None, None, 0),
1612
+ )
1613
+ conn.execute(
1614
+ "INSERT INTO slug_index VALUES(?,?,?)",
1615
+ ("github-actions", "skill", "skill:github-actions"),
1616
+ )
1617
+ conn.execute("INSERT INTO neighbors VALUES(?,?)", ("skill:github-actions", zlib.compress(b"[]")))
1618
+ conn.commit()
1619
+ finally:
1620
+ conn.close()
1621
+
1622
+ result = cm._graph_neighborhood("git hub", entity_type="skill")
1623
+
1624
+ assert result["center"] == "skill:github-actions"
1625
+ assert result["resolved"]["slug"] == "github-actions"
1626
+
1627
+
1628
+ def test_entity_subgraph_script_json_escapes_script_end_tag() -> None:
1629
+ graph_html = cm._render_entity_subgraph_svg(
1630
+ center="skill:evil",
1631
+ node_by_id={
1632
+ "skill:evil": {
1633
+ "label": "</script><script>alert(1)</script>",
1634
+ "type": "skill",
1635
+ },
1636
+ },
1637
+ edges=[],
1638
+ sidecar_by_id={},
1639
+ )
1640
+
1641
+ assert "</script><script>alert(1)</script>" not in graph_html
1642
+ assert "<\\/script>" in graph_html
1643
+
1644
+
1645
+ def test_graph_page_initial_query_escapes_script_end_tag() -> None:
1646
+ html_out = cm._render_graph("</script><script>alert(1)</script>")
1647
+
1648
+ assert "const initial = \"<\\/script>" in html_out
1649
+ assert "const initial = \"</script>" not in html_out
1650
+
1651
+
1652
+ def test_graph_neighborhood_extracts_missing_dashboard_index_from_archive(
1653
+ fake_claude: Path,
1654
+ tmp_path: Path,
1655
+ monkeypatch: pytest.MonkeyPatch,
1656
+ ) -> None:
1657
+ seed = tmp_path / "dashboard-neighborhoods.sqlite3"
1658
+ conn = sqlite3.connect(seed)
1659
+ try:
1660
+ conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
1661
+ conn.execute(
1662
+ "CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
1663
+ "description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
1664
+ )
1665
+ conn.execute(
1666
+ "CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
1667
+ "PRIMARY KEY(slug,type,node_id))"
1668
+ )
1669
+ conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
1670
+ conn.executemany(
1671
+ "INSERT INTO meta VALUES(?,?)",
1672
+ [
1673
+ ("max_degree", "10"),
1674
+ ("export_id", json.dumps("archive-export")),
1675
+ ("nodes_count", "1"),
1676
+ ("edges_count", "0"),
1677
+ ("top_k", "40"),
1678
+ ],
1679
+ )
1680
+ conn.execute(
1681
+ "INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
1682
+ ("skill:python-patterns", "python-patterns", "skill", '["python"]', "", 0.9, 0.1, 10),
1683
+ )
1684
+ conn.execute(
1685
+ "INSERT INTO slug_index VALUES(?,?,?)",
1686
+ ("python-patterns", "skill", "skill:python-patterns"),
1687
+ )
1688
+ conn.execute(
1689
+ "INSERT INTO neighbors VALUES(?,?)",
1690
+ ("skill:python-patterns", zlib.compress(b"[]")),
1691
+ )
1692
+ conn.commit()
1693
+ finally:
1694
+ conn.close()
1695
+
1696
+ manifest = fake_claude / "skill-wiki" / "graphify-out" / "graph-export-manifest.json"
1697
+ manifest.parent.mkdir(parents=True)
1698
+ manifest.write_text(
1699
+ json.dumps({"version": 1, "export_id": "archive-export"}),
1700
+ encoding="utf-8",
1701
+ )
1702
+
1703
+ archive = tmp_path / "wiki-graph-runtime.tar.gz"
1704
+ with tarfile.open(archive, "w:gz") as tar:
1705
+ tar.add(seed, arcname="./graphify-out/dashboard-neighborhoods.sqlite3")
1706
+
1707
+ monkeypatch.setattr(cm, "_dashboard_graph_index_archives", lambda: [archive])
1708
+ monkeypatch.setattr(
1709
+ cm,
1710
+ "_load_dashboard_graph",
1711
+ lambda: (_ for _ in ()).throw(AssertionError("full graph loaded")),
1712
+ )
1713
+
1714
+ result = cm._graph_neighborhood("python-patterns", entity_type="skill")
1715
+
1716
+ assert result["center"] == "skill:python-patterns"
1717
+ assert (fake_claude / "skill-wiki" / "graphify-out" / "dashboard-neighborhoods.sqlite3").is_file()
1718
+
1719
+
1720
+ def test_dashboard_index_extraction_skips_archive_export_mismatch(
1721
+ fake_claude: Path,
1722
+ tmp_path: Path,
1723
+ monkeypatch: pytest.MonkeyPatch,
1724
+ ) -> None:
1725
+ graph_dir = fake_claude / "skill-wiki" / "graphify-out"
1726
+ graph_dir.mkdir(parents=True)
1727
+ (graph_dir / "graph-export-manifest.json").write_text(
1728
+ json.dumps({"version": 1, "export_id": "local-export"}),
1729
+ encoding="utf-8",
1730
+ )
1731
+ manifest = tmp_path / "graph-export-manifest.json"
1732
+ manifest.write_text(
1733
+ json.dumps({"version": 1, "export_id": "archive-export"}),
1734
+ encoding="utf-8",
1735
+ )
1736
+ seed = tmp_path / "dashboard-neighborhoods.sqlite3"
1737
+ seed.write_bytes(b"should-not-be-extracted")
1738
+ archive = tmp_path / "wiki-graph-runtime.tar.gz"
1739
+ with tarfile.open(archive, "w:gz") as tar:
1740
+ tar.add(manifest, arcname="./graphify-out/graph-export-manifest.json")
1741
+ tar.add(seed, arcname="./graphify-out/dashboard-neighborhoods.sqlite3")
1742
+
1743
+ monkeypatch.setattr(cm, "_dashboard_graph_index_archives", lambda: [archive])
1744
+ monkeypatch.setattr(
1745
+ cm,
1746
+ "_dashboard_index_matches_manifest",
1747
+ lambda path: (_ for _ in ()).throw(
1748
+ AssertionError(f"should not validate extracted index: {path}"),
1749
+ ),
1750
+ )
1751
+
1752
+ assert cm._ensure_dashboard_graph_index() is None
1753
+ assert not (graph_dir / "dashboard-neighborhoods.sqlite3").exists()
1754
+
1755
+
1756
+ def test_dashboard_index_extraction_skips_installed_graph_report(
1757
+ fake_claude: Path,
1758
+ monkeypatch: pytest.MonkeyPatch,
1759
+ ) -> None:
1760
+ graph_dir = fake_claude / "skill-wiki" / "graphify-out"
1761
+ graph_dir.mkdir(parents=True)
1762
+ (graph_dir / "graph-export-manifest.json").write_text(
1763
+ json.dumps({"version": 1, "export_id": "local-export"}),
1764
+ encoding="utf-8",
1765
+ )
1766
+ (graph_dir / "graph-report.md").write_text(
1767
+ "> Nodes: 12 | Edges: 34 | Communities: 2\n",
1768
+ encoding="utf-8",
1769
+ )
1770
+ monkeypatch.setattr(
1771
+ cm,
1772
+ "_dashboard_graph_index_archives",
1773
+ lambda: (_ for _ in ()).throw(AssertionError("archive scan should be skipped")),
1774
+ )
1775
+
1776
+ assert cm._ensure_dashboard_graph_index() is None
1777
+
1778
+
1779
+ def test_graph_neighborhood_bypasses_archive_index_when_runtime_overlays_exist(
1780
+ fake_claude: Path,
1781
+ monkeypatch: pytest.MonkeyPatch,
1782
+ ) -> None:
1783
+ import networkx as nx
1784
+
1785
+ overlay = fake_claude / "skill-wiki" / "graphify-out" / "entity-overlays.jsonl"
1786
+ overlay.parent.mkdir(parents=True)
1787
+ overlay.write_text('{"source":"test"}\n', encoding="utf-8")
1788
+ monkeypatch.setattr(
1789
+ cm,
1790
+ "_dashboard_graph_index_archives",
1791
+ lambda: (_ for _ in ()).throw(AssertionError("archive index should be bypassed")),
1792
+ )
1793
+ G = nx.Graph()
1794
+ G.add_node("skill:local-overlay", label="local-overlay", type="skill", tags=["local"])
1795
+ monkeypatch.setattr(cm, "_load_dashboard_graph", lambda: G)
1796
+
1797
+ result = cm._graph_neighborhood("local-overlay", entity_type="skill")
1798
+
1799
+ assert result["center"] == "skill:local-overlay"
1800
+
1801
+
1802
+ def test_graph_neighborhood_rejects_stale_dashboard_index(
1803
+ fake_claude: Path,
1804
+ monkeypatch: pytest.MonkeyPatch,
1805
+ ) -> None:
1806
+ import networkx as nx
1807
+
1808
+ graph_dir = fake_claude / "skill-wiki" / "graphify-out"
1809
+ graph_dir.mkdir(parents=True)
1810
+ (graph_dir / "graph-export-manifest.json").write_text(
1811
+ json.dumps({"version": 1, "export_id": "new-export"}),
1812
+ encoding="utf-8",
1813
+ )
1814
+ index_path = graph_dir / "dashboard-neighborhoods.sqlite3"
1815
+ conn = sqlite3.connect(index_path)
1816
+ try:
1817
+ conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
1818
+ conn.execute(
1819
+ "CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
1820
+ "description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
1821
+ )
1822
+ conn.execute(
1823
+ "CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
1824
+ "PRIMARY KEY(slug,type,node_id))"
1825
+ )
1826
+ conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
1827
+ conn.executemany("INSERT INTO meta VALUES(?,?)", [("export_id", json.dumps("old-export"))])
1828
+ conn.commit()
1829
+ finally:
1830
+ conn.close()
1831
+
1832
+ G = nx.Graph()
1833
+ G.add_node("skill:fallback", label="fallback", type="skill", tags=[])
1834
+ monkeypatch.setattr(cm, "_load_dashboard_graph", lambda: G)
1835
+
1836
+ result = cm._graph_neighborhood("fallback", entity_type="skill")
1837
+
1838
+ assert result["center"] == "skill:fallback"
1839
+ assert not index_path.exists()
1840
+
1841
+
1842
+ def test_graph_neighborhood_rejects_orphan_dashboard_index_without_manifest(
1843
+ fake_claude: Path,
1844
+ monkeypatch: pytest.MonkeyPatch,
1845
+ ) -> None:
1846
+ import networkx as nx
1847
+
1848
+ graph_dir = fake_claude / "skill-wiki" / "graphify-out"
1849
+ graph_dir.mkdir(parents=True)
1850
+ index_path = graph_dir / "dashboard-neighborhoods.sqlite3"
1851
+ conn = sqlite3.connect(index_path)
1852
+ try:
1853
+ conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
1854
+ conn.executemany("INSERT INTO meta VALUES(?,?)", [("export_id", json.dumps("old-export"))])
1855
+ conn.commit()
1856
+ finally:
1857
+ conn.close()
1858
+
1859
+ G = nx.Graph()
1860
+ G.add_node("skill:fallback", label="fallback", type="skill", tags=[])
1861
+ monkeypatch.setattr(cm, "_load_dashboard_graph", lambda: G)
1862
+
1863
+ result = cm._graph_neighborhood("fallback", entity_type="skill")
1864
+
1865
+ assert result["center"] == "skill:fallback"
1866
+ assert not index_path.exists()
1867
+
1868
+
1869
+ def test_graph_index_node_size_uses_live_sidecar_when_scores_missing(
1870
+ fake_claude: Path,
1871
+ ) -> None:
1872
+ _write_graph_manifest(fake_claude, "test-export")
1873
+ _write_sidecar(fake_claude, "python-patterns", {
1874
+ "slug": "python-patterns",
1875
+ "subject_type": "skill",
1876
+ "grade": "A",
1877
+ "score": 1.0,
1878
+ "signals": {"telemetry": {"score": 1.0}},
1879
+ })
1880
+ index_path = fake_claude / "skill-wiki" / "graphify-out" / "dashboard-neighborhoods.sqlite3"
1881
+ index_path.parent.mkdir(parents=True, exist_ok=True)
1882
+ conn = sqlite3.connect(index_path)
1883
+ try:
1884
+ conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
1885
+ conn.execute(
1886
+ "CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
1887
+ "description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
1888
+ )
1889
+ conn.execute(
1890
+ "CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
1891
+ "PRIMARY KEY(slug,type,node_id))"
1892
+ )
1893
+ conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
1894
+ conn.executemany(
1895
+ "INSERT INTO meta VALUES(?,?)",
1896
+ [("max_degree", "1"), ("top_k", "40"), ("export_id", json.dumps("test-export"))],
1897
+ )
1898
+ conn.execute(
1899
+ "INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
1900
+ ("skill:python-patterns", "python-patterns", "skill", "[]", "", None, None, 0),
1901
+ )
1902
+ conn.execute(
1903
+ "INSERT INTO slug_index VALUES(?,?,?)",
1904
+ ("python-patterns", "skill", "skill:python-patterns"),
1905
+ )
1906
+ conn.execute("INSERT INTO neighbors VALUES(?,?)", ("skill:python-patterns", zlib.compress(b"[]")))
1907
+ conn.commit()
1908
+ finally:
1909
+ conn.close()
1910
+
1911
+ result = cm._graph_neighborhood("python-patterns", entity_type="skill")
1912
+ node = result["nodes"][0]["data"]
1913
+
1914
+ assert node["size_signal"] > 0.7
1915
+ assert "quality 1.000" in node["size_reason"]
1916
+ assert "usage 1.000" in node["size_reason"]
1917
+
1918
+
1919
+ def test_graph_neighborhood_empty_when_graph_absent(
1920
+ fake_claude: Path,
1921
+ monkeypatch,
1922
+ ) -> None:
1923
  # Force load_graph to raise so the helper returns the empty shape
1924
  # deterministically, independent of whether the user's graph is built.
1925
  import ctx_monitor as cm_mod
 
1960
  assert "No sessions recorded" in html_out or "Recent sessions" in html_out
1961
 
1962
 
1963
+ def test_render_home_defers_sidecar_grade_scan(
1964
+ fake_claude: Path,
1965
+ monkeypatch: pytest.MonkeyPatch,
1966
+ ) -> None:
1967
+ def fail_scan() -> dict[str, int]:
1968
+ raise AssertionError("home page should not synchronously scan sidecars")
1969
+
1970
+ monkeypatch.setattr(cm, "_grade_distribution", fail_scan)
1971
+
1972
+ html_out = cm._render_home()
1973
+
1974
+ assert "/api/grades.json" in html_out
1975
+ assert "home-sidecar-count" in html_out
1976
+ assert "data-home-grade='A'" in html_out
1977
+
1978
+
1979
  def test_render_skills_emits_sidebar_filters(fake_claude: Path) -> None:
1980
  _write_sidecar(fake_claude, "a", {"slug": "a", "grade": "A", "raw_score": 0.9,
1981
  "subject_type": "skill"})
 
2184
  server.server_close()
2185
 
2186
 
2187
+ def test_entity_upsert_api_requires_confirmation_for_existing_page(
2188
+ fake_claude: Path,
2189
+ monkeypatch: pytest.MonkeyPatch,
2190
+ ) -> None:
2191
+ entity_path = (
2192
+ fake_claude / "skill-wiki" / "entities" / "agents" / "custom-reviewer.md"
2193
+ )
2194
+ entity_path.parent.mkdir(parents=True)
2195
+ entity_path.write_text(
2196
+ "---\ntitle: Custom Reviewer\ntype: agent\ntags: [python]\n"
2197
+ "---\n# Custom Reviewer\n\nOriginal body.\n",
2198
+ encoding="utf-8",
2199
+ )
2200
+ server, thread, port = _serve_monitor(monkeypatch)
2201
+ try:
2202
+ status, payload = _post_json(
2203
+ port,
2204
+ "/api/entity/upsert",
2205
+ {
2206
+ "slug": "custom-reviewer",
2207
+ "entity_type": "agent",
2208
+ "title": "Custom Reviewer",
2209
+ "body": "# Custom Reviewer\n\nReplacement body.\n",
2210
+ },
2211
+ token="test-token",
2212
+ )
2213
+ assert status == 400
2214
+ assert payload["ok"] is False
2215
+ assert "confirm_update=true" in payload["detail"]
2216
+ assert "Original body." in entity_path.read_text(encoding="utf-8")
2217
+
2218
+ status, payload = _post_json(
2219
+ port,
2220
+ "/api/entity/upsert",
2221
+ {
2222
+ "slug": "custom-reviewer",
2223
+ "entity_type": "agent",
2224
+ "title": "Custom Reviewer",
2225
+ "body": "# Custom Reviewer\n\nReplacement body.\n",
2226
+ "confirm_update": "true",
2227
+ },
2228
+ token="test-token",
2229
+ )
2230
+ assert status == 200
2231
+ assert payload["ok"] is True
2232
+ assert "Replacement body." in entity_path.read_text(encoding="utf-8")
2233
+ finally:
2234
+ server.shutdown()
2235
+ thread.join(timeout=5)
2236
+ server.server_close()
2237
+
2238
+
2239
  def test_entity_delete_api_removes_wiki_page_and_queues_graph_refresh(
2240
  fake_claude: Path,
2241
  monkeypatch: pytest.MonkeyPatch,
 
2267
  wiki_queue.queue_db_path(fake_claude / "skill-wiki"),
2268
  limit=10,
2269
  )
2270
+ assert [job.kind for job in jobs] == [wiki_queue.ENTITY_UPSERT_JOB]
2271
+ assert jobs[0].payload["action"] == "delete"
 
 
 
2272
  finally:
2273
  server.shutdown()
2274
  thread.join(timeout=5)
2275
  server.server_close()
2276
 
2277
 
2278
+ def test_sidecar_cache_invalidates_on_file_rewrite(fake_claude: Path) -> None:
2279
+ cm._SIDECAR_INDEX_CACHE_KEY = None
2280
+ cm._SIDECAR_INDEX_CACHE_VALUE = None
2281
+ path = fake_claude / "skill-quality" / "alpha.json"
2282
+ path.parent.mkdir(parents=True, exist_ok=True)
2283
+ path.write_text(
2284
+ json.dumps({"slug": "alpha", "subject_type": "skill", "grade": "A"}),
2285
+ encoding="utf-8",
2286
+ )
2287
+ assert cm._all_sidecars()[0]["grade"] == "A"
2288
+
2289
+ path.write_text(
2290
+ json.dumps({"slug": "alpha", "subject_type": "skill", "grade": "F"}),
2291
+ encoding="utf-8",
2292
+ )
2293
+ os.utime(path, (time.time() + 2.0, time.time() + 2.0))
2294
+
2295
+ assert cm._all_sidecars()[0]["grade"] == "F"
2296
+
2297
+
2298
  def test_render_kpi_empty_state(fake_claude: Path) -> None:
2299
  """With no sidecars, /kpi must render a helpful empty state, not 500."""
2300
  html_out = cm._render_kpi()
src/tests/test_ctx_monitor_3type.py CHANGED
@@ -79,6 +79,7 @@ def wiki_3type(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
79
  )
80
 
81
  monkeypatch.setattr(_cm, "_wiki_dir", lambda: wiki)
 
82
  return wiki
83
 
84
 
@@ -888,6 +889,7 @@ class TestRenderGraphSidebar:
888
 
889
  def test_graph_neighborhood_filter_tokens_include_edge_shared_tags(
890
  self,
 
891
  monkeypatch,
892
  ):
893
  graph = nx.Graph()
 
79
  )
80
 
81
  monkeypatch.setattr(_cm, "_wiki_dir", lambda: wiki)
82
+ monkeypatch.setattr(_cm, "_dashboard_graph_index_archives", lambda: [])
83
  return wiki
84
 
85
 
 
889
 
890
  def test_graph_neighborhood_filter_tokens_include_edge_shared_tags(
891
  self,
892
+ wiki_3type,
893
  monkeypatch,
894
  ):
895
  graph = nx.Graph()
src/tests/test_ctx_monitor_browser.py CHANGED
@@ -39,6 +39,7 @@ def fake_claude(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
39
  claude = tmp_path / ".claude"
40
  (claude / "skill-quality").mkdir(parents=True)
41
  monkeypatch.setattr(cm, "_claude_dir", lambda: claude)
 
42
  return claude
43
 
44
 
 
39
  claude = tmp_path / ".claude"
40
  (claude / "skill-quality").mkdir(parents=True)
41
  monkeypatch.setattr(cm, "_claude_dir", lambda: claude)
42
+ monkeypatch.setattr(cm, "_dashboard_graph_index_archives", lambda: [])
43
  return claude
44
 
45
 
src/tests/test_incremental_attach_az_flow.py CHANGED
@@ -116,6 +116,7 @@ def test_entity_onboarding_incremental_attach_a_to_z(
116
  monkeypatch.setattr(mcp_add, "check_intake", _allow_intake)
117
  monkeypatch.setattr(mcp_add, "record_embedding", lambda **_kwargs: None)
118
  monkeypatch.setattr(cm, "_claude_dir", lambda: claude)
 
119
 
120
  source = tmp_path / "SKILL.md"
121
  source.write_text(
 
116
  monkeypatch.setattr(mcp_add, "check_intake", _allow_intake)
117
  monkeypatch.setattr(mcp_add, "record_embedding", lambda **_kwargs: None)
118
  monkeypatch.setattr(cm, "_claude_dir", lambda: claude)
119
+ monkeypatch.setattr(cm, "_dashboard_graph_index_archives", lambda: [])
120
 
121
  source = tmp_path / "SKILL.md"
122
  source.write_text(
src/tests/test_mcp_add.py CHANGED
@@ -30,6 +30,7 @@ if str(SRC_DIR) not in sys.path:
30
  sys.path.insert(0, str(SRC_DIR))
31
 
32
  from mcp_entity import McpRecord # noqa: E402
 
33
 
34
 
35
  # ---------------------------------------------------------------------------
@@ -197,85 +198,85 @@ class TestAddMcpIdempotency:
197
  assert len(result2["merged_sources"]) == 1
198
 
199
 
200
- class TestAddMcpSourceMerging:
201
- def test_two_different_sources_merged_and_sorted(
202
- self, patched_mcp_add: Any, wiki_dir: Path
203
- ) -> None:
204
- record_a = _make_record(name="github-mcp", sources=["awesome-mcp"])
205
  record_b = _make_record(name="github-mcp", sources=["pulsemcp"])
206
 
207
  patched_mcp_add.add_mcp(record=record_a, wiki_path=wiki_dir)
208
  result2 = patched_mcp_add.add_mcp(record=record_b, wiki_path=wiki_dir)
209
 
210
- assert sorted(result2["merged_sources"]) == ["awesome-mcp", "pulsemcp"]
211
- assert result2["is_new_page"] is False
212
-
213
-
214
- class TestAddMcpExistingReview:
215
- def test_review_existing_skips_and_preserves_existing_page(
216
- self, patched_mcp_add: Any, wiki_dir: Path
217
- ) -> None:
218
- record_a = _make_record(
219
- name="github-mcp",
220
- sources=["awesome-mcp"],
221
- description="A GitHub MCP server with repository management support.",
222
- )
223
- patched_mcp_add.add_mcp(record=record_a, wiki_path=wiki_dir)
224
- page = wiki_dir / "entities" / "mcp-servers" / "g" / "github-mcp.md"
225
- original_text = page.read_text(encoding="utf-8")
226
-
227
- record_b = _make_record(
228
- name="github-mcp",
229
- sources=["pulsemcp"],
230
- description="GitHub MCP.",
231
- )
232
- result = patched_mcp_add.add_mcp(
233
- record=record_b,
234
- wiki_path=wiki_dir,
235
- review_existing=True,
236
- )
237
-
238
- assert result["is_new_page"] is False
239
- assert result["skipped"] is True
240
- assert result["update_required"] is True
241
- assert result["merged_sources"] == ["awesome-mcp", "pulsemcp"]
242
- assert "Existing mcp-server already exists: github-mcp" in result["update_review"]
243
- assert "Benefits:" in result["update_review"]
244
- assert page.read_text(encoding="utf-8") == original_text
245
-
246
- def test_update_existing_applies_reviewed_merge(
247
- self, patched_mcp_add: Any, wiki_dir: Path
248
- ) -> None:
249
- record_a = _make_record(name="github-mcp", sources=["awesome-mcp"])
250
- patched_mcp_add.add_mcp(record=record_a, wiki_path=wiki_dir)
251
-
252
- record_b = _make_record(
253
- name="github-mcp",
254
- sources=["pulsemcp"],
255
- description="A longer GitHub MCP server description with more detail.",
256
- )
257
- result = patched_mcp_add.add_mcp(
258
- record=record_b,
259
- wiki_path=wiki_dir,
260
- review_existing=True,
261
- update_existing=True,
262
- )
263
-
264
- page = wiki_dir / "entities" / "mcp-servers" / "g" / "github-mcp.md"
265
- text = page.read_text(encoding="utf-8")
266
- _, fm_block, _ = text.split("---", 2)
267
- fm = yaml.safe_load(fm_block)
268
- assert isinstance(fm, dict)
269
- assert result["is_new_page"] is False
270
- assert result["skipped"] is False
271
- assert result["merged_sources"] == ["awesome-mcp", "pulsemcp"]
272
- assert fm["sources"] == ["awesome-mcp", "pulsemcp"]
273
- assert fm["description"] == record_b.description
274
-
275
-
276
- # ---------------------------------------------------------------------------
277
- # dry_run
278
- # ---------------------------------------------------------------------------
279
 
280
 
281
  class TestAddMcpDryRun:
@@ -545,8 +546,15 @@ class TestCrossSourceCanonicalKeyDedup:
545
  # not its own slug-based path.
546
  assert result2["is_new_page"] is False
547
  assert result2["path"] == str(first_path)
 
548
  assert result2["merged_sources"] == ["awesome-mcp", "pulsemcp"]
549
 
 
 
 
 
 
 
550
  # And only ONE entity file exists in the wiki.
551
  all_entities = list(
552
  (wiki_dir / "entities" / "mcp-servers").rglob("*.md")
 
30
  sys.path.insert(0, str(SRC_DIR))
31
 
32
  from mcp_entity import McpRecord # noqa: E402
33
+ from ctx.core.wiki import wiki_queue # noqa: E402
34
 
35
 
36
  # ---------------------------------------------------------------------------
 
198
  assert len(result2["merged_sources"]) == 1
199
 
200
 
201
+ class TestAddMcpSourceMerging:
202
+ def test_two_different_sources_merged_and_sorted(
203
+ self, patched_mcp_add: Any, wiki_dir: Path
204
+ ) -> None:
205
+ record_a = _make_record(name="github-mcp", sources=["awesome-mcp"])
206
  record_b = _make_record(name="github-mcp", sources=["pulsemcp"])
207
 
208
  patched_mcp_add.add_mcp(record=record_a, wiki_path=wiki_dir)
209
  result2 = patched_mcp_add.add_mcp(record=record_b, wiki_path=wiki_dir)
210
 
211
+ assert sorted(result2["merged_sources"]) == ["awesome-mcp", "pulsemcp"]
212
+ assert result2["is_new_page"] is False
213
+
214
+
215
+ class TestAddMcpExistingReview:
216
+ def test_review_existing_skips_and_preserves_existing_page(
217
+ self, patched_mcp_add: Any, wiki_dir: Path
218
+ ) -> None:
219
+ record_a = _make_record(
220
+ name="github-mcp",
221
+ sources=["awesome-mcp"],
222
+ description="A GitHub MCP server with repository management support.",
223
+ )
224
+ patched_mcp_add.add_mcp(record=record_a, wiki_path=wiki_dir)
225
+ page = wiki_dir / "entities" / "mcp-servers" / "g" / "github-mcp.md"
226
+ original_text = page.read_text(encoding="utf-8")
227
+
228
+ record_b = _make_record(
229
+ name="github-mcp",
230
+ sources=["pulsemcp"],
231
+ description="GitHub MCP.",
232
+ )
233
+ result = patched_mcp_add.add_mcp(
234
+ record=record_b,
235
+ wiki_path=wiki_dir,
236
+ review_existing=True,
237
+ )
238
+
239
+ assert result["is_new_page"] is False
240
+ assert result["skipped"] is True
241
+ assert result["update_required"] is True
242
+ assert result["merged_sources"] == ["awesome-mcp", "pulsemcp"]
243
+ assert "Existing mcp-server already exists: github-mcp" in result["update_review"]
244
+ assert "Benefits:" in result["update_review"]
245
+ assert page.read_text(encoding="utf-8") == original_text
246
+
247
+ def test_update_existing_applies_reviewed_merge(
248
+ self, patched_mcp_add: Any, wiki_dir: Path
249
+ ) -> None:
250
+ record_a = _make_record(name="github-mcp", sources=["awesome-mcp"])
251
+ patched_mcp_add.add_mcp(record=record_a, wiki_path=wiki_dir)
252
+
253
+ record_b = _make_record(
254
+ name="github-mcp",
255
+ sources=["pulsemcp"],
256
+ description="A longer GitHub MCP server description with more detail.",
257
+ )
258
+ result = patched_mcp_add.add_mcp(
259
+ record=record_b,
260
+ wiki_path=wiki_dir,
261
+ review_existing=True,
262
+ update_existing=True,
263
+ )
264
+
265
+ page = wiki_dir / "entities" / "mcp-servers" / "g" / "github-mcp.md"
266
+ text = page.read_text(encoding="utf-8")
267
+ _, fm_block, _ = text.split("---", 2)
268
+ fm = yaml.safe_load(fm_block)
269
+ assert isinstance(fm, dict)
270
+ assert result["is_new_page"] is False
271
+ assert result["skipped"] is False
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
+ # ---------------------------------------------------------------------------
278
+ # dry_run
279
+ # ---------------------------------------------------------------------------
280
 
281
 
282
  class TestAddMcpDryRun:
 
546
  # not its own slug-based path.
547
  assert result2["is_new_page"] is False
548
  assert result2["path"] == str(first_path)
549
+ assert result2["slug"] == first_path.stem
550
  assert result2["merged_sources"] == ["awesome-mcp", "pulsemcp"]
551
 
552
+ jobs = wiki_queue.list_jobs(wiki_queue.queue_db_path(wiki_dir))
553
+ assert jobs[-1].payload["slug"] == first_path.stem
554
+ assert jobs[-1].payload["entity_path"] == str(
555
+ first_path.relative_to(wiki_dir)
556
+ ).replace("\\", "/")
557
+
558
  # And only ONE entity file exists in the wiki.
559
  all_entities = list(
560
  (wiki_dir / "entities" / "mcp-servers").rglob("*.md")
src/tests/test_validate_graph_artifacts.py CHANGED
@@ -2,7 +2,9 @@ from __future__ import annotations
2
 
3
  import gzip
4
  import json
 
5
  import tarfile
 
6
  from io import BytesIO
7
  from pathlib import Path
8
  from typing import Any
@@ -35,6 +37,69 @@ def _add_text(tf: tarfile.TarFile, name: str, text: str) -> None:
35
  tf.addfile(info, BytesIO(payload))
36
 
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  def _write_catalog(graph_dir: Path, *, converted_path: str | None = None) -> None:
39
  skill = {
40
  "ctx_slug": "skills-sh-example-skill",
@@ -101,6 +166,11 @@ def _write_runtime_archive(
101
  "counts": {"nodes": 2, "edges": 1, "communities": 1},
102
  }),
103
  )
 
 
 
 
 
104
  _add_text(tf, "external-catalogs/skills-sh/catalog.json", "{}")
105
  if include_queue:
106
  _add_text(tf, ".ctx/wiki-queue.sqlite3", "not a shipped artifact\n")
@@ -181,6 +251,11 @@ def _write_archive(
181
  "counts": {"nodes": 2, "edges": 1, "communities": 1},
182
  }),
183
  )
 
 
 
 
 
184
  _add_text(tf, "./external-catalogs/skills-sh/catalog.json", "{}")
185
  _add_text(tf, "./entities/skills/skills-sh-example-skill.md", "# Example\n")
186
  _add_text(tf, "./entities/harnesses/langgraph.md", "# LangGraph\n")
@@ -312,6 +387,161 @@ def test_validate_graph_artifacts_rejects_mixed_export_generation(
312
  )
313
 
314
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
  def test_validate_graph_artifacts_rejects_stale_preview_html(
316
  tmp_path: Path,
317
  ) -> None:
@@ -618,17 +848,17 @@ def test_graph_only_workflow_uses_exact_release_counts() -> None:
618
  "--min-edges": "2000000",
619
  "--min-skills-sh-nodes": "89000",
620
  "--min-semantic-edges": "1000000",
621
- "--expected-nodes": "102718",
622
- "--expected-edges": "2911220",
623
- "--expected-semantic-edges": "1683265",
624
- "--expected-harness-nodes": "14",
625
  "--expected-skills-sh-nodes": "89463",
626
  "--expected-skills-sh-catalog-entries": "89463",
627
  "--expected-skills-sh-converted": "89463",
628
- "--expected-skill-pages": "91450",
629
  "--expected-agent-pages": "467",
630
  "--expected-mcp-pages": "10787",
631
- "--expected-harness-pages": "14",
632
  "--line-threshold": "180",
633
  "--max-stage-lines": "40",
634
  }
 
2
 
3
  import gzip
4
  import json
5
+ import sqlite3
6
  import tarfile
7
+ import zlib
8
  from io import BytesIO
9
  from pathlib import Path
10
  from typing import Any
 
37
  tf.addfile(info, BytesIO(payload))
38
 
39
 
40
+ def _add_bytes(tf: tarfile.TarFile, name: str, payload: bytes) -> None:
41
+ info = tarfile.TarInfo(name)
42
+ info.size = len(payload)
43
+ info.mode = 0o644
44
+ tf.addfile(info, BytesIO(payload))
45
+
46
+
47
+ def _dashboard_index_bytes(graph_dir: Path, *, export_id: str) -> bytes:
48
+ path = graph_dir / f"dashboard-index-{export_id}.sqlite3"
49
+ if path.exists():
50
+ path.unlink()
51
+ conn = sqlite3.connect(path)
52
+ try:
53
+ conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
54
+ conn.execute(
55
+ "CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
56
+ "description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
57
+ )
58
+ conn.execute(
59
+ "CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
60
+ "PRIMARY KEY(slug,type,node_id))"
61
+ )
62
+ conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
63
+ conn.executemany(
64
+ "INSERT INTO meta VALUES(?,?)",
65
+ [
66
+ ("version", "1"),
67
+ ("export_id", json.dumps(export_id)),
68
+ ("nodes_count", "2"),
69
+ ("edges_count", "1"),
70
+ ("max_degree", "1"),
71
+ ("top_k", "40"),
72
+ ],
73
+ )
74
+ conn.executemany(
75
+ "INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
76
+ [
77
+ ("skill:skills-sh-example-skill", "skills-sh-example-skill", "skill", "[]", "", None, None, 1),
78
+ ("harness:langgraph", "langgraph", "harness", "[]", "", None, None, 1),
79
+ ],
80
+ )
81
+ conn.executemany(
82
+ "INSERT INTO slug_index VALUES(?,?,?)",
83
+ [
84
+ ("skills-sh-example-skill", "skill", "skill:skills-sh-example-skill"),
85
+ ("langgraph", "harness", "harness:langgraph"),
86
+ ],
87
+ )
88
+ conn.executemany(
89
+ "INSERT INTO neighbors VALUES(?,?)",
90
+ [
91
+ ("skill:skills-sh-example-skill", zlib.compress(json.dumps([{"target": "harness:langgraph"}]).encode("utf-8"))),
92
+ ("harness:langgraph", zlib.compress(json.dumps([{"target": "skill:skills-sh-example-skill"}]).encode("utf-8"))),
93
+ ],
94
+ )
95
+ conn.commit()
96
+ finally:
97
+ conn.close()
98
+ payload = path.read_bytes()
99
+ path.unlink()
100
+ return payload
101
+
102
+
103
  def _write_catalog(graph_dir: Path, *, converted_path: str | None = None) -> None:
104
  skill = {
105
  "ctx_slug": "skills-sh-example-skill",
 
166
  "counts": {"nodes": 2, "edges": 1, "communities": 1},
167
  }),
168
  )
169
+ _add_bytes(
170
+ tf,
171
+ "graphify-out/dashboard-neighborhoods.sqlite3",
172
+ _dashboard_index_bytes(graph_dir, export_id=manifest_export_id),
173
+ )
174
  _add_text(tf, "external-catalogs/skills-sh/catalog.json", "{}")
175
  if include_queue:
176
  _add_text(tf, ".ctx/wiki-queue.sqlite3", "not a shipped artifact\n")
 
251
  "counts": {"nodes": 2, "edges": 1, "communities": 1},
252
  }),
253
  )
254
+ _add_bytes(
255
+ tf,
256
+ "./graphify-out/dashboard-neighborhoods.sqlite3",
257
+ _dashboard_index_bytes(graph_dir, export_id=manifest_export_id),
258
+ )
259
  _add_text(tf, "./external-catalogs/skills-sh/catalog.json", "{}")
260
  _add_text(tf, "./entities/skills/skills-sh-example-skill.md", "# Example\n")
261
  _add_text(tf, "./entities/harnesses/langgraph.md", "# LangGraph\n")
 
387
  )
388
 
389
 
390
+ def test_validate_graph_artifacts_rejects_runtime_full_export_split(
391
+ tmp_path: Path,
392
+ ) -> None:
393
+ _write_catalog(
394
+ tmp_path,
395
+ converted_path="converted/skills-sh-example-skill/SKILL.md",
396
+ )
397
+ _write_archive(tmp_path, graph_export_id="full-export")
398
+ runtime_graph = {
399
+ "graph": {"export_id": "runtime-export"},
400
+ "nodes": [
401
+ {"id": "skill:skills-sh-example-skill", "type": "skill"},
402
+ {"id": "harness:langgraph", "type": "harness"},
403
+ ],
404
+ "edges": [
405
+ {"source": "skill:skills-sh-example-skill", "target": "harness:langgraph"},
406
+ ],
407
+ }
408
+ _write_runtime_archive(
409
+ tmp_path,
410
+ graph=runtime_graph,
411
+ delta_export_id="runtime-export",
412
+ communities_export_id="runtime-export",
413
+ report_export_id="runtime-export",
414
+ manifest_export_id="runtime-export",
415
+ )
416
+
417
+ with pytest.raises(GraphArtifactError, match="runtime graph archive export_id mismatch"):
418
+ validate_graph_artifacts(
419
+ tmp_path,
420
+ deep=True,
421
+ min_nodes=2,
422
+ min_edges=1,
423
+ min_skills_sh_nodes=1,
424
+ min_semantic_edges=1,
425
+ expected_harnesses={"langgraph"},
426
+ )
427
+
428
+
429
+ def test_validate_graph_artifacts_rejects_corrupt_dashboard_index(
430
+ tmp_path: Path,
431
+ ) -> None:
432
+ _write_catalog(
433
+ tmp_path,
434
+ converted_path="converted/skills-sh-example-skill/SKILL.md",
435
+ )
436
+ _write_archive(tmp_path)
437
+ with tarfile.open(tmp_path / "wiki-graph-runtime.tar.gz", "w:gz") as tf:
438
+ graph = {
439
+ "graph": {"export_id": "export-test"},
440
+ "nodes": [
441
+ {"id": "skill:skills-sh-example-skill", "type": "skill"},
442
+ {"id": "harness:langgraph", "type": "harness"},
443
+ ],
444
+ "edges": [
445
+ {"source": "skill:skills-sh-example-skill", "target": "harness:langgraph"},
446
+ ],
447
+ }
448
+ _add_text(tf, "index.md", "# Wiki\n")
449
+ _add_text(tf, "graphify-out/graph.json", json.dumps(graph, separators=(",", ":")))
450
+ _add_text(tf, "graphify-out/graph-delta.json", json.dumps({"export_id": "export-test"}))
451
+ _add_text(tf, "graphify-out/communities.json", json.dumps({"export_id": "export-test"}))
452
+ _add_text(tf, "graphify-out/graph-report.md", "# Graph Report\n\n> Export ID: export-test\n")
453
+ _add_text(
454
+ tf,
455
+ "graphify-out/graph-export-manifest.json",
456
+ json.dumps({
457
+ "version": 1,
458
+ "export_id": "export-test",
459
+ "artifacts": {
460
+ "graph": "graph.json",
461
+ "delta": "graph-delta.json",
462
+ "communities": "communities.json",
463
+ "report": "graph-report.md",
464
+ },
465
+ "counts": {"nodes": 2, "edges": 1, "communities": 1},
466
+ }),
467
+ )
468
+ _add_text(tf, "graphify-out/dashboard-neighborhoods.sqlite3", "not sqlite\n")
469
+ _add_text(tf, "external-catalogs/skills-sh/catalog.json", "{}")
470
+ for slug in sorted(DEFAULT_HARNESSES):
471
+ _add_text(tf, f"entities/harnesses/{slug}.md", f"# {slug}\n")
472
+
473
+ with pytest.raises(GraphArtifactError, match="dashboard index"):
474
+ validate_graph_artifacts(
475
+ tmp_path,
476
+ deep=True,
477
+ min_nodes=2,
478
+ min_edges=1,
479
+ min_skills_sh_nodes=1,
480
+ min_semantic_edges=1,
481
+ expected_harnesses={"langgraph"},
482
+ )
483
+
484
+
485
+ def test_validate_graph_artifacts_rejects_stale_dashboard_index(
486
+ tmp_path: Path,
487
+ ) -> None:
488
+ _write_catalog(
489
+ tmp_path,
490
+ converted_path="converted/skills-sh-example-skill/SKILL.md",
491
+ )
492
+ _write_archive(tmp_path, graph_export_id="new-export", manifest_export_id="new-export")
493
+ with tarfile.open(tmp_path / "wiki-graph-runtime.tar.gz", "w:gz") as tf:
494
+ graph = {
495
+ "graph": {"export_id": "new-export"},
496
+ "nodes": [
497
+ {"id": "skill:skills-sh-example-skill", "type": "skill"},
498
+ {"id": "harness:langgraph", "type": "harness"},
499
+ ],
500
+ "edges": [
501
+ {"source": "skill:skills-sh-example-skill", "target": "harness:langgraph"},
502
+ ],
503
+ }
504
+ _add_text(tf, "index.md", "# Wiki\n")
505
+ _add_text(tf, "graphify-out/graph.json", json.dumps(graph, separators=(",", ":")))
506
+ _add_text(tf, "graphify-out/graph-delta.json", json.dumps({"export_id": "new-export"}))
507
+ _add_text(tf, "graphify-out/communities.json", json.dumps({"export_id": "new-export"}))
508
+ _add_text(tf, "graphify-out/graph-report.md", "# Graph Report\n\n> Export ID: new-export\n")
509
+ _add_text(
510
+ tf,
511
+ "graphify-out/graph-export-manifest.json",
512
+ json.dumps({
513
+ "version": 1,
514
+ "export_id": "new-export",
515
+ "artifacts": {
516
+ "graph": "graph.json",
517
+ "delta": "graph-delta.json",
518
+ "communities": "communities.json",
519
+ "report": "graph-report.md",
520
+ },
521
+ "counts": {"nodes": 2, "edges": 1, "communities": 1},
522
+ }),
523
+ )
524
+ _add_bytes(
525
+ tf,
526
+ "graphify-out/dashboard-neighborhoods.sqlite3",
527
+ _dashboard_index_bytes(tmp_path, export_id="old-export"),
528
+ )
529
+ _add_text(tf, "external-catalogs/skills-sh/catalog.json", "{}")
530
+ for slug in sorted(DEFAULT_HARNESSES):
531
+ _add_text(tf, f"entities/harnesses/{slug}.md", f"# {slug}\n")
532
+
533
+ with pytest.raises(GraphArtifactError, match="dashboard index export_id mismatch"):
534
+ validate_graph_artifacts(
535
+ tmp_path,
536
+ deep=True,
537
+ min_nodes=2,
538
+ min_edges=1,
539
+ min_skills_sh_nodes=1,
540
+ min_semantic_edges=1,
541
+ expected_harnesses={"langgraph"},
542
+ )
543
+
544
+
545
  def test_validate_graph_artifacts_rejects_stale_preview_html(
546
  tmp_path: Path,
547
  ) -> None:
 
848
  "--min-edges": "2000000",
849
  "--min-skills-sh-nodes": "89000",
850
  "--min-semantic-edges": "1000000",
851
+ "--expected-nodes": "102717",
852
+ "--expected-edges": "2911162",
853
+ "--expected-semantic-edges": "1683182",
854
+ "--expected-harness-nodes": "15",
855
  "--expected-skills-sh-nodes": "89463",
856
  "--expected-skills-sh-catalog-entries": "89463",
857
  "--expected-skills-sh-converted": "89463",
858
+ "--expected-skill-pages": "91448",
859
  "--expected-agent-pages": "467",
860
  "--expected-mcp-pages": "10787",
861
+ "--expected-harness-pages": "15",
862
  "--line-threshold": "180",
863
  "--max-stage-lines": "40",
864
  }
src/tests/test_wiki_queue_worker.py CHANGED
@@ -154,6 +154,44 @@ def test_process_next_entity_upsert_does_not_fail_when_incremental_attach_fails(
154
  assert "incremental attach skipped (embedding backend missing)" in result.message
155
 
156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  def test_process_next_retries_hash_mismatch(
158
  tmp_path: Path,
159
  monkeypatch: Any,
 
154
  assert "incremental attach skipped (embedding backend missing)" in result.message
155
 
156
 
157
+ def test_process_next_entity_delete_queues_full_graph_refresh(
158
+ tmp_path: Path,
159
+ monkeypatch: Any,
160
+ ) -> None:
161
+ wiki = tmp_path / "wiki"
162
+ entity_path = wiki / "entities" / "skills" / "deleted.md"
163
+ queued = wiki_queue.enqueue_entity_upsert(
164
+ wiki,
165
+ entity_type="skill",
166
+ slug="deleted",
167
+ entity_path=entity_path,
168
+ content="",
169
+ action="delete",
170
+ source="test",
171
+ now=10.0,
172
+ )
173
+ update_index = MagicMock()
174
+ monkeypatch.setattr(wiki_queue_worker, "update_index", update_index)
175
+
176
+ result = wiki_queue_worker.process_next(wiki, worker_id="worker-a", now=20.0)
177
+
178
+ assert result is not None
179
+ assert result.job_id == queued.id
180
+ assert result.status == wiki_queue.STATUS_SUCCEEDED
181
+ assert result.message == "queued full graph refresh for deleted skills entity deleted"
182
+ update_index.assert_not_called()
183
+ jobs = wiki_queue.list_jobs(wiki_queue.queue_db_path(wiki))
184
+ assert [job.kind for job in jobs] == [
185
+ wiki_queue.ENTITY_UPSERT_JOB,
186
+ wiki_queue.GRAPH_EXPORT_JOB,
187
+ ]
188
+ assert jobs[1].payload == {
189
+ "graph_only": True,
190
+ "incremental": False,
191
+ "source": "entity-delete",
192
+ }
193
+
194
+
195
  def test_process_next_retries_hash_mismatch(
196
  tmp_path: Path,
197
  monkeypatch: Any,
src/validate_graph_artifacts.py CHANGED
@@ -7,7 +7,10 @@ import argparse
7
  import gzip
8
  import json
9
  import re
 
10
  import tarfile
 
 
11
  from dataclasses import dataclass
12
  from pathlib import Path
13
  from typing import IO, Any
@@ -23,7 +26,9 @@ DEFAULT_HARNESSES = {
23
  "langgraph",
24
  "litellm",
25
  "mastra",
 
26
  "openai-agents-sdk",
 
27
  "pydantic-ai",
28
  "semantic-kernel",
29
  "text-to-cad",
@@ -56,8 +61,32 @@ _GRAPH_RUNTIME_REQUIRED_NAMES = {
56
  "graphify-out/communities.json",
57
  "graphify-out/graph-report.md",
58
  "graphify-out/graph-export-manifest.json",
 
59
  "external-catalogs/skills-sh/catalog.json",
60
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
 
63
  class GraphArtifactError(RuntimeError):
@@ -102,6 +131,84 @@ def _require_real_file(path: Path) -> None:
102
  raise GraphArtifactError(f"{path} is a Git LFS pointer, not hydrated content")
103
 
104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  def _safe_tar_name(raw_name: str) -> str:
106
  name = raw_name.replace("\\", "/")
107
  if (
@@ -252,7 +359,7 @@ def validate_graph_artifacts(
252
  _require_real_file(path)
253
 
254
  expected_harnesses = DEFAULT_HARNESSES if expected_harnesses is None else expected_harnesses
255
- _validate_runtime_graph_archive(
256
  runtime_tarball,
257
  expected_harnesses=expected_harnesses,
258
  )
@@ -289,6 +396,7 @@ def validate_graph_artifacts(
289
  export_ids: dict[str, str] = {}
290
  manifest: dict[str, Any] | None = None
291
  archive_communities: dict[str, Any] | None = None
 
292
 
293
  with tarfile.open(tarball, "r:gz") as tf:
294
  for member in tf:
@@ -353,6 +461,11 @@ def validate_graph_artifacts(
353
  if f is None:
354
  raise GraphArtifactError(f"{member.name} could not be read")
355
  _record_export_id(export_ids, name, _export_id_from_report(f.read()))
 
 
 
 
 
356
  elif member.isfile() and deep and name.startswith("converted/skills-sh-"):
357
  if name.endswith("/SKILL.md") or "/references/" in name:
358
  f = tf.extractfile(member)
@@ -370,11 +483,26 @@ def validate_graph_artifacts(
370
  if missing_required:
371
  raise GraphArtifactError(f"wiki graph archive is missing: {missing_required}")
372
  manifest_export_id = _validate_graph_export_manifest(manifest, names)
 
 
 
 
 
373
  _record_export_id(
374
  export_ids,
375
  "graphify-out/graph-export-manifest.json",
376
  manifest_export_id,
377
  )
 
 
 
 
 
 
 
 
 
 
378
  if "graphify-out/graph.json" not in export_ids:
379
  raise GraphArtifactError("graphify-out/graph.json is missing export_id")
380
  _validate_export_ids(export_ids, expected=manifest_export_id)
@@ -461,10 +589,12 @@ def _validate_runtime_graph_archive(
461
  tarball: Path,
462
  *,
463
  expected_harnesses: set[str],
464
- ) -> None:
 
465
  names: set[str] = set()
466
  export_ids: dict[str, str] = {}
467
  manifest: dict[str, Any] | None = None
 
468
  with tarfile.open(tarball, "r:gz") as tf:
469
  for member in tf:
470
  name = _safe_tar_name(member.name)
@@ -506,6 +636,11 @@ def _validate_runtime_graph_archive(
506
  if f is None:
507
  raise GraphArtifactError(f"{member.name} could not be read")
508
  _record_export_id(export_ids, name, _export_id_from_report(f.read()))
 
 
 
 
 
509
 
510
  missing_required = sorted(_GRAPH_RUNTIME_REQUIRED_NAMES - names)
511
  if missing_required:
@@ -527,9 +662,27 @@ def _validate_runtime_graph_archive(
527
  "graphify-out/graph-export-manifest.json",
528
  manifest_export_id,
529
  )
 
 
 
 
 
 
 
 
 
 
 
 
530
  if "graphify-out/graph.json" not in export_ids:
531
  raise GraphArtifactError("runtime graph.json is missing export_id")
532
  _validate_export_ids(export_ids, expected=manifest_export_id)
 
 
 
 
 
 
533
 
534
 
535
  def _validate_root_communities(
 
7
  import gzip
8
  import json
9
  import re
10
+ import sqlite3
11
  import tarfile
12
+ import tempfile
13
+ import zlib
14
  from dataclasses import dataclass
15
  from pathlib import Path
16
  from typing import IO, Any
 
26
  "langgraph",
27
  "litellm",
28
  "mastra",
29
+ "mirage",
30
  "openai-agents-sdk",
31
+ "optillm",
32
  "pydantic-ai",
33
  "semantic-kernel",
34
  "text-to-cad",
 
61
  "graphify-out/communities.json",
62
  "graphify-out/graph-report.md",
63
  "graphify-out/graph-export-manifest.json",
64
+ "graphify-out/dashboard-neighborhoods.sqlite3",
65
  "external-catalogs/skills-sh/catalog.json",
66
  }
67
+ _DASHBOARD_INDEX_REQUIRED_TABLES = {"meta", "nodes", "slug_index", "neighbors"}
68
+ _DASHBOARD_INDEX_REQUIRED_META = {
69
+ "export_id",
70
+ "nodes_count",
71
+ "edges_count",
72
+ "max_degree",
73
+ "top_k",
74
+ }
75
+ _DASHBOARD_INDEX_REQUIRED_COLUMNS = {
76
+ "meta": {"key", "value"},
77
+ "nodes": {
78
+ "id",
79
+ "label",
80
+ "type",
81
+ "tags",
82
+ "description",
83
+ "quality_score",
84
+ "usage_score",
85
+ "degree",
86
+ },
87
+ "slug_index": {"slug", "type", "node_id"},
88
+ "neighbors": {"source", "payload"},
89
+ }
90
 
91
 
92
  class GraphArtifactError(RuntimeError):
 
131
  raise GraphArtifactError(f"{path} is a Git LFS pointer, not hydrated content")
132
 
133
 
134
+ def _copy_tar_member_to_path(
135
+ tf: tarfile.TarFile,
136
+ member: tarfile.TarInfo,
137
+ target: Path,
138
+ ) -> None:
139
+ source = tf.extractfile(member)
140
+ if source is None:
141
+ raise GraphArtifactError(f"{member.name} could not be read")
142
+ try:
143
+ with target.open("wb") as out:
144
+ while chunk := source.read(1024 * 1024):
145
+ out.write(chunk)
146
+ finally:
147
+ source.close()
148
+
149
+
150
+ def _validate_dashboard_index(
151
+ path: Path,
152
+ *,
153
+ expected_export_id: str,
154
+ context: str,
155
+ ) -> None:
156
+ try:
157
+ conn = sqlite3.connect(f"file:{path.as_posix()}?mode=ro", uri=True)
158
+ conn.row_factory = sqlite3.Row
159
+ except sqlite3.Error as exc:
160
+ raise GraphArtifactError(f"{context} dashboard index is not valid SQLite: {exc}") from exc
161
+ try:
162
+ quick = conn.execute("PRAGMA quick_check").fetchone()
163
+ if quick is None or str(quick[0]).lower() != "ok":
164
+ raise GraphArtifactError(f"{context} dashboard index quick_check failed: {quick}")
165
+ tables = {
166
+ str(row["name"])
167
+ for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")
168
+ }
169
+ missing_tables = sorted(_DASHBOARD_INDEX_REQUIRED_TABLES - tables)
170
+ if missing_tables:
171
+ raise GraphArtifactError(
172
+ f"{context} dashboard index missing tables: {missing_tables}",
173
+ )
174
+ for table, expected_columns in _DASHBOARD_INDEX_REQUIRED_COLUMNS.items():
175
+ columns = {str(row["name"]) for row in conn.execute(f"PRAGMA table_info({table})")}
176
+ missing_columns = sorted(expected_columns - columns)
177
+ if missing_columns:
178
+ raise GraphArtifactError(
179
+ f"{context} dashboard index table {table} missing columns: "
180
+ f"{missing_columns}",
181
+ )
182
+ meta_rows = conn.execute("SELECT key,value FROM meta").fetchall()
183
+ meta = {str(row["key"]): json.loads(str(row["value"])) for row in meta_rows}
184
+ missing_meta = sorted(_DASHBOARD_INDEX_REQUIRED_META - set(meta))
185
+ if missing_meta:
186
+ raise GraphArtifactError(
187
+ f"{context} dashboard index missing meta keys: {missing_meta}",
188
+ )
189
+ if meta.get("export_id") != expected_export_id:
190
+ raise GraphArtifactError(
191
+ f"{context} dashboard index export_id mismatch: expected "
192
+ f"{expected_export_id}, got {meta.get('export_id') or 'missing'}",
193
+ )
194
+ nodes_count = int(meta.get("nodes_count") or 0)
195
+ if nodes_count != int(conn.execute("SELECT COUNT(*) FROM nodes").fetchone()[0]):
196
+ raise GraphArtifactError(f"{context} dashboard index nodes_count mismatch")
197
+ if nodes_count > 0 and int(conn.execute("SELECT COUNT(*) FROM slug_index").fetchone()[0]) == 0:
198
+ raise GraphArtifactError(f"{context} dashboard index slug_index is empty")
199
+ payload = conn.execute("SELECT payload FROM neighbors LIMIT 1").fetchone()
200
+ if payload is not None:
201
+ decoded = json.loads(zlib.decompress(payload["payload"]).decode("utf-8"))
202
+ if not isinstance(decoded, list):
203
+ raise GraphArtifactError(
204
+ f"{context} dashboard index neighbor payload is not a list",
205
+ )
206
+ except (sqlite3.Error, json.JSONDecodeError, ValueError, TypeError, zlib.error) as exc:
207
+ raise GraphArtifactError(f"{context} dashboard index validation failed: {exc}") from exc
208
+ finally:
209
+ conn.close()
210
+
211
+
212
  def _safe_tar_name(raw_name: str) -> str:
213
  name = raw_name.replace("\\", "/")
214
  if (
 
359
  _require_real_file(path)
360
 
361
  expected_harnesses = DEFAULT_HARNESSES if expected_harnesses is None else expected_harnesses
362
+ runtime_export_id = _validate_runtime_graph_archive(
363
  runtime_tarball,
364
  expected_harnesses=expected_harnesses,
365
  )
 
396
  export_ids: dict[str, str] = {}
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:
 
461
  if f is None:
462
  raise GraphArtifactError(f"{member.name} could not be read")
463
  _record_export_id(export_ids, name, _export_id_from_report(f.read()))
464
+ elif member.isfile() and name == "graphify-out/dashboard-neighborhoods.sqlite3":
465
+ tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".sqlite3")
466
+ tmp.close()
467
+ dashboard_index_path = Path(tmp.name)
468
+ _copy_tar_member_to_path(tf, member, dashboard_index_path)
469
  elif member.isfile() and deep and name.startswith("converted/skills-sh-"):
470
  if name.endswith("/SKILL.md") or "/references/" in name:
471
  f = tf.extractfile(member)
 
483
  if missing_required:
484
  raise GraphArtifactError(f"wiki graph archive is missing: {missing_required}")
485
  manifest_export_id = _validate_graph_export_manifest(manifest, names)
486
+ if runtime_export_id != manifest_export_id:
487
+ raise GraphArtifactError(
488
+ "runtime graph archive export_id mismatch: expected "
489
+ f"{manifest_export_id}, got {runtime_export_id}",
490
+ )
491
  _record_export_id(
492
  export_ids,
493
  "graphify-out/graph-export-manifest.json",
494
  manifest_export_id,
495
  )
496
+ if dashboard_index_path is None:
497
+ raise GraphArtifactError("graphify-out/dashboard-neighborhoods.sqlite3 is missing")
498
+ try:
499
+ _validate_dashboard_index(
500
+ dashboard_index_path,
501
+ expected_export_id=manifest_export_id,
502
+ context="full archive",
503
+ )
504
+ finally:
505
+ dashboard_index_path.unlink(missing_ok=True)
506
  if "graphify-out/graph.json" not in export_ids:
507
  raise GraphArtifactError("graphify-out/graph.json is missing export_id")
508
  _validate_export_ids(export_ids, expected=manifest_export_id)
 
589
  tarball: Path,
590
  *,
591
  expected_harnesses: set[str],
592
+ expected_export_id: str | None = None,
593
+ ) -> str:
594
  names: set[str] = set()
595
  export_ids: dict[str, str] = {}
596
  manifest: dict[str, Any] | None = None
597
+ dashboard_index_path: Path | None = None
598
  with tarfile.open(tarball, "r:gz") as tf:
599
  for member in tf:
600
  name = _safe_tar_name(member.name)
 
636
  if f is None:
637
  raise GraphArtifactError(f"{member.name} could not be read")
638
  _record_export_id(export_ids, name, _export_id_from_report(f.read()))
639
+ elif member.isfile() and name == "graphify-out/dashboard-neighborhoods.sqlite3":
640
+ tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".sqlite3")
641
+ tmp.close()
642
+ dashboard_index_path = Path(tmp.name)
643
+ _copy_tar_member_to_path(tf, member, dashboard_index_path)
644
 
645
  missing_required = sorted(_GRAPH_RUNTIME_REQUIRED_NAMES - names)
646
  if missing_required:
 
662
  "graphify-out/graph-export-manifest.json",
663
  manifest_export_id,
664
  )
665
+ if dashboard_index_path is None:
666
+ raise GraphArtifactError(
667
+ "runtime graph archive is missing dashboard-neighborhoods.sqlite3",
668
+ )
669
+ try:
670
+ _validate_dashboard_index(
671
+ dashboard_index_path,
672
+ expected_export_id=manifest_export_id,
673
+ context="runtime archive",
674
+ )
675
+ finally:
676
+ dashboard_index_path.unlink(missing_ok=True)
677
  if "graphify-out/graph.json" not in export_ids:
678
  raise GraphArtifactError("runtime graph.json is missing export_id")
679
  _validate_export_ids(export_ids, expected=manifest_export_id)
680
+ if expected_export_id is not None and manifest_export_id != expected_export_id:
681
+ raise GraphArtifactError(
682
+ "runtime graph archive export_id mismatch: expected "
683
+ f"{expected_export_id}, got {manifest_export_id}",
684
+ )
685
+ return manifest_export_id
686
 
687
 
688
  def _validate_root_communities(