@drafthq/draft 2.8.3 → 3.1.5

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 (68) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +5 -5
  4. package/bin/README.md +10 -0
  5. package/core/methodology.md +17 -18
  6. package/core/shared/condensation.md +9 -9
  7. package/core/shared/draft-context-loading.md +7 -9
  8. package/core/shared/graph-query.md +38 -31
  9. package/core/shared/graph-usage-report.md +1 -1
  10. package/core/shared/pattern-learning.md +2 -2
  11. package/core/shared/red-flags.md +3 -3
  12. package/core/templates/ai-context.md +2 -1
  13. package/core/templates/ai-profile.md +1 -0
  14. package/core/templates/architecture.md +4 -3
  15. package/core/templates/dependency-graph.md +2 -2
  16. package/core/templates/discovery.md +1 -0
  17. package/core/templates/guardrails.md +1 -0
  18. package/core/templates/hld.md +1 -0
  19. package/core/templates/lld.md +1 -0
  20. package/core/templates/plan.md +1 -0
  21. package/core/templates/product.md +1 -0
  22. package/core/templates/rca.md +1 -0
  23. package/core/templates/root-architecture.md +3 -3
  24. package/core/templates/root-product.md +2 -2
  25. package/core/templates/root-tech-stack.md +2 -2
  26. package/core/templates/service-index.md +3 -3
  27. package/core/templates/spec.md +1 -0
  28. package/core/templates/tech-matrix.md +2 -2
  29. package/core/templates/tech-stack.md +1 -0
  30. package/core/templates/workflow.md +1 -0
  31. package/integrations/agents/AGENTS.md +276 -1037
  32. package/integrations/copilot/.github/copilot-instructions.md +276 -1037
  33. package/package.json +1 -1
  34. package/scripts/lib.sh +2 -1
  35. package/scripts/tools/adr-index.sh +2 -2
  36. package/scripts/tools/check-scope-conflicts.sh +2 -2
  37. package/scripts/tools/check-skill-line-caps.sh +2 -2
  38. package/scripts/tools/cycle-detect.sh +5 -1
  39. package/scripts/tools/diff-templates-vs-tracks.sh +2 -2
  40. package/scripts/tools/fix-whitespace.sh +15 -9
  41. package/scripts/tools/graph-arch.sh +72 -0
  42. package/scripts/tools/graph-impact.sh +1 -0
  43. package/scripts/tools/graph-init.sh +187 -0
  44. package/scripts/tools/graph-snapshot.sh +52 -46
  45. package/scripts/tools/hotspot-rank.sh +2 -0
  46. package/scripts/tools/manage-symlinks.sh +1 -1
  47. package/scripts/tools/parse-reports.sh +1 -1
  48. package/scripts/tools/skill-caps.conf +0 -1
  49. package/scripts/tools/verify-doc-anchors.sh +2 -2
  50. package/scripts/tools/verify-graph-binary.sh +1 -1
  51. package/skills/GRAPH.md +9 -12
  52. package/skills/bughunt/SKILL.md +14 -1
  53. package/skills/debug/SKILL.md +3 -3
  54. package/skills/decompose/SKILL.md +5 -5
  55. package/skills/deep-review/SKILL.md +2 -2
  56. package/skills/deploy-checklist/SKILL.md +2 -2
  57. package/skills/discover/SKILL.md +2 -4
  58. package/skills/draft/SKILL.md +2 -2
  59. package/skills/draft/intent-mapping.md +3 -2
  60. package/skills/graph/SKILL.md +3 -3
  61. package/skills/implement/SKILL.md +1 -1
  62. package/skills/init/SKILL.md +102 -43
  63. package/skills/init/references/architecture-spec.md +17 -16
  64. package/skills/learn/SKILL.md +5 -5
  65. package/skills/quick-review/SKILL.md +3 -3
  66. package/skills/review/SKILL.md +7 -7
  67. package/skills/tech-debt/SKILL.md +2 -2
  68. package/skills/index/SKILL.md +0 -848
@@ -31,7 +31,7 @@ When `draft/` exists in the project, always consider:
31
31
  | Command | Purpose |
32
32
  |---------|---------|
33
33
  | `draft` | Show overview and available commands |
34
- | `draft init` | Initialize project (run once) |
34
+ | `draft init [refresh] [--graph-only] [--module-only]` | Initialize project context + code-graph memory; scope-aware (root or sub-module) |
35
35
  | `draft new-track <description>` | Create feature/bug track |
36
36
  | `draft implement` | Execute tasks from plan |
37
37
  | `draft review [--track <id>]` | Three-stage code review |
@@ -57,7 +57,6 @@ When `draft/` exists in the project, always consider:
57
57
  | `draft status` | Show progress overview |
58
58
  | `draft revert` | Git-aware rollback |
59
59
  | `draft change <description>` | Handle mid-track requirement changes |
60
- | `draft index [--init-missing]` | Aggregate monorepo service contexts |
61
60
  | `draft tour` | Interactive onboarding tour |
62
61
  | `draft impact` | Telemetry and analytics insights |
63
62
  | `draft assist-review` | Assist human reviewers with architectural risk audit |
@@ -124,7 +123,7 @@ Recognize and use these throughout plan.md:
124
123
 
125
124
  ## Init Command
126
125
 
127
- When user says "init draft" or "draft init [refresh]":
126
+ When user says "init draft", "build the code graph", or "draft init [refresh] [--graph-only] [--module-only]":
128
127
 
129
128
  Initialize a Draft project for Context-Driven Development.
130
129
 
@@ -173,7 +172,7 @@ Initialize a Draft project for Context-Driven Development.
173
172
 
174
173
  ## Graph Fidelity & Diagram-First Priority (MANDATORY)
175
174
 
176
- 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.
177
176
 
178
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:
179
178
  - Graph = authoritative modules, edges, public surfaces, hotspots, call relationships.
@@ -314,18 +313,24 @@ synced_to_commit: "a1b2c3d4e5f6789012345678901234567890abcd"
314
313
 
315
314
  Check for arguments:
316
315
  - `refresh`: Update existing context without full re-init
317
- - `index`: Route to `draft index`
316
+ - `--graph-only`: Build/refresh only the code-graph knowledge memory (no markdown) — see the fast path below
317
+ - `--module-only`: When run in a sub-module, do not touch the root graph (the module→root link is marked `pending`)
318
318
  - `discover`: Route to `draft discover`
319
319
 
320
+ > `draft init` is the **single entry point** for building context — there is no separate `index` command. Init is scope-aware (root vs sub-module); see **Scope Detection** below.
321
+
320
322
  ### Route Explicit Modes Before Initialization
321
323
 
322
324
  If the user explicitly invoked a specialist mode, route directly:
323
325
 
324
- - `draft init index` → follow `draft index`
325
326
  - `draft init discover` → follow `draft discover`
326
327
 
327
328
  Explicit mode always wins. Do not perform standard initialization if an explicit mode is requested.
328
329
 
330
+ ### `--graph-only` Fast Path
331
+
332
+ If `--graph-only` is present, run **Step 1.4** (scope-aware, root-first graph build via `graph-init.sh`) and **STOP** — generate no `architecture.md` or other markdown. This is the fast path to (re)build the whole-repo code-graph knowledge memory; in a sub-module it also ensures the root spine exists and writes the module→root link. This path is allowed even when `draft/` already exists (it refreshes the graph in place — no `draft.tmp/` staging, no overwrite prompt).
333
+
329
334
  ### Standard Init Check
330
335
 
331
336
  ```bash
@@ -357,16 +362,16 @@ mv draft.tmp/ draft/
357
362
 
358
363
  > **Forced re-init:** If `draft/` exists and the user explicitly requests a fresh init (not refresh), confirm with user before removing the existing `draft/` directory.
359
364
 
360
- ### Monorepo Detection
365
+ ### Scope Detection (root vs sub-module)
366
+
367
+ `draft init` is the single entry point and is **scope-aware** — it works the same whether run at the repository root or inside a sub-module. The root-first graph behavior is handled mechanically by `graph-init.sh` in Step 1.4; you do not detect the monorepo shape by hand.
361
368
 
362
- Check for monorepo indicators:
363
- - Multiple `package.json` / `go.mod` / `Cargo.toml` in child directories
364
- - `lerna.json`, `pnpm-workspace.yaml`, `nx.json`, or `turbo.json` at root
365
- - `packages/`, `apps/`, `services/` directories with independent manifests
369
+ Resolve **ROOT** = nearest ancestor (above the current dir) containing `draft/` → else the git toplevel → else the current dir. Then:
366
370
 
367
- If monorepo detected:
368
- - Announce: "Detected monorepo structure. Consider using `draft init index` at root level to aggregate service context, or run `draft init` within individual service directories."
369
- - Ask user to confirm: initialize here (single service) or abort (use draft init index instead)
371
+ - **Root init** (current dir IS root): the graph step builds the whole-repo spine. The generated markdown is a **sparse, high-level system map** that links *down* to each module's context — a large root must not carry deep per-module prose. (See "Root vs Module Markdown" below.)
372
+ - **Module init** (current dir is BELOW root): the graph step ensures the root spine exists first (building it if missing), builds the module snapshot, and writes `draft/graph/root-link.json` (module→root). The generated markdown is the **detailed** module reference produced by the standard deep analysis in this skill.
373
+
374
+ Use `--module-only` to skip touching the root (the link is marked `pending` and resolves when root init later runs). With no git and no ancestor `draft/`, init treats the current dir as root (module-local, no traversal).
370
375
 
371
376
  ### Migration Detection
372
377
 
@@ -599,20 +604,25 @@ If **Greenfield**: skip to Step 2 (Product Definition).
599
604
 
600
605
  **CRITICAL ORDERING**: Phase 0 (this step) MUST complete before writing any section of architecture.md. The graph provides: (a) exhaustive module list, (b) hotspot-ranked module priority, (c) authoritative proto API surface, (d) mermaid diagrams ready for slot injection, (e) codebase tier for .ai-context.md budget.
601
606
 
602
- ### 1. Build the graph snapshot
607
+ ### 1. Build the graph (scope-aware, root-first)
603
608
 
604
- The knowledge-graph engine is `codebase-memory-mcp`, resolved by `scripts/tools/_lib.sh:find_memory_bin` (`DRAFT_MEMORY_BIN` > PATH > `~/.cache/draft/bin` > vendored `bin/<arch>/`). `draft install` fetches it (skip with `--no-graph`); install manually with `scripts/fetch-memory-engine.sh`. Set `DRAFT_MEMORY_DISABLE=1` to opt out.
609
+ The knowledge-graph engine `codebase-memory-mcp` is Draft's **default** capability tier — deterministic call/dependency traversal beats grep/glob. It is normally already installed by `draft install`; `graph-init.sh` fetches it as a fallback when missing (blocking — download/index time is accepted, never gated on cost). Resolution: `scripts/tools/_lib.sh:find_memory_bin` (`DRAFT_MEMORY_BIN` > PATH > `~/.cache/draft/bin` > vendored `bin/<arch>/`). Set `DRAFT_MEMORY_DISABLE=1` to opt out.
605
610
 
606
- One command resolves the engine, indexes the repo, and writes the committed snapshot under `draft/graph/`:
611
+ One command resolves ROOT, ensures the engine, builds the whole-repo spine, and in a sub-module — builds the module snapshot and writes the `root-link.json` pointer:
607
612
 
608
613
  ```bash
609
- if scripts/tools/graph-snapshot.sh --repo .; then
610
- echo "Graph snapshot written to draft/graph/ (schema.yaml, architecture.json, hotspots.jsonl, *.mermaid)."
614
+ # Add --module-only to skip touching the root (link marked "pending").
615
+ if scripts/tools/graph-init.sh --scope .; then
616
+ echo "Graph memory ready under draft/graph/ (the root spine is the structural source of truth)."
611
617
  else
612
- echo "Graph engine unavailable — skipping automated graph analysis. Downstream skills degrade gracefully."
618
+ echo "Graph engine unavailable — proceeding with degraded manual discovery. Downstream skills degrade gracefully."
613
619
  fi
614
620
  ```
615
621
 
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
+ - **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 `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
+
616
626
  Optionally record which engine was selected (usage-report contract):
617
627
 
618
628
  ```bash
@@ -621,15 +631,20 @@ scripts/tools/verify-graph-binary.sh --repo . --json 2>/dev/null || true
621
631
 
622
632
  See `core/shared/graph-query.md` and `bin/README.md` for the query contract and engine resolution.
623
633
 
624
- If the snapshot 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
+
636
+ ### 2. If indexing succeeds, query the engine for structural context
625
637
 
626
- ### 2. If graph build succeeds, load the always-load artifacts
638
+ Pull the architecture view once and reuse it across phases:
627
639
 
628
- Read these files to get structural context for all subsequent phases:
629
- - `draft/graph/schema.yaml` module count, file count, edge count, language stats per module
630
- - `draft/graph/architecture.json` — module list (`.packages`) with fan-in/out
631
- - `draft/graph/architecture.json` `.routes` — detected service endpoints
632
- - `draft/graph/hotspots.jsonl` — all complexity hotspots (files ranked by lines + fanIn * 50)
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)
633
648
 
634
649
  ### 3. Use graph data to accelerate Step 1.5
635
650
 
@@ -643,10 +658,10 @@ Read these files to get structural context for all subsequent phases:
643
658
  ### 4. Compute codebase tier and module priority
644
659
 
645
660
  **Step 1.4.5 — Compute Codebase Tier:**
646
- Read `draft/graph/schema.yaml`. Extract:
647
- - `M = stats.modules`
648
- - `F = stats.go_functions + stats.py_functions`
649
- - `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)
650
665
 
651
666
  Apply tier table:
652
667
 
@@ -661,8 +676,8 @@ Apply tier table:
661
676
  Hold tier in memory. This governs: architecture.md length minimum, .ai-context.md budget, and module deep-dive depth.
662
677
 
663
678
  **Step 1.4.6 — Build Module Priority List:**
664
- From `draft/graph/hotspots.jsonl`: count hotspot files per module (group by `module` field).
665
- 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.
666
681
  Rank modules by: `(hotspot_count × 2) + fan_in_count`.
667
682
  Top-ranked modules drive Section 6 deep-dive ordering and depth. Modules ranked zero on both: summary treatment only.
668
683
  Hold ranked list in memory — it replaces directory scanning for module discovery.
@@ -682,7 +697,7 @@ The tool emits a ready-to-inject ` ```mermaid ``` ` block (or an empty stub on e
682
697
  ```
683
698
 
684
699
  For Section 20 (hotspots slot):
685
- 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:
686
701
  ```
687
702
  <!-- GRAPH:hotspots:START -->
688
703
  | Symbol | fanIn |
@@ -741,7 +756,7 @@ Perform a **one-time, exhaustive analysis** of the existing codebase. This is NO
741
756
 
742
757
  If the codebase is large (200+ files), focus on the module boundaries but still enumerate exhaustively within each module.
743
758
 
744
- > **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.
745
760
 
746
761
  ### Parallel Analysis Protocol (Tiers 3–5)
747
762
 
@@ -768,16 +783,16 @@ For tier 3+, readers run simultaneously; wall clock = slowest reader, not the su
768
783
 
769
784
  #### Phase 0: Graph Data (already done in Step 1.4)
770
785
 
771
- The graph binary has already run. Use its output throughout this protocol:
772
- - `draft.tmp/graph/schema.yaml` — module list, file counts, tier metrics
773
- - `draft.tmp/graph/architecture.json` — `.packages[].fan_in` per module (for grouping)
774
- - `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)
775
790
 
776
791
  #### Phase 1: Spawn Parallel Module Readers
777
792
 
778
793
  **Step 1: Group modules.**
779
794
 
780
- 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.
781
796
  Apply dependency-aware grouping (see `core/shared/parallel-analysis.md`).
782
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):
783
798
  - Assign highest fan-in modules to separate readers (tier 3+)
@@ -793,7 +808,7 @@ Hotspot files:
793
808
  execution/engine.go (847 lines, fanIn=12)
794
809
  execution/router.go (412 lines, fanIn=8)
795
810
  fill_processor/handler.go (623 lines, fanIn=5)
796
- Module edges (from architecture.json .packages fan-in/out):
811
+ Module edges (from $ARCH .packages fan-in/out):
797
812
  execution → [risk, data, services]
798
813
  fill_processor → [execution, persistence]
799
814
  ```
@@ -898,7 +913,7 @@ If any reader agent fails to produce valid JSON after one retry:
898
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.
899
914
 
900
915
  1. Use the ranked module list from Step 1.4.6 (graph-first — do not re-scan by directory if Phase 0 succeeded).
901
- 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.
902
917
  3. Always include §9 Graph Coverage Gaps and §10 Relationship when the Context Audit requires them.
903
918
  4. Run Completion Verification (defined later in this skill) before condensation. Fidelity, provenance, and gap honesty block completion — not line counts.
904
919
 
@@ -1021,11 +1036,11 @@ Follow these steps in order. The specific files to look for depend on the langua
1021
1036
 
1022
1037
  #### Phase 1: Discovery (Broad Scan)
1023
1038
 
1024
- 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.)
1025
1040
 
1026
1041
  2. **Read build / dependency files**: These reveal the module structure, dependencies, and targets. (See language guide above for which files.)
1027
1042
 
1028
- 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.)
1029
1044
 
1030
1045
  4. **Read interface / type definition files**: Class declarations, interface definitions, and type annotations reveal the public API and design intent.
1031
1046
 
@@ -1129,11 +1144,19 @@ The document is:
1129
1144
 
1130
1145
  **Full details, per-section guidance, provenance rules, and examples** live in:
1131
1146
  - `core/templates/architecture.md` (the source of truth for the 10 sections + Generation Contract)
1132
- - `docs/research/proposed-graph-backed-architecture-template.md` (design rationale and fidelity rules)
1133
1147
  - `references/architecture-spec.md` (deprecated legacy notes — **10-section template wins on any conflict**)
1134
1148
 
1135
1149
  There is no legacy 28-section structure and no volume targets. The template itself is the contract.
1136
1150
 
1151
+ ### Root vs Module Markdown (scope asymmetry)
1152
+
1153
+ The depth of generated markdown depends on the scope resolved in **Scope Detection**:
1154
+
1155
+ - **Module init** (current dir below root): generate the **full, detailed** 10-section `architecture.md` for the module subtree — the standard deep analysis described in this skill. This is where engineering depth lives.
1156
+ - **Root init** (current dir IS root, monorepo): generate a **sparse, high-level system map**, not deep per-module prose. The root `architecture.md` covers: system overview + Graph Health Dashboard (from the whole-repo spine), the module catalog with one-line responsibilities and links *down* to each module's `draft/.ai-context.md`, cross-module dependency topology (from `draft/graph/`), shared infrastructure, and system-wide invariants. Defer module internals to the module docs — a large root must not duplicate them. If a module has not been initialized, link it as "not yet initialized — run `draft init` there."
1157
+
1158
+ The graph is symmetric (root spine + per-module snapshots, linked); only the **prose** is asymmetric. Both consume `draft/graph/`.
1159
+
1137
1160
  **After completing analysis AND passing verification**, write to `draft/architecture.md`. This is the PRIMARY output. Then run the Condensation Subroutine.
1138
1161
 
1139
1162
  ## .ai-context.md Specification
@@ -1709,6 +1732,7 @@ Create `draft/tracks.md` with metadata header:
1709
1732
 
1710
1733
  ```markdown
1711
1734
  ---
1735
+ type: TrackIndex
1712
1736
  project: "{PROJECT_NAME}"
1713
1737
  module: "root"
1714
1738
  generated_by: "draft:init"
@@ -1754,6 +1778,38 @@ For **brownfield** projects, run `draft learn` (no arguments — full codebase s
1754
1778
 
1755
1779
  ## Completion
1756
1780
 
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.
1784
+
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.
1808
+ ```
1809
+
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.
1812
+
1757
1813
  **Finalize run memory:** Update `draft/.state/run-memory.json`:
1758
1814
  - `status`: `"completed"`
1759
1815
  - `completed_at`: current ISO timestamp
@@ -1763,6 +1819,7 @@ For **Brownfield** projects, announce:
1763
1819
  "Draft initialized successfully with comprehensive analysis!
1764
1820
 
1765
1821
  Created:
1822
+ - draft/index.md (plain docs index — navigable table of contents for the draft/ bundle)
1766
1823
  - draft/.ai-profile.md (20-50 lines — ultra-compact always-injected profile, Tier 0)
1767
1824
  - draft/.ai-context.md (200-400 lines — token-optimized AI context, self-contained, Tier 1)
1768
1825
  - draft/architecture.md (comprehensive human-readable engineering reference, Tier 2)
@@ -1797,6 +1854,7 @@ For **Greenfield** projects, announce:
1797
1854
  "Draft initialized successfully!
1798
1855
 
1799
1856
  Created:
1857
+ - draft/index.md (plain docs index — navigable table of contents for the draft/ bundle)
1800
1858
  - draft/product.md
1801
1859
  - draft/tech-stack.md
1802
1860
  - draft/workflow.md
@@ -2067,14 +2125,14 @@ Write the `GRAPH:module-deps` injection slot into architecture.md:
2067
2125
 
2068
2126
  If graph build succeeded (Step 1.4.7 completed), write the populated slot content using the diagram from Step 1.4.7. If filtered (>30 modules), include the filter note. Dashed edges indicate circular dependencies.
2069
2127
 
2070
- If graph binary was not found: write the slot with placeholder body so draft:index can populate it later:
2128
+ If graph binary was not found: write the slot with placeholder body so draft:init --graph-only can populate it later:
2071
2129
  ```
2072
2130
  <!-- GRAPH:module-deps:START -->
2073
- [Graph data unavailable — run draft:index to populate after graph binary is installed]
2131
+ [Graph data unavailable — run draft:init --graph-only to populate after graph binary is installed]
2074
2132
  <!-- GRAPH:module-deps:END -->
2075
2133
  ```
2076
2134
 
2077
- The slot markers MUST always be written — they are required for draft:index refresh to function.
2135
+ The slot markers MUST always be written — they are required for draft:init --graph-only refresh to function.
2078
2136
 
2079
2137
  #### 4.2 Process Lifecycle (or Usage Lifecycle for libraries)
2080
2138
 
@@ -2181,13 +2239,13 @@ Only when material: authentication/authorization checkpoints, distributed transa
2181
2239
 
2182
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.
2183
2241
 
2184
- 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 .`.
2185
2243
 
2186
2244
  #### 7.{N} {module-name}
2187
2245
 
2188
2246
  <!-- GRAPH:module-deep/{module-name}:START -->
2189
2247
  <!-- Rendered deterministic block: package name, node count, public API list, fan-in/fan-out (from
2190
- 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
2191
2249
  graph-callers.sh/graph-impact.sh), entry points if known. No LLM prose inside fence. -->
2192
2250
  <!-- GRAPH:module-deep/{module-name}:END -->
2193
2251
 
@@ -2206,7 +2264,7 @@ Synthesize a single, accurate Mermaid diagram (`stateDiagram-v2`, `sequenceDiagr
2206
2264
 
2207
2265
  #### Sub-Module Guidance (when graph justifies recursion)
2208
2266
 
2209
- 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:
2210
2268
  - Create `##### 7.X.Y {Parent}/{Child}` subsections only for children that have their own meaningful public surface or high internal fan-in.
2211
2269
  - Each sub-module subsection follows the same compact pattern: graph facts + **one mandatory workflow/state diagram** + ≤60 words Design Notes.
2212
2270
  - Do not descend further unless the child itself shows additional clear boundaries in the graph data.
@@ -2268,7 +2326,7 @@ Regardless of tier, any directory whose name contains `ops`, `handlers`, `execut
2268
2326
  | ... | (enumerate ALL — no sampling, no "and others") | | | |
2269
2327
  ```
2270
2328
 
2271
- 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.
2272
2330
 
2273
2331
  #### Example: Full Sub-Module Treatment for `icebox/` (917 files)
2274
2332
 
@@ -2315,7 +2373,7 @@ stateDiagram-v2
2315
2373
  After writing Section 7, run these checks before proceeding. **If any check fails, STOP and fix.**
2316
2374
 
2317
2375
  **Check 1 — Graph block present and faithful for every module:**
2318
- 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.
2319
2377
 
2320
2378
  **Check 2 — One mandatory workflow/state diagram per module:**
2321
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.
@@ -2419,12 +2477,13 @@ Include architecturally significant implementations (high fan-in, core extension
2419
2477
  |---|-----------|-------------|-------|-------------|
2420
2478
  | 1 | ArchiveFilesOp | `icebox/master/ops/archive_files_op.cc` | 2100 | Archives files to cloud vault |
2421
2479
  | 2 | CancelJobOp | `icebox/master/ops/cancel_job_op.cc` | 450 | Cancels running archive job |
2422
- | (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) |
2423
2481
  ```
2424
2482
 
2425
- > **MANDATORY (graph data)**: Read `draft/graph/modules/{module}.jsonl` to get the complete file
2426
- > list with line counts. Filter for files in operation sub-directories (paths containing `/ops/`,
2427
- > `/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
2428
2487
  > high-complexity operations (high line count or fanIn). Do NOT skip this step — incomplete
2429
2488
  > catalogs cause AI agents to reinvent existing functionality.
2430
2489
 
@@ -2984,11 +3043,11 @@ If graph build succeeded and proto files exist (Step 1.4.7 completed), write the
2984
3043
  If graph binary was not found or no proto files exist, write the slot with placeholder:
2985
3044
  ```
2986
3045
  <!-- GRAPH:proto-map:START -->
2987
- [Graph data unavailable — run draft:index to populate after graph binary is installed]
3046
+ [Graph data unavailable — run draft:init --graph-only to populate after graph binary is installed]
2988
3047
  <!-- GRAPH:proto-map:END -->
2989
3048
  ```
2990
3049
 
2991
- The slot markers MUST always be written — they are required for draft:index refresh to function.
3050
+ The slot markers MUST always be written — they are required for draft:init --graph-only refresh to function.
2992
3051
 
2993
3052
  ---
2994
3053
 
@@ -3115,11 +3174,11 @@ Fix: Add actual payload descriptions on arrows, `alt`/`opt` blocks for condition
3115
3174
 
3116
3175
  **FAILURE 3 — Empty Appendices:**
3117
3176
  Detection: Appendix B, C, or D tables have fewer than 10 data rows.
3118
- 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.
3119
3178
 
3120
3179
  **FAILURE 4 — Missing Sub-Modules:**
3121
3180
  Detection: A module with 100+ source files (check graph data) has no Sub-Module Structure table.
3122
- 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.
3123
3182
 
3124
3183
  **FAILURE 4b — Shallow Sub-Module Treatment:**
3125
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.
@@ -3166,859 +3225,11 @@ Run this checklist before writing architecture.md:
3166
3225
 
3167
3226
  ---
3168
3227
 
3169
- ## Index Command
3170
-
3171
- When user says "index services" or "draft index [--init-missing]":
3172
-
3173
- You are building a federated knowledge index for a monorepo with multiple services.
3174
-
3175
- ## Red Flags - STOP if you're:
3176
-
3177
- - Running at a non-root directory in a monorepo
3178
- - Indexing services that haven't been initialized with `draft init`
3179
- - Overwriting root-level context without confirming with the user
3180
- - Aggregating without verifying each service's draft/ directory exists
3181
- - Skipping dependency mapping between services
3182
-
3183
- **Aggregate from initialized services only. Verify before overwriting.**
3184
-
3185
- ---
3186
-
3187
- ## Standard File Metadata
3188
-
3189
- **ALL generated files MUST include the standard YAML frontmatter.** This enables refresh tracking, sync verification, and traceability.
3190
-
3191
- ### Project Metadata File (single source of truth)
3192
-
3193
- Before writing any file, update `draft/metadata.json` with current git state. This is the single source of truth for `synced_to_commit` and all `git.*` fields for every project-level artifact. Do NOT embed git fields in per-file frontmatter.
3194
-
3195
- Use the `--project-metadata` flag (preferred):
3196
-
3197
- ```bash
3198
- DRAFT_TOOLS="${DRAFT_PLUGIN_ROOT:-$HOME/.claude/plugins/draft}/scripts/tools"
3199
- [ -d "$DRAFT_TOOLS" ] || DRAFT_TOOLS="$HOME/.cursor/plugins/local/draft/scripts/tools"
3200
- [ -d "$DRAFT_TOOLS" ] || DRAFT_TOOLS="$PWD/scripts/tools"
3201
- bash "$DRAFT_TOOLS/git-metadata.sh" --project-metadata \
3202
- --project "$PROJECT" --generated-by "draft:index"
3203
- ```
3204
-
3205
- ### Per-File Metadata Template
3206
-
3207
- Insert this **stable** YAML frontmatter at the top of every generated file (`service-index.md`, `dependency-graph.md`, `tech-matrix.md`, `draft-index-bughunt-summary.md`):
3208
-
3209
- ```yaml
3210
- ---
3211
- project: "{PROJECT_NAME}"
3212
- module: "root"
3213
- generated_by: "draft:index"
3214
- generated_at: "{ISO_TIMESTAMP}"
3215
- ---
3216
- ```
3217
-
3218
- > **Note**: `generated_by` uses `draft:command` format (not `draft command`) for cross-platform compatibility.
3219
-
3220
- ---
3221
-
3222
- ## Pre-Check
3223
-
3224
- ```bash
3225
- ls draft/ 2>/dev/null
3226
- ```
3227
-
3228
- **If `draft/` does NOT exist at root:**
3229
- - Announce: "Root draft/ directory not found. Run `draft init` at monorepo root first to create base context, then run `draft index` to aggregate service knowledge."
3230
- - Stop here.
3231
-
3232
- **If `draft/` exists:** Continue to lockfile check.
3233
-
3234
- ## Lockfile Check
3235
-
3236
- Before proceeding, check for a stale lock:
3237
-
3238
- ```bash
3239
- ls draft/.index-lock 2>/dev/null
3240
- ```
3241
-
3242
- - **If `draft/.index-lock` exists and is less than 10 minutes old:** Warn: "Previous indexing may be incomplete. Remove `draft/.index-lock` to proceed." Stop here.
3243
- - **If `draft/.index-lock` exists and is older than 10 minutes:** Remove it and continue.
3244
- - **If no lock exists:** Continue.
3245
-
3246
- Create `draft/.index-lock` with the current timestamp before starting:
3247
-
3248
- ```bash
3249
- date -u +"%Y-%m-%dT%H:%M:%SZ" > draft/.index-lock
3250
- ```
3251
-
3252
- **On completion (Step 9) or fatal error, remove the lock:**
3253
-
3254
- ```bash
3255
- rm -f draft/.index-lock
3256
- ```
3257
-
3258
- ## Step 1: Parse Arguments
3259
-
3260
- Check for optional arguments:
3261
- - `--init-missing`: Also initialize services that don't have `draft/` directories
3262
- - `bughunt [dir1 dir2 ...]`: Run bug hunt across subdirectories with `draft/` folders
3263
- - If no directories specified: auto-discover all subdirectories with `draft/`
3264
- - If directories specified: run bughunt only in those subdirectories (skip if no `draft/`)
3265
- - Generate summary report at: `draft/bughunt-summary.md`
3266
-
3267
- **If `bughunt` argument detected:** Skip to Step 1A (Bughunt Mode) instead of continuing to Step 2.
3268
-
3269
- ## Step 1A: Bughunt Mode
3270
-
3271
- This mode runs `draft bughunt` across multiple subdirectories and aggregates results.
3272
-
3273
- ### 1A.1: Determine Target Directories
3274
-
3275
- **If directories explicitly specified** (e.g., `bughunt dir1 dir2 dir3`):
3276
- - Use provided directory list as targets
3277
- - Verify each directory exists
3278
- - Check each directory for `draft/` subdirectory
3279
- - Warn and skip any directory without `draft/`
3280
-
3281
- **If no directories specified** (e.g., just `bughunt`):
3282
- - Auto-discover all immediate child directories (depth=1)
3283
- - Filter for directories containing `draft/` subdirectory
3284
- - Exclude patterns: `node_modules/`, `vendor/`, `.git/`, `draft/`, `.*`
3285
-
3286
- ```bash
3287
- # Example auto-discovery
3288
- for dir in */; do
3289
- if [ -d "$dir/draft" ]; then
3290
- echo "$dir"
3291
- fi
3292
- done
3293
- ```
3294
-
3295
- **Output:**
3296
- ```
3297
- Target directories for bughunt:
3298
- - services/auth/
3299
- - services/billing/
3300
- - services/notifications/
3301
- ```
3302
-
3303
- ### 1A.2: Execute Bughunt Per Directory
3304
-
3305
- For each target directory:
3306
-
3307
- 1. **Set working directory** to `<target-dir>` for the bughunt scope. The AI agent should invoke `draft bughunt` with the target directory as the scope path, rather than using `cd`:
3308
- ```
3309
- draft bughunt
3310
- → (scope prompt) → "Specific paths"
3311
- → (paths prompt) → <target-dir>
3312
- ```
3313
-
3314
- 2. **Announce:**
3315
- ```
3316
- Running bughunt in <target-dir>...
3317
- ```
3318
-
3319
- 3. **Let `draft bughunt` run its full workflow:**
3320
- - Report will be generated at `<target-dir>/draft/bughunt-report-<timestamp>.md`
3321
- - Capture exit status (success/failure)
3322
-
3323
- 4. **Record results:**
3324
- - Directory path
3325
- - Total bugs found (by severity)
3326
- - Report location
3327
- - Any errors encountered
3328
-
3329
- **Note:** Run bughunts sequentially, not in parallel, to avoid context conflicts.
3330
-
3331
- ### 1A.3: Parse Individual Reports
3332
-
3333
- After all bughunts complete, read each generated report:
3334
-
3335
- ```bash
3336
- # For each target directory
3337
- cat <dir>/draft/bughunt-report-latest.md
3338
- ```
3339
-
3340
- Extract from each report:
3341
- - Branch and commit (from header)
3342
- - Summary table (bug counts by severity)
3343
- - Critical/High issue count
3344
- - Total issues count
3345
-
3346
- ### 1A.4: Generate Aggregate Summary Report
3347
-
3348
- Create `draft/bughunt-summary.md`:
3349
-
3350
- ```markdown
3351
- # Draft Index: Bughunt Summary
3352
-
3353
- **Date:** YYYY-MM-DD HH:MM
3354
- **Mode:** [Auto-discovery | Explicit directories]
3355
- **Directories Scanned:** N
3356
-
3357
- ## Overview
3358
-
3359
- | Directory | Critical | High | Medium | Low | Total | Report |
3360
- |-----------|----------|------|--------|-----|-------|--------|
3361
- | services/auth/ | 0 | 2 | 5 | 3 | 10 | [→](services/auth/draft/bughunt-report.md) |
3362
- | services/billing/ | 1 | 1 | 2 | 1 | 5 | [→](services/billing/draft/bughunt-report.md) |
3363
- | services/notifications/ | 0 | 0 | 1 | 2 | 3 | [→](services/notifications/draft/bughunt-report.md) |
3364
-
3365
- **Grand Total:** X Critical, Y High, Z Medium, W Low
3366
-
3367
- ## Directories With Critical Issues
3368
-
3369
- | Directory | Count | Details |
3370
- |-----------|-------|---------|
3371
- | services/billing/ | 1 | [→](services/billing/draft/bughunt-report.md#critical-issues) |
3372
-
3373
- ## Directories With No Issues
3374
-
3375
- - services/api-gateway/
3376
- - services/user-service/
3377
-
3378
- ## Skipped Directories
3379
-
3380
- | Directory | Reason |
3381
- |-----------|--------|
3382
- | services/legacy-tools/ | No draft/ directory found |
3383
- | services/experiments/ | No draft/ directory found |
3384
-
3385
- ## Next Steps
3386
-
3387
- 1. **Prioritize Critical Issues:** Review directories with Critical bugs first
3388
- 2. **Review Individual Reports:** Click links above to see detailed findings
3389
- 3. **Track Fixes:** Use `draft new-track` to create implementation tracks for fixes
3390
- 4. **Re-run After Fixes:** Run `draft index bughunt` again to verify
3391
-
3392
- ---
3393
-
3394
- *Generated by `draft index bughunt` command*
3395
- ```
3396
-
3397
- ### 1A.5: Completion Report
3398
-
3399
- ```
3400
- ---
3401
- DRAFT INDEX BUGHUNT COMPLETE
3402
- ---
3403
- Scanned: N directories
3404
- Completed: X successful
3405
- Skipped: Y (no draft/)
3406
- Failed: Z errors
3407
-
3408
- Grand Total Bugs:
3409
- Critical: W
3410
- High: X
3411
- Medium: Y
3412
- Low: Z
3413
-
3414
- Summary Report: draft/bughunt-summary.md
3415
-
3416
- Directories requiring immediate attention:
3417
- - services/billing/ (1 CRITICAL)
3418
- - services/auth/ (2 HIGH)
3419
-
3420
- ---
3421
- ```
3422
-
3423
- **STOP HERE** if bughunt mode. Do not continue to Step 2 (normal indexing flow).
3424
-
3425
- ## Step 2: Discover Services (Depth=1 Only)
3426
-
3427
- Scan immediate child directories for service markers. Do NOT recurse beyond depth=1.
3428
-
3429
- **Service detection markers (any of these):**
3430
- - `package.json` (Node.js)
3431
- - `go.mod` (Go)
3432
- - `Cargo.toml` (Rust)
3433
- - `pom.xml` or `build.gradle` (Java)
3434
- - `pyproject.toml` or `requirements.txt` (Python)
3435
- - `Dockerfile` (containerized service)
3436
- - `src/` directory with code files
3437
-
3438
- **Exclude patterns:**
3439
- - `node_modules/`
3440
- - `vendor/`
3441
- - `.git/`
3442
- - `draft/` (the root draft directory itself)
3443
- - Any directory starting with `.`
3444
-
3445
- ```bash
3446
- # Example discovery (adapt to actual structure)
3447
- ls -d */ | head -50
3448
- ```
3449
-
3450
- **Output:** List of detected service directories.
3451
-
3452
- ## Step 3: Categorize Services
3453
-
3454
- For each detected service directory, check for `draft/` subdirectory:
3455
-
3456
- ```bash
3457
- # For each service
3458
- ls <service>/draft/ 2>/dev/null
3459
- ```
3460
-
3461
- Categorize into:
3462
- - **Initialized:** Has `draft/` with context files
3463
- - **Uninitialized:** No `draft/` directory
3464
-
3465
- Report:
3466
- ```
3467
- Scanning immediate child directories...
3468
-
3469
- Detected X service directories:
3470
- ✓ Y initialized (draft/ found)
3471
- ○ Z uninitialized
3472
-
3473
- Initialized services:
3474
- - services/auth/
3475
- - services/billing/
3476
- - ...
3477
-
3478
- Uninitialized services:
3479
- - services/legacy-reports/
3480
- - services/admin-tools/
3481
- - ...
3482
- ```
3483
-
3484
- ## Step 4: Handle Uninitialized Services
3485
-
3486
- **If `init-missing` argument is present:**
3487
- 1. For each uninitialized service, prompt:
3488
- ```
3489
- Initialize <service-name>/? [y/n/all/skip-rest]
3490
- ```
3491
- 2. If user selects:
3492
- - `y`: Run `draft init` in that directory
3493
- - `n`: Skip this service
3494
- - `all`: Initialize all remaining without prompting
3495
- - `skip-rest`: Skip all remaining uninitialized services
3496
-
3497
- **If `init-missing` argument is NOT present:**
3498
- - Just report uninitialized services and continue
3499
- - Suggest: "Run `draft index --init-missing` to initialize these services"
3500
-
3501
- ## Step 5: Aggregate Context from Initialized Services
3502
-
3503
- For each initialized service, read and extract:
3504
-
3505
- ### 5.1 From `<service>/draft/product.md`:
3506
- - Service name
3507
- - First paragraph of Vision (summary)
3508
- - Target users (list)
3509
- - Core features (list)
3510
-
3511
- ### 5.2 From `<service>/draft/.ai-context.md` (or legacy `<service>/draft/architecture.md`):
3512
- - Key Takeaway paragraph (from `## System Overview`)
3513
- - External dependencies (from `## External Dependencies`)
3514
- - Exposed APIs or entry points (from `## Entry Points`)
3515
- - Dependencies on other services (look for references to sibling service names)
3516
- - Critical invariants summary (from `## Critical Invariants`, if available)
3517
-
3518
- ### 5.3 From `<service>/draft/tech-stack.md`:
3519
- - Primary language/framework
3520
- - Database
3521
- - Key dependencies
3522
-
3523
- ### 5.4 Create/Update `<service>/draft/manifest.json`:
3524
- ```json
3525
- {
3526
- "name": "<service-name>",
3527
- "type": "service",
3528
- "summary": "<first line of product vision>",
3529
- "primaryTech": "<main language/framework>",
3530
- "dependencies": ["<other-service-names>", "<external-deps>"],
3531
- "dependents": [],
3532
- "team": "<if found in docs>",
3533
- "initialized": "<date>",
3534
- "lastIndexed": "<current-date>"
3535
- }
3536
- ```
3537
-
3538
- ## Step 6: Detect Inter-Service Dependencies
3539
-
3540
- Analyze extracted data to build dependency graph:
3541
-
3542
- 1. Look for service name references in each service's architecture.md
3543
- 2. Look for API client imports or service URLs in tech-stack.md
3544
- 3. Look for mentions in product.md that reference other services
3545
- 4. **Graph-enriched detection** (if individual services have `draft/graph/` directories):
3546
- - Read each service's `draft/graph/architecture.json` `.routes` to map which service defines vs consumes which endpoints
3547
- - Cross-reference proto consumers with proto producers to build precise inter-service dependency edges
3548
- - Read `draft/graph/architecture.json` (`.packages`) per service for internal module structure
3549
- - This provides deterministic, code-level dependency data that supplements the heuristic name-matching above
3550
-
3551
- Build a dependency map:
3552
- ```
3553
- auth-service: [] # no dependencies on other services
3554
- billing-service: [auth-service]
3555
- api-gateway: [auth-service, billing-service]
3556
- ```
3557
-
3558
- ### Step 6.1b: Cycle Detection
3559
-
3560
- **Cycle detection:** Walk the dependency graph depth-first from each service. If a cycle is detected (service A depends on B depends on ... depends on A), emit a `> WARNING: Circular dependency detected: A → B → ... → A` line in `dependency-graph.md`, mark the back-edge with `circular: true` in `manifest.json`'s dependency entry, and continue processing. Do not fail on cycles — report and proceed.
3561
-
3562
- ### Step 6.2: Resolve Dependents (Reverse Lookup)
3563
-
3564
- For each service S, iterate all other services' `dependencies` arrays. If S appears in another service's dependencies, add that service to S's `dependents` array. Write the updated `manifest.json` for each service.
3565
-
3566
- ## Step 7: Generate Root Aggregated Files
3567
-
3568
- ### 7.1 Generate `draft/service-index.md`
3569
-
3570
- Use the following inline template:
3571
-
3572
- ```markdown
3573
- # Service Index
3574
-
3575
- > Auto-generated by `draft index` on <date>. Do not edit directly.
3576
- > Re-run `draft index` to update.
3577
-
3578
- ## Overview
3579
-
3580
- | Metric | Count |
3581
- |--------|-------|
3582
- | Total Services Detected | X |
3583
- | Initialized | Y |
3584
- | Uninitialized | Z |
3585
-
3586
- ## Service Registry
3587
-
3588
- | Service | Status | Tech Stack | Dependencies | Team | Details |
3589
- |---------|--------|------------|--------------|------|---------|
3590
- | auth | ✓ | Go, Postgres | - | @auth-team | [→](../services/auth/draft/.ai-context.md) |
3591
- | billing | ✓ | Node, Stripe | auth | @billing | [→](../services/billing/draft/.ai-context.md) |
3592
- | legacy-reports | ○ | - | - | - | Not initialized |
3593
-
3594
- ## Uninitialized Services
3595
-
3596
- The following services have not been initialized with `draft init`:
3597
- - `services/legacy-reports/`
3598
- - `services/admin-tools/`
3599
-
3600
- Run `draft index --init-missing` or initialize individually with:
3601
- ```bash
3602
- cd services/legacy-reports && draft init
3603
- ```
3604
- ```
3605
-
3606
- ### 7.2 Generate `draft/dependency-graph.md`
3607
-
3608
- ```markdown
3609
- # Service Dependency Graph
3610
-
3611
- > Auto-generated by `draft index` on <date>. Do not edit directly.
3612
-
3613
- ## System Topology
3614
-
3615
- ```mermaid
3616
- graph LR
3617
- subgraph "Core Services"
3618
- auth[auth-service]
3619
- billing[billing-service]
3620
- users[user-service]
3621
- end
3622
-
3623
- subgraph "Edge"
3624
- gateway[api-gateway]
3625
- end
3626
-
3627
- subgraph "Background"
3628
- notifications[notification-service]
3629
- reports[report-service]
3630
- end
3631
-
3632
- gateway --> auth
3633
- gateway --> billing
3634
- gateway --> users
3635
- billing --> auth
3636
- notifications --> users
3637
- reports --> billing
3638
- ```
3639
-
3640
- ## Dependency Matrix
3641
-
3642
- | Service | Depends On | Depended By |
3643
- |---------|-----------|-------------|
3644
- | auth-service | - | billing, gateway, users |
3645
- | billing-service | auth | gateway, reports |
3646
- | user-service | auth | gateway, notifications |
3647
- | api-gateway | auth, billing, users | - |
3648
-
3649
- ## Dependency Order (Topological)
3650
-
3651
- 1. **auth-service** (foundational - no internal dependencies)
3652
- 2. **user-service** (depends on: auth)
3653
- 3. **billing-service** (depends on: auth)
3654
- 4. **notification-service** (depends on: users)
3655
- 5. **report-service** (depends on: billing)
3656
- 6. **api-gateway** (depends on: auth, billing, users)
3657
-
3658
- > This ordering helps when planning cross-service changes or understanding impact.
3659
- ```
3660
-
3661
- ### 7.3 Generate `draft/tech-matrix.md`
3662
-
3663
- ```markdown
3664
- # Technology Matrix
3665
-
3666
- > Auto-generated by `draft index` on <date>. Do not edit directly.
3667
-
3668
- ## Common Stack (Org Standards)
3669
-
3670
- Technologies used by majority of services:
3671
-
3672
- | Technology | Usage | Services |
3673
- |------------|-------|----------|
3674
- | PostgreSQL | Database | auth, billing, users (85%) |
3675
- | Redis | Caching | auth, gateway, notifications (60%) |
3676
- | Docker | Containerization | all (100%) |
3677
- | GitHub Actions | CI/CD | all (100%) |
3678
-
3679
- ## Technology Distribution
3680
-
3681
- ### Languages
3682
-
3683
- | Language | Services | Percentage |
3684
- |----------|----------|------------|
3685
- | Go | auth, users, gateway | 45% |
3686
- | TypeScript | billing, notifications, reports | 45% |
3687
- | Python | ml-service, analytics | 10% |
3688
-
3689
- ### Databases
3690
-
3691
- | Database | Services |
3692
- |----------|----------|
3693
- | PostgreSQL | auth, billing, users, reports |
3694
- | MongoDB | notifications, analytics |
3695
- | Redis | auth, gateway (cache only) |
3696
-
3697
- ## Variance Report
3698
-
3699
- Services deviating from org standards:
3700
-
3701
- | Service | Deviation | Reason |
3702
- |---------|-----------|--------|
3703
- | ml-service | Python instead of Go/TS | ML ecosystem |
3704
- | analytics | MongoDB instead of Postgres | Time-series workload |
3705
- ```
3706
-
3707
- ### Placeholder Detection
3708
-
3709
- A file is considered a placeholder if it contains the marker `<!-- AUTO-GENERATED -->` or is smaller than 100 bytes. Placeholders may be overwritten without confirmation. Non-placeholder files require user confirmation before overwriting.
3710
-
3711
- ### 7.4 Synthesize `draft/product.md` (if not exists or is placeholder)
3712
-
3713
- Read all service product.md files and synthesize:
3714
-
3715
- ```markdown
3716
- # Product: [Org/Product Name]
3717
-
3718
- > Synthesized from X service contexts by `draft index` on <date>.
3719
- > Edit this file to refine the overall product vision.
3720
-
3721
- ## Vision
3722
-
3723
- [Synthesized from common themes across service visions - one paragraph describing what the overall product/platform does]
3724
-
3725
- ## Target Users
3726
-
3727
- <!-- Aggregated from all services, deduplicated -->
3728
- - **End Users**: [common user types across services]
3729
- - **Developers**: [if developer-facing APIs exist]
3730
- - **Operators**: [if ops/admin services exist]
3731
-
3732
- ## Service Capabilities
3733
-
3734
- | Capability | Provided By | Description |
3735
- |------------|-------------|-------------|
3736
- | Authentication | auth-service | User identity, JWT, OAuth |
3737
- | Payments | billing-service | Stripe integration, invoicing |
3738
- | API Access | api-gateway | Rate limiting, routing |
3739
-
3740
- ## Cross-Cutting Concerns
3741
-
3742
- <!-- Extracted from common patterns across services -->
3743
- - **Authentication**: All services validate via auth-service
3744
- - **Observability**: [common logging/tracing approach]
3745
- - **Data Privacy**: [common compliance patterns]
3746
- ```
3747
-
3748
- ### 7.5 Synthesize `draft/architecture.md` (if not exists or is placeholder)
3749
-
3750
- ```markdown
3751
- # Architecture: [Org/Product Name]
3752
-
3753
- > Synthesized from X service contexts by `draft index` on <date>.
3754
- > This is a system-of-systems view. For service internals, see individual service contexts.
3755
-
3756
- ## System Overview
3757
-
3758
- **Key Takeaway:** [One paragraph synthesizing overall system purpose from service summaries]
3759
-
3760
- ### System Topology
3761
-
3762
- ```mermaid
3763
- graph TD
3764
- subgraph "External"
3765
- Users[Users/Clients]
3766
- ThirdParty[Third-Party Services]
3767
- end
3768
-
3769
- subgraph "Edge Layer"
3770
- Gateway[API Gateway]
3771
- CDN[CDN/Static]
3772
- end
3773
-
3774
- subgraph "Core Services"
3775
- Auth[Auth Service]
3776
- Billing[Billing Service]
3777
- Users2[User Service]
3778
- end
3779
-
3780
- subgraph "Background"
3781
- Notifications[Notifications]
3782
- Reports[Reports]
3783
- end
3784
-
3785
- subgraph "Data Layer"
3786
- Postgres[(PostgreSQL)]
3787
- Redis[(Redis)]
3788
- Queue[Message Queue]
3789
- end
3790
-
3791
- Users --> Gateway
3792
- Gateway --> Auth
3793
- Gateway --> Billing
3794
- Gateway --> Users2
3795
- Billing --> ThirdParty
3796
- Auth --> Postgres
3797
- Billing --> Postgres
3798
- Notifications --> Queue
3799
- Reports --> Queue
3800
- ```
3801
-
3802
- ## Service Directory
3803
-
3804
- | Service | Responsibility | Tech | Status | Details |
3805
- |---------|---------------|------|--------|---------|
3806
- | auth-service | Identity & access management | Go, Postgres | ✓ Active | [→ context](../services/auth/draft/.ai-context.md) |
3807
- | billing-service | Payments & invoicing | Node, Stripe | ✓ Active | [→ context](../services/billing/draft/.ai-context.md) |
3808
-
3809
- ## Shared Infrastructure
3810
-
3811
- <!-- Extracted from common external dependencies -->
3812
-
3813
- | Component | Purpose | Used By |
3814
- |-----------|---------|---------|
3815
- | PostgreSQL | Primary datastore | auth, billing, users |
3816
- | Redis | Caching, sessions | auth, gateway |
3817
- | RabbitMQ | Async messaging | notifications, reports |
3818
- | Stripe | Payment processing | billing |
3819
-
3820
- ## Cross-Service Patterns
3821
-
3822
- <!-- Extracted from common conventions -->
3823
-
3824
- | Pattern | Description | Services |
3825
- |---------|-------------|----------|
3826
- | JWT Auth | All services validate JWT via auth-service | all |
3827
- | Event-Driven | Async events via message queue | notifications, reports |
3828
-
3829
- ## Notes
3830
-
3831
- - For detailed service architecture, navigate to individual service contexts
3832
- - This file is regenerable via `draft index`
3833
- - Manual edits to non-synthesized sections will be preserved on re-index
3834
- ```
3835
-
3836
- ### 7.6 Synthesize `draft/tech-stack.md` (if not exists or is placeholder)
3837
-
3838
- ```markdown
3839
- # Tech Stack: [Org/Product Name]
3840
-
3841
- > Synthesized from X service contexts by `draft index` on <date>.
3842
- > This defines org-wide standards. Service-specific additions are in their local tech-stack.md.
3843
-
3844
- ## Org Standards
3845
-
3846
- ### Languages
3847
- - **Primary**: [most common language] — [X% of services]
3848
- - **Secondary**: [second most common] — [Y% of services]
3849
-
3850
- ### Frameworks
3851
- - **API**: [common API framework]
3852
- - **Testing**: [common test framework]
3853
-
3854
- ### Infrastructure
3855
- - **Database**: PostgreSQL (standard), MongoDB (approved for specific use cases)
3856
- - **Caching**: Redis
3857
- - **Messaging**: RabbitMQ / SQS
3858
- - **Container**: Docker
3859
- - **Orchestration**: Kubernetes
3860
-
3861
- ### CI/CD
3862
- - **Platform**: GitHub Actions
3863
- - **Registry**: [container registry]
3864
-
3865
- ## Approved Variances
3866
-
3867
- | Service | Variance | Justification |
3868
- |---------|----------|---------------|
3869
- | ml-service | Python | ML ecosystem requirements |
3870
- | analytics | MongoDB | Time-series workload |
3871
-
3872
- ## Shared Libraries
3873
-
3874
- | Library | Purpose | Version | Used By |
3875
- |---------|---------|---------|---------|
3876
- | @org/auth-client | Auth service client | 2.x | billing, gateway, notifications |
3877
- | @org/logging | Structured logging | 1.x | all services |
3878
- ```
3879
-
3880
- ### 7.7 Synthesize `draft/.ai-context.md` (if not exists or is placeholder)
3881
-
3882
- After generating `draft/architecture.md`, derive a condensed `draft/.ai-context.md` using the Condensation Subroutine (as defined in `core/shared/condensation.md`). This provides a token-optimized, self-contained AI context file at the root level aggregating all service knowledge.
3883
-
3884
- - Read the synthesized `draft/architecture.md`
3885
- - Condense into 200-400 lines covering: system overview, service catalog, inter-service dependencies, shared infrastructure, cross-cutting patterns, critical invariants, and entry points
3886
- - If `draft/.ai-context.md` already exists and is not a placeholder, prompt before overwriting
3887
-
3888
- ## Step 8: Create Root Config
3889
-
3890
- Create `draft/config.yaml` if not exists:
3891
-
3892
- ```yaml
3893
- # Draft Index Configuration
3894
-
3895
- # Service detection patterns (immediate children only)
3896
- service_patterns:
3897
- - "package.json"
3898
- - "go.mod"
3899
- - "Cargo.toml"
3900
- - "pom.xml"
3901
- - "build.gradle"
3902
- - "pyproject.toml"
3903
- - "requirements.txt"
3904
- - "Dockerfile"
3905
-
3906
- # Directories to exclude from scanning
3907
- exclude_patterns:
3908
- - "node_modules"
3909
- - "vendor"
3910
- - ".git"
3911
- - "draft"
3912
- - ".*" # Hidden directories
3913
-
3914
- # Re-index on these events (for CI integration)
3915
- reindex_triggers:
3916
- - "service added"
3917
- - "service removed"
3918
- - "weekly"
3919
- ```
3920
-
3921
- ## Step 8.5: Refresh Graph Injection Slots
3922
-
3923
- For each initialized service with both `draft/architecture.md` AND `draft/graph/schema.yaml`:
3924
-
3925
- **A. Read current `architecture.md` into memory.**
3926
-
3927
- **B. Regenerate slot content from graph JSONL:**
3928
- - `GRAPH:module-deps` → run `scripts/tools/mermaid-from-graph.sh --repo . --diagram module-deps`
3929
- Parse JSON response, extract `.mermaid` string + `filtered` flag + stats
3930
- - `GRAPH:proto-map` → run `scripts/tools/mermaid-from-graph.sh --repo . --diagram proto-map`
3931
- Parse JSON response, extract `.mermaid` string + stats
3932
- - `GRAPH:hotspots` → read `draft/graph/hotspots.jsonl`, build top-10 markdown table:
3933
- `| File | Lines | fanIn | Score |` with one row per hotspot, ordered by score descending
3934
-
3935
- **C. For each slot, find `<!-- GRAPH:{id}:START -->` ... `<!-- GRAPH:{id}:END -->` markers.**
3936
- Replace entire block (inclusive of markers) with regenerated content.
3937
- If a marker pair is absent (legacy file): insert slot at the designated position and log:
3938
- `"Injected GRAPH:{id} slot into architecture.md (slot was absent — legacy file upgraded)"`
3939
-
3940
- **D. Write updated `architecture.md` back to disk.**
3941
- Update frontmatter: `generated_by = "draft:index"`, `generated_at = now`. Also update `draft/metadata.json` via `git-metadata.sh --project-metadata --generated-by "draft:index"` to re-anchor `synced_to_commit`.
3942
-
3943
- **E. Re-run Condensation Subroutine** (condensation.md) to propagate updated hotspot data into `.ai-context.md` GRAPH:HOTSPOTS and recompute tier budget. If `.ai-profile.md` exists, regenerate via Profile Generation Subroutine.
3944
-
3945
- **F. Report per service:**
3946
- ```
3947
- ✓ <service>: refreshed 3 graph slots (module-deps, proto-map, hotspots)
3948
- ✓ <service>: regenerated .ai-context.md (tier N, {lines} lines)
3949
- ```
3950
-
3951
- ## Step 9: Completion Report
3952
-
3953
- Remove the lockfile:
3954
-
3955
- ```bash
3956
- rm -f draft/.index-lock
3957
- ```
3958
-
3959
- ```
3960
- ---
3961
- DRAFT INDEX COMPLETE
3962
- ---
3963
- Scanned: X service directories (depth=1)
3964
- Indexed: Y services with draft/ context
3965
- Skipped: Z uninitialized services
3966
-
3967
- Generated/Updated:
3968
- ✓ draft/service-index.md (service registry)
3969
- ✓ draft/dependency-graph.md (inter-service topology)
3970
- ✓ draft/tech-matrix.md (technology distribution)
3971
- ✓ draft/product.md (synthesized product vision)
3972
- ✓ draft/architecture.md (system-of-systems view)
3973
- ✓ draft/tech-stack.md (org standards)
3974
- ✓ draft/config.yaml (index configuration)
3975
-
3976
- Service manifests updated: Y services
3977
-
3978
- Next steps:
3979
- 1. Review synthesized files in draft/
3980
- 2. Edit draft/product.md to refine overall vision
3981
- 3. Edit draft/architecture.md to add cross-cutting context
3982
- 4. Run draft index periodically to refresh
3983
-
3984
- For uninitialized services, run:
3985
- draft index init-missing
3986
- ---
3987
- ```
3988
-
3989
- ## Operational Notes
3990
-
3991
- ### What This Command Does NOT Do
3992
-
3993
- - **No deep code analysis** — Reads only existing `draft/*.md` files
3994
- - **No source code scanning** — That's `draft init`'s job per service
3995
- - **No recursive scanning** — Depth=1 only, immediate children
3996
- - **No duplication** — Root files link to service files, not copy content
3997
-
3998
- ### When to Re-Run
3999
-
4000
- - After running `draft init` on a new service
4001
- - After significant changes to service architectures
4002
- - Weekly/monthly as part of documentation hygiene
4003
- - Before major cross-service planning
4004
-
4005
- ### Preserving Manual Edits
4006
-
4007
- When regenerating, the skill:
4008
- 1. Reads existing root files
4009
- 2. Identifies manually-added sections (not marked as auto-generated)
4010
- 3. Preserves those sections while updating auto-generated parts
4011
- 4. Sections between `<!-- MANUAL START -->` and `<!-- MANUAL END -->` are never overwritten
4012
-
4013
- **Graph injection slots** (`<!-- GRAPH:...:START -->` / `<!-- GRAPH:...:END -->`) are ALWAYS overwritten during refresh — they are auto-managed. Never place manual content between these markers. Use `<!-- MANUAL START -->` / `<!-- MANUAL END -->` for content you want preserved near a slot.
4014
-
4015
- ---
4016
-
4017
3228
  ## Graph Command
4018
3229
 
4019
3230
  When user says "build graph", "refresh graph", or "draft graph [path]":
4020
3231
 
4021
- Initialize or refresh the `draft/graph/` knowledge-graph snapshot for a repository. This is the narrow "give me a fresh structural graph" command — it does **not** generate `architecture.md`/`.ai-context.md` (that is `draft init`) and does **not** re-inject doc diagram slots (that is `draft index`).
3232
+ Initialize or refresh the `draft/graph/` knowledge-graph snapshot for a single repository. This is the narrow "give me a fresh structural graph" command — it does **not** generate `architecture.md`/`.ai-context.md` and does **not** re-inject doc diagram slots (both are `draft init`). For scope-aware, root-first graph memory across a monorepo (root spine + module→root links), use `draft init --graph-only`.
4022
3233
 
4023
3234
  ## Red Flags - STOP if you're:
4024
3235
 
@@ -4068,7 +3279,7 @@ echo "Engine: $ENGINE"
4068
3279
 
4069
3280
  ## Step 3: Build / refresh the snapshot
4070
3281
 
4071
- 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`.
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 engine — no snapshot files are committed beyond `schema.yaml`.
4072
3283
 
4073
3284
  ```bash
4074
3285
  scripts/tools/graph-snapshot.sh --repo "$REPO_ABS"
@@ -4105,7 +3316,7 @@ Present a concise summary:
4105
3316
 
4106
3317
  Then point the user at the natural next steps:
4107
3318
 
4108
- - To re-inject the refreshed diagrams/hotspot tables into `architecture.md` / `.ai-context.md`: run `draft index`.
3319
+ - To re-inject the refreshed diagrams/hotspot tables into `architecture.md` / `.ai-context.md`: run `draft init refresh` (or `draft init --graph-only` to rebuild just the graph memory).
4109
3320
  - For a first-time full context bootstrap (architecture + profiles): run `draft init`.
4110
3321
 
4111
3322
  ## Graceful Degradation
@@ -4972,8 +4183,8 @@ You are decomposing a project or track into modules with clear responsibilities,
4972
4183
 
4973
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**:
4974
4185
 
4975
- 1. Load `draft/graph/architecture.json` (`.packages`) for the authoritative module list and fan-in/out.
4976
- 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.
4977
4188
  3. Use `scripts/tools/graph-callers.sh`/`graph-impact.sh` on demand for symbols/callers inside a candidate module.
4978
4189
  4. Run `scripts/tools/cycle-detect.sh --repo .` to enumerate existing cycles before proposing new boundaries.
4979
4190
 
@@ -5117,10 +4328,10 @@ ls -d src/*/ lib/*/ app/*/ packages/*/ 2>/dev/null
5117
4328
 
5118
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:
5119
4330
 
5120
- - **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
5121
4332
  - **Dependency edges**: Weighted inter-module dependencies with exact include counts — replaces manual import tracing
5122
4333
  - **Cycle detection**: Circular dependency paths already computed — use for identifying tight coupling and decomposition candidates
5123
- - **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
5124
4335
  - **Per-module detail**: query `scripts/tools/graph-callers.sh`/`graph-impact.sh` for symbol/call detail within modules of interest
5125
4336
 
5126
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.
@@ -5576,7 +4787,7 @@ When decomposition involves breaking a monolith, choosing module boundaries, or
5576
4787
 
5577
4788
  Before printing the completion announcement, internally verify and report:
5578
4789
 
5579
- 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`).
5580
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.
5581
4792
  3. **Filesystem grep fallback justification** — for every `grep`/`find` run, state the concept it searched for and quote the graph-miss sentence.
5582
4793
  4. **Citation Gate audit** — scan every Citation column in the generated component table, dependencies table, and LLD class table. Report:
@@ -5750,7 +4961,7 @@ If one of these applies, route directly to the specialist workflow and stop this
5750
4961
  - Keep matching invariants as **active constraints** for this task — these govern code generation, not just review
5751
4962
  - If invariants reference lock ordering, fail-closed behavior, or data integrity rules: these are non-negotiable during implementation
5752
4963
  9. **Load graph context** (if `draft/graph/schema.yaml` exists):
5753
- - 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
5754
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."
5755
4966
  - Query `scripts/tools/graph-impact.sh`/`graph-callers.sh` for the module(s) being modified — gives file-level dependency context
5756
4967
  - See `core/shared/graph-query.md` for on-demand query subroutines (callers, impact)
@@ -6759,8 +5970,8 @@ You are generating a pre-deployment verification checklist customized to this pr
6759
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:
6760
5971
 
6761
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.
6762
- 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.
6763
- 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.
6764
5975
 
6765
5976
  Filesystem `grep` is reserved for source-text scans (migration file names, flag-key strings). Module/impact discovery goes through the graph.
6766
5977
 
@@ -7069,7 +6280,7 @@ Read and follow the base procedure in `core/shared/draft-context-loading.md`.
7069
6280
  - **Leverage Storage Topology** — Identify data loss risks at each tier (cache eviction without writeback, event log gaps, missing archive)
7070
6281
  - **Leverage Consistency Boundaries** — Find bugs at eventual consistency seams (stale reads, lost events, missing reconciliation)
7071
6282
  - **Leverage Failure Recovery Matrix** — Verify idempotency claims, check for partial failure states without recovery paths
7072
- - **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`.
7073
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.
7074
6285
 
7075
6286
  ### 2. Confirm Scope
@@ -7095,6 +6306,19 @@ Use track context to:
7095
6306
 
7096
6307
  If no Draft context exists, proceed with code-only analysis.
7097
6308
 
6309
+ ## Multi-Directory Mode (monorepo)
6310
+
6311
+ `draft bughunt` can sweep multiple sub-projects in one run — useful at a monorepo root. Trigger it with an explicit directory list (`bughunt <dir1> <dir2> ...`) or no list (auto-discover).
6312
+
6313
+ 1. **Resolve targets:**
6314
+ - **Explicit list** → use the given directories; verify each exists; skip (with a warning) any that lack a `draft/` directory.
6315
+ - **Auto-discover** → immediate child directories containing a `draft/` folder, excluding `node_modules/`, `vendor/`, `.git/`, `draft/`, and dotfiles.
6316
+ 2. **Run sequentially** (not in parallel — avoids context conflicts): for each target, run the full single-target bug hunt below scoped to that directory. Each writes its own `<dir>/draft/bughunt-report-latest.md`.
6317
+ 3. **Aggregate** into `draft/bughunt-summary.md` at the invocation root: a table of `dir | Critical | High | Medium | Low | Total | report link`, a grand total, and a "directories with Critical issues" callout.
6318
+ 4. Report skipped directories (no `draft/`) and suggest running `draft init` in them first.
6319
+
6320
+ For a single target (the common case), skip this section and proceed.
6321
+
7098
6322
  ## Dimension Applicability Check
7099
6323
 
7100
6324
  Before analyzing all 14 dimensions, determine which apply to this codebase:
@@ -8080,7 +7304,7 @@ You are conducting a code review using Draft's Context-Driven Development method
8080
7304
 
8081
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**:
8082
7306
 
8083
- 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).
8084
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.
8085
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.
8086
7310
 
@@ -8439,18 +7663,18 @@ For the files changed in the diff, perform static checks using `grep` or similar
8439
7663
 
8440
7664
  - **Blast Radius Assessment** (if the `draft/graph/` snapshot exists):
8441
7665
  - List all changed files from the diff
8442
- - For each changed file, check if it appears in `hotspots.jsonl` — if yes, record its `fanIn` value
8443
- - 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**
8444
- - 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)
8445
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]`
8446
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
8447
7671
  - **Architecture Conformance:** Search for pattern violations documented in `draft/.ai-context.md`. (e.g. `import * from 'database'` in a React component).
8448
7672
  - **Dead Code:** Check for newly exported functions/classes in the diff that have 0 references across the codebase.
8449
7673
  - **Dependency Cycles:** Trace the import chains for new imports to ensure no circular dependencies (e.g., A → B → C → A) are introduced.
8450
- - **Graph Boundary Check** (if `draft/graph/architecture.json` exists) `[RC-013]`:
7674
+ - **Graph Boundary Check** (if `draft/graph/schema.yaml` exists) `[RC-013]`:
8451
7675
  - For each changed file, identify its module from the graph
8452
7676
  - Check if any new cross-module includes were added in the diff
8453
- - 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
8454
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"
8455
7679
  - Check if changes introduce files in modules listed in graph cycles — flag as higher risk
8456
7680
  - **Security Scan** `[RC-001, RC-002, RC-003, RC-011]`:
@@ -9144,7 +8368,7 @@ If Jira ticket linked, sync via `core/shared/jira-sync.md`:
9144
8368
 
9145
8369
  Before printing the final verdict, internally verify and report:
9146
8370
 
9147
- 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`).
9148
8372
  2. **Layer 1 files deliberately skipped** — list any context sections skipped as irrelevant to the diff under review.
9149
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.
9150
8374
 
@@ -9472,7 +8696,6 @@ When user says "discover debug" or "draft discover <intent>" (debug, bughunt, re
9472
8696
  - Code quality reviews (lightweight to exhaustive to architectural)
9473
8697
  - Coverage analysis and test strategy design
9474
8698
  - Discovering and codifying project conventions
9475
- - Monorepo indexing and context aggregation
9476
8699
  - Project tours, impact analysis, or reviewer assistance
9477
8700
 
9478
8701
  ## Routing Logic
@@ -9488,7 +8711,6 @@ Strong keyword and phrase matching with fallback to a menu when intent is broad
9488
8711
  | coverage, code coverage, test coverage report | `draft coverage` | Coverage measurement and gap report |
9489
8712
  | test strategy, testing plan, coverage targets, pyramid | `draft testing-strategy` | Test approach design |
9490
8713
  | learn patterns, discover conventions, update guardrails, anti-patterns | `draft learn` | Pattern mining + guardrail evolution |
9491
- | index services, aggregate context, monorepo index | `draft index` | Monorepo service context aggregation |
9492
8714
  | tour, walkthrough, onboard me, getting started tour | `draft tour` | Guided interactive project tour |
9493
8715
  | blast radius, code impact, affected modules, downstream callers | `draft review` or `scripts/tools/graph-impact.sh` | Graph-derived blast-radius before merge |
9494
8716
  | impact, delivery telemetry, track analytics, CDD effectiveness | `draft impact` | Project-wide track delivery telemetry |
@@ -9514,7 +8736,7 @@ User: "learn the coding patterns in this repo and tighten guardrails"
9514
8736
 
9515
8737
  User: "index the monorepo so agents see all services"
9516
8738
 
9517
- dispatches to `draft index --init-missing`
8739
+ Monorepo context is a foundation task, not a discover route: run `draft init` at the repo root (it builds the whole-repo code graph + a sparse root map linking each module). Running `draft init` inside a sub-module links that module up to the same root graph.
9518
8740
 
9519
8741
  ## Auto-Chains & Recommendations
9520
8742
 
@@ -11489,7 +10711,7 @@ You are performing a lightweight, ad-hoc code review. This is the fast alternati
11489
10711
 
11490
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:
11491
10713
 
11492
- 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).
11493
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".
11494
10716
 
11495
10717
  Filesystem `grep` is reserved for source-text scans (literal strings, regex patterns). Symbol and caller discovery go through the graph.
@@ -11546,9 +10768,9 @@ Determine the diff to review:
11546
10768
  3. If commit range: `git diff <range>`
11547
10769
  4. Default: `git diff HEAD~1..HEAD` (last commit)
11548
10770
 
11549
- ## 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)
11550
10772
 
11551
- 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:
11552
10774
 
11553
10775
  ```
11554
10776
  ⚠ HIGH IMPACT: {file} is a high-fanIn hotspot (fanIn={N}). Changes here propagate to many callers — review with extra care.
@@ -11705,10 +10927,10 @@ Perform an exhaustive end-to-end lifecycle review of a service, component, or mo
11705
10927
 
11706
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:
11707
10929
 
11708
- 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`.
11709
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.
11710
10932
  3. Run `scripts/tools/cycle-detect.sh --repo .` and flag any cycle that includes the audited module as Architecture Resilience finding.
11711
- 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.
11712
10934
 
11713
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.
11714
10936
 
@@ -12226,8 +11448,8 @@ Scan the codebase to discover recurring coding patterns and update `draft/guardr
12226
11448
 
12227
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:
12228
11450
 
12229
- 1. Enumerate a module's symbols/files via `scripts/tools/graph-callers.sh`/`graph-impact.sh` and `architecture.json` (preferred over `find`).
12230
- 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.
12231
11453
  3. For TS/Python/Go/C/C++, use `*-index.jsonl` to identify class/function definitions rather than re-discovering them via regex.
12232
11454
 
12233
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.
@@ -12461,15 +11683,15 @@ git log --follow --oneline -1 -- {file_containing_pattern}
12461
11683
 
12462
11684
  ### 2.7: Graph-Aware Severity Enrichment
12463
11685
 
12464
- 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 .`.
12465
11687
 
12466
11688
  For each anti-pattern candidate from Step 2.2:
12467
- 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 .`
12468
11690
  2. Take the highest fanIn value across all evidence files:
12469
11691
  - fanIn ≥ 10 → `graph_severity: critical` (breakage propagates to many callers)
12470
11692
  - fanIn 5–9 → `graph_severity: high`
12471
11693
  - fanIn 1–4 → `graph_severity: medium`
12472
- - fanIn 0 or file not in hotspots.jsonl → `graph_severity: low`
11694
+ - fanIn 0 or file not in hotspot output → `graph_severity: low`
12473
11695
  3. If no graph data exists → `graph_severity: unresolved`
12474
11696
 
12475
11697
  Collect all evidence files with fanIn ≥ 5 for the `high_fanin_files` field.
@@ -13078,10 +12300,10 @@ You are conducting a structured debugging session following systematic investiga
13078
12300
 
13079
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):
13080
12302
 
13081
- 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.
13082
12304
  2. Use `scripts/tools/graph-callers.sh --repo . --symbol <fn>` to enumerate call sites of suspect functions — not `grep`.
13083
12305
  3. Use `scripts/tools/graph-impact.sh --repo . --file <path>` to size the blast radius before proposing a fix.
13084
- 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).
13085
12307
 
13086
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.
13087
12309
 
@@ -13129,7 +12351,7 @@ Key context for debugging:
13129
12351
  - `.ai-context.md` — Module boundaries, data flows, invariants (crucial for tracing)
13130
12352
  - `tech-stack.md` — Language-specific debugging tools and techniques
13131
12353
  - `guardrails.md` — Known anti-patterns that may be causing the issue
13132
- - `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).
13133
12355
 
13134
12356
  ## Step 1: Parse Arguments
13135
12357
 
@@ -13462,8 +12684,8 @@ You are conducting a technical debt analysis to catalog, prioritize, and plan re
13462
12684
 
13463
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:
13464
12686
 
13465
- 1. Load `draft/graph/hotspots.jsonl` — **rank candidates by `fanIn × complexity`** to surface high-leverage debt first.
13466
- 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.
13467
12689
  3. Run `scripts/tools/cycle-detect.sh --repo .` to enumerate dependency cycles — every cycle is a candidate architecture-debt entry.
13468
12690
  4. For each catalogued finding, run `scripts/tools/graph-impact.sh --repo . --file <path>` so the remediation plan includes blast-radius.
13469
12691
 
@@ -15180,7 +14402,7 @@ Draft solves this through **Context-Driven Development**: structured documents t
15180
14402
  - [Command Workflows](#command-workflows)
15181
14403
  - [draft init](#draftinit--initialize-project)
15182
14404
  - [draft plan](#draftplan--planning-orchestrator)
15183
- - [draft index](#draftindex--monorepo-service-index)
14405
+ - [Monorepo Support (via draft init)](#monorepo-support-via-draftinit)
15184
14406
  - [draft new-track](#draftnew-track--create-feature-track)
15185
14407
  - [draft implement](#draftimplement--execute-tasks)
15186
14408
  - [draft status](#draftstatus--show-progress)
@@ -15555,7 +14777,7 @@ Draft auto-classifies the project:
15555
14777
  - **Brownfield (existing codebase):** Detected by the presence of `package.json`, `requirements.txt`, `go.mod`, `Cargo.toml`, `src/`, or git history with commits. Draft scans the existing stack and pre-fills `tech-stack.md`.
15556
14778
  - **Greenfield (new project):** Empty or near-empty directory. Developer provides all context through dialogue.
15557
14779
  - **Mature high-context brownfield:** Projects with strong existing agent-optimized docs (CLAUDE.md, INVARIANTS.md, ADRs, etc.) now receive an early Context Quality Audit, graph fidelity declaration, and explicit Relationship/Gaps sections so the generated architecture.md acts as graph-primary overlay rather than duplicative prose.
15558
- - **Monorepo:** Detected by `lerna.json`, `pnpm-workspace.yaml`, `nx.json`, `turbo.json`, or multiple package manifests in child directories. Suggests `draft index` instead.
14780
+ - **Monorepo:** Detected by `lerna.json`, `pnpm-workspace.yaml`, `nx.json`, `turbo.json`, or multiple package manifests in child directories. `draft init` is scope-aware — run it at the root for whole-repo context (sparse root map + the code-graph spine), or inside a sub-module to generate detailed module context that links up to the root graph. See **Monorepo Support (via draft init)** below.
15559
14781
 
15560
14782
  #### Initialization Sequence
15561
14783
 
@@ -15649,32 +14871,31 @@ The parent command should move planning forward rather than listing options.
15649
14871
 
15650
14872
  ---
15651
14873
 
15652
- ### `draft index` — Monorepo Service Index
14874
+ ### Monorepo Support (via `draft init`)
15653
14875
 
15654
- Aggregates Draft context from multiple services in a monorepo into unified root-level documents. Designed for organizations with multiple services, each with their own `draft/` context.
14876
+ There is no separate index command `draft init` is the single, scope-aware entry point. The same command behaves differently by where it is run, so a monorepo needs no special tooling.
15655
14877
 
15656
- #### What It Does
14878
+ #### Root init (run at the repo root)
15657
14879
 
15658
- 1. **Scans** immediate child directories for services (detects `package.json`, `go.mod`, `Cargo.toml`, etc.)
15659
- 2. **Reads** each service's `draft/product.md`, `draft/.ai-context.md` (or legacy `draft/architecture.md`), `draft/tech-stack.md`
15660
- 3. **Synthesizes** root-level documents:
14880
+ 1. **Builds the whole-repo code-graph spine** `graph-init.sh` indexes every file at every depth into one unified graph and writes the committed `draft/graph/` snapshot (the structural source of truth).
14881
+ 2. **Generates a sparse root map** (not deep per-module prose), aggregating the children into root-level documents:
15661
14882
  - `draft/service-index.md` — Service registry with status, tech, and links
15662
- - `draft/dependency-graph.md` — Inter-service dependency topology
14883
+ - `draft/dependency-graph.md` — Inter-service dependency topology (from the graph)
15663
14884
  - `draft/tech-matrix.md` — Technology distribution across services
15664
- - `draft/product.md` — Synthesized product vision (if not exists)
15665
- - `draft/.ai-context.md` — System-of-systems architecture view
15666
- - `draft/tech-stack.md` — Org-wide technology standards
14885
+ - `draft/architecture.md` — High-level system map linking *down* to each module's `draft/.ai-context.md`
14886
+ - `draft/.ai-context.md` / `draft/.ai-profile.md` Condensed system-of-systems views
15667
14887
 
15668
- #### Arguments
14888
+ #### Module init (run inside a sub-module)
15669
14889
 
15670
- - `init-missing` Run `draft init` on services that lack a `draft/` directory
15671
- - `bughunt [dir1 dir2 ...]` — Run `draft bughunt` across subdirectories with `draft/` folders. If no directories specified, auto-discovers all subdirectories with `draft/`. Generates summary report at `draft-index-bughunt-summary.md`.
14890
+ 1. **Ensures the root spine exists first** (builds it if missing), then builds the module's own `draft/graph/` snapshot.
14891
+ 2. **Writes `draft/graph/root-link.json`**a pointer up to the root graph so the module has full cross-module understanding regardless of where init ran.
14892
+ 3. **Generates the detailed module reference** (full 10-section `architecture.md` for the subtree). Use `--module-only` to skip touching the root (link marked `pending`).
15672
14893
 
15673
14894
  #### When to Use
15674
14895
 
15675
- - After running `draft init` on individual services
15676
- - After adding or removing services from the monorepo
15677
- - Periodically to refresh cross-service context
14896
+ - After cloning or adding a service — run `draft init` in it (auto-links to the root spine)
14897
+ - At the root after services change — refresh the whole-repo graph + sparse root map
14898
+ - `draft init --graph-only` to (re)build just the code-graph knowledge memory, no markdown
15678
14899
 
15679
14900
  ---
15680
14901
 
@@ -16554,7 +15775,7 @@ This matrix is the **single source of truth** for which Layer 0.5 files load per
16554
15775
 
16555
15776
  | Command type | Commands | Guardrails loaded |
16556
15777
  |---|---|---|
16557
- | **Read-only** | `draft status`, `draft standup`, `draft tour`, `draft index`, `draft coverage` | **none** |
15778
+ | **Read-only** | `draft status`, `draft standup`, `draft tour`, `draft coverage` | **none** |
16558
15779
  | **Spec / Plan** | `draft new-track`, `draft decompose`, `draft adr`, `draft testing-strategy`, `draft documentation` | `design-norms.md` only (architecture-shaped rules) |
16559
15780
  | **Code-touching (generation)** | `draft implement`, `draft debug`, `draft change`, `draft revert` | `code-quality.md` + `security.md` + `secure-patterns.md` + `language-standards.md` (detected stack) |
16560
15781
  | **Review** | `draft review`, `draft quick-review`, `draft deep-review`, `draft assist-review`, `draft bughunt`, `draft tech-debt` | `review-checks.md` + `security.md` + `language-standards.md` (detected stack); deep-review also loads `code-quality.md` + `design-norms.md` |
@@ -16587,13 +15808,11 @@ If `draft/graph/schema.yaml` exists, the project has automated graph analysis da
16587
15808
 
16588
15809
  | File | Purpose | Content |
16589
15810
  |------|---------|---------|
16590
- | `draft/graph/schema.yaml` | Snapshot metadata (engine, project, node/edge counts) | YAML, ~15 lines |
16591
- | `draft/graph/architecture.json` | Node labels, edge types, languages, packages (fan-in/out), entry points, routes, hotspots | JSON |
16592
- | `draft/graph/hotspots.jsonl` | Fan-in-ranked symbols, one object per line: `{id, name, fanIn}` | JSONL |
15811
+ | `draft/graph/schema.yaml` | Gate marker (engine + project metadata + point-of-index counts); presence gates graph use | YAML, ~15 lines |
16593
15812
 
16594
- 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).
16595
15814
 
16596
- 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:index`. For current data, regenerate via `scripts/tools/mermaid-from-graph.sh`.
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`.
16597
15816
 
16598
15817
  **Live structural queries** (run on demand — no per-language index files; the engine's model is unified):
16599
15818
 
@@ -16665,12 +15884,12 @@ Do NOT apply relevance scoring for commands that need full context (`draft init`
16665
15884
  | `## FILES` | Always (need file locations) |
16666
15885
  | `## VOCAB` | Domain-specific tasks |
16667
15886
 
16668
- 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:
16669
15888
 
16670
15889
  | Graph source | Use When Task Involves... |
16671
15890
  |------------|--------------------------|
16672
- | `architecture.json` | Module boundary changes, cross-module work, architecture analysis, API/route surface |
16673
- | `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 |
16674
15893
  | `scripts/tools/graph-callers.sh --symbol <name>` | Enumerating callers before a change |
16675
15894
  | `scripts/tools/graph-impact.sh --file <path>` / `--symbol <name>` | Tracing call paths, root cause analysis, function-level impact |
16676
15895
  | `scripts/tools/cycle-detect.sh` | Checking for call cycles |
@@ -17031,11 +16250,11 @@ Append under `## Learned Anti-Patterns`:
17031
16250
  - **Suggested fix:** [Brief description of the correct approach]
17032
16251
  ```
17033
16252
 
17034
- `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):
17035
16254
  - fanIn ≥ 10 in any evidence file → `critical`
17036
16255
  - fanIn 5–9 → `high`
17037
16256
  - fanIn 1–4 → `medium`
17038
- - fanIn 0 or file not in hotspots.jsonl → `low`
16257
+ - fanIn 0 or file not returned by hotspot query → `low`
17039
16258
  - Graph data absent → `unresolved`
17040
16259
 
17041
16260
  When `graph_severity` differs from `severity`, use `graph_severity` as the enforcement priority — it is objective and graph-derived.
@@ -17093,7 +16312,7 @@ This is a self-contained, callable procedure for generating `draft/.ai-context.m
17093
16312
 
17094
16313
  Any skill that mutates `architecture.md` should execute this subroutine afterward to keep the derived context files in sync.
17095
16314
 
17096
- **Called by:** `draft init`, `draft init refresh`, `draft implement`, `draft decompose`, `draft coverage`, `draft index`
16315
+ **Called by:** `draft init`, `draft init refresh`, `draft implement`, `draft decompose`, `draft coverage`
17097
16316
 
17098
16317
  ### Inputs
17099
16318
 
@@ -17165,16 +16384,16 @@ Transform each `architecture.md` section into machine-optimized format using thi
17165
16384
 
17166
16385
  #### Step 3.5: Generate Graph Summary Sections
17167
16386
 
17168
- 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.
17169
16388
 
17170
16389
  **GRAPH:MODULES** (tier ≥ 2 only):
17171
- - 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`)
17172
16391
  - Format: `{name}|{node_count} nodes|fan_in:{fan_in} fan_out:{fan_out}`
17173
16392
  - Order by `node_count` descending
17174
16393
  - Omit this section entirely for tier-1 codebases (≤5 modules) where Component Graph is sufficient
17175
16394
 
17176
16395
  **GRAPH:HOTSPOTS** (all tiers):
17177
- - 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
17178
16397
  - Format: `{name}|fanIn:{fanIn}` (use `id` for disambiguation when names collide)
17179
16398
  - Always include regardless of tier
17180
16399
 
@@ -17185,20 +16404,20 @@ If `draft/graph/schema.yaml` exists, generate these sections from the snapshot (
17185
16404
  - Always include — absence is positive signal that the call graph is acyclic
17186
16405
 
17187
16406
  **GRAPH:MODULE-HOTSPOTS** (tier ≥ 3 only):
17188
- - 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)
17189
16408
  - For each module: take its top 3 symbols by `fanIn`, format as indented lines under the module name
17190
16409
  - Format: `{module}: {name}|fanIn:{N}` with subsequent symbols indented to align
17191
16410
  - Order modules by their highest-fanIn symbol, descending
17192
16411
  - Omit modules with no hotspot entries; omit entire section for tier 1–2 (covered by global GRAPH:HOTSPOTS)
17193
16412
 
17194
16413
  **GRAPH:FAN-IN** (tier ≥ 3 only):
17195
- - 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
17196
16415
  - Format: `{name}|fanIn:{fan_in}|fanOut:{fan_out}`
17197
16416
  - Order by `fan_in` descending; include only modules with `fan_in ≥ 2`; cap at 15 rows
17198
16417
  - Omit entire section for tier 1–2 (trivially small graph)
17199
16418
 
17200
- **GRAPH:PROTO-MAP** (only when `architecture.json` `.routes` is non-empty):
17201
- - 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`)
17202
16421
  - Format: `{method} {path} → {handler}`
17203
16422
  - One line per route
17204
16423
  - Omit entire section if `.routes` is empty — do not write an empty section
@@ -17245,7 +16464,7 @@ Before writing `draft/.ai-context.md`, verify:
17245
16464
  - [ ] GRAPH:CYCLES present ("None ✓" or cycle list; or note if graph absent)
17246
16465
  - [ ] GRAPH:MODULE-HOTSPOTS present for tier ≥ 3 (or note if no hotspot data)
17247
16466
  - [ ] GRAPH:FAN-IN present for tier ≥ 3
17248
- - [ ] 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)
17249
16468
  - [ ] YAML frontmatter metadata is present at the top
17250
16469
 
17251
16470
  #### Step 7: Write Output
@@ -17629,13 +16848,13 @@ Shared procedure for querying the knowledge graph from any skill. The graph prov
17629
16848
 
17630
16849
  This is the **single source of truth** for graph lookup procedure. Consumer skills MUST reference this file rather than inlining their own lookup logic.
17631
16850
 
17632
- Referenced by: `draft init`, `draft implement`, `draft bughunt`, `draft review`, `draft deep-review`, `draft quick-review`, `draft debug`, `draft decompose`, `draft new-track`, `draft tech-debt`, `draft deploy-checklist`, `draft learn`, `draft index`
16851
+ Referenced by: `draft init`, `draft implement`, `draft bughunt`, `draft review`, `draft deep-review`, `draft quick-review`, `draft debug`, `draft decompose`, `draft new-track`, `draft tech-debt`, `draft deploy-checklist`, `draft learn`, `draft graph`
17633
16852
 
17634
16853
  ## Mandatory Lookup Contract
17635
16854
 
17636
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:
17637
16856
 
17638
- 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).
17639
16858
  2. **Generated context second** — `draft/.ai-context.md`, relevant `draft/architecture.md` slices, track-level `hld.md`/`lld.md`.
17640
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.
17641
16860
  4. **Filesystem `grep`/`find`/`rg` last** — only after an explicit graph miss.
@@ -17680,10 +16899,10 @@ A single "no" / "list" answer is a halt — fix and re-check before output.
17680
16899
 
17681
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.**
17682
16901
 
17683
- 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.
17684
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.
17685
- 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.
17686
- 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.
17687
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`.
17688
16907
 
17689
16908
  ## Graph Usage Report (Mandatory Footer)
@@ -17693,7 +16912,7 @@ Every code-touching skill output MUST end with this footer block. The lint check
17693
16912
  ```md
17694
16913
  ## Graph Usage Report
17695
16914
 
17696
- - 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>
17697
16916
  - Modules identified via graph: <comma-separated module names, or `none`>
17698
16917
  - Files identified via graph: <integer count>
17699
16918
  - Filesystem grep fallbacks: <list of `<pattern>` searches with one-line justification each, or `none`>
@@ -17731,7 +16950,7 @@ DRAFT_TOOLS="${DRAFT_PLUGIN_ROOT:-$HOME/.claude/plugins/draft}/scripts/tools"
17731
16950
  | `bash "$DRAFT_TOOLS/cycle-detect.sh"` | `--mode cycles` | Emits `{cycles:[],source:"unavailable"}` and exits 2 |
17732
16951
  | `bash "$DRAFT_TOOLS/mermaid-from-graph.sh" [--diagram module-deps\|proto-map]` | `--mode mermaid` | Emits an empty mermaid block and exits 2 |
17733
16952
 
17734
- Use the raw `graph` CLI directly for the lower-level modes documented below.
16953
+ 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)).
17735
16954
 
17736
16955
  ## Pre-Check
17737
16956
 
@@ -17743,26 +16962,26 @@ ls draft/graph/schema.yaml 2>/dev/null
17743
16962
 
17744
16963
  If absent, **skip all graph operations silently**. Graph enriches analysis — it never gates it. All skills must work identically without graph data.
17745
16964
 
17746
- ## Engine + snapshot model
16965
+ ## Engine model (engine-only)
16966
+
16967
+ 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.
17747
16968
 
17748
- 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:
16969
+ The only committed file is the gate marker:
17749
16970
 
17750
- 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.
17751
- 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.
16971
+ | File | Role |
16972
+ |------|------|
16973
+ | `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`. |
17752
16974
 
17753
- When `draft/graph/` exists, the snapshot contains:
16975
+ 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.
17754
16976
 
17755
- | File | Load | Content |
17756
- |------|------|---------|
17757
- | `schema.yaml` | Always | Engine + project metadata, node/edge counts, artifact list. Its presence **gates** graph use (see Pre-Check). |
17758
- | `architecture.json` | Always | `get_architecture(all)` output: node labels, edge types, languages, packages (with fan-in/out), entry points, routes, hotspots. |
17759
- | `hotspots.jsonl` | Always | Fan-in-ranked symbols, one JSON object per line: `{id, name, fanIn}`. |
17760
- | `module-deps.mermaid` | Diagram injection | File co-change coupling diagram (`FILE_CHANGES_WITH`). |
17761
- | `proto-map.mermaid` | Diagram injection | Detected service-route diagram (`Route` nodes). |
16977
+ ### How skills query (engine is the interface; jq is optional)
17762
16978
 
17763
- 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.
16979
+ - **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.
16980
+ - **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.
16981
+ - **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`).
16982
+ - **`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.
17764
16983
 
17765
- **Always-load files** are compact and should be read during context loading for any task that touches code structure.
16984
+ 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.
17766
16985
 
17767
16986
  ## Query Tools
17768
16987
 
@@ -17803,7 +17022,14 @@ Output: `{cycles[[a,b],[a,b,c]], source}` — fixed-length 2- and 3-node `CALLS`
17803
17022
 
17804
17023
  ### Modules — dependency overview
17805
17024
 
17806
- 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 .`.
17025
+ 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):
17026
+
17027
+ ```bash
17028
+ scripts/tools/graph-arch.sh --repo . \
17029
+ | jq '{packages, node_labels, edge_types, routes, layers, boundaries}'
17030
+ ```
17031
+
17032
+ `.packages` gives module fan-in/out, `.node_labels`/`.edge_types` the shape, `.routes` the service surface, `.layers`/`.boundaries` the dependency direction.
17807
17033
 
17808
17034
  ### Mermaid — diagram text
17809
17035
 
@@ -17812,15 +17038,15 @@ scripts/tools/mermaid-from-graph.sh --repo . --diagram module-deps # co-change
17812
17038
  scripts/tools/mermaid-from-graph.sh --repo . --diagram proto-map # detected routes
17813
17039
  ```
17814
17040
 
17815
- 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`.
17041
+ 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.
17816
17042
 
17817
- ### Building / refreshing the snapshot
17043
+ ### Indexing / refreshing the gate marker
17818
17044
 
17819
17045
  ```bash
17820
17046
  scripts/tools/graph-snapshot.sh --repo .
17821
17047
  ```
17822
17048
 
17823
- Writes the committed `draft/graph/` snapshot (`schema.yaml`, `architecture.json`, `hotspots.jsonl`, `*.mermaid`). Run during `draft init` and `draft index`, or whenever the reviewable graph state should be refreshed.
17049
+ Indexes the repo into the engine and writes the `draft/graph/schema.yaml` gate marker. It writes **no** graph data. Run during `draft init` and `draft graph`, or whenever the index should be refreshed.
17824
17050
 
17825
17051
  ## Finding the Engine (Resolution + Usage Report)
17826
17052
 
@@ -17844,24 +17070,24 @@ ENGINE_INFO="$(scripts/tools/verify-graph-binary.sh --repo . --json 2>/dev/null
17844
17070
 
17845
17071
  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.
17846
17072
 
17847
- ## Building the Snapshot
17073
+ ## Indexing the Repo
17848
17074
 
17849
- Run during `draft:init` / `draft:index`, or manually:
17075
+ Run during `draft:init` / `draft:graph`, or manually:
17850
17076
 
17851
17077
  ```bash
17852
17078
  scripts/tools/graph-snapshot.sh --repo .
17853
17079
  ```
17854
17080
 
17855
- 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.
17081
+ 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.
17856
17082
 
17857
17083
  ## Graceful Degradation
17858
17084
 
17859
17085
  | Scenario | Behavior |
17860
17086
  |----------|----------|
17861
- | No engine resolvable (or `DRAFT_MEMORY_DISABLE=1`) | Skip graph build in init; all skills proceed without graph data; tools emit `source: unavailable` |
17087
+ | No engine resolvable (or `DRAFT_MEMORY_DISABLE=1`) | Skip graph indexing in init; all skills proceed without graph data; tools emit `source: unavailable` |
17862
17088
  | Engine present but a query fails | Warn and proceed; skills work without graph data |
17863
- | `draft/graph/` snapshot exists | Load always-load files during context loading; use live query tools as needed |
17864
- | Stale snapshot | Still useful structural changes are infrequent. Re-run `graph-snapshot.sh` (or init) to refresh. |
17089
+ | `draft/graph/schema.yaml` exists | Engine is wired use live query tools as needed during the run |
17090
+ | 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. |
17865
17091
 
17866
17092
  </core-file>
17867
17093
 
@@ -18417,7 +17643,7 @@ See [graph-query.md](graph-query.md) §Graph Usage Report (Mandatory Footer) for
18417
17643
  ```md
18418
17644
  ## Graph Usage Report
18419
17645
 
18420
- - 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>
17646
+ - 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>
18421
17647
  - Modules identified via graph: <comma-separated module names, or `none`>
18422
17648
  - Files identified via graph: <integer count>
18423
17649
  - Filesystem grep fallbacks: <list of `<pattern>` searches with one-line justification each, or `none`>
@@ -18466,7 +17692,7 @@ Referenced by: `draft decompose`, `draft implement`, `draft review`, `draft deep
18466
17692
  ## Universal Red Flags (STOP if any apply)
18467
17693
 
18468
17694
  - **Ran `grep`/`find`/`rg` for symbol or file discovery before consulting the graph** (when `draft/graph/schema.yaml` exists).
18469
- - **Read more than 50 lines of source before consulting `draft/graph/hotspots.jsonl`** to know whether the file is a hotspot.
17695
+ - **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.
18470
17696
  - **Omitted the Graph Usage Report footer** from the final output (see [graph-query.md](graph-query.md) §Mandatory Lookup Contract).
18471
17697
  - **Used a `grep` fallback without an explicit graph-miss statement** in the form: `Graph returned no match for <X>; falling back to grep.`
18472
17698
  - **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).
@@ -18478,7 +17704,7 @@ Referenced by: `draft decompose`, `draft implement`, `draft review`, `draft deep
18478
17704
  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.
18479
17705
 
18480
17706
  - **Wrote a `path:line` / `func()` / `symbol` reference into a deliverable without opening the file in this run.** Graph hit ≠ Read. (G1)
18481
- - **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)
17707
+ - **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)
18482
17708
  - **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)
18483
17709
  - **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)
18484
17710
  - **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)
@@ -18488,7 +17714,7 @@ When in doubt, prefer "not yet validated against source" over an unbacked assert
18488
17714
 
18489
17715
  ## Graph-First Lookup Order (non-negotiable)
18490
17716
 
18491
- 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`).
17717
+ 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.
18492
17718
  2. **Generated context second** — `draft/.ai-context.md`, relevant `draft/architecture.md` slices, track-level `hld.md`/`lld.md`.
18493
17719
  3. **Source file reads third** — only narrowed targets identified via graph or generated context.
18494
17720
  4. **Filesystem `grep`/`find` last** — only after a graph miss, with the explicit fallback sentence above.
@@ -18644,6 +17870,7 @@ whose `pre_deploy_status != passing`.
18644
17870
  <core-file path="core/templates/guardrails.md">
18645
17871
 
18646
17872
  ---
17873
+ type: Guardrails
18647
17874
  project: "{PROJECT_NAME}"
18648
17875
  module: "root"
18649
17876
  generated_by: "draft:init"
@@ -19208,6 +18435,7 @@ Structured questions for track creation. **Ask ONE question at a time.** Wait fo
19208
18435
  <core-file path="core/templates/ai-context.md">
19209
18436
 
19210
18437
  ---
18438
+ type: ContextMap
19211
18439
  project: "{PROJECT_NAME}"
19212
18440
  module: "root"
19213
18441
  generated_by: "draft:init"
@@ -19257,7 +18485,7 @@ generated_at: "{ISO_TIMESTAMP}"
19257
18485
  ```
19258
18486
 
19259
18487
  > Include immediate sub-directories for all major modules (not just top-level).
19260
- > Use graph data (`draft/graph/modules/*.jsonl`) for exhaustive sub-module enumeration.
18488
+ > Use live engine queries (`get_architecture .packages[]` or `graph-callers.sh`) for exhaustive sub-module enumeration.
19261
18489
  > Show file counts per sub-module to indicate relative size/importance.
19262
18490
 
19263
18491
  ## GRAPH:MODULES
@@ -19487,6 +18715,7 @@ interface {ServiceName} {
19487
18715
  <core-file path="core/templates/ai-profile.md">
19488
18716
 
19489
18717
  ---
18718
+ type: Profile
19490
18719
  project: "{PROJECT_NAME}"
19491
18720
  module: "{MODULE_NAME or 'root'}"
19492
18721
  generated_by: "draft:{COMMAND_NAME}"
@@ -19537,6 +18766,7 @@ generated_at: "{ISO_TIMESTAMP}"
19537
18766
  <core-file path="core/templates/architecture.md">
19538
18767
 
19539
18768
  ---
18769
+ type: Architecture
19540
18770
  project: "{PROJECT_NAME}"
19541
18771
  module: "root"
19542
18772
  generated_by: "draft:init"
@@ -19567,9 +18797,9 @@ graph:
19567
18797
  go: "{approximate | high}"
19568
18798
  stats:
19569
18799
  modules: "{N from schema.yaml}"
19570
- edges: "{total_edges from architecture.json}"
18800
+ edges: "{total_edges from engine: get_architecture .edges}"
19571
18801
  hotspots: "{N}"
19572
- notes: "{explicit fidelity summary from architecture.json languages/packages}"
18802
+ notes: "{explicit fidelity summary from engine: get_architecture .languages/.packages}"
19573
18803
  generation_notes: "{High existing context detected via audit — see §10 Relationship for deference | Standard graph-primary generation}"
19574
18804
  ---
19575
18805
 
@@ -19651,7 +18881,7 @@ Each backed by:
19651
18881
 
19652
18882
  ## 4. Module & Dependency Map (Primarily Graph-Derived)
19653
18883
 
19654
- - Module dependency graph rendered from `draft/graph/architecture.json` (`.packages`) + `module-deps.mermaid`
18884
+ - 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)
19655
18885
  - High fan-in / fan-out modules highlighted
19656
18886
  - Cyclic dependencies called out
19657
18887
  - Cross-language boundaries (FFI, RPC, shared memory) explicitly surfaced with coverage notes
@@ -20196,6 +19426,7 @@ Use Cases:
20196
19426
  <core-file path="core/templates/product.md">
20197
19427
 
20198
19428
  ---
19429
+ type: Product
20199
19430
  project: "{PROJECT_NAME}"
20200
19431
  module: "root"
20201
19432
  generated_by: "draft:init"
@@ -20315,6 +19546,7 @@ Things explicitly out of scope for this product:
20315
19546
  <core-file path="core/templates/tech-stack.md">
20316
19547
 
20317
19548
  ---
19549
+ type: TechStack
20318
19550
  project: "{PROJECT_NAME}"
20319
19551
  module: "root"
20320
19552
  generated_by: "draft:init"
@@ -20493,6 +19725,7 @@ graph TD
20493
19725
  <core-file path="core/templates/workflow.md">
20494
19726
 
20495
19727
  ---
19728
+ type: Workflow
20496
19729
  project: "{PROJECT_NAME}"
20497
19730
  module: "root"
20498
19731
  generated_by: "draft:init"
@@ -20689,6 +19922,7 @@ If task exceeds 5 iterations:
20689
19922
  <core-file path="core/templates/spec.md">
20690
19923
 
20691
19924
  ---
19925
+ type: Spec
20692
19926
  project: "{PROJECT_NAME}"
20693
19927
  module: "root"
20694
19928
  track_id: "{TRACK_ID}"
@@ -20863,6 +20097,7 @@ approvers:
20863
20097
  <core-file path="core/templates/plan.md">
20864
20098
 
20865
20099
  ---
20100
+ type: Plan
20866
20101
  project: "{PROJECT_NAME}"
20867
20102
  module: "root"
20868
20103
  track_id: "{TRACK_ID}"
@@ -21113,7 +20348,7 @@ Portable stub. Content generalized from proven internal patterns.
21113
20348
  ---
21114
20349
  project: "{PROJECT_NAME}"
21115
20350
  module: "root"
21116
- generated_by: "draft:index"
20351
+ generated_by: "draft:init"
21117
20352
  generated_at: "{ISO_TIMESTAMP}"
21118
20353
  ---
21119
20354
 
@@ -21127,7 +20362,7 @@ generated_at: "{ISO_TIMESTAMP}"
21127
20362
  | **Synced To** | `{FULL_SHA}` |
21128
20363
 
21129
20364
  > Auto-generated. Do not edit directly.
21130
- > Re-run `draft index` to update.
20365
+ > Re-run `draft init` to update.
21131
20366
 
21132
20367
  ---
21133
20368
 
@@ -21154,7 +20389,7 @@ The following services have not been initialized with `draft init`:
21154
20389
 
21155
20390
  - `[path/to/service]/`
21156
20391
 
21157
- Run `draft index --init-missing` or initialize individually with:
20392
+ Initialize each one by running `draft init` inside its directory — it links the module's graph up to the root spine:
21158
20393
  ```bash
21159
20394
  cd [path/to/service] && draft init
21160
20395
  ```
@@ -21177,7 +20412,7 @@ cd [path/to/service] && draft init
21177
20412
  ---
21178
20413
  project: "{PROJECT_NAME}"
21179
20414
  module: "root"
21180
- generated_by: "draft:index"
20415
+ generated_by: "draft:init"
21181
20416
  generated_at: "{ISO_TIMESTAMP}"
21182
20417
  ---
21183
20418
 
@@ -21191,7 +20426,7 @@ generated_at: "{ISO_TIMESTAMP}"
21191
20426
  | **Synced To** | `{FULL_SHA}` |
21192
20427
 
21193
20428
  > Auto-generated. Do not edit directly.
21194
- > Re-run `draft index` to update.
20429
+ > Re-run `draft init` to update.
21195
20430
 
21196
20431
  ---
21197
20432
 
@@ -21289,7 +20524,7 @@ Services depending on external systems:
21289
20524
  ---
21290
20525
  project: "{PROJECT_NAME}"
21291
20526
  module: "root"
21292
- generated_by: "draft:index"
20527
+ generated_by: "draft:init"
21293
20528
  generated_at: "{ISO_TIMESTAMP}"
21294
20529
  ---
21295
20530
 
@@ -21303,7 +20538,7 @@ generated_at: "{ISO_TIMESTAMP}"
21303
20538
  | **Synced To** | `{FULL_SHA}` |
21304
20539
 
21305
20540
  > Auto-generated. Do not edit directly.
21306
- > Re-run `draft index` to update.
20541
+ > Re-run `draft init` to update.
21307
20542
 
21308
20543
  ---
21309
20544
 
@@ -21399,7 +20634,7 @@ Current versions in production:
21399
20634
  ---
21400
20635
  project: "{PROJECT_NAME}"
21401
20636
  module: "root"
21402
- generated_by: "draft:index"
20637
+ generated_by: "draft:init"
21403
20638
  generated_at: "{ISO_TIMESTAMP}"
21404
20639
  ---
21405
20640
 
@@ -21414,7 +20649,7 @@ generated_at: "{ISO_TIMESTAMP}"
21414
20649
 
21415
20650
  > Synthesized from [X] service contexts.
21416
20651
  > Edit this file to refine the overall product vision.
21417
- > Re-running `draft index` will update auto-generated sections but preserve manual edits.
20652
+ > Re-running `draft init` will update auto-generated sections but preserve manual edits.
21418
20653
 
21419
20654
  ---
21420
20655
 
@@ -21461,7 +20696,7 @@ generated_at: "{ISO_TIMESTAMP}"
21461
20696
  ---
21462
20697
  project: "{PROJECT_NAME}"
21463
20698
  module: "root"
21464
- generated_by: "draft:index"
20699
+ generated_by: "draft:init"
21465
20700
  generated_at: "{ISO_TIMESTAMP}"
21466
20701
  ---
21467
20702
 
@@ -21476,7 +20711,7 @@ generated_at: "{ISO_TIMESTAMP}"
21476
20711
 
21477
20712
  > Synthesized from [X] service contexts.
21478
20713
  > This is a **system-of-systems** view. For service internals, see individual service contexts.
21479
- > Re-running `draft index` will update auto-generated sections but preserve manual edits.
20714
+ > Re-running `draft init` will update auto-generated sections but preserve manual edits.
21480
20715
 
21481
20716
  ---
21482
20717
 
@@ -21583,7 +20818,7 @@ sequenceDiagram
21583
20818
  ## Notes
21584
20819
 
21585
20820
  - For detailed service architecture, navigate to individual service contexts via the Details column
21586
- - This file is regenerable via `draft index`
20821
+ - This file is regenerable via `draft init`
21587
20822
  - Manual edits between `<!-- MANUAL START -->` and `<!-- MANUAL END -->` are preserved
21588
20823
 
21589
20824
  </core-file>
@@ -21597,7 +20832,7 @@ sequenceDiagram
21597
20832
  ---
21598
20833
  project: "{PROJECT_NAME}"
21599
20834
  module: "root"
21600
- generated_by: "draft:index"
20835
+ generated_by: "draft:init"
21601
20836
  generated_at: "{ISO_TIMESTAMP}"
21602
20837
  ---
21603
20838
 
@@ -21612,7 +20847,7 @@ generated_at: "{ISO_TIMESTAMP}"
21612
20847
 
21613
20848
  > Synthesized from [X] service contexts.
21614
20849
  > This defines **org-wide standards**. Service-specific additions are in their local tech-stack.md.
21615
- > Re-running `draft index` will update auto-generated sections but preserve manual edits.
20850
+ > Re-running `draft init` will update auto-generated sections but preserve manual edits.
21616
20851
 
21617
20852
  ---
21618
20853
 
@@ -21721,6 +20956,7 @@ Org-wide conventions:
21721
20956
  <core-file path="core/templates/rca.md">
21722
20957
 
21723
20958
  ---
20959
+ type: RCA
21724
20960
  project: "{PROJECT_NAME}"
21725
20961
  track_id: "{TRACK_ID}"
21726
20962
  jira_ticket: "{JIRA_KEY}"
@@ -21895,6 +21131,7 @@ git-ignored at the track level. No HTML or PDF templates ship here.
21895
21131
  <core-file path="core/templates/discovery.md">
21896
21132
 
21897
21133
  ---
21134
+ type: Discovery
21898
21135
  project: "{PROJECT_NAME}"
21899
21136
  module: "root"
21900
21137
  track_id: "{TRACK_ID}"
@@ -21983,6 +21220,7 @@ without line numbers are exempt from drift checks (they document
21983
21220
  <core-file path="core/templates/hld.md">
21984
21221
 
21985
21222
  ---
21223
+ type: HLD
21986
21224
  project: "{PROJECT_NAME}"
21987
21225
  module: "root"
21988
21226
  track_id: "{TRACK_ID}"
@@ -22319,6 +21557,7 @@ Result stored in `metadata.json:pre_deploy_status`
22319
21557
  <core-file path="core/templates/lld.md">
22320
21558
 
22321
21559
  ---
21560
+ type: LLD
22322
21561
  project: "{PROJECT_NAME}"
22323
21562
  module: "root"
22324
21563
  track_id: "{TRACK_ID}"