init
/init
Initialize Draft project context for Context-Driven Development — the single, scope-aware entry point (works at the repo root or inside any sub-module; no separate index command). Builds the root-first code-graph knowledge memory (draft/graph/, with a module→root link) and creates product.md, tech-stack.md, workflow.md, tracks.md, architecture.md (brownfield), .ai-context.md (derived), and .ai-profile.md. Supports --graph-only (graph memory only, no markdown) and --module-only. Use when the user asks to 'init draft', 'set up Draft for this project', 'bootstrap context', 'build the code graph',
Assessment and security
- Files in this package
- 3
- Scripts
- 0
- HTML comments
- 11
- URLs in SKILL.md
- 0
No signals detected. Repository changed on 20.10.2026, without references to retired models or APIs.
MIT, open: use and modify while retaining author attribution.
- SKILL.md zawiera komentarze HTML (11). Nie widać ich w podglądzie Markdown, a model je czyta.
What it does and when to use it
Initialize Draft project context for Context-Driven Development — the single, scope-aware entry point (works at the repo root or inside any sub-module; no separate index command). Builds the root-first code-graph knowledge memory (draft/graph/, with a module→root link) and creates product.md, tech-stack.md, workflow.md, tracks.md, architecture.md (brownfield), .ai-context.md (derived), and .ai-profile.md. Supports --graph-only (graph memory only, no markdown) and --module-only. Use when the user asks to 'init draft', 'set up Draft for this project', 'bootstrap context', 'build the code graph',
Triggers from the description
Original author description
Initialize Draft project context for Context-Driven Development — the single, scope-aware entry point (works at the repo root or inside any sub-module; no separate index command). Builds the root-first code-graph knowledge memory (draft/graph/, with a module→root link) and creates product.md, tech-stack.md, workflow.md, tracks.md, architecture.md (brownfield), .ai-context.md (derived), and .ai-profile.md. Supports --graph-only (graph memory only, no markdown) and --module-only. Use when the user asks to 'init draft', 'set up Draft for this project', 'bootstrap context', 'build the code graph',
How it works
- Red Flags - STOP if you're
- MANDATORY SECTION CHECKLIST — architecture.md (Graph-Primary)
- Graph Fidelity & Diagram-First Priority (MANDATORY)
- Standard File Metadata
- Pre-Check
- Existing High-Quality Agent Context Audit (MANDATORY)
- Step 1: Project Discovery
- Step 1.4: Graph Analysis (Automated, Before Manual Discovery)
- Step 1.5: Architecture Discovery (Brownfield Only)
- architecture.md Specification (Graph-Primary — Forward Only)
SKILL.md preview
---
name: init
description: "Initialize Draft project context for Context-Driven Development — the single, scope-aware entry point (works at the repo root or inside any sub-module; no separate index command). Builds the root-first code-graph knowledge memory (draft/graph/, with a module→root link) and creates product.md, tech-stack.md, workflow.md, tracks.md, architecture.md (brownfield), .ai-context.md (derived), and .ai-profile.md. Supports --graph-only (graph memory only, no markdown) and --module-only. Use when the user asks to 'init draft', 'set up Draft for this project', 'bootstrap context', 'build the code graph', or says 'start using Draft', 'I want to use Draft here'."
---
# Draft Init
Initialize a Draft project for Context-Driven Development.
## Red Flags - STOP if you're
- Re-initializing a project that already has `draft/` without using `refresh` mode
- Skipping brownfield analysis for an existing codebase
- Rushing through product definition questions without probing for detail
- Auto-generating tech-stack.md without verifying detected dependencies
- Not presenting .ai-context.md for developer review before proceeding
- Overwriting existing tracks.md (this destroys track history)
- **Producing copy-paste module descriptions** — if 3+ modules share identical Responsibilities or description text, you have NOT analyzed the source files
- **Writing sequence diagrams under 15 lines** of Mermaid code — shallow diagrams without alt/opt blocks, payloads, and error paths are useless
- **Writing module deep-dives that ignore the graph or lack a workflow/state diagram** — the graph is ground truth; every significant module must have at least one synthesized diagram showing its primary flow or lifecycle. Prose volume without diagram fidelity is a failure.
- **Using "See X/" or "follow BUILD patterns"** as a substitute for reading actual source files and documenting real content
- **Ignoring detected high-quality existing agent context** (e.g. CLAUDE.md + docs/INVARIANTS.md written explicitly for AI agents) and regenerating large volumes of duplicative prose instead of a graph-primary overlay with strong cross-references and explicit Relationship section — this creates documentation debt and divergence risk in mature brownfield systems
- **Retaining any legacy 28-section or volume-oriented language** in generated architecture.md or in the reasoning process — the modern 10-section graph-primary template is the only accepted format.
**Initialize once, refresh to update. Never overwrite without confirmation.**
---
## MANDATORY SECTION CHECKLIST — architecture.md (Graph-Primary)
> **READ THIS BEFORE WRITING A SINGLE LINE OF architecture.md.**
> The document MUST use the EXACT modern graph-primary structure below. Freeform sections, renamed headings, or missing mandatory sections are FAILURES. This is the single forward-looking format — no legacy 28-section or volume-oriented material is accepted.
```text
## 1. Executive Summary + Graph Health Dashboard
## 2. Critical Invariants & Safety Rules (with provenance)
## 3. Primary Control & Data Flows (Graph + Synthesis)
## 4. Module & Dependency Map (Primarily Graph-Derived)
## 5. Concurrency, Ownership & Isolation Model
## 6. Error Handling & Failure Mode Catalog
## 7. State & Data Truth Sources + Reconciliation
## 8. Extension Points & Safe Mutation Patterns
## 9. Graph Coverage Gaps & Known Limitations (MANDATORY)
## 10. Relationship to Other Authoritative Documentation (MANDATORY on high/medium Context Audit)
```
**Self-check before finalizing**: Confirm every one of the 10 sections above exists with the required fidelity declarations, provenance tags on claims, and (where applicable) Mermaid diagrams grounded in the graph. The Graph Health Dashboard + §9 Gaps + §10 Relationship are the highest-leverage sections for future agents.
> **If you are a subagent**: your prompt is a summary. The 10-section graph-primary structure above is authoritative. Use the exact headings. No legacy 28-section material is permitted.
---
## Graph Fidelity & Diagram-First Priority (MANDATORY)
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.
**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:
- Graph = authoritative modules, edges, public surfaces, hotspots, call relationships.
- Your IDE/Agent index + full project understanding = semantic layer, workflow discovery, intent, and validation of the graph.
Cross-validate: if your index suggests a workflow, lifecycle, or design pattern that the graph does not yet surface, read the relevant source to confirm and then synthesize an accurate diagram that reflects reality.
**LLM role is faithful, high-fidelity synthesis** — not invention.
- Every structural claim must be consistent with the graph records. Contradiction = failure.
- **Diagrams are first-class deliverables.** For each major module or pipeline, produce at least one accurate Mermaid workflow, state, or sequence diagram.
- **Accuracy and correctness > document length.** Short, precise synthesis + good diagrams is superior to long prose or file lists.
- **Workflow and state focus.** Prioritize understanding primary control flows and state transitions so you can draw accurate diagrams.
This rule takes precedence over older volume-oriented language in this file.
---
## Standard File Metadata
**ALL files in `draft/` MUST include this metadata header.** This enables refresh tracking, sync verification, and traceability.
### Gathering Git Information
Before generating any file, run these commands to gather metadata:
```bash
# Project name (from manifest or directory)
basename "$(pwd)"
# Check if inside a git repository
if git rev-parse --is-inside-work-tree 2>/dev/null; then
# Git branch
git branch --show-current
# Git remote tracking branch
git rev-parse --abbrev-ref --symbolic-full-name @{upstream} 2>/dev/null || echo "none"
# Git commit SHA (full) — fails on repos with zero commits
git rev-parse HEAD 2>/dev/null || echo "none"
# Git commit SHA (short)
git rev-parse --short HEAD 2>/dev/null || echo "none"
# Git commit date
git log -1 --format="%ci" 2>/dev/null || echo "none"
# Git commit message (first line)
git log -1 --format="%s" 2>/dev/null || echo "none"
# Check for uncommitted changes
git status --porcelain | head -1
else
# Non-git project: use fallback values
echo "none" # branch
echo "none" # remote
echo "none" # commit
echo "none" # commit_short
echo "none" # commit_date
echo "none" # commit_message
# dirty: N/A for non-git projects
fi
```
> **Non-git projects:** If the project is not a git repository, all git metadata fields will be set to `"none"` and `git.dirty` to `false`. Refresh mode's incremental sync (`synced_to_commit`) will not function — full re-analysis is required on each refresh.
### Metadata Template
Insert this YAML frontmatter block at the **top of every draft/ file**:
```yaml
---
project: "{PROJECT_NAME}"
module: "{MODULE_NAME or 'root'}"
generated_by: "draft:{COMMAND_NAME}"
generated_at: "{ISO_TIMESTAMP}"
git:
branch: "{LOCAL_BRANCH}"
remote: "{REMOTE/BRANCH or 'none'}"
commit: "{FULL_SHA}"
commit_short: "{SHORT_SHA}"
commit_date: "{COMMIT_DATE}"
commit_message: "{FIRST_LINE_OF_COMMIT_MESSAGE}"
dirty: {true|false}
synced_to_commit: "{FULL_SHA}"
---
```
> **Note**: `generated_by` uses `draft:command` format (not `/draft:command`) for cross-platform compatibility.
### Field Definitions
| Field | Description | Example |
|-------|-------------|---------|
| `project` | Project name from package.json/go.mod/Cargo.toml or directory name | `my-api-service` |
| `module` | Module name if in monorepo, otherwise `root` | `auth-service` |
| `generated_by` | The Draft command that created/updated this file | `draft:init` |
| `generated_at` | ISO 8601 timestamp when file was generated | `2024-01-15T14:30:00Z` |
| `git.branch` | Current local branch name | `main` |
| `git.remote` | Upstream tracking branch | `origin/main` |
| `git.commit` | Full SHA of HEAD when generated | `a1b2c3d4e5f6...` |
| `git.commit_short` | Short SHA (7 chars) | `a1b2c3d` |
| `git.commit_date` | Commit timestamp | `2024-01-15 10:00:00 -0500` |
| `git.commit_message` | First line of commit message | `feat: add user auth` |
| `git.dirty` | Were there uncommitted changes? | `true` or `false` |
| `synced_to_commit` | The commit SHA this doc is synchronized to | `a1b2c3d4e5f6...` |
### Usage in Refresh
The `synced_to_commit` field is critical for incremental refresh:
- `/draft:init refresh` reads this field to find changed files since last sync
- If `git.dirty: true`, warn user that docs may not reflect committed state
- After refresh, update `synced_to_commit` to current HEAD
### Example Header
```yaml
---
project: "payment-gateway"
module: "root"
generated_by: "draft:init"
generated_at: "2024-01-15T14:30:00Z"
git:
branch: "main"
remote: "origin/main"
commit: "a1b2c3d4e5f6789012345678901234567890abcd"
commit_short: "a1b2c3d"
commit_date: "2024-01-15 10:00:00 -0500"
commit_message: "feat: add stripe integration"
dirty: false
synced_to_commit: "a1b2c3d4e5f6789012345678901234567890abcd"
---
```
---
## Pre-Check
Check for arguments:
- `refresh`: Update existing context without full re-init
- `--graph-only`: Build/refresh only the code-graph knowledge memory (no markdown) — see the fast path below
- `--module-only`: When run in a sub-module, do not touch the root graph (the module→root link is marked `pending`)
- `discover`: Route to `/draft:discover`
> `/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.
### Output Mode (`DRAFT_INIT_MODE`)
Init has two output modes. The default is **tier-gated (`auto`)** — resolved from the codebase tier computed in Step 1.4.5 — and the `DRAFT_INIT_MODE` environment variable overrides it:
```bash
DRAFT_INIT_MODE="${DRAFT_INIT_MODE:-auto}"
# auto → resolved AFTER tier is known (Step 1.4.5):
# tier 1–2 (micro/small) → monolith
# tier 3–5 (medium/large/XL) → okf
# monolith / okf → explicit override; honored as-is.
```
- **`monolith`** — the standard path documented in this skill: a single `architecture.md` (10-section graph-primary) + derived `.ai-context.md` / `.ai-profile.md`. The default for **small repos (tier 1–2)**, where one linear document beats a taxonomy with little to navigate. Also the A/B baseline and the over-fetch fallback.
- **`okf`** — emit an OKF-conformant concept taxonomy bundle (`draft/wiki/`) with `.ai-context.md` as the index root and `architecture.md` demoted to a generated rendered view. The default for **tier 3+ repos**, where navigation + maintainability pay off. When active, follow `references/okf-emitter.md` for the decomposition + serialization + validation stage; all shared phases (5-phase analysis, graph snapshot, `.state/` hashing, scope detection, atomic staging) are reused unchanged.
The tier-gated default rests on **maintainability/readability** (one navigable concept per file, cleaner PRs, a generated `architecture.md` preserved for linear onboarding) — not on the A/B benchmark, which was accuracy-parity (`docs/audit/okf-benchmark.md`). `monolith` is **retained, not retired**: it is the tier-1/2 default, the A/B baseline, and the fallback. If `DRAFT_INIT_MODE` is unset, do not commit to a mode until **Step 1.4.5** has computed the tier.
**OKF Completeness Verification (blocking — tier 3+ `okf` mode).** Completeness is enforced by tooling, not honor system, so the wiki is generated completely for every module/sub-module/component on every run. Before promoting `draft.tmp/` → `draft/`, ALL must hold (see `references/okf-emitter.md` for the pipeline):
1. `okf-plan-concepts.sh` ran and counts were logged **before** any page was written. Plan discovery is language-aware: **Cargo workspace members / npm workspaces / Go modules first**, then graph packages (noise-filtered), then heuristic dirs. Log `discovery[]` (e.g. `cargo+graph`).
2. `okf-emit-catalog.sh` ran so every REQUIRED plan entry has at least a minimum non-stub catalog page (LLM deep-dives may enrich top hotspots afterward).
3. Every `required` entry in `concept-plan.json` has a non-stub page.
4. `okf-render-views.sh` + `okf-fix-links.sh --fix` produced `architecture.md` with resolving `wiki/…` links and GFM TOC anchors.
5. `okf-validate-all.sh … --plan … --strict` exits 0 (**quality → coverage → structure**; structure runs last so coverage.md rewrites are checked).
6. `okf-fix-links.sh --draft draft.tmp --check` exits 0 (zero dead links in architecture / wiki views).
7. `systems/coverage.md` has the `<!-- okf:coverage-generated -->` marker; section indexes were regenerated by `okf-render-views.sh --section-indexes`.
8. On any failure: **do not** atomic-rename; surface `.state/validation-report.json`.
> **Red flag:** writing concept pages without first running `okf-plan-concepts.sh` + `okf-emit-catalog.sh`, or finishing while any `required` plan entry is unwritten, is a **completeness failure** — not a stylistic one.
### Route Explicit Modes Before Initialization
If the user explicitly invoked a specialist mode, route directly:
- `/draft:init discover` → follow `/draft:discover`
Explicit mode always wins. Do not perform standard initialization if an explicit mode is requested.
### `--graph-only` Fast Path
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).
### Standard Init Check
```bash
ls draft/ 2>/dev/null
```
If `draft/` exists with context files:
- Announce: "Project already initialized. Use `/draft:init refresh` to update context or `/draft:new-track` to create a feature."
- Stop here.
### Atomic File Staging
To prevent partial initialization from leaving a broken `draft/` directory:
1. **Stage all files** in a temporary directory (`draft.tmp/`) during init
2. **On success**: `mv draft.tmp/ draft/` (atomic rename on POSIX)
3. **On failure**: `rm -rf draft.tmp/` — no half-initialized state left behind
```bash
# Before writing any files:
mkdir -p draft.tmp/tracks
# Write all files to draft.tmp/ instead of draft/
# ... (product.md, tech-stack.md, workflow.md, tracks.md, architecture.md, .ai-context.md)
# After all files are written and verified:
mv draft.tmp/ draft/
```
> **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.
### Scope Detection (root vs sub-module)
`/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.
Resolve **ROOT** = nearest ancestor (above the current dir) containing `draft/` → else the git toplevel → else the current dir. Then:
- **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.)
- **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.
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).
### Migration Detection
If `draft/architecture.md` exists WITHOUT `draft/.ai-context.md`:
- Announce: "Detected architecture.md without .ai-context.md. Would you like to generate .ai-context.md? This will condense your existing architecture.md into a token-optimized AI context file."
- If user accepts: Run the Condensation Subroutine to derive `.ai-context.md` from existing `architecture.md`
- If user declines: Continue without .ai-context.md
If `draft/.ai-context.md` exists WITHOUT `draft/architecture.md`:
- Announce: "Detected .ai-context.md without its source architecture.md. The derived file exists but its primary source is missing (may have been accidentally deleted). Recommend running `/draft:init refresh` to regenerate architecture.md from codebase analysis."
- Do NOT delete the existing `.ai-context.md` — it still provides useful context until `architecture.md` is regenerated
### Refresh Mode
If the user runs `/draft:init refresh`:
**0. State-Aware Pre-Check** (before any refresh work):
**a. Check for interrupted previous run:**
```bash
cat draft/.state/run-memory.json 2>/dev/null
```
If `status` is `"in_progress"`, offer to resume from `resumable_checkpoint` or start fresh.
**b. Load freshness state (if available):**
```bash
cat draft/.state/freshness.json 2>/dev/null
```
If `freshness.json` exists, compute current file hashes and diff against stored hashes:
- **Changed files**: Hash differs from stored → these files need re-analysis
- **New files**: Present in current tree but not in stored → new modules/components to document
- **Deleted files**: Present in stored but not in current tree → sections to prune
- **Unchanged files**: Hash matches → skip re-reading these files entirely
If NO files changed (all hashes match AND no new/deleted files), announce:
"No source file changes detected since last init/refresh ({generated_at}). Architecture context is current. Nothing to refresh."
Stop here unless the user insists.
**c. Load signal state (if available):**
```bash
cat draft/.state/signals.json 2>/dev/null
```
If `signals.json` exists, re-run signal classification (Phase 1 step 5) and diff against stored signals:
- **New signal categories** (0→N): A new architectural concern appeared (e.g., auth files added for the first time). Flag these — new architecture.md sections may need to be generated.
- **Removed signal categories** (N→0): An architectural concern was removed. Flag for section pruning.
- **Signal count changes**: Significant growth (>50% increase) suggests the section needs deeper treatment.
Report signal drift:
```text
Signal drift detected:
NEW: auth_files (0 → 5) — §16 Security Architecture needs generation
GROWN: backend_routes (12 → 24) — §12 API Definitions, §14 Cross-Module Integration need expansion
REMOVED: background_jobs (3 → 0) — §8 Concurrency can be simplified
STABLE: services (8 → 9), test_infra (15 → 16)
```
**d. Create refresh run memory:**
If starting fresh: write new `draft/.state/run-memory.json` with `run_type: "refresh"` and `status: "in_progress"`.
If resuming from a checkpoint (step 0a): preserve existing fields (`phases_completed`, `resumable_checkpoint`, `active_focus_areas`) and only update `started_at` to current timestamp.
**e. Load previous unresolved questions:**
If the previous run had `unresolved_questions`, display them:
"Previous run flagged these unresolved questions: {list}. Keep these in mind during refresh."
1. **Tech Stack Refresh**: Re-scan `package.json`, `go.mod`, etc. Compare with `draft/tech-stack.md`. Propose updates.
2. **Architecture Refresh**:
**Mode detection (do this first).** If `draft/wiki/` exists, the bundle was generated in **`okf` mode** and `architecture.md` is a *generated rendered view*, not the source of truth. In that case **follow `references/okf-emitter.md` §"Incremental refresh at concept granularity (M5)"** instead of the monolith steps below: diff `hashes.json` → map changed source paths to affected concepts → regenerate only those concepts (carry the rest forward from cache) → always re-render `.ai-context.md`, `architecture.md`, and `log.md` via `okf-render-views.sh` → re-run `okf-validate.sh` so cross-links still resolve. Do **not** hand-edit `architecture.md` in this mode — it is overwritten by the renderer. Then skip to step 3.
Otherwise (**`monolith` mode** — `draft/architecture.md` is the source of truth and no `draft/wiki/` exists), use metadata-based incremental analysis. If freshness state is available from step 0b, use file-level deltas to scope the refresh more precisely than git-diff alone:
**a. Read synced commit from metadata:**
```bash
# Extract synced_to_commit from YAML frontmatter
SYNCED_SHA=$(grep "synced_to_commit:" draft/architecture.md | head -1 | sed 's/.*synced_to_commit:[[:space:]]*"\{0,1\}\([^"]*\)"\{0,1\}/\1/')
# Validate extracted SHA is a real git object
if [ -z "$SYNCED_SHA" ] || ! git cat-file -t "$SYNCED_SHA" 2>/dev/null; then
echo "Invalid or missing synced_to_commit — falling back to full refresh"
# Jump to step (i) — full refresh
fi
```
This returns the commit SHA the docs were last synced to (more reliable than file modification time). The SHA is validated before use to prevent silent failures in `git diff`.
**b. Get changed files since that commit:**
```bash
git diff --name-only <SYNCED_SHA> HEAD -- . ':!draft/'
```
This lists all source files changed since the last architecture sync, excluding the draft/ directory itself.
**c. Check if docs were generated with dirty state:**
If the original `git.dirty: true`, warn: "Previous generation had uncommitted changes. Full refresh recommended."
**d. Categorize changes:**
- **Added files**: New modules, components, or features to document
- **Modified files**: Existing sections that may need updates
- **Deleted files**: Components to remove from documentation
- **Renamed files**: Update file references
**e. Targeted analysis (only changed files):**
> **Guardrail:** If more than 100 files changed since last sync, recommend full 5-phase refresh instead of incremental analysis. Too many changes means the incremental approach loses its token-efficiency advantage.
- Read each changed file to understand modifications (up to 100 files; if more, fall back to full refresh)
- Identify which architecture.md sections are affected:
- New files → Component Map, Implementation Catalog, File Structure
- Modified interfaces → API Definitions, Interface Contracts
- Changed dependencies → External Dependencies, Dependency Graph
- New tests → Testing Infrastructure
- Config changes → Configuration & Tuning
- Preserve unchanged sections exactly as-is
- Preserve modules added by `/draft:decompose` (planned modules)
**f. Present incremental diff:**
Show user:
- Files analyzed: `N changed files since <date>`
- Sections updated: list of affected sections
- Summary of changes per section
**g. On user approval:**
- Update only the affected sections in `draft/architecture.md`
- Regenerate `draft/.ai-context.md` and `draft/.ai-profile.md` using the Condensation Subroutine
**h. On user rejection:**
- No changes made to `draft/architecture.md`
- However, verify `.ai-context.md` consistency: if `.ai-context.md` is missing or its `synced_to_commit` differs from `architecture.md`, offer to regenerate it from the current (unchanged) `architecture.md`
**i. Fallback to full refresh:**
If `synced_to_commit` is missing from metadata, or the commit SHA doesn't exist in git history:
```bash
git cat-file -t <SYNCED_SHA> 2>/dev/null || echo "not found"
```
If this returns "not found", run full 5-phase architecture discovery instead.
- If `draft/architecture.md` does NOT exist and the project is brownfield, offer to generate it now
**j. Update metadata after refresh:**
After successful refresh, update the YAML frontmatter in all modified files:
- `generated_by`: `draft:init refresh`
- `generated_at`: current timestamp
- `git.*`: current git state
- `synced_to_commit`: current HEAD SHA
**k. Refresh state files:**
After successful architecture refresh, regenerate all state files:
- `draft/.state/facts.json` — re-extract atomic facts, perform contradiction detection (see step 2l)
- `draft/.state/freshness.json` — recompute hashes of all source files (new baseline)
- `draft/.state/signals.json` — re-run signal classification (update baseline)
- `draft/.state/run-memory.json` — set `status: "completed"`, `completed_at: "{ISO_TIMESTAMP}"`, preserve `unresolved_questions`
**l. Contradiction detection (if facts.json exists):**
If `draft/.state/facts.json` exists from a previous run, perform fact-level diff:
1. **Re-extract facts** from changed files identified in step 2b
2. **Compare against existing facts** sourced from those files:
- **CONFIRMED**: Fact still holds — update `last_verified_at` and `last_active_at`
- **UPDATED**: Fact changed (e.g., API endpoint renamed) — mark old fact with `superseded_by` edge, create new fact
- **EXTENDED**: Fact refined with new detail — add `extends` edge to original fact
- **NEW**: Fact not previously recorded — add with full timestamps
- **STALE**: Fact's source file was deleted — mark `last_active_at` as stale, reduce confidence
3. **Generate Fact Evolution Report** — display summary to user:
```text
Fact Evolution Report:
CONFIRMED: N facts unchanged
UPDATED: N facts superseded (old → new)
EXTENDED: N facts refined
NEW: N facts discovered
STALE: N facts from deleted files
```
4. **Update relationship edges** in `facts.json` knowledge graph
3. **Product Refinement**: Ask if product vision/goals in `draft/product.md` need updates.
4. **Workflow Review**: Ask if `draft/workflow.md` settings (TDD, commits) need changing.
5. **Preserve**: Do NOT modify `draft/tracks.md` unless explicitly requested.
6. **Pattern Re-Discovery**: Run `/draft:learn` (no arguments — full codebase scan) to update `draft/guardrails.md` with any new or changed patterns since the last init/refresh. This keeps learned conventions and anti-patterns in sync with codebase evolution.
Stop here after refreshing. Continue to standard steps ONLY for fresh init.
## Existing High-Quality Agent Context Audit (MANDATORY)
Before any architecture discovery or large document generation, scan for known high-signal, agent-optimized documentation that may already serve as authoritative source of truth:
```bash
find . -maxdepth 4 \( -name "CLAUDE.md" -o -name "AGENTS.md" -o -name "INVARIANTS.md" -o -name "AUDIT_STANDARDS.md" -o -name "ARCHITECTURE.md" \) -not -path "./draft/*" -not -path "./node_modules/*" -not -path "./.git/*" 2>/dev/null | head -20
ls -d docs/ADRs 2>/dev/null && echo "ADR directory present ($(ls docs/ADRs/*.md 2>/dev/null | wc -l) records)" || true
```
Classify and emit **Context Quality Report** (always, even if none found):
- High: Multiple strong files with explicit AI/agent focus (e.g. "written so future AI agents don't have to re-read source", machine-verified INVARIANTS with test backing).
- Medium: Partial (README + some docs/).
- Low/None: Standard project.
If High or Medium:
- Emit terminal report with file list, sizes/signals, and explicit warning:
```text
Context Quality Report:
High-quality agent-optimized docs detected:
- CLAUDE.md (10k+ lines, purpose-built for AI coding assistants)
- docs/INVARIANTS.md (single source of truth, test-referenced)
- docs/AUDIT_STANDARDS.md
Duplication risk: Generating a large parallel architecture.md can create divergence in safety-critical systems. Highest risk is inconsistent documentation, not insufficient volume.
Action: architecture.md will be graph-primary (Full mode) with mandatory "Graph Coverage Gaps" and "Relationship to Existing Authoritative Documentation" sections. Strong cross-references + provenance tags required. Prose duplication of existing high-fidelity material is a verification failure.
```
- Set internal flag `EXISTING_CONTEXT_QUALITY=high` (propagate to synthesis, writing, and Completion Verification steps).
- Force §30 (Relationship) and §29 (Gaps) as non-skippable in later phases.
- In Completion Verification: add explicit check that Relationship section defers appropriately and adds only graph-derived or synthesized value.
This audit ensures Draft is safe and effective for mature brownfield projects that have already solved the "permanent AI agent context" problem at high fidelity.
## Step 1: Project Discovery
Analyze the current directory to classify the project:
**Brownfield (Existing)** indicators:
- Has `package.json`, `requirements.txt`, `go.mod`, `Cargo.toml`, etc.
- Has `src/`, `lib/`, or similar code directories
- Has git history with commits
**Greenfield (New)** indicators:
- Empty or near-empty directory
- Only has README or basic config
Respect `.gitignore` and `.claudeignore` when scanning.
If **Brownfield**: proceed to Step 1.5 (Architecture Discovery).
If **Greenfield**: skip to Step 2 (Product Definition).
---
## Step 1.4: Graph Analysis (Automated, Before Manual Discovery)
**IMPORTANT**: Before reading any source files manually, run the graph builder to get precise structural data. This step is fast (seconds, not minutes) and dramatically accelerates all subsequent phases.
**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.
### 1. Build the graph (scope-aware, root-first)
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.
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:
```bash
# Locate Draft's bundled helpers (cwd is the user's project; ${CLAUDE_PLUGIN_ROOT}
# is not exported into skill Bash). See core/shared/tool-resolver.md.
DRAFT_TOOLS="${DRAFT_PLUGIN_ROOT:-$(cat ~/.cache/draft/plugin-root 2>/dev/null)}/scripts/tools"
[ -d "$DRAFT_TOOLS" ] || DRAFT_TOOLS="$(ls -d ~/.claude/plugins/cache/*/draft/*/scripts/tools 2>/dev/null | sort -V | tail -1)"
[ -d "$DRAFT_TOOLS" ] || DRAFT_TOOLS="$(ls -d ~/.claude/plugins/marketplaces/*draft*/scripts/tools 2>/dev/null | tail -1)"
[ -d "$DRAFT_TOOLS" ] || DRAFT_TOOLS="$PWD/scripts/tools"
# Add --module-only to skip touching the root (link marked "pending").
if "$DRAFT_TOOLS/graph-init.sh" --scope .; then
echo "Graph memory ready under draft/graph/ (the root spine is the structural source of truth)."
else
echo "Graph engine unavailable — proceeding with degraded manual discovery. Downstream skills degrade gracefully."
fi
```
- **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.
- **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.
- 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.
Optionally record which engine was selected (usage-report contract):
```bash
"$DRAFT_TOOLS/verify-graph-binary.sh" --repo . --json 2>/dev/null || true
```
See `core/shared/graph-query.md` and `bin/README.md` for the query contract and engine resolution.
If indexing succeeds, `draft/graph/schema.yaml` is written and later steps query the engine live for structure + populate the injection slots.
### 2. If indexing succeeds, query the engine for structural context
Pull the architecture view once and reuse it across phases:
```bash
ARCH=$("$DRAFT_TOOLS/graph-arch.sh" --repo .)
```
- `$ARCH | jq '.packages'` — module list with fan-in/out
- `$ARCH | jq '.routes'` — detected service endpoints
- `$ARCH | jq '.languages, .node_labels, .layers, .boundaries'` — language mix, node shape, layering
- `"$DRAFT_TOOLS/hotspot-rank.sh" --repo . --top 20` — complexity/fan-in hotspots (live)
### 3. Use graph data to accelerate Step 1.5
- **Module boundaries**: Exact module list with file counts — skip manual directory tree mapping
- **Dependency wiring**: Exact inter-module edges with weights — skip manual `#include` / import tracing
- **Proto API surface**: Exact services, RPCs, and message definitions — skip manual proto discovery
- **Hotspots**: Know which high-complexity, high-fanIn files to prioritize reading
- **Language mix**: Exact `.cc`, `.h`, `.go`, `.proto`, `.py` counts per module
- **Cycle detection**: Circular dependency paths between modules — flag for architecture.md
### 4. Compute codebase tier and module priority
**Step 1.4.5 — Compute Codebase Tier:**
From the live `$ARCH` (above), extract:
- `M = $ARCH | jq '.packages | length'` (modules)
- `F = $ARCH | jq '[.node_labels[] | select(.label=="Function" or .label=="Method") | .count] | add // 0'` (functions+methods)
- `P = $ARCH | jq '.routes | length'` (routes / RPCs)
Apply tier table:
| Tier | Label | Condition | .ai-context.md Budget |
|------|--------|----------------------------------------|-----------------------|
| 1 | micro | M≤5 AND F≤50 AND P≤10 | 100–180 lines |
| 2 | small | M≤15 AND F≤300 AND P≤30 | 180–280 lines |
| 3 | medium | M≤40 AND F≤1000 AND P≤100 | 280–400 lines |
| 4 | large | M≤100 AND F≤5000 AND P≤500 | 400–600 lines |
| 5 | XL | M>100 OR F>5000 OR P>500 | 600–900 lines |
Hold tier in memory. This governs: architecture.md length minimum, .ai-context.md budget, and module deep-dive depth.
**Resolve the output mode now (if `auto`).** If `DRAFT_INIT_MODE` is unset/`auto`, finalize it from the tier just computed: **tier 1–2 → `monolith`**, **tier 3–5 → `okf`** (see **Output Mode** in Pre-Check). An explicit `DRAFT_INIT_MODE=monolith|okf` always wins and skips this resolution. Announce the resolved mode, e.g. `Tier 4 (large) → okf mode (wiki taxonomy bundle).` If `okf`, switch to `references/okf-emitter.md` for the decomposition + serialization + render-views + validate stage from here on; all the shared analysis above is reused unchanged.
**Step 1.4.6 — Build Module Priority List:**
From `"$DRAFT_TOOLS/hotspot-rank.sh" --repo .`: count hotspot symbols per module.
From `$ARCH | jq '.packages[]'`: read `fan_in` per module.
Rank modules by: `(hotspot_count × 2) + fan_in_count`.
Top-ranked modules drive Section 6 deep-dive ordering and depth. Modules ranked zero on both: summary treatment only.
Hold ranked list in memory — it replaces directory scanning for module discovery.
**Step 1.4.7 — Populate Graph Injection Slots:**
Query for diagram content and write into architecture.md slots using the standard marker format.
For Section 4.4 (module-deps slot):
```bash
"$DRAFT_TOOLS/mermaid-from-graph.sh" --repo . --diagram module-deps
```
The tool emits a ready-to-inject ` ```mermaid ``` ` block (or an empty stub on exit 2). Write between the markers:
```text
<!-- GRAPH:module-deps:START -->
{mermaid block from the tool}
<!-- GRAPH:module-deps:END -->
```
For Section 20 (hotspots slot):
Run `"$DRAFT_TOOLS/hotspot-rank.sh" --repo . --top 10`, take the top 10 by fanIn, build a markdown table:
```text
<!-- GRAPH:hotspots:START -->
| Symbol | fanIn |
|--------|-------|
| {name} | {fanIn} |
...
<!-- GRAPH:hotspots:END -->
```
For Appendix E (proto-map slot):
```bash
"$DRAFT_TOOLS/mermaid-from-graph.sh" --repo . --diagram proto-map
```
The tool emits a ` ```mermaid ``` ` block from detected routes (empty stub if none). Write:
```text
<!-- GRAPH:proto-map:START -->
```mermaid
{diagram content}
```
<!-- GRAPH:proto-map:END -->
```text
**If slot markers are absent** (first run on a repo that has no prior slot structure): write the slot content at the designated location in the template. The markers are always present in `core/templates/architecture.md`, so this path is only hit if a user has an older pre-slot architecture.md.
### 5. If graph binary not found or build fails
Proceed with standard Step 1.5 manual discovery. No degradation — the 5-phase analysis works as before. Architecture.md length minimum defaults to tier-2 guidance (medium-depth treatment).
See `core/shared/graph-query.md` for the full graph query subroutine reference.
---
## Step 1.5: Architecture Discovery (Brownfield Only)
Perform a **one-time, exhaustive analysis** of the existing codebase. This is NOT a summary — it is a comprehensive reference document that enables future AI agents and engineers to work without re-reading source files.
**Outputs**:
- `draft/architecture.md` — Human-readable, **comprehensive** engineering reference (PRIMARY)
- `draft/.ai-context.md` — Token-optimized, tier-scaled budget, condensed from architecture.md (DERIVED)
- `draft/.ai-profile.md` — Ultra-compact, 20-50 lines, always-injected project profile (DERIVED)
- `draft/graph/` — Knowledge graph artifacts (module-graph, proto-index, hotspots, per-module files) from Step 1.4
**Target output**: A single self-contained reference document designed for **dual consumption**:
1. **LLM / AI-agent context** — enabling future code changes, Q&A, and onboarding without re-reading source files.
2. **Engineer reference** — enabling debugging, extension, and operational understanding.
### Graph + Indexed Knowledge Fidelity Mandate
**CRITICAL**: The output must be **faithful to the deterministic graph and your environment's full indexed understanding** of the project. This is not "read every file" exhaustiveness — it is correctness and completeness of the *model*.
- The knowledge graph (`draft/graph/`) + your agent/IDE's rich codebase index together form the authoritative view.
- Use direct source reads strategically (hotspots, interfaces, key implementation paths) to validate, enrich, and draw accurate diagrams — not as a brute-force enumeration exercise.
- **Prioritize synthesis of accurate workflow, state, sequence, and component diagrams** that make the graph's facts and the project's higher-level design immediately usable.
- **Include real, verified code snippets and invariants** only where they add understanding not already visible in the graph or diagrams.
- **Target: highest possible correctness** of the generated architecture model. A concise, diagram-rich document that an agent or engineer can trust is the goal. Volume without fidelity is noise.
If the codebase is large (200+ files), focus on the module boundaries but still enumerate exhaustively within each module.
> **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.
### Parallel Analysis Protocol (Tiers 3–5)
**MANDATORY for tiers 3–5 (medium / large / XL).** Uses Map → IR+Prose → Reduce: parallel reader agents each produce both structured IR metadata and full §7 deep-dive prose, then a synthesis agent composes the final document. Cuts wall clock by ~55% at XL tier while preserving depth — readers write the module narratives from source; synthesis assembles the cross-cutting sections.
**For tiers 1–2 (micro / small): skip this protocol entirely.** Use the Sequential Generation Protocol below. At small scale, parallelism adds overhead with no speed benefit, and the IR intermediate step discards source-level depth that a direct sequential pass produces cheaply.
> Full protocol details, IR schema, and prompt templates are in `core/shared/parallel-analysis.md`.
#### Tier-Adaptive Agent Counts
From the tier computed in Step 1.4.5, determine reader agent count:
| Tier | Label | Reader Agents | Strategy |
|------|--------|--------------------------------------|--------------------------------------|
| 1 | micro | 1 (all modules in one agent) | 1 reader → 1 synthesizer |
| 2 | small | 1–2 (all or half modules each) | 1–2 readers → 1 synthesizer |
| 3 | medium | 2–3 (ceil(M/6) agents) | parallel readers → 1 synthesizer |
| 4 | large | ceil(M/4) agents | parallel readers → 1 synthesizer + parallel finalizers |
| 5 | XL | ceil(M/4) agents | parallel readers → 1 synthesizer + parallel finalizers |
For tiers 1–2, the "parallel" phase is just a single reader agent — no overhead, same clean IR boundary.
For tier 3+, readers run simultaneously; wall clock = slowest reader, not the sum.
#### Phase 0: Graph Data (already done in Step 1.4)
The engine is already indexed. Query it live throughout this protocol (reuse `$ARCH` from Step 1.4.2):
- `$ARCH | jq '.packages'` — module list with `.fan_in`/`.fan_out` (for grouping)
- `$ARCH | jq '.languages, .node_labels'` — file/symbol counts, tier metrics
- `"$DRAFT_TOOLS/hotspot-rank.sh" --repo .` — top hotspot symbols per module (feed to readers)
#### Phase 1: Spawn Parallel Module Readers
**Step 1: Group modules.**
From `$ARCH | jq '.packages[]'`, extract all module names and their `fan_in` counts.
Apply dependency-aware grouping (see `core/shared/parallel-analysis.md`).
Use the modules-per-agent count from the tier table above (4 for tier 4/5; all modules in one agent for tier 1):
- Assign highest fan-in modules to separate readers (tier 3+)
- Co-locate coupled module pairs in the same reader
- Target balanced token budgets across groups
**Step 2: Build graph data summary per group.**
For each reader group, prepare a compact summary from graph artifacts:
```
Modules: [execution, fill_processor, order_manager]
Hotspot files:
execution/engine.go (847 lines, fanIn=12)
execution/router.go (412 lines, fanIn=8)
fill_processor/handler.go (623 lines, fanIn=5)
Module edges (from $ARCH .packages fan-in/out):
execution → [risk, data, services]
fill_processor → [execution, persistence]
```text
**Step 3: Spawn all reader agents in parallel using the Agent tool.**
Spawn `ceil(module_count / 4)` agents simultaneously. Use the Module Reader Prompt Template from `core/shared/parallel-analysis.md`, replacing:
- `{MODULE_LIST}` — comma-separated module names for this agent
- `{REPO_ROOT}` — absolute path to repository root
- `{GRAPH_DATA_SUMMARY}` — the compact summary built in Step 2
Each reader agent:
- Reads source files in its assigned modules only
- Outputs a JSON array of IR objects (one per module)
- Produces NO prose, NO documentation
**Critical constraints to include in reader prompts:**
```
MUST output IR JSON array only.
MUST NOT write any documentation or architecture sections.
MUST NOT read files outside assigned modules.
Token budget: max 600 tokens per module in IR output.
```text
**Step 4: Collect and validate reader outputs.**
Each reader produces two outputs, separated by `## IR` and `## Deep-Dives` headings.
After all readers complete:
1. Extract the `## IR` section from each reader output and parse as JSON. If parse fails, retry that reader (see failure modes in `core/shared/parallel-analysis.md`).
2. Check IR `token_budget_used` — if < 150 for a module with >20 files AND deep-dive for that module is < 100 lines, re-run that reader with explicit instruction to read more files.
3. Concatenate all IR objects into a single JSON array → `draft.tmp/.state/reader-irs.json`
4. Concatenate all `## Deep-Dives` sections from all readers → `draft.tmp/.state/reader-deep-dives.md`
#### Phase 2: Synthesis
Collect reader outputs before spawning synthesis:
1. Parse and concatenate all IR JSON arrays → `draft.tmp/.state/reader-irs.json`
2. Concatenate all reader deep-dive Markdown sections → `draft.tmp/.state/reader-deep-dives.md`
Spawn a **single synthesis agent** with the Synthesis Coordinator Prompt from `core/shared/parallel-analysis.md`, replacing:
- `{CONCATENATED_DEEP_DIVES}` — content of `draft.tmp/.state/reader-deep-dives.md`
- `{CONCATENATED_IRS}` — content of `draft.tmp/.state/reader-irs.json`
- `{GRAPH_DEPENDENCY_DIAGRAM}` — mermaid output from `--query --mode mermaid --symbol module-deps`
- `{ARCHITECTURE_TEMPLATE_STRUCTURE}` — the modern 10-section graph-primary outline from `core/templates/architecture.md` (the single source of truth)
The synthesis agent:
- Integrates the reader outputs (now graph + one high-quality workflow/state diagram + minimal notes per module) into §7 with light editing only for consistency and cross-references.
- Derives the true cross-cutting sections (§4 topology, §5 component map, §6 operational flows, §8 concurrency, §14 integration sequences, §15 invariants, etc.) by combining IR data, reader diagrams, and additional targeted source reads.
- Aggressively uses its own full indexed project knowledge (from the host Cursor/Claude Code/Copilot environment) to improve accuracy of workflows, state machines, and higher-level design synthesis beyond what the static graph snapshot provides.
- Produces a document whose primary value is faithful, visual, diagram-rich representation of the actual system design.
**Source reading policy for synthesis agent (enforce in prompt):**
```
Read source (and aggressively use your full project index) for:
- §6 Core Operational Flows — the most important system-level workflows, lifecycles, and state machines (this is the highest-ROI section for future coding accuracy)
- §12 API / Interface surface
- §14 Cross-module integration sequences
- §15 Critical Invariants (verification against actual code)
- §18 Key Design Patterns
All other sections: compose primarily from the graph + reader outputs + IR, with light additional reads only where needed for diagram accuracy.
```text
#### Phase 3: Parallel Finalization
Once `draft.tmp/architecture.md` is written, spawn two agents simultaneously:
**Finalizer A — Context Derivation:**
Run the Condensation Subroutine (defined later in this skill) to generate:
- `draft.tmp/.ai-context.md`
- `draft.tmp/.ai-profile.md`
**Finalizer B — State Files:**
Write all `.state/` artifacts from the concatenated IRs:
- `draft.tmp/.state/facts.json` — extract atomic facts from IR fields (key_classes, invariants, state, error_handling)
- `draft.tmp/.state/freshness.json` — compute hashes of all source files read (baseline for incremental refresh)
- `draft.tmp/.state/signals.json` — derive signal classification from IR module roles and graph data
- `draft.tmp/.state/run-memory.json` — set `status: "completed"`, record phase timings
Finalizers A and B have no dependency on each other — run truly in parallel.
#### Phase 4: Quality Gate
After both finalizers complete, run the Completion Verification (defined later in this skill) against the standard hard minimum thresholds. If any metric fails:
1. Identify the sparse sections (most likely cross-cutting sections: §14 Integration, §16 Security, §8 Concurrency)
2. Request the synthesis agent to expand those sections, providing the relevant IR fields as targeted input
3. Only proceed to atomic rename (`mv draft.tmp/ draft/`) after all metrics pass
#### Failure Recovery
If any reader agent fails to produce valid JSON after one retry:
- Log which modules failed: `draft.tmp/.state/failed-readers.json`
- Run those modules through the standard sequential analysis (Phase 3 in the Large Codebase Protocol below)
- Merge the resulting content into the IR set before synthesis
- The other readers' IRs remain valid — only the failed group needs re-work
---
### Sequential Fallback (when parallel IR pipeline unavailable)
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.
1. Use the ranked module list from Step 1.4.6 (graph-first — do not re-scan by directory if Phase 0 succeeded).
2. For each top module (up to 20 by fan-in), query the engine for its symbols/callers (`"$DRAFT_TOOLS/graph-callers.sh"`, `"$DRAFT_TOOLS/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.
3. Always include §9 Graph Coverage Gaps and §10 Relationship when the Context Audit requires them.
4. Run Completion Verification (defined later in this skill) before condensation. Fidelity, provenance, and gap honesty block completion — not line counts.
---
### Execution Strategy for Depth
**Mindset**: You are creating a PERMANENT reference document. Future AI agents and engineers will use this instead of reading source code. Incomplete analysis means they'll make mistakes.
**File Reading Strategy**:
1. **Read broadly first** (Phase 1-2): Map the entire codebase structure
2. **Read deeply second** (Phase 3-4): For each major module, read the FULL implementation
3. **Cross-reference** (Phase 5): Verify every component appears in all relevant sections
**Diagram Generation Strategy**:
1. **Generate diagrams AFTER understanding** — not during exploration
2. **Use proper Mermaid syntax** — validate mentally before writing
3. **One diagram per concept** — don't combine unrelated flows
4. **Annotate arrows** — show what data moves between nodes
**Iteration Guidance**:
- After initial generation, review each HIGH-priority section
- If any section is thin (< 1 page for HIGH priority), expand it
- If any required diagram is missing, add it
- If tables have < 5 rows, verify you've enumerated exhaustively
---
### Adaptive Sections
Not every codebase has every concept. Apply these rules:
| If the codebase... | Then... |
|---------------------|---------|
| Has no plugin / algorithm / handler system | Skip Section 9 (Framework & Extension Points) and Section 10 (Full Catalog) |
| Has no V1/V2 generational split | Skip Section 11 (Secondary Subsystem) |
| Has no RPC / proto / API definitions | Skip Section 12, or retitle to "API Definitions" and cover REST / GraphQL / OpenAPI |
| Is a library (no binary / process) | Adapt Section 4.2 (Process Lifecycle) to "Usage Lifecycle" — how consumers integrate it |
| Is a frontend / UI module | Add: Component hierarchy, route map, state management, styling system |
| Uses a database directly | Add to Section 19: schema definitions, migration system, ORM models |
| Is containerized / has infra config | Add: Dockerfile, Kubernetes manifests, Helm charts, Terraform, CI/CD pipeline |
| Is a single-threaded / simple module | Simplify Section 8 (Concurrency) to note "single-threaded" and skip detailed thread maps |
| Has no configuration flags | Adapt Section 22 to cover whatever config mechanism exists (env vars, YAML, JSON, TOML, .env) |
---
### Language-Specific Exploration Guide
#### C / C++
| What to Find | Where to Look |
|-------------|--------------|
| Build targets & deps | `BUILD`, `CMakeLists.txt`, `Makefile` |
| Entry point | `main()` in `*_exec.cc`, `main.cc`, `*_main.cc` |
| Interfaces | `.h` header files (class declarations, virtual methods) |
| Implementation | `.cc` / `.cpp` files |
| API definitions | `.proto` files (protobuf), `.thrift` files |
| Config / flags | gflags: `DEFINE_*` macros in `flags.cc` / `flags.h` |
| Tests | `*_test.cc`, `*_unittest.cc`, files in `test/` or `qa/` dirs |
#### Go
| What to Find | Where to Look |
|-------------|--------------|
| Build targets & deps | `go.mod`, `go.sum`, `BUILD` (if Bazel) |
| Entry point | `func main()` in `main.go` or `cmd/*/main.go` |
| Interfaces | `type XxxInterface interface` in `*.go` files |
| Implementation | `*.go` files (non-test) |
| API definitions | `.proto` files, or handler registrations in router setup |
| Config / flags | `flag.*`, Viper config, environment variables |
| Tests | `*_test.go` files |
#### Python
| What to Find | Where to Look |
|-------------|--------------|
| Build targets & deps | `requirements.txt`, `pyproject.toml`, `setup.py`, `setup.cfg`, `Pipfile` |
| Entry point | `if __name__ == "__main__"` blocks, `app.py`, `main.py`, CLI entry points in pyproject.toml |
| Interfaces | Abstract base classes (`ABC`), Protocol classes, type hints |
| Implementation | `.py` files |
| API definitions | FastAPI/Flask route decorators, OpenAPI spec, `.proto` files |
| Config / flags | `settings.py`, `.env`, `config.yaml`, `argparse`, Pydantic Settings |
| Tests | `test_*.py`, `*_test.py`, files in `tests/` dirs |
#### TypeScript / JavaScript
| What to Find | Where to Look |
|-------------|--------------|
| Build targets & deps | `package.json`, `tsconfig.json`, `yarn.lock` / `package-lock.json` |
| Entry point | `"main"` in package.json, `index.ts`, `app.ts`, `server.ts` |
| Interfaces | TypeScript `interface` / `type` definitions in `*.ts` / `*.d.ts` |
| Implementation | `*.ts` / `*.js` files |
| API definitions | Route files, OpenAPI spec, GraphQL `.graphql` / `.gql` files |
| Config / flags | `.env`, `config.ts`, environment variables, `process.env.*` |
| Tests | `*.test.ts`, `*.spec.ts`, files in `__tests__/` dirs |
#### Java / Kotlin
| What to Find | Where to Look |
|-------------|--------------|
| Build targets & deps | `pom.xml` (Maven), `build.gradle` / `build.gradle.kts` (Gradle), `BUILD` (Bazel) |
| Entry point | `public static void main(String[] args)`, Spring Boot `@SpringBootApplication` |
| Interfaces | Java `interface` declarations, abstract classes |
| Implementation | `*.java` / `*.kt` files in `src/main/` |
| API definitions | `@RestController` / `@RequestMapping` annotations, `.proto` files, OpenAPI |
| Config / flags | `application.yml` / `application.properties`, Spring `@Value`, env vars |
| Tests | `*Test.java`, `*Spec.kt`, files in `src/test/` |
#### Rust
| What to Find | Where to Look |
|-------------|--------------|
| Build targets & deps | `Cargo.toml`, `Cargo.lock` |
| Entry point | `fn main()` in `src/main.rs` or `src/bin/*.rs` |
| Interfaces | `trait` definitions |
| Implementation | `*.rs` files |
| API definitions | Handler registrations (Actix/Axum routes), `.proto` files |
| Config / flags | `clap` structs, `config` crate, `.env`, `config.toml` |
| Tests | `#[test]` functions, `tests/` directory, `#[cfg(test)]` modules |
---
### Analysis Strategy — How to Explore the Codebase
Follow these steps in order. The specific files to look for depend on the language — use the Language-Specific Exploration Guide above.
#### Phase 1: Discovery (Broad Scan)
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.)
2. **Read build / dependency files**: These reveal the module structure, dependencies, and targets. (See language guide above for which files.)
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.)
4. **Read interface / type definition files**: Class declarations, interface definitions, and type annotations reveal the public API and design intent.
5. **Classify codebase signals**: Walk the file tree from step 1 and tag every file that matches one or more signal categories. This drives adaptive section depth in later phases — sections with strong signals get deep treatment, sections with no signals get marked SKIP. (If Step 1.4 succeeded, use module file counts and dependency edges to accelerate signal classification.)
| Signal Category | Detection Patterns | Drives Section(s) |
|----------------|-------------------|-------------------|
| `backend_routes` | `routes/`, `handlers/`, `controllers/`, `**/api/**`, route decorators (`@app.route`, `@router`, `@RequestMapping`) | §12 API Definitions, §14 Cross-Module Integration |
| `frontend_routes` | `pages/`, `views/`, `**/routes.*`, `**/router.*`, React Router, Next.js `app/` dir | §4 Architecture (add UI topology) |
| `components` | `components/`, `widgets/`, `*.component.ts`, `*.tsx` in component dirs | §7 Core Modules (add component hierarchy) |
| `services` | `services/`, `*Service.*`, `*_service.*`, `**/service/**` | §5 Component Map, §7 Core Modules |
| `data_models` | `models/`, `entities/`, `schemas/`, `*.model.*`, `*.entity.*`, `migrations/` | §19 State Management, §12 API Definitions |
| `auth_files` | `auth/`, `**/auth/**`, `middleware/auth*`, `guards/`, JWT/OAuth imports | §16 Security Architecture |
| `state_management` | `store/`, `reducers/`, `**/state/**`, Redux/Vuex/Zustand/Pinia imports | §19 State Management (frontend state) |
| `background_jobs` | `jobs/`, `workers/`, `tasks/`, `queues/`, `**/cron/**`, Celery/Sidekiq/Bull imports | §8 Concurrency, §22 Configuration |
| `persistence` | `repositories/`, `dao/`, `**/db/**`, ORM config files, migration directories | §19 State Management |
| `test_infra` | `test/`, `tests/`, `__tests__/`, `*.test.*`, `*.spec.*`, test config files | §26 Testing Infrastructure |
| `config_files` | `.env*`, `config/`, `*.config.*`, `application.yml`, `settings.*` | §22 Configuration |
**Procedure:**
```bash
# Count files ma
[…] pełny plik w paczce .zip
Files in this package (3)
- SKILL.md 96 KB
- references/architecture-spec.md 58 KB
- references/okf-emitter.md 14 KB
Versions
| Repository | Score | Licence |
|---|---|---|
| This page · drafthq/draft | 91 | MIT |
| CodaColaLight/nightmill | 100 | Apache-2.0 |
| userKael/rastro | 100 | MIT |
| elalfner/relevo | 100 | MIT |
| abatyuk/okf | 100 | MIT |
| duronext/jig | 100 | MIT |
| sh5623/e2e-rail | 100 | MIT |
| Calvin-LLC/skills | 100 | MIT |
| arxdsilva/ai-loops | 100 | MIT |
Database snapshot: 13.11.2026 · package version f01a6f9d182f (SHA-256 digest of the entire package)
Downloads in the last 30 days: 0 · ranking
Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.
Similar skills
- 100docs-init
Bootstrap agent-ready project documentation in docs/ plus an AGENTS.md entry point, tailored to the project type (backend, frontend, fullstack, mobile). Focuses on flows and conventions an AI agent needs before changing code. Marks anything that cannot be derived from code and… - 90adev:init
Initialize or diagnose the .context-index/ directory. Interactive wizard that explains each layer, detects existing setup, and lets users opt in or skip per layer. Use --brownfield for existing codebases, --dry-run to preview without writing. Trigger when the user wants to set… - 95dev-init
This skill should be used when the user asks to "dev-init", "技術スタックを選定", "新規プロジェクト初期化", "initialize tech stack", "プロジェクトをセットアップ", "setup project", "scaffold project", "プロジェクト作成", "tech stackを決める". インタラクティブなヒアリングでプロジェクトの技術スタックを決定し、dev-context互換のコンテキストファイルを生成する。承認制でプロジェクトスキャフォールディングも実行可能。 - 100pm-init
Initialize or refresh Project Memory for a repository. Use after amplifying a new repo, when the user says "init PM", "set up project memory", or when pm-index.md is missing or empty. Surveys the codebase, creates starter PM units, and populates the index. - 100context-driven-development
Creates and maintains project context artifacts (product.md, tech-stack.md, workflow.md, tracks.md) in a `conductor/` directory. Scaffolds new projects from scratch, extracts context from existing codebases, validates artifact consistency before implementation, and synchronizes… - 100ctx-init
Initialize AGENTS.md + CLAUDE.md + rules/ in a code repo (fresh mode). Triggers on "/ctx-init", "init context", "scaffold AGENTS.md", or when user asks to set up project context in a new repo.