const e=`### Orchestrator Dispatch Protocol

Follow \`multi-agents-development\` dispatch patterns:

1. **Independence Check**:
   - Same files, shared mutable state, or order dependency → sequential
   - Shared new types → define contract, then parallel
   - Otherwise → **parallel dispatch**

2. **Subagent Context**:
   - **Scope**: exact files + do NOT touch boundary
   - **Goal**: testable acceptance criteria
   - **Arch Context**: code via \`compact()\`/\`digest()\` or a cached ref via \`compact({ ref, query? })\`
   - **Constraints**: patterns, conventions, anti-patterns
   - **Self-Review**: checklist before DONE

3. **Status**: \`DONE\` | \`DONE_WITH_CONCERNS\` | \`NEEDS_CONTEXT\` | \`BLOCKED\`
4. **Max 2 retries** per task → escalate`,t=`### FORGE Quality Gate

After reviews complete:
1. \`evidence_map({ action: "gate", task_id: "<slug>" })\` → YIELD/HOLD/HARD_BLOCK
2. YIELD → approved, proceed
3. HOLD → fix, re-gate (max 3 rounds)
4. HARD_BLOCK → escalate`;function n(e,t=``,n=``){return`## Foundation Integration

Load these skills BEFORE executing this step:

| Skill | Purpose | When |
|-------|---------|------|
| \`aikit\` | Core MCP tools — search, analyze, ${e}, validate | Always |
| \`present\` | Rich rendering for structured output | Any output that benefits from rich rendering |
| \`multi-agents-development\` | Dispatch templates, task decomposition, review patterns | Before dispatching any subagent |
| \`brainstorming\` | Structured ideation for design decisions | Before design choice or feature exploration |${t?`\n${t}`:``}

### Presentation Rules
- Use \`present\` for any output that benefits from rich rendering
- Assessments, reports, comparisons, reviews, status boards, tables, charts, progress, findings → \`present({ schemaVersion: 1, title: "Assessment", blocks: [...] })\`
- Use \`table\` for comparisons/findings, \`kv\` for status/summary, \`list\` for findings/tasks, \`metrics\` for numeric health, \`checklist\` for task status, \`markdown\` for prose
- NEVER use \`code\` blocks for structured data
- Plain text only for brief confirmations and simple questions${n?`\n\n${n}`:``}`}const r=e=>`## Knowledge Capture

Before completing this step, persist important findings with \`knowledge({ action: "remember", ... })\`:

${e}

If this step produced reusable knowledge, store it now.`,i={_epilogue:[{file:`steps/docs-sync/README.md`,content:`# Epilogue: Documentation Sync

> **This is a mandatory epilogue step.** Runs after every flow to keep project documentation synced with code changes.

## Objective

Review flow changes and update \`docs/\` with AI Kit analysis tools. Never write docs from scratch when a tool can generate the base.

## Prerequisites

Load the \`docs\` skill before proceeding.

## Instructions

### 0. Gather Flow Artifacts

Read all flow artifacts.

\`\`\`
flow({ action: 'status' })                             # Get artifactsPath
find({ glob: "{{artifacts_path}}/**/*.md" })         # Discover all flow artifacts
digest({ sources: [                                     # Compress artifacts for context
  { path: "<found-artifact-1>" },
  { path: "<found-artifact-2>" },
  ...
]})
\`\`\`

Map each artifact to doc actions with the \`docs\` skill mapping. Focus on decisions, requirements, and verification.

If no artifacts exist, proceed to Step 1 in source-only mode.

### 1. Assess Changes (tool-driven)

\`\`\`
git_context({})                                         # What changed in this flow
blast_radius({ path: ".", files: ["<changed-files>"] }) # Impact analysis — which modules affected
\`\`\`

Classify changes from tool output:

| Change Signal | Documentation Action |
|---------------|---------------------|
| New files in \`src/\` | Potential new component doc |
| Modified API surface | Update reference docs |
| New package or module boundary | Update architecture overview |
| Architecture decision made | Delegate to \`adr-skill\` |
| Test-only or config-only changes | Likely skip |

### 2. Apply the Change-to-Doc Mapping

Follow the \`docs\` skill decision tree.

### 3. Bootstrap \`docs/\` If Needed (full tool-driven workflow)

If \`docs/\` doesn't exist, run the **Architecture Blueprint Workflow** from the \`docs\` skill:

\`\`\`
# Step 1: Generate content with AI Kit tools
produce_knowledge({ scope: "." })                       # → Foundation for docs/README.md
analyze({ aspect: "structure", path: "." })             # → docs/architecture/overview.md structure
analyze({ aspect: "diagram", path: "." })               # → docs/architecture/ Mermaid diagrams
analyze({ aspect: "dependencies", path: "." })          # → docs/architecture/overview.md deps section
analyze({ aspect: "entry_points", path: "." })          # → docs/reference/api.md foundation
analyze({ aspect: "patterns", path: "." })              # → docs/architecture/overview.md patterns

# Step 2: Create the docs/ tree from tool outputs
docs/
├── README.md              ← From produce_knowledge + project context
├── architecture/
│   ├── overview.md        ← From analyze(structure|dependencies|diagram)
│   └── components/        ← From analyze(symbols) per major component
├── decisions/
│   └── index.md           ← ADR log (delegate to adr-skill)
├── guides/
│   └── testing.md         ← From analyze(patterns) test info
└── reference/
   └── api.md             ← From analyze(entry_points)
\`\`\`

Use the \`docs\` skill Architecture Blueprint sections as the template.

### 4. Update Existing Docs (tool-assisted)

When \`docs/\` already exists:

\`\`\`
compact({ path: "docs/architecture/overview.md", query: "section to update" })  # Read target section
blast_radius({ path: ".", files: ["<files>"] })                                # What's affected
\`\`\`

- **Don't rewrite** — update relevant sections only
- **Don't duplicate** — reference code comments or READMEs when they already contain it
- Use \`compact\` to read existing doc sections before editing
- Use \`blast_radius\` output to determine which sections need updating

### 5. Delegate When Appropriate

- Architecture decisions → \`adr-skill\` → \`docs/decisions/\`
- Architecture diagrams → \`c4-architecture\` skill → \`docs/architecture/\`
- Full architecture refresh → run the \`docs\` skill Architecture Blueprint Workflow

### 6. Update Index

If docs were added, removed, or renamed, update \`docs/README.md\`.

### 6b. Update HTML Documentation Site (if exists)

If \`docs/site/\` exists with a manifest:

1. **Detect staleness** — compare source changes from \`git_context\` against manifest page data
2. **Identify affected pages** — use \`blast_radius\` to find pages whose source data changed
3. **Regenerate affected pages only** — update manifest JSON with fresh data for changed pages
4. **Rebuild** — Run \`inject-viewer.mjs --manifest\` with the updated manifest
5. **Regenerate hub** — If pages were added or removed, regenerate the docs-hub page

If \`docs/site/\` doesn't exist but the flow produced architecture diagrams or process flows, suggest \`/docs-site\`.

### 7. Skip If Nothing Changed

If changes don't warrant doc updates, report:
- "No documentation updates needed"
- Reason: (brief explanation)

## Completion Criteria

- [ ] \`git_context\` + \`blast_radius\` used to assess changes
- [ ] Change-to-doc mapping applied from \`docs\` skill
- [ ] \`docs/\` bootstrapped with tool outputs if it didn't exist
- [ ] \`docs/site/\` checked for staleness if it exists
- [ ] Stale HTML pages regenerated from fresh analysis data
- [ ] Relevant docs created or updated (or skipped with reason)
- [ ] \`docs/README.md\` index is current
- [ ] No placeholder/empty docs created — all content tool-generated or written with purpose`},{file:`steps/lesson-learned/README.md`,content:`---
name: _lesson-learned
description: Extract engineering principles from the completed flow
skills: [lesson-learned]
---

# Epilogue: Lesson Learned

## Condition Check (MUST evaluate first)

Before extracting lessons, check whether this flow produced learnable outcomes:

**Skip this step (advance with 'skip') when ALL are true:**
- Flow was Floor-tier (trivial change)
- blast_radius ≤ 2 for all changes
- Flow completed in a single batch with no iteration
- No agent returned BLOCKED or DONE_WITH_CONCERNS
- evidence_map never reached HOLD state

**Proceed when ANY are true:**
- An agent returned BLOCKED or DONE_WITH_CONCERNS during the flow
- evidence_map had HOLD before reaching YIELD (required iteration to pass)
- Multi-model decision protocol was invoked
- blast_radius > 5 (complex change with systemic implications)
- A novel pattern or anti-pattern was discovered
- A debugging session revealed non-obvious root cause

If skip condition is met → \`flow({ action: 'step', advance: 'skip' })\` with note: "No lesson signals detected."

## Extraction Protocol

1. **Load the \`lesson-learned\` skill**
2. Run \`git_context({ include_diff: true, commit_count: 10 })\`
3. Review flow artifacts in \`{{artifacts_path}}\`
4. Extract 1-3 principles using the skill's framework:
   - What went wrong → What we learned → What we'll do differently
   - OR: What went right → Why it worked → How to replicate
5. Store each principle: \`knowledge({ action: "remember", title: "Lesson: <principle>", content: "<context + evidence>", category: "patterns" })\`

## Quality Bar

A good lesson:
- Is **generalizable** (applies beyond this task)
- Has **evidence** (references files, errors, or decisions)
- Is **actionable** (tells future agents what to do or avoid)

Skip lessons that:
- Restate what was done without insight
- Is too specific to reuse ("file X had a typo on line 42")
- Captures a convention already documented elsewhere
`}],"aikit-advanced":[{file:`README.md`,content:`# aikit:advanced — Full Development Flow

Full development flow for **new features, API design, and architecture changes**.

## Steps

| # | Step | Skill | Produces | Requires | Agents |
|---|------|-------|----------|----------|--------|
| 1 | **Design Gate** | \`steps/design/README.md\` | \`design-decisions.md\` | — | Researcher-Alpha/Beta/Gamma/Delta |
| 2 | **Specification** | \`steps/spec/README.md\` | \`spec.md\` | \`design-decisions.md\` | Researcher-Alpha |
| 3 | **Planning** | \`steps/plan/README.md\` | \`plan.md\` | \`spec.md\` | Planner, Explorer |
| 4 | **Task Breakdown** | \`steps/task/README.md\` | \`tasks.md\` | \`plan.md\` | Planner, Architect-Reviewer-Alpha |
| 5 | **Execution** | \`steps/execute/README.md\` | \`progress.md\` | \`tasks.md\` | Orchestrator, Implementer, Frontend, Refactor |
| 6 | **Verification** | \`steps/verify/README.md\` | \`verify-report.md\` | \`progress.md\` | Code-Reviewer-Alpha/Beta, Architect-Reviewer-Alpha/Beta, Security |

## How It Works

Each step has a **README.md**. Orchestrator reads it via \`flow({ action: 'read' })\` and delegates work.

### Step 1: Design Gate
- Brainstorming for new features and arch changes
- FORGE classification + grounding for complex tasks
- 3-phase decision protocol for non-trivial technical decisions
- ADRs for critical-tier tasks
- **Mandatory user stop** before proceeding — design decisions must be approved
- Read \`steps/design/README.md\` for the full protocol

### Step 2: Specification
- Elicit requirements, clarify scope
- Define acceptance criteria and constraints
- Build on design decisions

### Step 3: Planning
- Analyze codebase with \`search\`, \`scope_map\`, \`trace\`, \`analyze_*\`
- Design architecture from spec and design decisions
- Create implementation plan with file-level changes

### Step 4: Task Breakdown
- Break plan into ordered, atomic tasks
- Define task deps
- Identify parallel batches
- Review task structure

### Step 5: Execution
- Orchestrator dispatches agents in parallel batches per the task breakdown
- Each agent gets a scoped task (1-3 files) with clear acceptance criteria
- TDD: write tests first, then implement
- Per-batch review cycle: Code Review → Arch Review → Security → Evidence Gate

### Step 6: Verification
- Dual code review (Code-Reviewer-Alpha + Beta)
- Architecture review (Architect-Reviewer-Alpha + Beta)
- Security review
- Run \`check({})\` + \`test_run({})\` + \`blast_radius({})\`
- \`evidence_map({ action: "gate" })\` for final quality gate

## Using Skills Inside Steps

When the Orchestrator activates a step:

1. **Read the instruction first** — \`flow({ action: 'read' })\` returns the current step README.md
2. **Follow step instructions** — primary guide
3. **Delegate to listed agents** — each step lists which agents are appropriate
4. **Produce the required artifact** — the step's \`produces\` field specifies the artifact file
5. **Check dependencies** — required prior artifacts must exist
6. **Report status** — agents report \`DONE\` | \`DONE_WITH_CONCERNS\` | \`NEEDS_CONTEXT\` | \`BLOCKED\` to the Orchestrator

## Artifacts

Artifacts are stored under \`.flows/{topic}/\`. \`{{artifacts_path}}\` resolves at runtime.
`},{file:`steps/design/README.md`,content:`# Design Gate — Advanced Flow

Full design gate for new features, API design, and architecture changes. Runs brainstorming, decision protocol, and FORGE classification before specification begins.

## When This Step Runs

First step of \`aikit:advanced\`. Runs before specification.

## Instructions

### 1. Task Classification

Classify the task:

| Category | Indicators | Action |
|----------|-----------|--------|
| **Bug fix** | Error, regression, "fix" — wrong flow, should use \`aikit:basic\` | → Note mismatch, still run Quick Design |
| **New feature** | New behavior, new API, new component | → Run **Full Design** below |
| **Architecture change** | Restructure, migration, new pattern, cross-cutting | → Run **Full Design** with architecture focus |

### 2. FORGE Classification

Run \`forge_classify({ task: "<task description>", files: [<relevant files>], root_path: "." })\` to determine tier.

| Tier | Meaning | Design Depth |
|------|---------|-------------|
| **Floor** | Low risk, well-understood | Quick brainstorm, 1-2 decisions |
| **Standard** | Moderate complexity | Full brainstorm, parallel research, decision protocol |
| **Critical** | High risk, contract/security implications | Deep brainstorm, 4-researcher parallel review, ADR required |

### 3. Brainstorming Session

Load \`brainstorming\` and run:

1. **Intent Discovery** — What is the user trying to achieve? What problem does this solve?
2. **Constraint Mapping** — Technical, time, compatibility constraints
3. **Approach Exploration** — Generate 2-4 possible approaches
4. **Trade-off Analysis** — Compare approaches on: complexity, maintainability, performance, risk

For **Critical** tier tasks, also explore:
- Security implications
- Backward compatibility
- Migration path
- Rollback strategy

### 4. Decision Protocol (Standard & Critical tiers)

When technical decisions need resolution, follow the **3-phase multi-model decision protocol**:

1. **Identify decisions** — list each decision point with 2+ viable options
2. **Phase 1 — Independent Research** — Launch ALL 4 Researcher variants in parallel:
   - Researcher-Alpha (Contrarian): Deep analysis, actively seeks fatal flaws
   - Researcher-Beta (First Principles): Trade-offs and edge cases, strips assumptions
   - Researcher-Gamma (Expansionist): Cross-domain patterns, undervalued opportunities
   - Researcher-Delta (Executor): Feasibility, performance, fastest implementation path
3. **Phase 2 — Peer Review** — anonymize outputs as Perspective A/B/C/D, launch 4 reviewers in parallel asking: strongest argument, biggest blind spot, consensus gap, verdict
4. **Phase 3 — Structured Verdict** — synthesize into: Where Agrees / Where Clashes / Blind Spots Caught / Recommendation (with confidence) / First Step
5. **Present & Record** — Render verdict with \`present({ schemaVersion: 1, title: "Decision Verdict", blocks: [...] })\`; use \`table\` for multi-perspective comparisons, \`list\` for blind spots/recommendations, and \`kv\` for verdict metadata. NEVER \`code\` blocks for structured data. Produce ADR via \`adr-skill\`

**Floor tier shortcut**: Skip Phase 2 (peer review), go straight from research to verdict.

### 5. FORGE Ground (Standard & Critical tiers)

Run \`forge_ground({ task, files: [<relevant files>], root_path: "." })\` to:
- Scope affected files and modules
- Identify unknowns and risks
- Load existing constraints and conventions

**Auto-upgrade check**: If \`forge_ground\` reveals contract-type unknowns or security concerns missed by \`forge_classify\`, recommend a tier upgrade.

### 6. Write \`{{artifacts_path}}/design-decisions.md\` to disk

**You MUST create this file on disk** using the IDE's native file creation capability or equivalent — do not only present content in chat.

\`\`\`markdown
## Design Decisions

### FORGE Assessment
- **Tier**: {Floor | Standard | Critical}
- **Rationale**: {why this tier}
- **Auto-upgrade**: {yes/no — if yes, explain}

### Task Summary
- **Goal**: {what we're building}
- **Problem**: {what problem this solves}
- **Users affected**: {who is impacted}

### Approach
- **Chosen approach**: {description}
- **Alternatives considered**: {list with reasons for rejection}

### Key Decisions
| # | Decision | Choice | Rationale |
|---|----------|--------|-----------|
| 1 | {decision} | {choice} | {why} |

### Constraints
- {constraint 1}
- {constraint 2}

### Risks
| Risk | Likelihood | Impact | Mitigation |
|------|-----------|--------|------------|
| {risk} | {L/M/H} | {L/M/H} | {mitigation} |

### Open Questions
- {question 1}
- {question 2}
\`\`\`

### 7. Present to User

Use \`present({ schemaVersion: 1, title: "Design Review", blocks: [...] })\` to show:
- Design decisions summary
- FORGE tier and rationale
- Key trade-offs
- Open questions requiring user input

Use \`kv\` for FORGE tier/rationale, \`list\` for trade-offs/open questions, \`table\` for decision comparisons, \`markdown\` for narrative summary. NEVER \`code\` blocks for structured data. Add \`actions\` only for browser transport.

**🛑 MANDATORY STOP** — Wait for user approval of design decisions before proceeding.

### 8. Report to Orchestrator

After user approves:
- \`DONE\` — design decisions approved, ready for specification
- \`DONE_WITH_CONCERNS\` — approved with caveats (list them)
- \`NEEDS_CONTEXT\` — user raised questions that need more research

**Do NOT call \`flow({ action: 'step', advance: 'next' })\`** — let the Orchestrator advance the flow.

## Outputs

Write \`{{artifacts_path}}/design-decisions.md\` to disk. **You MUST create this file** using the IDE's native file creation capability or equivalent — do not only present content in chat.

## Produces

- \`{{artifacts_path}}/design-decisions.md\` — FORGE tier, approach, key decisions, constraints, risks

## Agents

- \`Researcher-Alpha\` — Primary approach
- \`Researcher-Beta\` — Trade-offs
- \`Researcher-Gamma\` — Cross-domain patterns
- \`Researcher-Delta\` — Feasibility

${n(`knowledge`,"| `c4-architecture` | C4 diagrams for system structure changes | When visualizing architecture |\n| `adr-skill` | ADRs for non-trivial decisions | Critical tier — document architecture decisions |")}

## Completion Criteria

- [ ] \`{{artifacts_path}}/design-decisions.md\` written to disk (NOT just presented in chat)
- [ ] FORGE tier determined and documented
- [ ] Brainstorming completed (for Standard+ tier)
- [ ] Key design decisions documented with rationale
- [ ] User approval received (🛑 MANDATORY STOP)

${r(`- **Design decisions**: Chosen approach and rejected alternatives
- **Architecture patterns**: New patterns or patterns that must be followed
- **Constraints discovered**: Technical, compatibility, performance limits`)}
`},{file:`steps/execute/README.md`,content:`---
name: execute
description: Implement tasks from the task breakdown, dispatching agents in parallel where possible.
---

# Execution

## Prerequisites Check

Before starting this step, verify:
- [ ] Task breakdown approved with valid task graph
- [ ] \`{{artifacts_path}}/tasks.md\` exists with defined batches and dependencies

If prerequisites are NOT met -> **backtrack to task step** (\`flow({ action: 'step', advance: 'redo' })\` on previous step)

## Purpose

Execute tasks from the breakdown in batches, maximizing parallelism without losing correctness.

## Inputs

- \`{{artifacts_path}}/tasks.md\` — task list with deps and agents

## Process

1. **Load tasks** — read task graph, deps, parallelism map
2. **Execute by batch** — For each batch in the parallelism map:
   a. Dispatch assigned agents in parallel (different files = safe parallelism)
   b. Each agent receives: task scope, affected files, acceptance criteria, code context via \`compact()\`/\`digest()\`
   c. Wait for all agents in batch to complete
   d. Run \`check({})\` + \`test_run({})\` after each batch
   e. Fix any failures before proceeding to next batch
3. **Track progress** — update task checkboxes
4. **Handle failures** — If an agent reports \`BLOCKED\` or \`NEEDS_CONTEXT\`:
   - Max 2 retries per task with refined context
   - If still blocked, escalate to user
5. **Final validation** — after all batches: \`check({})\` + \`test_run({})\` must pass

## DAG Task Decomposition

For multi-task implementations, use the queue with dependencies:

\`\`\`
queue({ action: 'create', name: 'execute-tasks' })
queue({ action: 'push', name: 'execute-tasks', title: 'Task A', id: 'a' })
queue({ action: 'push', name: 'execute-tasks', title: 'Task B', id: 'b', dependsOn: ['a'] })
\`\`\`

Tasks with \`dependsOn\` stay blocked until deps complete. This preserves execution order.

## Outputs

Write \`{{artifacts_path}}/progress.md\` to disk. **You MUST create this file** using the IDE's native file creation capability or equivalent — do not only present content in chat.

Template:

\`\`\`markdown
# Execution Progress: <feature title>

## Task Status
- [x] T1.1: <description> — DONE
- [x] T1.2: <description> — DONE
- [x] T2.1: <description> — DONE
- [ ] T2.2: <description> — IN PROGRESS
...

## Changes Made
| File | Change | Task |
|------|--------|------|
| <file> | <description> | T1.1 |
| ... | ... | ... |

## Tests Added/Modified
<list of test files and what they cover>

## Validation
- check: PASS/FAIL
- test_run: PASS/FAIL (<N> passed, <M> failed)

## Deviations
<any changes from the task plan and why>

## Blocked Items
<items that needed user intervention, if any>
\`\`\`

## Agents

| Agent | Role |
|-------|------|
| **Orchestrator** | Batches, failures, retries |
| **Implementer** | Backend, logic, infra |
| **Frontend** | React, styling, responsive |
| **Refactor** | Cleanup, restructuring |

**Parallelism rules**:
- Read-only agents: unlimited parallelism
- File-modifying agents: parallel ONLY on different files
- Max 4 concurrent file-modifying agents

${n(`knowledge`,"| `session-handoff` | Context preservation for long-running execution | When execution spans sessions or context is filling |",e)}

## Completion Criteria

- [ ] All tasks marked completed
- [ ] \`check({})\` passes
- [ ] \`test_run({})\` passes
- [ ] No blocked items remaining
- [ ] \`{{artifacts_path}}/progress.md\` written

${r(`- **Implementation decisions**: Why specific approaches were chosen
- **Patterns established**: New conventions or patterns to follow
- **Gotchas encountered**: Edge cases, workarounds, non-obvious behaviors`)}
`},{file:`steps/plan/README.md`,content:`---
name: plan
description: Analyze the codebase, design the architecture, and create an implementation plan.
---

# Planning

## Prerequisites Check

Before starting this step, verify:
- [ ] Specification approved with clarity score ≥90
- [ ] \`{{artifacts_path}}/spec.md\` exists and is complete

If prerequisites are NOT met → **backtrack to spec step** (\`flow({ action: 'step', advance: 'redo' })\` on previous step)

## Purpose

Translate the spec into a phased implementation plan with architecture decisions, file scope, and dependency order.

## Inputs

- \`{{artifacts_path}}/spec.md\` — validated spec

## Requirements Alignment

Before implementation, verify alignment with requirements:
- Read \`{{artifacts_path}}/requirements.md\` if it exists
- Ensure all acceptance criteria from requirements are covered by the plan
- Flag any requirement that cannot be met and explain why

## Process

1. **Load spec** — read requirements and acceptance criteria
2. **Codebase analysis** — \`scope_map({ task: "<feature>" })\` to identify affected subsystems
3. **Deep dive** — \`file_summary()\` + \`compact()\` on each affected module
4. **Architecture design** — Decide on:
   - Where new code lives (new files vs extensions)
   - API surface changes
   - Data model changes
   - Integration patterns
5. **ADR for non-trivial decisions** — use \`adr-skill\` for decisions that affect future development
6. **Phase decomposition** — break work into 3–10 ordered phases, each independently testable
7. **Dependency graph** — map which phases depend on others and which can parallelize
8. **Risk assessment** — Identify implementation risks per phase

## Outputs

Write \`{{artifacts_path}}/plan.md\` to disk. **You MUST create this file** using the IDE's native file creation capability or equivalent — do not only present content in chat.

Template:

\`\`\`markdown
# Implementation Plan: <feature title>

## Architecture Overview
<high-level design with rationale>

## Affected Modules
| Module | Changes | Risk |
|--------|---------|------|
| <module> | <what changes> | low/medium/high |

## Phases
### Phase 1: <name>
- **Files**: <list>
- **Changes**: <description>
- **Tests**: <what to test>
- **Depends on**: none
- **Parallelizable with**: Phase 2

### Phase 2: <name>
...

## Architecture Decisions
- ADR-<N>: <title> — <chosen option and rationale>

## Risks
| Risk | Likelihood | Impact | Mitigation |
|------|-----------|--------|------------|
| <risk> | low/medium/high | <impact> | <mitigation> |
\`\`\`

## Agents

| Agent | Role |
|-------|------|
| **Planner** | TDD implementation plans |
| **Explorer** | Codebase exploration for files and deps |

**Dispatch via \`runSubagent\` — never \`switchAgent\`:**
1. \`runSubagent({ agent: "Explorer", ... })\` — initial breadth: file discovery, dependency tracing
2. \`runSubagent({ agent: "Planner", ... })\` — depth: phase design, ordering, plan artifact creation

The Planner agent (\`Planner.agent.md\`) owns the \`{{artifacts_path}}/plan.md\` artifact. Pass spec content, Explorer findings, and artifacts path as context.

${n(`knowledge`,"| `adr-skill` | ADRs for non-trivial technical decisions | When plan involves architecture choices that need documentation |\n| `c4-architecture` | C4 diagrams for system structure changes | When plan modifies system architecture |")}

## Completion Criteria

- [ ] All spec requirements have corresponding plan phases
- [ ] Each phase has explicit file scope and test strategy
- [ ] Architecture decisions documented with rationale
- [ ] Dependency graph has no circular dependencies
- [ ] Risks identified with mitigations
- [ ] \`{{artifacts_path}}/plan.md\` written

${r(`- **Task dependencies**: Ordering constraints and parallel opportunities
- **Risk assessment**: Risks and mitigations
- **Resource decisions**: File ownership, module boundaries, integration points`)}
`},{file:`steps/spec/README.md`,content:`---
name: spec
description: Elicit requirements, clarify scope, and define acceptance criteria through dialogue.
---

# Specification

## Prerequisites Check

Before starting this step, verify:
- [ ] Design decisions approved (design-decisions.md exists with user approval)
- [ ] FORGE tier assigned and documented

If prerequisites are NOT met -> **backtrack to design step** (\`flow({ action: 'step', advance: 'redo' })\` on previous step)

## Purpose

Transform a vague or broad feature request into a precise, testable specification.

## Inputs

- User's feature request, issue, or idea
- Codebase context (via aikit MCP tools)

### Input Artifacts

Read these from \`{{artifacts_path}}/\` before writing the spec:
1. \`requirements.md\` — Requirements clarity output (score, criteria, constraints). **If this file exists, the spec MUST address all listed requirements and acceptance criteria.**
2. \`design-decisions.md\` — Design decisions from the design step

If \`requirements.md\` is not found in artifacts, check flow-scoped knowledge:
\`\`\`
knowledge({ action: "withdraw", scope: "flow", profile: "implementer", budget: 4000 })
\`\`\`
Look for a "Requirements:" entry in withdrawn context.

## Process

1. **Understand intent** — parse what the user wants and why
2. **Search for context** — \`search()\` for related decisions, patterns, similar features
3. **Elicit requirements** — Ask structured questions to clarify:
   - **Functional**: What must the system do?
   - **Non-functional**: Performance, security, accessibility constraints
   - **Scope boundaries**: What is explicitly out of scope?
   - **Acceptance criteria**: How do we know it's done?
4. **Score clarity** — use the \`requirements-clarity\` skill to score 0–100. Iterate until ≥ 90.
5. **Draft specification** — write formal spec with all requirements resolved

## Requirements Clarity Gate (MANDATORY)

Before producing any spec.md or design document:

1. **Load the \`requirements-clarity\` skill**
2. **Score current requirements** using the skill's 0-100 rubric
3. **If score < 90:** Ask clarifying questions, iterate with user until ≥ 90
4. **If score ≥ 90:** Proceed to spec writing

**HARD RULE:** A spec.md produced without requirements-clarity score ≥ 90 is INVALID and will be rejected in review. The score MUST be documented in the spec header:

\`\`\`yaml
# In spec.md frontmatter or header:
Requirements Clarity Score: [score]/100
Scoring Date: [date]
Key Clarifications:
   - [question asked → answer received]
\`\`\`

This gate prevents designing for misunderstood problems.

## Outputs

Write \`{{artifacts_path}}/spec.md\` to disk. **You MUST create this file** using the IDE's native file creation capability or equivalent — do not only present content in chat.

Template:

\`\`\`markdown
# Specification: <feature title>

Requirements Clarity Score: <N>/100
Scoring Date: <YYYY-MM-DD>
Key Clarifications:
- <question asked -> answer received>

## Summary
<1-2 sentence description>

## Motivation
<why this feature is needed>

## Functional Requirements
1. <requirement with acceptance criterion>
2. ...

## Non-Functional Requirements
- Performance: <constraints>
- Security: <constraints>
- Accessibility: <constraints>

## Scope
### In Scope
- <item>

### Out of Scope
- <item>

## Acceptance Criteria
- [ ] <testable criterion>
- [ ] ...

## Open Questions
<none — all resolved during elicitation>
\`\`\`

## Agents

| Agent | Role |
|-------|------|
| **Researcher-Alpha** | Patterns, prior decisions, technical constraints |

Use \`brainstorming\` for creative/design exploration before formalizing requirements. Use \`requirements-clarity\` to score and iterate until the spec is unambiguous.

${n(`remember`,"| `requirements-clarity` | Score requirements 0-100, iterate until ≥90 | Before writing spec — ensures requirements are clear enough |")}

## Completion Criteria

- [ ] All functional requirements have acceptance criteria
- [ ] Scope boundaries are explicit
- [ ] Requirements clarity score ≥ 90
- [ ] No open questions remain
- [ ] \`{{artifacts_path}}/spec.md\` written

${r(`- **Requirements clarified**: Ambiguities resolved and assumptions validated
- **Scope boundaries**: What the spec covers and excludes
- **Acceptance criteria**: Key testable conditions that define "done"`)}
`},{file:`steps/task/README.md`,content:`---
name: task
description: Break the implementation plan into ordered, atomic tasks with deps and agent assignments.
---

# Task Breakdown

## Prerequisites Check

Before starting this step, verify:
- [ ] Implementation plan approved
- [ ] \`{{artifacts_path}}/plan.md\` exists with defined phases

If prerequisites are NOT met → **backtrack to plan step** (\`flow({ action: 'step', advance: 'redo' })\` on previous step)

## Purpose

Decompose the implementation plan into small, atomic tasks with clear dependency order and acceptance criteria.

## Inputs

- \`{{artifacts_path}}/plan.md\` — phased implementation plan

## Process

1. **Load plan** — read phases, file scope, dependency graph
2. **Decompose phases into tasks** — Each task should:
   - Touch 1–3 files maximum
   - Have a single, testable outcome
   - Fit one focused agent session
3. **Define dependencies** — Map task-to-task dependencies (not just phase-to-phase)
4. **Assign agents** — match each task to the best-fit agent
5. **Identify parallelism** — Mark which tasks can run simultaneously
6. **Architecture review** — have Architect-Reviewer validate task ordering won't create integration issues

## Outputs

Write \`{{artifacts_path}}/tasks.md\` to disk. **You MUST create this file** using the IDE's native file creation capability or equivalent — do not only present content in chat.

Template:

\`\`\`markdown
# Task Breakdown: <feature title>

## Task Graph

### Phase 1: <name>
- [ ] **T1.1**: <description>
  - Files: <list>
  - Agent: <agent name>
  - Depends on: none
  - Acceptance: <testable criterion>

- [ ] **T1.2**: <description>
  - Files: <list>
  - Agent: <agent name>
  - Depends on: T1.1
  - Acceptance: <testable criterion>

### Phase 2: <name>
- [ ] **T2.1**: <description> (can parallel with T1.2)
  ...

## Parallelism Map
| Batch | Tasks | Agents |
|-------|-------|--------|
| 1 | T1.1 | Implementer |
| 2 | T1.2, T2.1 | Implementer, Frontend |
| 3 | T2.2 | Implementer |
| ... | ... | ... |

## Estimated Batches: <N>
\`\`\`

## Visualization

After writing \`tasks.md\`, present the task plan visually for approval:

\`\`\`
present({ schemaVersion: 1, title: "Task Plan: <feature>", template: "task-plan@1", data: {
   title: "<feature title>",
   phases: [/* map each Phase to { id, label, outcome, batches: [{ id, order, parallel, tasks: [{ id, title, agent, files, status: "pending", dependsOn }] }] } */]
} })
\`\`\`

This renders an interactive dependency graph showing phases, parallel batches, and agent assignments.

Use the template-driven graph for the dependency view; if you add summary content, use \`kv\` for approval metadata, \`list\` for task notes, and NEVER \`code\` blocks for structured data.

## Agents

| Agent | Role |
|-------|------|
| **Planner** | Atomic task decomposition |
| **Architect-Reviewer-Alpha** | Validates task graph |

Planner does the decomposition; Architect-Reviewer validates the task graph.

${n(`remember`)}

## Completion Criteria

- [ ] Every plan phase maps to ≥1 task
- [ ] Each task touches ≤3 files
- [ ] Dependencies form a DAG (no cycles)
- [ ] Parallelism opportunities identified
- [ ] Architect review confirms no integration risks
- [ ] \`{{artifacts_path}}/tasks.md\` written

${r(`- **Task decomposition rationale**: Why tasks were split this way
- **Interface contracts**: APIs, types, or data shapes tasks depend on
- **Coordination points**: Where tasks interact and handoff requirements`)}
`},{file:`steps/verify/README.md`,content:`---
name: verify
description: Dual code review, architecture review, security review, and test validation.
---

# Verification (Advanced)

## Prerequisites Check

Before starting this step, verify:
- [ ] All tasks marked complete in progress tracker
- [ ] \`check({})\` and \`test_run({})\` pass
- [ ] \`{{artifacts_path}}/progress.md\` exists with execution results

If prerequisites are NOT met → **backtrack to execute step** (\`flow({ action: 'step', advance: 'redo' })\` on previous step)

## Purpose

Perform multi-perspective validation through dual code review, architecture review, and security analysis.

## Inputs

- \`{{artifacts_path}}/spec.md\` — original requirements and acceptance criteria
- \`{{artifacts_path}}/plan.md\` — architecture decisions and phase design
- \`{{artifacts_path}}/tasks.md\` — task breakdown with per-task acceptance criteria
- \`{{artifacts_path}}/progress.md\` — implementation status and changes made

## Process

1. **Load all artifacts** — read spec, plan, tasks, progress
2. **Dual code review** (parallel):
   - Code-Reviewer-Alpha: correctness, conventions, quality
   - Code-Reviewer-Beta: edge cases, error handling, maintainability
3. **Architecture review** (parallel with code review):
   - Architect-Reviewer-Alpha: alignment with plan and ADRs
   - Architect-Reviewer-Beta: long-term maintainability and evolution
4. **Security review**:
   - Security agent: OWASP Top 10, auth/authz, input validation, secrets
5. **Quality gates** — \`check({})\` + \`test_run({})\` must pass
6. **Blast radius** — \`blast_radius({ path: ".", files: [...] })\` on all modified files
7. **Acceptance criteria** — Verify each spec acceptance criterion is met
8. **FORGE gate** — \`evidence_map({ action: "gate" })\` for final quality assessment
9. **Synthesize report** — merge reviewer findings into a unified verdict

## Evidence Map Gate Detail

After the process steps above, the FORGE gate must return YIELD:

- **YIELD** → All claims verified, proceed to completion
- **HOLD** → Fix unresolved claims, re-gate (max 2 retries)
- **HARD_BLOCK** → Contract-type unknowns detected, escalate to user

Never declare verification complete without YIELD.

## Outputs

Write \`{{artifacts_path}}/verify-report.md\` to disk. **You MUST create this file** using the IDE's native file creation capability or equivalent — do not only present content in chat.

Template:

\`\`\`markdown
# Verification Report: <feature title>

## Verdict: PASS | FAIL

## Acceptance Criteria
- [x] <criterion> — verified by <method>
- [ ] <criterion> — FAILED: <reason>

## Quality Gates
- check: PASS/FAIL
- test_run: PASS/FAIL (<N> passed, <M> failed)
- blast_radius: <impact summary>
- FORGE gate: YIELD/HOLD/HARD_BLOCK

## Code Review (Alpha)
<findings with severity: critical/major/minor/suggestion>

## Code Review (Beta)
<findings with severity>

## Architecture Review
<alignment assessment, any concerns>

## Security Review
<vulnerabilities found, OWASP compliance>

## Recommendation
APPROVE | REQUEST CHANGES

### Required Changes (if any)
1. <change needed>
2. ...
\`\`\`

## Agents

| Agent | Role |
|-------|------|
| **Code-Reviewer-Alpha** | Correctness, quality, conventions |
| **Code-Reviewer-Beta** | Edge cases, error handling, maintainability |
| **Architect-Reviewer-Alpha** | Alignment with plan and ADRs |
| **Architect-Reviewer-Beta** | Long-term evolution |
| **Security** | OWASP, auth, input validation |

**Parallelism**: All 5 reviewers can run in parallel — read-only.

${n(`remember`,"| `lesson-learned` | Extract engineering principles from completed work | After verification — capture lessons from the implementation |\n| `session-handoff` | Context preservation for session continuity | When verification spans sessions or for final handoff |",t)}

## Completion Criteria

- [ ] Dual code review complete (2 reviewers)
- [ ] Architecture review complete (2 reviewers)
- [ ] Security review complete
- [ ] \`check({})\` passes
- [ ] \`test_run({})\` passes
- [ ] All spec acceptance criteria verified
- [ ] FORGE gate passed (YIELD)
- [ ] \`{{artifacts_path}}/verify-report.md\` written with clear verdict

${r(`- **Test coverage gaps**: Areas that couldn't be fully tested and why
- **Quality findings**: Issues found during verification and their resolutions
- **Session checkpoint**: What was accomplished, decisions made, remaining work`)}
`}],"aikit-basic":[{file:`README.md`,content:"# aikit:basic — Quick Development Flow\n\nQuick development flow for **bug fixes, small features, and refactoring**.\n\n## Steps\n\n| # | Step | Skill | Produces | Requires | Agents |\n|---|------|-------|----------|----------|--------|\n| 1 | **Design Gate** | `steps/design/README.md` | `design-decisions.md` | — | Researcher-Alpha/Beta/Gamma/Delta |\n| 2 | **Assessment** | `steps/assess/README.md` | `assessment.md` | `design-decisions.md` | Explorer, Researcher-Alpha |\n| 3 | **Implementation** | `steps/implement/README.md` | `progress.md` | `assessment.md` | Implementer, Frontend |\n| 4 | **Verification** | `steps/verify/README.md` | `verify-report.md` | `progress.md` | Code-Reviewer-Alpha, Security |\n\n## How It Works\n\nEach step has a **README.md**. Orchestrator reads it via `flow({ action: 'read' })` and delegates work.\n\n### Step 1: Design Gate\n- **Auto-skips** for bug fixes and refactors (produces minimal `design-decisions.md` noting the skip)\n- For small features: runs quick brainstorming, FORGE classification, and optional decision protocol\n- Read `steps/design/README.md` for the full decision tree\n\n### Step 2: Assessment\n- Explore the codebase to understand scope and impact\n- Use `search`, `scope_map`, `file_summary`, `compact` to gather context\n- Identify the approach and produce `assessment.md`\n\n### Step 3: Implementation\n- Write code following the assessment plan\n- The Orchestrator dispatches Implementer/Frontend agents with specific file scopes\n- Follow TDD practices where applicable\n\n### Step 4: Verification\n- Code review, test execution, security check\n- Run `check({})` + `test_run({})` + `blast_radius({})`\n- Produce `verify-report.md` with findings\n\n## Using Skills Inside Steps\n\nWhen the Orchestrator activates a step:\n\n1. **Read the instruction first** — `flow({ action: 'read' })` returns the current step README.md\n2. **Follow step instructions** — primary guide\n3. **Delegate to listed agents** — each step lists which agents are appropriate\n4. **Produce the required artifact** — the step's `produces` field specifies the artifact file\n5. **Check dependencies** — required prior artifacts must exist\n6. **Report status** — agents report `DONE` | `DONE_WITH_CONCERNS` | `NEEDS_CONTEXT` | `BLOCKED` to the Orchestrator\n\n## Artifacts\n\nArtifacts are stored under `.flows/{topic}/`. `{{artifacts_path}}` resolves at runtime.\n"},{file:`steps/assess/README.md`,content:`---
name: assess
description: Understand scope, analyze the codebase, and identify the approach.
---

# Assessment

## Purpose

Analyze task requirements and codebase to produce a clear, actionable assessment before code changes begin.

## Inputs

- User's task description or issue reference
- Codebase (via aikit MCP tools)

## Prerequisites Check

Before executing this step, verify:

- [ ] Design decisions documented (from the design step)
- [ ] FORGE classification determined (tier assigned)
- [ ] If brainstorming was done, session outcomes are recorded

If prerequisites are missing or incomplete:
1. Inform the Orchestrator with specifics about what's missing
2. Recommend \`flow({ action: 'step', advance: 'redo' })\` on the **design** step
3. Do NOT proceed with partial inputs

### Requirements Input (if available)

If \`{{artifacts_path}}/requirements.md\` exists (produced by requirements-clarity in the Design Gate):
- Use its acceptance criteria as the test plan basis
- Ensure the implementation addresses all listed requirements
- The quality score must be ≥ 90 — if it's lower, the Design Gate should not have advanced

If no requirements.md exists (Design Gate was auto-skipped for bug fix/refactor), proceed without it.

## Process

1. **Parse the goal** — extract what needs to change, success criteria, constraints
2. **Search for prior work** — \`search({ query: "<task keywords>" })\` for existing decisions or related code
3. **Map affected scope** — \`scope_map({ task: "<description>" })\` to identify files and modules involved
4. **Analyze structure** — \`file_summary()\` on each affected file; \`compact()\` for deeper sections
5. **Identify risks** — note deps, breaking-change potential, test gaps
6. **Draft approach** — outline implementation strategy in 3–7 steps

## Outputs

Write \`{{artifacts_path}}/assessment.md\` to disk. **You MUST create this file** using the IDE's native file creation capability or equivalent — do not only present content in chat.

Template:

\`\`\`markdown
# Assessment: <task title>

## Goal
<what needs to happen>

## Affected Files
<list of files with brief reason>

## Approach
<numbered implementation steps>

## Risks
<potential issues and mitigations>

## Open Questions
<anything that needs clarification before proceeding>
\`\`\`

## Agents

| Agent | Role |
|-------|------|
| **Explorer** | File discovery, dependency tracing, structural context |
| **Researcher-Alpha** | Complex logic, prior decisions, architecture |

Use Explorer first for breadth, then Researcher-Alpha for depth.

${n(`remember`,"| `c4-architecture` | C4 diagrams — system context, container, component, deployment | When visualizing system structure during assessment |\n| `adr-skill` | ADRs — create, review, maintain | When assessment reveals non-trivial design decisions |")}

## Completion Criteria

- [ ] All affected files identified
- [ ] Implementation approach is concrete (not vague)
- [ ] Risks documented with mitigations
- [ ] No unresolved open questions that block implementation
- [ ] \`{{artifacts_path}}/assessment.md\` written

${r(`- **Codebase discoveries**: File locations, patterns, or dependency relationships found during assessment
- **Problem diagnosis**: Root cause, contributing factors, affected components
- **Scope decisions**: What's in scope, what's excluded, and why`)}
`},{file:`steps/design/README.md`,content:`# Design Gate — Basic Flow

Lightweight design gate for bug fixes, small features, and refactoring. Evaluates task type and whether design work is needed.

## When This Step Runs

First step of \`aikit:basic\`. Runs before assessment.

## Instructions

### 1. Task Classification

Classify the task:

| Category | Indicators | Action |
|----------|-----------|--------|
| **Bug fix** | Error reports, stack traces, regression, "fix", "broken" | → **Auto-skip** to next step |
| **Refactor** | Code cleanup, rename, restructure, no behavior change | → **Auto-skip** to next step |
| **Small feature** | New behavior, new endpoint, new component, UI change | → Run **Quick Design** below |

**If the task is a bug fix or refactor**, write \`{{artifacts_path}}/design-decisions.md\` to disk:
\`\`\`markdown
## Design Decisions
- **Task type**: Bug fix / Refactor
- **Design gate**: Auto-skipped — no design work needed
- **Proceed to**: Assessment
\`\`\`
**You MUST create this file on disk** at the exact \`{{artifacts_path}}/design-decisions.md\` path — do not only present the content in chat.
Then report \`DONE\` to the Orchestrator.

### 2. Quick Design (Small Features Only)

For small features that need minimal design:

#### For Small Features (requires design):

1. **If requirements are unclear** (ambiguous scope, multiple interpretations, or cross-component):
   - Load \`requirements-clarity\` skill
   - Score requirements, iterate until ≥ 90
   - Output: \`{{artifacts_path}}/requirements.md\`
2. **If requirements are clear** (single concern, obvious scope, clear acceptance):
   - Skip requirements-clarity, proceed to Quick Design directly

1. **FORGE Classify** — Run \`forge_classify({ task: "<task description>", files: [<relevant files>], root_path: "." })\` to determine tier
2. **Brainstorming** (if tier ≥ Standard) — Load \`brainstorming\` and run a focused session:
   - What is the user trying to achieve?
   - What are the constraints?
   - What is the simplest approach?
3. **Decision Protocol** (if technical decisions exist) — Follow the full 3-phase multi-model decision protocol:
   - **Phase 1**: Launch ALL 4 Researcher variants in parallel (Alpha/Beta/Gamma/Delta)
   - **Phase 2**: Anonymize outputs as A/B/C/D, run peer review round (4 reviewers in parallel)
   - **Phase 3**: Synthesize into structured verdict (Agrees / Clashes / Blind Spots / Recommendation / First Step)
   - Present verdict visually using \`present({ schemaVersion: 1, title: "Decision Verdict", blocks: [...] })\`; use \`table\` for multi-approach comparisons, \`list\` for recommendations/blind spots, and \`kv\` for verdict metadata. NEVER \`code\` blocks for structured data. Produce ADR for Standard+ tiers
4. **Write \`{{artifacts_path}}/design-decisions.md\`** to disk:

\`\`\`markdown
## Design Decisions

### FORGE Assessment
- **Tier**: {Floor | Standard | Critical}
- **Rationale**: {why this tier}

### Task Summary
- **Goal**: {what we're building}
- **Approach**: {chosen approach}
- **Key decisions**: {list}

### Constraints
- {constraint 1}
- {constraint 2}
\`\`\`

### 3. Report to Orchestrator

When complete, report status:
- \`DONE\` — design decisions captured, ready for assessment
- \`DONE_WITH_CONCERNS\` — design captured but open questions remain

**Do NOT call \`flow({ action: 'step', advance: 'next' })\`** — let the Orchestrator advance the flow.

## Outputs

Write \`{{artifacts_path}}/design-decisions.md\` to disk. **You MUST create this file** using the IDE's native file creation capability or equivalent — do not only present content in chat. This file is a prerequisite for the next step.

## Produces

- \`{{artifacts_path}}/design-decisions.md\` — Task classification, FORGE tier, key design decisions

## Agents

- \`Researcher-Alpha\`, \`Researcher-Beta\`, \`Researcher-Gamma\`, \`Researcher-Delta\` — parallel research during decision protocol

${n(`remember`,"| `c4-architecture` | C4 diagrams — system context, container, component, deployment | When visualizing system structure during design |\n| `adr-skill` | ADRs — create, review, maintain | When making non-trivial design or technology decisions |")}

## Completion Criteria

- [ ] \`{{artifacts_path}}/design-decisions.md\` written to disk (NOT just presented in chat)
- [ ] FORGE tier determined (for small features)
- [ ] Key design decisions documented

${r(`- **Design decisions**: Chosen approach and rejected alternatives
- **Architecture patterns**: New patterns or patterns that must be followed
- **Constraints discovered**: Technical, compatibility, performance limits`)}
`},{file:`steps/implement/README.md`,content:`---
name: implement
description: Write code following the assessment plan, using TDD where applicable.
---

# Implementation

## Purpose

Execute the implementation plan from assessment, writing production code and tests.

## Inputs

- \`{{artifacts_path}}/assessment.md\` — approach, affected files, risks

## Prerequisites Check

Before executing this step, verify:

- [ ] Assessment complete and scope approved (from the assess step)
- [ ] Files-to-modify list is clear and bounded
- [ ] \`check({})\` baseline captured (know what currently passes)

If prerequisites are missing or incomplete:
1. Inform the Orchestrator with specifics about what's missing
2. Recommend \`flow({ action: 'step', advance: 'redo' })\` on the **assess** step
3. Do NOT proceed with partial inputs

## Process

1. **Read assessment** — load \`{{artifacts_path}}/assessment.md\` and internalize the approach
2. **Set up tests first** — where applicable, write failing tests that define success
3. **Implement changes** — follow approach steps sequentially
   - One logical change per chunk
   - Stay within assessed file scope — do not expand without re-assessment
4. **Run validation** — \`check({})\` for type/lint errors, \`test_run({})\` for test results
5. **Fix issues** — Iterate until \`check\` and \`test_run\` pass (max 3 rounds)
6. **Document progress** — write progress artifact with what was done and deviations

## Validation Boundary (MANDATORY)

Before declaring implementation complete, run:

1. \`check({})\` — typecheck + lint must pass
2. \`test_run({})\` — all tests must pass

If either fails:
- Fix the issue in the same implementation cycle
- Re-run validation
- If stuck after 2 attempts → report as BLOCKED and escalate

**Never advance past implement without green check + test.**

## Outputs

Write \`{{artifacts_path}}/progress.md\` to disk. **You MUST create this file** using the IDE's native file creation capability or equivalent — do not only present content in chat.

Template:

\`\`\`markdown
# Implementation Progress: <task title>

## Changes Made
<list of files changed with brief description>

## Tests
<tests added or modified>

## Deviations from Assessment
<any changes to the original plan and why>

## Validation
- check: PASS/FAIL
- test_run: PASS/FAIL (<N> passed, <M> failed)

## Notes
<anything the reviewer should know>
\`\`\`

## Agents

| Agent | Role |
|-------|------|
| **Implementer** | TDD, production code, tests |
| **Frontend** | React, styling, responsive design |

Dispatch Implementer for backend/logic changes, Frontend for UI changes. They can run in parallel on different files.

${n(`remember`,"| `session-handoff` | Context preservation for session transfers | When implementation is long-running or context may fill up |",e)}

## Completion Criteria

- [ ] All assessment steps implemented
- [ ] \`check({})\` passes (no type/lint errors)
- [ ] \`test_run({})\` passes (no test failures)
- [ ] No files modified outside assessed scope
- [ ] \`{{artifacts_path}}/progress.md\` written

${r(`- **Implementation decisions**: Why specific approaches were chosen
- **Patterns established**: New conventions or patterns to follow
- **Gotchas encountered**: Edge cases, workarounds, non-obvious behaviors`)}
`},{file:`steps/verify/README.md`,content:`---
name: verify
description: Review code changes, run tests, validate correctness and quality.
---

# Verification

## Purpose

Validate that implementation meets requirements, passes quality gates, and introduces no regressions.

## Inputs

- \`{{artifacts_path}}/assessment.md\` — original requirements and approach
- \`{{artifacts_path}}/progress.md\` — implemented changes and deviations

## Prerequisites Check

Before executing this step, verify:

- [ ] Implementation complete (from the implement step)
- [ ] \`check({})\` + \`test_run({})\` pass at baseline
- [ ] Changed files list is available for blast radius analysis

If prerequisites are missing or incomplete:
1. Inform the Orchestrator with specifics about what's missing
2. Recommend \`flow({ action: 'step', advance: 'redo' })\` on the **implement** step
3. Do NOT proceed with partial inputs

## Process

1. **Load context** — read assessment and progress artifacts
2. **Code review** — review changed files for:
   - Correctness against requirements
   - Code quality and project conventions
   - Error handling and edge cases
   - No unnecessary changes (scope creep)
3. **Run quality gates** — \`check({})\` + \`test_run({})\` must pass
4. **Blast radius** — \`blast_radius({ path: ".", files: [...] })\` to assess impact
5. **Security scan** — Check for OWASP Top 10 issues in changed code
6. **Write report** — document findings with PASS/FAIL verdict

## Outputs

Write \`{{artifacts_path}}/verify-report.md\` to disk. **You MUST create this file** using the IDE's native file creation capability or equivalent — do not only present content in chat.

Template:

\`\`\`markdown
# Verification Report: <task title>

## Verdict: PASS | FAIL

## Quality Gates
- check: PASS/FAIL
- test_run: PASS/FAIL (<N> passed, <M> failed)
- blast_radius: <summary of impact>

## Code Review Findings
<issues found, if any, with severity>

## Security
<any security concerns>

## Recommendation
<APPROVE for commit / REQUEST CHANGES with specific items>
\`\`\`

## Agents

| Agent | Role |
|-------|------|
| **Code-Reviewer-Alpha** | Correctness, quality, conventions |
| **Security** | Vulnerability analysis, OWASP compliance |

Run both in parallel — they review different aspects of the same changes.

${n(`remember`,"| `lesson-learned` | Extract engineering lessons from completed work via git history | After verification completes — capture principles from what was built |\n| `session-handoff` | Context preservation for session transfers | When verification is final step and session context should be saved |",t)}

## Completion Criteria

- [ ] \`check({})\` passes
- [ ] \`test_run({})\` passes
- [ ] Code review complete with no blocking issues
- [ ] Security review complete
- [ ] Blast radius assessed
- [ ] \`{{artifacts_path}}/verify-report.md\` written with clear PASS/FAIL verdict

${r(`- **Test coverage gaps**: Areas that couldn't be fully tested and why
- **Quality findings**: Issues found during verification and their resolutions
- **Session checkpoint**: What was accomplished, decisions made, remaining work`)}
`}]};export{i as FLOWS};