@drafthq/draft 3.0.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +3 -3
  4. package/bin/README.md +4 -7
  5. package/cli/src/hosts/claude-code.js +4 -1
  6. package/cli/src/installer.js +12 -5
  7. package/core/shared/condensation.md +8 -8
  8. package/core/shared/draft-context-loading.md +5 -9
  9. package/core/shared/graph-query.md +170 -33
  10. package/core/shared/graph-usage-report.md +1 -1
  11. package/core/shared/pattern-learning.md +2 -2
  12. package/core/shared/red-flags.md +3 -3
  13. package/core/templates/ai-context.md +1 -1
  14. package/core/templates/architecture.md +3 -3
  15. package/integrations/agents/AGENTS.md +299 -145
  16. package/integrations/copilot/.github/copilot-instructions.md +299 -145
  17. package/package.json +2 -1
  18. package/scripts/lib.sh +11 -3
  19. package/scripts/tools/_graph_queries.sh +102 -0
  20. package/scripts/tools/adr-index.sh +2 -2
  21. package/scripts/tools/check-scope-conflicts.sh +2 -2
  22. package/scripts/tools/check-skill-line-caps.sh +2 -2
  23. package/scripts/tools/cycle-detect.sh +22 -15
  24. package/scripts/tools/diff-templates-vs-tracks.sh +2 -2
  25. package/scripts/tools/fix-whitespace.sh +15 -9
  26. package/scripts/tools/graph-arch.sh +72 -0
  27. package/scripts/tools/graph-callers.sh +71 -20
  28. package/scripts/tools/graph-deps.sh +76 -0
  29. package/scripts/tools/graph-errors.sh +97 -0
  30. package/scripts/tools/graph-hierarchy.sh +89 -0
  31. package/scripts/tools/graph-impact.sh +1 -0
  32. package/scripts/tools/graph-init.sh +3 -3
  33. package/scripts/tools/graph-query.sh +124 -0
  34. package/scripts/tools/graph-risk.sh +81 -0
  35. package/scripts/tools/graph-search.sh +84 -0
  36. package/scripts/tools/graph-snapshot.sh +63 -50
  37. package/scripts/tools/graph-snippet.sh +92 -0
  38. package/scripts/tools/graph-tests.sh +112 -0
  39. package/scripts/tools/graph-traces.sh +83 -0
  40. package/scripts/tools/hotspot-rank.sh +44 -15
  41. package/scripts/tools/manage-symlinks.sh +1 -1
  42. package/scripts/tools/mermaid-from-graph.sh +31 -10
  43. package/scripts/tools/parse-reports.sh +1 -1
  44. package/scripts/tools/verify-doc-anchors.sh +2 -2
  45. package/scripts/tools/verify-graph-binary.sh +1 -1
  46. package/skills/GRAPH.md +2 -2
  47. package/skills/bughunt/SKILL.md +1 -1
  48. package/skills/debug/SKILL.md +3 -3
  49. package/skills/decompose/SKILL.md +5 -5
  50. package/skills/deep-review/SKILL.md +2 -2
  51. package/skills/deploy-checklist/SKILL.md +2 -2
  52. package/skills/graph/SKILL.md +1 -1
  53. package/skills/implement/SKILL.md +1 -1
  54. package/skills/init/SKILL.md +62 -42
  55. package/skills/init/references/architecture-spec.md +12 -11
  56. package/skills/learn/SKILL.md +5 -5
  57. package/skills/quick-review/SKILL.md +3 -3
  58. package/skills/review/SKILL.md +7 -7
  59. package/skills/tech-debt/SKILL.md +2 -2
  60. package/scripts/tools/okf-bundle.sh +0 -141
  61. package/scripts/tools/okf-check.sh +0 -137
  62. package/scripts/tools/okf-emit.sh +0 -161
@@ -172,7 +172,7 @@ Initialize a Draft project for Context-Driven Development.
172
172
 
173
173
  ## Graph Fidelity & Diagram-First Priority (MANDATORY)
174
174
 
175
- The knowledge graph in `draft/graph/` (architecture.json with packages, languages, routes, and fan-in/out; hotspots.jsonl) is the **deterministic structural ground truth** for the system's actual architecture.
175
+ The knowledge graph served live by the local `codebase-memory-mcp` engine (packages, languages, routes, fan-in/out, hotspots) and queried via the `graph-*.sh` wrappers — is the **deterministic structural ground truth** for the system's actual architecture. Draft is engine-only: `draft/graph/` holds only the `schema.yaml` gate marker; all graph data comes from live queries.
176
176
 
177
177
  **You are running inside a powerful agentic coding environment** (Cursor, Claude Code, Copilot, Windsurf, etc.) that maintains its own rich, continuously updated index of the entire codebase. **Use that indexed knowledge aggressively** in addition to the explicit graph data and direct source reads. Your environment's index often captures higher-level intent, naming patterns, cross-file workflows, and architectural signals that the static graph may not fully express yet. Combine both sources:
178
178
  - Graph = authoritative modules, edges, public surfaces, hotspots, call relationships.
@@ -619,9 +619,9 @@ else
619
619
  fi
620
620
  ```
621
621
 
622
- - **Root init** writes `<root>/draft/graph/` — the committed, git-tracked whole-repo memory.
622
+ - **Root init** writes `<root>/draft/graph/schema.yaml` — the committed gate marker. Draft is engine-only: graph data is served live by the engine, never committed.
623
623
  - **Module init** also writes `draft/graph/root-link.json` (module→root); follow `root_graph` for cross-module understanding. The root spine is rebuilt first so the link is live.
624
- - Only `draft/graph/` is committed. The engine's `~/.cache` index is a disposable accelerator — never commit it; it rebuilds deterministically from source.
624
+ - Only `schema.yaml` (and `root-link.json` in a module) is committed. The engine's `~/.cache` index is the live structural store — never commit it; it rebuilds deterministically from source.
625
625
 
626
626
  Optionally record which engine was selected (usage-report contract):
627
627
 
@@ -631,15 +631,20 @@ scripts/tools/verify-graph-binary.sh --repo . --json 2>/dev/null || true
631
631
 
632
632
  See `core/shared/graph-query.md` and `bin/README.md` for the query contract and engine resolution.
633
633
 
634
- If the build succeeds, `draft/graph/` is populated and later steps consume the always-load artifacts + injection slots.
634
+ If indexing succeeds, `draft/graph/schema.yaml` is written and later steps query the engine live for structure + populate the injection slots.
635
635
 
636
- ### 2. If graph build succeeds, load the always-load artifacts
636
+ ### 2. If indexing succeeds, query the engine for structural context
637
637
 
638
- Read these files to get structural context for all subsequent phases:
639
- - `draft/graph/schema.yaml` — module count, file count, edge count, language stats per module
640
- - `draft/graph/architecture.json` — module list (`.packages`) with fan-in/out
641
- - `draft/graph/architecture.json` `.routes` — detected service endpoints
642
- - `draft/graph/hotspots.jsonl` — all complexity hotspots (files ranked by lines + fanIn * 50)
638
+ Pull the architecture view once and reuse it across phases:
639
+
640
+ ```bash
641
+ ARCH=$(scripts/tools/graph-arch.sh --repo .)
642
+ ```
643
+
644
+ - `$ARCH | jq '.packages'` — module list with fan-in/out
645
+ - `$ARCH | jq '.routes'` — detected service endpoints
646
+ - `$ARCH | jq '.languages, .node_labels, .layers, .boundaries'` — language mix, node shape, layering
647
+ - `scripts/tools/hotspot-rank.sh --repo . --top 20` — complexity/fan-in hotspots (live)
643
648
 
644
649
  ### 3. Use graph data to accelerate Step 1.5
645
650
 
@@ -653,10 +658,10 @@ Read these files to get structural context for all subsequent phases:
653
658
  ### 4. Compute codebase tier and module priority
654
659
 
655
660
  **Step 1.4.5 — Compute Codebase Tier:**
656
- Read `draft/graph/schema.yaml`. Extract:
657
- - `M = stats.modules`
658
- - `F = stats.go_functions + stats.py_functions`
659
- - `P = stats.proto_rpcs`
661
+ From the live `$ARCH` (above), extract:
662
+ - `M = $ARCH | jq '.packages | length'` (modules)
663
+ - `F = $ARCH | jq '[.node_labels[] | select(.label=="Function" or .label=="Method") | .count] | add // 0'` (functions+methods)
664
+ - `P = $ARCH | jq '.routes | length'` (routes / RPCs)
660
665
 
661
666
  Apply tier table:
662
667
 
@@ -671,8 +676,8 @@ Apply tier table:
671
676
  Hold tier in memory. This governs: architecture.md length minimum, .ai-context.md budget, and module deep-dive depth.
672
677
 
673
678
  **Step 1.4.6 — Build Module Priority List:**
674
- From `draft/graph/hotspots.jsonl`: count hotspot files per module (group by `module` field).
675
- From `draft/graph/architecture.json` `.packages[]`: read `fan_in` per module.
679
+ From `scripts/tools/hotspot-rank.sh --repo .`: count hotspot symbols per module.
680
+ From `$ARCH | jq '.packages[]'`: read `fan_in` per module.
676
681
  Rank modules by: `(hotspot_count × 2) + fan_in_count`.
677
682
  Top-ranked modules drive Section 6 deep-dive ordering and depth. Modules ranked zero on both: summary treatment only.
678
683
  Hold ranked list in memory — it replaces directory scanning for module discovery.
@@ -692,7 +697,7 @@ The tool emits a ready-to-inject ` ```mermaid ``` ` block (or an empty stub on e
692
697
  ```
693
698
 
694
699
  For Section 20 (hotspots slot):
695
- Read `draft/graph/hotspots.jsonl` (or run `scripts/tools/hotspot-rank.sh --repo . --top 10`), take the top 10 by fanIn, build a markdown table:
700
+ Run `scripts/tools/hotspot-rank.sh --repo . --top 10`, take the top 10 by fanIn, build a markdown table:
696
701
  ```
697
702
  <!-- GRAPH:hotspots:START -->
698
703
  | Symbol | fanIn |
@@ -751,7 +756,7 @@ Perform a **one-time, exhaustive analysis** of the existing codebase. This is NO
751
756
 
752
757
  If the codebase is large (200+ files), focus on the module boundaries but still enumerate exhaustively within each module.
753
758
 
754
- > **Large codebase guardrail:** If the codebase exceeds 500 source files, limit Section 7 deep dives to the top 20 most-imported modules and summarize others in a table. Rank modules by the number of unique files that import/reference them (descending) — use `draft/graph/architecture.json` `.packages[].fan_in` if graph data is available. For dynamic languages where static import counting is impractical, rank by file count within each module directory (larger modules first). **Even for summarized modules, enumerate immediate sub-directories with file counts** (one-line per sub-dir) — this is cheap with graph data and provides essential navigation context.
759
+ > **Large codebase guardrail:** If the codebase exceeds 500 source files, limit Section 7 deep dives to the top 20 most-imported modules and summarize others in a table. Rank modules by the number of unique files that import/reference them (descending) — use the engine's `.packages[].fan_in` (`get_architecture`, captured as `$ARCH` in Step 1.4.2) if the engine is available. For dynamic languages where static import counting is impractical, rank by file count within each module directory (larger modules first). **Even for summarized modules, enumerate immediate sub-directories with file counts** (one-line per sub-dir) — this is cheap with graph data and provides essential navigation context.
755
760
 
756
761
  ### Parallel Analysis Protocol (Tiers 3–5)
757
762
 
@@ -778,16 +783,16 @@ For tier 3+, readers run simultaneously; wall clock = slowest reader, not the su
778
783
 
779
784
  #### Phase 0: Graph Data (already done in Step 1.4)
780
785
 
781
- The graph binary has already run. Use its output throughout this protocol:
782
- - `draft.tmp/graph/schema.yaml` — module list, file counts, tier metrics
783
- - `draft.tmp/graph/architecture.json` — `.packages[].fan_in` per module (for grouping)
784
- - `draft.tmp/graph/hotspots.jsonl` — top hotspot files per module (feed to readers)
786
+ The engine is already indexed. Query it live throughout this protocol (reuse `$ARCH` from Step 1.4.2):
787
+ - `$ARCH | jq '.packages'` — module list with `.fan_in`/`.fan_out` (for grouping)
788
+ - `$ARCH | jq '.languages, .node_labels'` — file/symbol counts, tier metrics
789
+ - `scripts/tools/hotspot-rank.sh --repo .` — top hotspot symbols per module (feed to readers)
785
790
 
786
791
  #### Phase 1: Spawn Parallel Module Readers
787
792
 
788
793
  **Step 1: Group modules.**
789
794
 
790
- From `draft.tmp/graph/architecture.json` `.packages[]`, extract all module names and their `fan_in` counts.
795
+ From `$ARCH | jq '.packages[]'`, extract all module names and their `fan_in` counts.
791
796
  Apply dependency-aware grouping (see `core/shared/parallel-analysis.md`).
792
797
  Use the modules-per-agent count from the tier table above (4 for tier 4/5; all modules in one agent for tier 1):
793
798
  - Assign highest fan-in modules to separate readers (tier 3+)
@@ -803,7 +808,7 @@ Hotspot files:
803
808
  execution/engine.go (847 lines, fanIn=12)
804
809
  execution/router.go (412 lines, fanIn=8)
805
810
  fill_processor/handler.go (623 lines, fanIn=5)
806
- Module edges (from architecture.json .packages fan-in/out):
811
+ Module edges (from $ARCH .packages fan-in/out):
807
812
  execution → [risk, data, services]
808
813
  fill_processor → [execution, persistence]
809
814
  ```
@@ -908,7 +913,7 @@ If any reader agent fails to produce valid JSON after one retry:
908
913
  When the Agent tool is unavailable or reader agents fail after retry, write `draft/architecture.md` using the **10-section graph-primary structure** (checklist above + `core/templates/architecture.md`). Do not use legacy 28-section or Pass 1/2/3 volume protocols.
909
914
 
910
915
  1. Use the ranked module list from Step 1.4.6 (graph-first — do not re-scan by directory if Phase 0 succeeded).
911
- 2. For each top module (up to 20 by fan-in), read `draft/graph/modules/{name}.jsonl`, hotspot files, and 3–5 key sources; embed graph blocks and at least one workflow/state diagram per significant module inside §4–§8 as appropriate.
916
+ 2. For each top module (up to 20 by fan-in), query the engine for its symbols/callers (`scripts/tools/graph-callers.sh`, `graph-impact.sh`, or `$ARCH | jq '.packages[] | select(.name=="<m>")'`), read the hotspot files and 3–5 key sources; embed graph blocks and at least one workflow/state diagram per significant module inside §4–§8 as appropriate.
912
917
  3. Always include §9 Graph Coverage Gaps and §10 Relationship when the Context Audit requires them.
913
918
  4. Run Completion Verification (defined later in this skill) before condensation. Fidelity, provenance, and gap honesty block completion — not line counts.
914
919
 
@@ -1031,11 +1036,11 @@ Follow these steps in order. The specific files to look for depend on the langua
1031
1036
 
1032
1037
  #### Phase 1: Discovery (Broad Scan)
1033
1038
 
1034
- 1. **Map the directory tree**: Recursively list the project to understand the file layout. Note subdirectory groupings. (If Step 1.4 graph analysis succeeded, use `draft.tmp/graph/schema.yaml` module list instead — it is exhaustive and includes file counts.)
1039
+ 1. **Map the directory tree**: Recursively list the project to understand the file layout. Note subdirectory groupings. (If Step 1.4 graph analysis succeeded, use the engine's `$ARCH | jq '.packages, .file_tree'` instead — it is exhaustive and includes file counts.)
1035
1040
 
1036
1041
  2. **Read build / dependency files**: These reveal the module structure, dependencies, and targets. (See language guide above for which files.)
1037
1042
 
1038
- 3. **Read API definition files**: These define the module's data model and service interfaces. (See language guide above for which files. If Step 1.4 succeeded, `draft.tmp/graph/architecture.json` `.routes` already has all detected service endpoints.)
1043
+ 3. **Read API definition files**: These define the module's data model and service interfaces. (See language guide above for which files. If Step 1.4 succeeded, the engine's `$ARCH | jq '.routes'` already has all detected service endpoints.)
1039
1044
 
1040
1045
  4. **Read interface / type definition files**: Class declarations, interface definitions, and type annotations reveal the public API and design intent.
1041
1046
 
@@ -1773,22 +1778,37 @@ For **brownfield** projects, run `draft learn` (no arguments — full codebase s
1773
1778
 
1774
1779
  ## Completion
1775
1780
 
1776
- **Finalize OKF bundle:** After all `draft/` files are written, run the bundle tool
1777
- to (re)generate the Open Knowledge Format root index so the whole `draft/` tree is
1778
- a portable, vendor-neutral OKF bundle. This is the default no flag required.
1781
+ **Finalize the context index:** After all `draft/` files are written, author (or refresh)
1782
+ `draft/index.md` a plain, navigable index over the context bundle. No OKF framing, no
1783
+ special frontmatter; it is a human- and agent-readable table of contents.
1779
1784
 
1780
- ```bash
1781
- scripts/tools/okf-bundle.sh --dir draft # writes the bundle-root draft/index.md
1782
- scripts/tools/okf-check.sh --dir draft # OKF v0.1 conformance (advisory, non-fatal)
1785
+ Write `draft/index.md` with this structure (omit rows whose files were not generated):
1786
+
1787
+ ```md
1788
+ # <project> — Draft Context
1789
+
1790
+ Start here. This indexes the Draft context for this repo.
1791
+
1792
+ ## Context
1793
+ - [Architecture](architecture.md) — module map, dependencies, hotspots (graph-grounded)
1794
+ - [Product](product.md) — what this system does and for whom
1795
+ - [Tech Stack](tech-stack.md) — languages, frameworks, infra
1796
+ - [Workflow](workflow.md) — how work flows through the repo
1797
+ - [Guardrails](guardrails.md) — learned conventions and anti-patterns
1798
+ - [AI Context Map](.ai-context.md) — condensed orientation for agents
1799
+ - [AI Profile](.ai-profile.md) — repo profile + tiering
1800
+
1801
+ ## Tracks
1802
+ - [Track Index](tracks.md) — active, completed, and archived tracks
1803
+
1804
+ ## Knowledge graph
1805
+ - Engine-only (`codebase-memory-mcp`). Structural data is queried live via the
1806
+ `graph-*.sh` wrappers; `draft/graph/schema.yaml` is the gate marker. There is no
1807
+ committed graph mirror to browse.
1783
1808
  ```
1784
1809
 
1785
- `okf-bundle.sh` links every concept file present (`.ai-profile.md`, `.ai-context.md`,
1786
- `architecture.md`, `product.md`, `tech-stack.md`, `workflow.md`, `guardrails.md`), the
1787
- tracks, and the graph sub-bundle (`graph/okf/`). Concept `type:` frontmatter comes from
1788
- the templates; `okf-check.sh` validates §9 conformance (frontmatter + `type` on every
1789
- concept; reserved `index.md`/`log.md` structure). It is advisory — report the result,
1790
- do not fail init. Note: operational reports later written into `draft/` (e.g.
1791
- `deep-review-report.md`) are not OKF concepts and will be flagged.
1810
+ Keep one-line descriptions accurate to what each file actually contains. This index is
1811
+ the single committed entry point to the `draft/` bundle.
1792
1812
 
1793
1813
  **Finalize run memory:** Update `draft/.state/run-memory.json`:
1794
1814
  - `status`: `"completed"`
@@ -1799,7 +1819,7 @@ For **Brownfield** projects, announce:
1799
1819
  "Draft initialized successfully with comprehensive analysis!
1800
1820
 
1801
1821
  Created:
1802
- - draft/index.md (Open Knowledge Format bundle root cross-links every concept)
1822
+ - draft/index.md (plain docs index navigable table of contents for the draft/ bundle)
1803
1823
  - draft/.ai-profile.md (20-50 lines — ultra-compact always-injected profile, Tier 0)
1804
1824
  - draft/.ai-context.md (200-400 lines — token-optimized AI context, self-contained, Tier 1)
1805
1825
  - draft/architecture.md (comprehensive human-readable engineering reference, Tier 2)
@@ -1834,7 +1854,7 @@ For **Greenfield** projects, announce:
1834
1854
  "Draft initialized successfully!
1835
1855
 
1836
1856
  Created:
1837
- - draft/index.md (Open Knowledge Format bundle root cross-links every concept)
1857
+ - draft/index.md (plain docs index navigable table of contents for the draft/ bundle)
1838
1858
  - draft/product.md
1839
1859
  - draft/tech-stack.md
1840
1860
  - draft/workflow.md
@@ -2219,13 +2239,13 @@ Only when material: authentication/authorization checkpoints, distributed transa
2219
2239
 
2220
2240
  **Core rule:** The graph is the source of truth for structure. LLM synthesis exists only to interpret the graph into actionable design understanding — primarily via one accurate workflow or state diagram per module — plus tiny supporting notes. The previous volume-oriented deep-dive expectations are superseded.
2221
2241
 
2222
- For each module in `draft/graph/architecture.json` (`.packages[]`), produce a subsection whose **primary content** is the deterministic graph block followed by one synthesized behavioral diagram. Every module gets a slot; do not sample. The block's fan-in/out and node counts come from `.packages[]`; public API and key call edges come from live per-package queries (`scripts/tools/graph-callers.sh`, `graph-impact.sh`) and `hotspots.jsonl`.
2242
+ For each module returned by `scripts/tools/graph-arch.sh --repo . | jq '.packages[]'`, produce a subsection whose **primary content** is the deterministic graph block followed by one synthesized behavioral diagram. Every module gets a slot; do not sample. The block's fan-in/out and node counts come from `.packages[]`; public API and key call edges come from live per-package queries (`scripts/tools/graph-callers.sh`, `graph-impact.sh`) and `scripts/tools/hotspot-rank.sh --repo .`.
2223
2243
 
2224
2244
  #### 7.{N} {module-name}
2225
2245
 
2226
2246
  <!-- GRAPH:module-deep/{module-name}:START -->
2227
2247
  <!-- Rendered deterministic block: package name, node count, public API list, fan-in/fan-out (from
2228
- architecture.json .packages), hotspot fan-in (from hotspots.jsonl), key call edges (from
2248
+ get_architecture .packages), hotspot fan-in (from hotspot-rank.sh), key call edges (from
2229
2249
  graph-callers.sh/graph-impact.sh), entry points if known. No LLM prose inside fence. -->
2230
2250
  <!-- GRAPH:module-deep/{module-name}:END -->
2231
2251
 
@@ -2244,7 +2264,7 @@ Synthesize a single, accurate Mermaid diagram (`stateDiagram-v2`, `sequenceDiagr
2244
2264
 
2245
2265
  #### Sub-Module Guidance (when graph justifies recursion)
2246
2266
 
2247
- When a module has clear internal structure visible in `draft/graph/architecture.json` (`.packages` fan-in/out) or live per-package queries:
2267
+ When a module has clear internal structure visible in live engine query `get_architecture .packages` (fan-in/out) or live per-package queries:
2248
2268
  - Create `##### 7.X.Y {Parent}/{Child}` subsections only for children that have their own meaningful public surface or high internal fan-in.
2249
2269
  - Each sub-module subsection follows the same compact pattern: graph facts + **one mandatory workflow/state diagram** + ≤60 words Design Notes.
2250
2270
  - Do not descend further unless the child itself shows additional clear boundaries in the graph data.
@@ -2306,7 +2326,7 @@ Regardless of tier, any directory whose name contains `ops`, `handlers`, `execut
2306
2326
  | ... | (enumerate ALL — no sampling, no "and others") | | | |
2307
2327
  ```
2308
2328
 
2309
- Use `draft/graph/modules/{module}.jsonl` to get the complete file list with line counts. Use `draft/graph/hotspots.jsonl` to flag high-complexity operations.
2329
+ Use `scripts/tools/graph-callers.sh --symbol <module>` or `scripts/tools/graph-arch.sh --repo .` to get the complete file list. Use `scripts/tools/hotspot-rank.sh --repo .` to flag high-complexity operations.
2310
2330
 
2311
2331
  #### Example: Full Sub-Module Treatment for `icebox/` (917 files)
2312
2332
 
@@ -2353,7 +2373,7 @@ stateDiagram-v2
2353
2373
  After writing Section 7, run these checks before proceeding. **If any check fails, STOP and fix.**
2354
2374
 
2355
2375
  **Check 1 — Graph block present and faithful for every module:**
2356
- Every top-level module from `draft/graph/architecture.json` (`.packages`) has its `<!-- GRAPH:module-deep/...:START --> ... <!-- GRAPH:module-deep/...:END -->` fence rendered verbatim. No LLM prose inside the fence. No modules missing.
2376
+ Every top-level module from the live engine (`get_architecture .packages`) has its `<!-- GRAPH:module-deep/...:START --> ... <!-- GRAPH:module-deep/...:END -->` fence rendered verbatim. No LLM prose inside the fence. No modules missing.
2357
2377
 
2358
2378
  **Check 2 — One mandatory workflow/state diagram per module:**
2359
2379
  Every `#### 7.X` (and every `##### 7.X.Y` that the graph justified) contains exactly one high-signal `Primary Workflow / State` Mermaid diagram (`stateDiagram-v2`, `sequenceDiagram`, or clear `flowchart`). The diagram must reflect facts from the module's graph record (entry points, public symbols, call targets). Generic placeholder diagrams fail this check.
@@ -2457,12 +2477,13 @@ Include architecturally significant implementations (high fan-in, core extension
2457
2477
  |---|-----------|-------------|-------|-------------|
2458
2478
  | 1 | ArchiveFilesOp | `icebox/master/ops/archive_files_op.cc` | 2100 | Archives files to cloud vault |
2459
2479
  | 2 | CancelJobOp | `icebox/master/ops/cancel_job_op.cc` | 450 | Cancels running archive job |
2460
- | (enumerate ALL — use graph hotspots.jsonl and per-module JSONL for file list and line counts) |
2480
+ | (enumerate ALL — use hotspot-rank.sh and graph-callers.sh / get_architecture for file list and line counts) |
2461
2481
  ```
2462
2482
 
2463
- > **MANDATORY (graph data)**: Read `draft/graph/modules/{module}.jsonl` to get the complete file
2464
- > list with line counts. Filter for files in operation sub-directories (paths containing `/ops/`,
2465
- > `/handlers/`, `/executors/`, `/workers/`). Use `draft/graph/hotspots.jsonl` to flag
2483
+ > **MANDATORY (graph data)**: Query `scripts/tools/graph-arch.sh --repo .` or
2484
+ > `scripts/tools/graph-callers.sh --symbol <module>` to get the complete file list with line counts.
2485
+ > Filter for files in operation sub-directories (paths containing `/ops/`,
2486
+ > `/handlers/`, `/executors/`, `/workers/`). Use `scripts/tools/hotspot-rank.sh --repo .` to flag
2466
2487
  > high-complexity operations (high line count or fanIn). Do NOT skip this step — incomplete
2467
2488
  > catalogs cause AI agents to reinvent existing functionality.
2468
2489
 
@@ -3153,11 +3174,11 @@ Fix: Add actual payload descriptions on arrows, `alt`/`opt` blocks for condition
3153
3174
 
3154
3175
  **FAILURE 3 — Empty Appendices:**
3155
3176
  Detection: Appendix B, C, or D tables have fewer than 10 data rows.
3156
- Fix: Cross-reference ALL data sources (Appendix B), ALL implementation outputs (Appendix C), and add 2-3 detailed sequence diagrams to Appendix D. Use graph data (`architecture.json` `.packages`/`.routes`) to enumerate exhaustively.
3177
+ Fix: Cross-reference ALL data sources (Appendix B), ALL implementation outputs (Appendix C), and add 2-3 detailed sequence diagrams to Appendix D. Use live engine queries (`get_architecture .packages`/`.routes`) to enumerate exhaustively.
3157
3178
 
3158
3179
  **FAILURE 4 — Missing Sub-Modules:**
3159
3180
  Detection: A module with 100+ source files (check graph data) has no Sub-Module Structure table.
3160
- Fix: Read `draft/graph/modules/{name}.jsonl`, group files by immediate sub-directory, and generate the table with file counts and one-line role descriptions per sub-directory.
3181
+ Fix: Query `scripts/tools/graph-arch.sh --repo .` or `scripts/tools/graph-callers.sh --symbol <name>`, group results by immediate sub-directory, and generate the table with file counts and one-line role descriptions per sub-directory.
3161
3182
 
3162
3183
  **FAILURE 4b — Shallow Sub-Module Treatment:**
3163
3184
  Detection: Large sub-modules (50+ files) listed only as table rows with no dedicated deep-dive subsection. Or ops/handler directories have no operation catalog.
@@ -3258,7 +3279,7 @@ echo "Engine: $ENGINE"
3258
3279
 
3259
3280
  ## Step 3: Build / refresh the snapshot
3260
3281
 
3261
- One call resolves the engine, indexes the repo (incrementally on refresh), and writes the committed snapshot under `<repo>/draft/graph/` — `schema.yaml`, `architecture.json`, `hotspots.jsonl`, `module-deps.mermaid`, `proto-map.mermaid`, and an Open Knowledge Format bundle under `okf/` (a portable, vendor-neutral markdown mirror of the graph`index.md` + one cross-linked `modules/<name>.md` concept per module).
3282
+ One call resolves the engine, indexes the repo (incrementally on refresh), and updates the gate marker `<repo>/draft/graph/schema.yaml` (engine metadata + point-of-index counts; `access: engine-live`). All structural graph data is queried live from the engineno snapshot files are committed beyond `schema.yaml`.
3262
3283
 
3263
3284
  ```bash
3264
3285
  scripts/tools/graph-snapshot.sh --repo "$REPO_ABS"
@@ -4162,8 +4183,8 @@ You are decomposing a project or track into modules with clear responsibilities,
4162
4183
 
4163
4184
  When `draft/graph/schema.yaml` exists, this skill **must** follow the graph-first lookup contract in [core/shared/graph-query.md](../../core/shared/graph-query.md) §Mandatory Lookup Contract. Module identification (Step 3) and dependency mapping (Step 4) **start from the graph**:
4164
4185
 
4165
- 1. Load `draft/graph/architecture.json` (`.packages`) for the authoritative module list and fan-in/out.
4166
- 2. Load `draft/graph/hotspots.jsonl` to identify candidate modules to split.
4186
+ 1. Query `scripts/tools/graph-arch.sh --repo .` for the authoritative module list and fan-in/out.
4187
+ 2. Run `scripts/tools/hotspot-rank.sh --repo .` to identify candidate modules to split.
4167
4188
  3. Use `scripts/tools/graph-callers.sh`/`graph-impact.sh` on demand for symbols/callers inside a candidate module.
4168
4189
  4. Run `scripts/tools/cycle-detect.sh --repo .` to enumerate existing cycles before proposing new boundaries.
4169
4190
 
@@ -4307,10 +4328,10 @@ ls -d src/*/ lib/*/ app/*/ packages/*/ 2>/dev/null
4307
4328
 
4308
4329
  When graph data is available, the graph is the **primary** (not optional) source for module discovery — manual scanning above is reserved for the graph-miss fallback path:
4309
4330
 
4310
- - **Module boundaries**: Read `draft/graph/architecture.json` (`.packages`, `.languages`) — module list with node counts and per-language file counts
4331
+ - **Module boundaries**: Query `scripts/tools/graph-arch.sh --repo .` — module list with node counts and per-language file counts
4311
4332
  - **Dependency edges**: Weighted inter-module dependencies with exact include counts — replaces manual import tracing
4312
4333
  - **Cycle detection**: Circular dependency paths already computed — use for identifying tight coupling and decomposition candidates
4313
- - **Hotspots**: Load `draft/graph/hotspots.jsonl` — high-complexity files that may need further decomposition
4334
+ - **Hotspots**: Run `scripts/tools/hotspot-rank.sh --repo .` — high-complexity files that may need further decomposition
4314
4335
  - **Per-module detail**: query `scripts/tools/graph-callers.sh`/`graph-impact.sh` for symbol/call detail within modules of interest
4315
4336
 
4316
4337
  This data is deterministic and exhaustive. The manual scanning recipes above only run **after** the graph misses on the concept the user named — and the miss must be reported in the Graph Usage Report footer. See [core/shared/graph-query.md](../../core/shared/graph-query.md) §Concept-to-Files Recipe.
@@ -4766,7 +4787,7 @@ When decomposition involves breaking a monolith, choosing module boundaries, or
4766
4787
 
4767
4788
  Before printing the completion announcement, internally verify and report:
4768
4789
 
4769
- 1. **Graph files queried** — which JSONL files were loaded (e.g. `architecture.json, hotspots.jsonl` and tools like `cycle-detect.sh`).
4790
+ 1. **Graph data queried** — which live-engine tools were invoked (e.g. `get_architecture`, `hotspot-rank.sh`, `cycle-detect.sh`).
4770
4791
  2. **Layer 1 files deliberately skipped** — list any `.ai-context.md` sections, `tech-stack.md`, `product.md`, `workflow.md` you skipped as irrelevant to this decomposition. Be explicit; do not silently skip.
4771
4792
  3. **Filesystem grep fallback justification** — for every `grep`/`find` run, state the concept it searched for and quote the graph-miss sentence.
4772
4793
  4. **Citation Gate audit** — scan every Citation column in the generated component table, dependencies table, and LLD class table. Report:
@@ -4940,7 +4961,7 @@ If one of these applies, route directly to the specialist workflow and stop this
4940
4961
  - Keep matching invariants as **active constraints** for this task — these govern code generation, not just review
4941
4962
  - If invariants reference lock ordering, fail-closed behavior, or data integrity rules: these are non-negotiable during implementation
4942
4963
  9. **Load graph context** (if `draft/graph/schema.yaml` exists):
4943
- - Read `draft/graph/hotspots.jsonl` — check if any files this task will modify appear as hotspots
4964
+ - Run `scripts/tools/hotspot-rank.sh --repo .` — check if any files this task will modify appear as hotspots
4944
4965
  - If modifying a hotspot file (high fanIn), warn: "This task modifies {file} (fanIn={N}). Changes here affect many downstream files. Consider running a graph impact query."
4945
4966
  - Query `scripts/tools/graph-impact.sh`/`graph-callers.sh` for the module(s) being modified — gives file-level dependency context
4946
4967
  - See `core/shared/graph-query.md` for on-demand query subroutines (callers, impact)
@@ -5949,8 +5970,8 @@ You are generating a pre-deployment verification checklist customized to this pr
5949
5970
  When `draft/graph/schema.yaml` exists, this skill **must** follow the graph-first lookup contract in [core/shared/graph-query.md](../../core/shared/graph-query.md) §Mandatory Lookup Contract. Use the graph to validate module boundaries before the deploy:
5950
5971
 
5951
5972
  1. For each file in the deploy diff, run `scripts/tools/graph-impact.sh --repo . --file <path>` to enumerate the modules affected — flag any module **not** declared in `hld.md` §Detailed Design as a deployment-scope miss.
5952
- 2. Run `scripts/tools/cycle-detect.sh --repo .` (and read `draft/graph/architecture.json` for the module overview) to ensure no fresh cycles were introduced after HLD sign-off.
5953
- 3. Load `draft/graph/hotspots.jsonl` — any hotspot in the diff escalates the Resiliency row of Phase 0.
5973
+ 2. Run `scripts/tools/cycle-detect.sh --repo .` (and query `scripts/tools/graph-arch.sh --repo .` for the module overview) to ensure no fresh cycles were introduced after HLD sign-off.
5974
+ 3. Run `scripts/tools/hotspot-rank.sh --repo .` — any hotspot in the diff escalates the Resiliency row of Phase 0.
5954
5975
 
5955
5976
  Filesystem `grep` is reserved for source-text scans (migration file names, flag-key strings). Module/impact discovery goes through the graph.
5956
5977
 
@@ -6259,7 +6280,7 @@ Read and follow the base procedure in `core/shared/draft-context-loading.md`.
6259
6280
  - **Leverage Storage Topology** — Identify data loss risks at each tier (cache eviction without writeback, event log gaps, missing archive)
6260
6281
  - **Leverage Consistency Boundaries** — Find bugs at eventual consistency seams (stale reads, lost events, missing reconciliation)
6261
6282
  - **Leverage Failure Recovery Matrix** — Verify idempotency claims, check for partial failure states without recovery paths
6262
- - **Leverage Graph Data** (if `draft/graph/` exists) — Read `architecture.json` (`.packages`) for dependency awareness. Flag dependencies on unexpected modules. Flag code in modules involved in dependency cycles as higher risk. Use `hotspots.jsonl` to prioritize analysis of high-complexity, high-fanIn files. See `core/shared/graph-query.md`.
6283
+ - **Leverage Graph Data** (if `draft/graph/` exists) — Query `scripts/tools/graph-arch.sh --repo .` for dependency awareness. Flag dependencies on unexpected modules. Flag code in modules involved in dependency cycles as higher risk. Run `scripts/tools/hotspot-rank.sh --repo .` to prioritize analysis of high-complexity, high-fanIn files. See `core/shared/graph-query.md`.
6263
6284
  - **Leverage Learned Anti-Patterns** — If `draft/guardrails.md` exists, read the `## Learned Anti-Patterns` section. During the bug sweep, when a bug matches a learned anti-pattern, prefix the report entry with `[KNOWN-ANTI-PATTERN: {pattern name}]`. This distinguishes recurring documented patterns from newly discovered bugs, and signals that a systemic fix may be needed rather than a one-off patch.
6264
6285
 
6265
6286
  ### 2. Confirm Scope
@@ -7283,7 +7304,7 @@ You are conducting a code review using Draft's Context-Driven Development method
7283
7304
 
7284
7305
  When `draft/graph/schema.yaml` exists, this skill **must** follow the graph-first lookup contract in [core/shared/graph-query.md](../../core/shared/graph-query.md) §Mandatory Lookup Contract. Stage 1 (Automated Validation) **starts from the graph**:
7285
7306
 
7286
- 1. Run blast-radius assessment from `draft/graph/hotspots.jsonl` and `scripts/tools/graph-impact.sh` (see Stage 1).
7307
+ 1. Run blast-radius assessment via `scripts/tools/hotspot-rank.sh --repo .` and `scripts/tools/graph-impact.sh` (see Stage 1).
7287
7308
  2. For each changed file with non-trivial diff size, run `scripts/tools/graph-impact.sh --repo . --file <path>` to obtain the affected module set deterministically.
7288
7309
  3. For each public symbol modified, run `scripts/tools/graph-callers.sh --repo . --symbol <name>` to enumerate downstream callers before judging breaking-change severity.
7289
7310
 
@@ -7642,18 +7663,18 @@ For the files changed in the diff, perform static checks using `grep` or similar
7642
7663
 
7643
7664
  - **Blast Radius Assessment** (if the `draft/graph/` snapshot exists):
7644
7665
  - List all changed files from the diff
7645
- - For each changed file, check if it appears in `hotspots.jsonl` — if yes, record its `fanIn` value
7646
- - Classify: files with fanIn in the top 20% of the hotspots list = **HIGH IMPACT**; top 21–50% = **MEDIUM**; below 50% or not in list = **STANDARD**
7647
- - For any file in a HIGH or MEDIUM module, check `architecture.json` `.packages[].fan_in` (how many modules depend on this module)
7666
+ - For each changed file, check if it appears in `scripts/tools/hotspot-rank.sh --repo .` output — if yes, record its `fanIn` value
7667
+ - Classify: files with fanIn in the top 20% of the hotspot output = **HIGH IMPACT**; top 21–50% = **MEDIUM**; below 50% or not in output = **STANDARD**
7668
+ - For any file in a HIGH or MEDIUM module, query `scripts/tools/graph-arch.sh --repo . | jq '.packages[].fan_in'` (how many modules depend on this module)
7648
7669
  - Include a `Blast Radius` line in the Stage 1 report summary: `Blast Radius: HIGH | MEDIUM | STANDARD — <N> changed files affect high-fanIn modules: [file list]`
7649
7670
  - If any changed file is HIGH IMPACT: escalate Stage 3 thoroughness (check all callers of changed functions) and note this in the report header
7650
7671
  - **Architecture Conformance:** Search for pattern violations documented in `draft/.ai-context.md`. (e.g. `import * from 'database'` in a React component).
7651
7672
  - **Dead Code:** Check for newly exported functions/classes in the diff that have 0 references across the codebase.
7652
7673
  - **Dependency Cycles:** Trace the import chains for new imports to ensure no circular dependencies (e.g., A → B → C → A) are introduced.
7653
- - **Graph Boundary Check** (if `draft/graph/architecture.json` exists) `[RC-013]`:
7674
+ - **Graph Boundary Check** (if `draft/graph/schema.yaml` exists) `[RC-013]`:
7654
7675
  - For each changed file, identify its module from the graph
7655
7676
  - Check if any new cross-module includes were added in the diff
7656
- - Verify they follow the established dependency direction from `architecture.json` package fan-in/out
7677
+ - Verify they follow the established dependency direction from `scripts/tools/graph-arch.sh --repo .` package fan-in/out
7657
7678
  - Flag reverse-direction dependencies (module A now depends on module B, but only B→A existed before) as "Potential architecture violation — new dependency direction"
7658
7679
  - Check if changes introduce files in modules listed in graph cycles — flag as higher risk
7659
7680
  - **Security Scan** `[RC-001, RC-002, RC-003, RC-011]`:
@@ -8347,7 +8368,7 @@ If Jira ticket linked, sync via `core/shared/jira-sync.md`:
8347
8368
 
8348
8369
  Before printing the final verdict, internally verify and report:
8349
8370
 
8350
- 1. **Graph files queried** — which JSONL files were loaded (e.g. `architecture.json, hotspots.jsonl`) plus any live graph query-tool invocations (impact, callers, cycles).
8371
+ 1. **Graph data queried** — which live-engine tools were invoked (e.g. `get_architecture`, `hotspot-rank.sh`, `graph-impact.sh`, `graph-callers.sh`, `cycle-detect.sh`).
8351
8372
  2. **Layer 1 files deliberately skipped** — list any context sections skipped as irrelevant to the diff under review.
8352
8373
  3. **Filesystem grep fallback justification** — for every `grep`/`find` run, state the concept it searched for. Source-text scans (string literals, regex matches in code) are exempt — they are not symbol/file discovery.
8353
8374
 
@@ -10690,7 +10711,7 @@ You are performing a lightweight, ad-hoc code review. This is the fast alternati
10690
10711
 
10691
10712
  When `draft/graph/schema.yaml` exists, this skill **must** follow the graph-first lookup contract in [core/shared/graph-query.md](../../core/shared/graph-query.md) §Mandatory Lookup Contract. Quick-review keeps the graph load light:
10692
10713
 
10693
- 1. Always check `draft/graph/hotspots.jsonl` for every changed file (Step 2 blast-radius pre-check below).
10714
+ 1. Always run `scripts/tools/hotspot-rank.sh --repo .` for every changed file (Step 2 blast-radius pre-check below).
10694
10715
  2. If a finding spans more than one file, run `scripts/tools/graph-callers.sh --repo . --symbol <name>` to enumerate the call sites before claiming "no other usages".
10695
10716
 
10696
10717
  Filesystem `grep` is reserved for source-text scans (literal strings, regex patterns). Symbol and caller discovery go through the graph.
@@ -10747,9 +10768,9 @@ Determine the diff to review:
10747
10768
  3. If commit range: `git diff <range>`
10748
10769
  4. Default: `git diff HEAD~1..HEAD` (last commit)
10749
10770
 
10750
- ## Step 2: Blast Radius Pre-check (if `draft/graph/hotspots.jsonl` exists)
10771
+ ## Step 2: Blast Radius Pre-check (if `draft/graph/schema.yaml` exists)
10751
10772
 
10752
- Before the four-dimension review, check if any files in scope appear in `draft/graph/hotspots.jsonl`. If any file has a `fanIn` in the top 20% of the list, add this warning at the top of the review report:
10773
+ Before the four-dimension review, run `scripts/tools/hotspot-rank.sh --repo .` and check if any files in scope appear in the output. If any file has a `fanIn` in the top 20% of the list, add this warning at the top of the review report:
10753
10774
 
10754
10775
  ```
10755
10776
  ⚠ HIGH IMPACT: {file} is a high-fanIn hotspot (fanIn={N}). Changes here propagate to many callers — review with extra care.
@@ -10906,10 +10927,10 @@ Perform an exhaustive end-to-end lifecycle review of a service, component, or mo
10906
10927
 
10907
10928
  When `draft/graph/schema.yaml` exists, this skill **must** follow the graph-first lookup contract in [core/shared/graph-query.md](../../core/shared/graph-query.md) §Mandatory Lookup Contract. Deep-review uses the graph to **narrow review scope** — a key 30–50% scope reduction:
10908
10929
 
10909
- 1. Use `scripts/tools/graph-impact.sh`/`graph-callers.sh` and `architecture.json` for the audited module's structure — do not enumerate via `find`.
10930
+ 1. Use `scripts/tools/graph-impact.sh`/`graph-callers.sh` and `scripts/tools/graph-arch.sh --repo .` for the audited module's structure — do not enumerate via `find`.
10910
10931
  2. Run `scripts/tools/graph-impact.sh --repo . --file <each-changed-file>` per file in the diff (or per file in the module if no diff) to obtain the affected module set deterministically.
10911
10932
  3. Run `scripts/tools/cycle-detect.sh --repo .` and flag any cycle that includes the audited module as Architecture Resilience finding.
10912
- 4. Cross-check `draft/graph/hotspots.jsonl` to identify high-fanIn files inside the module — these get deeper inspection.
10933
+ 4. Run `scripts/tools/hotspot-rank.sh --repo .` to identify high-fanIn files inside the module — these get deeper inspection.
10913
10934
 
10914
10935
  Filesystem `grep` is reserved for source-text scans (API contract strings, secret patterns, log message audits). Module enumeration and caller tracing go through the graph.
10915
10936
 
@@ -11427,8 +11448,8 @@ Scan the codebase to discover recurring coding patterns and update `draft/guardr
11427
11448
 
11428
11449
  When `draft/graph/schema.yaml` exists, this skill **must** follow the graph-first lookup contract in [core/shared/graph-query.md](../../core/shared/graph-query.md) §Mandatory Lookup Contract. Use the graph to:
11429
11450
 
11430
- 1. Enumerate a module's symbols/files via `scripts/tools/graph-callers.sh`/`graph-impact.sh` and `architecture.json` (preferred over `find`).
11431
- 2. Prioritize hotspots from `draft/graph/hotspots.jsonl` — patterns in high-fanIn files are more impactful when learned.
11451
+ 1. Enumerate a module's symbols/files via `scripts/tools/graph-callers.sh`/`graph-impact.sh` and `scripts/tools/graph-arch.sh --repo .` (preferred over `find`).
11452
+ 2. Prioritize hotspots via `scripts/tools/hotspot-rank.sh --repo .` — patterns in high-fanIn files are more impactful when learned.
11432
11453
  3. For TS/Python/Go/C/C++, use `*-index.jsonl` to identify class/function definitions rather than re-discovering them via regex.
11433
11454
 
11434
11455
  Filesystem `find` for source discovery (Step 2.1) is permitted **as a complement** to the graph for languages not covered by indexes (e.g. Ruby, Java without ctags). Record the rationale in the Graph Usage Report.
@@ -11662,15 +11683,15 @@ git log --follow --oneline -1 -- {file_containing_pattern}
11662
11683
 
11663
11684
  ### 2.7: Graph-Aware Severity Enrichment
11664
11685
 
11665
- If `draft/graph/hotspots.jsonl` exists, derive objective severity for all anti-pattern candidates based on the fanIn of files where the pattern was found.
11686
+ If `draft/graph/schema.yaml` exists (engine live), derive objective severity for all anti-pattern candidates based on the fanIn of files where the pattern was found via `scripts/tools/hotspot-rank.sh --repo .`.
11666
11687
 
11667
11688
  For each anti-pattern candidate from Step 2.2:
11668
- 1. Check if any evidence files appear in `draft/graph/hotspots.jsonl`
11689
+ 1. Check if any evidence files appear in the hotspot output from `scripts/tools/hotspot-rank.sh --repo .`
11669
11690
  2. Take the highest fanIn value across all evidence files:
11670
11691
  - fanIn ≥ 10 → `graph_severity: critical` (breakage propagates to many callers)
11671
11692
  - fanIn 5–9 → `graph_severity: high`
11672
11693
  - fanIn 1–4 → `graph_severity: medium`
11673
- - fanIn 0 or file not in hotspots.jsonl → `graph_severity: low`
11694
+ - fanIn 0 or file not in hotspot output → `graph_severity: low`
11674
11695
  3. If no graph data exists → `graph_severity: unresolved`
11675
11696
 
11676
11697
  Collect all evidence files with fanIn ≥ 5 for the `high_fanin_files` field.
@@ -12279,10 +12300,10 @@ You are conducting a structured debugging session following systematic investiga
12279
12300
 
12280
12301
  When `draft/graph/schema.yaml` exists, this skill **must** follow the graph-first lookup contract in [core/shared/graph-query.md](../../core/shared/graph-query.md) §Mandatory Lookup Contract. During Steps 3–4 (Isolate, Diagnose):
12281
12302
 
12282
- 1. Locate the suspect file's module via `draft/graph/architecture.json` (`.packages`) before tracing data flow.
12303
+ 1. Locate the suspect file's module via `scripts/tools/graph-arch.sh --repo .` before tracing data flow.
12283
12304
  2. Use `scripts/tools/graph-callers.sh --repo . --symbol <fn>` to enumerate call sites of suspect functions — not `grep`.
12284
12305
  3. Use `scripts/tools/graph-impact.sh --repo . --file <path>` to size the blast radius before proposing a fix.
12285
- 4. Cross-check `draft/graph/hotspots.jsonl` to know whether the file is high-fanIn (any fix needs extra caution).
12306
+ 4. Run `scripts/tools/hotspot-rank.sh --repo .` to know whether the file is high-fanIn (any fix needs extra caution).
12286
12307
 
12287
12308
  Filesystem `grep` is reserved for source-text scans (literal error strings, stack-trace symbols when the graph misses). Use the fallback sentence on graph miss.
12288
12309
 
@@ -12330,7 +12351,7 @@ Key context for debugging:
12330
12351
  - `.ai-context.md` — Module boundaries, data flows, invariants (crucial for tracing)
12331
12352
  - `tech-stack.md` — Language-specific debugging tools and techniques
12332
12353
  - `guardrails.md` — Known anti-patterns that may be causing the issue
12333
- - `draft/graph/` (MANDATORY when present) — Load `architecture.json` for dependency/module context and `hotspots.jsonl` for complexity awareness. Use `scripts/tools/graph-callers.sh --repo . --symbol <fn>` to find all callers, and `scripts/tools/graph-impact.sh --repo . --file <path>` to size blast radius before any fix. See [core/shared/graph-query.md](../../core/shared/graph-query.md).
12354
+ - `draft/graph/` (MANDATORY when present) — Query `scripts/tools/graph-arch.sh --repo .` for dependency/module context and `scripts/tools/hotspot-rank.sh --repo .` for complexity awareness. Use `scripts/tools/graph-callers.sh --repo . --symbol <fn>` to find all callers, and `scripts/tools/graph-impact.sh --repo . --file <path>` to size blast radius before any fix. See [core/shared/graph-query.md](../../core/shared/graph-query.md).
12334
12355
 
12335
12356
  ## Step 1: Parse Arguments
12336
12357
 
@@ -12663,8 +12684,8 @@ You are conducting a technical debt analysis to catalog, prioritize, and plan re
12663
12684
 
12664
12685
  When `draft/graph/schema.yaml` exists, this skill **must** follow the graph-first lookup contract in [core/shared/graph-query.md](../../core/shared/graph-query.md) §Mandatory Lookup Contract. Tech-debt prioritization is fundamentally driven by graph data:
12665
12686
 
12666
- 1. Load `draft/graph/hotspots.jsonl` — **rank candidates by `fanIn × complexity`** to surface high-leverage debt first.
12667
- 2. Read `draft/graph/architecture.json` (`.packages`) and run `scripts/tools/cycle-detect.sh --repo .` — flag debt in modules involved in cycles as higher priority.
12687
+ 1. Run `scripts/tools/hotspot-rank.sh --repo .` — **rank candidates by `fanIn × complexity`** to surface high-leverage debt first.
12688
+ 2. Query `scripts/tools/graph-arch.sh --repo .` and run `scripts/tools/cycle-detect.sh --repo .` — flag debt in modules involved in cycles as higher priority.
12668
12689
  3. Run `scripts/tools/cycle-detect.sh --repo .` to enumerate dependency cycles — every cycle is a candidate architecture-debt entry.
12669
12690
  4. For each catalogued finding, run `scripts/tools/graph-impact.sh --repo . --file <path>` so the remediation plan includes blast-radius.
12670
12691
 
@@ -15787,13 +15808,9 @@ If `draft/graph/schema.yaml` exists, the project has automated graph analysis da
15787
15808
 
15788
15809
  | File | Purpose | Content |
15789
15810
  |------|---------|---------|
15790
- | `draft/graph/schema.yaml` | Snapshot metadata (engine, project, node/edge counts) | YAML, ~15 lines |
15791
- | `draft/graph/architecture.json` | Node labels, edge types, languages, packages (fan-in/out), entry points, routes, hotspots | JSON |
15792
- | `draft/graph/hotspots.jsonl` | Fan-in-ranked symbols, one object per line: `{id, name, fanIn}` | JSONL |
15793
-
15794
- The snapshot also includes `draft/graph/okf/` — an Open Knowledge Format v0.1 bundle (`index.md` + `modules/*.md`) emitted by default. It is a portable mirror of the graph, not an always-load target.
15811
+ | `draft/graph/schema.yaml` | Gate marker (engine + project metadata + point-of-index counts); presence gates graph use | YAML, ~15 lines |
15795
15812
 
15796
- Note: `.ai-context.md` embeds a condensed graph summary (`GRAPH:MODULES`, `GRAPH:HOTSPOTS`, `GRAPH:CYCLES`) for first-pass structural ground truth. `architecture.json` is authoritative for deep structure.
15813
+ Note: `.ai-context.md` embeds a condensed graph summary (`GRAPH:MODULES`, `GRAPH:HOTSPOTS`, `GRAPH:CYCLES`) for first-pass structural ground truth. Deep structural data is queried live from the engine (see Live structural queries below).
15797
15814
 
15798
15815
  Note: The canonical embedded mermaid diagrams are in architecture.md injection slots (`<!-- GRAPH:module-deps:START/END -->`, `<!-- GRAPH:proto-map:START/END -->`), refreshed by `draft:init`. For current data, regenerate via `scripts/tools/mermaid-from-graph.sh`.
15799
15816
 
@@ -15867,12 +15884,12 @@ Do NOT apply relevance scoring for commands that need full context (`draft init`
15867
15884
  | `## FILES` | Always (need file locations) |
15868
15885
  | `## VOCAB` | Domain-specific tasks |
15869
15886
 
15870
- 3. **Score graph files** (if `draft/graph/` exists) against the task concepts:
15887
+ 3. **Score graph queries** (if `draft/graph/schema.yaml` exists) against the task concepts:
15871
15888
 
15872
15889
  | Graph source | Use When Task Involves... |
15873
15890
  |------------|--------------------------|
15874
- | `architecture.json` | Module boundary changes, cross-module work, architecture analysis, API/route surface |
15875
- | `hotspots.jsonl` | Performance work, refactoring, changes to high-fanIn symbols |
15891
+ | `scripts/tools/graph-arch.sh --repo .` | Module boundary changes, cross-module work, architecture analysis, API/route surface |
15892
+ | `scripts/tools/hotspot-rank.sh --repo .` | Performance work, refactoring, changes to high-fanIn symbols |
15876
15893
  | `scripts/tools/graph-callers.sh --symbol <name>` | Enumerating callers before a change |
15877
15894
  | `scripts/tools/graph-impact.sh --file <path>` / `--symbol <name>` | Tracing call paths, root cause analysis, function-level impact |
15878
15895
  | `scripts/tools/cycle-detect.sh` | Checking for call cycles |
@@ -16233,11 +16250,11 @@ Append under `## Learned Anti-Patterns`:
16233
16250
  - **Suggested fix:** [Brief description of the correct approach]
16234
16251
  ```
16235
16252
 
16236
- `graph_severity` derivation rules (from `draft/graph/hotspots.jsonl` fanIn values):
16253
+ `graph_severity` derivation rules (from live hotspot query `scripts/tools/hotspot-rank.sh --repo .` fanIn values):
16237
16254
  - fanIn ≥ 10 in any evidence file → `critical`
16238
16255
  - fanIn 5–9 → `high`
16239
16256
  - fanIn 1–4 → `medium`
16240
- - fanIn 0 or file not in hotspots.jsonl → `low`
16257
+ - fanIn 0 or file not returned by hotspot query → `low`
16241
16258
  - Graph data absent → `unresolved`
16242
16259
 
16243
16260
  When `graph_severity` differs from `severity`, use `graph_severity` as the enforcement priority — it is objective and graph-derived.
@@ -16367,16 +16384,16 @@ Transform each `architecture.md` section into machine-optimized format using thi
16367
16384
 
16368
16385
  #### Step 3.5: Generate Graph Summary Sections
16369
16386
 
16370
- If `draft/graph/schema.yaml` exists, generate these sections from the snapshot (`draft/graph/architecture.json`, `draft/graph/hotspots.jsonl`) and the live query tools:
16387
+ If `draft/graph/schema.yaml` exists, generate these sections via live engine queries.
16371
16388
 
16372
16389
  **GRAPH:MODULES** (tier ≥ 2 only):
16373
- - Read `draft/graph/architecture.json` `.packages[]` (each has `name`, `node_count`, `fan_in`, `fan_out`)
16390
+ - Query: `scripts/tools/graph-arch.sh --repo . | jq '.packages[]'` (each has `name`, `node_count`, `fan_in`, `fan_out`)
16374
16391
  - Format: `{name}|{node_count} nodes|fan_in:{fan_in} fan_out:{fan_out}`
16375
16392
  - Order by `node_count` descending
16376
16393
  - Omit this section entirely for tier-1 codebases (≤5 modules) where Component Graph is sufficient
16377
16394
 
16378
16395
  **GRAPH:HOTSPOTS** (all tiers):
16379
- - Read `draft/graph/hotspots.jsonl` (already fan-in-ranked), take top 10
16396
+ - Query: `scripts/tools/hotspot-rank.sh --repo . --top 10`; take top 10 results
16380
16397
  - Format: `{name}|fanIn:{fanIn}` (use `id` for disambiguation when names collide)
16381
16398
  - Always include regardless of tier
16382
16399
 
@@ -16387,20 +16404,20 @@ If `draft/graph/schema.yaml` exists, generate these sections from the snapshot (
16387
16404
  - Always include — absence is positive signal that the call graph is acyclic
16388
16405
 
16389
16406
  **GRAPH:MODULE-HOTSPOTS** (tier ≥ 3 only):
16390
- - Read `draft/graph/hotspots.jsonl`; group by the package segment of each `id` (the qualified name minus the leaf symbol)
16407
+ - Query: `scripts/tools/hotspot-rank.sh --repo .`; group results by the package segment of each `id` (the qualified name minus the leaf symbol)
16391
16408
  - For each module: take its top 3 symbols by `fanIn`, format as indented lines under the module name
16392
16409
  - Format: `{module}: {name}|fanIn:{N}` with subsequent symbols indented to align
16393
16410
  - Order modules by their highest-fanIn symbol, descending
16394
16411
  - Omit modules with no hotspot entries; omit entire section for tier 1–2 (covered by global GRAPH:HOTSPOTS)
16395
16412
 
16396
16413
  **GRAPH:FAN-IN** (tier ≥ 3 only):
16397
- - Read `architecture.json` `.packages[]`, use the `fan_in` field per module
16414
+ - Query: `scripts/tools/graph-arch.sh --repo . | jq '.packages[]'`, use the `fan_in` field per module
16398
16415
  - Format: `{name}|fanIn:{fan_in}|fanOut:{fan_out}`
16399
16416
  - Order by `fan_in` descending; include only modules with `fan_in ≥ 2`; cap at 15 rows
16400
16417
  - Omit entire section for tier 1–2 (trivially small graph)
16401
16418
 
16402
- **GRAPH:PROTO-MAP** (only when `architecture.json` `.routes` is non-empty):
16403
- - Read `architecture.json` `.routes[]` (each has `method`, `path`, `handler`)
16419
+ **GRAPH:PROTO-MAP** (only when routes are non-empty):
16420
+ - Query: `scripts/tools/graph-arch.sh --repo . | jq '.routes[]'` (each has `method`, `path`, `handler`)
16404
16421
  - Format: `{method} {path} → {handler}`
16405
16422
  - One line per route
16406
16423
  - Omit entire section if `.routes` is empty — do not write an empty section
@@ -16447,7 +16464,7 @@ Before writing `draft/.ai-context.md`, verify:
16447
16464
  - [ ] GRAPH:CYCLES present ("None ✓" or cycle list; or note if graph absent)
16448
16465
  - [ ] GRAPH:MODULE-HOTSPOTS present for tier ≥ 3 (or note if no hotspot data)
16449
16466
  - [ ] GRAPH:FAN-IN present for tier ≥ 3
16450
- - [ ] GRAPH:PROTO-MAP present when `stats.proto_rpcs > 0` (omit entirely if no protos)
16467
+ - [ ] GRAPH:PROTO-MAP present when engine reports non-empty routes (omit entirely if no protos)
16451
16468
  - [ ] YAML frontmatter metadata is present at the top
16452
16469
 
16453
16470
  #### Step 7: Write Output
@@ -16837,7 +16854,7 @@ Referenced by: `draft init`, `draft implement`, `draft bughunt`, `draft review`,
16837
16854
 
16838
16855
  Any code-touching skill that needs to discover files, modules, symbols, callers, or blast-radius **MUST** follow this lookup order whenever `draft/graph/schema.yaml` exists:
16839
16856
 
16840
- 1. **Graph first** — the committed snapshot (`architecture.json`, `hotspots.jsonl`) and the live query tools (`scripts/tools/graph-callers.sh`, `graph-impact.sh`, `cycle-detect.sh`, `hotspot-rank.sh`).
16857
+ 1. **Graph first** — live engine queries via the query tools (`scripts/tools/graph-callers.sh`, `graph-impact.sh`, `cycle-detect.sh`, `hotspot-rank.sh`, `mermaid-from-graph.sh`), which drive the local `codebase-memory-mcp` engine on demand. Draft is **engine-only**: there is no committed machine-readable graph to read — `draft/graph/` holds only `schema.yaml` (the gate marker).
16841
16858
  2. **Generated context second** — `draft/.ai-context.md`, relevant `draft/architecture.md` slices, track-level `hld.md`/`lld.md`.
16842
16859
  3. **Source file reads third** — narrow via tiers 1–2, then **Read** the candidate files. Reading is **not optional**: see §Ground-Truth Discipline below.
16843
16860
  4. **Filesystem `grep`/`find`/`rg` last** — only after an explicit graph miss.
@@ -16882,10 +16899,10 @@ A single "no" / "list" answer is a halt — fix and re-check before output.
16882
16899
 
16883
16900
  Use this recipe whenever the user names a concept, feature, or domain term ("in-memory shuffle", "auth flow", "ingest pipeline") and you need to locate the implementing files. **Run it before any filesystem search.**
16884
16901
 
16885
- 1. **Concept → modules** — `grep` the concept token against `draft/graph/architecture.json` (`.packages[].name`) and `draft/.ai-context.md` (module headings). Record the candidate module list.
16902
+ 1. **Concept → modules** — query the engine for the package list (`scripts/tools/graph-arch.sh --repo . | jq -r '.packages[].name'`) and cross-reference `draft/.ai-context.md` (module headings). Record the candidate module list. For an **intent/concept** name (not an exact symbol), start with semantic search: `scripts/tools/graph-search.sh --repo . --query "<concept>"` returns ranked candidate symbols directly.
16886
16903
  2. **Concept → symbols/callers** — for a named function, run `scripts/tools/graph-callers.sh --repo . --symbol <name>` to find call sites, and `scripts/tools/graph-impact.sh --repo . --symbol <name>` for transitive dependents. These are the authoritative structural answers.
16887
- 3. **Modules → risk ranking** — cross-reference `draft/graph/hotspots.jsonl` (or `scripts/tools/hotspot-rank.sh`). High-fanIn symbols are the most likely entry points for impact.
16888
- 4. **Concept → public API** — for API-shaped concepts, consult `architecture.json` `.routes` (detected HTTP/gRPC/GraphQL routes) for matching service surface.
16904
+ 3. **Modules → risk ranking** — rank with `scripts/tools/hotspot-rank.sh --repo . [--top N]`. High-fanIn symbols are the most likely entry points for impact.
16905
+ 4. **Concept → public API** — for API-shaped concepts, read the engine's `.routes` (`get_architecture` output, detected HTTP/gRPC/GraphQL routes) for matching service surface.
16889
16906
  5. **Graph miss → grep fallback** — only if steps 1–4 return nothing relevant, emit the fallback sentence and use `grep`/`find`. Narrow the search by file extension and exclude `node_modules`, `vendor`, `dist`, `build`, `.git`.
16890
16907
 
16891
16908
  ## Graph Usage Report (Mandatory Footer)
@@ -16895,7 +16912,7 @@ Every code-touching skill output MUST end with this footer block. The lint check
16895
16912
  ```md
16896
16913
  ## Graph Usage Report
16897
16914
 
16898
- - Graph files queried: <comma-separated list, e.g. `architecture.json, hotspots.jsonl` and/or query tools like `graph-callers.sh` — or `NONE` with justification below>
16915
+ - Graph files queried: <comma-separated list of query tools invoked, e.g. `graph-callers.sh, hotspot-rank.sh` — or `NONE` with justification below>
16899
16916
  - Modules identified via graph: <comma-separated module names, or `none`>
16900
16917
  - Files identified via graph: <integer count>
16901
16918
  - Filesystem grep fallbacks: <list of `<pattern>` searches with one-line justification each, or `none`>
@@ -16929,11 +16946,75 @@ DRAFT_TOOLS="${DRAFT_PLUGIN_ROOT:-$HOME/.claude/plugins/draft}/scripts/tools"
16929
16946
 
16930
16947
  | Wrapper | Graph mode | Behavior on missing graph |
16931
16948
  |---|---|---|
16932
- | `bash "$DRAFT_TOOLS/hotspot-rank.sh" [--top N] [--module NAME]` | `--mode hotspots` | Emits `{hotspots:[],source:"unavailable"}` and exits 2 |
16933
- | `bash "$DRAFT_TOOLS/cycle-detect.sh"` | `--mode cycles` | Emits `{cycles:[],source:"unavailable"}` and exits 2 |
16934
- | `bash "$DRAFT_TOOLS/mermaid-from-graph.sh" [--diagram module-deps\|proto-map]` | `--mode mermaid` | Emits an empty mermaid block and exits 2 |
16949
+ | `bash "$DRAFT_TOOLS/hotspot-rank.sh" [--top N]` | complexity-weighted hotspots | Emits `{hotspots:[],source:"unavailable"}` and exits 2 |
16950
+ | `bash "$DRAFT_TOOLS/cycle-detect.sh"` | call cycles | Emits `{cycles:[],source:"unavailable"}` and exits 2 |
16951
+ | `bash "$DRAFT_TOOLS/mermaid-from-graph.sh" [--diagram module-deps\|co-change\|proto-map]` | diagram text | Emits an empty mermaid block and exits 2 |
16952
+ | `bash "$DRAFT_TOOLS/graph-callers.sh" --symbol N [--transitive[=N]] [--prod-only] [--qualified]` | callers | `{callers:[],status:"unavailable",source:"unavailable"}`, exit 2 |
16953
+ | `bash "$DRAFT_TOOLS/graph-snippet.sh" --qualified N` | verified source + caller/callee counts | `{status:"unavailable",source:"unavailable"}`, exit 2 |
16954
+ | `bash "$DRAFT_TOOLS/graph-search.sh" --query "STR" [--limit N]` | semantic/ranked search | `{results:[],source:"unavailable"}`, exit 2 |
16955
+ | `bash "$DRAFT_TOOLS/graph-tests.sh" (--symbol N \| --untested)` | test→symbol coverage | `{tests:[]/untested:[],source:"unavailable"}`, exit 2 |
16956
+ | `bash "$DRAFT_TOOLS/graph-deps.sh" [--file PATH]` | real IMPORTS graph | `{imports:[],source:"unavailable"}`, exit 2 |
16957
+ | `bash "$DRAFT_TOOLS/graph-hierarchy.sh" [--symbol N \| --derived N]` | INHERITS tree | `{edges:[],source:"unavailable"}`, exit 2 |
16958
+ | `bash "$DRAFT_TOOLS/graph-errors.sh" (--symbol N \| --type N)` | RAISES/THROWS | `{raises:[]/raisers:[],source:"unavailable"}`, exit 2 |
16959
+ | `bash "$DRAFT_TOOLS/graph-risk.sh" [--min-complexity N]` | pre-computed risk flags | `{risky:[],source:"unavailable"}`, exit 2 |
16960
+ | `bash "$DRAFT_TOOLS/graph-query.sh" (--cypher STR \| --tool NAME --json '{...}')` | generic read-only passthrough | `{source:"unavailable"}`, exit 2 |
16961
+ | `bash "$DRAFT_TOOLS/graph-traces.sh" ingest --file F --experimental` | runtime traces (experimental write) | `{source:"unavailable"}`, exit 2 |
16962
+
16963
+ For lower-level modes, call the engine directly: `codebase-memory-mcp cli <tool> '<json>'` (see the tool list in [bin/README.md](../../bin/README.md)).
16964
+
16965
+ ### Capability wrappers & dialect limits (graph-tooling-v2)
16966
+
16967
+ All Cypher lives in `scripts/tools/_graph_queries.sh` (the single source of query
16968
+ truth). Wrappers are thin arg-parse → builder → fail-loud JSON. Three contracts
16969
+ matter when consuming them:
16970
+
16971
+ **Fail-loud status.** Symbol-scoped wrappers (`graph-callers`, `graph-snippet`,
16972
+ `graph-tests --symbol`, `graph-hierarchy --symbol/--derived`, `graph-errors`)
16973
+ emit a `status` field that distinguishes the three real outcomes — never read a
16974
+ bare `[]` as a confirmed true negative:
16975
+
16976
+ | `status` | Meaning |
16977
+ |---|---|
16978
+ | `ok` | node found, edges returned |
16979
+ | `no-edges` | node exists but has no matching edge (a *real* negative) |
16980
+ | `no-match` | the named symbol was not found at all (check the name / try `--qualified`) |
16981
+ | `unavailable` | engine could not be resolved (exit 2) |
16982
+
16983
+ **Verified engine param shapes** (engine v0.8.x — the runtime source of truth is
16984
+ `get_graph_schema`; do not hardcode a property set):
16935
16985
 
16936
- Use the raw `graph` CLI directly for the lower-level modes documented below.
16986
+ ```bash
16987
+ get_code_snippet '{"project":P,"qualified_name":"pkg.Mod.Class.method"}' # → source + callers/callees counts + transitive_loop_depth
16988
+ search_graph '{"project":P,"query":"order submission to broker","limit":5}' # → {results:[{name,qualified_name,label,file_path,rank}]}
16989
+ trace_path '{"project":P,"function_name":"submit_order","depth":3,"direction":"both"}' # depth-bounded caller EXPANDER, not an A→B pathfinder
16990
+ detect_changes '{"project":P}' # → {changed_files, changed_count, impacted_symbols, depth}
16991
+ get_graph_schema '{"project":P}' # → {node_labels:[{label,count,properties}], edge_types:[{type,count}]}
16992
+ ```
16993
+
16994
+ **Cypher dialect — keep queries inside the SAFE set:**
16995
+
16996
+ - ✅ SAFE: fixed-length patterns, single/multi-hop explicit patterns, `=`, `<`,
16997
+ `STARTS WITH`, `NOT x STARTS WITH`, `AND`, `OR`, relationship-type alternation
16998
+ `[:A|B]`, simple `count(x)`.
16999
+ - ❌ UNSAFE (rejected or silently empty): `coalesce()`, `<>` / `!=` / `<=` / `>=`,
17000
+ `NOT EXISTS(...)`, `NOT (pattern)`, `WITH`-grouping aggregation, multi-pattern
17001
+ joins. `graph-query.sh --cypher` returns the engine's raw error, not a silent
17002
+ empty — but the builders never emit these forms.
17003
+
17004
+ **Caveats consumers must respect:**
17005
+
17006
+ - **`--prod-only` is best-effort.** It filters `is_test=false AND NOT file_path
17007
+ STARTS WITH 'tests/'`. `is_test` is partially populated by the engine, so test
17008
+ helpers/mocks can leak through. Treat it as a heuristic, not a guarantee.
17009
+ - **`--transitive` uses the `trace_path` expander** (a depth-bounded caller
17010
+ expansion from one symbol), not a from→to pathfinder. "Path between A and B"
17011
+ still needs an explicit fixed-length `graph-query.sh --cypher` pattern.
17012
+ - **Honest caps.** `cycle-detect`, `graph-deps`, `graph-risk`, `graph-tests
17013
+ --untested` cap their output and report `"truncated": true` when the cap is
17014
+ hit — results are a sample, not exhaustive.
17015
+ - **`graph-tests --untested`** is a set difference (exported symbols minus TESTS
17016
+ targets) because the dialect has no anti-join; coverage depends on the engine
17017
+ resolving test→symbol links, which varies by language/framework.
16937
17018
 
16938
17019
  ## Pre-Check
16939
17020
 
@@ -16945,27 +17026,26 @@ ls draft/graph/schema.yaml 2>/dev/null
16945
17026
 
16946
17027
  If absent, **skip all graph operations silently**. Graph enriches analysis — it never gates it. All skills must work identically without graph data.
16947
17028
 
16948
- ## Engine + snapshot model
17029
+ ## Engine model (engine-only)
17030
+
17031
+ The graph is produced by the **codebase-memory-mcp** engine (a single binary; see [bin/README.md](../../bin/README.md)). Draft is **engine-only and opinionated**: the engine is the one structural source of truth, queried live. There is **no committed machine-readable mirror** of the graph — no `architecture.json`, `hotspots.jsonl`, `*.mermaid`, or `okf/`. Those were lossy, went stale on the next commit, and duplicated what the engine serves precisely on demand.
16949
17032
 
16950
- The graph is produced by the **codebase-memory-mcp** engine (a single binary; see [bin/README.md](../../bin/README.md)). There are two ways skills consume it:
17033
+ The only committed file is the gate marker:
16951
17034
 
16952
- 1. **Live queries** (preferred when the engine is resolvable) — the shell tools under `scripts/tools/` drive the engine on demand (it auto-indexes into its own cache). No committed files required.
16953
- 2. **Committed snapshot** (`draft/graph/`) — a small, derived, PR-reviewable snapshot written by `scripts/tools/graph-snapshot.sh`. It exists for reviewability and for the Copilot/Gemini integrations, which cannot run the engine but can read committed files. Git remains the source of truth.
17035
+ | File | Role |
17036
+ |------|------|
17037
+ | `draft/graph/schema.yaml` | Engine + project metadata and point-of-index counts (provenance, not authoritative). Carries **no graph data**. Its presence is the **gate** (see Pre-Check) — it signals the engine is wired for this repo. Written by `scripts/tools/graph-snapshot.sh`. |
16954
17038
 
16955
- When `draft/graph/` exists, the snapshot contains:
17039
+ All structural data is obtained live by shelling out to the engine — either through the query-tool wrappers under `scripts/tools/` or directly via `codebase-memory-mcp cli <tool> '<json>'`. The shell tools auto-index the repo into the engine's own cache on demand, so no committed files are required.
16956
17040
 
16957
- | File | Load | Content |
16958
- |------|------|---------|
16959
- | `schema.yaml` | Always | Engine + project metadata, node/edge counts, artifact list. Its presence **gates** graph use (see Pre-Check). |
16960
- | `architecture.json` | Always | `get_architecture(all)` output: node labels, edge types, languages, packages (with fan-in/out), entry points, routes, hotspots. |
16961
- | `hotspots.jsonl` | Always | Fan-in-ranked symbols, one JSON object per line: `{id, name, fanIn}`. |
16962
- | `module-deps.mermaid` | Diagram injection | File co-change coupling diagram (`FILE_CHANGES_WITH`). |
16963
- | `proto-map.mermaid` | Diagram injection | Detected service-route diagram (`Route` nodes). |
16964
- | `okf/` | On demand | Open Knowledge Format v0.1 bundle (emitted by default): `index.md` (reserved bundle root, no frontmatter) + cross-linked `modules/<name>.md` concept pages. Portable, vendor-neutral mirror of the graph; validate with `okf-check.sh`. |
17041
+ ### How skills query (engine is the interface; jq is optional)
16965
17042
 
16966
- The engine uses a **unified, language-agnostic** node model `Function`, `Method`, `Class`, `Module`, `File`, `Folder`, `Route`, `Section`, `Variable` (language is inferred from file extension) and edges `CALLS`, `DEFINES`, `CONTAINS_FILE`, `IMPORTS`, `HTTP_CALLS`, `FILE_CHANGES_WITH`, `SEMANTICALLY_RELATED`, `SIMILAR_TO`. There are **no** per-language index files and no `ctags-sym` fallback; that detail is served by live queries against the unified model.
17043
+ - **The engine is the query.** `codebase-memory-mcp cli <tool> '<json>'` (and the wrappers that call it) is how you askit takes JSON args and returns JSON. There is no other query surface.
17044
+ - **Prefer the wrappers — they resolve the engine for you.** `graph-arch.sh` (architecture view: packages/routes/layers/hotspots), `graph-callers.sh`, `hotspot-rank.sh`, `graph-impact.sh`, `cycle-detect.sh`, `mermaid-from-graph.sh` return already-shaped JSON. The engine binary is usually **not on `$PATH`** (it lives under `~/.cache/draft/bin/`); the wrappers locate it via `_lib.sh:find_memory_bin`, so a skill using a wrapper needs no resolution step.
17045
+ - **Raw `codebase-memory-mcp cli` requires resolving the binary first** (it is not on `$PATH`): `CM="${DRAFT_MEMORY_BIN:-$HOME/.cache/draft/bin/codebase-memory-mcp}"; "$CM" cli <tool> '<json>'`. Reach for this only for tools without a wrapper (`search_graph`, `search_code`, `trace_path`).
17046
+ - **`jq` is not a query tool — it only trims output.** Reach for it solely to slice a *large* response (chiefly the `get_architecture` blob) down to the field you need, for token economy. The agent can read raw JSON directly; jq is an optimization, not a requirement. Don't pipe wrapper output through jq unless you genuinely need a sub-field.
16967
17047
 
16968
- **Always-load files** are compact and should be read during context loading for any task that touches code structure.
17048
+ The engine uses a **unified, language-agnostic** node model — `Function`, `Method`, `Class`, `Module`, `File`, `Folder`, `Route`, `Section`, `Variable` (language is inferred from file extension) — and edges `CALLS`, `DEFINES`, `CONTAINS_FILE`, `IMPORTS`, `HTTP_CALLS`, `FILE_CHANGES_WITH`, `SEMANTICALLY_RELATED`, `SIMILAR_TO`. Each node carries `file_path` + `start_line`/`end_line` and rich `properties` (complexity, signature, parent_class), and the engine exposes full-text (`search_code`) and semantic search — none of which a committed snapshot reproduced.
16969
17049
 
16970
17050
  ## Query Tools
16971
17051
 
@@ -17006,7 +17086,14 @@ Output: `{cycles[[a,b],[a,b,c]], source}` — fixed-length 2- and 3-node `CALLS`
17006
17086
 
17007
17087
  ### Modules — dependency overview
17008
17088
 
17009
- Read `draft/graph/architecture.json` (`.packages` for module fan-in/out, `.node_labels`/`.edge_types` for shape, `.routes` for service surface), or regenerate it with `scripts/tools/graph-snapshot.sh --repo .`.
17089
+ Query the engine's architecture view live with the `graph-arch.sh` wrapper (it resolves the engine, indexes on demand, and auto-resolves the project):
17090
+
17091
+ ```bash
17092
+ scripts/tools/graph-arch.sh --repo . \
17093
+ | jq '{packages, node_labels, edge_types, routes, layers, boundaries}'
17094
+ ```
17095
+
17096
+ `.packages` gives module fan-in/out, `.node_labels`/`.edge_types` the shape, `.routes` the service surface, `.layers`/`.boundaries` the dependency direction.
17010
17097
 
17011
17098
  ### Mermaid — diagram text
17012
17099
 
@@ -17015,15 +17102,82 @@ scripts/tools/mermaid-from-graph.sh --repo . --diagram module-deps # co-change
17015
17102
  scripts/tools/mermaid-from-graph.sh --repo . --diagram proto-map # detected routes
17016
17103
  ```
17017
17104
 
17018
- Emits a ready-to-inject ` ```mermaid ``` ` block, or an empty stub (exit 2) when the engine is unavailable. The committed `draft/graph/*.mermaid` snapshots are written by `graph-snapshot.sh`.
17105
+ Emits a ready-to-inject ` ```mermaid ``` ` block on the fly (computed live by the engine), or an empty stub (exit 2) when the engine is unavailable. Diagrams are generated at the moment of use — they are never committed.
17106
+
17107
+ ### Snippet — verified source + caller/callee counts
17108
+
17109
+ ```bash
17110
+ scripts/tools/graph-snippet.sh --repo . --qualified <pkg.Mod.Class.method>
17111
+ ```
17112
+
17113
+ Output: `{qualified_name, file, start_line, end_line, callers, callees, transitive_loop_depth, complexity, code, status, source}`. Prefer this over grep+Read when you have a qualified name — it returns the engine's attributed source plus pre-computed counts.
17114
+
17115
+ ### Search — semantic / ranked symbol lookup
17116
+
17117
+ ```bash
17118
+ scripts/tools/graph-search.sh --repo . --query "auth token refresh" [--limit N]
17119
+ ```
17120
+
17121
+ Output: `{query, results[{name, qualified_name, label, file, rank}], total, source}`. Use when the user names an **intent/concept** rather than an exact symbol — this is the first move in the Concept-to-Files recipe.
17122
+
17123
+ ### Tests — coverage edges and untested surface
17124
+
17125
+ ```bash
17126
+ scripts/tools/graph-tests.sh --repo . --symbol <name> # tests covering a symbol
17127
+ scripts/tools/graph-tests.sh --repo . --untested # exported symbols with no TESTS edge
17128
+ ```
17129
+
17130
+ Output: `{symbol, tests[{test,file}], status, source}` or `{untested[{symbol,file}], total, truncated, source}`. Feeds coverage gaps for `init`/`testing-strategy`/`coverage`.
17131
+
17132
+ ### Deps — real module/file import graph
17133
+
17134
+ ```bash
17135
+ scripts/tools/graph-deps.sh --repo . [--file PATH]
17136
+ ```
17137
+
17138
+ Output: `{imports[{src,dst}], total, truncated, source}` from actual `IMPORTS` edges (self-imports filtered). This is the auto-derived dependency graph behind `mermaid-from-graph.sh --diagram module-deps` and `architecture.md §9`.
17139
+
17140
+ ### Hierarchy — class inheritance
17141
+
17142
+ ```bash
17143
+ scripts/tools/graph-hierarchy.sh --repo . [--symbol <Class> | --derived <Base>]
17144
+ ```
17145
+
17146
+ Output: `{edges[{child,parent}], status, source}`. `--derived` gives the blast radius of changing a base class.
17147
+
17148
+ ### Errors — error-propagation paths
17149
+
17150
+ ```bash
17151
+ scripts/tools/graph-errors.sh --repo . --symbol <name> # what it raises/throws
17152
+ scripts/tools/graph-errors.sh --repo . --type <ErrType> # who raises/throws that type
17153
+ ```
17154
+
17155
+ Output: `{symbol, raises[...], status, source}` or `{type, raisers[...], status, source}`. `--type` drives fail-closed audits.
17156
+
17157
+ ### Risk — pre-computed risk hotspots
17158
+
17159
+ ```bash
17160
+ scripts/tools/graph-risk.sh --repo . [--min-complexity N]
17161
+ ```
17162
+
17163
+ Output: `{risky[{symbol, file, complexity, flags}], total, truncated, source}` from the engine's pre-computed flags (`unguarded_recursion`, `recursion_in_loop`, `alloc_in_loop`, `linear_scan_in_loop`). High-signal input for `bughunt`/`deep-review` — the engine already found these.
17164
+
17165
+ ### Generic — read-only escape hatch (all 20 edges / ~30 properties)
17166
+
17167
+ ```bash
17168
+ scripts/tools/graph-query.sh --repo . --cypher 'MATCH (f)-[:WRITES]->(v) RETURN f.name, v.name LIMIT 50'
17169
+ scripts/tools/graph-query.sh --repo . --tool get_graph_schema --json '{}'
17170
+ ```
17171
+
17172
+ Unlocks any edge type or node property without a purpose-built wrapper. Write verbs are rejected; stay inside the SAFE dialect set (above). Emits raw engine JSON.
17019
17173
 
17020
- ### Building / refreshing the snapshot
17174
+ ### Indexing / refreshing the gate marker
17021
17175
 
17022
17176
  ```bash
17023
17177
  scripts/tools/graph-snapshot.sh --repo .
17024
17178
  ```
17025
17179
 
17026
- Writes the committed `draft/graph/` snapshot (`schema.yaml`, `architecture.json`, `hotspots.jsonl`, `*.mermaid`, plus the Open Knowledge Format bundle under `okf/`). Run during `draft init` and `draft graph`, or whenever the reviewable graph state should be refreshed.
17180
+ Indexes the repo into the engine and writes the `draft/graph/schema.yaml` gate marker (now including the `detect_changes` delta: `changed_files`/`impacted_symbols`). It writes **no** graph data. Run during `draft init` and `draft graph`, or whenever the index should be refreshed.
17027
17181
 
17028
17182
  ## Finding the Engine (Resolution + Usage Report)
17029
17183
 
@@ -17047,7 +17201,7 @@ ENGINE_INFO="$(scripts/tools/verify-graph-binary.sh --repo . --json 2>/dev/null
17047
17201
 
17048
17202
  After successful detection, `draft/.graph-binary-report.json` contains: `detected_at`, `engine_bin`, `source` (`path` | `managed` | `bundled:<arch>` | `override`), `arch`, `status`. It is a derived artifact (safe to prune), regenerated by each graph-using command that calls the verifier.
17049
17203
 
17050
- ## Building the Snapshot
17204
+ ## Indexing the Repo
17051
17205
 
17052
17206
  Run during `draft:init` / `draft:graph`, or manually:
17053
17207
 
@@ -17055,16 +17209,16 @@ Run during `draft:init` / `draft:graph`, or manually:
17055
17209
  scripts/tools/graph-snapshot.sh --repo .
17056
17210
  ```
17057
17211
 
17058
- The engine indexes C/C++, Go, Python, TypeScript/JS, and more (tree-sitter, 159 languages) plus LSP-assisted resolution for the major ones, and detects HTTP/gRPC/GraphQL routes. Indexing is incremental in the engine (content-based, git-aware); the snapshot is re-derived on each run.
17212
+ The engine indexes C/C++, Go, Python, TypeScript/JS, and more (tree-sitter, 159 languages) plus LSP-assisted resolution for the major ones, and detects HTTP/gRPC/GraphQL routes. Indexing is incremental in the engine (content-based, git-aware). This refreshes the engine index and rewrites the `schema.yaml` gate marker; it produces no committed graph data.
17059
17213
 
17060
17214
  ## Graceful Degradation
17061
17215
 
17062
17216
  | Scenario | Behavior |
17063
17217
  |----------|----------|
17064
- | No engine resolvable (or `DRAFT_MEMORY_DISABLE=1`) | Skip graph build in init; all skills proceed without graph data; tools emit `source: unavailable` |
17218
+ | No engine resolvable (or `DRAFT_MEMORY_DISABLE=1`) | Skip graph indexing in init; all skills proceed without graph data; tools emit `source: unavailable` |
17065
17219
  | Engine present but a query fails | Warn and proceed; skills work without graph data |
17066
- | `draft/graph/` snapshot exists | Load always-load files during context loading; use live query tools as needed |
17067
- | Stale snapshot | Still useful structural changes are infrequent. Re-run `graph-snapshot.sh` (or init) to refresh. |
17220
+ | `draft/graph/schema.yaml` exists | Engine is wired use live query tools as needed during the run |
17221
+ | Engine index out of date | The engine indexes incrementally (content-based, git-aware) on each query, so it self-freshens. Re-run `graph-snapshot.sh` (or init) to force a reindex and refresh the marker. |
17068
17222
 
17069
17223
  </core-file>
17070
17224
 
@@ -17620,7 +17774,7 @@ See [graph-query.md](graph-query.md) §Graph Usage Report (Mandatory Footer) for
17620
17774
  ```md
17621
17775
  ## Graph Usage Report
17622
17776
 
17623
- - Graph files queried: <comma-separated list, e.g. `architecture.json, hotspots.jsonl` and/or query tools like `graph-callers.sh` — or `NONE` with justification below>
17777
+ - Graph files queried: <comma-separated list, e.g. `get_architecture, hotspot-rank.sh` and/or query tools like `graph-callers.sh` — or `NONE` with justification below>
17624
17778
  - Modules identified via graph: <comma-separated module names, or `none`>
17625
17779
  - Files identified via graph: <integer count>
17626
17780
  - Filesystem grep fallbacks: <list of `<pattern>` searches with one-line justification each, or `none`>
@@ -17669,7 +17823,7 @@ Referenced by: `draft decompose`, `draft implement`, `draft review`, `draft deep
17669
17823
  ## Universal Red Flags (STOP if any apply)
17670
17824
 
17671
17825
  - **Ran `grep`/`find`/`rg` for symbol or file discovery before consulting the graph** (when `draft/graph/schema.yaml` exists).
17672
- - **Read more than 50 lines of source before consulting `draft/graph/hotspots.jsonl`** to know whether the file is a hotspot.
17826
+ - **Read more than 50 lines of source before querying hotspot rank** (`scripts/tools/hotspot-rank.sh --repo .`) to know whether the file is a hotspot.
17673
17827
  - **Omitted the Graph Usage Report footer** from the final output (see [graph-query.md](graph-query.md) §Mandatory Lookup Contract).
17674
17828
  - **Used a `grep` fallback without an explicit graph-miss statement** in the form: `Graph returned no match for <X>; falling back to grep.`
17675
17829
  - **Loaded full Layer 0.5 guardrails when the command type does not require them** (see selective-loading matrix in [draft-context-loading.md](draft-context-loading.md) §Layer 0.5).
@@ -17681,7 +17835,7 @@ Referenced by: `draft decompose`, `draft implement`, `draft review`, `draft deep
17681
17835
  These enforce [graph-query.md](graph-query.md) §Ground-Truth Discipline. Graph identifies candidates; Read confirms them. Shipping unread claims is the dominant correctness failure mode observed in Draft output.
17682
17836
 
17683
17837
  - **Wrote a `path:line` / `func()` / `symbol` reference into a deliverable without opening the file in this run.** Graph hit ≠ Read. (G1)
17684
- - **Declared something in-scope or out-of-scope without Reading at least one file in that path.** Module names from `architecture.json` are a candidate set, not proof that the candidate contains the named cost. (G2)
17838
+ - **Declared something in-scope or out-of-scope without Reading at least one file in that path.** Module names from the live engine (`get_architecture`) are a candidate set, not proof that the candidate contains the named cost. (G2)
17685
17839
  - **Shipped `Citation: TBD` / `Path: TBD` / `Symbol: TBD` on a row whose Status is `Modified` or `Existing`.** TBD is reserved for `Status: New` rows with a planned path filled in. (G3)
17686
17840
  - **Claimed code behavior (writes / blocks / loops / fails / is the only path) from graph metadata alone.** Fan-in / fan-out / complexity scores are necessary signal, not sufficient evidence. (G4)
17687
17841
  - **Promoted a spec / generated an HLD or LLD / closed a review without checking that the in-scope file set covers every cost term in the problem statement.** Silent scope narrowing that excludes the named cost is the highest-impact failure class. (G5)
@@ -17691,7 +17845,7 @@ When in doubt, prefer "not yet validated against source" over an unbacked assert
17691
17845
 
17692
17846
  ## Graph-First Lookup Order (non-negotiable)
17693
17847
 
17694
- 1. **Graph first** — the committed snapshot (`draft/graph/architecture.json`, `draft/graph/hotspots.jsonl`) and the live query tools (`scripts/tools/graph-callers.sh`, `graph-impact.sh`, `cycle-detect.sh`, `hotspot-rank.sh`).
17848
+ 1. **Graph first** — wrapper scripts (`scripts/tools/graph-arch.sh`, `graph-callers.sh`, `graph-impact.sh`, `cycle-detect.sh`, `hotspot-rank.sh`) and direct engine queries (`search_graph`, `search_code`). The gate marker `draft/graph/schema.yaml` (present = engine available) is the only committed graph file.
17695
17849
  2. **Generated context second** — `draft/.ai-context.md`, relevant `draft/architecture.md` slices, track-level `hld.md`/`lld.md`.
17696
17850
  3. **Source file reads third** — only narrowed targets identified via graph or generated context.
17697
17851
  4. **Filesystem `grep`/`find` last** — only after a graph miss, with the explicit fallback sentence above.
@@ -18462,7 +18616,7 @@ generated_at: "{ISO_TIMESTAMP}"
18462
18616
  ```
18463
18617
 
18464
18618
  > Include immediate sub-directories for all major modules (not just top-level).
18465
- > Use graph data (`draft/graph/modules/*.jsonl`) for exhaustive sub-module enumeration.
18619
+ > Use live engine queries (`get_architecture .packages[]` or `graph-callers.sh`) for exhaustive sub-module enumeration.
18466
18620
  > Show file counts per sub-module to indicate relative size/importance.
18467
18621
 
18468
18622
  ## GRAPH:MODULES
@@ -18774,9 +18928,9 @@ graph:
18774
18928
  go: "{approximate | high}"
18775
18929
  stats:
18776
18930
  modules: "{N from schema.yaml}"
18777
- edges: "{total_edges from architecture.json}"
18931
+ edges: "{total_edges from engine: get_architecture .edges}"
18778
18932
  hotspots: "{N}"
18779
- notes: "{explicit fidelity summary from architecture.json languages/packages}"
18933
+ notes: "{explicit fidelity summary from engine: get_architecture .languages/.packages}"
18780
18934
  generation_notes: "{High existing context detected via audit — see §10 Relationship for deference | Standard graph-primary generation}"
18781
18935
  ---
18782
18936
 
@@ -18858,7 +19012,7 @@ Each backed by:
18858
19012
 
18859
19013
  ## 4. Module & Dependency Map (Primarily Graph-Derived)
18860
19014
 
18861
- - Module dependency graph rendered from `draft/graph/architecture.json` (`.packages`) + `module-deps.mermaid`
19015
+ - Module dependency graph rendered from live engine query `scripts/tools/graph-arch.sh --repo . | jq '.packages'` + `scripts/tools/mermaid-from-graph.sh --repo . --diagram module-deps` (generated live, never committed)
18862
19016
  - High fan-in / fan-out modules highlighted
18863
19017
  - Cyclic dependencies called out
18864
19018
  - Cross-language boundaries (FFI, RPC, shared memory) explicitly surfaced with coverage notes