From 86e4c8d605357036e7300ced14f77b92fec25257 Mon Sep 17 00:00:00 2001 From: Rasmus Widing <152263317+Wirasm@users.noreply.github.com> Date: Thu, 16 Apr 2026 21:27:51 +0200 Subject: [PATCH] fix(bundled-defaults): auto-generate import list, emit inline strings (#1263) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(bundled-defaults): auto-generate import list, emit inline strings Root-cause fix for bundle drift (15 commands + 7 workflows previously missing from binary distributions) and a prerequisite for packaging @archon/workflows as a Node-loadable SDK. The hand-maintained `bundled-defaults.ts` import list is replaced by `scripts/generate-bundled-defaults.ts`, which walks `.archon/{commands,workflows}/defaults/` and emits a generated source file with inline string literals. `bundled-defaults.ts` becomes a thin facade that re-exports the generated records and keeps the `isBinaryBuild()` helper. Inline strings (via JSON.stringify) replace Bun's `import X from '...' with { type: 'text' }` attributes. The binary build still embeds the data at compile time, but the module now loads under Node too — removing SDK blocker #2. - Generator: `scripts/generate-bundled-defaults.ts` (+ `--check` mode for CI) - `package.json`: `generate:bundled`, `check:bundled`; wired into `validate` - `build-binaries.sh`: regenerates defaults before compile - Test: `bundle completeness` now derives expected set from on-disk files - All 56 defaults (36 commands + 20 workflows) now in the bundle * fix(bundled-defaults): address PR review feedback Review: https://github.com/coleam00/Archon/pull/1263#issuecomment-4262719090 Generator: - Guard against .yaml/.yml name collisions (previously silent overwrite) - Add early access() check with actionable error when run from wrong cwd - Type top-level catch as unknown; print only message for Error instances - Drop redundant /* eslint-disable */ emission (global ignore covers it) - Fix misleading CI-mechanism claim in header comment - Collapse dead `if (!ext) continue` guard into a single typed pass Scripts get real type-checking + linting: - New scripts/tsconfig.json extending root config - type-check now includes scripts/ via `tsc --noEmit -p scripts/tsconfig.json` - Drop `scripts/**` from eslint ignores; add to projectService file scope Tests: - Inline listNames helper (Rule of Three) - Drop redundant toBeDefined/typeof assertions; the Record type plus length > 50 already cover them - Add content-fidelity round-trip assertion (defense against generator content bugs, not just key-set drift) Facade comment: drop dead reference to .claude/rules/dx-quirks.md. CI: wire `bun run check:bundled` into .github/workflows/test.yml so the header's CI-verification claim is truthful. Docs: CLAUDE.md step count four→five; add contributor bullet about `bun run generate:bundled` in the Defaults section and CONTRIBUTING.md. * chore(e2e): bump Codex model to gpt-5.2 gpt-5.1-codex-mini is deprecated and unavailable on ChatGPT-account Codex auth. Plain gpt-5.2 works. Verified end-to-end: - e2e-codex-smoke: structured output returns {category:'math'} - e2e-mixed-providers: claude+codex both return expected tokens --- .archon/workflows/e2e-codex-smoke.yaml | 2 +- .archon/workflows/e2e-mixed-providers.yaml | 2 +- .github/workflows/test.yml | 3 + .prettierignore | 3 + CLAUDE.md | 5 +- CONTRIBUTING.md | 13 +- eslint.config.mjs | 3 +- package.json | 6 +- .../defaults/bundled-defaults.generated.ts | 78 ++++++++ .../src/defaults/bundled-defaults.test.ts | 139 ++++++-------- .../src/defaults/bundled-defaults.ts | 118 ++---------- scripts/build-binaries.sh | 6 + scripts/generate-bundled-defaults.ts | 172 ++++++++++++++++++ scripts/tsconfig.json | 11 ++ 14 files changed, 368 insertions(+), 193 deletions(-) create mode 100644 packages/workflows/src/defaults/bundled-defaults.generated.ts create mode 100644 scripts/generate-bundled-defaults.ts create mode 100644 scripts/tsconfig.json diff --git a/.archon/workflows/e2e-codex-smoke.yaml b/.archon/workflows/e2e-codex-smoke.yaml index 747a8a81..f24336b3 100644 --- a/.archon/workflows/e2e-codex-smoke.yaml +++ b/.archon/workflows/e2e-codex-smoke.yaml @@ -3,7 +3,7 @@ name: e2e-codex-smoke description: "E2E smoke test for Codex provider. Runs a simple prompt + structured output node." provider: codex -model: gpt-5.1-codex-mini +model: gpt-5.2 nodes: - id: simple diff --git a/.archon/workflows/e2e-mixed-providers.yaml b/.archon/workflows/e2e-mixed-providers.yaml index ef0c0b4f..9f5c408a 100644 --- a/.archon/workflows/e2e-mixed-providers.yaml +++ b/.archon/workflows/e2e-mixed-providers.yaml @@ -18,7 +18,7 @@ nodes: - id: codex-node prompt: "Say 'codex-ok' and nothing else." provider: codex - model: gpt-5.1-codex-mini + model: gpt-5.2 idle_timeout: 30000 # 3. Assert both providers returned output diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b41d9740..7a2e17ef 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -27,6 +27,9 @@ jobs: - name: Install dependencies run: bun install --frozen-lockfile + - name: Check bundled defaults + run: bun run check:bundled + - name: Type check run: bun run type-check diff --git a/.prettierignore b/.prettierignore index 5f7484c1..d0dd71f9 100644 --- a/.prettierignore +++ b/.prettierignore @@ -22,6 +22,9 @@ workspace/ # Lock files (auto-generated) package-lock.json +# Auto-generated source (regenerated by scripts/generate-bundled-defaults.ts) +**/*.generated.ts + # Agent commands and documentation (user-managed) .agents/ .claude/ diff --git a/CLAUDE.md b/CLAUDE.md index d1f786a0..985475dd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -150,7 +150,7 @@ bun run format:check bun run validate ``` -This runs type-check, lint, format check, and tests. All four must pass for CI to succeed. +This runs `check:bundled`, type-check, lint, format check, and tests. All five must pass for CI to succeed. ### ESLint Guidelines @@ -710,10 +710,11 @@ async function createSession(conversationId: string, codebaseId: string) { **Defaults:** - Bundled in `.archon/commands/defaults/` and `.archon/workflows/defaults/` -- Binary builds: Embedded at compile time (no filesystem access needed) +- Binary builds: Embedded at compile time (no filesystem access needed) via `packages/workflows/src/defaults/bundled-defaults.generated.ts` - Source builds: Loaded from filesystem at runtime - Merged with repo-specific commands/workflows (repo overrides defaults by name) - Opt-out: Set `defaults.loadDefaultCommands: false` or `defaults.loadDefaultWorkflows: false` in `.archon/config.yaml` +- **After adding, removing, or editing a default file, run `bun run generate:bundled`** to refresh the embedded bundle. `bun run validate` (and CI) run `check:bundled` and will fail loudly if the generated file is stale. **Global workflows** (user-level, applies to every project): - Path: `~/.archon/.archon/workflows/` (or `$ARCHON_HOME/.archon/workflows/`) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index da3b90fa..c0120a16 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -17,15 +17,20 @@ Thank you for your interest in contributing to Archon! Before submitting a PR, ensure: ```bash -bun run type-check # TypeScript types -bun run lint # ESLint -bun run format # Prettier -bun run test # All tests (per-package isolation) +bun run check:bundled # Bundled defaults are up to date (see note below) +bun run type-check # TypeScript types +bun run lint # ESLint +bun run format # Prettier +bun run test # All tests (per-package isolation) # Or run the full validation suite: bun run validate ``` +**Bundled defaults**: If you added, removed, or edited a file under +`.archon/commands/defaults/` or `.archon/workflows/defaults/`, run +`bun run generate:bundled` to refresh the embedded bundle before committing. + **Important:** Use `bun run test` (not `bun test` from the repo root) to avoid mock pollution across packages. ### Commit Messages diff --git a/eslint.config.mjs b/eslint.config.mjs index a7ba5b4c..152c4245 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -17,6 +17,7 @@ export default tseslint.config( 'worktrees/**', '.claude/worktrees/**', '.claude/skills/**', + '**/*.generated.ts', // Auto-generated source files (content inlined via JSON.stringify) '**/*.js', '*.mjs', '**/*.test.ts', @@ -41,7 +42,7 @@ export default tseslint.config( // Project-specific settings { - files: ['packages/*/src/**/*.{ts,tsx}'], + files: ['packages/*/src/**/*.{ts,tsx}', 'scripts/**/*.ts'], languageOptions: { parserOptions: { projectService: true, diff --git a/package.json b/package.json index b296d638..2023b822 100644 --- a/package.json +++ b/package.json @@ -14,9 +14,11 @@ "build": "bun --filter '*' build", "build:binaries": "bash scripts/build-binaries.sh", "build:checksums": "bash scripts/checksums.sh", + "generate:bundled": "bun run scripts/generate-bundled-defaults.ts", + "check:bundled": "bun run scripts/generate-bundled-defaults.ts --check", "test": "bun --filter '*' --parallel test", "test:watch": "bun --filter @archon/server test:watch", - "type-check": "bun --filter '*' type-check", + "type-check": "bun --filter '*' type-check && bun x tsc --noEmit -p scripts/tsconfig.json", "lint": "bun x eslint . --cache", "lint:fix": "bun x eslint . --cache --fix", "format": "bun x prettier --write .", @@ -25,7 +27,7 @@ "build:web": "bun --filter @archon/web build", "dev:docs": "bun --filter @archon/docs-web dev", "build:docs": "bun --filter @archon/docs-web build", - "validate": "bun run type-check && bun run lint --max-warnings 0 && bun run format:check && bun run test", + "validate": "bun run check:bundled && bun run type-check && bun run lint --max-warnings 0 && bun run format:check && bun run test", "prepare": "husky", "setup-auth": "bun --filter @archon/server setup-auth" }, diff --git a/packages/workflows/src/defaults/bundled-defaults.generated.ts b/packages/workflows/src/defaults/bundled-defaults.generated.ts new file mode 100644 index 00000000..3c74c57b --- /dev/null +++ b/packages/workflows/src/defaults/bundled-defaults.generated.ts @@ -0,0 +1,78 @@ +/** + * AUTO-GENERATED — DO NOT EDIT. + * + * Regenerate with: bun run generate:bundled + * Verify up-to-date: bun run check:bundled + * + * Source of truth: + * .archon/commands/defaults/*.md + * .archon/workflows/defaults/*.{yaml,yml} + * + * Contents are inlined as plain string literals (JSON-escaped) so this + * module loads in both Bun and Node. Previous versions used + * `import X from '...' with { type: 'text' }` which is Bun-specific. + */ + +// Bundled default commands (36 total) +export const BUNDLED_COMMANDS: Record = { + "archon-assist": "---\ndescription: General assistance - questions, debugging, one-off tasks, exploration\nargument-hint: \n---\n\n# Assist Mode\n\n**Request**: $ARGUMENTS\n\n---\n\nYou are helping with a request that didn't match a specific workflow.\n\n## Instructions\n\n1. **Understand the request** - What is the user actually asking for?\n2. **Take action** - Use your full Claude Code capabilities to help\n3. **Be helpful** - Answer questions, debug issues, explore code, make changes\n4. **Note the gap** - If this should have been a specific workflow, mention it:\n \"Note: Using assist mode. Consider creating a workflow for this use case.\"\n\n## Capabilities\n\nYou have full Claude Code capabilities:\n- Read and write files\n- Run commands\n- Search the codebase\n- Make code changes\n- Answer questions\n\n## Request\n\n$ARGUMENTS\n", + "archon-auto-fix-review": "---\ndescription: Auto-fix all review findings unless clear YAGNI violations, post fix report\nargument-hint: (none - reads all review artifacts from $ARTIFACTS_DIR/review/)\n---\n\n# Auto-Fix Review Findings\n\n---\n\n## IMPORTANT: Output Behavior\n\n**Your output will be posted as a GitHub comment.** Keep working output minimal:\n- Do NOT narrate each step\n- Do NOT output verbose progress updates\n- Only output the final structured report at the end\n- Use the TodoWrite tool to track progress silently\n\n---\n\n## Your Mission\n\nRead all review artifacts produced in this workflow run and fix everything surfaced — unless a finding is a clear YAGNI violation or speculative over-engineering beyond the scope of the original fix. Validate, commit, push, write an artifact, and post a GitHub comment explaining what was fixed and why anything was skipped.\n\n**Output artifact**: `$ARTIFACTS_DIR/review/fix-report.md`\n**Git action**: Commit AND push fixes to the PR branch\n**GitHub action**: Post fix report as a comment on the PR\n\n---\n\n## Phase 1: LOAD — Get Context\n\n### 1.1 Get PR Number and Branch\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number)\nHEAD_BRANCH=$(gh pr view $PR_NUMBER --json headRefName --jq '.headRefName')\necho \"PR: $PR_NUMBER, Branch: $HEAD_BRANCH\"\n```\n\n### 1.2 Checkout PR Branch\n\n**Always re-checkout to ensure you are on the right branch.**\n\n```bash\ngit fetch origin $HEAD_BRANCH\ngit checkout $HEAD_BRANCH\ngit pull origin $HEAD_BRANCH\n```\n\nVerify:\n\n```bash\ngit branch --show-current\ngit status --porcelain\n```\n\n### 1.3 Read All Review Artifacts\n\nDiscover whatever review artifacts exist — there may be one or many depending on which review agents ran:\n\n```bash\nls $ARTIFACTS_DIR/review/\n```\n\nRead each `.md` file that looks like a findings artifact (e.g. `code-review-findings.md`, `error-handling-findings.md`, `test-coverage-findings.md`, `docs-impact-findings.md`, `consolidated-review.md`). Skip non-findings files like `scope.md` and `fix-report.md`.\n\n```bash\nfor f in $ARTIFACTS_DIR/review/*.md; do\n echo \"=== $f ===\"; cat \"$f\"; echo\ndone\n```\n\n### 1.4 Extract Findings\n\nFrom all loaded artifacts, compile a unified list of all findings with their severity, location, and suggested fix.\n\n**PHASE_1_CHECKPOINT:**\n- [ ] PR number and branch identified\n- [ ] On correct PR branch\n- [ ] All review artifacts read\n- [ ] All findings extracted\n\n---\n\n## Phase 2: TRIAGE — Decide What to Fix\n\nFor each finding, decide: **FIX** or **SKIP**.\n\n### Fix if:\n- It is a real bug, type error, silent failure, or clear code quality issue\n- The fix is concrete and low-risk\n\n### Skip (YAGNI / out-of-scope) if the finding recommends:\n- Adding something not required to fix the original issue (new config options, new abstractions, speculative fallbacks, \"what if\" edge cases)\n- Refactoring or restructuring code that isn't broken\n- Adding validation for inputs that cannot actually be invalid in this context\n- Extracting utilities or helpers for code that currently has only one caller\n- Architectural changes that touch code well outside the PR's scope\n\nUse judgment — don't be overly restrictive. If it's a legitimate bug the reviewer found, fix it even if it's adjacent to the PR. If it's clearly speculative (\"this might be useful someday\"), skip it.\n\nFor each skipped finding, write down **the specific reason** — this goes in the report.\n\n**PHASE_2_CHECKPOINT:**\n- [ ] Every finding marked FIX or SKIP\n- [ ] Skip reasons documented\n\n---\n\n## Phase 3: IMPLEMENT — Apply Fixes\n\n### 3.1 For Each Finding Marked FIX\n\n1. Read the relevant file(s)\n2. Apply the fix following the suggested approach from the review artifact\n3. Run type-check after each fix: `bun run type-check`\n4. Note exactly what was changed\n\n### 3.2 Handle Unfixable Findings\n\nIf a fix cannot be applied (code changed since review, fix is ambiguous, fix would break other things), mark it as **BLOCKED** and document why. Do not force a broken fix.\n\n### 3.3 Add Tests for Fixed Code\n\nIf the review flagged missing test coverage for something you just fixed, add a targeted test. Run it:\n\n```bash\nbun test {file}\n```\n\n**PHASE_3_CHECKPOINT:**\n- [ ] All FIX findings attempted\n- [ ] Tests added where flagged\n- [ ] BLOCKED findings documented\n\n---\n\n## Phase 4: VALIDATE — Full Check\n\n```bash\nbun run type-check\nbun run lint\nbun test\n```\n\nAll must pass. If something fails after a fix:\n1. Review the error\n2. Adjust the fix or revert it and mark BLOCKED\n3. Re-run until clean\n\n**PHASE_4_CHECKPOINT:**\n- [ ] Type check passes\n- [ ] Lint passes\n- [ ] Tests pass\n\n---\n\n## Phase 5: COMMIT AND PUSH\n\n### 5.1 Stage and Commit\n\nOnly stage files you actually changed:\n\n```bash\ngit add {specific files}\ngit status\ngit commit -m \"fix: address review findings\n\n$(echo \"Fixed:\"; echo \"- {brief list}\")\n$(echo \"\"; echo \"Skipped (YAGNI/out-of-scope):\"; echo \"- {brief list if any}\")\"\n```\n\n### 5.2 Push\n\n```bash\ngit push origin $HEAD_BRANCH\n```\n\nIf push fails due to divergence:\n\n```bash\ngit pull --rebase origin $HEAD_BRANCH\ngit push origin $HEAD_BRANCH\n```\n\n**PHASE_5_CHECKPOINT:**\n- [ ] Changes committed\n- [ ] Pushed to PR branch\n\n---\n\n## Phase 6: GENERATE — Write Fix Report\n\nWrite to `$ARTIFACTS_DIR/review/fix-report.md`:\n\n```markdown\n# Fix Report: PR #{number}\n\n**Date**: {ISO timestamp}\n**Status**: COMPLETE | PARTIAL\n**Branch**: {HEAD_BRANCH}\n**Commit**: {commit hash}\n\n---\n\n## Summary\n\n{2-3 sentences covering what was found, what was fixed, what was skipped and why}\n\n---\n\n## Fixes Applied\n\n| Severity | Finding | Location | What Was Done |\n|----------|---------|----------|---------------|\n| CRITICAL | {title} | `file:line` | {description} |\n| HIGH | {title} | `file:line` | {description} |\n\n---\n\n## Skipped Findings\n\n| Severity | Finding | Location | Reason Skipped |\n|----------|---------|----------|----------------|\n| HIGH | {title} | `file:line` | YAGNI: {specific reason} |\n| MEDIUM | {title} | `file:line` | Out of scope: {reason} |\n\n---\n\n## Tests Added\n\n| File | Test Cases |\n|------|------------|\n| `{file}.test.ts` | `{test description}` |\n\n*(none)* if no tests were added\n\n---\n\n## Blocked (Could Not Fix)\n\n| Severity | Finding | Reason |\n|----------|---------|--------|\n| {sev} | {title} | {why it could not be applied} |\n\n*(none)* if nothing was blocked\n\n---\n\n## Validation\n\n| Check | Status |\n|-------|--------|\n| Type check | ✅ / ❌ |\n| Lint | ✅ / ❌ |\n| Tests | ✅ {n} passed / ❌ |\n```\n\n**PHASE_6_CHECKPOINT:**\n- [ ] Fix report written\n\n---\n\n## Phase 7: POST — GitHub Comment\n\nPost the fix report as a PR comment:\n\n```bash\ngh pr comment $PR_NUMBER --body \"$(cat <<'EOF'\n## ⚡ Auto-Fix Report\n\n**Status**: {COMPLETE | PARTIAL}\n**Pushed**: ✅ Changes pushed to `{HEAD_BRANCH}`\n\n---\n\n### Fixes Applied\n\n| Severity | Finding | Location |\n|----------|---------|----------|\n| 🔴 CRITICAL | {title} | `file:line` |\n| 🟠 HIGH | {title} | `file:line` |\n\n*(none)* if nothing was fixed\n\n---\n\n### Skipped\n\n| Severity | Finding | Reason |\n|----------|---------|--------|\n| 🟠 HIGH | {title} | {reason — YAGNI, out of scope, blocked} |\n\n*(none)* if nothing was skipped\n\n---\n\n### Tests Added\n\n{List or \"(none)\"}\n\n---\n\n### Validation\n\n✅ Type check | ✅ Lint | ✅ Tests ({n} passed)\n\n---\n\n*Auto-fix by Archon · fixes pushed to `{HEAD_BRANCH}`*\nEOF\n)\"\n```\n\n**PHASE_7_CHECKPOINT:**\n- [ ] GitHub comment posted\n\n---\n\n## Phase 8: OUTPUT — Final Summary\n\nOutput only this:\n\n```\n## ⚡ Auto-Fix Complete\n\n**PR**: #{number}\n**Branch**: {HEAD_BRANCH}\n**Status**: COMPLETE | PARTIAL\n\nFixed: {n}\nSkipped: {n} (YAGNI/out-of-scope)\nBlocked: {n}\n\nValidation: ✅ All checks pass\nPushed: ✅\n\nFix report: $ARTIFACTS_DIR/review/fix-report.md\n```\n\n---\n\n## Error Handling\n\n### Type check fails after a fix\n1. Review the error\n2. Adjust or revert the fix\n3. If still failing after a reasonable attempt, mark BLOCKED\n\n### Tests fail\n1. Check whether the fix caused it or it was pre-existing\n2. Fix the test if the fix is correct\n3. If unclear, mark BLOCKED — do not ship broken tests\n\n### Push fails\n1. `git pull --rebase origin $HEAD_BRANCH`\n2. Resolve conflicts if any\n3. Push again\n\n### No review artifacts found\n```\n❌ No review artifacts found in $ARTIFACTS_DIR/review/\nCannot proceed without findings.\n```\n\n---\n\n## Success Criteria\n\n- **ON_CORRECT_BRANCH**: Working on PR's head branch\n- **ALL_FINDINGS_ADDRESSED**: Every finding is either fixed, skipped (with reason), or blocked (with reason)\n- **VALIDATION_PASSED**: Type check, lint, and tests all pass\n- **COMMITTED_AND_PUSHED**: Changes committed and pushed to PR branch\n- **REPORTED**: Fix report artifact written and GitHub comment posted\n", + "archon-code-review-agent": "---\ndescription: Review code quality, CLAUDE.md compliance, and detect bugs\nargument-hint: (none - reads from scope artifact)\n---\n\n# Code Review Agent\n\n---\n\n## Your Mission\n\nReview the PR for code quality, CLAUDE.md compliance, patterns, and bugs. Produce a structured artifact with findings, fix suggestions with multiple options, and reasoning.\n\n**Output artifact**: `$ARTIFACTS_DIR/review/code-review-findings.md`\n\n---\n\n## Phase 1: LOAD - Get Context\n\n### 1.1 Get PR Number from Registry\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number)\n```\n\n### 1.2 Read Scope\n\n```bash\ncat $ARTIFACTS_DIR/review/scope.md\n```\n\nNote:\n- Changed files list\n- CLAUDE.md rules to check\n- Focus areas\n\n**CRITICAL**: Check for \"NOT Building (Scope Limits)\" section. Items listed there are **intentionally excluded** - do NOT flag them as bugs or missing features!\n\n### 1.3 Get PR Diff\n\n```bash\ngh pr diff {number}\n```\n\n### 1.4 Read CLAUDE.md\n\n```bash\ncat CLAUDE.md\n```\n\nNote all coding standards, patterns, and rules.\n\n**PHASE_1_CHECKPOINT:**\n- [ ] PR number identified\n- [ ] Scope loaded\n- [ ] Diff available\n- [ ] CLAUDE.md rules noted\n\n---\n\n## Phase 2: ANALYZE - Review Code\n\n### 2.1 Check CLAUDE.md Compliance\n\nFor each changed file, verify:\n- Import patterns match project style\n- Naming conventions followed\n- Error handling patterns correct\n- Type annotations complete\n- Testing patterns followed\n\n### 2.2 Detect Bugs\n\nLook for:\n- Logic errors\n- Null/undefined handling issues\n- Race conditions\n- Memory leaks\n- Security vulnerabilities\n- Off-by-one errors\n- Missing error handling\n\n### 2.3 Check Code Quality\n\nEvaluate:\n- Code duplication\n- Function complexity\n- Proper abstractions\n- Clear naming\n- Appropriate comments\n\n### 2.4 Pattern Matching\n\nFor each issue found, search codebase for correct patterns:\n\n```bash\n# Find similar patterns in codebase\ngrep -r \"pattern\" src/ --include=\"*.ts\" | head -5\n```\n\n### 2.5 Check for Primitive Duplication\n\nFor each new interface, class, type alias, or utility module introduced in the diff:\n\n1. Search for similar existing abstractions:\n\n```bash\n# Replace {Name} with the new abstraction's name\ngrep -r \"interface {Name}\\|class {Name}\\|type {Name}\" packages/ --include=\"*.ts\" | head -10\n```\n\n2. Flag if the new abstraction duplicates or closely overlaps an existing one.\n3. Flag if a new utility function reimplements logic already available in a shared package.\n4. Note findings in the CLAUDE.md Compliance section with verdict: **EXTENDS** (extends existing primitive) or **DUPLICATE** (redundant with existing) or **NEW** (genuinely new, no existing primitive).\n\n**PHASE_2_CHECKPOINT:**\n- [ ] CLAUDE.md compliance checked\n- [ ] Bugs identified\n- [ ] Quality issues noted\n- [ ] Patterns found for fixes\n- [ ] Primitive duplication checked\n\n---\n\n## Phase 3: GENERATE - Create Artifact\n\nWrite to `$ARTIFACTS_DIR/review/code-review-findings.md`:\n\n```markdown\n# Code Review Findings: PR #{number}\n\n**Reviewer**: code-review-agent\n**Date**: {ISO timestamp}\n**Files Reviewed**: {count}\n\n---\n\n## Summary\n\n{2-3 sentence overview of code quality and main concerns}\n\n**Verdict**: {APPROVE | REQUEST_CHANGES | NEEDS_DISCUSSION}\n\n---\n\n## Findings\n\n### Finding 1: {Descriptive Title}\n\n**Severity**: CRITICAL | HIGH | MEDIUM | LOW\n**Category**: bug | style | performance | security | pattern-violation\n**Location**: `{file}:{line}`\n\n**Issue**:\n{Clear description of what's wrong}\n\n**Evidence**:\n```typescript\n// Current code at {file}:{line}\n{problematic code snippet}\n```\n\n**Why This Matters**:\n{Explain the impact - what could go wrong, why it violates standards}\n\n---\n\n#### Fix Suggestions\n\n| Option | Approach | Pros | Cons |\n|--------|----------|------|------|\n| A | {approach description} | {benefits} | {drawbacks} |\n| B | {alternative approach} | {benefits} | {drawbacks} |\n\n**Recommended**: Option {A/B}\n\n**Reasoning**:\n{Explain why this option is preferred, referencing:\n- Codebase patterns\n- CLAUDE.md rules\n- Best practices\n- Specific project context}\n\n**Recommended Fix**:\n```typescript\n// Suggested fix\n{corrected code}\n```\n\n**Codebase Pattern Reference**:\n```typescript\n// SOURCE: {file}:{lines}\n// This pattern shows how similar code is handled elsewhere\n{existing code from codebase}\n```\n\n---\n\n### Finding 2: {Title}\n\n{Same structure...}\n\n---\n\n## Statistics\n\n| Severity | Count | Auto-fixable |\n|----------|-------|--------------|\n| CRITICAL | {n} | {n} |\n| HIGH | {n} | {n} |\n| MEDIUM | {n} | {n} |\n| LOW | {n} | {n} |\n\n---\n\n## CLAUDE.md Compliance\n\n| Rule | Status | Notes |\n|------|--------|-------|\n| {rule from CLAUDE.md} | PASS/FAIL | {details} |\n| ... | ... | ... |\n\n---\n\n## Patterns Referenced\n\n| File | Lines | Pattern |\n|------|-------|---------|\n| `src/example.ts` | 42-50 | {what this pattern demonstrates} |\n| ... | ... | ... |\n\n---\n\n## Positive Observations\n\n{List things done well - good patterns, clean code, etc.}\n\n---\n\n## Metadata\n\n- **Agent**: code-review-agent\n- **Timestamp**: {ISO timestamp}\n- **Artifact**: `$ARTIFACTS_DIR/review/code-review-findings.md`\n```\n\n**PHASE_3_CHECKPOINT:**\n- [ ] Artifact file created\n- [ ] All findings have severity and location\n- [ ] Fix options provided with reasoning\n- [ ] Codebase patterns referenced\n\n---\n\n## Phase 4: VALIDATE - Check Artifact\n\n### 4.1 Verify File Exists\n\n```bash\ncat $ARTIFACTS_DIR/review/code-review-findings.md | head -20\n```\n\n### 4.2 Check Structure\n\nVerify artifact contains:\n- Summary with verdict\n- At least findings section (even if empty)\n- Statistics table\n- CLAUDE.md compliance table\n\n**PHASE_4_CHECKPOINT:**\n- [ ] Artifact file exists\n- [ ] Structure is complete\n- [ ] No placeholder text remaining\n\n---\n\n## Success Criteria\n\n- **CONTEXT_LOADED**: Scope and diff read successfully\n- **ANALYSIS_COMPLETE**: All changed files reviewed\n- **ARTIFACT_CREATED**: Findings file written\n- **PATTERNS_INCLUDED**: Each finding references codebase patterns\n- **OPTIONS_PROVIDED**: Multiple fix options where applicable\n", + "archon-comment-quality-agent": "---\ndescription: Review code comments for accuracy, completeness, and maintainability\nargument-hint: (none - reads from scope artifact)\n---\n\n# Comment Quality Agent\n\n---\n\n## Your Mission\n\nAnalyze code comments for accuracy against actual code, identify comment rot, check documentation completeness, and ensure comments aid long-term maintainability. Produce a structured artifact with findings and recommendations.\n\n**Output artifact**: `$ARTIFACTS_DIR/review/comment-quality-findings.md`\n\n---\n\n## Phase 1: LOAD - Get Context\n\n### 1.1 Get PR Number from Registry\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number)\n```\n\n### 1.2 Read Scope\n\n```bash\ncat $ARTIFACTS_DIR/review/scope.md\n```\n\n**CRITICAL**: Check for \"NOT Building (Scope Limits)\" section. Items listed there are **intentionally excluded** - do NOT flag them as missing documentation or comment issues!\n\n### 1.3 Get PR Diff\n\n```bash\ngh pr diff {number}\n```\n\nFocus on:\n- New comments added\n- Comments near modified code\n- JSDoc/docstrings added or changed\n\n**PHASE_1_CHECKPOINT:**\n- [ ] PR number identified\n- [ ] Changed files with comments identified\n- [ ] Diff available\n\n---\n\n## Phase 2: ANALYZE - Review Comments\n\n### 2.1 Check Comment Accuracy\n\nFor each comment in changed code:\n- Does the comment accurately describe what the code does?\n- Is the comment up-to-date with the implementation?\n- Are parameter descriptions correct?\n- Are return value descriptions accurate?\n- Are edge cases documented correctly?\n\n### 2.2 Identify Comment Rot\n\nLook for:\n- Comments that describe old behavior\n- TODO/FIXME that should have been addressed\n- Outdated references (old file names, removed functions)\n- Comments that contradict the code\n\n### 2.3 Check Documentation Completeness\n\nEvaluate:\n- Are complex functions properly documented?\n- Are public APIs documented?\n- Are non-obvious algorithms explained?\n- Are magic numbers/constants explained?\n- Are important decisions documented?\n\n### 2.4 Assess Maintainability\n\nConsider:\n- Will future developers understand the \"why\"?\n- Are there redundant comments (just restating code)?\n- Is the signal-to-noise ratio good?\n- Are comments in the right places?\n\n**PHASE_2_CHECKPOINT:**\n- [ ] Comment accuracy verified\n- [ ] Comment rot identified\n- [ ] Completeness gaps found\n- [ ] Maintainability assessed\n\n---\n\n## Phase 3: GENERATE - Create Artifact\n\nWrite to `$ARTIFACTS_DIR/review/comment-quality-findings.md`:\n\n```markdown\n# Comment Quality Findings: PR #{number}\n\n**Reviewer**: comment-quality-agent\n**Date**: {ISO timestamp}\n**Comments Reviewed**: {count}\n\n---\n\n## Summary\n\n{2-3 sentence overview of comment quality}\n\n**Verdict**: {APPROVE | REQUEST_CHANGES | NEEDS_DISCUSSION}\n\n---\n\n## Findings\n\n### Finding 1: {Descriptive Title}\n\n**Severity**: CRITICAL | HIGH | MEDIUM | LOW\n**Category**: inaccurate | outdated | missing | redundant | misleading\n**Location**: `{file}:{line}`\n\n**Issue**:\n{Clear description of the comment problem}\n\n**Current Comment**:\n```typescript\n// {the problematic comment}\n{code the comment describes}\n```\n\n**Actual Code Behavior**:\n{What the code actually does vs what comment says}\n\n**Impact**:\n{How this could mislead future developers}\n\n---\n\n#### Fix Suggestions\n\n| Option | Approach | Pros | Cons |\n|--------|----------|------|------|\n| A | {update comment} | {benefits} | {drawbacks} |\n| B | {remove comment} | {benefits} | {drawbacks} |\n| C | {expand comment} | {benefits} | {drawbacks} |\n\n**Recommended**: Option {X}\n\n**Reasoning**:\n{Why this option:\n- Matches documentation standards\n- Provides value without being redundant\n- Will remain accurate over time}\n\n**Recommended Fix**:\n```typescript\n/**\n * {corrected/improved comment}\n *\n * @param {type} param - {accurate description}\n * @returns {type} - {accurate description}\n */\n{code}\n```\n\n**Good Comment Pattern**:\n```typescript\n// SOURCE: {file}:{lines}\n// Example of good documentation in this codebase\n{existing well-documented code}\n```\n\n---\n\n### Finding 2: {Title}\n\n{Same structure...}\n\n---\n\n## Comment Audit\n\n| Location | Type | Accurate | Up-to-date | Useful | Verdict |\n|----------|------|----------|------------|--------|---------|\n| `file:line` | JSDoc | YES/NO | YES/NO | YES/NO | GOOD/UPDATE/REMOVE |\n| ... | ... | ... | ... | ... | ... |\n\n---\n\n## Statistics\n\n| Severity | Count | Auto-fixable |\n|----------|-------|--------------|\n| CRITICAL | {n} | {n} |\n| HIGH | {n} | {n} |\n| MEDIUM | {n} | {n} |\n| LOW | {n} | {n} |\n\n---\n\n## Documentation Gaps\n\n| Code Area | What's Missing | Priority |\n|-----------|----------------|----------|\n| `function xyz()` | Parameter docs, return type | HIGH |\n| `class Abc` | Class purpose, usage example | MEDIUM |\n| ... | ... | ... |\n\n---\n\n## Comment Rot Found\n\n| Location | Comment Says | Code Does | Age |\n|----------|--------------|-----------|-----|\n| `file:line` | \"{old description}\" | {actual behavior} | {when introduced} |\n| ... | ... | ... | ... |\n\n---\n\n## Positive Observations\n\n{Well-documented code, helpful comments, good explanations}\n\n---\n\n## Metadata\n\n- **Agent**: comment-quality-agent\n- **Timestamp**: {ISO timestamp}\n- **Artifact**: `$ARTIFACTS_DIR/review/comment-quality-findings.md`\n```\n\n**PHASE_3_CHECKPOINT:**\n- [ ] Artifact file created\n- [ ] Comment accuracy verified\n- [ ] Comment rot documented\n- [ ] Documentation gaps listed\n\n---\n\n## Success Criteria\n\n- **COMMENTS_AUDITED**: All comments in changed code reviewed\n- **ACCURACY_CHECKED**: Comments verified against actual code\n- **ROT_IDENTIFIED**: Outdated comments found\n- **GAPS_DOCUMENTED**: Missing documentation noted\n", + "archon-confirm-plan": "---\ndescription: Verify plan research is still valid - check patterns exist, code hasn't drifted\nargument-hint: (no arguments - reads from workflow artifacts)\n---\n\n# Confirm Plan Research\n\n**Workflow ID**: $WORKFLOW_ID\n\n---\n\n## Your Mission\n\nVerify that the plan's research is still valid before implementation begins.\n\nPlans can become stale:\n- Files may have been renamed or moved\n- Code patterns may have changed\n- APIs may have been updated\n\n**This step does NOT implement anything** - it only validates the plan is still accurate.\n\n---\n\n## Phase 1: LOAD - Read Context Artifact\n\n### 1.1 Load Plan Context\n\n```bash\ncat $ARTIFACTS_DIR/plan-context.md\n```\n\nIf not found, STOP with error:\n```\n❌ Plan context not found at $ARTIFACTS_DIR/plan-context.md\n\nRun archon-plan-setup first.\n```\n\n### 1.2 Extract Verification Targets\n\nFrom the context, identify:\n\n1. **Patterns to Mirror** - Files and line ranges to verify\n2. **Files to Change** - Files that will be created/updated\n3. **Validation Commands** - Commands that should work\n\n**PHASE_1_CHECKPOINT:**\n\n- [ ] Context artifact loaded\n- [ ] Patterns to verify extracted\n- [ ] Files to change identified\n\n---\n\n## Phase 2: VERIFY - Check Patterns Exist\n\n### 2.1 Verify Pattern Files\n\nFor each file in \"Patterns to Mirror\":\n\n1. Check if file exists:\n ```bash\n test -f {file-path} && echo \"EXISTS\" || echo \"MISSING\"\n ```\n\n2. If exists, read the referenced lines:\n ```bash\n sed -n '{start},{end}p' {file-path}\n ```\n\n3. Compare with what the plan expected (if plan included code snippets)\n\n### 2.2 Document Findings\n\nFor each pattern file:\n\n| File | Status | Notes |\n|------|--------|-------|\n| `src/adapters/telegram.ts` | ✅ EXISTS | Lines 11-23 match expected pattern |\n| `src/types/index.ts` | ✅ EXISTS | Interface still present |\n| `src/old-file.ts` | ❌ MISSING | File was renamed/deleted |\n| `src/changed.ts` | ⚠️ DRIFTED | Code structure changed significantly |\n\n### 2.3 Severity Assessment\n\n| Finding | Severity | Action |\n|---------|----------|--------|\n| File exists, code matches | ✅ OK | Proceed |\n| File exists, minor differences | ⚠️ WARNING | Note in artifact, proceed with caution |\n| File exists, major drift | 🟠 CONCERN | Flag for review, may need plan update |\n| File missing | ❌ BLOCKER | Stop, plan needs revision |\n\n**PHASE_2_CHECKPOINT:**\n\n- [ ] All pattern files checked\n- [ ] Findings documented\n- [ ] Severity assessed\n\n---\n\n## Phase 3: VERIFY - Check Target Locations\n\n### 3.1 Check Files to Create\n\nFor each file marked CREATE:\n\n1. Verify it doesn't already exist (would be unexpected):\n ```bash\n test -f {file-path} && echo \"ALREADY EXISTS\" || echo \"OK - will create\"\n ```\n\n2. Verify parent directory exists or can be created:\n ```bash\n dirname {file-path} | xargs test -d && echo \"DIR EXISTS\" || echo \"DIR WILL BE CREATED\"\n ```\n\n### 3.2 Check Files to Update\n\nFor each file marked UPDATE:\n\n1. Verify it exists:\n ```bash\n test -f {file-path} && echo \"EXISTS\" || echo \"MISSING\"\n ```\n\n2. If the plan references specific lines/functions, verify they exist\n\n**PHASE_3_CHECKPOINT:**\n\n- [ ] CREATE targets verified (don't exist yet)\n- [ ] UPDATE targets verified (do exist)\n\n---\n\n## Phase 4: VERIFY - Check Validation Commands\n\n### 4.1 Dry Run Validation Commands\n\nTest that the validation commands work (without expecting them to pass):\n\n```bash\n# Check type-check command exists\nbun run type-check --help 2>/dev/null || echo \"type-check not available\"\n\n# Check lint command exists\nbun run lint --help 2>/dev/null || echo \"lint not available\"\n\n# Check test command exists\nbun test --help 2>/dev/null || echo \"test not available\"\n```\n\n### 4.2 Document Command Availability\n\n| Command | Status |\n|---------|--------|\n| `bun run type-check` | ✅ Available |\n| `bun run lint` | ✅ Available |\n| `bun test` | ✅ Available |\n| `bun run build` | ✅ Available |\n\n**PHASE_4_CHECKPOINT:**\n\n- [ ] Validation commands tested\n- [ ] All required commands available\n\n---\n\n## Phase 5: ARTIFACT - Write Confirmation\n\n### 5.1 Write Confirmation Artifact\n\nWrite to `$ARTIFACTS_DIR/plan-confirmation.md`:\n\n```markdown\n# Plan Confirmation\n\n**Generated**: {YYYY-MM-DD HH:MM}\n**Workflow ID**: $WORKFLOW_ID\n**Status**: {CONFIRMED | WARNINGS | BLOCKED}\n\n---\n\n## Pattern Verification\n\n| Pattern | File | Status | Notes |\n|---------|------|--------|-------|\n| Constructor pattern | `src/adapters/telegram.ts:11-23` | ✅ | Matches expected |\n| Interface definition | `src/types/index.ts:49-74` | ✅ | Present |\n| ... | ... | ... | ... |\n\n**Pattern Summary**: {X} of {Y} patterns verified\n\n---\n\n## Target Files\n\n### Files to Create\n\n| File | Status |\n|------|--------|\n| `src/new-file.ts` | ✅ Does not exist (ready to create) |\n\n### Files to Update\n\n| File | Status |\n|------|--------|\n| `src/existing.ts` | ✅ Exists |\n\n---\n\n## Validation Commands\n\n| Command | Available |\n|---------|-----------|\n| `bun run type-check` | ✅ |\n| `bun run lint` | ✅ |\n| `bun test` | ✅ |\n| `bun run build` | ✅ |\n\n---\n\n## Issues Found\n\n{If no issues:}\nNo issues found. Plan research is valid.\n\n{If issues:}\n### Warnings\n\n- **{file}**: {description of drift or concern}\n\n### Blockers\n\n- **{file}**: {description of missing file or critical issue}\n\n---\n\n## Recommendation\n\n{One of:}\n- ✅ **PROCEED**: Plan research is valid, continue to implementation\n- ⚠️ **PROCEED WITH CAUTION**: Minor drift detected, implementation may need adjustments\n- ❌ **STOP**: Critical issues found, plan needs revision\n\n---\n\n## Next Step\n\n{If PROCEED or PROCEED WITH CAUTION:}\nContinue to `archon-implement-tasks` to execute the plan.\n\n{If STOP:}\nRevise the plan to address blockers, then re-run `archon-plan-setup`.\n```\n\n**PHASE_5_CHECKPOINT:**\n\n- [ ] Confirmation artifact written\n- [ ] Status clearly indicated\n- [ ] Issues documented\n\n---\n\n## Phase 6: OUTPUT - Report to User\n\n### If Confirmed (no blockers):\n\n```markdown\n## Plan Confirmed ✅\n\n**Workflow ID**: `$WORKFLOW_ID`\n**Status**: Ready for implementation\n\n### Verification Summary\n\n| Check | Result |\n|-------|--------|\n| Pattern files | ✅ {X}/{Y} verified |\n| Target files | ✅ Ready |\n| Validation commands | ✅ Available |\n\n{If warnings:}\n### Warnings\n\n- {warning 1}\n- {warning 2}\n\nThese are minor and shouldn't block implementation.\n\n### Artifact\n\nConfirmation written to: `$ARTIFACTS_DIR/plan-confirmation.md`\n\n### Next Step\n\nProceed to `archon-implement-tasks` to execute the plan.\n```\n\n### If Blocked:\n\n```markdown\n## Plan Blocked ❌\n\n**Workflow ID**: `$WORKFLOW_ID`\n**Status**: Cannot proceed\n\n### Blockers Found\n\n1. **{file}**: {description}\n2. **{file}**: {description}\n\n### Required Action\n\nThe plan references files or patterns that no longer exist. Options:\n\n1. **Update the plan** to reflect current codebase state\n2. **Restore missing files** if they were accidentally deleted\n3. **Re-run planning** with `/archon-plan` to generate a fresh plan\n\n### Artifact\n\nDetails written to: `$ARTIFACTS_DIR/plan-confirmation.md`\n```\n\n---\n\n## Success Criteria\n\n- **PATTERNS_VERIFIED**: All pattern files exist and are reasonably similar\n- **TARGETS_VALID**: CREATE files don't exist, UPDATE files do exist\n- **COMMANDS_AVAILABLE**: Validation commands can be run\n- **ARTIFACT_WRITTEN**: Confirmation artifact created with clear status\n", + "archon-create-plan": "---\ndescription: Create comprehensive feature implementation plan with codebase analysis and research\nargument-hint: \n---\n\n# Create Implementation Plan\n\n**Input**: $ARGUMENTS\n**Workflow ID**: $WORKFLOW_ID\n\n---\n\n## Your Mission\n\nTransform \"$ARGUMENTS\" into a battle-tested implementation plan through systematic codebase exploration, pattern extraction, and strategic research.\n\n**Core Principle**: PLAN ONLY - no code written. Create a context-rich document that enables one-pass implementation success.\n\n**Execution Order**: CODEBASE FIRST, RESEARCH SECOND. Solutions must fit existing patterns before introducing new ones.\n\n**Agent Strategy**: Use Task tool with subagent_type=\"Explore\" for codebase intelligence gathering. This ensures thorough pattern discovery before any external research.\n\n**Output**: `$ARTIFACTS_DIR/plan.md`\n\n---\n\n## Phase 0: DETECT - Input Type Resolution\n\n### 0.1 Determine Input Type\n\n| Input Pattern | Type | Action |\n|---------------|------|--------|\n| Ends with `.prd.md` | PRD file | Parse PRD, select next phase |\n| Ends with `.md` and contains \"Implementation Phases\" | PRD file | Parse PRD, select next phase |\n| File path that exists | Document | Read and extract feature description |\n| Free-form text | Description | Use directly as feature input |\n| Empty/blank | Error | STOP - require input |\n\n### 0.2 If PRD File Detected\n\n1. **Read the PRD file**\n2. **Parse the Implementation Phases table** - find rows with `Status: pending`\n3. **Check dependencies** - only select phases whose dependencies are `complete`\n4. **Select the next actionable phase:**\n - First pending phase with all dependencies complete\n - If multiple candidates with same dependencies, note parallelism opportunity\n\n5. **Extract phase context:**\n ```\n PHASE: {phase number and name}\n GOAL: {from phase details}\n SCOPE: {from phase details}\n SUCCESS SIGNAL: {from phase details}\n PRD CONTEXT: {problem statement, user, hypothesis from PRD}\n ```\n\n6. **Report selection to user:**\n ```\n PRD: {prd file path}\n Selected Phase: #{number} - {name}\n\n {If parallel phases available:}\n Note: Phase {X} can also run in parallel (in separate worktree).\n\n Proceeding with Phase #{number}...\n ```\n\n### 0.3 If Free-form Description\n\nProceed directly to Phase 1 with the input as feature description.\n\n**PHASE_0_CHECKPOINT:**\n\n- [ ] Input type determined\n- [ ] If PRD: next phase selected and dependencies verified\n- [ ] Feature description ready for Phase 1\n\n---\n\n## Phase 1: PARSE - Feature Understanding\n\n### 1.1 Discover Project Structure\n\n**CRITICAL**: Do NOT assume `src/` exists. Discover actual structure:\n\n```bash\n# List root contents\nls -la\n\n# Find main source directories\nls -la */ 2>/dev/null | head -50\n\n# Identify project type from config files\ncat package.json 2>/dev/null | head -20\ncat pyproject.toml 2>/dev/null | head -20\ncat Cargo.toml 2>/dev/null | head -20\ncat go.mod 2>/dev/null | head -20\n```\n\nCommon alternatives to `src/`:\n- `app/` (Next.js, Rails, Laravel)\n- `lib/` (Ruby gems, Elixir)\n- `packages/` (monorepos)\n- `cmd/`, `internal/`, `pkg/` (Go)\n- Root-level source files (Python, scripts)\n\n### 1.2 Read CLAUDE.md\n\n```bash\ncat CLAUDE.md\n```\n\nNote all coding standards, patterns, and rules that apply to this codebase.\n\n### 1.3 Extract from Input\n\n- Core problem being solved\n- User value and business impact\n- Feature type: NEW_CAPABILITY | ENHANCEMENT | REFACTOR | BUG_FIX\n- Complexity: LOW | MEDIUM | HIGH\n- Affected systems list\n\n### 1.4 Formulate User Story\n\n```\nAs a \nI want to \nSo that \n```\n\n**PHASE_1_CHECKPOINT:**\n\n- [ ] Project structure discovered\n- [ ] CLAUDE.md rules noted\n- [ ] Problem statement is specific and testable\n- [ ] User story follows correct format\n- [ ] Complexity assessment has rationale\n- [ ] Affected systems identified\n\n**GATE**: If requirements are AMBIGUOUS → STOP and ASK user for clarification before proceeding.\n\n---\n\n## Phase 2: EXPLORE - Codebase Intelligence\n\n**CRITICAL: Use Task tool with subagent_type=\"Explore\" with thoroughness=\"very thorough\"**\n\n### 2.1 Launch Explore Agent\n\n```\nExplore the codebase to find patterns, conventions, and integration points\nrelevant to implementing: [feature description].\n\nDISCOVER:\n1. Similar implementations - find analogous features with file:line references\n2. Naming conventions - extract actual examples of function/class/file naming\n3. Error handling patterns - how errors are created, thrown, caught\n4. Logging patterns - logger usage, message formats\n5. Type definitions - relevant interfaces and types\n6. Test patterns - test file structure, assertion styles\n7. Integration points - where new code connects to existing\n8. Dependencies - relevant libraries already in use\n\nReturn ACTUAL code snippets from codebase, not generic examples.\n```\n\n### 2.2 Document Discoveries\n\n**Format in table:**\n\n| Category | File:Lines | Pattern Description | Code Snippet |\n|----------|------------|---------------------|--------------|\n| NAMING | `src/features/X/service.ts:10-15` | camelCase functions | `export function createThing()` |\n| ERRORS | `src/features/X/errors.ts:5-20` | Custom error classes | `class ThingNotFoundError` |\n| LOGGING | `src/core/logging/index.ts:1-10` | getLogger pattern | `const logger = getLogger(\"domain\")` |\n| TESTS | `src/features/X/tests/service.test.ts:1-30` | describe/it blocks | `describe(\"service\", () => {` |\n| TYPES | `src/features/X/models.ts:1-20` | Type inference | `type Thing = typeof things.$inferSelect` |\n\n**PHASE_2_CHECKPOINT:**\n\n- [ ] Explore agent launched and completed successfully\n- [ ] At least 3 similar implementations found with file:line refs\n- [ ] Code snippets are ACTUAL (copy-pasted from codebase, not invented)\n- [ ] Integration points mapped with specific file paths\n- [ ] Dependencies cataloged with versions from package.json\n\n---\n\n## Phase 3: RESEARCH - External Documentation\n\n**ONLY AFTER Phase 2 is complete** - solutions must fit existing codebase patterns first.\n\n### 3.1 Search for Documentation\n\nUse WebSearch tool for:\n- Official documentation for involved libraries (match versions from package.json)\n- Known gotchas, breaking changes, deprecations\n- Security considerations and best practices\n- Performance optimization patterns\n\n### 3.2 Format References\n\n```markdown\n- [Library Docs v{version}](https://url#specific-section)\n - KEY_INSIGHT: {what we learned that affects implementation}\n - APPLIES_TO: {which task/file this affects}\n - GOTCHA: {potential pitfall and how to avoid}\n```\n\n**PHASE_3_CHECKPOINT:**\n\n- [ ] Documentation versions match package.json\n- [ ] URLs include specific section anchors (not just homepage)\n- [ ] Gotchas documented with mitigation strategies\n- [ ] No conflicting patterns between external docs and existing codebase\n\n---\n\n## Phase 4: DESIGN - UX Transformation\n\n### 4.1 Create ASCII Diagrams\n\n**Before State:**\n\n```\n╔═══════════════════════════════════════════════════════════════════════════════╗\n║ BEFORE STATE ║\n╠═══════════════════════════════════════════════════════════════════════════════╣\n║ ║\n║ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ║\n║ │ Screen/ │ ──────► │ Action │ ──────► │ Result │ ║\n║ │ Component │ │ Current │ │ Current │ ║\n║ └─────────────┘ └─────────────┘ └─────────────┘ ║\n║ ║\n║ USER_FLOW: [describe current step-by-step experience] ║\n║ PAIN_POINT: [what's missing, broken, or inefficient] ║\n║ DATA_FLOW: [how data moves through the system currently] ║\n║ ║\n╚═══════════════════════════════════════════════════════════════════════════════╝\n```\n\n**After State:**\n\n```\n╔═══════════════════════════════════════════════════════════════════════════════╗\n║ AFTER STATE ║\n╠═══════════════════════════════════════════════════════════════════════════════╣\n║ ║\n║ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ║\n║ │ Screen/ │ ──────► │ Action │ ──────► │ Result │ ║\n║ │ Component │ │ NEW │ │ NEW │ ║\n║ └─────────────┘ └─────────────┘ └─────────────┘ ║\n║ │ ║\n║ ▼ ║\n║ ┌─────────────┐ ║\n║ │ NEW_FEATURE │ ◄── [new capability added] ║\n║ └─────────────┘ ║\n║ ║\n║ USER_FLOW: [describe new step-by-step experience] ║\n║ VALUE_ADD: [what user gains from this change] ║\n║ DATA_FLOW: [how data moves through the system after] ║\n║ ║\n╚═══════════════════════════════════════════════════════════════════════════════╝\n```\n\n### 4.2 Document Interaction Changes\n\n| Location | Before | After | User_Action | Impact |\n|----------|--------|-------|-------------|--------|\n| `/route` | State A | State B | Click X | Can now Y |\n| `Component.tsx` | Missing feature | Has feature | Input Z | Gets result W |\n\n**PHASE_4_CHECKPOINT:**\n\n- [ ] Before state accurately reflects current system behavior\n- [ ] After state shows ALL new capabilities\n- [ ] Data flows are traceable from input to output\n- [ ] User value is explicit and measurable\n\n---\n\n## Phase 5: ARCHITECT - Strategic Design\n\n### 5.0 Primitives Inventory\n\nBefore designing the solution, audit existing building blocks:\n\n1. **What primitives already exist?** List the core abstractions in the codebase\n related to this feature — with file:line references from the Explore agent output.\n2. **Are they complete?** Do the existing primitives cover this use case, or do they\n have gaps that require extension?\n3. **Extend before adding** — can we extend an existing primitive rather than creating\n a new one? Prefer `implements ExistingInterface` over `interface NewInterface`.\n4. **Minimum primitive surface** — if new primitives ARE needed, what's the smallest\n addition that enables this feature and remains useful to future callers?\n5. **Dependency chain** — what must exist first? What does this feature unlock downstream?\n\n| Primitive | File:Lines | Complete? | Role in Feature |\n|-----------|-----------|-----------|----------------|\n| {name} | `path/to/file.ts:10-30` | Yes/Partial/No | {how it's used or extended} |\n\n### 5.1 Deep Analysis\n\nConsider (use extended thinking if needed):\n\n- **ARCHITECTURE_FIT**: How does this integrate with the existing architecture?\n- **EXECUTION_ORDER**: What must happen first → second → third?\n- **FAILURE_MODES**: Edge cases, race conditions, error scenarios?\n- **PERFORMANCE**: Will this scale? Database queries optimized?\n- **SECURITY**: Attack vectors? Data exposure risks? Auth/authz?\n- **MAINTAINABILITY**: Will future devs understand this code?\n\n### 5.2 Document Decisions\n\n```markdown\nAPPROACH_CHOSEN: [description]\nRATIONALE: [why this over alternatives - reference codebase patterns]\n\nALTERNATIVES_REJECTED:\n- [Alternative 1]: Rejected because [specific reason]\n- [Alternative 2]: Rejected because [specific reason]\n\nNOT_BUILDING (explicit scope limits):\n- [Item 1 - explicitly out of scope and why]\n- [Item 2 - explicitly out of scope and why]\n```\n\n**PHASE_5_CHECKPOINT:**\n\n- [ ] Approach aligns with existing architecture and patterns\n- [ ] Dependencies ordered correctly (types → repository → service → routes)\n- [ ] Edge cases identified with specific mitigation strategies\n- [ ] Scope boundaries are explicit and justified\n\n---\n\n## Phase 6: GENERATE - Write Plan File\n\n### 6.1 Create Artifact Directory\n\n```bash\n```\n\n### 6.2 Write Plan\n\nWrite to `$ARTIFACTS_DIR/plan.md`:\n\n```markdown\n# Feature: {Feature Name}\n\n## Summary\n\n{One paragraph: What we're building and high-level approach}\n\n## User Story\n\nAs a {user type}\nI want to {action}\nSo that {benefit}\n\n## Problem Statement\n\n{Specific problem this solves - must be testable}\n\n## Solution Statement\n\n{How we're solving it - architecture overview}\n\n## Metadata\n\n| Field | Value |\n|-------|-------|\n| Type | NEW_CAPABILITY / ENHANCEMENT / REFACTOR / BUG_FIX |\n| Complexity | LOW / MEDIUM / HIGH |\n| Systems Affected | {comma-separated list} |\n| Dependencies | {external libs/services with versions} |\n| Estimated Tasks | {count} |\n\n---\n\n## UX Design\n\n### Before State\n\n{ASCII diagram - current user experience with data flows}\n\n### After State\n\n{ASCII diagram - new user experience with data flows}\n\n### Interaction Changes\n\n| Location | Before | After | User Impact |\n|----------|--------|-------|-------------|\n| {path/component} | {old behavior} | {new behavior} | {what changes for user} |\n\n---\n\n## Mandatory Reading\n\n**CRITICAL: Implementation agent MUST read these files before starting any task:**\n\n| Priority | File | Lines | Why Read This |\n|----------|------|-------|---------------|\n| P0 | `path/to/critical.ts` | 10-50 | Pattern to MIRROR exactly |\n| P1 | `path/to/types.ts` | 1-30 | Types to IMPORT |\n| P2 | `path/to/test.ts` | all | Test pattern to FOLLOW |\n\n**External Documentation:**\n\n| Source | Section | Why Needed |\n|--------|---------|------------|\n| [Lib Docs v{version}](url#anchor) | {section name} | {specific reason} |\n\n---\n\n## Patterns to Mirror\n\n**NAMING_CONVENTION:**\n```typescript\n// SOURCE: {file:lines}\n// COPY THIS PATTERN:\n{actual code snippet from codebase}\n```\n\n**ERROR_HANDLING:**\n```typescript\n// SOURCE: {file:lines}\n// COPY THIS PATTERN:\n{actual code snippet from codebase}\n```\n\n**LOGGING_PATTERN:**\n```typescript\n// SOURCE: {file:lines}\n// COPY THIS PATTERN:\n{actual code snippet from codebase}\n```\n\n**TEST_STRUCTURE:**\n```typescript\n// SOURCE: {file:lines}\n// COPY THIS PATTERN:\n{actual code snippet from codebase}\n```\n\n---\n\n## Files to Change\n\n| File | Action | Justification |\n|------|--------|---------------|\n| `src/features/new/models.ts` | CREATE | Type definitions |\n| `src/features/new/service.ts` | CREATE | Business logic |\n| `src/existing/index.ts` | UPDATE | Add integration |\n\n---\n\n## NOT Building (Scope Limits)\n\nExplicit exclusions to prevent scope creep:\n\n- {Item 1 - explicitly out of scope and why}\n- {Item 2 - explicitly out of scope and why}\n\n---\n\n## Step-by-Step Tasks\n\nExecute in order. Each task is atomic and independently verifiable.\n\n### Task 1: {CREATE/UPDATE} `{file path}`\n\n- **ACTION**: {CREATE new file / UPDATE existing file}\n- **IMPLEMENT**: {specific what to implement}\n- **MIRROR**: `{source-file:lines}` - follow this pattern exactly\n- **IMPORTS**: `{specific imports needed}`\n- **GOTCHA**: {known issue to avoid}\n- **VALIDATE**: `{validation-command}` - must pass before next task\n\n### Task 2: {CREATE/UPDATE} `{file path}`\n\n{... repeat for each task ...}\n\n---\n\n## Testing Strategy\n\n### Unit Tests to Write\n\n| Test File | Test Cases | Validates |\n|-----------|------------|-----------|\n| `src/features/new/tests/service.test.ts` | CRUD ops, edge cases | Business logic |\n\n### Edge Cases Checklist\n\n- [ ] Empty string inputs\n- [ ] Missing required fields\n- [ ] Unauthorized access attempts\n- [ ] Not found scenarios\n- [ ] {feature-specific edge case}\n\n---\n\n## Validation Commands\n\n### Level 1: STATIC_ANALYSIS\n\n```bash\n{runner} run type-check && {runner} run lint\n```\n\n**EXPECT**: Exit 0, no errors or warnings\n\n### Level 2: UNIT_TESTS\n\n```bash\n{runner} test {path/to/feature/tests}\n```\n\n**EXPECT**: All tests pass\n\n### Level 3: FULL_SUITE\n\n```bash\n{runner} run validate\n```\n\n**EXPECT**: All tests pass, build succeeds\n\n---\n\n## Acceptance Criteria\n\n- [ ] All specified functionality implemented per user story\n- [ ] Level 1-3 validation commands pass with exit 0\n- [ ] Code mirrors existing patterns exactly (naming, structure, logging)\n- [ ] No regressions in existing tests\n- [ ] UX matches \"After State\" diagram\n\n---\n\n## Completion Checklist\n\n- [ ] All tasks completed in dependency order\n- [ ] Each task validated immediately after completion\n- [ ] All acceptance criteria met\n\n---\n\n## Risks and Mitigations\n\n| Risk | Likelihood | Impact | Mitigation |\n|------|------------|--------|------------|\n| {Risk description} | LOW/MED/HIGH | LOW/MED/HIGH | {Specific prevention/handling strategy} |\n\n---\n\n## Notes\n\n{Additional context, design decisions, trade-offs, future considerations}\n```\n\n### 6.3 If Input Was PRD\n\nAlso update the PRD file:\n1. Change the phase's Status from `pending` to `in-progress`\n2. Add the plan file path to the PRP Plan column\n\n**PHASE_6_CHECKPOINT:**\n\n- [ ] Plan file written to `$ARTIFACTS_DIR/plan.md`\n- [ ] All sections populated with actual codebase data\n- [ ] If PRD: source file updated\n\n---\n\n## Phase 7: VERIFY - Plan Quality Check\n\n### 7.1 Context Completeness\n\n- [ ] All patterns from Explore agent documented with file:line references\n- [ ] External docs versioned to match package.json\n- [ ] Integration points mapped with specific file paths\n- [ ] Gotchas captured with mitigation strategies\n- [ ] Every task has at least one executable validation command\n\n### 7.2 Implementation Readiness\n\n- [ ] Tasks ordered by dependency (can execute top-to-bottom)\n- [ ] Each task is atomic and independently testable\n- [ ] No placeholders - all content is specific and actionable\n- [ ] Pattern references include actual code snippets (copy-pasted, not invented)\n\n### 7.3 Pattern Faithfulness\n\n- [ ] Every new file mirrors existing codebase style exactly\n- [ ] No unnecessary abstractions introduced\n- [ ] Naming follows discovered conventions\n- [ ] Error/logging patterns match existing\n- [ ] Test structure matches existing tests\n\n### 7.4 No Prior Knowledge Test\n\n**Could an agent unfamiliar with this codebase implement using ONLY the plan?**\n\nIf NO → add missing context to plan.\n\n**PHASE_7_CHECKPOINT:**\n\n- [ ] All verification checks pass\n- [ ] Plan is self-contained\n\n---\n\n## Phase 8: OUTPUT - Report to User\n\n```markdown\n## Plan Created\n\n**File**: `$ARTIFACTS_DIR/plan.md`\n**Workflow ID**: `$WORKFLOW_ID`\n\n{If from PRD:}\n**Source PRD**: `{prd-file-path}`\n**Phase**: #{number} - {phase name}\n**PRD Updated**: Status set to `in-progress`, plan linked\n\n{If parallel phases available:}\n**Parallel Opportunity**: Phase {X} can run concurrently in a separate worktree.\n\n---\n\n### Summary\n\n{2-3 sentence feature overview}\n\n### Metadata\n\n| Field | Value |\n|-------|-------|\n| Complexity | {LOW/MEDIUM/HIGH} |\n| Files to CREATE | {N} |\n| Files to UPDATE | {M} |\n| Total Tasks | {K} |\n\n### Key Patterns Discovered\n\n- {Pattern 1 from Explore agent with file:line}\n- {Pattern 2 from Explore agent with file:line}\n- {Pattern 3 from Explore agent with file:line}\n\n### External Research\n\n- {Key doc 1 with version}\n- {Key doc 2 with version}\n\n### UX Transformation\n\n- **BEFORE**: {one-line current state}\n- **AFTER**: {one-line new state}\n\n### Risks\n\n- {Primary risk}: {mitigation}\n\n### Confidence Score\n\n**{1-10}/10** for one-pass implementation success\n\n{Rationale for score}\n\n---\n\n### Next Step\n\nPlan ready. Proceeding to implementation setup.\n```\n\n---\n\n## Success Criteria\n\n- **CONTEXT_COMPLETE**: All patterns, gotchas, integration points documented from actual codebase via Explore agent\n- **IMPLEMENTATION_READY**: Tasks executable top-to-bottom without questions, research, or clarification\n- **PATTERN_FAITHFUL**: Every new file mirrors existing codebase style exactly\n- **VALIDATION_DEFINED**: Every task has executable verification command\n- **UX_DOCUMENTED**: Before/After transformation is visually clear with data flows\n- **ONE_PASS_TARGET**: Confidence score 8+ indicates high likelihood of first-attempt success\n- **ARTIFACT_WRITTEN**: Plan saved to `$ARTIFACTS_DIR/plan.md`\n", + "archon-create-pr": "---\ndescription: Create a PR from current branch with implementation context\nargument-hint: [base-branch] (default: auto-detected from config or repo)\n---\n\n# Create Pull Request\n\n**Base branch override**: $ARGUMENTS\n**Default base branch**: $BASE_BRANCH\n\n> If a base branch was provided as argument above, use it for `--base`. Otherwise use the default base branch.\n\n---\n\n## Pre-flight: Check for Existing PRs\n\nExtract the issue number from the current branch name or context (e.g., `fix/issue-580` → `580`).\n\n```bash\nBRANCH=$(git branch --show-current)\nISSUE_NUM=$(echo \"$BRANCH\" | grep -oE '[0-9]+' | tail -1)\n```\n\nIf an issue number was found, search for open PRs that already reference it:\n\n```bash\ngh pr list \\\n --search \"Fixes #${ISSUE_NUM} OR Closes #${ISSUE_NUM}\" \\\n --state open \\\n --json number,url,headRefName\n```\n\n**If a matching PR is returned**: stop here, report the existing PR URL, and do **not** proceed to Phase 2 or Phase 3.\n\n```\nExisting PR found for issue #${ISSUE_NUM}: [url]\nSkipping PR creation.\n```\n\n**If no match is found** (or no issue number could be extracted): continue to Phase 1.\n\n---\n\n## Phase 1: Gather Context\n\n### 1.1 Check Git State\n\n```bash\ngit branch --show-current\ngit status --short\ngit log origin/$BASE_BRANCH..HEAD --oneline\n```\n\n### 1.2 Check for Implementation Report\n\nLook for the most recent implementation report:\n\n```bash\nls -t $ARTIFACTS_DIR/../reports/*-report.md 2>/dev/null | head -1\n```\n\nIf found, read it to extract:\n- Summary of what was implemented\n- Files changed\n- Validation results\n- Any deviations from plan\n\n### 1.3 Get Commit Summary\n\n```bash\ngit log origin/$BASE_BRANCH..HEAD --pretty=format:\"- %s\"\n```\n\n---\n\n## Phase 2: Prepare Branch\n\n### 2.1 Ensure All Changes Committed\n\nIf uncommitted changes exist:\n\n```bash\ngit status --porcelain\n```\n\n**If dirty**:\n1. Stage changes: `git add -A`\n2. Commit: `git commit -m \"Final changes before PR\"`\n\n### 2.2 Push Branch\n\n```bash\ngit push -u origin HEAD\n```\n\n---\n\n## Phase 3: Create PR\n\n### 3.1 Check for PR Template\n\nLook for the project's PR template at `.github/pull_request_template.md`, `.github/PULL_REQUEST_TEMPLATE.md`, or `docs/PULL_REQUEST_TEMPLATE.md`. Read whichever one exists.\n\n**If template found**: Use it as the structure, fill in **every section** with details from the implementation report and commits. Don't skip sections or leave placeholders.\n\n**If no template**, use this format:\n\n```markdown\n## Summary\n\n[Brief description from implementation report or commits]\n\n## Changes\n\n[List from implementation report \"Files Changed\" section, or from commits]\n- file1.ts - description\n- file2.ts - description\n\n## Validation\n\n[From implementation report \"Validation Results\" section]\n- [x] Type check passes\n- [x] Lint passes\n- [x] Tests pass\n- [x] Build succeeds\n\n## Testing Notes\n\n[Any manual testing done or integration test results]\n\n---\n\n[If from a GitHub issue, add: Closes #XXX]\n```\n\n### 3.2 Determine PR Title\n\n**Title**: Concise, imperative mood\n- From implementation report summary, OR\n- From commit messages\n\n### 3.3 Create the PR\n\n```bash\n# Write body to file to avoid shell escaping\ncat > $ARTIFACTS_DIR/pr-body.md <<'EOF'\n[body from above]\nEOF\n\ngh pr create \\\n --title \"[title]\" \\\n --body-file $ARTIFACTS_DIR/pr-body.md \\\n --base $BASE_BRANCH\n```\n\nOr if the content is simple:\n\n```bash\ngh pr create --fill --base $BASE_BRANCH\n```\n\nAfter creating the PR, capture its identifiers for downstream steps. Only write artifacts if PR creation succeeded — never persist stale data from a pre-existing PR:\n\n```bash\n# After creating the PR, capture and persist the PR number for downstream steps\n# IMPORTANT: Only write artifacts after confirmed successful PR creation\nif gh pr view --json number,url -q '.number,.url' > /dev/null 2>&1; then\n PR_NUMBER=$(gh pr view --json number -q '.number')\n PR_URL=$(gh pr view --json url -q '.url')\n echo \"$PR_NUMBER\" > \"$ARTIFACTS_DIR/.pr-number\"\n echo \"$PR_URL\" > \"$ARTIFACTS_DIR/.pr-url\"\nelse\n echo \"WARNING: Could not confirm PR creation; skipping .pr-number/.pr-url artifacts\"\nfi\n```\n\n---\n\n## Phase 4: Output\n\nReport the result:\n\n```markdown\n## PR Created\n\n**URL**: [PR URL]\n**Branch**: [branch-name] → [base-branch]\n**Title**: [PR title]\n\n### Summary\n[Brief summary of what the PR contains]\n\n### Next Steps\n1. Request review if needed\n2. Address any CI failures\n3. Merge when approved\n```\n\n---\n\n## Error Handling\n\n### No Commits to Push\n\n```\nNo commits between origin/$BASE_BRANCH and HEAD.\nNothing to create a PR for.\n```\n\n### Branch Already Has PR\n\n```bash\ngh pr view --web\n```\n\nOpens the existing PR instead of creating a duplicate.\n\n### Push Fails\n\n1. Check if branch exists remotely: `git ls-remote --heads origin [branch]`\n2. If conflicts: `git pull --rebase origin $BASE_BRANCH` then retry push\n3. If permission issues: Check GitHub access\n", + "archon-docs-impact-agent": "---\ndescription: Check if PR changes require documentation updates (CLAUDE.md, docs/, agents)\nargument-hint: (none - reads from scope artifact)\n---\n\n# Documentation Impact Agent\n\n---\n\n## Your Mission\n\nAnalyze if the PR changes require updates to project documentation: CLAUDE.md, docs/ folder, agent definitions, or other documentation. Produce a structured artifact with recommendations.\n\n**Output artifact**: `$ARTIFACTS_DIR/review/docs-impact-findings.md`\n\n---\n\n## Phase 1: LOAD - Get Context\n\n### 1.1 Get PR Number from Registry\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number)\n```\n\n### 1.2 Read Scope\n\n```bash\ncat $ARTIFACTS_DIR/review/scope.md\n```\n\n**CRITICAL**: Check for \"NOT Building (Scope Limits)\" section. Items listed there are **intentionally excluded** - do NOT flag them as missing documentation needs!\n\n### 1.3 Get PR Diff\n\n```bash\ngh pr diff {number}\n```\n\n### 1.4 Read Current Documentation\n\n```bash\n# Read CLAUDE.md\ncat CLAUDE.md\n\n# List docs folder\nls -la $DOCS_DIR\n\n# List agent definitions\nls -la .claude/agents/ 2>/dev/null || true\nls -la .archon/commands/ 2>/dev/null || true\n```\n\n**PHASE_1_CHECKPOINT:**\n- [ ] PR number identified\n- [ ] Changes understood\n- [ ] Current docs read\n\n---\n\n## Phase 2: ANALYZE - Check Documentation Impact\n\n### 2.1 CLAUDE.md Impact\n\nCheck if changes affect documented:\n- Commands or slash commands\n- Workflows\n- Development setup\n- Environment variables\n- Database schema\n- API endpoints\n- Testing instructions\n- Code patterns/standards\n\n### 2.2 docs/ Folder Impact\n\nCheck if changes affect:\n- Architecture documentation\n- Getting started guide\n- Configuration documentation\n- API documentation\n- Deployment instructions\n\n### 2.3 Agent/Command Definitions\n\nCheck if changes affect:\n- Agent capabilities\n- Command arguments\n- Workflow steps\n- Tool usage patterns\n\n### 2.4 README Impact\n\nCheck if changes affect:\n- Feature list\n- Installation instructions\n- Usage examples\n- Configuration options\n\n**PHASE_2_CHECKPOINT:**\n- [ ] CLAUDE.md impact assessed\n- [ ] docs/ impact assessed\n- [ ] Agent definitions checked\n- [ ] README checked\n\n---\n\n## Phase 3: GENERATE - Create Artifact\n\nWrite to `$ARTIFACTS_DIR/review/docs-impact-findings.md`:\n\n```markdown\n# Documentation Impact Findings: PR #{number}\n\n**Reviewer**: docs-impact-agent\n**Date**: {ISO timestamp}\n**Docs Checked**: CLAUDE.md, docs/, agents, README\n\n---\n\n## Summary\n\n{2-3 sentence overview of documentation impact}\n\n**Verdict**: {NO_CHANGES_NEEDED | UPDATES_REQUIRED | CRITICAL_UPDATES}\n\n---\n\n## Impact Assessment\n\n| Document | Impact | Required Update |\n|----------|--------|-----------------|\n| CLAUDE.md | NONE/LOW/HIGH | {description or \"None\"} |\n| $DOCS_DIR/architecture.md | NONE/LOW/HIGH | {description or \"None\"} |\n| $DOCS_DIR/configuration.md | NONE/LOW/HIGH | {description or \"None\"} |\n| README.md | NONE/LOW/HIGH | {description or \"None\"} |\n| .claude/agents/*.md | NONE/LOW/HIGH | {description or \"None\"} |\n| .archon/commands/*.md | NONE/LOW/HIGH | {description or \"None\"} |\n\n---\n\n## Findings\n\n### Finding 1: {Descriptive Title}\n\n**Severity**: CRITICAL | HIGH | MEDIUM | LOW\n**Category**: missing-docs | outdated-docs | incomplete-docs | misleading-docs\n**Document**: `{file path}`\n**PR Change**: `{source file}:{line}` - {what changed}\n\n**Issue**:\n{Clear description of why docs need updating}\n\n**Current Documentation**:\n```markdown\n{current text in docs}\n```\n\n**Code Change**:\n```typescript\n// What changed in the PR\n{new code that docs don't reflect}\n```\n\n**Impact if Not Updated**:\n{What happens if docs aren't updated - user confusion, wrong setup, etc.}\n\n---\n\n#### Update Suggestions\n\n| Option | Approach | Scope | Effort |\n|--------|----------|-------|--------|\n| A | {minimal update} | {what it covers} | LOW |\n| B | {comprehensive update} | {what it covers} | MED/HIGH |\n\n**Recommended**: Option {X}\n\n**Reasoning**:\n{Why this update approach:\n- Keeps docs accurate\n- Matches existing documentation style\n- Appropriate level of detail}\n\n**Suggested Documentation Update**:\n```markdown\n{what the docs should say after update}\n```\n\n**Documentation Style Reference**:\n```markdown\n# SOURCE: {doc file}\n# How similar features are documented\n{existing documentation pattern}\n```\n\n---\n\n### Finding 2: {Title}\n\n{Same structure...}\n\n---\n\n## CLAUDE.md Sections to Update\n\n| Section | Current | Needed Update |\n|---------|---------|---------------|\n| {section name} | {current text summary} | {what to add/change} |\n| ... | ... | ... |\n\n---\n\n## Statistics\n\n| Severity | Count | Documents Affected |\n|----------|-------|-------------------|\n| CRITICAL | {n} | {list} |\n| HIGH | {n} | {list} |\n| MEDIUM | {n} | {list} |\n| LOW | {n} | {list} |\n\n---\n\n## New Documentation Needed\n\n| Topic | Suggested Location | Priority |\n|-------|-------------------|----------|\n| {new feature/change} | {where to document} | HIGH/MED/LOW |\n| ... | ... | ... |\n\n---\n\n## Positive Observations\n\n{Documentation already updated in PR, good inline docs, etc.}\n\n---\n\n## Metadata\n\n- **Agent**: docs-impact-agent\n- **Timestamp**: {ISO timestamp}\n- **Artifact**: `$ARTIFACTS_DIR/review/docs-impact-findings.md`\n```\n\n**PHASE_3_CHECKPOINT:**\n- [ ] Artifact file created\n- [ ] All docs checked\n- [ ] Update suggestions provided\n- [ ] Existing doc style referenced\n\n---\n\n## Success Criteria\n\n- **DOCS_ANALYZED**: All relevant docs checked\n- **IMPACT_ASSESSED**: Each doc rated for impact\n- **UPDATES_SPECIFIED**: Clear update suggestions\n- **STYLE_MATCHED**: Suggestions match existing doc style\n", + "archon-error-handling-agent": "---\ndescription: Review error handling for silent failures, inadequate catch blocks, and poor fallbacks\nargument-hint: (none - reads from scope artifact)\n---\n\n# Error Handling Agent\n\n---\n\n## Your Mission\n\nHunt for silent failures, inadequate error handling, broad catch blocks, and inappropriate fallback behavior. Produce a structured artifact with findings, fix suggestions with options, and reasoning.\n\n**Output artifact**: `$ARTIFACTS_DIR/review/error-handling-findings.md`\n\n---\n\n## Phase 1: LOAD - Get Context\n\n### 1.1 Get PR Number from Registry\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number)\n```\n\n### 1.2 Read Scope\n\n```bash\ncat $ARTIFACTS_DIR/review/scope.md\n```\n\n**CRITICAL**: Check for \"NOT Building (Scope Limits)\" section. Items listed there are **intentionally excluded** - do NOT flag them as bugs or missing features!\n\n### 1.3 Get PR Diff\n\n```bash\ngh pr diff {number}\n```\n\n### 1.4 Read CLAUDE.md Error Handling Rules\n\n```bash\ncat CLAUDE.md | grep -A 20 -i \"error\"\n```\n\n**PHASE_1_CHECKPOINT:**\n- [ ] PR number identified\n- [ ] Scope loaded\n- [ ] Diff available\n\n---\n\n## Phase 2: ANALYZE - Hunt for Issues\n\n### 2.1 Find All Error Handling Code\n\nSearch for:\n- `try { ... } catch` blocks\n- `.catch(` handlers\n- `|| fallback` patterns\n- `?? defaultValue` patterns\n- `?.` optional chaining that might hide errors\n- Error event handlers\n- Conditional error state handling\n\n### 2.2 Scrutinize Each Handler\n\nFor every error handling location, evaluate:\n\n**Logging Quality:**\n- Is error logged with appropriate severity?\n- Does log include sufficient context?\n- Would this help debugging in 6 months?\n\n**User Feedback:**\n- Does user receive actionable feedback?\n- Is the error message specific and helpful?\n- Are technical details appropriately hidden/shown?\n\n**Catch Block Specificity:**\n- Does it catch only expected error types?\n- Could it accidentally suppress unrelated errors?\n- Should it be multiple catch blocks?\n\n**Fallback Behavior:**\n- Is fallback explicitly documented/intended?\n- Does fallback mask the underlying problem?\n- Is user aware they're seeing fallback behavior?\n\n### 2.3 Find Codebase Error Patterns\n\n```bash\n# Find error handling patterns in codebase\ngrep -r \"catch\" src/ --include=\"*.ts\" -A 3 | head -30\ngrep -r \"console.error\" src/ --include=\"*.ts\" -B 2 -A 2 | head -30\n```\n\n**PHASE_2_CHECKPOINT:**\n- [ ] All error handlers identified\n- [ ] Each handler evaluated\n- [ ] Codebase patterns found\n\n---\n\n## Phase 3: GENERATE - Create Artifact\n\nWrite to `$ARTIFACTS_DIR/review/error-handling-findings.md`:\n\n```markdown\n# Error Handling Findings: PR #{number}\n\n**Reviewer**: error-handling-agent\n**Date**: {ISO timestamp}\n**Error Handlers Reviewed**: {count}\n\n---\n\n## Summary\n\n{2-3 sentence overview of error handling quality}\n\n**Verdict**: {APPROVE | REQUEST_CHANGES | NEEDS_DISCUSSION}\n\n---\n\n## Findings\n\n### Finding 1: {Descriptive Title}\n\n**Severity**: CRITICAL | HIGH | MEDIUM | LOW\n**Category**: silent-failure | broad-catch | missing-logging | poor-user-feedback | unsafe-fallback\n**Location**: `{file}:{line}`\n\n**Issue**:\n{Clear description of the error handling problem}\n\n**Evidence**:\n```typescript\n// Current error handling at {file}:{line}\n{problematic code}\n```\n\n**Hidden Errors**:\nThis catch block could silently hide:\n- {Error type 1}: {scenario when it occurs}\n- {Error type 2}: {scenario when it occurs}\n- {Error type 3}: {scenario when it occurs}\n\n**User Impact**:\n{What happens to the user when this error occurs? Why is it bad?}\n\n---\n\n#### Fix Suggestions\n\n| Option | Approach | Pros | Cons |\n|--------|----------|------|------|\n| A | {e.g., Add specific error types} | {benefits} | {drawbacks} |\n| B | {e.g., Add logging + user message} | {benefits} | {drawbacks} |\n| C | {e.g., Propagate error instead} | {benefits} | {drawbacks} |\n\n**Recommended**: Option {X}\n\n**Reasoning**:\n{Explain why this option is preferred:\n- Aligns with project error handling patterns\n- Provides better debugging experience\n- Gives users actionable feedback\n- Follows CLAUDE.md rules}\n\n**Recommended Fix**:\n```typescript\n// Improved error handling\n{corrected code with proper logging, specific catches, user feedback}\n```\n\n**Codebase Pattern Reference**:\n```typescript\n// SOURCE: {file}:{lines}\n// This is how similar errors are handled elsewhere\n{existing error handling pattern from codebase}\n```\n\n---\n\n### Finding 2: {Title}\n\n{Same structure...}\n\n---\n\n## Error Handler Audit\n\n| Location | Type | Logging | User Feedback | Specificity | Verdict |\n|----------|------|---------|---------------|-------------|---------|\n| `file:line` | try-catch | GOOD/BAD | GOOD/BAD | GOOD/BAD | PASS/FAIL |\n| ... | ... | ... | ... | ... | ... |\n\n---\n\n## Statistics\n\n| Severity | Count | Auto-fixable |\n|----------|-------|--------------|\n| CRITICAL | {n} | {n} |\n| HIGH | {n} | {n} |\n| MEDIUM | {n} | {n} |\n| LOW | {n} | {n} |\n\n---\n\n## Silent Failure Risk Assessment\n\n| Risk | Likelihood | Impact | Mitigation |\n|------|------------|--------|------------|\n| {potential silent failure} | HIGH/MED/LOW | {user impact} | {fix needed} |\n| ... | ... | ... | ... |\n\n---\n\n## Patterns Referenced\n\n| File | Lines | Pattern |\n|------|-------|---------|\n| `src/example.ts` | 42-50 | {error handling pattern} |\n| ... | ... | ... |\n\n---\n\n## Positive Observations\n\n{Error handling done well, good patterns, proper logging}\n\n---\n\n## Metadata\n\n- **Agent**: error-handling-agent\n- **Timestamp**: {ISO timestamp}\n- **Artifact**: `$ARTIFACTS_DIR/review/error-handling-findings.md`\n```\n\n**PHASE_3_CHECKPOINT:**\n- [ ] Artifact file created\n- [ ] All error handlers audited\n- [ ] Hidden errors listed for each finding\n- [ ] Fix options with reasoning provided\n\n---\n\n## Success Criteria\n\n- **ERROR_HANDLERS_FOUND**: All try/catch, .catch, fallbacks identified\n- **EACH_HANDLER_AUDITED**: Logging, feedback, specificity evaluated\n- **HIDDEN_ERRORS_LISTED**: Each finding lists what could be hidden\n- **ARTIFACT_CREATED**: Findings file written with complete structure\n", + "archon-finalize-pr": "---\ndescription: Commit changes, create PR with template, mark ready for review\nargument-hint: (no arguments - reads from workflow artifacts)\n---\n\n# Finalize Pull Request\n\n**Workflow ID**: $WORKFLOW_ID\n\n---\n\n## Your Mission\n\nFinalize the implementation and create the PR:\n1. Commit all changes\n2. Push to remote\n3. Create PR using project's template (if exists)\n4. Mark PR as ready for review\n\n---\n\n## Phase 1: LOAD - Gather Context\n\n### 1.1 Load Workflow Artifacts\n\n```bash\ncat $ARTIFACTS_DIR/plan-context.md\ncat $ARTIFACTS_DIR/implementation.md\ncat $ARTIFACTS_DIR/validation.md\n```\n\nExtract:\n- Plan title and summary\n- Branch name\n- Files changed\n- Tests written\n- Validation results\n- Deviations from plan (if any)\n\n### 1.2 Check for PR Template\n\n**IMPORTANT**: Always check for the project's PR template first. Look for it at `.github/pull_request_template.md`, `.github/PULL_REQUEST_TEMPLATE.md`, or `docs/PULL_REQUEST_TEMPLATE.md`. Read whichever one exists.\n\n**If template found**: Use it as the structure, fill in **every section** with implementation details.\n**If no template**: Use the default format defined in Phase 3.\n\n### 1.3 Check for Existing PR\n\n```bash\ngh pr list --head $(git branch --show-current) --json number,url,state\n```\n\n**If PR already exists**: Will update it instead of creating new one.\n**If no PR**: Will create new one.\n\n**PHASE_1_CHECKPOINT:**\n\n- [ ] Artifacts loaded\n- [ ] Template identified (or using default)\n- [ ] Existing PR status known\n\n---\n\n## Phase 2: COMMIT - Stage and Commit Changes\n\n### 2.1 Check Git Status\n\n```bash\ngit status --porcelain\n```\n\n### 2.2 Stage Changes\n\nStage all implementation changes:\n\n```bash\ngit add -A\n```\n\n**Review staged files** - ensure no sensitive files (.env, credentials) are included:\n\n```bash\ngit diff --cached --name-only\n```\n\n### 2.3 Create Commit\n\nCreate a descriptive commit message:\n\n```bash\ngit commit -m \"{summary of implementation}\n\n- {key change 1}\n- {key change 2}\n- {key change 3}\n\n{If from plan/issue: Implements #{number}}\n\"\n```\n\n### 2.4 Push to Remote\n\n```bash\ngit push origin HEAD\n```\n\n**PHASE_2_CHECKPOINT:**\n\n- [ ] All changes staged\n- [ ] No sensitive files included\n- [ ] Commit created\n- [ ] Pushed to remote\n\n---\n\n## Phase 3: CREATE/UPDATE - Pull Request\n\n### 3.1 Prepare PR Body\n\n**If project has PR template**, fill in each section with implementation details:\n- Replace placeholder text with actual content\n- Fill in checkboxes based on what was done\n- Keep the template's structure intact\n\n**If no template**, use this default format:\n\n```markdown\n## Summary\n\n{Brief description from plan summary}\n\n## Changes\n\n{From implementation.md \"Files Changed\" section}\n\n| File | Action | Description |\n|------|--------|-------------|\n| `src/x.ts` | CREATE | {what it does} |\n| `src/y.ts` | UPDATE | {what changed} |\n\n## Tests\n\n{From implementation.md \"Tests Written\" section}\n\n- `src/x.test.ts` - {test descriptions}\n- `src/y.test.ts` - {test descriptions}\n\n## Validation\n\n{From validation.md}\n\n- [x] Type check passes\n- [x] Lint passes\n- [x] Format passes\n- [x] All tests pass ({N} tests)\n- [x] Build succeeds\n\n## Implementation Notes\n\n{If deviations from plan:}\n### Deviations from Plan\n\n{List deviations and reasons}\n\n{If issues encountered:}\n### Issues Resolved\n\n{List issues and resolutions}\n\n---\n\n**Plan**: `{plan-source-path}`\n**Workflow ID**: `$WORKFLOW_ID`\n```\n\n### 3.2 Create or Update PR\n\n**If no PR exists**, create one:\n\n```bash\n# Write prepared body to file to avoid shell escaping\ncat > $ARTIFACTS_DIR/pr-body.md <<'EOF'\n{prepared-body}\nEOF\n\ngh pr create \\\n --title \"{plan-title}\" \\\n --body-file $ARTIFACTS_DIR/pr-body.md \\\n --base $BASE_BRANCH\n```\n\n**If PR already exists**, update it:\n\n```bash\ngh pr edit {pr-number} --body-file $ARTIFACTS_DIR/pr-body.md\n```\n\n### 3.3 Ensure Ready for Review\n\nIf PR was created as draft, mark ready:\n\n```bash\ngh pr ready {pr-number} 2>/dev/null || true\n```\n\n### 3.4 Capture PR Info\n\n```bash\ngh pr view --json number,url,headRefName,baseRefName\n```\n\n### 3.5 Write PR Number Registry\n\nWrite PR number for downstream review steps:\n\n```bash\nPR_NUMBER=$(gh pr view --json number -q '.number')\nPR_URL=$(gh pr view --json url -q '.url')\necho \"$PR_NUMBER\" > $ARTIFACTS_DIR/.pr-number\necho \"$PR_URL\" > $ARTIFACTS_DIR/.pr-url\n```\n\n**PHASE_3_CHECKPOINT:**\n\n- [ ] PR created or updated\n- [ ] PR body uses template (if available)\n- [ ] PR ready for review\n- [ ] PR URL captured\n- [ ] PR number registry written\n\n---\n\n## Phase 4: ARTIFACT - Write PR Ready Status\n\n### 4.1 Write Final Artifact\n\nWrite to `$ARTIFACTS_DIR/pr-ready.md`:\n\n```markdown\n# PR Ready for Review\n\n**Generated**: {YYYY-MM-DD HH:MM}\n**Workflow ID**: $WORKFLOW_ID\n\n---\n\n## Pull Request\n\n| Field | Value |\n|-------|-------|\n| **Number** | #{number} |\n| **URL** | {url} |\n| **Branch** | `{head}` → `{base}` |\n| **Status** | Ready for Review |\n\n---\n\n## Commit\n\n**Hash**: {commit-sha}\n**Message**: {commit-message-first-line}\n\n---\n\n## Files in PR\n\n{From git diff --name-only origin/$BASE_BRANCH}\n\n| File | Status |\n|------|--------|\n| `src/x.ts` | Added |\n| `src/y.ts` | Modified |\n\n---\n\n## PR Description\n\n{Whether template was used or default format}\n\n- Template used: {yes/no}\n- Template path: {path if used}\n\n---\n\n## Next Step\n\nContinue to PR review workflow:\n1. `archon-pr-review-scope`\n2. `archon-sync-pr-with-main`\n3. Review agents (parallel)\n4. `archon-synthesize-review`\n5. `archon-implement-review-fixes`\n```\n\n**PHASE_4_CHECKPOINT:**\n\n- [ ] PR ready artifact written\n\n---\n\n## Phase 5: OUTPUT - Report Status\n\n```markdown\n## PR Ready for Review ✅\n\n**Workflow ID**: `$WORKFLOW_ID`\n\n### Pull Request\n\n| Field | Value |\n|-------|-------|\n| PR | #{number} |\n| URL | {url} |\n| Branch | `{branch}` → `{base}` |\n| Status | 🟢 Ready for Review |\n\n### Commit\n\n```\n{commit-sha-short} {commit-message-first-line}\n```\n\n### Files Changed\n\n- {N} files added\n- {M} files modified\n- {K} files deleted\n\n### Validation Summary\n\n| Check | Status |\n|-------|--------|\n| Type check | ✅ |\n| Lint | ✅ |\n| Tests | ✅ ({N} passed) |\n| Build | ✅ |\n\n### Artifact\n\nStatus written to: `$ARTIFACTS_DIR/pr-ready.md`\n\n### Next Step\n\nProceeding to comprehensive PR review.\n```\n\n---\n\n## Error Handling\n\n### Nothing to Commit\n\nIf no changes to commit:\n\n```markdown\nℹ️ No changes to commit\n\nAll changes were already committed. Proceeding to update PR description.\n```\n\n### Push Fails\n\n```bash\n# Try force push if branch was rebased\ngit push --force-with-lease origin HEAD\n```\n\nIf still fails:\n```\n❌ Push failed\n\nCheck:\n1. Branch protection rules\n2. Push access to repository\n3. Remote branch status: `git fetch origin && git status`\n```\n\n### PR Not Found\n\n```\n❌ PR not found: #{number}\n\nThe draft PR may have been closed or deleted. Create a new one:\n`gh pr create --title \"...\" --body \"...\"`\n```\n\n### Template Parsing\n\nIf template has complex structure that's hard to fill:\n- Use as much of the template as possible\n- Add implementation details in relevant sections\n- Note at bottom: \"Some template sections may need manual completion\"\n\n---\n\n## Success Criteria\n\n- **CHANGES_COMMITTED**: All changes in a commit\n- **PUSHED**: Branch pushed to remote\n- **PR_UPDATED**: PR description reflects implementation\n- **PR_READY**: Draft status removed\n- **ARTIFACT_WRITTEN**: PR ready artifact created\n", + "archon-fix-issue": "---\ndescription: Implement a fix from investigation artifact - code changes, validation, and commit (no PR)\nargument-hint: \n---\n\n# Fix Issue\n\n**Input**: $ARGUMENTS\n\n---\n\n## Your Mission\n\nExecute the implementation plan from `/investigate-issue`:\n\n1. Load and validate the artifact\n2. Ensure git state is correct\n3. Discover and install dependencies in the worktree\n4. Implement the changes exactly as specified\n5. Run validation\n6. Commit changes\n7. Write implementation report\n\n**Golden Rule**: Follow the artifact. If something seems wrong, validate it first - don't silently deviate.\n\n---\n\n## Phase 1: LOAD - Get the Artifact\n\n### 1.1 Find Investigation Artifact\n\nLook for the investigation artifact from the previous step:\n\n```bash\n# Check for artifact in workflow runs directory\nls $ARTIFACTS_DIR/investigation.md\n```\n\n**If input is a specific path**, use that path directly.\n\n### 1.2 Load and Parse Artifact\n\n```bash\ncat {artifact-path}\n```\n\n**Extract from artifact:**\n- Issue number and title\n- Type (BUG/ENHANCEMENT/etc)\n- Files to modify (with line numbers)\n- Implementation steps\n- Validation commands\n- Test cases to add\n\n### 1.3 Validate Artifact Exists\n\n**If artifact not found:**\n```\n❌ Investigation artifact not found at $ARTIFACTS_DIR/investigation.md\n\nRun `/investigate-issue {number}` first to create the implementation plan.\n```\n\n**PHASE_1_CHECKPOINT:**\n- [ ] Artifact found and loaded\n- [ ] Key sections parsed (files, steps, validation)\n- [ ] Issue number extracted (if applicable)\n\n---\n\n## Phase 2: VALIDATE - Sanity Check\n\n### 2.1 Verify Plan Accuracy\n\nFor each file mentioned in the artifact:\n- Read the actual current code\n- Compare to what artifact expects\n- Check if the \"current code\" snippets match reality\n\n**If significant drift detected:**\n```\n⚠️ Code has changed since investigation:\n\nFile: src/x.ts:45\n- Artifact expected: {snippet}\n- Actual code: {different snippet}\n\nOptions:\n1. Re-run /investigate-issue to get fresh analysis\n2. Proceed carefully with manual adjustments\n```\n\n### 2.2 Confirm Approach Makes Sense\n\nAsk yourself:\n- Does the proposed fix actually address the root cause?\n- Are there obvious problems with the approach?\n- Has something changed that invalidates the plan?\n\n**If plan seems wrong:**\n- STOP\n- Explain what's wrong\n- Suggest re-investigation\n\n**PHASE_2_CHECKPOINT:**\n- [ ] Artifact matches current codebase state\n- [ ] Approach still makes sense\n- [ ] No blocking issues identified\n\n---\n\n## Phase 3: GIT-CHECK - Ensure Correct State\n\n### 3.1 Check Current Git State\n\n```bash\n# What branch are we on?\ngit branch --show-current\n\n# Are we in a worktree?\ngit rev-parse --show-toplevel\ngit worktree list\n\n# Is working directory clean?\ngit status --porcelain\n\n# Are we up to date with remote?\ngit fetch origin\ngit status\n```\n\n### 3.2 Decision Tree\n\n```text\n┌─ IN WORKTREE?\n│ └─ YES → Use current branch AS-IS. Do NOT switch branches. Do NOT create\n│ new branches. The isolation system has already set up the correct\n│ branch; any deviation operates on the wrong code.\n│ Log: \"Using worktree at {path} on branch {branch}\"\n│\n├─ ON $BASE_BRANCH? (main, master, or configured base branch)\n│ └─ Q: Working directory clean?\n│ ├─ YES → Create branch: fix/issue-{number}-{slug}\n│ │ git checkout -b fix/issue-{number}-{slug}\n│ │ (only applies outside a worktree — e.g., manual CLI usage)\n│ └─ NO → STOP: \"Uncommitted changes on $BASE_BRANCH.\n│ Please commit or stash before proceeding.\"\n│\n├─ ON OTHER BRANCH?\n│ └─ Use it AS-IS (assume it was set up for this work).\n│ Do NOT switch to another branch (e.g., one shown by `git branch` but\n│ not currently checked out).\n│ If branch name doesn't contain issue number:\n│ Warn: \"Branch '{name}' may not be for issue #{number}\"\n│\n└─ DIRTY STATE?\n └─ STOP: \"Uncommitted changes. Please commit or stash first.\"\n```\n\n### 3.3 Ensure Up-to-Date\n\n```bash\n# If branch tracks remote\ngit pull --rebase origin $BASE_BRANCH 2>/dev/null || git pull origin $BASE_BRANCH\n```\n\n**PHASE_3_CHECKPOINT:**\n- [ ] Git state is clean and correct\n- [ ] On appropriate branch (created or existing)\n- [ ] Up to date with base branch\n\n---\n\n## Phase 4: DEPENDENCIES - Discover and Install\n\n### 4.1 Detect Install Command\n\nInspect the worktree for lock/config files and choose the install command:\n\n- `package.json` + `bun.lock` → `bun install`\n- `package.json` + `package-lock.json` → `npm install`\n- `package.json` + `yarn.lock` → `yarn install`\n- `package.json` + `pnpm-lock.yaml` → `pnpm install`\n- `requirements.txt` → `pip install -r requirements.txt`\n- `pyproject.toml` + `poetry.lock` → `poetry install`\n- `Cargo.toml` → `cargo build`\n- `go.mod` → `go mod download`\n\n### 4.2 Run Install\n\nRun the chosen install command from the worktree root before any validation or tests.\n\n### 4.3 Failure Handling\n\nIf install fails, STOP and report the error. Do not proceed to validation with missing dependencies.\n\n**PHASE_4_CHECKPOINT:**\n- [ ] Install command discovered\n- [ ] Dependencies installed successfully\n\n---\n\n## Phase 5: IMPLEMENT - Make Changes\n\n### 5.1 Execute Each Step\n\nFor each step in the artifact's Implementation Plan:\n\n1. **Read the target file** - understand current state\n2. **Make the change** - exactly as specified\n3. **Verify types compile** - `bun run type-check`\n\n### 5.2 Implementation Rules\n\n**DO:**\n- Follow artifact steps in order\n- Match existing code style exactly\n- Copy patterns from \"Patterns to Follow\" section\n- Add tests as specified\n\n**DON'T:**\n- Refactor unrelated code\n- Add \"improvements\" not in the plan\n- Change formatting of untouched lines\n- Deviate from the artifact without noting it\n\n### 5.3 Handle Each File Type\n\n**For UPDATE files:**\n- Read current content\n- Find the exact lines mentioned\n- Make the specified change\n- Preserve surrounding code\n\n**For CREATE files:**\n- Use patterns from artifact\n- Follow existing file structure conventions\n- Include all specified content\n\n**For test files:**\n- Add test cases as specified\n- Follow existing test patterns\n- Ensure tests actually test the fix\n\n### 5.4 Track Deviations\n\nIf you must deviate from the artifact:\n- Note what changed and why\n- Include in implementation report\n\n**PHASE_5_CHECKPOINT:**\n- [ ] All steps from artifact executed\n- [ ] Types compile after each change\n- [ ] Tests added as specified\n- [ ] Any deviations documented\n\n---\n\n## Phase 6: VERIFY - Run Validation\n\n### 6.1 Run Artifact Validation Commands\n\nExecute each command from the artifact's Validation section:\n\n```bash\nbun run type-check\nbun test {pattern-from-artifact}\nbun run lint\n```\n\n### 6.2 Check Results\n\n**All must pass before proceeding.**\n\nIf failures:\n1. Analyze what's wrong\n2. Fix the issue\n3. Re-run validation\n4. Note any fixes in implementation report\n\n### 6.3 Manual Verification (if specified)\n\nExecute any manual verification steps from the artifact.\n\n**PHASE_6_CHECKPOINT:**\n- [ ] Type check passes\n- [ ] Tests pass\n- [ ] Lint passes\n- [ ] Manual verification complete (if applicable)\n\n---\n\n## Phase 7: COMMIT - Save Changes\n\n### 7.1 Stage Changes\n\n```bash\ngit add -A\ngit status # Review what's being committed\n```\n\n### 7.2 Write Commit Message\n\n**Format:**\n```\nFix: {brief description} (#{issue-number})\n\n{Problem statement from artifact - 1-2 sentences}\n\nChanges:\n- {Change 1 from artifact}\n- {Change 2 from artifact}\n- Added test for {case}\n\nFixes #{issue-number}\n```\n\n**Commit:**\n```bash\ngit commit -m \"$(cat <<'EOF'\nFix: {title} (#{number})\n\n{problem statement}\n\nChanges:\n- {change 1}\n- {change 2}\n\nFixes #{number}\nEOF\n)\"\n```\n\n**PHASE_7_CHECKPOINT:**\n- [ ] All changes committed\n- [ ] Commit message references issue\n\n---\n\n## Phase 8: WRITE - Implementation Report\n\n### 8.1 Write Implementation Artifact\n\nWrite to `$ARTIFACTS_DIR/implementation.md`:\n\n```markdown\n# Implementation Report\n\n**Issue**: #{number}\n**Generated**: {YYYY-MM-DD HH:MM}\n**Workflow ID**: $WORKFLOW_ID\n\n---\n\n## Tasks Completed\n\n| # | Task | File | Status |\n|---|------|------|--------|\n| 1 | {task} | `src/x.ts` | ✅ |\n| 2 | {task} | `src/x.test.ts` | ✅ |\n\n---\n\n## Files Changed\n\n| File | Action | Lines |\n|------|--------|-------|\n| `src/x.ts` | UPDATE | +{N}/-{M} |\n| `src/x.test.ts` | CREATE | +{N} |\n\n---\n\n## Deviations from Investigation\n\n{If none: \"Implementation matched the investigation exactly.\"}\n\n{If any:}\n### Deviation 1: {title}\n\n**Expected**: {from investigation}\n**Actual**: {what was done}\n**Reason**: {why}\n\n---\n\n## Validation Results\n\n| Check | Result |\n|-------|--------|\n| Type check | ✅ |\n| Tests | ✅ ({N} passed) |\n| Lint | ✅ |\n```\n\n**PHASE_8_CHECKPOINT:**\n- [ ] Implementation artifact written\n\n---\n\n## Phase 9: OUTPUT - Report to User\n\nSkip archiving - artifacts remain in place for review workflow to access.\n\n---\n\n```markdown\n## Implementation Complete\n\n**Issue**: #{number} - {title}\n**Branch**: `{branch-name}`\n\n### Changes Made\n\n| File | Change |\n|------|--------|\n| `src/x.ts` | {description} |\n| `src/x.test.ts` | Added test |\n\n### Validation\n\n| Check | Result |\n|-------|--------|\n| Type check | ✅ Pass |\n| Tests | ✅ Pass |\n| Lint | ✅ Pass |\n\n### Artifacts\n\n- 📄 Investigation: `$ARTIFACTS_DIR/investigation.md`\n- 📄 Implementation: `$ARTIFACTS_DIR/implementation.md`\n\n### Next Step\n\nProceeding to PR creation...\n```\n\n---\n\n## Handling Edge Cases\n\n### Artifact is outdated\n- Warn user about drift\n- Suggest re-running `/investigate-issue`\n- Can proceed with caution if changes are minor\n\n### Tests fail after implementation\n- Debug the failure\n- Fix the code (not the test, unless test is wrong)\n- Re-run validation\n- Note the additional fix in implementation report\n\n### Merge conflicts during rebase\n- Resolve conflicts\n- Re-run full validation\n- Note conflict resolution in implementation report\n\n### Already on a branch with changes\n- Use the existing branch\n- Warn if branch name doesn't match issue\n- Don't create a new branch\n\n### In a worktree\n- Use it as-is\n- Assume it was created for this purpose\n- Log that worktree is being used\n\n---\n\n## Success Criteria\n\n- **PLAN_EXECUTED**: All investigation steps completed\n- **VALIDATION_PASSED**: All checks green\n- **CHANGES_COMMITTED**: All changes committed to branch\n- **IMPLEMENTATION_ARTIFACT**: Written to $ARTIFACTS_DIR/\n- **READY_FOR_PR**: Workflow continues to PR creation\n", + "archon-implement-issue": "---\ndescription: Implement a fix from investigation artifact - code changes, PR, and self-review\nargument-hint: \n---\n\n# Implement Issue\n\n**Input**: $ARGUMENTS\n\n---\n\n## Your Mission\n\nExecute the implementation plan from `/investigate-issue`:\n\n1. Load and validate the artifact\n2. Ensure git state is correct\n3. Discover and install dependencies in the worktree\n4. Implement the changes exactly as specified\n5. Run validation\n6. Create PR linked to issue\n7. Run self-review and post findings\n8. Archive the artifact\n\n**Golden Rule**: Follow the artifact. If something seems wrong, validate it first - don't silently deviate.\n\n---\n\n## Phase 1: LOAD - Get the Artifact\n\n### 1.1 Find Investigation Artifact\n\nLook for the investigation artifact from the previous step:\n\n```bash\n# Check for artifact in workflow runs directory\nls $ARTIFACTS_DIR/investigation.md\n```\n\n**If input is a specific path**, use that path directly.\n\n### 1.2 Load and Parse Artifact\n\n```bash\ncat {artifact-path}\n```\n\n**Extract from artifact:**\n- Issue number and title\n- Type (BUG/ENHANCEMENT/etc)\n- Files to modify (with line numbers)\n- Implementation steps\n- Validation commands\n- Test cases to add\n\n### 1.3 Validate Artifact Exists\n\n**If artifact not found:**\n```\n❌ Investigation artifact not found at $ARTIFACTS_DIR/investigation.md\n\nRun `/investigate-issue {number}` first to create the implementation plan.\n```\n\n**PHASE_1_CHECKPOINT:**\n- [ ] Artifact found and loaded\n- [ ] Key sections parsed (files, steps, validation)\n- [ ] Issue number extracted (if applicable)\n\n---\n\n## Phase 2: VALIDATE - Sanity Check\n\n### 2.1 Verify Plan Accuracy\n\nFor each file mentioned in the artifact:\n- Read the actual current code\n- Compare to what artifact expects\n- Check if the \"current code\" snippets match reality\n\n**If significant drift detected:**\n```\n⚠️ Code has changed since investigation:\n\nFile: src/x.ts:45\n- Artifact expected: {snippet}\n- Actual code: {different snippet}\n\nOptions:\n1. Re-run /investigate-issue to get fresh analysis\n2. Proceed carefully with manual adjustments\n```\n\n### 2.2 Confirm Approach Makes Sense\n\nAsk yourself:\n- Does the proposed fix actually address the root cause?\n- Are there obvious problems with the approach?\n- Has something changed that invalidates the plan?\n\n**If plan seems wrong:**\n- STOP\n- Explain what's wrong\n- Suggest re-investigation\n\n**PHASE_2_CHECKPOINT:**\n- [ ] Artifact matches current codebase state\n- [ ] Approach still makes sense\n- [ ] No blocking issues identified\n\n---\n\n## Phase 3: GIT-CHECK - Ensure Correct State\n\n### 3.1 Check Current Git State\n\n```bash\n# What branch are we on?\ngit branch --show-current\n\n# Are we in a worktree?\ngit rev-parse --show-toplevel\ngit worktree list\n\n# Is working directory clean?\ngit status --porcelain\n\n# Are we up to date with remote?\ngit fetch origin\ngit status\n```\n\n### 3.2 Decision Tree\n\n```text\n┌─ IN WORKTREE?\n│ └─ YES → Use current branch AS-IS. Do NOT switch branches. Do NOT create\n│ new branches. The isolation system has already set up the correct\n│ branch; any deviation operates on the wrong code.\n│ Log: \"Using worktree at {path} on branch {branch}\"\n│\n├─ ON $BASE_BRANCH? (main, master, or configured base branch)\n│ └─ Q: Working directory clean?\n│ ├─ YES → Create branch: fix/issue-{number}-{slug}\n│ │ git checkout -b fix/issue-{number}-{slug}\n│ │ (only applies outside a worktree — e.g., manual CLI usage)\n│ └─ NO → STOP: \"Uncommitted changes on $BASE_BRANCH.\n│ Please commit or stash before proceeding.\"\n│\n├─ ON OTHER BRANCH?\n│ └─ Use it AS-IS (assume it was set up for this work).\n│ Do NOT switch to another branch (e.g., one shown by `git branch` but\n│ not currently checked out).\n│ If branch name doesn't contain issue number:\n│ Warn: \"Branch '{name}' may not be for issue #{number}\"\n│\n└─ DIRTY STATE?\n └─ STOP: \"Uncommitted changes. Please commit or stash first.\"\n```\n\n### 3.3 Ensure Up-to-Date\n\n```bash\n# If branch tracks remote\ngit pull --rebase origin $BASE_BRANCH 2>/dev/null || git pull origin $BASE_BRANCH\n```\n\n**PHASE_3_CHECKPOINT:**\n- [ ] Git state is clean and correct\n- [ ] On appropriate branch (created or existing)\n- [ ] Up to date with base branch\n\n---\n\n## Phase 4: DEPENDENCIES - Discover and Install\n\n### 4.1 Detect Install Command\n\nInspect the worktree for lock/config files and choose the install command:\n\n- `package.json` + `bun.lock` → `bun install`\n- `package.json` + `package-lock.json` → `npm install`\n- `package.json` + `yarn.lock` → `yarn install`\n- `package.json` + `pnpm-lock.yaml` → `pnpm install`\n- `requirements.txt` → `pip install -r requirements.txt`\n- `pyproject.toml` + `poetry.lock` → `poetry install`\n- `Cargo.toml` → `cargo build`\n- `go.mod` → `go mod download`\n\n### 4.2 Run Install\n\nRun the chosen install command from the worktree root before any validation or tests.\n\n### 4.3 Failure Handling\n\nIf install fails, STOP and report the error. Do not proceed to validation with missing dependencies.\n\n**PHASE_4_CHECKPOINT:**\n- [ ] Install command discovered\n- [ ] Dependencies installed successfully\n\n---\n\n## Phase 5: IMPLEMENT - Make Changes\n\n### 5.1 Execute Each Step\n\nFor each step in the artifact's Implementation Plan:\n\n1. **Read the target file** - understand current state\n2. **Make the change** - exactly as specified\n3. **Verify types compile** - `bun run type-check`\n\n### 5.2 Implementation Rules\n\n**DO:**\n- Follow artifact steps in order\n- Match existing code style exactly\n- Copy patterns from \"Patterns to Follow\" section\n- Add tests as specified\n\n**DON'T:**\n- Refactor unrelated code\n- Add \"improvements\" not in the plan\n- Change formatting of untouched lines\n- Deviate from the artifact without noting it\n\n### 5.3 Handle Each File Type\n\n**For UPDATE files:**\n- Read current content\n- Find the exact lines mentioned\n- Make the specified change\n- Preserve surrounding code\n\n**For CREATE files:**\n- Use patterns from artifact\n- Follow existing file structure conventions\n- Include all specified content\n\n**For test files:**\n- Add test cases as specified\n- Follow existing test patterns\n- Ensure tests actually test the fix\n\n### 5.4 Track Deviations\n\nIf you must deviate from the artifact:\n- Note what changed and why\n- Include in PR description\n\n**PHASE_5_CHECKPOINT:**\n- [ ] All steps from artifact executed\n- [ ] Types compile after each change\n- [ ] Tests added as specified\n- [ ] Any deviations documented\n\n---\n\n## Phase 6: VERIFY - Run Validation\n\n### 6.1 Run Artifact Validation Commands\n\nExecute each command from the artifact's Validation section:\n\n```bash\nbun run type-check\nbun test {pattern-from-artifact}\nbun run lint\n```\n\n### 6.2 Check Results\n\n**All must pass before proceeding.**\n\nIf failures:\n1. Analyze what's wrong\n2. Fix the issue\n3. Re-run validation\n4. Note any fixes in PR description\n\n### 6.3 Manual Verification (if specified)\n\nExecute any manual verification steps from the artifact.\n\n**PHASE_6_CHECKPOINT:**\n- [ ] Type check passes\n- [ ] Tests pass\n- [ ] Lint passes\n- [ ] Manual verification complete (if applicable)\n\n---\n\n## Phase 7: COMMIT - Save Changes\n\n### 7.1 Stage Changes\n\n```bash\ngit add -A\ngit status # Review what's being committed\n```\n\n### 7.2 Write Commit Message\n\n**Format:**\n```\nFix: {brief description} (#{issue-number})\n\n{Problem statement from artifact - 1-2 sentences}\n\nChanges:\n- {Change 1 from artifact}\n- {Change 2 from artifact}\n- Added test for {case}\n\nFixes #{issue-number}\n```\n\n**Commit:**\n```bash\ngit commit -m \"$(cat <<'EOF'\nFix: {title} (#{number})\n\n{problem statement}\n\nChanges:\n- {change 1}\n- {change 2}\n\nFixes #{number}\nEOF\n)\"\n```\n\n**PHASE_7_CHECKPOINT:**\n- [ ] All changes committed\n- [ ] Commit message references issue\n\n---\n\n## Phase 8: PR - Create Pull Request\n\n**Before creating a PR**, check if one already exists for this issue or branch using `gh pr list`. If a PR already exists, skip creation and use the existing one.\n\n### 8.1 Push to Remote\n\n```bash\ngit push -u origin HEAD\n```\n\nIf branch was rebased:\n```bash\ngit push -u origin HEAD --force-with-lease\n```\n\n### 8.2 Prepare PR Body\n\nLook for the project's PR template at `.github/pull_request_template.md`, `.github/PULL_REQUEST_TEMPLATE.md`, or `docs/PULL_REQUEST_TEMPLATE.md`. Read whichever one exists.\n\n**If template found**: Use it as the structure, fill in **every section** with details from the artifact (root cause, changes, validation results, etc.). Don't skip sections or leave placeholders. Make sure to include `Fixes #{number}`.\n\n**If no template**, write a body covering: summary, root cause, changes table, validation evidence, and `Fixes #{number}`.\n\n### 8.3 Create PR\n\nWrite the prepared body to `$ARTIFACTS_DIR/pr-body.md`, then:\n\n```bash\ngh pr create --title \"Fix: {title} (#{number})\" \\\n --body-file $ARTIFACTS_DIR/pr-body.md\n```\n\n### 8.3 Get PR Number\n\n```bash\nPR_URL=$(gh pr view --json url -q '.url')\nPR_NUMBER=$(gh pr view --json number -q '.number')\n```\n\n**PHASE_8_CHECKPOINT:**\n- [ ] Changes pushed to remote\n- [ ] PR created\n- [ ] PR linked to issue with \"Fixes #{number}\"\n\n---\n\n## Phase 9: WRITE - Implementation Report\n\n### 9.1 Write Implementation Artifact\n\nWrite to `$ARTIFACTS_DIR/implementation.md`:\n\n```markdown\n# Implementation Report\n\n**Issue**: #{number}\n**Generated**: {YYYY-MM-DD HH:MM}\n**Workflow ID**: $WORKFLOW_ID\n\n---\n\n## Tasks Completed\n\n| # | Task | File | Status |\n|---|------|------|--------|\n| 1 | {task} | `src/x.ts` | ✅ |\n| 2 | {task} | `src/x.test.ts` | ✅ |\n\n---\n\n## Files Changed\n\n| File | Action | Lines |\n|------|--------|-------|\n| `src/x.ts` | UPDATE | +{N}/-{M} |\n| `src/x.test.ts` | CREATE | +{N} |\n\n---\n\n## Deviations from Investigation\n\n{If none: \"Implementation matched the investigation exactly.\"}\n\n{If any:}\n### Deviation 1: {title}\n\n**Expected**: {from investigation}\n**Actual**: {what was done}\n**Reason**: {why}\n\n---\n\n## Validation Results\n\n| Check | Result |\n|-------|--------|\n| Type check | ✅ |\n| Tests | ✅ ({N} passed) |\n| Lint | ✅ |\n\n---\n\n## PR Created\n\n- **Number**: #{pr-number}\n- **URL**: {pr-url}\n- **Branch**: {branch-name}\n```\n\n**PHASE_9_CHECKPOINT:**\n- [ ] Implementation artifact written\n\n---\n\n## Phase 10: OUTPUT - Report to User\n\nSkip archiving - artifacts remain in place for review workflow to access.\n\n---\n\n```markdown\n## Implementation Complete\n\n**Issue**: #{number} - {title}\n**Branch**: `{branch-name}`\n**PR**: #{pr-number} - {pr-url}\n\n### Changes Made\n\n| File | Change |\n|------|--------|\n| `src/x.ts` | {description} |\n| `src/x.test.ts` | Added test |\n\n### Validation\n\n| Check | Result |\n|-------|--------|\n| Type check | ✅ Pass |\n| Tests | ✅ Pass |\n| Lint | ✅ Pass |\n\n### Artifacts\n\n- 📄 Investigation: `$ARTIFACTS_DIR/investigation.md`\n- 📄 Implementation: `$ARTIFACTS_DIR/implementation.md`\n\n### Next Step\n\nProceeding to comprehensive code review...\n```\n\n---\n\n## Handling Edge Cases\n\n### Artifact is outdated\n- Warn user about drift\n- Suggest re-running `/investigate-issue`\n- Can proceed with caution if changes are minor\n\n### Tests fail after implementation\n- Debug the failure\n- Fix the code (not the test, unless test is wrong)\n- Re-run validation\n- Note the additional fix in PR\n\n### Merge conflicts during rebase\n- Resolve conflicts\n- Re-run full validation\n- Note conflict resolution in PR\n\n### PR creation fails\n- Check if PR already exists for branch\n- Check for permission issues\n- Provide manual gh command\n\n### Already on a branch with changes\n- Use the existing branch\n- Warn if branch name doesn't match issue\n- Don't create a new branch\n\n### In a worktree\n- Use it as-is\n- Assume it was created for this purpose\n- Log that worktree is being used\n\n---\n\n## Success Criteria\n\n- **PLAN_EXECUTED**: All investigation steps completed\n- **VALIDATION_PASSED**: All checks green\n- **PR_CREATED**: PR exists and linked to issue\n- **IMPLEMENTATION_ARTIFACT**: Written to runs/$WORKFLOW_ID/\n- **READY_FOR_REVIEW**: Workflow continues to comprehensive review\n", + "archon-implement-review-fixes": "---\ndescription: Implement CRITICAL and HIGH fixes from review, add tests, report remaining issues\nargument-hint: (none - reads from consolidated review artifact)\n---\n\n# Implement Review Fixes\n\n---\n\n## IMPORTANT: Output Behavior\n\n**Your output will be posted as a GitHub comment.** Keep your working output minimal:\n- Do NOT narrate each step (\"Now I'll read the file...\", \"Let me check...\")\n- Do NOT output verbose progress updates\n- Only output the final structured report at the end\n- Use the TodoWrite tool to track progress silently\n\n---\n\n## Your Mission\n\nRead the consolidated review artifact and implement all CRITICAL and HIGH priority fixes. Add tests for fixed code if missing. Commit and push changes. Report what was fixed, what wasn't (and why), and suggest follow-up issues for remaining items.\n\n**Output artifact**: `$ARTIFACTS_DIR/review/fix-report.md`\n**Git action**: Commit AND push fixes to the PR branch\n**GitHub action**: Post fix report comment\n\n---\n\n## Phase 1: LOAD - Get Fix List\n\n### 1.1 Get PR Number from Registry\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number)\n\n# Get the PR's head branch name\nHEAD_BRANCH=$(gh pr view $PR_NUMBER --json headRefName --jq '.headRefName')\necho \"PR: $PR_NUMBER, Branch: $HEAD_BRANCH\"\n```\n\n### 1.2 Checkout the PR Branch\n\n**CRITICAL: Work on the PR's actual branch, not a new branch.**\n\n```bash\n# Fetch and checkout the PR's branch\ngit fetch origin $HEAD_BRANCH\ngit checkout $HEAD_BRANCH\ngit pull origin $HEAD_BRANCH\n```\n\n### 1.3 Read Consolidated Review\n\n```bash\ncat $ARTIFACTS_DIR/review/consolidated-review.md\n```\n\nExtract:\n- All CRITICAL issues with fixes\n- All HIGH issues with fixes\n- MEDIUM issues (for reporting)\n- LOW issues (for reporting)\n\n### 1.4 Read Individual Artifacts for Details\n\nIf consolidated doesn't have full fix code, read original artifacts:\n\n```bash\ncat $ARTIFACTS_DIR/review/code-review-findings.md\ncat $ARTIFACTS_DIR/review/error-handling-findings.md\ncat $ARTIFACTS_DIR/review/test-coverage-findings.md\ncat $ARTIFACTS_DIR/review/docs-impact-findings.md\n```\n\n### 1.5 Check Current Git State\n\n```bash\ngit status --porcelain\ngit branch --show-current\n```\n\nVerify you are on the correct PR branch (should be `$HEAD_BRANCH`).\n\n**PHASE_1_CHECKPOINT:**\n- [ ] PR number identified\n- [ ] On the correct PR branch (NOT base branch, NOT a new branch)\n- [ ] Consolidated review loaded\n- [ ] CRITICAL/HIGH issues extracted\n\n---\n\n## Phase 2: IMPLEMENT - Apply Fixes\n\n### 2.1 For Each CRITICAL Issue\n\n1. **Read the file**\n2. **Apply the recommended fix**\n3. **Verify fix compiles**: `bun run type-check`\n4. **Track**: Note what was changed\n\n### 2.2 For Each HIGH Issue\n\nSame process as CRITICAL.\n\n### 2.3 For Test Coverage Gaps\n\nIf test-coverage-agent identified missing tests for fixed code:\n\n1. **Create/update test file**\n2. **Add tests for the fix**\n3. **Verify tests pass**: `bun test {file}`\n\n### 2.4 Handle Unfixable Issues\n\nIf a fix cannot be applied:\n- **Conflict**: Code has changed since review\n- **Complex**: Requires architectural changes\n- **Unclear**: Recommendation is ambiguous\n- **Risk**: Fix might break other things\n\nDocument the reason clearly.\n\n**PHASE_2_CHECKPOINT:**\n- [ ] All CRITICAL fixes attempted\n- [ ] All HIGH fixes attempted\n- [ ] Tests added for fixes\n- [ ] Unfixable issues documented\n\n---\n\n## Phase 3: VALIDATE - Verify Fixes\n\n### 3.1 Type Check\n\n```bash\nbun run type-check\n```\n\nMust pass. If not, fix type errors.\n\n### 3.2 Lint\n\n```bash\nbun run lint\n```\n\nFix any lint errors introduced.\n\n### 3.3 Run Tests\n\n```bash\nbun test\n```\n\nAll tests must pass. If new tests fail, fix them.\n\n### 3.4 Build Check\n\n```bash\nbun run build\n```\n\nMust succeed.\n\n**PHASE_3_CHECKPOINT:**\n- [ ] Type check passes\n- [ ] Lint passes\n- [ ] All tests pass\n- [ ] Build succeeds\n\n---\n\n## Phase 4: COMMIT AND PUSH - Save and Push Changes\n\n### 4.1 Stage Changes\n\n```bash\ngit add -A\ngit status\n```\n\n### 4.2 Commit\n\n```bash\ngit commit -m \"fix: Address review findings (CRITICAL/HIGH)\n\nFixes applied:\n- {brief list of fixes}\n\nTests added:\n- {list of new tests if any}\n\nSkipped (see review artifacts):\n- {brief list of unfixable if any}\n\nReview artifacts: $ARTIFACTS_DIR/review/\"\n```\n\n### 4.3 Push to PR Branch\n\n**Push the fixes to the PR branch so they appear in the PR.**\n\n```bash\ngit push origin $HEAD_BRANCH\n```\n\nIf push fails due to divergence:\n```bash\ngit pull --rebase origin $HEAD_BRANCH\ngit push origin $HEAD_BRANCH\n```\n\n**PHASE_4_CHECKPOINT:**\n- [ ] Changes committed\n- [ ] Changes pushed to PR branch\n- [ ] PR now shows the fixes\n\n---\n\n## Phase 5: GENERATE - Create Fix Report\n\nWrite to `$ARTIFACTS_DIR/review/fix-report.md`:\n\n```markdown\n# Fix Report: PR #{number}\n\n**Date**: {ISO timestamp}\n**Status**: {COMPLETE | PARTIAL}\n**Branch**: {HEAD_BRANCH}\n\n---\n\n## Summary\n\n{2-3 sentence overview of fixes applied}\n\n---\n\n## Fixes Applied\n\n### CRITICAL Fixes ({n}/{total})\n\n| Issue | Location | Status | Details |\n|-------|----------|--------|---------|\n| {title} | `file:line` | ✅ FIXED | {what was done} |\n| {title} | `file:line` | ❌ SKIPPED | {why} |\n\n---\n\n### HIGH Fixes ({n}/{total})\n\n| Issue | Location | Status | Details |\n|-------|----------|--------|---------|\n| {title} | `file:line` | ✅ FIXED | {what was done} |\n\n---\n\n## Tests Added\n\n| Test File | Test Cases | For Issue |\n|-----------|------------|-----------|\n| `src/x.test.ts` | `it('should...')` | {issue title} |\n\n---\n\n## Not Fixed (Requires Manual Action)\n\n### {Issue Title}\n\n**Severity**: {CRITICAL/HIGH}\n**Location**: `{file}:{line}`\n**Reason Not Fixed**: {reason}\n\n**Suggested Action**:\n{What the user should do}\n\n---\n\n## MEDIUM Issues (User Decision Required)\n\n| Issue | Location | Options |\n|-------|----------|---------|\n| {title} | `file:line` | Fix now / Create issue / Skip |\n\n---\n\n## LOW Issues (For Consideration)\n\n| Issue | Location | Suggestion |\n|-------|----------|------------|\n| {title} | `file:line` | {brief suggestion} |\n\n---\n\n## Suggested Follow-up Issues\n\n| Issue Title | Priority | Related Finding |\n|-------------|----------|-----------------|\n| \"{title}\" | P{1/2/3} | {which finding} |\n\n---\n\n## Validation Results\n\n| Check | Status |\n|-------|--------|\n| Type check | ✅ |\n| Lint | ✅ |\n| Tests | ✅ ({n} passed) |\n| Build | ✅ |\n\n---\n\n## Git Status\n\n- **Branch**: {HEAD_BRANCH}\n- **Commit**: {commit-hash}\n- **Pushed**: ✅ Yes\n```\n\n**PHASE_5_CHECKPOINT:**\n- [ ] Fix report created\n- [ ] All fixes documented\n\n---\n\n## Phase 6: POST - GitHub Comment\n\n### 6.1 Post Fix Report\n\n```bash\ngh pr comment {number} --body \"$(cat <<'EOF'\n# ⚡ Auto-Fix Report\n\n**Status**: {COMPLETE | PARTIAL}\n**Pushed**: ✅ Changes pushed to PR\n\n---\n\n## Fixes Applied\n\n| Severity | Fixed | Skipped |\n|----------|-------|---------|\n| 🔴 CRITICAL | {n} | {n} |\n| 🟠 HIGH | {n} | {n} |\n\n### What Was Fixed\n\n{For each fix:}\n- ✅ **{title}** (`{file}:{line}`) - {brief description}\n\n### Tests Added\n\n{If any:}\n- `{test-file}`: {n} new test cases\n\n---\n\n## ❌ Not Fixed (Manual Action Required)\n\n{If any:}\n- **{title}** (`{file}`) - {reason}\n\n---\n\n## 🟡 MEDIUM Issues (Your Decision)\n\n{If any:}\n| Issue | Options |\n|-------|---------|\n| {title} | Fix now / Create issue / Skip |\n\n---\n\n## 📋 Suggested Follow-up Issues\n\n{If any items should become issues:}\n1. **{Issue Title}** (P{1/2/3}) - {brief description}\n\n---\n\n## Validation\n\n✅ Type check | ✅ Lint | ✅ Tests | ✅ Build\n\n---\n\n*Auto-fixed by Archon comprehensive-pr-review workflow*\n*Fixes pushed to branch `{HEAD_BRANCH}`*\nEOF\n)\"\n```\n\n**PHASE_6_CHECKPOINT:**\n- [ ] GitHub comment posted\n\n---\n\n## Phase 7: OUTPUT - Final Report\n\nOutput only this summary (keep it brief):\n\n```markdown\n## ✅ Fix Implementation Complete\n\n**PR**: #{number}\n**Branch**: {HEAD_BRANCH}\n**Status**: {COMPLETE | PARTIAL}\n\n| Severity | Fixed |\n|----------|-------|\n| CRITICAL | {n}/{total} |\n| HIGH | {n}/{total} |\n\n**Validation**: ✅ All checks pass\n**Pushed**: ✅ Changes pushed to PR\n\nSee fix report: `$ARTIFACTS_DIR/review/fix-report.md`\n```\n\n---\n\n## Error Handling\n\n### Type Check Fails After Fix\n\n1. Review the error\n2. Adjust the fix\n3. Re-run type check\n4. If still failing, mark as \"Not Fixed\" with reason\n\n### Tests Fail\n\n1. Check if fix caused the failure\n2. Either: fix the implementation, or fix the test\n3. If unclear, mark as \"Not Fixed\" for manual review\n\n### Push Fails\n\n1. Pull with rebase: `git pull --rebase origin $HEAD_BRANCH`\n2. Resolve any conflicts\n3. Push again\n\n---\n\n## Success Criteria\n\n- **ON_CORRECT_BRANCH**: Working on PR's head branch, not base branch or new branch\n- **CRITICAL_ADDRESSED**: All CRITICAL issues attempted\n- **HIGH_ADDRESSED**: All HIGH issues attempted\n- **VALIDATION_PASSED**: Type check, lint, tests, build all pass\n- **COMMITTED_AND_PUSHED**: Changes committed AND pushed to PR branch\n- **REPORTED**: Fix report artifact and GitHub comment created\n", + "archon-implement-tasks": "---\ndescription: Execute plan tasks with type-checking after each change\nargument-hint: (no arguments - reads from workflow artifacts)\n---\n\n# Implement Tasks\n\n**Workflow ID**: $WORKFLOW_ID\n\n---\n\n## Your Mission\n\nExecute each task from the plan, validating after every change.\n\n**Core Philosophy**:\n- Type-check after EVERY file change\n- Fix issues immediately before moving on\n- Document any deviations from the plan\n\n**This step assumes setup is complete** - branch exists, PR is created, plan is confirmed.\n\n---\n\n## Phase 1: LOAD - Read Context\n\n### 1.1 Load Plan Context\n\n```bash\ncat $ARTIFACTS_DIR/plan-context.md\n```\n\nExtract:\n- Files to change (CREATE/UPDATE list)\n- Validation commands (especially type-check)\n- Patterns to mirror\n\n### 1.2 Load Plan Confirmation\n\n```bash\ncat $ARTIFACTS_DIR/plan-confirmation.md\n```\n\nCheck:\n- Status is CONFIRMED or PROCEED WITH CAUTION\n- Note any warnings to handle during implementation\n\n### 1.3 Load Original Plan\n\nThe plan source path is in `plan-context.md`. Read the full plan for detailed task instructions:\n\n```bash\ncat {plan-source-path}\n```\n\n### 1.4 Identify Package Manager\n\n```bash\ntest -f bun.lockb && echo \"bun\" || \\\ntest -f pnpm-lock.yaml && echo \"pnpm\" || \\\ntest -f yarn.lock && echo \"yarn\" || \\\ntest -f package-lock.json && echo \"npm\" || \\\necho \"unknown\"\n```\n\nStore the runner for validation commands.\n\n**PHASE_1_CHECKPOINT:**\n\n- [ ] Plan context loaded\n- [ ] Confirmation status verified\n- [ ] Original plan loaded\n- [ ] Package manager identified\n\n---\n\n## Phase 2: EXECUTE - Implement Each Task\n\n**For each task in the plan's \"Tasks\" or \"Step-by-Step Tasks\" section:**\n\n### 2.1 Read Task Context\n\nBefore implementing each task:\n\n1. **Read the MIRROR file** referenced in the task\n2. **Understand the pattern** to follow\n3. **Note any GOTCHA warnings**\n4. **Check IMPORTS** needed\n\n### 2.2 Implement the Task\n\nMake the change as specified:\n\n- **CREATE**: Write new file following the pattern\n- **UPDATE**: Modify existing file as described\n- **Follow patterns exactly** - match style, naming, structure\n\n### 2.3 Type-Check Immediately\n\n**After EVERY file change:**\n\n```bash\n{runner} run type-check\n```\n\n**If type-check fails:**\n\n1. Read the error message carefully\n2. Fix the type issue\n3. Re-run type-check\n4. Only proceed when passing\n\n**Do NOT accumulate errors** - fix each one before moving to the next task.\n\n### 2.4 Track Progress\n\nLog each task as completed:\n\n```\nTask 1: CREATE src/features/x/models.ts ✅\nTask 2: CREATE src/features/x/service.ts ✅\nTask 3: UPDATE src/routes/index.ts ✅\n```\n\n### 2.5 Handle Deviations\n\nIf you must deviate from the plan:\n\n1. **Document WHAT** changed\n2. **Document WHY** it changed\n3. **Continue** with the deviation noted\n\nCommon reasons for deviation:\n- Pattern file has changed since plan was created\n- Missing import discovered\n- Type incompatibility requires different approach\n- Better solution discovered during implementation\n\n**PHASE_2_CHECKPOINT (per task):**\n\n- [ ] Task implemented\n- [ ] Type-check passes\n- [ ] Progress logged\n- [ ] Deviations documented (if any)\n\n---\n\n## Phase 3: TESTS - Write Required Tests\n\n### 3.1 Test Requirements\n\nEvery new function/feature needs at least one test:\n\n- **New file created** → Create corresponding test file\n- **New function added** → Add test for that function\n- **Behavior changed** → Update existing tests\n\n### 3.2 Follow Test Patterns\n\nFind existing test files to mirror:\n\n```bash\nfind . -name \"*.test.ts\" -type f | head -5\n```\n\nRead a relevant test file to understand the project's test patterns.\n\n### 3.3 Write Tests\n\nFor each new/changed file, write tests that cover:\n\n1. **Happy path** - Normal expected behavior\n2. **Edge cases** - Boundary conditions from the plan\n3. **Error cases** - What happens with bad input\n\n### 3.4 Run Tests\n\n```bash\n{runner} test\n```\n\n**If tests fail:**\n\n1. Determine: bug in implementation or bug in test?\n2. Fix the actual issue (usually implementation)\n3. Re-run tests\n4. Repeat until green\n\n**PHASE_3_CHECKPOINT:**\n\n- [ ] Tests written for new code\n- [ ] All tests pass\n\n---\n\n## Phase 4: ARTIFACT - Write Implementation Progress\n\n### 4.1 Write Progress Artifact\n\nWrite to `$ARTIFACTS_DIR/implementation.md`:\n\n```markdown\n# Implementation Progress\n\n**Generated**: {YYYY-MM-DD HH:MM}\n**Workflow ID**: $WORKFLOW_ID\n**Status**: {COMPLETE | IN_PROGRESS | BLOCKED}\n\n---\n\n## Tasks Completed\n\n| # | Task | File | Status | Notes |\n|---|------|------|--------|-------|\n| 1 | {description} | `src/x.ts` | ✅ | |\n| 2 | {description} | `src/y.ts` | ✅ | |\n| 3 | {description} | `src/z.ts` | ✅ | Minor deviation - see below |\n\n**Progress**: {X} of {Y} tasks completed\n\n---\n\n## Files Changed\n\n| File | Action | Lines |\n|------|--------|-------|\n| `src/new-file.ts` | CREATE | +{N} |\n| `src/existing.ts` | UPDATE | +{N}/-{M} |\n\n---\n\n## Tests Written\n\n| Test File | Test Cases |\n|-----------|------------|\n| `src/x.test.ts` | `should do X`, `should handle Y` |\n| `src/y.test.ts` | `creates correctly`, `validates input` |\n\n---\n\n## Deviations from Plan\n\n{If none:}\nNo deviations. Implementation matched the plan exactly.\n\n{If any:}\n### Deviation 1: {brief title}\n\n**Task**: {which task}\n**Expected**: {what plan said}\n**Actual**: {what was done}\n**Reason**: {why the change was necessary}\n\n---\n\n## Type-Check Status\n\n- [x] Passes after all changes\n\n---\n\n## Test Status\n\n- [x] All tests pass\n- Tests added: {N}\n- Tests modified: {M}\n\n---\n\n## Issues Encountered\n\n{If none:}\nNo issues encountered.\n\n{If any:}\n### Issue 1: {title}\n\n**Problem**: {description}\n**Resolution**: {how it was fixed}\n\n---\n\n## Next Step\n\nContinue to `archon-validate` for full validation suite.\n```\n\n**PHASE_4_CHECKPOINT:**\n\n- [ ] Implementation artifact written\n- [ ] All tasks documented\n- [ ] Deviations noted\n- [ ] Test status recorded\n\n---\n\n## Phase 5: OUTPUT - Report Progress\n\n```markdown\n## Implementation Complete\n\n**Workflow ID**: `$WORKFLOW_ID`\n**Status**: ✅ All tasks executed\n\n### Progress Summary\n\n| Metric | Count |\n|--------|-------|\n| Tasks completed | {X}/{Y} |\n| Files created | {N} |\n| Files updated | {M} |\n| Tests written | {K} |\n\n### Type-Check\n\n✅ Passes\n\n### Tests\n\n✅ All pass ({N} tests)\n\n{If deviations:}\n### Deviations\n\n{count} deviation(s) from plan documented in artifact.\n\n### Artifact\n\nProgress written to: `$ARTIFACTS_DIR/implementation.md`\n\n### Next Step\n\nProceed to `archon-validate` for full validation (lint, build, integration tests).\n```\n\n---\n\n## Error Handling\n\n### Type-Check Fails\n\nDo NOT proceed to next task. Fix the issue:\n\n1. Read the error carefully\n2. Identify the file and line\n3. Fix the type issue\n4. Re-run type-check\n5. Only continue when green\n\n### Test Fails\n\n1. Read the failure output\n2. Identify: implementation bug or test bug?\n3. Fix the root cause\n4. Re-run tests\n\n### Pattern File Changed\n\nIf a pattern file has changed since the plan was created:\n\n1. Read the current version\n2. Adapt the implementation to match current patterns\n3. Document as a deviation\n4. Continue\n\n### Task Unclear\n\nIf a task description is ambiguous:\n\n1. Check the plan's context sections for clarity\n2. Look at the MIRROR file for guidance\n3. Make a reasonable decision\n4. Document the interpretation as a deviation\n\n---\n\n## Success Criteria\n\n- **TASKS_COMPLETE**: All tasks from plan executed\n- **TYPES_PASS**: Type-check passes after all changes\n- **TESTS_WRITTEN**: New code has tests\n- **TESTS_PASS**: All tests green\n- **DEVIATIONS_DOCUMENTED**: Any plan deviations noted\n- **ARTIFACT_WRITTEN**: Implementation progress artifact created\n", + "archon-implement": "---\ndescription: Execute an implementation plan with rigorous validation loops\nargument-hint: \n---\n\n# Implement Plan\n\n**Plan**: $ARGUMENTS\n\n---\n\n## Your Mission\n\nExecute the plan end-to-end with rigorous self-validation. You are autonomous.\n\n**Core Philosophy**: Validation loops catch mistakes early. Run checks after every change. Fix issues immediately. The goal is a working implementation, not just code that exists.\n\n**Golden Rule**: If a validation fails, fix it before moving on. Never accumulate broken state.\n\n---\n\n## Phase 0: DETECT - Project Environment\n\n### 0.1 Identify Package Manager\n\nCheck for these files to determine the project's toolchain:\n\n| File Found | Package Manager | Runner |\n|------------|-----------------|--------|\n| `bun.lockb` | bun | `bun` / `bun run` |\n| `pnpm-lock.yaml` | pnpm | `pnpm` / `pnpm run` |\n| `yarn.lock` | yarn | `yarn` / `yarn run` |\n| `package-lock.json` | npm | `npm run` |\n| `pyproject.toml` | uv/pip | `uv run` / `python` |\n| `Cargo.toml` | cargo | `cargo` |\n| `go.mod` | go | `go` |\n\n**Store the detected runner** - use it for all subsequent commands.\n\n### 0.2 Identify Validation Scripts\n\nCheck `package.json` (or equivalent) for available scripts:\n- Type checking: `type-check`, `typecheck`, `tsc`\n- Linting: `lint`, `lint:fix`\n- Testing: `test`, `test:unit`, `test:integration`\n- Building: `build`, `compile`\n\n**Use the plan's \"Validation Commands\" section** - it should specify exact commands for this project.\n\n---\n\n## Phase 1: LOAD - Read the Plan\n\n### 1.1 Load Plan File\n\n```bash\ncat $ARGUMENTS\n```\n\nIf `$ARGUMENTS` is a GitHub issue URL or number (e.g., `#123`), fetch the issue body which contains the plan.\n\n### 1.2 Extract Key Sections\n\nLocate and understand:\n\n- **Summary** - What we're building\n- **Patterns to Mirror** - Code to copy from\n- **Files to Change** - CREATE/UPDATE list\n- **Step-by-Step Tasks** - Implementation order\n- **Validation Commands** - How to verify (USE THESE, not hardcoded commands)\n- **Acceptance Criteria** - Definition of done\n\n### 1.3 Validate Plan Exists\n\n**If plan not found:**\n\n```\nError: Plan not found at $ARGUMENTS\n\nProvide a valid plan path or GitHub issue containing the plan.\n```\n\n**PHASE_1_CHECKPOINT:**\n\n- [ ] Plan file loaded\n- [ ] Key sections identified\n- [ ] Tasks list extracted\n\n---\n\n## Phase 2: PREPARE - Git State\n\n### 2.1 Check Current State\n\n```bash\n# What branch are we on?\ngit branch --show-current\n\n# Are we in a worktree?\ngit rev-parse --show-toplevel\ngit worktree list\n\n# Is working directory clean?\ngit status --porcelain\n```\n\n### 2.2 Branch Decision\n\n```text\n┌─ IN WORKTREE?\n│ └─ YES → Use current branch AS-IS. Do NOT switch branches. Do NOT create\n│ new branches. The isolation system has already set up the correct\n│ branch; any deviation operates on the wrong code.\n│ Log: \"Using worktree at {path} on branch {branch}\"\n│\n├─ ON $BASE_BRANCH? (main, master, or configured base branch)\n│ └─ Q: Working directory clean?\n│ ├─ YES → Create branch: git checkout -b feature/{plan-slug}\n│ │ (only applies outside a worktree — e.g., manual CLI usage)\n│ └─ NO → STOP: \"Stash or commit changes first\"\n│\n├─ ON OTHER BRANCH?\n│ └─ Use it AS-IS. Do NOT switch to another branch (e.g., one shown by\n│ `git branch` but not currently checked out).\n│ Log: \"Using existing branch {name}\"\n│\n└─ DIRTY STATE?\n └─ STOP: \"Stash or commit changes first\"\n```\n\n### 2.3 Sync with Remote\n\n```bash\ngit fetch origin\ngit pull --rebase origin $BASE_BRANCH 2>/dev/null || true\n```\n\n**PHASE_2_CHECKPOINT:**\n\n- [ ] On correct branch (not $BASE_BRANCH with uncommitted work)\n- [ ] Working directory ready\n- [ ] Up to date with remote\n\n---\n\n## Phase 3: EXECUTE - Implement Tasks\n\n**For each task in the plan's Step-by-Step Tasks section:**\n\n### 3.1 Read Context\n\n1. Read the **MIRROR** file reference from the task\n2. Understand the pattern to follow\n3. Read any **IMPORTS** specified\n\n### 3.2 Implement\n\n1. Make the change exactly as specified\n2. Follow the pattern from MIRROR reference\n3. Handle any **GOTCHA** warnings\n\n### 3.3 Validate Immediately\n\n**After EVERY file change, run the type-check command from the plan's Validation Commands section.**\n\nCommon patterns:\n- `{runner} run type-check` (JS/TS projects)\n- `mypy .` (Python)\n- `cargo check` (Rust)\n- `go build ./...` (Go)\n\n**If types fail:**\n\n1. Read the error\n2. Fix the issue\n3. Re-run type-check\n4. Only proceed when passing\n\n### 3.4 Track Progress\n\nLog each task as you complete it:\n\n```\nTask 1: CREATE src/features/x/models.ts ✅\nTask 2: CREATE src/features/x/service.ts ✅\nTask 3: UPDATE src/routes/index.ts ✅\n```\n\n**Deviation Handling:**\nIf you must deviate from the plan:\n\n- Note WHAT changed\n- Note WHY it changed\n- Continue with the deviation documented\n\n**PHASE_3_CHECKPOINT:**\n\n- [ ] All tasks executed in order\n- [ ] Each task passed type-check\n- [ ] Deviations documented\n\n---\n\n## Phase 4: VALIDATE - Full Verification\n\n### 4.1 Static Analysis\n\n**Run the type-check and lint commands from the plan's Validation Commands section.**\n\nCommon patterns:\n- JS/TS: `{runner} run type-check && {runner} run lint`\n- Python: `ruff check . && mypy .`\n- Rust: `cargo check && cargo clippy`\n- Go: `go vet ./...`\n\n**Must pass with zero errors.**\n\nIf lint errors:\n\n1. Run the lint fix command (e.g., `{runner} run lint:fix`, `ruff check --fix .`)\n2. Re-check\n3. Manual fix remaining issues\n\n### 4.2 Unit Tests\n\n**You MUST write or update tests for new code.** This is not optional.\n\n**Test requirements:**\n\n1. Every new function/feature needs at least one test\n2. Edge cases identified in the plan need tests\n3. Update existing tests if behavior changed\n\n**Write tests**, then run the test command from the plan.\n\nCommon patterns:\n- JS/TS: `{runner} test` or `{runner} run test`\n- Python: `pytest` or `uv run pytest`\n- Rust: `cargo test`\n- Go: `go test ./...`\n\n**If tests fail:**\n\n1. Read failure output\n2. Determine: bug in implementation or bug in test?\n3. Fix the actual issue\n4. Re-run tests\n5. Repeat until green\n\n### 4.3 Build Check\n\n**Run the build command from the plan's Validation Commands section.**\n\nCommon patterns:\n- JS/TS: `{runner} run build`\n- Python: N/A (interpreted) or `uv build`\n- Rust: `cargo build --release`\n- Go: `go build ./...`\n\n**Must complete without errors.**\n\n### 4.4 Integration Testing (if applicable)\n\n**If the plan involves API/server changes, use the integration test commands from the plan.**\n\nExample pattern:\n```bash\n# Start server in background (command varies by project)\n{runner} run dev &\nSERVER_PID=$!\nsleep 3\n\n# Test endpoints (adjust URL/port per project config)\ncurl -s http://localhost:{port}/health | jq\n\n# Stop server\nkill $SERVER_PID\n```\n\n### 4.5 Edge Case Testing\n\nRun any edge case tests specified in the plan.\n\n**PHASE_4_CHECKPOINT:**\n\n- [ ] Type-check passes (command from plan)\n- [ ] Lint passes (0 errors)\n- [ ] Tests pass (all green)\n- [ ] Build succeeds\n- [ ] Integration tests pass (if applicable)\n\n---\n\n## Phase 5: REPORT - Create Implementation Report\n\n### 5.1 Create Report Directory\n\n```bash\nmkdir -p $ARTIFACTS_DIR/../reports\n```\n\n### 5.2 Generate Report\n\n**Path**: `$ARTIFACTS_DIR/../reports/{plan-name}-report.md`\n\n```markdown\n# Implementation Report\n\n**Plan**: `$ARGUMENTS`\n**Source Issue**: #{number} (if applicable)\n**Branch**: `{branch-name}`\n**Date**: {YYYY-MM-DD}\n**Status**: {COMPLETE | PARTIAL}\n\n---\n\n## Summary\n\n{Brief description of what was implemented}\n\n---\n\n## Assessment vs Reality\n\nCompare the original plan's assessment with what actually happened:\n\n| Metric | Predicted | Actual | Reasoning |\n| ---------- | ----------- | -------- | ------------------------------------------------------------------------------ |\n| Complexity | {from plan} | {actual} | {Why it matched or differed - e.g., \"discovered additional integration point\"} |\n| Confidence | {from plan} | {actual} | {e.g., \"root cause was correct\" or \"had to pivot because X\"} |\n\n**If implementation deviated from the plan, explain why:**\n\n- {What changed and why - based on what you discovered during implementation}\n\n---\n\n## Tasks Completed\n\n| # | Task | File | Status |\n| --- | ------------------ | ---------- | ------ |\n| 1 | {task description} | `src/x.ts` | ✅ |\n| 2 | {task description} | `src/y.ts` | ✅ |\n\n---\n\n## Validation Results\n\n| Check | Result | Details |\n| ----------- | ------ | --------------------- |\n| Type check | ✅ | No errors |\n| Lint | ✅ | 0 errors, N warnings |\n| Unit tests | ✅ | X passed, 0 failed |\n| Build | ✅ | Compiled successfully |\n| Integration | ✅/⏭️ | {result or \"N/A\"} |\n\n---\n\n## Files Changed\n\n| File | Action | Lines |\n| ---------- | ------ | --------- |\n| `src/x.ts` | CREATE | +{N} |\n| `src/y.ts` | UPDATE | +{N}/-{M} |\n\n---\n\n## Deviations from Plan\n\n{List any deviations with rationale, or \"None\"}\n\n---\n\n## Issues Encountered\n\n{List any issues and how they were resolved, or \"None\"}\n\n---\n\n## Tests Written\n\n| Test File | Test Cases |\n| --------------- | ------------------------ |\n| `src/x.test.ts` | {list of test functions} |\n\n---\n\n## Next Steps\n\n- [ ] Review implementation\n- [ ] Create PR (next step in workflow)\n- [ ] Merge when approved\n```\n\n### 5.3 Archive Plan\n\n```bash\nmkdir -p $ARTIFACTS_DIR/../plans/completed\ncp $ARGUMENTS $ARTIFACTS_DIR/../plans/completed/ 2>/dev/null || true\n```\n\n**PHASE_5_CHECKPOINT:**\n\n- [ ] Report created at `$ARTIFACTS_DIR/../reports/`\n- [ ] Plan copied to completed folder (if local file)\n\n---\n\n## Phase 6: OUTPUT - Report to User\n\n```markdown\n## Implementation Complete\n\n**Plan**: `$ARGUMENTS`\n**Source Issue**: #{number} (if applicable)\n**Branch**: `{branch-name}`\n**Status**: ✅ Complete\n\n### Validation Summary\n\n| Check | Result |\n| ---------- | --------------- |\n| Type check | ✅ |\n| Lint | ✅ |\n| Tests | ✅ ({N} passed) |\n| Build | ✅ |\n\n### Files Changed\n\n- {N} files created\n- {M} files updated\n- {K} tests written\n\n### Deviations\n\n{If none: \"Implementation matched the plan.\"}\n{If any: Brief summary of what changed and why}\n\n### Artifacts\n\n- Report: `$ARTIFACTS_DIR/../reports/{name}-report.md`\n\n### Next Steps\n\n1. Review the report (especially if deviations noted)\n2. Create PR (next workflow step)\n3. Merge when approved\n```\n\n---\n\n## Handling Failures\n\n### Type Check Fails\n\n1. Read error message carefully\n2. Fix the type issue\n3. Re-run the type-check command\n4. Don't proceed until passing\n\n### Tests Fail\n\n1. Identify which test failed\n2. Determine: implementation bug or test bug?\n3. Fix the root cause (usually implementation)\n4. Re-run tests\n5. Repeat until green\n\n### Lint Fails\n\n1. Run the lint fix command for auto-fixable issues\n2. Manually fix remaining issues\n3. Re-run lint\n4. Proceed when clean\n\n### Build Fails\n\n1. Usually a type or import issue\n2. Check the error output\n3. Fix and re-run\n\n### Integration Test Fails\n\n1. Check if server started correctly\n2. Verify endpoint exists\n3. Check request format\n4. Fix implementation and retry\n\n---\n\n## Success Criteria\n\n- **TASKS_COMPLETE**: All plan tasks executed\n- **TYPES_PASS**: Type-check command exits 0\n- **LINT_PASS**: Lint command exits 0 (warnings OK)\n- **TESTS_PASS**: Test command all green\n- **BUILD_PASS**: Build command succeeds\n- **REPORT_CREATED**: Implementation report exists\n", + "archon-investigate-issue": "---\ndescription: Investigate a GitHub issue or problem - analyze codebase, create plan, post to GitHub\nargument-hint: \n---\n\n# Investigate Issue\n\n**Input**: $ARGUMENTS\n\n---\n\n## Your Mission\n\nInvestigate the issue/problem and produce a comprehensive implementation plan that:\n\n1. Can be executed by `/implement-issue`\n2. Is posted as a GitHub comment (if GH issue provided)\n3. Captures all context needed for one-pass implementation\n\n**Golden Rule**: The artifact you produce IS the specification. The implementing agent should be able to work from it without asking questions.\n\n---\n\n## Phase 1: PARSE - Understand Input\n\n### 1.1 Determine Input Type\n\n**Check the input format:**\n\n- Looks like a number (`123`, `#123`) → GitHub issue number\n- Starts with `http` → GitHub URL (extract issue number)\n- Anything else → Free-form description\n\n```bash\n# If GitHub issue, fetch it:\ngh issue view {number} --json title,body,labels,comments,state,url,author\n```\n\n### 1.2 Extract Context\n\n**If GitHub issue:**\n- Title: What's the reported problem?\n- Body: Details, reproduction steps, expected vs actual\n- Labels: bug? enhancement? documentation?\n- Comments: Additional context from discussion\n- State: Is it still open?\n\n**If free-form:**\n- Parse as problem description\n- Note: No GitHub posting (artifact only)\n\n### 1.3 Classify Issue Type\n\n| Type | Indicators |\n|------|------------|\n| BUG | \"broken\", \"error\", \"crash\", \"doesn't work\", stack trace |\n| ENHANCEMENT | \"add\", \"support\", \"feature\", \"would be nice\" |\n| REFACTOR | \"clean up\", \"improve\", \"simplify\", \"reorganize\" |\n| CHORE | \"update\", \"upgrade\", \"maintenance\", \"dependency\" |\n| DOCUMENTATION | \"docs\", \"readme\", \"clarify\", \"example\" |\n\n### 1.4 Assess Severity/Priority, Complexity, and Confidence\n\nEach assessment requires a **one-sentence reasoning** explaining WHY you chose that value. This reasoning must be based on concrete findings from your investigation (codebase exploration, git history, integration analysis).\n\n**For BUG issues - Severity:**\n\n| Severity | Criteria |\n|----------|----------|\n| CRITICAL | System down, data loss, security vulnerability, no workaround |\n| HIGH | Major feature broken, significant user impact, difficult workaround |\n| MEDIUM | Feature partially broken, moderate impact, workaround exists |\n| LOW | Minor issue, cosmetic, edge case, easy workaround |\n\n**For ENHANCEMENT/REFACTOR/CHORE/DOCUMENTATION - Priority:**\n\n| Priority | Criteria |\n|----------|----------|\n| HIGH | Blocking other work, frequently requested, high user value |\n| MEDIUM | Important but not urgent, moderate user value |\n| LOW | Nice to have, low urgency, minimal user impact |\n\n**Complexity** (based on codebase findings):\n\n| Complexity | Criteria |\n|------------|----------|\n| HIGH | 5+ files, multiple integration points, architectural changes, high risk |\n| MEDIUM | 2-4 files, some integration points, moderate risk |\n| LOW | 1-2 files, isolated change, low risk |\n\n**Confidence** (based on evidence quality):\n\n| Confidence | Criteria |\n|------------|----------|\n| HIGH | Clear root cause, strong evidence, well-understood code path |\n| MEDIUM | Likely root cause, some assumptions, partially understood |\n| LOW | Uncertain root cause, limited evidence, many unknowns |\n\n**PHASE_1_CHECKPOINT:**\n- [ ] Input type identified (GH issue or free-form)\n- [ ] Issue content extracted\n- [ ] Type classified\n- [ ] Severity (bug) or Priority (other) assessed with reasoning\n- [ ] Complexity assessed with reasoning (after Phase 2)\n- [ ] Confidence assessed with reasoning (after Phase 3)\n- [ ] If GH issue: confirmed it's open and not already has PR\n\n---\n\n## Phase 2: EXPLORE - Codebase Intelligence\n\n### 2.1 Search for Relevant Code\n\nUse Task tool with subagent_type=\"Explore\":\n\n```\nExplore the codebase to understand the issue:\n\nISSUE: {title/description}\n\nDISCOVER:\n1. Files directly related to this functionality\n2. How the current implementation works\n3. Integration points - what calls this, what it calls\n4. Similar patterns elsewhere to mirror\n5. Existing test patterns for this area\n6. Error handling patterns used\n\nReturn:\n- File paths with specific line numbers\n- Actual code snippets (not summaries)\n- Dependencies and data flow\n```\n\n### 2.2 Document Findings\n\n| Area | File:Lines | Notes |\n|------|-----------|-------|\n| Core logic | `src/x.ts:10-50` | Main function affected |\n| Callers | `src/y.ts:20-30` | Uses the core function |\n| Types | `src/types/x.ts:5-15` | Relevant interfaces |\n| Tests | `src/x.test.ts:1-100` | Existing test patterns |\n| Similar | `src/z.ts:40-60` | Pattern to mirror |\n\n**PHASE_2_CHECKPOINT:**\n- [ ] Explore agent completed successfully\n- [ ] Core files identified with line numbers\n- [ ] Integration points mapped\n- [ ] Similar patterns found to mirror\n- [ ] Test patterns documented\n\n---\n\n## Phase 3: ANALYZE - Form Approach\n\n### 3.0 First-Principles Analysis\n\nBefore diving into bug analysis or enhancement scoping, identify the primitive:\n\n1. **What primitive is involved?** What is the core abstraction this bug/feature touches?\n (e.g., the condition evaluator, the approval system, the isolation provider)\n2. **Is the primitive sound?** Does the existing design handle this case, or is the\n primitive itself incomplete or missing a case?\n3. **Root cause vs symptom** — are we fixing where the error manifests, or where it\n originates? Trace the data flow back to the source.\n4. **What's the minimal change?** What is the smallest edit that fixes the root cause?\n Avoid adding new abstractions when extending existing ones works.\n5. **What does this unlock?** If we add/change a primitive, what other improvements\n become possible?\n\n| Primitive | File:Lines | Sound? | Notes |\n|-----------|-----------|--------|-------|\n| {abstraction name} | `src/x.ts:10-30` | Yes/No/Partial | {if incomplete: what's missing} |\n\n### 3.1 For BUG Issues - Root Cause Analysis\n\nApply the 5 Whys:\n\n```\nWHY 1: Why does [symptom] occur?\n→ Because [cause A]\n→ Evidence: `file.ts:123` - {code snippet}\n\nWHY 2: Why does [cause A] happen?\n→ Because [cause B]\n→ Evidence: {proof}\n\n... continue until you reach fixable code ...\n\nROOT CAUSE: [the specific code/logic to change]\nEvidence: `source.ts:456` - {the problematic code}\n```\n\n**Check git history:**\n```bash\ngit log --oneline -10 -- {affected-file}\ngit blame -L {start},{end} {affected-file}\n```\n\n### 3.2 For ENHANCEMENT/REFACTOR Issues\n\n**Identify:**\n- What needs to be added/changed?\n- Where does it integrate?\n- What are the scope boundaries?\n- What should NOT be changed?\n\n### 3.3 For All Issues\n\n**Determine:**\n- Files to CREATE (new files)\n- Files to UPDATE (existing files)\n- Files to DELETE (if any)\n- Dependencies and order of changes\n- Edge cases and risks\n- Validation strategy\n\n**PHASE_3_CHECKPOINT:**\n- [ ] Root cause identified (for bugs) OR change rationale clear (for enhancements)\n- [ ] All affected files listed with specific changes\n- [ ] Scope boundaries defined (what NOT to change)\n- [ ] Risks and edge cases identified\n- [ ] Validation approach defined\n\n---\n\n## Phase 4: GENERATE - Create Artifact\n\n### 4.1 Artifact Path\n\n```bash\n```\n\n**Path:** `$ARTIFACTS_DIR/investigation.md`\n\nThis unified path allows review agents to find the artifact regardless of workflow type.\n\n### 4.2 Artifact Template\n\nWrite this structure to the artifact file.\n\n**Note on Severity vs Priority:**\n- Use **Severity** for BUG type (CRITICAL, HIGH, MEDIUM, LOW)\n- Use **Priority** for all other types (HIGH, MEDIUM, LOW)\n\n**Important:** Each assessment must include a one-sentence reasoning based on your investigation findings.\n\n```markdown\n# Investigation: {Title}\n\n**Issue**: #{number} ({url})\n**Type**: {BUG|ENHANCEMENT|REFACTOR|CHORE|DOCUMENTATION}\n**Investigated**: {ISO timestamp}\n\n### Assessment\n\n| Metric | Value | Reasoning |\n|--------|-------|-----------|\n| Severity | {CRITICAL\\|HIGH\\|MEDIUM\\|LOW} | {Why this severity? Based on user impact, workarounds, scope of failure} |\n| Complexity | {LOW\\|MEDIUM\\|HIGH} | {Why this complexity? Based on files affected, integration points, risk} |\n| Confidence | {HIGH\\|MEDIUM\\|LOW} | {Why this confidence? Based on evidence quality, unknowns, assumptions} |\n\n\n\n---\n\n## Problem Statement\n\n{Clear 2-3 sentence description of what's wrong or what's needed}\n\n---\n\n## Analysis\n\n### Root Cause / Change Rationale\n\n{For BUG: The 5 Whys chain with evidence}\n{For ENHANCEMENT: Why this change and what it enables}\n\n### Evidence Chain\n\nWHY: {symptom}\n↓ BECAUSE: {cause 1}\n Evidence: `file.ts:123` - `{code snippet}`\n\n↓ BECAUSE: {cause 2}\n Evidence: `file.ts:456` - `{code snippet}`\n\n↓ ROOT CAUSE: {the fixable thing}\n Evidence: `file.ts:789` - `{problematic code}`\n\n### Affected Files\n\n| File | Lines | Action | Description |\n|------|-------|--------|-------------|\n| `src/x.ts` | 45-60 | UPDATE | {what changes} |\n| `src/x.test.ts` | NEW | CREATE | {test to add} |\n\n### Integration Points\n\n- `src/y.ts:20` calls this function\n- `src/z.ts:30` depends on this behavior\n- {other dependencies}\n\n### Git History\n\n- **Introduced**: {commit} - {date} - \"{message}\"\n- **Last modified**: {commit} - {date}\n- **Implication**: {regression? original bug? long-standing?}\n\n---\n\n## Implementation Plan\n\n### Step 1: {First change description}\n\n**File**: `src/x.ts`\n**Lines**: 45-60\n**Action**: UPDATE\n\n**Current code:**\n```typescript\n// Line 45-50\n{actual current code}\n```\n\n**Required change:**\n```typescript\n// What it should become\n{the fix/change}\n```\n\n**Why**: {brief rationale}\n\n---\n\n### Step 2: {Second change description}\n\n{Same structure...}\n\n---\n\n### Step N: Add/Update Tests\n\n**File**: `src/x.test.ts`\n**Action**: {CREATE|UPDATE}\n\n**Test cases to add:**\n```typescript\ndescribe('{feature}', () => {\n it('should {expected behavior}', () => {\n // Test the fix\n });\n\n it('should handle {edge case}', () => {\n // Test edge case\n });\n});\n```\n\n---\n\n## Patterns to Follow\n\n**From codebase - mirror these exactly:**\n\n```typescript\n// SOURCE: src/similar.ts:20-30\n// Pattern for {what this demonstrates}\n{actual code snippet from codebase}\n```\n\n---\n\n## Edge Cases & Risks\n\n| Risk/Edge Case | Mitigation |\n|----------------|------------|\n| {risk 1} | {how to handle} |\n| {edge case} | {how to handle} |\n\n---\n\n## Validation\n\n### Automated Checks\n\n```bash\nbun run type-check\nbun test {relevant-pattern}\nbun run lint\n```\n\n### Manual Verification\n\n1. {Step to verify the fix/feature works}\n2. {Step to verify no regression}\n\n---\n\n## Scope Boundaries\n\n**IN SCOPE:**\n- {what we're changing}\n\n**OUT OF SCOPE (do not touch):**\n- {what to leave alone}\n- {future improvements to defer}\n\n---\n\n## Metadata\n\n- **Investigated by**: Claude\n- **Timestamp**: {ISO timestamp}\n- **Artifact**: `$ARTIFACTS_DIR/investigation.md`\n```\n\n**PHASE_4_CHECKPOINT:**\n- [ ] Artifact file created\n- [ ] All sections filled with specific content\n- [ ] Code snippets are actual (not invented)\n- [ ] Steps are actionable without clarification\n\n---\n\n## Phase 5: POST - GitHub Comment\n\n**Only if input was a GitHub issue (not free-form):**\n\nFormat the artifact for GitHub and post:\n\n```bash\ngh issue comment {number} --body \"$(cat <<'EOF'\n## 🔍 Investigation: {Title}\n\n**Type**: `{TYPE}`\n\n### Assessment\n\n| Metric | Value | Reasoning |\n|--------|-------|-----------|\n| {Severity or Priority} | `{VALUE}` | {one-sentence why} |\n| Complexity | `{COMPLEXITY}` | {one-sentence why} |\n| Confidence | `{CONFIDENCE}` | {one-sentence why} |\n\n---\n\n### Problem Statement\n\n{problem statement from artifact}\n\n---\n\n### Root Cause Analysis\n\n{evidence chain, formatted for GitHub}\n\n---\n\n### Implementation Plan\n\n| Step | File | Change |\n|------|------|--------|\n| 1 | `src/x.ts:45` | {description} |\n| 2 | `src/x.test.ts` | Add test for {case} |\n\n
\n📋 Detailed Implementation Steps\n\n{detailed steps from artifact}\n\n
\n\n---\n\n### Validation\n\n```bash\nbun run type-check && bun test {pattern} && bun run lint\n```\n\n---\n\n### Next Step\n\nTo implement: `/implement-issue {number}`\n\n---\n*Investigated by Claude • {timestamp}*\nEOF\n)\"\n```\n\n**PHASE_5_CHECKPOINT:**\n- [ ] Comment posted to GitHub (if GH issue)\n- [ ] Formatting renders correctly\n\n---\n\n## Phase 6: REPORT - Output to User\n\n```markdown\n## Investigation Complete\n\n**Issue**: #{number} - {title}\n**Type**: {BUG|ENHANCEMENT|REFACTOR|...}\n\n### Assessment\n\n| Metric | Value | Reasoning |\n|--------|-------|-----------|\n| {Severity or Priority} | {value} | {why - based on investigation} |\n| Complexity | {LOW\\|MEDIUM\\|HIGH} | {why - based on files/integration/risk} |\n| Confidence | {HIGH\\|MEDIUM\\|LOW} | {why - based on evidence/unknowns} |\n\n### Key Findings\n\n- **Root Cause**: {one-line summary}\n- **Files Affected**: {count} files\n- **Estimated Changes**: {brief scope}\n\n### Files to Modify\n\n| File | Action |\n|------|--------|\n| `src/x.ts` | UPDATE |\n| `src/x.test.ts` | CREATE |\n\n### Artifact\n\n📄 `$ARTIFACTS_DIR/investigation.md`\n\n### GitHub\n\n{✅ Posted to issue | ⏭️ Skipped (free-form input)}\n\n### Next Step\n\nRun `/implement-issue {number}` to execute the plan.\n```\n\n---\n\n## Handling Edge Cases\n\n### Issue is already closed\n- Report: \"Issue #{number} is already closed\"\n- Still create artifact if user wants analysis\n\n### Issue already has linked PR\n- Warn: \"PR #{pr} already addresses this issue\"\n- Ask if user wants to continue anyway\n\n### Can't determine root cause\n- Document what you found\n- Set confidence to LOW\n- Note uncertainty in artifact\n- Proceed with best hypothesis\n\n### Very large scope\n- Suggest breaking into smaller issues\n- Focus on core problem first\n- Note deferred items in \"Out of Scope\"\n\n---\n\n## Success Criteria\n\n- **ARTIFACT_COMPLETE**: All sections filled with specific, actionable content\n- **EVIDENCE_BASED**: Every claim has file:line reference or proof\n- **IMPLEMENTABLE**: Another agent can execute without questions\n- **GITHUB_POSTED**: Comment visible on issue (if GH issue)\n- **COMMITTED**: Artifact saved in git\n", + "archon-issue-completion-report": "---\ndescription: Post completion report to GitHub issue with results, unaddressed items, and follow-up suggestions\nargument-hint: (none - reads from workflow artifacts)\n---\n\n# Issue Completion Report\n\n**Input**: $ARGUMENTS\n**Workflow ID**: $WORKFLOW_ID\n\n---\n\n## Your Mission\n\nCompile all workflow artifacts into a final report and post it to the original GitHub issue. Summarize what was done, what wasn't addressed (and why), and suggest follow-up issues if needed.\n\n**GitHub action**: Post completion report as a comment on the original issue\n**Output artifact**: `$ARTIFACTS_DIR/completion-report.md`\n\n---\n\n## Phase 1: LOAD — Gather All Artifacts\n\n### 1.1 Get Issue Number\n\nExtract issue number from `$ARGUMENTS`:\n\n```bash\n# $ARGUMENTS should be the issue number or URL\necho \"$ARGUMENTS\"\n```\n\n### 1.2 Get PR Info\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number 2>/dev/null || echo \"unknown\")\nPR_URL=$(cat $ARTIFACTS_DIR/.pr-url 2>/dev/null || echo \"unknown\")\necho \"PR: $PR_NUMBER ($PR_URL)\"\n```\n\n### 1.3 Read All Available Artifacts\n\nCheck for and read each artifact that may exist:\n\n```bash\n# Investigation/Plan\ncat $ARTIFACTS_DIR/investigation.md 2>/dev/null\ncat $ARTIFACTS_DIR/plan.md 2>/dev/null\n\n# Implementation\ncat $ARTIFACTS_DIR/implementation.md 2>/dev/null\n\n# Web research\ncat $ARTIFACTS_DIR/web-research.md 2>/dev/null\n\n# Validation\ncat $ARTIFACTS_DIR/validation.md 2>/dev/null\n\n# Review artifacts\nls $ARTIFACTS_DIR/review/ 2>/dev/null\ncat $ARTIFACTS_DIR/review/consolidated-review.md 2>/dev/null\ncat $ARTIFACTS_DIR/review/fix-report.md 2>/dev/null\n```\n\n### 1.4 Get Git Info\n\n```bash\ngit branch --show-current\ngit log --oneline -5\n```\n\n**PHASE_1_CHECKPOINT:**\n\n- [ ] Issue number identified\n- [ ] PR info loaded\n- [ ] All available artifacts read\n- [ ] Git state captured\n\n---\n\n## Phase 2: COMPILE — Build Report\n\n### 2.1 Summarize What Was Done\n\nFrom the artifacts, compile:\n\n- **Classification**: What type of issue (bug/feature/etc)\n- **Investigation/Plan**: Key findings and approach\n- **Implementation**: What was changed, files modified\n- **Validation**: Test results, lint, type-check\n- **Review**: What was reviewed, findings count\n- **Self-fix**: What review findings were fixed\n\n### 2.2 Identify Unaddressed Items\n\nFrom the fix report and consolidated review:\n\n- Findings that were SKIPPED (with reasons)\n- Findings that were BLOCKED (with reasons)\n- MEDIUM/LOW findings not auto-fixed\n- Any validation issues that persisted\n\n### 2.3 Suggest Follow-up Issues\n\nFor each unaddressed item, determine if it warrants a follow-up issue:\n\n| Item | Warrants Issue? | Why |\n|------|----------------|-----|\n| {skipped finding} | YES/NO | {reason} |\n\n**PHASE_2_CHECKPOINT:**\n\n- [ ] Summary compiled\n- [ ] Unaddressed items identified\n- [ ] Follow-up suggestions prepared\n\n---\n\n## Phase 3: GENERATE — Write Artifact\n\nWrite to `$ARTIFACTS_DIR/completion-report.md`:\n\n```markdown\n# Completion Report: Issue $ARGUMENTS\n\n**Date**: {ISO timestamp}\n**Workflow ID**: $WORKFLOW_ID\n**PR**: #{pr-number} ({pr-url})\n\n---\n\n## Summary\n\n{3-5 sentence overview of the entire workflow execution}\n\n---\n\n## Classification\n\n| Field | Value |\n|-------|-------|\n| Type | {bug/feature/enhancement/...} |\n| Complexity | {LOW/MEDIUM/HIGH} |\n| Confidence | {HIGH/MEDIUM/LOW} |\n\n---\n\n## What Was Done\n\n### Investigation/Planning\n\n{Brief summary of root cause or plan}\n\n### Implementation\n\n| File | Action | Description |\n|------|--------|-------------|\n| `{file}` | {CREATE/UPDATE} | {what changed} |\n\n### Validation\n\n| Check | Result |\n|-------|--------|\n| Type check | ✅ / ❌ |\n| Lint | ✅ / ❌ |\n| Tests | ✅ ({n} passed) / ❌ |\n\n### Review & Self-Fix\n\n- **Findings**: {n} total from review agents\n- **Fixed**: {n} (including tests, docs, simplification)\n- **Skipped**: {n}\n- **Blocked**: {n}\n\n---\n\n## Unaddressed Items\n\n{If none: \"All findings were addressed.\"}\n\n### Skipped\n\n| Finding | Severity | Reason |\n|---------|----------|--------|\n| {title} | {sev} | {reason} |\n\n### Blocked\n\n| Finding | Severity | Reason |\n|---------|----------|--------|\n| {title} | {sev} | {reason} |\n\n---\n\n## Suggested Follow-up Issues\n\n| Title | Priority | Description |\n|-------|----------|-------------|\n| \"{title}\" | {P1/P2/P3} | {brief description} |\n\n*(none)* if everything was addressed\n\n---\n\n## Artifacts\n\n| Artifact | Path |\n|----------|------|\n| Investigation/Plan | `$ARTIFACTS_DIR/{investigation or plan}.md` |\n| Web Research | `$ARTIFACTS_DIR/web-research.md` |\n| Implementation | `$ARTIFACTS_DIR/implementation.md` |\n| Consolidated Review | `$ARTIFACTS_DIR/review/consolidated-review.md` |\n| Fix Report | `$ARTIFACTS_DIR/review/fix-report.md` |\n```\n\n**PHASE_3_CHECKPOINT:**\n\n- [ ] Completion report written\n\n---\n\n## Phase 4: POST — GitHub Issue Comment\n\nPost to the original GitHub issue:\n\n```bash\nISSUE_NUMBER=$(echo \"$ARGUMENTS\" | grep -oE '[0-9]+')\n\ngh issue comment $ISSUE_NUMBER --body \"$(cat <<'EOF'\n## ✅ Issue Resolution Report\n\n**PR**: #{pr-number} ({pr-url})\n**Status**: COMPLETE\n\n---\n\n### Summary\n\n{Brief overview of what was done to resolve this issue}\n\n---\n\n### Changes Made\n\n| File | Change |\n|------|--------|\n| `{file}` | {description} |\n\n---\n\n### Validation\n\n✅ Type check | ✅ Lint | ✅ Tests ({n} passed)\n\n---\n\n### Review & Self-Fix\n\n- **{n}** review findings addressed\n- **{n}** tests added\n- **{n}** docs updated\n- **{n}** code simplifications applied\n\n---\n\n### Unaddressed Items\n\n{If none: \"All review findings were addressed in the PR.\"}\n\n{If any:}\n\n| Finding | Severity | Reason |\n|---------|----------|--------|\n| {title} | {sev} | {why not addressed} |\n\n---\n\n### Suggested Follow-up Issues\n\n{If any:}\n\n1. **{Issue Title}** ({priority}) — {brief description}\n\n{If none: \"No follow-up issues needed.\"}\n\n---\n\n*Resolved by Archon workflow `$WORKFLOW_ID`*\nEOF\n)\"\n```\n\n**PHASE_4_CHECKPOINT:**\n\n- [ ] GitHub comment posted to issue\n\n---\n\n## Phase 5: OUTPUT — Final Summary\n\n```markdown\n## Issue Resolution Complete\n\n**Issue**: $ARGUMENTS\n**PR**: #{pr-number}\n**Workflow**: $WORKFLOW_ID\n\n### Results\n\n- Implementation: ✅\n- Validation: ✅\n- Review: ✅\n- Self-fix: ✅\n\n### Unaddressed: {n} items\n### Follow-up issues suggested: {n}\n\n### Artifacts\n\n- Completion report: `$ARTIFACTS_DIR/completion-report.md`\n- GitHub comment: Posted to issue\n\n### Next Steps\n\n1. Review the PR: #{pr-number}\n2. Create suggested follow-up issues if agreed\n3. Merge when ready\n```\n\n---\n\n## Success Criteria\n\n- **ALL_ARTIFACTS_READ**: All workflow artifacts loaded and parsed\n- **REPORT_COMPILED**: Comprehensive completion report written\n- **GITHUB_POSTED**: Comment posted to original issue\n- **UNADDRESSED_DOCUMENTED**: Clear reasons for anything not fixed\n- **FOLLOWUPS_SUGGESTED**: Actionable follow-up issues recommended where appropriate\n", + "archon-plan-setup": "---\ndescription: Setup for plan execution - read plan, ensure branch ready, write context artifact\nargument-hint: \n---\n\n# Plan Setup\n\n**Plan**: $ARGUMENTS\n**Workflow ID**: $WORKFLOW_ID\n\n---\n\n## Your Mission\n\nPrepare everything needed for plan implementation:\n1. Read and parse the plan (including scope limits)\n2. Ensure we're on the correct branch\n3. Write a comprehensive context artifact for subsequent steps\n\n**This step does NOT implement anything** - it only sets up the environment.\n**This step does NOT create a PR** - that happens in `archon-finalize-pr` after implementation.\n\n---\n\n## Phase 1: LOAD - Read the Plan\n\n### 1.1 Locate Plan File\n\n**Check in order:**\n\n1. **If `$ARGUMENTS` provided**: Use that path\n2. **If plan already in workflow artifacts**: Use `$ARTIFACTS_DIR/plan.md`\n\n```bash\n# Check if plan was created by archon-create-plan in this workflow\nif [ -f \"$ARTIFACTS_DIR/plan.md\" ]; then\n PLAN_PATH=\"$ARTIFACTS_DIR/plan.md\"\n echo \"Using plan from workflow: $PLAN_PATH\"\nelif [ -n \"$ARGUMENTS\" ] && [ -f \"$ARGUMENTS\" ]; then\n PLAN_PATH=\"$ARGUMENTS\"\n echo \"Using plan from arguments: $PLAN_PATH\"\nelse\n echo \"ERROR: No plan found\"\n exit 1\nfi\n```\n\n### 1.2 Load Plan File\n\nRead the plan file:\n\n```bash\ncat $PLAN_PATH\n```\n\nIf `$ARGUMENTS` is a GitHub issue URL or number (e.g., `#123`), fetch the issue body instead.\n\n### 1.3 Extract Key Information\n\nFrom the plan, identify and extract:\n\n| Field | Where to Find | Example |\n|-------|---------------|---------|\n| **Title** | First `#` heading or \"Summary\" section | \"Discord Platform Adapter\" |\n| **Summary** | \"Summary\" or \"Feature Description\" section | 1-2 sentence overview |\n| **Files to Change** | \"Files to Change\" or \"Tasks\" section | List of CREATE/UPDATE files |\n| **Validation Commands** | \"Validation Commands\" or \"Validation Strategy\" | `bun run type-check`, etc. |\n| **Acceptance Criteria** | \"Acceptance Criteria\" section | Checklist items |\n| **NOT Building (Scope Limits)** | \"NOT Building\", \"Scope Limits\", or \"Out of Scope\" section | Explicit exclusions |\n\n**CRITICAL**: The \"NOT Building\" section defines what is **intentionally excluded** from scope. This MUST be captured and passed to review agents so they don't flag intentional exclusions as bugs.\n\n### 1.4 Derive Branch Name\n\nCreate a branch name from the plan title:\n\n```\nfeature/{slug}\n```\n\nWhere `{slug}` is the title lowercased, spaces replaced with hyphens, max 50 chars.\n\nExamples:\n- \"Discord Platform Adapter\" → `feature/discord-platform-adapter`\n- \"ESLint/Prettier Integration\" → `feature/eslint-prettier-integration`\n\n**PHASE_1_CHECKPOINT:**\n\n- [ ] Plan file loaded and readable\n- [ ] Key information extracted\n- [ ] Branch name derived\n\n---\n\n## Phase 2: PREPARE - Git State\n\n### 2.1 Check Current State\n\n```bash\ngit branch --show-current\ngit status --porcelain\ngit remote get-url origin\n```\n\n### 2.2 Determine Repository Info\n\nExtract owner/repo from the remote URL for PR creation:\n\n```bash\ngh repo view --json nameWithOwner -q .nameWithOwner\n```\n\n### 2.3 Branch Decision\n\nEvaluate in order (first matching case wins):\n\n```text\n┌─ IN WORKTREE?\n│ └─ YES → Use current branch AS-IS. Do NOT switch branches. Do NOT create\n│ new branches. The isolation system has already set up the correct\n│ branch; any deviation operates on the wrong code.\n│ Log: \"Using worktree branch: {name}\"\n│\n├─ ON $BASE_BRANCH? (main, master, or configured base branch)\n│ └─ Q: Working directory clean?\n│ ├─ YES → Create and checkout: `git checkout -b {branch-name}`\n│ │ (only applies outside a worktree — e.g., manual CLI usage)\n│ └─ NO → STOP: \"Uncommitted changes on $BASE_BRANCH. Stash or commit first.\"\n│\n└─ ON OTHER BRANCH?\n └─ Q: Does it match the expected branch for this plan?\n ├─ YES → Use it, log \"Using existing branch: {name}\"\n └─ NO → STOP: \"On branch {X}, expected {Y}. Switch branches or adjust plan.\"\n```\n\n### 2.4 Sync with Remote\n\n```bash\ngit fetch origin\ngit rebase origin/$BASE_BRANCH || git merge origin/$BASE_BRANCH\n```\n\nIf conflicts occur, STOP with error: \"Merge conflicts with $BASE_BRANCH. Resolve manually.\"\n\n### 2.5 Push Branch (if commits exist)\n\nIf there are commits on the branch:\n```bash\ngit push -u origin HEAD\n```\n\nIf no commits yet (fresh branch), skip push - it will happen after implementation.\n\n**PHASE_2_CHECKPOINT:**\n\n- [ ] On correct branch\n- [ ] No uncommitted changes\n- [ ] Up to date with base branch\n\n---\n\n## Phase 3: ARTIFACT - Write Context File\n\n### 3.1 Create Artifact Directory\n\n```bash\n```\n\n### 3.2 Write Context Artifact\n\nWrite to `$ARTIFACTS_DIR/plan-context.md`:\n\n```markdown\n# Plan Context\n\n**Generated**: {YYYY-MM-DD HH:MM}\n**Workflow ID**: $WORKFLOW_ID\n**Plan Source**: $ARGUMENTS\n\n---\n\n## Branch\n\n| Field | Value |\n|-------|-------|\n| **Branch** | {branch-name} |\n| **Base** | {base-branch} |\n\n---\n\n## Plan Summary\n\n**Title**: {extracted-title}\n\n**Overview**: {1-2 sentence summary from plan}\n\n---\n\n## Files to Change\n\n{Copy the \"Files to Change\" table from the plan, or list extracted files}\n\n| File | Action |\n|------|--------|\n| `src/example.ts` | CREATE |\n| `src/other.ts` | UPDATE |\n\n---\n\n## NOT Building (Scope Limits)\n\n**CRITICAL FOR REVIEWERS**: These items are **intentionally excluded** from scope. Do NOT flag them as bugs or missing features.\n\n{Copy from plan's \"NOT Building\", \"Scope Limits\", or \"Out of Scope\" section}\n\n- {Explicit exclusion 1 with rationale}\n- {Explicit exclusion 2 with rationale}\n\n{If no explicit exclusions in plan: \"No explicit scope limits defined in plan.\"}\n\n---\n\n## Validation Commands\n\n{Copy from plan's \"Validation Commands\" section}\n\n```bash\nbun run type-check\nbun run lint\nbun test\nbun run build\n```\n\n---\n\n## Acceptance Criteria\n\n{Copy from plan's \"Acceptance Criteria\" section}\n\n- [ ] Criterion 1\n- [ ] Criterion 2\n- [ ] ...\n\n---\n\n## Patterns to Mirror\n\n{Copy key file references from plan's \"Patterns to Mirror\" section}\n\n| Pattern | Source File | Lines |\n|---------|-------------|-------|\n| {pattern-name} | `src/example.ts` | 10-50 |\n\n---\n\n## Next Steps\n\n1. `archon-confirm-plan` - Verify patterns still exist\n2. `archon-implement-tasks` - Execute the plan\n3. `archon-validate` - Run full validation\n4. `archon-finalize-pr` - Create PR and mark ready\n```\n\n**PHASE_3_CHECKPOINT:**\n\n- [ ] Artifact directory created\n- [ ] `plan-context.md` written with all sections\n- [ ] \"NOT Building\" section captured (even if empty)\n\n---\n\n## Phase 4: OUTPUT - Report to User\n\n```markdown\n## Plan Setup Complete\n\n**Plan**: `$ARGUMENTS`\n**Workflow ID**: `$WORKFLOW_ID`\n\n### Branch\n\n| Field | Value |\n|-------|-------|\n| Branch | `{branch-name}` |\n| Base | `{base-branch}` |\n\n### Plan Summary\n\n**{plan-title}**\n\n{1-2 sentence overview}\n\n### Scope\n\n- {N} files to create\n- {M} files to update\n- {K} explicit exclusions captured\n\n### Artifact\n\nContext written to: `$ARTIFACTS_DIR/plan-context.md`\n\n### Next Step\n\nProceed to `archon-confirm-plan` to verify the plan's research is still valid.\n```\n\n---\n\n## Error Handling\n\n### Plan File Not Found\n\n```\n❌ Plan not found: $ARGUMENTS\n\nVerify the path exists and try again.\n```\n\n### Uncommitted Changes on Base Branch\n\n```\n❌ Uncommitted changes on base branch\n\nOptions:\n1. Stash changes: `git stash`\n2. Commit changes: `git add . && git commit -m \"WIP\"`\n3. Discard changes: `git checkout .`\n\nThen retry.\n```\n\n### Merge Conflicts\n\n```\n❌ Merge conflicts with $BASE_BRANCH\n\nResolve conflicts manually:\n1. `git status` to see conflicts\n2. Edit conflicting files\n3. `git add `\n4. `git rebase --continue`\n\nThen retry.\n```\n\n---\n\n## Success Criteria\n\n- **PLAN_LOADED**: Plan file read and parsed\n- **SCOPE_LIMITS_CAPTURED**: \"NOT Building\" section extracted (even if empty)\n- **BRANCH_READY**: On correct branch, synced with base branch\n- **ARTIFACT_WRITTEN**: `plan-context.md` contains all required sections including scope limits\n", + "archon-post-review-to-pr": "---\ndescription: Post code review findings as a comment on the PR\nargument-hint: (none - reads from artifacts)\n---\n\n# Post Review to PR\n\n---\n\n## Your Mission\n\nRead the code review findings artifact and post a formatted summary as a comment on the PR.\n\n---\n\n## Phase 1: LOAD - Get Context\n\n### 1.1 Get PR Number\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number)\n```\n\n**If not found:**\n```\n❌ No PR number found at $ARTIFACTS_DIR/.pr-number\nCannot post review without a PR number.\n```\n\n### 1.2 Read Review Findings\n\n```bash\ncat $ARTIFACTS_DIR/review/code-review-findings.md\n```\n\n**If not found:**\n```\n❌ No review findings found at $ARTIFACTS_DIR/review/code-review-findings.md\nRun code review first.\n```\n\n**PHASE_1_CHECKPOINT:**\n- [ ] PR number loaded\n- [ ] Review findings loaded\n\n---\n\n## Phase 2: FORMAT - Build PR Comment\n\n### 2.1 Extract Key Information\n\nFrom the review findings, extract:\n- **Verdict**: APPROVE / REQUEST_CHANGES / NEEDS_DISCUSSION\n- **Summary**: 2-3 sentence overview\n- **Findings**: All findings with severity and location\n- **Statistics**: Finding counts by severity\n\n### 2.2 Build Comment Body\n\nFormat the review as a GitHub-friendly comment:\n\n```markdown\n## 🔍 Code Review\n\n**Verdict**: {APPROVE ✅ | REQUEST_CHANGES ❌ | NEEDS_DISCUSSION 💬}\n\n{Summary from findings}\n\n---\n\n### Findings\n\n{For each finding:}\n\n#### {severity emoji} {title}\n\n**Severity**: {CRITICAL|HIGH|MEDIUM|LOW} · **Category**: {category} · **Location**: `{file}:{line}`\n\n{Issue description}\n\n
\nSuggested Fix\n\n```typescript\n{recommended fix code}\n```\n\n**Why**: {reasoning}\n\n
\n\n---\n\n{End of findings}\n\n### Summary\n\n| Severity | Count |\n|----------|-------|\n| 🔴 Critical | {n} |\n| 🟠 High | {n} |\n| 🟡 Medium | {n} |\n| 🔵 Low | {n} |\n\n{If positive observations exist:}\n\n### What's Done Well\n\n{Positive observations from review}\n\n---\n\n*Automated code review*\n```\n\n**Severity emojis:**\n- CRITICAL → 🔴\n- HIGH → 🟠\n- MEDIUM → 🟡\n- LOW → 🔵\n\n**PHASE_2_CHECKPOINT:**\n- [ ] Comment body formatted\n- [ ] All findings included\n- [ ] Statistics table present\n\n---\n\n## Phase 3: POST - Comment on PR\n\n### 3.1 Post the Comment\n\n```bash\ngh pr comment {PR_NUMBER} --body \"$(cat <<'EOF'\n{formatted comment body}\nEOF\n)\"\n```\n\n### 3.2 Verify\n\n```bash\n# Check the comment was posted\ngh pr view {PR_NUMBER} --comments --json comments --jq '.comments | length'\n```\n\n**PHASE_3_CHECKPOINT:**\n- [ ] Comment posted to PR\n- [ ] Verified comment exists\n\n---\n\n## Phase 4: OUTPUT - Report to User\n\n```markdown\n## Review Posted to PR\n\n**PR**: #{PR_NUMBER}\n**Verdict**: {verdict}\n**Findings**: {total count} ({critical} critical, {high} high, {medium} medium, {low} low)\n\nReview comment has been posted to the pull request.\n```\n\n---\n\n## Error Handling\n\n### PR not found\n- Verify PR number is correct\n- Check if PR is still open\n- Report error to user\n\n### Comment fails to post\n- Check GitHub authentication\n- Try with shorter body if too large\n- Report error with details\n\n### No findings\n- Post a clean review comment: \"No issues found. LGTM!\"\n\n---\n\n## Success Criteria\n\n- **FINDINGS_LOADED**: Review artifact read successfully\n- **COMMENT_FORMATTED**: PR comment built with all findings\n- **COMMENT_POSTED**: Comment visible on the PR\n", + "archon-pr-review-scope": "---\ndescription: Gather PR context, verify reviewability, and prepare artifacts directory for comprehensive review\nargument-hint: \n---\n\n# PR Review Scope\n\n**Input**: $ARGUMENTS\n\n---\n\n## Your Mission\n\nVerify the PR is in a reviewable state, gather all context needed for the parallel review agents, and prepare the artifacts directory structure.\n\n---\n\n## Phase 1: IDENTIFY - Determine PR\n\n### 1.1 Get PR Number\n\n```bash\nif [ -f \"$ARTIFACTS_DIR/.pr-number\" ]; then\n PR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number | tr -d '\\n' | tr -d ' ')\n if ! echo \"$PR_NUMBER\" | grep -qE '^[0-9]+$'; then\n PR_NUMBER=\"\"\n fi\nfi\n\n# From arguments (standalone review)\nif [ -z \"$PR_NUMBER\" ] && [ -n \"$ARGUMENTS\" ]; then\n PR_NUMBER=$(echo \"$ARGUMENTS\" | grep -oE '[0-9]+' | head -1)\nfi\n\n# From current branch\nif [ -z \"$PR_NUMBER\" ]; then\n PR_NUMBER=$(gh pr view --json number -q '.number' 2>/dev/null)\nfi\n\nif [ -z \"$PR_NUMBER\" ]; then\n echo \"ERROR: No PR number found\"\n exit 1\nfi\n\n# Write to registry for downstream steps (if not already there)\necho \"$PR_NUMBER\" > $ARTIFACTS_DIR/.pr-number\n```\n\n### 1.2 Fetch PR Details\n\n```bash\ngh pr view {number} --json number,title,body,url,headRefName,baseRefName,files,additions,deletions,changedFiles,state,author,isDraft,mergeable,mergeStateStatus\n```\n\n**Extract:**\n- PR number and title\n- Branch names (head → base)\n- Changed files list\n- Addition/deletion counts\n- Draft status\n- Mergeable status\n\n**PHASE_1_CHECKPOINT:**\n- [ ] PR number identified\n- [ ] PR is open (not merged/closed)\n- [ ] Basic metadata extracted\n\n---\n\n## Phase 2: VERIFY - Pre-Review Checks\n\n**Before launching review agents, verify the PR is in a reviewable state.**\n\n### 2.1 Check for Merge Conflicts\n\n```bash\ngh pr view {number} --json mergeable,mergeStateStatus --jq '.mergeable, .mergeStateStatus'\n```\n\n| Status | Action |\n|--------|--------|\n| `MERGEABLE` | Continue |\n| `CONFLICTING` | **STOP** - Tell user to resolve conflicts first |\n| `UNKNOWN` | Warn, continue (GitHub still calculating) |\n\n**If conflicts exist:**\n```markdown\n❌ **Cannot review: PR has merge conflicts**\n\nPlease resolve conflicts before requesting a review:\n```bash\ngit fetch origin {base}\ngit rebase origin/{base}\n# Resolve conflicts\ngit push --force-with-lease\n```\n\nThen re-request the review.\n```\n**Exit workflow if conflicts detected.**\n\n### 2.2 Check CI Status\n\n```bash\ngh pr checks {number} --json name,state,conclusion --jq '.[] | \"\\(.name): \\(.state) (\\(.conclusion // \"pending\"))\"'\n```\n\n| Status | Action |\n|--------|--------|\n| All passing | Continue |\n| Some failing | Warn, continue (note in scope) |\n| All failing | Warn strongly, continue (note in scope) |\n| Pending | Note, continue |\n\n**Flag CI status for review report.**\n\n### 2.3 Check Behind Base\n\n```bash\n# Get branch names\nPR_BASE=$(gh pr view {number} --json baseRefName --jq '.baseRefName')\nPR_HEAD=$(gh pr view {number} --json headRefName --jq '.headRefName')\n\n# Fetch and count\ngit fetch origin $PR_BASE --quiet\ngit fetch origin $PR_HEAD --quiet\n\n# Commits behind base branch\nBEHIND=$(git rev-list --count origin/$PR_HEAD..origin/$PR_BASE 2>/dev/null || echo \"0\")\n```\n\n| Commits Behind | Action |\n|----------------|--------|\n| 0-5 | Continue |\n| 6-15 | Warn, suggest rebase, continue |\n| 16+ | Warn strongly, recommend rebase before review |\n\n**If significantly behind:**\n```markdown\n⚠️ **Branch is {N} commits behind {base}**\n\nConsider rebasing before review to ensure you're reviewing against current code:\n```bash\ngit fetch origin {base}\ngit rebase origin/{base}\ngit push --force-with-lease\n```\n```\n\n### 2.4 Check Draft Status\n\n```bash\ngh pr view {number} --json isDraft --jq '.isDraft'\n```\n\n| Status | Action |\n|--------|--------|\n| `false` | Continue normally |\n| `true` | Note in scope, continue (user wants early feedback) |\n\n### 2.5 Check PR Size\n\n| Metric | Warning Threshold | Action |\n|--------|-------------------|--------|\n| Changed files | 20+ | Warn about review thoroughness |\n| Lines changed | 1000+ | Warn about review thoroughness |\n\n**If very large:**\n```markdown\n⚠️ **Large PR: {files} files, +{additions} -{deletions} lines**\n\nLarge PRs are harder to review thoroughly. Consider splitting into smaller PRs for better review quality.\n```\n\n### 2.6 Compile Reviewability Summary\n\n```markdown\n## Pre-Review Status\n\n| Check | Status | Notes |\n|-------|--------|-------|\n| Merge Conflicts | ✅ None / ❌ Has conflicts | {details} |\n| CI Status | ✅ Passing / ⚠️ Failing / ⏳ Pending | {details} |\n| Behind Base | ✅ Up to date / ⚠️ {N} commits behind | {details} |\n| Draft | ✅ Ready / 📝 Draft | {details} |\n| Size | ✅ Normal / ⚠️ Large ({N} files) | {details} |\n```\n\n**PHASE_2_CHECKPOINT:**\n- [ ] No merge conflicts (or workflow stopped)\n- [ ] CI status noted\n- [ ] Behind-base status checked\n- [ ] Draft status noted\n- [ ] Size warnings issued if needed\n\n---\n\n## Phase 3: CONTEXT - Gather Review Context\n\n### 3.1 Get Full Diff\n\n```bash\ngh pr diff {number}\n```\n\nStore this for reference - parallel agents will re-fetch as needed.\n\n### 3.2 List Changed Files by Type\n\n```bash\ngh pr view {number} --json files --jq '.files[].path'\n```\n\n**Categorize files:**\n- Source code (`.ts`, `.js`, `.py`, etc.)\n- Test files (`*.test.ts`, `*.spec.ts`, `test_*.py`)\n- Documentation (`*.md`, `docs/`)\n- Configuration (`.json`, `.yaml`, `.toml`)\n- Types/interfaces\n\n### 3.3 Check for CLAUDE.md\n\n```bash\ncat CLAUDE.md 2>/dev/null | head -100\n```\n\nNote key rules that reviewers should check against.\n\n### 3.4 Identify New Abstractions\n\nScan the diff for new abstractions introduced by this PR:\n\n- New interfaces, types, or abstract classes (search diff for `interface `, `type `, `abstract class`)\n- New utility modules or helper files (new `.ts` files that aren't feature files or tests)\n- New configuration keys or schema fields\n\nFor each new abstraction found, note it in the scope manifest under \"Review Focus Areas\" so the code review agent can verify it doesn't duplicate an existing primitive.\n\n```bash\n# Quick scan for new abstractions in diff\ngh pr diff {number} | grep \"^+\" | sed 's/^+//' | grep -E \"(^interface |^export interface |^type |^abstract class |^export class )\" | head -20\n```\n\n**PHASE_3_CHECKPOINT:**\n- [ ] Diff available\n- [ ] Files categorized by type\n- [ ] CLAUDE.md rules noted\n- [ ] New abstractions scanned\n\n---\n\n## Phase 3.5: PLAN/ISSUE CONTEXT - Check for Workflow Artifacts\n\n**CRITICAL**: If this PR was created by a workflow, there will be artifacts that contain important context for reviewers.\n\n### 3.5.1 Find Workflow Artifacts\n\nCheck for artifacts from EITHER workflow type:\n\n```bash\n# Option 1: Plan-based workflow (archon-plan-to-merge)\nls -t $ARTIFACTS_DIR/../runs/*/plan-context.md 2>/dev/null | head -1\n\n# Option 2: Issue-based workflow (archon-fix-github-issue)\nls -t $ARTIFACTS_DIR/../runs/*/investigation.md 2>/dev/null | head -1\n```\n\n### 3.5.2 Extract Scope Limits\n\n**If plan-context.md exists** (from plan workflow):\n\n```bash\n# Extract the NOT Building section\nsed -n '/## NOT Building/,/^## /p' $ARTIFACTS_DIR/../runs/*/plan-context.md | head -30\n```\n\n**If investigation.md exists** (from issue workflow):\n\n```bash\n# Extract the Scope Boundaries / OUT OF SCOPE section\nsed -n '/## Scope Boundaries/,/^## /p' $ARTIFACTS_DIR/../runs/*/investigation.md | head -30\n```\n\n**These are INTENTIONAL exclusions** - do NOT flag them as bugs or missing features!\n\n### 3.5.3 Check Implementation Report\n\n```bash\n# Look for implementation report (either workflow)\nls -t $ARTIFACTS_DIR/../runs/*/implementation.md 2>/dev/null | head -1\n```\n\n**If implementation.md exists**, note any deviations:\n\n```bash\n# Extract deviations section\nsed -n '/## Deviations/,/^## /p' $ARTIFACTS_DIR/../runs/*/implementation.md | head -20\n```\n\n**PHASE_3.5_CHECKPOINT:**\n- [ ] Workflow artifacts checked (plan-context.md OR investigation.md)\n- [ ] Scope limits extracted (NOT Building OR OUT OF SCOPE)\n- [ ] Implementation deviations noted (if available)\n\n---\n\n## Phase 4: PREPARE - Create Artifacts Directory\n\n### 4.1 Create Directory Structure\n\n```bash\nmkdir -p $ARTIFACTS_DIR/review\n```\n\n### 4.2 Clean Stale Artifacts\n\n```bash\n# Remove review directories older than 7 days\nfind $ARTIFACTS_DIR/../reviews/pr-* -maxdepth 0 -mtime +7 -exec rm -rf {} \\; 2>/dev/null || true\n```\n\n### 4.3 Create Scope Manifest\n\nWrite `$ARTIFACTS_DIR/review/scope.md`:\n\n```markdown\n# PR Review Scope: #{number}\n\n**Title**: {PR title}\n**URL**: {PR URL}\n**Branch**: {head} → {base}\n**Author**: {author}\n**Date**: {ISO timestamp}\n\n---\n\n## Pre-Review Status\n\n| Check | Status | Notes |\n|-------|--------|-------|\n| Merge Conflicts | {status} | {details} |\n| CI Status | {status} | {passing}/{total} checks |\n| Behind Base | {status} | {N} commits behind |\n| Draft | {status} | {Ready/Draft} |\n| Size | {status} | {files} files, +{add}/-{del} |\n\n---\n\n## Changed Files\n\n| File | Type | Additions | Deletions |\n|------|------|-----------|-----------|\n| `src/file.ts` | source | +10 | -5 |\n| `src/file.test.ts` | test | +20 | -0 |\n| ... | ... | ... | ... |\n\n**Total**: {changedFiles} files, +{additions} -{deletions}\n\n---\n\n## File Categories\n\n### Source Files ({count})\n- `src/...`\n\n### Test Files ({count})\n- `src/...test.ts`\n\n### Documentation ({count})\n- `$DOCS_DIR/...`\n- `README.md`\n\n### Configuration ({count})\n- `package.json`\n\n---\n\n## Review Focus Areas\n\nBased on changes, reviewers should focus on:\n\n1. **Code Quality**: {list key source files}\n2. **Error Handling**: {files with try/catch, error handling}\n3. **Test Coverage**: {new functionality needing tests}\n4. **Comments/Docs**: {files with documentation changes}\n5. **Docs Impact**: {check if CLAUDE.md or $DOCS_DIR need updates}\n6. **Primitive Alignment**: {If new abstractions found: list them} — verify no duplication of existing primitives\n\n---\n\n## CLAUDE.md Rules to Check\n\n{Extract key rules from CLAUDE.md that apply to this PR}\n\n---\n\n## Workflow Context (if from automated workflow)\n\n{If plan-context.md OR investigation.md was found:}\n\n### Scope Limits (NOT Building / OUT OF SCOPE)\n\n**CRITICAL FOR REVIEWERS**: These items are **intentionally excluded** from scope. Do NOT flag them as bugs or missing features.\n\n{From plan-context.md \"NOT Building\" section OR investigation.md \"Scope Boundaries/OUT OF SCOPE\" section}\n\n**IN SCOPE:**\n- {what we're changing}\n\n**OUT OF SCOPE (do not touch):**\n- {Explicit exclusion 1 with rationale}\n- {Explicit exclusion 2 with rationale}\n\n### Implementation Deviations\n\n{If implementation.md was found and has deviations:}\n\n{Copy the \"Deviations\" section from implementation.md}\n\n{If no workflow artifacts found:}\n\n_No workflow artifacts found - this appears to be a manual PR._\n\n---\n\n## CI Details\n\n{If CI failing, list which checks failed}\n\n---\n\n## Metadata\n\n- **Scope created**: {ISO timestamp}\n- **Artifact path**: `$ARTIFACTS_DIR/review/`\n```\n\n**PHASE_4_CHECKPOINT:**\n- [ ] Directory created\n- [ ] Stale artifacts cleaned\n- [ ] Scope manifest written with pre-review status\n\n---\n\n## Phase 5: OUTPUT - Report to User\n\n### If Blocked (Conflicts)\n\n```markdown\n## ❌ Review Blocked: Merge Conflicts\n\n**PR**: #{number} - {title}\n\nThis PR has merge conflicts that must be resolved before review.\n\n### To Resolve\n\n```bash\ngit fetch origin {base}\ngit checkout {head}\ngit rebase origin/{base}\n# Resolve conflicts in your editor\ngit add .\ngit rebase --continue\ngit push --force-with-lease\n```\n\nThen re-request the review: `@archon review this PR`\n```\n\n### If Proceeding\n\n```markdown\n## PR Review Scope Complete\n\n**PR**: #{number} - {title}\n**Files**: {count} changed (+{additions} -{deletions})\n\n### Pre-Review Status\n| Check | Status |\n|-------|--------|\n| Conflicts | ✅ None |\n| CI | {✅ Passing / ⚠️ {N} failing} |\n| Behind Base | {✅ Up to date / ⚠️ {N} behind} |\n| Draft | {✅ Ready / 📝 Draft} |\n| Size | {✅ Normal / ⚠️ Large} |\n\n### File Categories\n- Source: {count} files\n- Tests: {count} files\n- Docs: {count} files\n- Config: {count} files\n\n### Artifacts Directory\n`$ARTIFACTS_DIR/review/`\n\n### Next Step\nLaunching 5 parallel review agents...\n```\n\n---\n\n## Success Criteria\n\n- **PR_IDENTIFIED**: Valid open PR found\n- **NO_CONFLICTS**: Merge conflicts block workflow\n- **CONTEXT_GATHERED**: Diff and file list available\n- **ARTIFACTS_DIR_CREATED**: Directory structure exists\n- **SCOPE_MANIFEST_WRITTEN**: `scope.md` file created with pre-review status\n", + "archon-ralph-generate": "---\ndescription: Autonomously generate Ralph PRD files (prd.md + prd.json) from an idea or existing PRD\nargument-hint: \n---\n\n# Ralph PRD Generator (Autonomous)\n\n**Input**: $ARGUMENTS\n**Workflow ID**: $WORKFLOW_ID\n\n---\n\n## Your Mission\n\nGenerate production-quality Ralph PRD files — `prd.md` (full context document) and `prd.json` (story tracking) — through systematic codebase exploration and analysis. No interactive questions — make informed decisions autonomously.\n\n**Core Principle**: CODEBASE FIRST. Explore the project before writing anything. Stories must reference real files, real patterns, and real types.\n\n---\n\n## Phase 0: DETECT — Determine Input Type\n\n| Input Pattern | Type | Action |\n|---------------|------|--------|\n| Path to `.md` file that exists | Existing PRD | Read it, generate prd.json stories from it |\n| `.archon/ralph/{slug}/prd.md` exists | Existing PRD in ralph dir | Generate prd.json alongside it |\n| Free-form text | Feature idea | Generate both prd.md and prd.json |\n| Empty/blank | Error | STOP — require input |\n\n### If existing PRD detected:\n\n1. Read the PRD file\n2. Extract: problem statement, goals, user context, scope limits, technical requirements\n3. Skip to Phase 3 (Technical Grounding) — the PRD already covers Phases 1-2\n\n### If feature idea:\n\n1. Store the idea description\n2. Proceed through all phases\n\n---\n\n## Phase 1: UNDERSTAND — Problem & Context\n\n**Autonomously determine:**\n\n1. **Problem**: What pain point does this solve? What happens without it?\n2. **User**: Who benefits? What's their role and daily workflow?\n3. **Goal**: What's the ideal outcome? How will success be measured?\n4. **Scope**: What's MVP? What's explicitly out of scope?\n5. **Success metrics**: What measurable signals indicate this worked?\n\nBase these on the input description and your understanding of the codebase.\n\n**PHASE_1_CHECKPOINT:**\n- [ ] Problem clearly articulated\n- [ ] Target user identified\n- [ ] Goals and success metrics defined\n- [ ] Scope boundaries set\n\n---\n\n## Phase 2: UX & DESIGN — User Journey\n\n**Autonomously determine:**\n\n1. **Trigger**: What event causes the user to need this feature?\n2. **Happy path**: Step-by-step user flow from trigger to success\n3. **States**: Empty, loading, error, success — what does each look like?\n4. **Edge cases**: What can go wrong? How should it be handled?\n5. **Interaction model**: CLI commands, API endpoints, UI components?\n\nIf the feature has a UI component, describe the visual requirements.\nIf it's backend-only, describe the API surface.\n\n**PHASE_2_CHECKPOINT:**\n- [ ] User journey mapped\n- [ ] States enumerated\n- [ ] Edge cases identified\n\n---\n\n## Phase 3: TECHNICAL GROUNDING — Codebase Exploration\n\n**This is the critical phase.** Use the Task tool with `subagent_type=\"Explore\"` to systematically explore the codebase.\n\n### 3.1 Find Similar Implementations\n\n```\nExplore the codebase for patterns relevant to: {feature description}\n\nFIND:\n1. Similar implementations to mirror (with file:line references)\n2. Existing types/interfaces to extend or use\n3. Naming conventions (functions, files, variables)\n4. Error handling patterns\n5. Test patterns (framework, structure, assertion style)\n6. Database schema patterns (if applicable)\n7. Component patterns (if UI involved)\n```\n\n### 3.2 Identify Integration Points\n\n```\nTrace data flow and entry points for: {feature description}\n\nFIND:\n1. Where new code connects to existing code\n2. Which modules/packages are affected\n3. Import patterns to follow\n4. Config/env dependencies\n```\n\n### 3.3 Read Project Rules\n\n```bash\ncat CLAUDE.md\n```\n\nExtract: coding standards, naming conventions, testing requirements, lint rules.\n\n**PHASE_3_CHECKPOINT:**\n- [ ] Similar implementations found with file:line references\n- [ ] Types and interfaces identified\n- [ ] Integration points mapped\n- [ ] CLAUDE.md rules noted\n\n---\n\n## Phase 4: STORY BREAKDOWN — Split Into Iterations\n\n### 4.1 Identify Layers\n\nBreak the feature into implementation layers:\n\n| Layer | Examples | Typical story count |\n|-------|---------|-------------------|\n| Schema/types | DB columns, interfaces, Zod schemas | 1-2 |\n| Backend logic | Services, utilities, API endpoints | 2-4 |\n| UI components | New components, modifications | 1-3 |\n| Integration | Wiring, config, exports | 1-2 |\n| Tests | Dedicated test stories (if complex) | 0-2 |\n\n### 4.2 Sizing Rules\n\nEach story must be completable in ONE iteration (~15-30 min of AI work):\n\n**Right-sized (ONE iteration):**\n- Add a database column + migration\n- Create one utility function + tests\n- Add one UI component\n- Update one API endpoint + tests\n- Write integration tests for one feature\n\n**TOO BIG (must split):**\n- \"Build entire feature\" → split into schema, types, backend, UI\n- \"Add authentication\" → split into schema, middleware, login UI, token handling\n- \"Refactor module\" → split by file or concern\n\n### 4.3 Dependency Ordering\n\n- Stories ordered by dependency (lower priority = runs first)\n- Schema before types before backend before UI before integration\n- `dependsOn` must only reference lower-priority stories\n- Validate: no circular dependencies, no forward references\n\n### 4.4 Acceptance Criteria Rules\n\n**GOOD (verifiable):**\n- \"Add `priority` column with type `'high' | 'medium' | 'low'`\"\n- \"Function returns empty array when input is null\"\n- \"Button shows loading state while submitting\"\n- \"Type-check passes with zero errors\"\n\n**BAD (vague):**\n- \"Works correctly\"\n- \"Good UX\"\n- \"Handles edge cases\"\n\nEvery criterion must be pass/fail testable.\n\n**PHASE_4_CHECKPOINT:**\n- [ ] Stories sized for single iterations\n- [ ] Dependencies form a valid DAG (no cycles)\n- [ ] Acceptance criteria are all verifiable\n- [ ] Technical notes reference real files and patterns\n\n---\n\n## Phase 5: GENERATE — Write PRD Files\n\n### 5.1 Determine Feature Slug\n\nGenerate a kebab-case slug from the feature name:\n- \"Workflow Lifecycle Overhaul\" → `workflow-lifecycle-overhaul`\n- \"Dark Mode Toggle\" → `dark-mode-toggle`\n- Max 50 characters\n\n### 5.2 Create Directory\n\n```bash\nmkdir -p .archon/ralph/{slug}\n```\n\n### 5.3 Write prd.md\n\n**Output path**: `.archon/ralph/{slug}/prd.md`\n\nInclude ALL of the following sections:\n\n```markdown\n# {Feature Name} — Product Requirements\n\n## Overview\n\n**Problem**: {What pain this solves — from Phase 1}\n**Solution**: {What we're building}\n**Branch**: `ralph/{slug}`\n\n---\n\n## Goals & Success\n\n### Primary Goal\n{The main outcome}\n\n### Success Metrics\n| Metric | Target | How Measured |\n|--------|--------|--------------|\n| {metric} | {target} | {method} |\n\n### Non-Goals (Out of Scope)\n- {Item 1} — {why excluded}\n- {Item 2} — {why excluded}\n\n---\n\n## User & Context\n\n### Target User\n- **Who**: {description}\n- **Role**: {their context}\n- **Current Pain**: {what they struggle with}\n\n### User Journey\n1. **Trigger**: {what prompts the need}\n2. **Action**: {what they do}\n3. **Outcome**: {success state}\n\n---\n\n## UX Requirements\n\n### Interaction Model\n{How users interact — CLI commands, API endpoints, UI components}\n\n### States to Handle\n| State | Description | Behavior |\n|-------|-------------|----------|\n| Empty | {when} | {what happens} |\n| Loading | {when} | {what happens} |\n| Error | {when} | {what happens} |\n| Success | {when} | {what happens} |\n\n---\n\n## Technical Context\n\n### Patterns to Follow\n- **Similar implementation**: `{file:lines}` — {what to mirror}\n- **Component pattern**: `{file:lines}` — {pattern description}\n- **Test pattern**: `{file:lines}` — {how to test}\n\n### Types & Interfaces\n```typescript\n// Key types to use or extend\n{relevant type definitions from codebase exploration}\n```\n\n### Architecture Notes\n- {Key technical decisions}\n- {Integration points from Phase 3}\n- {Dependencies}\n\n---\n\n## Implementation Summary\n\n### Story Overview\n| ID | Title | Priority | Dependencies |\n|----|-------|----------|--------------|\n| US-001 | {title} | 1 | — |\n| US-002 | {title} | 2 | US-001 |\n\n### Dependency Graph\n```\nUS-001 (schema/types)\n ↓\nUS-002 (backend)\n ↓\nUS-003 (UI) → US-004 (integration)\n```\n\n---\n\n## Validation Requirements\n\nEvery story must pass:\n- [ ] Type-check: `bun run type-check`\n- [ ] Lint: `bun run lint`\n- [ ] Tests: `bun run test`\n- [ ] Format: `bun run format:check`\n\n---\n\n*Generated: {ISO timestamp}*\n```\n\n**If input was an existing PRD**: Incorporate its content into this structure. Don't lose information — merge the existing PRD's goals, context, and requirements into the appropriate sections. Add the technical context from your codebase exploration (Phase 3).\n\n### 5.4 Write prd.json\n\n**Output path**: `.archon/ralph/{slug}/prd.json`\n\n```json\n{\n \"project\": \"{ProjectName}\",\n \"branchName\": \"ralph/{slug}\",\n \"prdFile\": \"prd.md\",\n \"description\": \"{One line summary}\",\n \"userStories\": [\n {\n \"id\": \"US-001\",\n \"title\": \"{Short title}\",\n \"description\": \"As a {user}, I want {capability} so that {benefit}\",\n \"acceptanceCriteria\": [\n \"{Specific verifiable criterion 1}\",\n \"{Specific verifiable criterion 2}\",\n \"Type-check passes\",\n \"Tests pass\"\n ],\n \"technicalNotes\": \"{Files to modify, patterns to follow, types to use — from Phase 3}\",\n \"dependsOn\": [],\n \"priority\": 1,\n \"passes\": false,\n \"notes\": \"\"\n }\n ]\n}\n```\n\n### 5.5 Commit PRD Files\n\n```bash\ngit add .archon/ralph/{slug}/\ngit commit -m \"docs: add Ralph PRD for {feature name}\"\n```\n\n**PHASE_5_CHECKPOINT:**\n- [ ] `.archon/ralph/{slug}/prd.md` written with all sections\n- [ ] `.archon/ralph/{slug}/prd.json` written with properly sized stories\n- [ ] Stories have verifiable acceptance criteria\n- [ ] Technical notes reference real files from codebase exploration\n- [ ] Files committed\n\n---\n\n## Phase 6: OUTPUT — Report\n\n```\nPRD_DIR=.archon/ralph/{slug}\nSTORIES_TOTAL={count}\nFILES_CREATED=prd.md,prd.json\n\n## Ralph PRD Ready\n\n**Feature**: {name}\n**Directory**: `.archon/ralph/{slug}/`\n**Stories**: {count} user stories\n**Dependencies**: Valid DAG (no cycles)\n\n| # | ID | Title | Dependencies |\n|---|-----|-------|--------------|\n| 1 | US-001 | {title} | — |\n| 2 | US-002 | {title} | US-001 |\n```\n\n---\n\n## Success Criteria\n\n- **CONTEXT_COMPLETE**: prd.md has goals, user context, UX, technical patterns from real codebase exploration\n- **STORIES_SIZED**: Each story completable in one iteration\n- **DEPENDENCIES_VALID**: No circular dependencies, lower priority runs first\n- **CRITERIA_VERIFIABLE**: All acceptance criteria are pass/fail testable\n- **TECHNICAL_GROUNDED**: Technical notes reference real files, types, and patterns from the codebase\n- **FILES_WRITTEN**: Both prd.md and prd.json exist in `.archon/ralph/{slug}/`\n", + "archon-ralph-prd": "# Ralph PRD Generator\n\n**Input**: $ARGUMENTS\n\n---\n\n## Your Role\n\nYou are creating a PRD for the Ralph autonomous loop. You generate TWO files:\n1. `prd.md` - Full context document (goals, persona, UX, success criteria)\n2. `prd.json` - Story tracking with passes/fails\n\nEach Ralph iteration receives the FULL prd.md context plus its specific story from prd.json.\n\n**Critical Rules:**\n- Each story must be completable in ONE iteration\n- Stories ordered by dependency (schema → backend → UI)\n- Acceptance criteria must be VERIFIABLE (not vague)\n\n---\n\n## Phase 1: INITIATE\n\n**If no input provided**, ask:\n\n> **What do you want to build?**\n> Describe the feature or capability in a few sentences.\n\n**If input provided**, confirm:\n\n> I understand you want to build: {restated understanding}\n> Is this correct?\n\n**GATE**: Wait for confirmation.\n\n---\n\n## Phase 2: FOUNDATION\n\nAsk these questions together:\n\n> **Foundation Questions:**\n>\n> 1. **Problem**: What pain point does this solve? What happens if we don't build it?\n>\n> 2. **User**: Who is this for? Describe their role and context.\n>\n> 3. **Goal**: What's the ideal outcome if this succeeds?\n>\n> 4. **Scope**: MVP or full implementation? What's explicitly out of scope?\n>\n> 5. **Success**: How will we measure if this worked? What metrics matter?\n\n**GATE**: Wait for answers.\n\n---\n\n## Phase 3: UX & DESIGN\n\nAsk:\n\n> **UX Questions:**\n>\n> 1. **User Journey**: What triggers the user to need this? What's the happy path?\n>\n> 2. **UI Requirements**: Any specific visual requirements? Colors, placement, components?\n>\n> 3. **Interaction Model**: How does the user interact? Clicks, keyboard, API?\n>\n> 4. **Edge Cases**: What error states need handling? Empty states?\n>\n> 5. **Accessibility**: Any a11y requirements?\n\n**GATE**: Wait for answers.\n\n---\n\n## Phase 4: TECHNICAL GROUNDING\n\n**Use Explore agent:**\n\n```\nExplore the codebase for patterns relevant to: {feature}\n\nFIND:\n1. Similar implementations to mirror (with file:line references)\n2. Existing types/interfaces to extend\n3. Component patterns to follow\n4. Test patterns used\n5. Database schema patterns\n```\n\n**Summarize:**\n\n> **Technical Context:**\n> - Similar pattern: {file:lines}\n> - Types to extend: {types}\n> - Components to use: {components}\n> - Test pattern: {pattern}\n>\n> Any additional technical constraints?\n\n**GATE**: Brief pause for input.\n\n---\n\n## Phase 5: STORY BREAKDOWN\n\nAsk:\n\n> **Story Planning:**\n>\n> 1. **Database**: Schema changes needed? New tables/columns?\n>\n> 2. **Types**: New interfaces or type extensions?\n>\n> 3. **Backend**: Server logic, API endpoints, services?\n>\n> 4. **UI Components**: New components or modifications?\n>\n> 5. **Integration**: How do pieces connect?\n\n**GATE**: Wait for answers.\n\n---\n\n## Phase 6: GENERATE FILES\n\n**Naming Convention**: Use the feature name as a kebab-case slug.\n- Feature: \"User Authentication\" → slug: `user-authentication`\n- Feature: \"Dark Mode Toggle\" → slug: `dark-mode-toggle`\n\n**First**, create the ralph directory for this feature:\n```bash\n# Replace {feature-slug} with the actual kebab-case feature name\nmkdir -p .archon/ralph/{feature-slug}\n```\n\n### File 1: prd.md\n\n**Output path**: `.archon/ralph/{feature-slug}/prd.md`\n\n```markdown\n# {Feature Name} - Product Requirements\n\n## Overview\n\n**Problem**: {What pain this solves}\n**Solution**: {What we're building}\n**Branch**: `ralph/{feature-kebab}`\n\n---\n\n## Goals & Success\n\n### Primary Goal\n{The main outcome we want}\n\n### Success Metrics\n| Metric | Target | How Measured |\n|--------|--------|--------------|\n| {metric} | {target} | {method} |\n\n### Non-Goals (Out of Scope)\n- {Item 1} - {why excluded}\n- {Item 2} - {why excluded}\n\n---\n\n## User & Context\n\n### Target User\n- **Who**: {Specific description}\n- **Role**: {Their job/context}\n- **Current Pain**: {What they struggle with today}\n\n### User Journey\n1. **Trigger**: {What prompts the need}\n2. **Action**: {What they do}\n3. **Outcome**: {What success looks like}\n\n### Jobs to Be Done\nWhen {situation}, I want to {motivation}, so I can {outcome}.\n\n---\n\n## UX Requirements\n\n### Visual Design\n- {Color/style requirements}\n- {Component preferences}\n- {Layout requirements}\n\n### Interaction Model\n- {How users interact}\n- {Keyboard shortcuts if any}\n- {Mobile considerations}\n\n### States to Handle\n| State | Description | UI Behavior |\n|-------|-------------|-------------|\n| Empty | {when} | {show what} |\n| Loading | {when} | {show what} |\n| Error | {when} | {show what} |\n| Success | {when} | {show what} |\n\n### Accessibility\n- {A11y requirements}\n\n---\n\n## Technical Context\n\n### Patterns to Follow\n- **Similar implementation**: `{file:lines}` - {what to mirror}\n- **Component pattern**: `{file:lines}` - {pattern description}\n- **Test pattern**: `{file:lines}` - {how to test}\n\n### Types & Interfaces\n```typescript\n// Extend or use these existing types:\n{relevant type definitions}\n```\n\n### Architecture Notes\n- {Key technical decisions}\n- {Integration points}\n- {Dependencies}\n\n---\n\n## Implementation Summary\n\n### Story Overview\n| ID | Title | Priority | Dependencies |\n|----|-------|----------|--------------|\n| US-001 | {title} | 1 | - |\n| US-002 | {title} | 2 | US-001 |\n{...}\n\n### Dependency Graph\n```\nUS-001 (schema)\n ↓\nUS-002 (types)\n ↓\nUS-003 (backend) → US-004 (UI components)\n ↓\n US-005 (integration)\n```\n\n---\n\n## Validation Requirements\n\nEvery story must pass:\n- [ ] Typecheck: `bun run type-check`\n- [ ] Lint: `bun run lint`\n- [ ] Tests: `bun test`\n\n---\n\n*Generated: {ISO timestamp}*\n```\n\n### File 2: prd.json\n\n**Output path**: `.archon/ralph/{feature-slug}/prd.json`\n\n```json\n{\n \"project\": \"{ProjectName}\",\n \"branchName\": \"ralph/{feature-kebab}\",\n \"prdFile\": \"prd.md\",\n \"description\": \"{One line summary}\",\n \"userStories\": [\n {\n \"id\": \"US-001\",\n \"title\": \"{Short title}\",\n \"description\": \"As a {user}, I want {capability} so that {benefit}\",\n \"acceptanceCriteria\": [\n \"{Specific verifiable criterion}\",\n \"Typecheck passes\"\n ],\n \"technicalNotes\": \"{Implementation hints from prd.md}\",\n \"dependsOn\": [],\n \"priority\": 1,\n \"passes\": false,\n \"notes\": \"\"\n }\n ]\n}\n```\n\n### Story Sizing Rules\n\n**Right-sized (ONE iteration):**\n- Add a database column + migration\n- Create one utility function + tests\n- Add one UI component\n- Update one API endpoint\n\n**TOO BIG (split):**\n- \"Build entire feature\" → schema, types, backend, UI\n- \"Add authentication\" → schema, middleware, login UI\n\n### Acceptance Criteria Rules\n\n**GOOD (verifiable):**\n- \"Add `priority` column with type 'high' | 'medium' | 'low'\"\n- \"Function returns empty array when input is null\"\n- \"Button shows loading state while submitting\"\n\n**BAD (vague):**\n- \"Works correctly\"\n- \"Good UX\"\n- \"Handles edge cases\"\n\n---\n\n## Phase 7: OUTPUT\n\nAfter generating both files, report:\n\n```markdown\n## Ralph PRD Created\n\n### Files Generated\n\n| File | Purpose |\n|------|---------|\n| `.archon/ralph/{feature-slug}/prd.md` | Full context - goals, UX, technical patterns |\n| `.archon/ralph/{feature-slug}/prd.json` | Story tracking - passes/fails per story |\n\n### Summary\n\n**Feature**: {name}\n**Branch**: `ralph/{feature}`\n**Stories**: {count} user stories\n**Estimated iterations**: {count}\n\n### User Stories\n\n| # | ID | Title | Dependencies |\n|---|-----|-------|--------------|\n| 1 | US-001 | {title} | - |\n| 2 | US-002 | {title} | US-001 |\n{...}\n\n### Context Passed to Each Iteration\n\nEach Ralph iteration receives:\n1. **Full PRD** (`.archon/ralph/{feature-slug}/prd.md`) - Goals, persona, UX, technical patterns\n2. **Current Story** - From `.archon/ralph/{feature-slug}/prd.json` with acceptance criteria\n3. **Previous Learnings** - From `.archon/ralph/{feature-slug}/progress.txt`\n\n### To Start\n\n```bash\n# Create feature branch\ngit checkout -b ralph/{feature-slug}\n\n# Initialize progress\necho \"# Ralph Progress Log\\nStarted: $(date)\\n---\" > .archon/ralph/{feature-slug}/progress.txt\n\n# Run Ralph - specify the feature directory\n@Archon run ralph .archon/ralph/{feature-slug}\n```\n```\n\n---\n\n## Question Flow\n\n```\nINITIATE → FOUNDATION → UX/DESIGN → TECHNICAL → BREAKDOWN → GENERATE\n ↓ ↓ ↓ ↓ ↓ ↓\n Confirm Problem, Journey, Patterns, Stories, prd.md +\n idea User, UI reqs, Types, DB/API/ prd.json\n Goals States Tests UI split\n```\n\n---\n\n## Success Criteria\n\n- **CONTEXT_COMPLETE**: prd.md has goals, persona, UX, technical context\n- **STORIES_SIZED**: Each story completable in one iteration\n- **DEPENDENCIES_VALID**: Lower priority never depends on higher\n- **CRITERIA_VERIFIABLE**: All acceptance criteria are pass/fail\n- **READY_TO_RUN**: User can immediately start Ralph loop\n", + "archon-resolve-merge-conflicts": "---\ndescription: Analyze and resolve merge conflicts in a PR\nargument-hint: \n---\n\n# Resolve Merge Conflicts\n\n**Input**: $ARGUMENTS\n\n---\n\n## Your Mission\n\nAnalyze merge conflicts in the PR, automatically resolve simple conflicts where intent is clear, present options for complex conflicts, and push the resolution.\n\n---\n\n## Phase 1: IDENTIFY - Get PR and Conflict Info\n\n### 1.1 Parse Input\n\n**Check input format:**\n- Number (`123`, `#123`) → GitHub PR number\n- URL (`https://github.com/...`) → Extract PR number\n- Empty → Check current branch for open PR\n\n```bash\ngh pr view {number} --json number,title,headRefName,baseRefName,mergeable,mergeStateStatus\n```\n\n### 1.2 Verify Conflicts Exist\n\n```bash\ngh pr view {number} --json mergeable,mergeStateStatus --jq '.mergeable, .mergeStateStatus'\n```\n\n| Status | Action |\n|--------|--------|\n| `CONFLICTING` | Continue with resolution |\n| `MERGEABLE` | Report \"No conflicts to resolve\" and exit |\n| `UNKNOWN` | Wait and retry, or proceed with caution |\n\n**If no conflicts:**\n```markdown\n## ✅ No Conflicts\n\nPR #{number} has no merge conflicts. It's ready for review/merge.\n```\n**Exit if no conflicts.**\n\n### 1.3 Setup Local Branch\n\n```bash\n# Get branch info\nPR_HEAD=$(gh pr view {number} --json headRefName --jq '.headRefName')\nPR_BASE=$(gh pr view {number} --json baseRefName --jq '.baseRefName')\n\n# Fetch latest\ngit fetch origin $PR_BASE\ngit fetch origin $PR_HEAD\n\n# Checkout the PR branch\ngit checkout $PR_HEAD\ngit pull origin $PR_HEAD\n```\n\n**PHASE_1_CHECKPOINT:**\n- [ ] PR identified with conflicts\n- [ ] Branches fetched\n- [ ] On PR branch locally\n\n---\n\n## Phase 2: ANALYZE - Understand the Conflicts\n\n### 2.1 Attempt Rebase to Surface Conflicts\n\n```bash\ngit rebase origin/$PR_BASE\n```\n\nThis will stop at the first conflict. Note the output.\n\n### 2.2 Identify Conflicting Files\n\n```bash\ngit diff --name-only --diff-filter=U\n```\n\nList all files with conflicts.\n\n### 2.3 Analyze Each Conflict\n\nFor each conflicting file:\n\n```bash\n# Show the conflict markers\ngit diff --check\ncat {file} | grep -A 10 -B 2 \"<<<<<<<\"\n```\n\n**Categorize each conflict:**\n\n| Type | Description | Auto-resolvable? |\n|------|-------------|------------------|\n| **SIMPLE_ADDITION** | One side added, other didn't change that area | ✅ Yes |\n| **SIMPLE_DELETION** | One side deleted, other didn't change | ⚠️ Maybe (check intent) |\n| **DIFFERENT_AREAS** | Both changed but different lines | ✅ Yes |\n| **SAME_LINES** | Both changed the exact same lines | ❌ No - needs decision |\n| **STRUCTURAL** | File moved/renamed + modified | ❌ No - needs decision |\n\n### 2.4 Read Both Versions\n\nFor complex conflicts, understand what each side was trying to do:\n\n```bash\n# Show base version (common ancestor)\ngit show :1:{file} 2>/dev/null || echo \"File didn't exist in base\"\n\n# Show \"ours\" version (HEAD/current branch)\ngit show :2:{file}\n\n# Show \"theirs\" version (incoming from base branch)\ngit show :3:{file}\n```\n\n**PHASE_2_CHECKPOINT:**\n- [ ] All conflicting files identified\n- [ ] Each conflict categorized\n- [ ] Both sides' intent understood\n\n---\n\n## Phase 3: RESOLVE - Fix the Conflicts\n\n### 3.1 Auto-Resolve Simple Conflicts\n\nFor conflicts where intent is clear:\n\n```bash\n# For each auto-resolvable file\n# Edit to keep both changes (if both are additive)\n# Or keep the appropriate side based on intent\n```\n\n**Auto-resolution rules:**\n1. **Both added different things**: Keep both additions\n2. **One updated, one didn't touch**: Keep the update\n3. **Import additions**: Merge both import lists\n4. **Comment changes**: Prefer the more informative version\n\n### 3.2 Present Options for Complex Conflicts\n\nFor conflicts that need human decision:\n\n```markdown\n## Conflict in `{file}`\n\n**Lines {start}-{end}**\n\n### Option A: Keep PR Changes (HEAD)\n```{language}\n{code from PR branch}\n```\n\n**What this does**: {explanation of PR's intent}\n\n### Option B: Keep Base Branch Changes\n```{language}\n{code from base branch}\n```\n\n**What this does**: {explanation of base branch's intent}\n\n### Option C: Merge Both (Recommended if compatible)\n```{language}\n{merged version if possible}\n```\n\n**Why**: {explanation of why this merge makes sense}\n\n### Option D: Custom Resolution Needed\nThe changes are incompatible. Manual review required.\n\n---\n\n**Recommendation**: Option {X}\n\n**Reasoning**: {why this option based on:\n- Code functionality\n- PR intent from title/description\n- Which change is more recent/complete\n- Impact on other code}\n```\n\n### 3.3 Apply Resolutions\n\nFor each conflict:\n\n1. **If auto-resolvable**: Apply the resolution\n2. **If needs decision**: Use recommended option (or ask user if unclear)\n\n```bash\n# After editing each file\ngit add {file}\n```\n\n### 3.4 Continue Rebase\n\n```bash\n# After resolving all conflicts in current commit\ngit rebase --continue\n```\n\nRepeat for any additional conflicting commits.\n\n**PHASE_3_CHECKPOINT:**\n- [ ] All simple conflicts auto-resolved\n- [ ] Complex conflicts resolved with documented reasoning\n- [ ] All files staged\n- [ ] Rebase completed\n\n---\n\n## Phase 4: VALIDATE - Verify Resolution\n\n### 4.1 Check No Remaining Conflicts\n\n```bash\ngit diff --check\n```\n\nShould return empty (no conflict markers remaining).\n\n### 4.2 Verify Code Compiles\n\n```bash\nbun run type-check\n```\n\nIf type errors related to resolution, fix them.\n\n### 4.3 Run Tests\n\n```bash\nbun test\n```\n\nIf tests fail due to resolution, investigate and fix.\n\n### 4.4 Lint Check\n\n```bash\nbun run lint\n```\n\nFix any lint issues.\n\n**PHASE_4_CHECKPOINT:**\n- [ ] No conflict markers remaining\n- [ ] Type check passes\n- [ ] Tests pass\n- [ ] Lint passes\n\n---\n\n## Phase 5: PUSH - Update the PR\n\n### 5.1 Force Push the Resolved Branch\n\n```bash\ngit push --force-with-lease origin $PR_HEAD\n```\n\n**Note**: `--force-with-lease` is safer than `--force` as it fails if someone else pushed.\n\n### 5.2 Verify PR is Now Mergeable\n\n```bash\ngh pr view {number} --json mergeable,mergeStateStatus\n```\n\nShould show `MERGEABLE`.\n\n**PHASE_5_CHECKPOINT:**\n- [ ] Branch pushed successfully\n- [ ] PR shows as mergeable\n\n---\n\n## Phase 6: REPORT - Document Resolution\n\n### 6.1 Create Resolution Artifact\n\nWrite to `$ARTIFACTS_DIR/../reviews/pr-{number}/conflict-resolution.md` (create dir if needed):\n\n```markdown\n# Conflict Resolution: PR #{number}\n\n**Date**: {ISO timestamp}\n**Branch**: {head} rebased onto {base}\n\n---\n\n## Summary\n\nResolved {N} conflicts in {M} files.\n\n---\n\n## Conflicts Resolved\n\n### File: `{file1}`\n\n**Conflict Type**: {SIMPLE_ADDITION | SAME_LINES | etc.}\n**Resolution**: {Auto-resolved | Option A/B/C chosen}\n\n**Before (conflict)**:\n```{language}\n<<<<<<< HEAD\n{head version}\n=======\n{base version}\n>>>>>>> {base}\n```\n\n**After (resolved)**:\n```{language}\n{final code}\n```\n\n**Reasoning**: {why this resolution}\n\n---\n\n### File: `{file2}`\n\n{Same structure...}\n\n---\n\n## Validation\n\n| Check | Status |\n|-------|--------|\n| No conflict markers | ✅ |\n| Type check | ✅ |\n| Tests | ✅ |\n| Lint | ✅ |\n\n---\n\n## Git Log\n\n```\n{git log --oneline -5}\n```\n\n---\n\n## Metadata\n\n- **Resolved by**: Archon\n- **Timestamp**: {ISO timestamp}\n```\n\n### 6.2 Post GitHub Comment\n\n```bash\ngh pr comment {number} --body \"$(cat <<'EOF'\n## ✅ Conflicts Resolved\n\n**Rebased onto**: `{base}`\n**Conflicts resolved**: {N} in {M} files\n\n### Resolution Summary\n\n| File | Conflict Type | Resolution |\n|------|---------------|------------|\n| `{file1}` | {type} | {resolution approach} |\n| `{file2}` | {type} | {resolution approach} |\n\n### Validation\n✅ Type check | ✅ Tests | ✅ Lint\n\n### Details\nSee `$ARTIFACTS_DIR/../reviews/pr-{number}/conflict-resolution.md` for full resolution details.\n\n---\n*Resolved by Archon resolve-conflicts workflow*\nEOF\n)\"\n```\n\n**PHASE_6_CHECKPOINT:**\n- [ ] Artifact created\n- [ ] GitHub comment posted\n\n---\n\n## Phase 7: OUTPUT - Final Report\n\n```markdown\n## ✅ Conflicts Resolved\n\n**PR**: #{number} - {title}\n**Branch**: `{head}` rebased onto `{base}`\n\n### Summary\n- **Files with conflicts**: {M}\n- **Conflicts resolved**: {N}\n- **Auto-resolved**: {X}\n- **Manual decisions**: {Y}\n\n### Resolution Details\n\n| File | Type | Resolution |\n|------|------|------------|\n| `{file}` | {type} | {approach} |\n\n### Validation\n| Check | Status |\n|-------|--------|\n| Type check | ✅ |\n| Tests | ✅ |\n| Lint | ✅ |\n\n### Artifacts\n- Resolution details: `$ARTIFACTS_DIR/../reviews/pr-{number}/conflict-resolution.md`\n\n### Next Steps\n1. Review the resolution if needed: `git log -p -1`\n2. PR is now ready for review\n3. Request review: `@archon review this PR`\n```\n\n---\n\n## Error Handling\n\n### Rebase Fails Mid-way\n\nIf rebase fails on a commit that can't be resolved:\n\n```bash\n# Check status\ngit status\n\n# If truly stuck, abort and report\ngit rebase --abort\n```\n\nReport the failure with details about which commit and why.\n\n### Push Fails\n\nIf `--force-with-lease` fails (someone else pushed):\n\n1. Fetch latest\n2. Re-analyze conflicts\n3. Start over\n\n### Validation Fails After Resolution\n\nIf type-check/tests fail after resolution:\n\n1. Investigate which resolution caused the issue\n2. Try alternative resolution\n3. If stuck, report and suggest manual review\n\n---\n\n## Success Criteria\n\n- **CONFLICTS_IDENTIFIED**: All conflicting files found\n- **CONFLICTS_RESOLVED**: All conflicts resolved (auto or manual)\n- **VALIDATION_PASSED**: Type check, tests, lint all pass\n- **BRANCH_PUSHED**: PR branch updated with resolution\n- **PR_MERGEABLE**: GitHub shows PR as mergeable\n- **DOCUMENTED**: Resolution artifact and GitHub comment created\n", + "archon-self-fix-all": "---\ndescription: Aggressively fix all review findings - lean towards fixing unless clearly a new concern\nargument-hint: (none - reads all review artifacts from $ARTIFACTS_DIR/review/)\n---\n\n# Self-Fix All Review Findings\n\n---\n\n## IMPORTANT: Output Behavior\n\n**Your output will be posted as a GitHub comment.** Keep working output minimal:\n- Do NOT narrate each step\n- Do NOT output verbose progress updates\n- Only output the final structured report at the end\n\n---\n\n## Your Mission\n\nRead all review artifacts and fix EVERYTHING surfaced. Unlike conservative auto-fix, you lean aggressively towards fixing. LLMs are fast at generating code — use that advantage to add tests, fix docs, improve error handling, and address all findings.\n\n**Philosophy**: Fix it unless it's clearly a NEW unrelated concern that deserves its own issue. Adding tests for existing code? Fix it. Updating docs? Fix it. Adding missing error handling? Fix it. The bar for skipping is HIGH — only skip when the fix would introduce a genuinely new feature or concern outside the PR's scope.\n\n**Output artifact**: `$ARTIFACTS_DIR/review/fix-report.md`\n**Git action**: Commit AND push fixes to the PR branch\n**GitHub action**: Post fix report as a comment on the PR\n\n---\n\n## Phase 1: LOAD — Get Context\n\n### 1.1 Get PR Number and Branch\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number)\nHEAD_BRANCH=$(gh pr view $PR_NUMBER --json headRefName --jq '.headRefName')\necho \"PR: $PR_NUMBER, Branch: $HEAD_BRANCH\"\n```\n\n### 1.2 Checkout PR Branch\n\n```bash\ngit fetch origin $HEAD_BRANCH\ngit checkout $HEAD_BRANCH\ngit pull origin $HEAD_BRANCH\n```\n\nVerify:\n\n```bash\ngit branch --show-current\ngit status --porcelain\n```\n\n### 1.3 Read All Review Artifacts\n\n```bash\nls $ARTIFACTS_DIR/review/\n```\n\nRead each `.md` file that contains findings (e.g. `code-review-findings.md`, `error-handling-findings.md`, `test-coverage-findings.md`, `comment-quality-findings.md`, `docs-impact-findings.md`, `consolidated-review.md`). Skip `scope.md` and `fix-report.md`.\n\n```bash\nfor f in $ARTIFACTS_DIR/review/*.md; do\n echo \"=== $f ===\"; cat \"$f\"; echo\ndone\n```\n\n### 1.4 Extract All Findings\n\nCompile a unified list of ALL findings with severity, location, and suggested fix.\n\n**PHASE_1_CHECKPOINT:**\n\n- [ ] PR number and branch identified\n- [ ] On correct PR branch\n- [ ] All review artifacts read\n- [ ] All findings extracted\n\n---\n\n## Phase 2: TRIAGE — Decide What to Fix\n\nFor each finding, decide: **FIX** or **SKIP**.\n\n### FIX (default — lean towards fixing):\n\n- Real bugs, type errors, silent failures, code quality issues\n- Missing tests for changed or existing code touched by the PR\n- Missing or outdated documentation\n- Error handling gaps\n- Comment quality issues\n- Import organization\n- Naming improvements\n- Any finding where the fix is concrete and the code is within the PR's touched area\n\n### SKIP only if:\n\n- The fix introduces a **genuinely new feature** not related to the PR\n- The fix requires **architectural changes** that affect untouched subsystems\n- The fix is about code **completely unrelated** to the PR's changes\n- The finding is factually wrong or based on a misunderstanding\n\n**Key principle**: If the review agent found it while reviewing THIS PR, it's fair game to fix. Tests, docs, simplification, error handling — all fixable. The only skip reason is \"this is a new concern that deserves its own issue.\"\n\nFor each skipped finding, write down **the specific reason**.\n\n**PHASE_2_CHECKPOINT:**\n\n- [ ] Every finding marked FIX or SKIP\n- [ ] Skip reasons documented (should be very few)\n\n---\n\n## Phase 3: IMPLEMENT — Apply Fixes\n\n### 3.1 For Each Finding Marked FIX\n\n1. Read the relevant file(s)\n2. Apply the fix following the suggested approach\n3. Run type-check after each fix: `bun run type-check`\n4. Note exactly what was changed\n\n### 3.2 Add Tests\n\nFor ANY finding about missing tests:\n\n1. Create or update the test file\n2. Write meaningful tests (not just stubs)\n3. Run them: `bun test {file}`\n\n### 3.3 Fix Documentation\n\nFor ANY finding about docs:\n\n1. Update the relevant documentation\n2. Ensure accuracy with the current code\n\n### 3.4 Handle Blocked Fixes\n\nIf a fix cannot be applied (code changed since review, fix would break other things), mark as **BLOCKED** with reason. Do not force a broken fix.\n\n**PHASE_3_CHECKPOINT:**\n\n- [ ] All FIX findings attempted\n- [ ] Tests added where flagged\n- [ ] Docs updated where flagged\n- [ ] BLOCKED findings documented\n\n---\n\n## Phase 4: VALIDATE — Full Check\n\n```bash\nbun run type-check\nbun run lint\nbun test\n```\n\nAll must pass. If something fails after a fix:\n\n1. Review the error\n2. Adjust the fix or revert it and mark BLOCKED\n3. Re-run until clean\n\n**PHASE_4_CHECKPOINT:**\n\n- [ ] Type check passes\n- [ ] Lint passes\n- [ ] Tests pass\n\n---\n\n## Phase 5: COMMIT AND PUSH\n\n### 5.1 Stage and Commit\n\nOnly stage files you actually changed:\n\n```bash\ngit add {specific files}\ngit status\ngit commit -m \"$(cat <<'EOF'\nfix: address review findings\n\nFixed:\n- {brief list of fixes}\n\nTests added:\n- {brief list if any}\n\nSkipped:\n- {brief list if any, with reasons}\nEOF\n)\"\n```\n\n### 5.2 Push\n\n```bash\ngit push origin $HEAD_BRANCH\n```\n\nIf push fails due to divergence:\n\n```bash\ngit pull --rebase origin $HEAD_BRANCH\ngit push origin $HEAD_BRANCH\n```\n\n**PHASE_5_CHECKPOINT:**\n\n- [ ] Changes committed\n- [ ] Pushed to PR branch\n\n---\n\n## Phase 6: GENERATE — Write Fix Report\n\nWrite to `$ARTIFACTS_DIR/review/fix-report.md`:\n\n```markdown\n# Fix Report: PR #{number}\n\n**Date**: {ISO timestamp}\n**Status**: COMPLETE | PARTIAL\n**Branch**: {HEAD_BRANCH}\n**Commit**: {commit hash}\n**Philosophy**: Aggressive fix — lean towards fixing everything\n\n---\n\n## Summary\n\n{2-3 sentences: what was found, what was fixed, what was skipped and why}\n\n---\n\n## Fixes Applied\n\n| Severity | Finding | Location | What Was Done |\n|----------|---------|----------|---------------|\n| CRITICAL | {title} | `file:line` | {description} |\n| HIGH | {title} | `file:line` | {description} |\n| MEDIUM | {title} | `file:line` | {description} |\n| LOW | {title} | `file:line` | {description} |\n\n---\n\n## Tests Added\n\n| File | Test Cases |\n|------|------------|\n| `{file}.test.ts` | `{test description}` |\n\n*(none)* if no tests were added\n\n---\n\n## Docs Updated\n\n| File | Changes |\n|------|---------|\n| `{file}` | {what was updated} |\n\n*(none)* if no docs were updated\n\n---\n\n## Skipped Findings\n\n| Severity | Finding | Location | Reason Skipped |\n|----------|---------|----------|----------------|\n| {sev} | {title} | `file:line` | New concern: {specific reason} |\n\n*(none)* if nothing was skipped — ideal outcome\n\n---\n\n## Blocked (Could Not Fix)\n\n| Severity | Finding | Reason |\n|----------|---------|--------|\n| {sev} | {title} | {why it could not be applied} |\n\n*(none)* if nothing was blocked\n\n---\n\n## Suggested Follow-up Issues\n\n{For any skipped or blocked findings that warrant their own issue:}\n\n| Issue Title | Priority | Reason |\n|-------------|----------|--------|\n| \"{title}\" | {P1/P2/P3} | {why this deserves a separate issue} |\n\n*(none)* if everything was addressed\n\n---\n\n## Validation\n\n| Check | Status |\n|-------|--------|\n| Type check | ✅ / ❌ |\n| Lint | ✅ / ❌ |\n| Tests | ✅ {n} passed / ❌ |\n```\n\n**PHASE_6_CHECKPOINT:**\n\n- [ ] Fix report written\n\n---\n\n## Phase 7: POST — GitHub Comment\n\nPost the fix report as a PR comment:\n\n```bash\ngh pr comment $PR_NUMBER --body \"$(cat <<'EOF'\n## ⚡ Self-Fix Report (Aggressive)\n\n**Status**: {COMPLETE | PARTIAL}\n**Pushed**: ✅ Changes pushed to `{HEAD_BRANCH}`\n**Philosophy**: Fix everything unless clearly a new concern\n\n---\n\n### Fixes Applied ({n} total)\n\n| Severity | Count |\n|----------|-------|\n| 🔴 CRITICAL | {n} |\n| 🟠 HIGH | {n} |\n| 🟡 MEDIUM | {n} |\n| 🟢 LOW | {n} |\n\n
\nView all fixes\n\n{For each fix:}\n- ✅ **{title}** (`{file}:{line}`) — {brief description}\n\n
\n\n---\n\n### Tests Added\n\n{List or \"(none)\"}\n\n---\n\n### Skipped ({n})\n\n{If any:}\n| Finding | Reason |\n|---------|--------|\n| {title} | New concern: {reason} |\n\n*(none — all findings addressed)*\n\n---\n\n### Suggested Follow-up Issues\n\n{If any skipped/blocked items warrant issues:}\n1. **{Issue Title}** — {brief description}\n\n*(none)*\n\n---\n\n### Validation\n\n✅ Type check | ✅ Lint | ✅ Tests ({n} passed)\n\n---\n\n*Self-fix by Archon · aggressive mode · fixes pushed to `{HEAD_BRANCH}`*\nEOF\n)\"\n```\n\n**PHASE_7_CHECKPOINT:**\n\n- [ ] GitHub comment posted\n\n---\n\n## Phase 8: OUTPUT — Final Summary\n\n```\n## ⚡ Self-Fix Complete\n\n**PR**: #{number}\n**Branch**: {HEAD_BRANCH}\n**Status**: COMPLETE | PARTIAL\n\nFixed: {n} (across all severities)\nTests added: {n}\nDocs updated: {n}\nSkipped: {n} (new concerns only)\nBlocked: {n}\n\nValidation: ✅ All checks pass\nPushed: ✅\n\nFix report: $ARTIFACTS_DIR/review/fix-report.md\n```\n\n---\n\n## Success Criteria\n\n- **ON_CORRECT_BRANCH**: Working on PR's head branch\n- **ALL_FINDINGS_ADDRESSED**: Every finding is fixed, skipped (with reason), or blocked (with reason)\n- **AGGRESSIVE_FIXING**: Most findings fixed — skip rate should be very low\n- **TESTS_ADDED**: Missing test coverage addressed\n- **DOCS_UPDATED**: Documentation gaps filled\n- **VALIDATION_PASSED**: Type check, lint, and tests all pass\n- **COMMITTED_AND_PUSHED**: Changes committed and pushed to PR branch\n- **REPORTED**: Fix report artifact written and GitHub comment posted\n", + "archon-simplify-changes": "---\ndescription: Simplify code changed in this PR — implements fixes directly, commits, and pushes\nargument-hint: (none - operates on the current branch diff against $BASE_BRANCH)\n---\n\n# Simplify Changed Code\n\n---\n\n## IMPORTANT: Output Behavior\n\n**Your output will be posted as a GitHub comment.** Keep working output minimal:\n- Do NOT narrate each step\n- Do NOT output verbose progress updates\n- Only output the final structured report at the end\n\n---\n\n## Your Mission\n\nReview ALL code changed on this branch and implement simplifications directly. You are not advisory — you edit files, validate, commit, and push.\n\n## Scope\n\n**Only code changed in this PR** — run `git diff $BASE_BRANCH...HEAD --name-only` to get the file list. Do not touch unrelated files.\n\n## What to Simplify\n\n| Opportunity | What to Look For |\n|-------------|------------------|\n| **Unnecessary complexity** | Deep nesting, convoluted logic paths |\n| **Redundant code** | Duplicated logic, unused variables/imports |\n| **Over-abstraction** | Abstractions that obscure rather than clarify |\n| **Poor naming** | Unclear variable/function names |\n| **Nested ternaries** | Multiple conditions in ternary chains — use if/else |\n| **Dense one-liners** | Compact code that sacrifices readability |\n| **Obvious comments** | Comments that describe what code clearly shows |\n| **Inconsistent patterns** | Code that doesn't follow project conventions (read CLAUDE.md) |\n\n## Rules\n\n- **Preserve exact functionality** — simplification must not change behavior\n- **Clarity over brevity** — readable beats compact\n- **No speculative refactors** — only simplify what's obviously improvable\n- **Follow project conventions** — read CLAUDE.md before making changes\n- **Small, obvious changes** — each simplification should be self-evidently correct\n\n## Process\n\n### Phase 1: ANALYZE\n\n1. Read CLAUDE.md for project conventions\n2. Get changed files: `git diff $BASE_BRANCH...HEAD --name-only`\n3. Read each changed file\n4. Identify simplification opportunities per file\n\n### Phase 2: IMPLEMENT\n\nFor each simplification:\n1. Edit the file\n2. Run `bun run type-check` — if it fails, revert that change\n3. Run `bun run lint` — if it fails, fix or revert\n\n### Phase 3: VALIDATE & COMMIT\n\n1. Run full validation: `bun run type-check && bun run lint`\n2. If changes were made:\n ```bash\n git add -A\n git commit -m \"simplify: reduce complexity in changed files\"\n git push\n ```\n3. If no simplifications found, skip commit\n\n### Phase 4: REPORT\n\nWrite report to `$ARTIFACTS_DIR/review/simplify-report.md` and output:\n\n```markdown\n## Code Simplification Report\n\n### Changes Made\n\n#### 1. [Brief Title]\n**File**: `path/to/file.ts:45-60`\n**Type**: Reduced nesting / Improved naming / Removed redundancy / etc.\n**Before**: [snippet]\n**After**: [snippet]\n\n---\n\n### Summary\n\n| Metric | Value |\n|--------|-------|\n| Files analyzed | X |\n| Simplifications applied | Y |\n| Net line change | -N lines |\n| Validation | PASS / FAIL |\n\n### No Changes Needed\n(If nothing to simplify, say so — \"Code is already clean. No simplifications applied.\")\n```\n", + "archon-sync-pr-with-main": "---\ndescription: Sync PR branch with latest main (rebase if needed, resolve conflicts if any)\nargument-hint: (none - uses PR from scope)\n---\n\n# Sync PR with Main\n\n---\n\n## Your Mission\n\nEnsure the PR branch is up-to-date with the latest main branch before review. Rebase if needed, resolve conflicts if any arise. This step is silent when no action is needed.\n\n**Output artifact**: `$ARTIFACTS_DIR/review/sync-report.md` (only if rebase/conflicts occurred)\n\n---\n\n## Phase 1: CHECK - Determine if Sync Needed\n\n### 1.1 Get PR Number from Registry\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number)\n```\n\n### 1.2 Read Scope\n\n```bash\ncat $ARTIFACTS_DIR/review/scope.md\n```\n\nGet branch names: `PR_HEAD` and `PR_BASE`.\n\n### 1.3 Fetch and Checkout PR Branch\n\n```bash\ngit fetch origin $PR_BASE\ngit fetch origin $PR_HEAD\n```\n\nConfirm you are on the PR's branch (`$PR_HEAD`). If not, checkout it:\n\n```bash\ngit checkout $PR_HEAD\n```\n\n### 1.4 Check if Behind\n\n```bash\n# Count commits PR branch is behind main\nBEHIND=$(git rev-list --count HEAD..origin/$PR_BASE)\necho \"Behind by: $BEHIND commits\"\n```\n\n**Decision:**\n\n| Behind Count | Action |\n|--------------|--------|\n| 0 | Skip - already up to date |\n| 1+ | Rebase needed |\n\n**If already up to date:**\n```markdown\nBranch is up to date with `{base}`. No sync needed.\n```\n**Exit early - no artifact created.**\n\n**PHASE_1_CHECKPOINT:**\n- [ ] PR number identified\n- [ ] Branches fetched\n- [ ] Behind count determined\n\n---\n\n## Phase 2: REBASE - Sync with Main\n\n### 2.1 Attempt Rebase\n\n```bash\ngit rebase origin/$PR_BASE\n```\n\n**Possible outcomes:**\n\n| Result | Next Step |\n|--------|-----------|\n| Success (no conflicts) | Go to Phase 4 (Validate) |\n| Conflicts | Go to Phase 3 (Resolve) |\n| Other error | Report and abort |\n\n### 2.2 Check for Conflicts\n\n```bash\n# If rebase stopped, check for conflicts\ngit diff --name-only --diff-filter=U\n```\n\nIf files listed → conflicts exist, go to Phase 3.\nIf empty → rebase successful, go to Phase 4.\n\n**PHASE_2_CHECKPOINT:**\n- [ ] Rebase attempted\n- [ ] Conflict status determined\n\n---\n\n## Phase 3: RESOLVE - Handle Conflicts (If Any)\n\n### 3.1 Identify Conflicting Files\n\n```bash\ngit diff --name-only --diff-filter=U\n```\n\n### 3.2 Analyze Each Conflict\n\nFor each conflicting file:\n\n```bash\n# Show conflict markers\ncat {file} | grep -A 10 -B 2 \"<<<<<<<\"\n```\n\n**Categorize:**\n- **SIMPLE**: One side added/changed, other didn't touch → Auto-resolve\n- **COMPLEX**: Both sides changed same lines → Need decision\n\n### 3.3 Auto-Resolve Simple Conflicts\n\nFor conflicts where intent is clear:\n- Both added different things → Keep both\n- One updated, other didn't → Keep update\n- Import additions → Merge both\n\n```bash\n# Edit file to resolve\n# Then stage\ngit add {file}\n```\n\n### 3.4 Resolve Complex Conflicts\n\nFor conflicts needing decision:\n\n1. Read both versions to understand intent\n2. Choose resolution based on:\n - PR intent (what was the change trying to do?)\n - Base branch updates (what changed in main?)\n - Code correctness\n3. Apply resolution and stage\n\n```bash\ngit add {file}\n```\n\n### 3.5 Continue Rebase\n\n```bash\ngit rebase --continue\n```\n\nRepeat if more commits have conflicts.\n\n**PHASE_3_CHECKPOINT:**\n- [ ] All conflicts identified\n- [ ] Simple conflicts auto-resolved\n- [ ] Complex conflicts resolved with reasoning\n- [ ] Rebase completed\n\n---\n\n## Phase 4: VALIDATE - Verify Sync\n\n### 4.1 Check No Conflicts Remaining\n\n```bash\ngit diff --check\n```\n\nShould return empty.\n\n### 4.2 Type Check\n\n```bash\nbun run type-check\n```\n\n### 4.3 Run Tests\n\n```bash\nbun test\n```\n\n### 4.4 Lint\n\n```bash\nbun run lint\n```\n\n**If any fail**: Fix issues before proceeding.\n\n**PHASE_4_CHECKPOINT:**\n- [ ] No conflict markers\n- [ ] Type check passes\n- [ ] Tests pass\n- [ ] Lint passes\n\n---\n\n## Phase 5: PUSH - Update Remote\n\n### 5.1 Confirm Branch and Push\n\nConfirm you're on `$PR_HEAD`, then push:\n\n```bash\ngit push --force-with-lease origin $PR_HEAD\n```\n\n**Note**: `--force-with-lease` is safer - fails if someone else pushed.\n\n### 5.2 Verify Push\n\n```bash\ngit log origin/$PR_HEAD --oneline -3\n```\n\nConfirm local and remote match.\n\n**PHASE_5_CHECKPOINT:**\n- [ ] Branch pushed\n- [ ] Remote updated\n\n---\n\n## Phase 6: REPORT - Document Sync (Only if Rebase/Conflicts Occurred)\n\n### 6.1 Create Sync Artifact\n\nWrite to `$ARTIFACTS_DIR/review/sync-report.md`:\n\n```markdown\n# Sync Report: PR #{number}\n\n**Date**: {ISO timestamp}\n**Action**: Rebased onto `{base}`\n\n---\n\n## Summary\n\n- **Commits rebased**: {N}\n- **Conflicts resolved**: {M} (in {X} files)\n- **Status**: ✅ Synced successfully\n\n---\n\n## Conflicts Resolved\n\n{If conflicts were resolved:}\n\n### `{file}`\n\n**Type**: {SIMPLE | COMPLEX}\n**Resolution**: {description}\n\n```{language}\n{resolved code}\n```\n\n---\n\n{If no conflicts:}\n\nNo conflicts encountered during rebase.\n\n---\n\n## Validation\n\n| Check | Status |\n|-------|--------|\n| Type check | ✅ |\n| Tests | ✅ |\n| Lint | ✅ |\n\n---\n\n## Git State\n\n**Before**: {old HEAD commit}\n**After**: {new HEAD commit}\n**Commits ahead of {base}**: {count}\n\n---\n\n## Metadata\n\n- **Synced by**: Archon\n- **Timestamp**: {ISO timestamp}\n```\n\n### 6.2 Update Scope Artifact\n\nAppend to `$ARTIFACTS_DIR/review/scope.md`:\n\n```markdown\n---\n\n## Sync Status\n\n**Synced**: {ISO timestamp}\n**Rebased onto**: `{base}` at {commit}\n**Conflicts resolved**: {N}\n```\n\n**PHASE_6_CHECKPOINT:**\n- [ ] Sync artifact created (if action taken)\n- [ ] Scope artifact updated\n\n---\n\n## Phase 7: OUTPUT - Report Status\n\n### If Rebased (with or without conflicts):\n\n```markdown\n## ✅ PR Synced with Main\n\n**Branch**: `{head}` rebased onto `{base}`\n**Commits rebased**: {N}\n**Conflicts resolved**: {M}\n\nValidation: ✅ Type check | ✅ Tests | ✅ Lint\n\nProceeding to parallel review...\n```\n\n### If Already Up to Date:\n\n```markdown\n## ✅ PR Already Up to Date\n\nBranch `{head}` is current with `{base}`. No sync needed.\n\nProceeding to parallel review...\n```\n\n### If Sync Failed:\n\n```markdown\n## ❌ Sync Failed\n\n**Error**: {description}\n\n**Action Required**: Manual intervention needed.\n\n```bash\n# To abort the failed rebase\ngit rebase --abort\n```\n\n**Recommendation**: Resolve conflicts manually, then re-trigger review.\n```\n\n---\n\n## Error Handling\n\n### Rebase Fails Completely\n\n```bash\ngit rebase --abort\n```\n\nReport failure with specific error.\n\n### Push Rejected\n\nIf `--force-with-lease` fails:\n1. Someone else pushed to the branch\n2. Fetch and re-attempt rebase\n3. Or report for manual handling\n\n### Validation Fails\n\nIf type-check/tests fail after rebase:\n1. Investigate which changes broke\n2. Attempt to fix\n3. If unfixable, abort and report\n\n---\n\n## Success Criteria\n\n- **UP_TO_DATE**: Branch is synced with base (or was already)\n- **NO_CONFLICTS**: All conflicts resolved (if any existed)\n- **VALIDATION_PASSED**: Type check, tests, lint all pass\n- **PUSHED**: Remote branch updated (if rebase occurred)\n", + "archon-synthesize-review": "---\ndescription: Synthesize all review agent findings into consolidated report and post to GitHub\nargument-hint: (none - reads from review artifacts)\n---\n\n# Synthesize Review\n\n---\n\n## Your Mission\n\nRead all parallel review agent artifacts, synthesize findings into a consolidated report, create a master artifact, and post a comprehensive review comment to the GitHub PR.\n\n**Output artifact**: `$ARTIFACTS_DIR/review/consolidated-review.md`\n**GitHub action**: Post PR comment with full review\n\n---\n\n## Phase 1: LOAD - Gather All Findings\n\n### 1.1 Get PR Number from Registry\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number)\n```\n\n### 1.2 Read Scope\n\n```bash\ncat $ARTIFACTS_DIR/review/scope.md\n```\n\n### 1.3 Read All Agent Artifacts\n\n```bash\n# Read each agent's findings\ncat $ARTIFACTS_DIR/review/code-review-findings.md\ncat $ARTIFACTS_DIR/review/error-handling-findings.md\ncat $ARTIFACTS_DIR/review/test-coverage-findings.md\ncat $ARTIFACTS_DIR/review/comment-quality-findings.md\ncat $ARTIFACTS_DIR/review/docs-impact-findings.md\n```\n\n**PHASE_1_CHECKPOINT:**\n- [ ] PR number identified\n- [ ] All 5 agent artifacts read\n- [ ] Findings extracted from each\n\n---\n\n## Phase 2: SYNTHESIZE - Combine Findings\n\n### 2.1 Aggregate by Severity\n\nCombine all findings across agents:\n- **CRITICAL**: Must fix before merge\n- **HIGH**: Should fix before merge\n- **MEDIUM**: Consider fixing (options provided)\n- **LOW**: Nice to have (defer or create issue)\n\n### 2.2 Deduplicate\n\nCheck for overlapping findings:\n- Same issue reported by multiple agents\n- Related issues that should be grouped\n- Conflicting recommendations (resolve)\n\n### 2.3 Prioritize\n\nRank findings by:\n1. Severity (CRITICAL > HIGH > MEDIUM > LOW)\n2. User impact\n3. Ease of fix\n4. Risk if not fixed\n\n### 2.4 Compile Statistics\n\n```\nTotal findings: {n}\n- CRITICAL: {n}\n- HIGH: {n}\n- MEDIUM: {n}\n- LOW: {n}\n\nBy agent:\n- code-review: {n} findings\n- error-handling: {n} findings\n- test-coverage: {n} findings\n- comment-quality: {n} findings\n- docs-impact: {n} findings\n```\n\n**PHASE_2_CHECKPOINT:**\n- [ ] Findings aggregated by severity\n- [ ] Duplicates removed\n- [ ] Priority order established\n- [ ] Statistics compiled\n\n---\n\n## Phase 3: GENERATE - Create Consolidated Artifact\n\nWrite to `$ARTIFACTS_DIR/review/consolidated-review.md`:\n\n```markdown\n# Consolidated Review: PR #{number}\n\n**Date**: {ISO timestamp}\n**Agents**: code-review, error-handling, test-coverage, comment-quality, docs-impact\n**Total Findings**: {count}\n\n---\n\n## Executive Summary\n\n{3-5 sentence overview of PR quality and main concerns}\n\n**Overall Verdict**: {APPROVE | REQUEST_CHANGES | NEEDS_DISCUSSION}\n\n**Auto-fix Candidates**: {n} CRITICAL + HIGH issues can be auto-fixed\n**Manual Review Needed**: {n} MEDIUM + LOW issues require decision\n\n---\n\n## Statistics\n\n| Agent | CRITICAL | HIGH | MEDIUM | LOW | Total |\n|-------|----------|------|--------|-----|-------|\n| Code Review | {n} | {n} | {n} | {n} | {n} |\n| Error Handling | {n} | {n} | {n} | {n} | {n} |\n| Test Coverage | {n} | {n} | {n} | {n} | {n} |\n| Comment Quality | {n} | {n} | {n} | {n} | {n} |\n| Docs Impact | {n} | {n} | {n} | {n} | {n} |\n| **Total** | **{n}** | **{n}** | **{n}** | **{n}** | **{n}** |\n\n---\n\n## CRITICAL Issues (Must Fix)\n\n### Issue 1: {Title}\n\n**Source Agent**: {agent-name}\n**Location**: `{file}:{line}`\n**Category**: {category}\n\n**Problem**:\n{description}\n\n**Recommended Fix**:\n```typescript\n{fix code}\n```\n\n**Why Critical**:\n{impact explanation}\n\n---\n\n### Issue 2: {Title}\n\n{Same structure...}\n\n---\n\n## HIGH Issues (Should Fix)\n\n### Issue 1: {Title}\n\n{Same structure as CRITICAL...}\n\n---\n\n## MEDIUM Issues (Options for User)\n\n### Issue 1: {Title}\n\n**Source Agent**: {agent-name}\n**Location**: `{file}:{line}`\n\n**Problem**:\n{description}\n\n**Options**:\n\n| Option | Approach | Effort | Risk if Skipped |\n|--------|----------|--------|-----------------|\n| Fix Now | {approach} | {LOW/MED/HIGH} | {risk} |\n| Create Issue | Defer to separate PR | LOW | {risk} |\n| Skip | Accept as-is | NONE | {risk} |\n\n**Recommendation**: {which option and why}\n\n---\n\n## LOW Issues (For Consideration)\n\n| Issue | Location | Agent | Suggestion |\n|-------|----------|-------|------------|\n| {title} | `file:line` | {agent} | {brief recommendation} |\n| ... | ... | ... | ... |\n\n---\n\n## Positive Observations\n\n{Aggregated good things from all agents:\n- Well-structured code\n- Good error handling in X\n- Comprehensive tests for Y\n- Clear documentation}\n\n---\n\n## Suggested Follow-up Issues\n\nIf not addressing in this PR, create issues for:\n\n| Issue Title | Priority | Related Finding |\n|-------------|----------|-----------------|\n| \"{suggested issue title}\" | {P1/P2/P3} | MEDIUM issue #{n} |\n| ... | ... | ... |\n\n---\n\n## Next Steps\n\n1. **Auto-fix step** will address {n} CRITICAL + HIGH issues\n2. **Review** the MEDIUM issues and decide: fix now, create issue, or skip\n3. **Consider** LOW issues for future improvements\n\n---\n\n## Agent Artifacts\n\n| Agent | Artifact | Findings |\n|-------|----------|----------|\n| Code Review | `code-review-findings.md` | {n} |\n| Error Handling | `error-handling-findings.md` | {n} |\n| Test Coverage | `test-coverage-findings.md` | {n} |\n| Comment Quality | `comment-quality-findings.md` | {n} |\n| Docs Impact | `docs-impact-findings.md` | {n} |\n\n---\n\n## Metadata\n\n- **Synthesized**: {ISO timestamp}\n- **Artifact**: `$ARTIFACTS_DIR/review/consolidated-review.md`\n```\n\n**PHASE_3_CHECKPOINT:**\n- [ ] Consolidated artifact created\n- [ ] All findings included\n- [ ] Severity ordering correct\n- [ ] Options provided for MEDIUM/LOW\n\n---\n\n## Phase 4: POST - GitHub PR Comment\n\n### 4.1 Format for GitHub\n\nCreate a GitHub-friendly version of the review:\n\n```bash\ngh pr comment {number} --body \"$(cat <<'EOF'\n# 🔍 Comprehensive PR Review\n\n**PR**: #{number}\n**Reviewed by**: 5 specialized agents\n**Date**: {date}\n\n---\n\n## Summary\n\n{executive summary}\n\n**Verdict**: `{APPROVE | REQUEST_CHANGES}`\n\n| Severity | Count |\n|----------|-------|\n| 🔴 CRITICAL | {n} |\n| 🟠 HIGH | {n} |\n| 🟡 MEDIUM | {n} |\n| 🟢 LOW | {n} |\n\n---\n\n## 🔴 Critical Issues (Auto-fixing)\n\n{For each CRITICAL issue:}\n\n### {Title}\n📍 `{file}:{line}`\n\n{Brief description}\n\n
\nView fix\n\n```typescript\n{fix code}\n```\n\n
\n\n---\n\n## 🟠 High Issues (Auto-fixing)\n\n{Same format as CRITICAL}\n\n---\n\n## 🟡 Medium Issues (Needs Decision)\n\n{For each MEDIUM issue:}\n\n### {Title}\n📍 `{file}:{line}`\n\n{Brief description}\n\n**Options**: Fix now | Create issue | Skip\n\n
\nView details\n\n{full details and options table}\n\n
\n\n---\n\n## 🟢 Low Issues\n\n
\nView {n} low-priority suggestions\n\n| Issue | Location | Suggestion |\n|-------|----------|------------|\n| {title} | `file:line` | {suggestion} |\n\n
\n\n---\n\n## ✅ What's Good\n\n{Positive observations}\n\n---\n\n## 📋 Suggested Follow-up Issues\n\n{If any MEDIUM/LOW issues should become issues}\n\n---\n\n## Next Steps\n\n1. ⚡ Auto-fix step will address CRITICAL + HIGH issues\n2. 📝 Review MEDIUM issues above\n3. 🎯 Merge when ready\n\n---\n\n*Reviewed by Archon comprehensive-pr-review workflow*\n*Artifacts: `$ARTIFACTS_DIR/review/`*\nEOF\n)\"\n```\n\n**PHASE_4_CHECKPOINT:**\n- [ ] GitHub comment posted\n- [ ] Formatting renders correctly\n- [ ] All severity levels included\n\n---\n\n## Phase 5: OUTPUT - Confirmation\n\nOutput only a brief confirmation (this will be posted as a comment):\n\n```\n✅ Review synthesis complete. Proceeding to auto-fix step...\n```\n\n---\n\n## Success Criteria\n\n- **ALL_ARTIFACTS_READ**: All 5 agent findings loaded\n- **FINDINGS_SYNTHESIZED**: Combined, deduplicated, prioritized\n- **CONSOLIDATED_CREATED**: Master artifact written\n- **GITHUB_POSTED**: PR comment visible\n", + "archon-test-coverage-agent": "---\ndescription: Review test coverage quality, identify gaps, and evaluate test effectiveness\nargument-hint: (none - reads from scope artifact)\n---\n\n# Test Coverage Agent\n\n---\n\n## Your Mission\n\nAnalyze test coverage for the PR changes. Identify critical gaps, evaluate test quality, and ensure tests verify behavior (not implementation). Produce a structured artifact with findings and recommendations.\n\n**Output artifact**: `$ARTIFACTS_DIR/review/test-coverage-findings.md`\n\n---\n\n## Phase 1: LOAD - Get Context\n\n### 1.1 Get PR Number from Registry\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number)\n```\n\n### 1.2 Read Scope\n\n```bash\ncat $ARTIFACTS_DIR/review/scope.md\n```\n\nNote which files are source vs test files.\n\n**CRITICAL**: Check for \"NOT Building (Scope Limits)\" section. Items listed there are **intentionally excluded** - do NOT flag them as bugs or missing test coverage!\n\n### 1.3 Get PR Diff\n\n```bash\ngh pr diff {number}\n```\n\n### 1.4 Read Existing Tests\n\nFor each new/modified source file, find corresponding test file:\n\n```bash\n# Find test files\nfind src -name \"*.test.ts\" -o -name \"*.spec.ts\" | head -20\n```\n\n**PHASE_1_CHECKPOINT:**\n- [ ] PR number identified\n- [ ] Source and test files identified\n- [ ] Existing test patterns noted\n\n---\n\n## Phase 2: ANALYZE - Evaluate Coverage\n\n### 2.1 Map Source to Tests\n\nFor each changed source file:\n- Does a corresponding test file exist?\n- Are new functions/features tested?\n- Are modified functions' tests updated?\n\n### 2.2 Identify Critical Gaps\n\nLook for untested:\n- Error handling paths\n- Edge cases (null, empty, boundary values)\n- Critical business logic\n- Security-sensitive code\n- Async/concurrent behavior\n- Integration points\n\n### 2.3 Evaluate Test Quality\n\nFor existing tests, check:\n- Do they test behavior or implementation?\n- Would they catch meaningful regressions?\n- Are they resilient to refactoring?\n- Do they follow DAMP principles?\n- Are assertions meaningful?\n\n### 2.4 Find Test Patterns\n\n```bash\n# Find test patterns in codebase\ngrep -r \"describe\\|it\\|test\\(\" src/ --include=\"*.test.ts\" | head -20\n```\n\n**PHASE_2_CHECKPOINT:**\n- [ ] Source-to-test mapping complete\n- [ ] Critical gaps identified\n- [ ] Test quality evaluated\n- [ ] Codebase test patterns found\n\n---\n\n## Phase 3: GENERATE - Create Artifact\n\nWrite to `$ARTIFACTS_DIR/review/test-coverage-findings.md`:\n\n```markdown\n# Test Coverage Findings: PR #{number}\n\n**Reviewer**: test-coverage-agent\n**Date**: {ISO timestamp}\n**Source Files**: {count}\n**Test Files**: {count}\n\n---\n\n## Summary\n\n{2-3 sentence overview of test coverage quality}\n\n**Verdict**: {APPROVE | REQUEST_CHANGES | NEEDS_DISCUSSION}\n\n---\n\n## Coverage Map\n\n| Source File | Test File | New Code Tested | Modified Code Tested |\n|-------------|-----------|-----------------|---------------------|\n| `src/x.ts` | `src/x.test.ts` | FULL/PARTIAL/NONE | FULL/PARTIAL/NONE |\n| `src/y.ts` | (missing) | N/A | N/A |\n| ... | ... | ... | ... |\n\n---\n\n## Findings\n\n### Finding 1: {Descriptive Title}\n\n**Severity**: CRITICAL | HIGH | MEDIUM | LOW\n**Category**: missing-test | weak-test | implementation-coupled | missing-edge-case\n**Location**: `{file}:{line}` (source) / `{test-file}` (test)\n**Criticality Score**: {1-10}\n\n**Issue**:\n{Clear description of the coverage gap}\n\n**Untested Code**:\n```typescript\n// This code at {file}:{line} is not tested\n{untested code}\n```\n\n**Why This Matters**:\n{Specific bugs or regressions this could miss:\n- \"If {scenario}, users would see {bad outcome}\"\n- \"A future change to {X} could break {Y} without detection\"}\n\n---\n\n#### Test Suggestions\n\n| Option | Approach | Catches | Effort |\n|--------|----------|---------|--------|\n| A | {test approach} | {what it catches} | LOW/MED/HIGH |\n| B | {alternative} | {what it catches} | LOW/MED/HIGH |\n\n**Recommended**: Option {X}\n\n**Reasoning**:\n{Why this test approach:\n- Matches codebase test patterns\n- Tests behavior not implementation\n- Good cost/benefit ratio\n- Catches the most critical failures}\n\n**Recommended Test**:\n```typescript\ndescribe('{feature}', () => {\n it('should {expected behavior}', () => {\n // Arrange\n {setup}\n\n // Act\n {action}\n\n // Assert\n {assertions}\n });\n\n it('should handle {edge case}', () => {\n // Test edge case\n });\n});\n```\n\n**Test Pattern Reference**:\n```typescript\n// SOURCE: {test-file}:{lines}\n// This is how similar functionality is tested\n{existing test from codebase}\n```\n\n---\n\n### Finding 2: {Title}\n\n{Same structure...}\n\n---\n\n## Test Quality Audit\n\n| Test | Tests Behavior | Resilient | Meaningful Assertions | Verdict |\n|------|---------------|-----------|----------------------|---------|\n| `it('should...')` | YES/NO | YES/NO | YES/NO | GOOD/NEEDS_WORK |\n| ... | ... | ... | ... | ... |\n\n---\n\n## Statistics\n\n| Severity | Count | Criticality 8-10 | Criticality 5-7 | Criticality 1-4 |\n|----------|-------|------------------|-----------------|-----------------|\n| CRITICAL | {n} | {n} | - | - |\n| HIGH | {n} | {n} | {n} | - |\n| MEDIUM | {n} | - | {n} | {n} |\n| LOW | {n} | - | - | {n} |\n\n---\n\n## Risk Assessment\n\n| Untested Area | Failure Mode | User Impact | Priority |\n|---------------|--------------|-------------|----------|\n| {code area} | {how it could fail} | {user sees} | CRITICAL/HIGH/MED |\n| ... | ... | ... | ... |\n\n---\n\n## Patterns Referenced\n\n| Test File | Lines | Pattern |\n|-----------|-------|---------|\n| `src/x.test.ts` | 10-30 | {testing pattern description} |\n| ... | ... | ... |\n\n---\n\n## Positive Observations\n\n{Good test coverage, well-written tests, proper mocking}\n\n---\n\n## Metadata\n\n- **Agent**: test-coverage-agent\n- **Timestamp**: {ISO timestamp}\n- **Artifact**: `$ARTIFACTS_DIR/review/test-coverage-findings.md`\n```\n\n**PHASE_3_CHECKPOINT:**\n- [ ] Artifact file created\n- [ ] Coverage map complete\n- [ ] Each gap has criticality score\n- [ ] Test suggestions with example code\n\n---\n\n## Success Criteria\n\n- **COVERAGE_MAPPED**: Each source file mapped to tests\n- **GAPS_IDENTIFIED**: Missing tests found with criticality scores\n- **QUALITY_EVALUATED**: Existing tests assessed\n- **TESTS_SUGGESTED**: Example test code provided for gaps\n", + "archon-validate-pr-code-review-feature": "---\ndescription: Analyze code on the feature branch to verify the PR's fix is correct and optimal\nargument-hint: (none - reads from artifacts)\n---\n\n# Code Review: Feature Branch (Post-PR State)\n\nAnalyze the code changes in the PR to verify the fix is correct, complete, and implemented in the best way possible.\n\n---\n\n## Phase 1: Load Context\n\n### 1.1 Read PR Details and Main Branch Analysis\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number | tr -d '\\n')\ngh pr view \"$PR_NUMBER\" --json title,body,headRefName,baseRefName,labels\n```\n\n```bash\n# Read the main branch analysis (guaranteed available — this node depends on code-review-main)\ncat $ARTIFACTS_DIR/code-review-main.md\n```\n\n### 1.2 Read Path Information\n\n```bash\ncat $ARTIFACTS_DIR/.worktree-path\ncat $ARTIFACTS_DIR/.feature-branch\n```\n\n---\n\n## Phase 2: Analyze the Diff\n\n### 2.1 Get the Full Diff\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number | tr -d '\\n')\ngh pr diff \"$PR_NUMBER\"\n```\n\n### 2.2 Read Changed Files on Feature Branch\n\nThe current working directory IS the feature branch (worktree). Read each changed file:\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number | tr -d '\\n')\n# List changed files\ngh pr view \"$PR_NUMBER\" --json files -q '.files[].path'\n```\n\nFor each file, read the full file in the current working directory to understand the complete context, not just the diff hunks.\n\n### 2.3 Deep Analysis of Each Change\n\nFor each changed file:\n\n1. **Read the full file** — understand the complete context around the changes\n2. **Compare with main** — read the same file from `$ARTIFACTS_DIR/.canonical-repo` to see the before/after\n3. **Evaluate the fix**:\n - Does it actually address the bug/gap found on main?\n - Is it the simplest possible fix? (KISS)\n - Does it handle edge cases?\n - Could it introduce new bugs?\n - Does it follow existing patterns in the codebase?\n4. **Check CLAUDE.md compliance**:\n ```bash\n cat CLAUDE.md\n ```\n - Import patterns correct?\n - Type annotations complete?\n - Error handling appropriate?\n - No unnecessary complexity?\n\n### 2.4 Look for Issues\n\nCheck for:\n- **Correctness**: Does the fix actually solve the problem?\n- **Completeness**: Are all aspects of the bug addressed?\n- **Side effects**: Could this break something else?\n- **Performance**: Any unnecessary re-renders, expensive operations?\n- **Type safety**: All types correct, no `any` without justification?\n- **Error handling**: Errors caught and handled appropriately?\n- **Overengineering**: More changes than necessary? (YAGNI)\n- **Missing changes**: Files that SHOULD have been changed but weren't?\n\n### 2.5 Compare Alternative Approaches\n\nThink about whether there's a better way to fix this:\n- Could a simpler approach work?\n- Is there an existing utility/pattern that should be used?\n- Would the fix work differently if applied at a different layer?\n\n---\n\n## Phase 3: Write Findings\n\nWrite your analysis to `$ARTIFACTS_DIR/code-review-feature.md`:\n\n```markdown\n# Feature Branch Code Review: PR #{number}\n\n**PR Title**: {title}\n**Feature Branch**: {branch}\n**Files Changed**: {count}\n**Lines**: +{additions} -{deletions}\n\n## Fix Assessment\n\n### Does the Fix Address the Bug?\n**YES / PARTIALLY / NO**\n\n{Explanation with specific code references}\n\n### Fix Quality\n\n| Criterion | Rating (1-5) | Notes |\n|-----------|-------------|-------|\n| Correctness | {n} | {does it fix the bug?} |\n| Completeness | {n} | {all edge cases handled?} |\n| Simplicity | {n} | {minimal changes, KISS?} |\n| Safety | {n} | {no side effects?} |\n| Patterns | {n} | {follows codebase conventions?} |\n\n**Overall Score**: {average}/5\n\n### File-by-File Analysis\n\n#### `{file1}`\n**Change Summary**: {what changed}\n**Assessment**: {good/needs-work/concern}\n```{language}\n// Key change\n{relevant code snippet}\n```\n**Notes**: {specific feedback}\n\n#### `{file2}`\n{Same structure...}\n\n### Issues Found\n\n#### Issue 1: {title}\n**Severity**: CRITICAL / HIGH / MEDIUM / LOW\n**File**: `{file}:{line}`\n**Description**: {what's wrong}\n**Suggested Fix**:\n```{language}\n{how to fix it}\n```\n\n### Alternative Approaches Considered\n{Were there better ways to implement this? If so, describe them and why they might be preferable.\nIf the current approach is optimal, say so and explain why.}\n\n### Missing Changes\n{Files or areas that should have been changed but weren't. If everything is covered, say so.}\n\n## CLAUDE.md Compliance\n\n| Rule | Status | Notes |\n|------|--------|-------|\n| Type annotations | PASS/FAIL | {details} |\n| Import patterns | PASS/FAIL | {details} |\n| Error handling | PASS/FAIL | {details} |\n| No any types | PASS/FAIL | {details} |\n| KISS principle | PASS/FAIL | {details} |\n\n## Verdict\n\n**APPROVE / REQUEST_CHANGES / NEEDS_DISCUSSION**\n\n{2-3 sentence final assessment: Is this fix ready to merge as-is?}\n```\n\n---\n\n## Success Criteria\n\n- **DIFF_ANALYZED**: Full PR diff reviewed\n- **FILES_READ**: All changed files read in full context\n- **MAIN_COMPARED**: Feature code compared against main branch code\n- **CLAUDE_MD_CHECKED**: CLAUDE.md compliance verified\n- **ARTIFACT_WRITTEN**: `$ARTIFACTS_DIR/code-review-feature.md` created\n", + "archon-validate-pr-code-review-main": "---\ndescription: Analyze code on the main/base branch to confirm the bug or gap exists before the PR's changes\nargument-hint: (none - reads from artifacts)\n---\n\n# Code Review: Main Branch (Pre-PR State)\n\nAnalyze the codebase on the **main branch** to confirm that the bug, gap, or missing feature described in the PR actually exists.\n\n---\n\n## Phase 1: Load Context\n\n### 1.1 Read PR Details\n\n```bash\ncat $ARTIFACTS_DIR/.pr-number\n```\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number | tr -d '\\n')\ngh pr view \"$PR_NUMBER\" --json title,body,headRefName,baseRefName,labels\n```\n\n### 1.2 Read Path Information\n\n```bash\ncat $ARTIFACTS_DIR/.canonical-repo\ncat $ARTIFACTS_DIR/.worktree-path\ncat $ARTIFACTS_DIR/.pr-base\n```\n\n### 1.3 Understand What the PR Claims to Fix\n\nFrom the PR title, body, and linked issue(s):\n- What bug or gap does the PR claim exists?\n- What is the expected behavior vs actual behavior?\n- Which files/components are involved?\n\nIf the PR body references a GitHub issue, fetch it:\n\n```bash\n# Extract issue number from PR body (looks for \"Fixes #N\", \"Closes #N\", etc.)\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number | tr -d '\\n')\nISSUE_NUMBER=$(gh pr view \"$PR_NUMBER\" --json body -q '.body' | grep -oE '(Fixes|Closes|Resolves)\\s*#[0-9]+' | grep -oE '[0-9]+' | head -1)\nif [ -n \"$ISSUE_NUMBER\" ]; then\n gh issue view \"$ISSUE_NUMBER\" --json title,body,labels,comments\nfi\n```\n\n---\n\n## Phase 2: Analyze Main Branch Code\n\n### 2.1 Read the Files That the PR Changes\n\nGet the list of changed files from the PR diff, then read those **same files on the main branch** (the canonical repo path).\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number | tr -d '\\n')\ngh pr view \"$PR_NUMBER\" --json files -q '.files[].path'\n```\n\n**CRITICAL**: Read the files from the **canonical repo** (main branch), NOT from the current worktree (feature branch). The canonical repo path is in `$ARTIFACTS_DIR/.canonical-repo`.\n\nFor each changed file, read it from the main branch:\n\n```bash\nCANONICAL_REPO=$(cat $ARTIFACTS_DIR/.canonical-repo | tr -d '\\n')\n# Read each file from the canonical repo (on main branch)\ncat \"$CANONICAL_REPO/\"\n```\n\n### 2.2 Trace the Bug or Gap\n\nFor each claim in the PR:\n1. **Find the relevant code** on main — read the specific functions, components, hooks\n2. **Trace the data flow** — where does the data come from? How does it transform?\n3. **Identify the root cause** — can you see the bug in the code?\n4. **Check related code** — are there adjacent issues the PR might miss?\n\n### 2.3 Assess Severity\n\n- How impactful is this bug/gap on main?\n- Is it user-facing or internal?\n- Does it affect core functionality or edge cases?\n- How likely is a user to encounter it?\n\n---\n\n## Phase 3: Write Findings\n\nWrite your analysis to `$ARTIFACTS_DIR/code-review-main.md`:\n\n```markdown\n# Main Branch Code Review: PR #{number}\n\n**PR Title**: {title}\n**Base Branch**: {base}\n**Analyzed Commit**: {main branch HEAD}\n\n## Bug/Gap Assessment\n\n### Claimed Issue\n{What the PR claims to fix}\n\n### Confirmed on Main?\n**YES / NO / PARTIAL**\n\n### Evidence\n\n{For each claim, provide specific code evidence:}\n\n#### Claim 1: {description}\n**Status**: Confirmed / Not Found / Partially Confirmed\n\n**Code Location**: `{file}:{lines}`\n```{language}\n{actual code on main showing the bug/gap}\n```\n\n**Analysis**: {Why this code is buggy/incomplete}\n\n#### Claim 2: {description}\n{Same structure...}\n\n### Related Issues Found\n{Any additional problems discovered in the same code areas}\n\n### Severity Assessment\n| Factor | Rating |\n|--------|--------|\n| User Impact | High / Medium / Low |\n| Frequency | Common / Uncommon / Rare |\n| Core Feature | Yes / No |\n| Data Loss Risk | Yes / No |\n\n## Summary\n{2-3 sentence summary: Is the bug real? How bad is it? Is the PR's scope appropriate?}\n```\n\n---\n\n## Success Criteria\n\n- **PR_CONTEXT_LOADED**: PR details and linked issue read\n- **MAIN_CODE_ANALYZED**: Changed files read from main branch\n- **BUG_ASSESSED**: Each PR claim verified against main branch code\n- **ARTIFACT_WRITTEN**: `$ARTIFACTS_DIR/code-review-main.md` created\n", + "archon-validate-pr-e2e-feature": "---\ndescription: Start Archon from the feature branch, use agent-browser to verify the fix works correctly\nargument-hint: (none - reads from artifacts)\n---\n\n# E2E Testing: Feature Branch (Verify Fix)\n\nStart Archon from the **feature branch** (this worktree) and use browser automation to verify that the bug is fixed and the UI/UX is correct. Take screenshots as evidence.\n\n**CRITICAL**: You MUST use the `agent-browser` CLI for ALL browser interactions. Load the `/agent-browser` skill for the full command reference.\n\n**CRITICAL**: You MUST clean up ALL spawned processes before finishing. Record PIDs and kill them in Phase 4. Orphaned processes from previous E2E runs may still be running — check and kill them first.\n\n**CRITICAL — SESSION ISOLATION**: This workflow runs in parallel with other validate-pr instances.\nYou MUST use `--session $WORKFLOW_ID` on EVERY `agent-browser` command to isolate your browser session.\nExample: `agent-browser --session $WORKFLOW_ID open \"http://...\"`, `agent-browser --session $WORKFLOW_ID snapshot -i`, etc.\n\n**ABSOLUTELY FORBIDDEN — NEVER DO ANY OF THESE**:\n- `taskkill //F //IM chrome.exe` or ANY variant that kills chrome by image name — this kills the USER's browser\n- `taskkill //F //IM node.exe` or `taskkill //F //IM bun.exe` — this kills Claude Code, the Archon server, and all other workflows\n- `pkill chrome`, `pkill node`, `pkill bun`, or any broad process-name kill\n- `agent-browser close` without `--session $WORKFLOW_ID` — this kills OTHER workflows' browser sessions\n- Any \"kill everything\" or \"kill all\" escalation pattern — if agent-browser isn't working, SKIP E2E testing and note it in your report\n- If agent-browser fails to connect after 2 attempts, STOP trying and write your findings based on code review only\n\n---\n\n## Phase 0: Kill Orphaned Processes from Previous E2E Run\n\nBefore starting, clean up any leftover processes from the main branch E2E test:\n\n```bash\nBACKEND_PORT=$(cat $ARTIFACTS_DIR/.backend-port | tr -d '\\n')\nFRONTEND_PORT=$(cat $ARTIFACTS_DIR/.frontend-port | tr -d '\\n')\n\n# Kill by PID files from main E2E run\nfor pidfile in \"$ARTIFACTS_DIR/.e2e-main-backend-pid\" \"$ARTIFACTS_DIR/.e2e-main-frontend-pid\"; do\n if [ -f \"$pidfile\" ]; then\n PID=$(cat \"$pidfile\" | tr -d '\\n')\n echo \"Killing leftover main E2E PID $PID\"\n kill \"$PID\" 2>/dev/null || taskkill //F //T //PID \"$PID\" 2>/dev/null || true\n fi\ndone\n\n# Kill anything still on our ports\nfor PORT in $BACKEND_PORT $FRONTEND_PORT; do\n fuser -k \"$PORT/tcp\" 2>/dev/null || true\n lsof -ti:\"$PORT\" 2>/dev/null | xargs kill -9 2>/dev/null || true\n netstat -ano 2>/dev/null | grep \":$PORT \" | grep LISTENING | awk '{print $5}' | sort -u | while read pid; do\n taskkill //F //T //PID \"$pid\" 2>/dev/null || true\n done\ndone\nsleep 2\necho \"Orphan cleanup complete\"\n```\n\n---\n\n## Phase 1: Load Context\n\n### 1.1 Read Artifacts\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number | tr -d '\\n')\nBACKEND_PORT=$(cat $ARTIFACTS_DIR/.backend-port | tr -d '\\n')\nFRONTEND_PORT=$(cat $ARTIFACTS_DIR/.frontend-port | tr -d '\\n')\nWORKTREE_PATH=$(cat $ARTIFACTS_DIR/.worktree-path | tr -d '\\n')\necho \"PR: #$PR_NUMBER\"\necho \"Backend port: $BACKEND_PORT\"\necho \"Frontend port: $FRONTEND_PORT\"\necho \"Feature branch path: $WORKTREE_PATH\"\n```\n\n### 1.2 Read Main Branch Test Results\n\n```bash\ncat $ARTIFACTS_DIR/e2e-main.md 2>/dev/null || echo \"No main branch E2E results available\"\n```\n\nThis tells you:\n- Which bugs were reproduced on main (you need to verify they're FIXED here)\n- Which test cases to re-run\n- What screenshots to compare against\n\n### 1.3 Read Code Reviews\n\n```bash\ncat $ARTIFACTS_DIR/code-review-main.md 2>/dev/null || echo \"\"\ncat $ARTIFACTS_DIR/code-review-feature.md 2>/dev/null || echo \"\"\n```\n\n---\n\n## Phase 2: Start Archon on Feature Branch\n\n### 2.1 Install Dependencies (if needed)\n\n```bash\nWORKTREE_PATH=$(cat $ARTIFACTS_DIR/.worktree-path | tr -d '\\n')\ncd \"$WORKTREE_PATH\" && bun install --frozen-lockfile 2>/dev/null || bun install\n```\n\n### 2.2 Start Backend on Custom Port\n\n**IMPORTANT**: Record the PID so we can kill it later. Redirect output to /dev/null to prevent terminal spawning.\n\n```bash\nWORKTREE_PATH=$(cat $ARTIFACTS_DIR/.worktree-path | tr -d '\\n')\nBACKEND_PORT=$(cat $ARTIFACTS_DIR/.backend-port | tr -d '\\n')\n\ncd \"$WORKTREE_PATH\" && PORT=$BACKEND_PORT bun run --filter @archon/server dev > \"$ARTIFACTS_DIR/.e2e-feature-backend.log\" 2>&1 &\nBACKEND_PID=$!\necho \"$BACKEND_PID\" > \"$ARTIFACTS_DIR/.e2e-feature-backend-pid\"\necho \"Backend started with PID: $BACKEND_PID\"\n\n# Poll until healthy (max 60s)\nMAX_WAIT=60\nWAITED=0\nuntil curl -sf \"http://localhost:$BACKEND_PORT/api/health\" > /dev/null 2>&1; do\n if [ $WAITED -ge $MAX_WAIT ]; then\n echo \"ERROR: Backend did not become healthy within ${MAX_WAIT}s\"\n echo \"Last log lines:\"\n tail -20 \"$ARTIFACTS_DIR/.e2e-feature-backend.log\" 2>/dev/null || true\n exit 1\n fi\n sleep 2\n WAITED=$((WAITED + 2))\ndone\necho \"Backend healthy after ${WAITED}s\"\ncurl -s \"http://localhost:$BACKEND_PORT/api/health\" | head -c 200\necho \"\"\n```\n\n### 2.3 Start Frontend on Custom Port\n\n```bash\nWORKTREE_PATH=$(cat $ARTIFACTS_DIR/.worktree-path | tr -d '\\n')\nBACKEND_PORT=$(cat $ARTIFACTS_DIR/.backend-port | tr -d '\\n')\nFRONTEND_PORT=$(cat $ARTIFACTS_DIR/.frontend-port | tr -d '\\n')\n\ncd \"$WORKTREE_PATH/packages/web\" && PORT=$BACKEND_PORT npx vite --port $FRONTEND_PORT --host > \"$ARTIFACTS_DIR/.e2e-feature-frontend.log\" 2>&1 &\nFRONTEND_PID=$!\necho \"$FRONTEND_PID\" > \"$ARTIFACTS_DIR/.e2e-feature-frontend-pid\"\necho \"Frontend started with PID: $FRONTEND_PID\"\n\n# Poll until serving (max 60s)\nMAX_WAIT=60\nWAITED=0\nuntil curl -sf \"http://localhost:$FRONTEND_PORT\" > /dev/null 2>&1; do\n if [ $WAITED -ge $MAX_WAIT ]; then\n echo \"ERROR: Frontend did not become ready within ${MAX_WAIT}s\"\n echo \"Last log lines:\"\n tail -20 \"$ARTIFACTS_DIR/.e2e-feature-frontend.log\" 2>/dev/null || true\n exit 1\n fi\n sleep 2\n WAITED=$((WAITED + 2))\ndone\necho \"Frontend ready after ${WAITED}s\"\ncurl -s \"http://localhost:$FRONTEND_PORT\" | head -c 100\necho \"\"\n```\n\n### 2.4 Seed Test Data (if needed)\n\n```bash\nBACKEND_PORT=$(cat $ARTIFACTS_DIR/.backend-port | tr -d '\\n')\n\n# Check if codebases exist\nCODEBASE_COUNT=$(curl -s \"http://localhost:$BACKEND_PORT/api/codebases\" | grep -c '\"id\"' || echo 0)\n\nif [ \"$CODEBASE_COUNT\" -eq 0 ]; then\n WORKTREE_PATH=$(cat $ARTIFACTS_DIR/.worktree-path | tr -d '\\n')\n curl -s -X POST \"http://localhost:$BACKEND_PORT/api/codebases\" \\\n -H \"Content-Type: application/json\" \\\n -d \"{\\\"path\\\": \\\"$WORKTREE_PATH\\\"}\"\nfi\n```\n\n---\n\n## Phase 3: Browser Testing (Verify Fix)\n\n### 3.1 Load the Agent-Browser Skill\n\n**YOU MUST LOAD THE AGENT-BROWSER SKILL NOW.** Use `/agent-browser` or invoke the skill. This gives you the full command reference for browser automation.\n\n### 3.2 Core Browser Workflow\n\n```bash\n# 1. Open the Archon UI (ALWAYS use --session)\nFRONTEND_PORT=$(cat $ARTIFACTS_DIR/.frontend-port | tr -d '\\n')\nagent-browser --session $WORKFLOW_ID open \"http://localhost:$FRONTEND_PORT\"\n\n# 2. Wait for the app to load\nagent-browser --session $WORKFLOW_ID wait --load networkidle\n\n# 3. Get interactive elements\nagent-browser --session $WORKFLOW_ID snapshot -i\n\n# 4. Take a screenshot of initial state\nagent-browser --session $WORKFLOW_ID screenshot \"$ARTIFACTS_DIR/e2e-feature-01-initial.png\"\n```\n\n### 3.3 Re-Run All Test Cases from Main\n\nFor EVERY test case that was run on main, re-run it on the feature branch:\n\n1. **Same preconditions** — set up identical starting state\n2. **Same reproduction steps** — follow the exact same actions\n3. **Verify the fix** — the bug should NOT be present now\n4. **Capture evidence** — screenshot at same points as main for side-by-side comparison\n5. **Read each screenshot** — use the Read tool to visually inspect\n6. **Compare with main** — explicitly note what's different\n\n### 3.4 Additional UX Validation\n\nBeyond just checking the bug is fixed, validate the overall experience:\n\n1. **Happy path works** — the normal user flow is smooth\n2. **Edge cases** — try unusual inputs, rapid clicks, page refreshes\n3. **Visual quality** — no layout issues, colors correct, text readable\n4. **Responsiveness** — resize the viewport, check different sizes:\n ```bash\n agent-browser --session $WORKFLOW_ID set viewport 1920 1080\n agent-browser --session $WORKFLOW_ID screenshot \"$ARTIFACTS_DIR/e2e-feature-desktop.png\"\n agent-browser --session $WORKFLOW_ID set viewport 768 1024\n agent-browser --session $WORKFLOW_ID screenshot \"$ARTIFACTS_DIR/e2e-feature-tablet.png\"\n ```\n5. **No regressions** — other features near the fix still work correctly\n\n### 3.5 API Cross-Verification\n\n```bash\nBACKEND_PORT=$(cat $ARTIFACTS_DIR/.backend-port | tr -d '\\n')\n\n# Verify data integrity matches UI\ncurl -s \"http://localhost:$BACKEND_PORT/api/conversations\" | head -c 500\n```\n\n---\n\n## Phase 4: Cleanup and Report\n\n**CRITICAL: You MUST complete cleanup before writing findings. Orphaned processes will accumulate and crash the system.**\n\n### 4.1 Close Browser\n\n```bash\n# ALWAYS use --session to only close YOUR browser, not other workflows'\nagent-browser --session $WORKFLOW_ID close 2>/dev/null || true\n```\n\n### 4.2 Stop Feature Branch Archon (Cross-Platform)\n\nKill processes by PID (recorded in Phase 2) AND by port (fallback). This works on both Windows and Unix.\n\n```bash\nBACKEND_PORT=$(cat $ARTIFACTS_DIR/.backend-port | tr -d '\\n')\nFRONTEND_PORT=$(cat $ARTIFACTS_DIR/.frontend-port | tr -d '\\n')\n\n# Kill by recorded PID (primary method — both main and feature PIDs)\nfor pidfile in \"$ARTIFACTS_DIR/.e2e-feature-backend-pid\" \"$ARTIFACTS_DIR/.e2e-feature-frontend-pid\" \"$ARTIFACTS_DIR/.e2e-main-backend-pid\" \"$ARTIFACTS_DIR/.e2e-main-frontend-pid\"; do\n if [ -f \"$pidfile\" ]; then\n PID=$(cat \"$pidfile\" | tr -d '\\n')\n echo \"Killing PID $PID from $pidfile\"\n kill \"$PID\" 2>/dev/null || taskkill //F //T //PID \"$PID\" 2>/dev/null || true\n fi\ndone\n\n# Fallback: kill by port (handles child processes the PID kill might miss)\nfor PORT in $BACKEND_PORT $FRONTEND_PORT; do\n echo \"Cleaning up port $PORT...\"\n fuser -k \"$PORT/tcp\" 2>/dev/null || true\n lsof -ti:\"$PORT\" 2>/dev/null | xargs kill -9 2>/dev/null || true\n netstat -ano 2>/dev/null | grep \":$PORT \" | grep LISTENING | awk '{print $5}' | sort -u | while read pid; do\n taskkill //F //T //PID \"$pid\" 2>/dev/null || true\n done\ndone\n\nsleep 2\necho \"Cleanup complete — verify ports are free:\"\nnetstat -ano 2>/dev/null | grep -E \":($BACKEND_PORT|$FRONTEND_PORT) \" | grep LISTENING || echo \"All ports free\"\n```\n\n### 4.3 Write Findings\n\nWrite to `$ARTIFACTS_DIR/e2e-feature.md`:\n\n```markdown\n# E2E Test Results: Feature Branch\n\n**PR**: #{number}\n**Branch**: {feature-branch} @ {commit}\n**Backend Port**: {port}\n**Frontend Port**: {port}\n**Screenshots**: $ARTIFACTS_DIR/e2e-feature-*.png\n\n## Test Summary\n\n| Test Case | Main Result | Feature Result | Fix Verified? |\n|-----------|-------------|----------------|---------------|\n| {test 1} | BUG REPRODUCED | FIXED | YES / NO |\n| {test 2} | BUG REPRODUCED | FIXED | YES / NO |\n\n## Detailed Findings\n\n### Test 1: {description}\n**Main branch**: {bug behavior — reference e2e-main screenshot}\n**Feature branch**: {fixed behavior — reference e2e-feature screenshot}\n**Fix verified**: YES / NO / PARTIAL\n**Screenshot comparison**: `e2e-main-{N}.png` vs `e2e-feature-{N}.png`\n\n### Test 2: {description}\n{Same structure...}\n\n## UX Quality Assessment\n\n| Aspect | Rating (1-5) | Notes |\n|--------|-------------|-------|\n| Visual correctness | {n} | {details} |\n| Responsiveness | {n} | {details} |\n| Edge case handling | {n} | {details} |\n| Error states | {n} | {details} |\n| Performance feel | {n} | {details} |\n\n## Regressions Found\n{Any new issues introduced by the fix, or NONE}\n\n## Additional Observations\n{Any other UX improvements or issues noticed}\n\n## Fix Confidence\n**HIGH / MEDIUM / LOW**\n\n{Overall confidence that the fix works correctly and completely}\n```\n\n---\n\n## Success Criteria\n\n- **ARCHON_STARTED**: Backend and frontend running on feature branch code\n- **ALL_TESTS_RERUN**: Every test case from main branch E2E re-executed\n- **FIX_VERIFIED**: Each bug confirmed fixed (or documented as still present)\n- **UX_VALIDATED**: Visual quality, responsiveness, edge cases checked\n- **NO_REGRESSIONS**: No new issues introduced\n- **ARCHON_STOPPED**: Processes killed, ports freed — **VERIFY ports are free before finishing**\n- **ARTIFACT_WRITTEN**: `$ARTIFACTS_DIR/e2e-feature.md` created\n", + "archon-validate-pr-e2e-main": "---\ndescription: Start Archon from main branch, use agent-browser to reproduce the bug via E2E testing\nargument-hint: (none - reads from artifacts)\n---\n\n# E2E Testing: Main Branch (Reproduce Bug)\n\nStart Archon from the **main branch** code and use browser automation to reproduce the bug or gap described in the PR. Take screenshots as evidence.\n\n**CRITICAL**: You MUST use the `agent-browser` CLI for ALL browser interactions. Load the `/agent-browser` skill for the full command reference.\n\n**CRITICAL**: You MUST clean up ALL spawned processes before finishing. Record PIDs and kill them in Phase 4.\n\n**CRITICAL — SESSION ISOLATION**: This workflow runs in parallel with other validate-pr instances.\nYou MUST use `--session $WORKFLOW_ID` on EVERY `agent-browser` command to isolate your browser session.\nExample: `agent-browser --session $WORKFLOW_ID open \"http://...\"`, `agent-browser --session $WORKFLOW_ID snapshot -i`, etc.\nThe session ID is written to `$ARTIFACTS_DIR/.browser-session` for cleanup.\n\n**ABSOLUTELY FORBIDDEN — NEVER DO ANY OF THESE**:\n- `taskkill //F //IM chrome.exe` or ANY variant that kills chrome by image name — this kills the USER's browser\n- `taskkill //F //IM node.exe` or `taskkill //F //IM bun.exe` — this kills Claude Code, the Archon server, and all other workflows\n- `pkill chrome`, `pkill node`, `pkill bun`, or any broad process-name kill\n- `agent-browser close` without `--session $WORKFLOW_ID` — this kills OTHER workflows' browser sessions\n- Any \"kill everything\" or \"kill all\" escalation pattern — if agent-browser isn't working, SKIP E2E testing and note it in your report\n- If agent-browser fails to connect after 2 attempts, STOP trying and write your findings based on code review only\n\n---\n\n## Phase 1: Load Context\n\n### 1.1 Read Artifacts\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number | tr -d '\\n')\nBACKEND_PORT=$(cat $ARTIFACTS_DIR/.backend-port | tr -d '\\n')\nFRONTEND_PORT=$(cat $ARTIFACTS_DIR/.frontend-port | tr -d '\\n')\nCANONICAL_REPO=$(cat $ARTIFACTS_DIR/.canonical-repo | tr -d '\\n')\necho \"PR: #$PR_NUMBER\"\necho \"Backend port: $BACKEND_PORT\"\necho \"Frontend port: $FRONTEND_PORT\"\necho \"Main repo: $CANONICAL_REPO\"\n```\n\n### 1.2 Read PR and Test Plan\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number | tr -d '\\n')\ngh pr view \"$PR_NUMBER\" --json title,body\n```\n\n```bash\n# Read the main branch code review for context on what to test\ncat $ARTIFACTS_DIR/code-review-main.md 2>/dev/null || echo \"No main branch review available yet\"\n```\n\n### 1.3 Testability Classification\n\nThe testability classifier determined:\n- **Decision**: $classify-testability.output.testable\n- **Reasoning**: $classify-testability.output.reasoning\n- **Test Plan**: $classify-testability.output.test_plan\n\nUse the test plan above combined with the PR description and code review to build your execution plan:\n- What user journeys reproduce the bug?\n- What should the broken behavior look like?\n- What screenshots would prove the bug exists?\n\n---\n\n## Phase 2: Start Archon on Main Branch\n\n### 2.1 Create Isolated Main Branch Worktree\n\n**IMPORTANT**: Use a dedicated worktree instead of mutating the canonical repo. This is safe\nfor concurrent validation runs — each gets its own isolated checkout.\n\n```bash\nCANONICAL_REPO=$(cat $ARTIFACTS_DIR/.canonical-repo | tr -d '\\n')\nPR_BASE=$(cat $ARTIFACTS_DIR/.pr-base | tr -d '\\n')\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number | tr -d '\\n')\n\n# Create an isolated worktree for main branch E2E testing\nMAIN_E2E_PATH=\"$ARTIFACTS_DIR/main-checkout\"\ngit -C \"$CANONICAL_REPO\" fetch origin \"$PR_BASE\" --quiet\ngit -C \"$CANONICAL_REPO\" worktree add \"$MAIN_E2E_PATH\" \"origin/$PR_BASE\" --detach --quiet\necho \"$MAIN_E2E_PATH\" > \"$ARTIFACTS_DIR/.e2e-main-worktree\"\necho \"Main E2E worktree at: $MAIN_E2E_PATH\"\necho \"Base branch: $PR_BASE @ $(git -C \"$MAIN_E2E_PATH\" log --oneline -1)\"\n```\n\n### 2.2 Install Dependencies\n\n```bash\nMAIN_E2E_PATH=$(cat $ARTIFACTS_DIR/.e2e-main-worktree | tr -d '\\n')\ncd \"$MAIN_E2E_PATH\" && bun install --frozen-lockfile 2>/dev/null || bun install\n```\n\n### 2.3 Start Backend on Custom Port\n\n**IMPORTANT**: Record the PID so we can kill it later. Server output is logged for debugging.\n\n```bash\nMAIN_E2E_PATH=$(cat $ARTIFACTS_DIR/.e2e-main-worktree | tr -d '\\n')\nBACKEND_PORT=$(cat $ARTIFACTS_DIR/.backend-port | tr -d '\\n')\n\ncd \"$MAIN_E2E_PATH\" && PORT=$BACKEND_PORT bun run --filter @archon/server dev > \"$ARTIFACTS_DIR/.e2e-main-backend.log\" 2>&1 &\nBACKEND_PID=$!\necho \"$BACKEND_PID\" > \"$ARTIFACTS_DIR/.e2e-main-backend-pid\"\necho \"Backend started with PID: $BACKEND_PID\"\n\n# Poll until healthy (max 60s)\nMAX_WAIT=60\nWAITED=0\nuntil curl -sf \"http://localhost:$BACKEND_PORT/api/health\" > /dev/null 2>&1; do\n if [ $WAITED -ge $MAX_WAIT ]; then\n echo \"ERROR: Backend did not become healthy within ${MAX_WAIT}s\"\n echo \"Last log lines:\"\n tail -20 \"$ARTIFACTS_DIR/.e2e-main-backend.log\" 2>/dev/null || true\n exit 1\n fi\n sleep 2\n WAITED=$((WAITED + 2))\ndone\necho \"Backend healthy after ${WAITED}s\"\ncurl -s \"http://localhost:$BACKEND_PORT/api/health\" | head -c 200\necho \"\"\n```\n\n### 2.4 Start Frontend on Custom Port\n\n```bash\nMAIN_E2E_PATH=$(cat $ARTIFACTS_DIR/.e2e-main-worktree | tr -d '\\n')\nBACKEND_PORT=$(cat $ARTIFACTS_DIR/.backend-port | tr -d '\\n')\nFRONTEND_PORT=$(cat $ARTIFACTS_DIR/.frontend-port | tr -d '\\n')\n\ncd \"$MAIN_E2E_PATH/packages/web\" && PORT=$BACKEND_PORT npx vite --port $FRONTEND_PORT --host > \"$ARTIFACTS_DIR/.e2e-main-frontend.log\" 2>&1 &\nFRONTEND_PID=$!\necho \"$FRONTEND_PID\" > \"$ARTIFACTS_DIR/.e2e-main-frontend-pid\"\necho \"Frontend started with PID: $FRONTEND_PID\"\n\n# Poll until serving (max 60s)\nMAX_WAIT=60\nWAITED=0\nuntil curl -sf \"http://localhost:$FRONTEND_PORT\" > /dev/null 2>&1; do\n if [ $WAITED -ge $MAX_WAIT ]; then\n echo \"ERROR: Frontend did not become ready within ${MAX_WAIT}s\"\n echo \"Last log lines:\"\n tail -20 \"$ARTIFACTS_DIR/.e2e-main-frontend.log\" 2>/dev/null || true\n exit 1\n fi\n sleep 2\n WAITED=$((WAITED + 2))\ndone\necho \"Frontend ready after ${WAITED}s\"\ncurl -s \"http://localhost:$FRONTEND_PORT\" | head -c 100\necho \"\"\n```\n\n### 2.5 Seed Test Data (if needed)\n\n```bash\nBACKEND_PORT=$(cat $ARTIFACTS_DIR/.backend-port | tr -d '\\n')\n\n# Check if codebases exist\nCODEBASE_COUNT=$(curl -s \"http://localhost:$BACKEND_PORT/api/codebases\" | grep -c '\"id\"' || echo 0)\n\nif [ \"$CODEBASE_COUNT\" -eq 0 ]; then\n MAIN_E2E_PATH=$(cat $ARTIFACTS_DIR/.e2e-main-worktree | tr -d '\\n')\n curl -s -X POST \"http://localhost:$BACKEND_PORT/api/codebases\" \\\n -H \"Content-Type: application/json\" \\\n -d \"{\\\"path\\\": \\\"$MAIN_E2E_PATH\\\"}\"\nfi\n```\n\n---\n\n## Phase 3: Browser Testing (Reproduce Bug)\n\n### 3.1 Load the Agent-Browser Skill\n\n**YOU MUST LOAD THE AGENT-BROWSER SKILL NOW.** Use `/agent-browser` or invoke the skill. This gives you the full command reference for browser automation.\n\n### 3.2 Core Browser Workflow\n\nFollow this pattern for every interaction:\n\n```bash\n# 0. Store session ID for cleanup\necho \"$WORKFLOW_ID\" > \"$ARTIFACTS_DIR/.browser-session\"\n\n# 1. Open the Archon UI (ALWAYS use --session)\nFRONTEND_PORT=$(cat $ARTIFACTS_DIR/.frontend-port | tr -d '\\n')\nagent-browser --session $WORKFLOW_ID open \"http://localhost:$FRONTEND_PORT\"\n\n# 2. Wait for the app to load\nagent-browser --session $WORKFLOW_ID wait --load networkidle\n\n# 3. Get interactive elements\nagent-browser --session $WORKFLOW_ID snapshot -i\n\n# 4. Take a screenshot of initial state\nagent-browser --session $WORKFLOW_ID screenshot \"$ARTIFACTS_DIR/e2e-main-01-initial.png\"\n\n# 5. Interact using refs from snapshot\n# agent-browser --session $WORKFLOW_ID click @e1\n# agent-browser --session $WORKFLOW_ID fill @e2 \"text\"\n\n# 6. Re-snapshot after DOM changes\n# agent-browser --session $WORKFLOW_ID snapshot -i\n\n# 7. Take screenshots at every significant point\n# agent-browser --session $WORKFLOW_ID screenshot \"$ARTIFACTS_DIR/e2e-main-02-{step}.png\"\n```\n\n### 3.3 Execute Test Plan\n\nFollow the test plan derived from the PR description and code review. For EACH test case:\n\n1. **Set up the preconditions** — navigate to the right page, create conversations/workflows as needed\n2. **Execute the reproduction steps** — exactly as described in the issue/PR\n3. **Capture evidence** — screenshot BEFORE the action, DURING, and AFTER\n4. **Verify the broken behavior** — confirm what you see matches the reported bug\n5. **Read each screenshot** — use the Read tool to visually inspect screenshots\n6. **Document what you see** — note exact error messages, visual glitches, missing elements\n\n### 3.4 API Cross-Verification\n\nFor bugs involving data integrity or SSE, cross-reference the UI with direct API calls:\n\n```bash\nBACKEND_PORT=$(cat $ARTIFACTS_DIR/.backend-port | tr -d '\\n')\n\n# Check conversations\ncurl -s \"http://localhost:$BACKEND_PORT/api/conversations\" | head -c 500\n\n# Check specific conversation messages\n# curl -s \"http://localhost:$BACKEND_PORT/api/conversations/{id}/messages\"\n\n# Check workflow runs\n# curl -s \"http://localhost:$BACKEND_PORT/api/workflows/runs\"\n```\n\n---\n\n## Phase 4: Cleanup and Report\n\n**CRITICAL: You MUST complete cleanup before writing findings. Orphaned processes will accumulate and crash the system.**\n\n### 4.1 Close Browser\n\n```bash\n# ALWAYS use --session to only close YOUR browser, not other workflows'\nagent-browser --session $WORKFLOW_ID close 2>/dev/null || true\n```\n\n### 4.2 Stop Main Branch Archon (Cross-Platform)\n\nKill processes by PID (recorded in Phase 2) AND by port (fallback). This works on both Windows and Unix.\n\n```bash\nBACKEND_PORT=$(cat $ARTIFACTS_DIR/.backend-port | tr -d '\\n')\nFRONTEND_PORT=$(cat $ARTIFACTS_DIR/.frontend-port | tr -d '\\n')\n\n# Kill by recorded PID (primary method)\nfor pidfile in \"$ARTIFACTS_DIR/.e2e-main-backend-pid\" \"$ARTIFACTS_DIR/.e2e-main-frontend-pid\"; do\n if [ -f \"$pidfile\" ]; then\n PID=$(cat \"$pidfile\" | tr -d '\\n')\n echo \"Killing PID $PID from $pidfile\"\n # Try Unix kill first, then Windows taskkill\n kill \"$PID\" 2>/dev/null || taskkill //F //T //PID \"$PID\" 2>/dev/null || true\n fi\ndone\n\n# Fallback: kill by port (handles child processes the PID kill might miss)\n# Unix: fuser/lsof, Windows: netstat + taskkill\nfor PORT in $BACKEND_PORT $FRONTEND_PORT; do\n echo \"Cleaning up port $PORT...\"\n # Try fuser (Linux)\n fuser -k \"$PORT/tcp\" 2>/dev/null || true\n # Try lsof (macOS/Linux)\n lsof -ti:\"$PORT\" 2>/dev/null | xargs kill -9 2>/dev/null || true\n # Try netstat (Windows - Git Bash)\n netstat -ano 2>/dev/null | grep \":$PORT \" | grep LISTENING | awk '{print $5}' | sort -u | while read pid; do\n taskkill //F //T //PID \"$pid\" 2>/dev/null || true\n done\ndone\n\nsleep 2\necho \"Process cleanup complete\"\n```\n\n### 4.3 Remove Main Branch Worktree\n\n```bash\nCANONICAL_REPO=$(cat $ARTIFACTS_DIR/.canonical-repo | tr -d '\\n')\nMAIN_E2E_PATH=$(cat \"$ARTIFACTS_DIR/.e2e-main-worktree\" 2>/dev/null | tr -d '\\n')\nif [ -n \"$MAIN_E2E_PATH\" ] && [ -d \"$MAIN_E2E_PATH\" ]; then\n echo \"Removing main E2E worktree: $MAIN_E2E_PATH\"\n git -C \"$CANONICAL_REPO\" worktree remove \"$MAIN_E2E_PATH\" --force 2>/dev/null || rm -rf \"$MAIN_E2E_PATH\"\nfi\necho \"Worktree cleanup complete\"\n```\n\n### 4.4 Write Findings\n\nWrite to `$ARTIFACTS_DIR/e2e-main.md`:\n\n```markdown\n# E2E Test Results: Main Branch\n\n**PR**: #{number}\n**Branch**: main @ {commit}\n**Backend Port**: {port}\n**Frontend Port**: {port}\n**Screenshots**: $ARTIFACTS_DIR/e2e-main-*.png\n\n## Test Summary\n\n| Test Case | Result | Evidence |\n|-----------|--------|----------|\n| {test 1} | BUG REPRODUCED / NOT REPRODUCED | e2e-main-{N}.png |\n| {test 2} | BUG REPRODUCED / NOT REPRODUCED | e2e-main-{N}.png |\n\n## Detailed Findings\n\n### Test 1: {description}\n**Steps**: {what was done}\n**Expected**: {what should happen on a fixed version}\n**Actual**: {what happened on main — the bug}\n**Screenshot**: `$ARTIFACTS_DIR/e2e-main-{N}.png`\n\n### Test 2: {description}\n{Same structure...}\n\n## Additional Issues Discovered\n{Any other bugs or UX issues noticed during testing}\n\n## Reproduction Confidence\n**HIGH / MEDIUM / LOW / NOT REPRODUCIBLE**\n\n{Explain confidence level. If not reproducible, explain what was tried.}\n```\n\n---\n\n## Success Criteria\n\n- **ARCHON_STARTED**: Backend and frontend running on allocated ports\n- **BROWSER_TESTED**: All test cases executed with agent-browser\n- **SCREENSHOTS_TAKEN**: Evidence captured for each test case\n- **BUG_ASSESSED**: Each PR claim tested on main branch\n- **ARCHON_STOPPED**: Processes killed, ports freed — **VERIFY ports are free before finishing**\n- **ARTIFACT_WRITTEN**: `$ARTIFACTS_DIR/e2e-main.md` created\n", + "archon-validate-pr-report": "---\ndescription: Synthesize all validation findings into a final PR verdict report\nargument-hint: (none - reads from artifacts)\n---\n\n# PR Validation Report\n\nSynthesize all code review and E2E testing findings into a comprehensive verdict.\n\n---\n\n## Phase 1: Gather All Artifacts\n\nRead every artifact produced by earlier workflow nodes:\n\n```bash\necho \"=== Available artifacts ===\"\nls -la $ARTIFACTS_DIR/\necho \"\"\necho \"=== Code review (main) ===\"\ncat $ARTIFACTS_DIR/code-review-main.md 2>/dev/null || echo \"NOT AVAILABLE\"\necho \"\"\necho \"=== Code review (feature) ===\"\ncat $ARTIFACTS_DIR/code-review-feature.md 2>/dev/null || echo \"NOT AVAILABLE\"\necho \"\"\necho \"=== E2E test (main) ===\"\ncat $ARTIFACTS_DIR/e2e-main.md 2>/dev/null || echo \"NOT AVAILABLE (code-review-only PR)\"\necho \"\"\necho \"=== E2E test (feature) ===\"\ncat $ARTIFACTS_DIR/e2e-feature.md 2>/dev/null || echo \"NOT AVAILABLE (code-review-only PR)\"\n```\n\nAlso read the PR details:\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number | tr -d '\\n')\ngh pr view \"$PR_NUMBER\" --json title,body,url,headRefName,baseRefName,additions,deletions,changedFiles\n```\n\nList all screenshots taken:\n\n```bash\nls $ARTIFACTS_DIR/e2e-*.png 2>/dev/null || echo \"No screenshots\"\n```\n\nIf screenshots exist, read a few key ones to include visual context in the report.\n\n---\n\n## Phase 2: Synthesize Findings\n\n### 2.1 Cross-Reference Code Review with E2E Results\n\nFor each bug/gap identified:\n- **Code review (main)**: Did the code analysis find the bug?\n- **E2E test (main)**: Was the bug visible in the UI?\n- **Code review (feature)**: Does the code fix look correct?\n- **E2E test (feature)**: Is the bug actually fixed in the UI?\n\n### 2.2 Identify Discrepancies\n\nLook for cases where:\n- Code review says it's fixed but E2E shows it's not\n- E2E shows it's fixed but the code fix is fragile/incomplete\n- New issues were found during E2E that code review missed\n- Code review found issues that E2E couldn't test\n\n### 2.3 Determine Final Verdict\n\n| Criteria | Required for APPROVE |\n|----------|---------------------|\n| Bug confirmed on main | Yes (or justified why not) |\n| Fix addresses root cause | Yes |\n| E2E confirms fix works | Yes (if E2E testable) |\n| No regressions | Yes |\n| Code quality acceptable | Yes |\n| CLAUDE.md compliant | Yes |\n\n---\n\n## Phase 3: Write Final Report\n\nWrite to `$ARTIFACTS_DIR/validation-report.md`:\n\n```markdown\n# PR Validation Report: #{number}\n\n**Title**: {PR title}\n**URL**: {PR URL}\n**Branch**: {head} → {base}\n**Files**: {count} changed (+{additions} -{deletions})\n**Validation Date**: {ISO timestamp}\n\n---\n\n## Verdict: {APPROVE / REQUEST_CHANGES / NEEDS_DISCUSSION}\n\n{2-3 sentence executive summary. Be direct: is this PR ready to merge?}\n\n---\n\n## Bug Confirmation\n\n| Claim | Confirmed on Main? | Fixed on Feature? | Evidence |\n|-------|--------------------|--------------------|----------|\n| {claim 1} | YES/NO | YES/NO | {screenshot refs or code refs} |\n| {claim 2} | YES/NO | YES/NO | {screenshot refs or code refs} |\n\n---\n\n## Code Review Summary\n\n### Main Branch (Pre-Fix)\n{Brief summary from code-review-main.md — was the bug evident in code?}\n\n### Feature Branch (Post-Fix)\n{Brief summary from code-review-feature.md — is the fix correct and optimal?}\n\n**Fix Quality Score**: {n}/5\n\n---\n\n## E2E Testing Summary\n\n{If E2E testing was performed:}\n\n### Main Branch (Bug Reproduction)\n{Brief summary from e2e-main.md — was the bug visible in the UI?}\n\n### Feature Branch (Fix Verification)\n{Brief summary from e2e-feature.md — is the fix verified in the UI?}\n\n**Fix Confidence**: HIGH / MEDIUM / LOW\n\n{If code-review-only:}\n\n_E2E testing was skipped — this PR's changes are not UI-visible. Validation based on code review only._\n\n---\n\n## Screenshots\n\n{List key screenshots with descriptions:}\n\n| Screenshot | Description |\n|------------|-------------|\n| `e2e-main-01-initial.png` | {what it shows} |\n| `e2e-feature-01-initial.png` | {what it shows — compare with main} |\n\n---\n\n## Issues Found\n\n### Must Fix Before Merge\n{CRITICAL or HIGH issues from any review stage. If none, say \"None.\"}\n\n### Should Fix (Non-Blocking)\n{MEDIUM issues — recommended but not blocking. If none, say \"None.\"}\n\n### Minor / Suggestions\n{LOW issues — nice to have. If none, say \"None.\"}\n\n---\n\n## Regressions\n{Any new issues introduced by the fix, or \"None found.\"}\n\n---\n\n## What's Done Well\n{Positive observations — good patterns, clean code, thorough fix}\n\n---\n\n## Recommendation\n\n**{APPROVE / REQUEST_CHANGES / NEEDS_DISCUSSION}**\n\n{Final paragraph: clear recommendation with reasoning. If REQUEST_CHANGES, list the specific changes needed. If NEEDS_DISCUSSION, describe what needs to be discussed.}\n```\n\n### 3.1 Post Summary to PR (optional)\n\nIf the verdict is clear, post a condensed summary to the PR as a comment:\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number | tr -d '\\n')\n\n# Create a concise PR comment\ngh pr comment \"$PR_NUMBER\" --body \"$(cat <<'COMMENT'\n## Archon PR Validation Report\n\n**Verdict**: {APPROVE / REQUEST_CHANGES}\n\n### Summary\n{2-3 sentence summary}\n\n### Bug Confirmation\n| Claim | Main | Feature |\n|-------|------|---------|\n| {claim} | {status} | {status} |\n\n### Issues\n{List any must-fix issues, or \"No blocking issues found.\"}\n\n---\n_Validated by archon-validate-pr workflow_\nCOMMENT\n)\"\n```\n\n---\n\n## Success Criteria\n\n- **ALL_ARTIFACTS_READ**: Every available artifact loaded and analyzed\n- **CROSS_REFERENCED**: Code review and E2E results reconciled\n- **VERDICT_DETERMINED**: Clear APPROVE / REQUEST_CHANGES / NEEDS_DISCUSSION\n- **REPORT_WRITTEN**: `$ARTIFACTS_DIR/validation-report.md` created\n- **PR_COMMENTED**: Summary posted to the PR\n", + "archon-validate": "---\ndescription: Run full validation suite - type-check, lint, tests, build\nargument-hint: (no arguments - reads from workflow artifacts)\n---\n\n# Validate Implementation\n\n**Workflow ID**: $WORKFLOW_ID\n\n---\n\n## Your Mission\n\nRun the complete validation suite and fix any failures.\n\nThis is a focused step: run checks, fix issues, repeat until green.\n\n---\n\n## Phase 1: LOAD - Get Validation Commands\n\n### 1.1 Load Plan Context\n\n```bash\ncat $ARTIFACTS_DIR/plan-context.md\n```\n\nExtract the \"Validation Commands\" section.\n\n### 1.2 Identify Package Manager\n\n```bash\ntest -f bun.lockb && echo \"bun\" || \\\ntest -f pnpm-lock.yaml && echo \"pnpm\" || \\\ntest -f yarn.lock && echo \"yarn\" || \\\ntest -f package-lock.json && echo \"npm\" || \\\necho \"unknown\"\n```\n\n### 1.3 Determine Available Commands\n\nCheck `package.json` for available scripts:\n\n```bash\ncat package.json | grep -A 20 '\"scripts\"'\n```\n\n**PHASE_1_CHECKPOINT:**\n\n- [ ] Validation commands identified\n- [ ] Package manager known\n\n---\n\n## Phase 2: VALIDATE - Run All Checks\n\nRun each check in order. Fix any failures before proceeding.\n\n### 2.1 Type Check\n\n```bash\n{runner} run type-check\n```\n\n**If fails:**\n1. Read error output\n2. Fix the type issues\n3. Re-run until passing\n\n**Record result**: ✅ Pass / ❌ Fail (fixed)\n\n### 2.2 Lint Check\n\n```bash\n{runner} run lint\n```\n\n**If fails:**\n\n1. Try auto-fix first:\n ```bash\n {runner} run lint:fix\n ```\n\n2. Re-run lint check\n\n3. If still failing, manually fix remaining issues\n\n**Record result**: ✅ Pass / ❌ Fail (fixed)\n\n### 2.3 Format Check\n\n```bash\n{runner} run format:check\n```\n\n**If fails:**\n\n1. Auto-fix:\n ```bash\n {runner} run format\n ```\n\n2. Verify fixed:\n ```bash\n {runner} run format:check\n ```\n\n**Record result**: ✅ Pass / ❌ Fail (fixed)\n\n### 2.4 Test Suite\n\n```bash\n{runner} test\n```\n\n**If fails:**\n\n1. Identify which test(s) failed\n2. Determine: implementation bug or test bug?\n3. Fix the root cause\n4. Re-run tests\n\n**Record result**: ✅ Pass ({N} tests) / ❌ Fail (fixed)\n\n### 2.5 Build Check\n\n```bash\n{runner} run build\n```\n\n**If fails:**\n\n1. Usually a type or import issue\n2. Fix and re-run\n\n**Record result**: ✅ Pass / ❌ Fail (fixed)\n\n**PHASE_2_CHECKPOINT:**\n\n- [ ] Type check passes\n- [ ] Lint passes\n- [ ] Format passes\n- [ ] Tests pass\n- [ ] Build passes\n\n---\n\n## Phase 3: ARTIFACT - Write Validation Results\n\n### 3.1 Write Validation Artifact\n\nWrite to `$ARTIFACTS_DIR/validation.md`:\n\n```markdown\n# Validation Results\n\n**Generated**: {YYYY-MM-DD HH:MM}\n**Workflow ID**: $WORKFLOW_ID\n**Status**: {ALL_PASS | FIXED | BLOCKED}\n\n---\n\n## Summary\n\n| Check | Result | Details |\n|-------|--------|---------|\n| Type check | ✅ | No errors |\n| Lint | ✅ | 0 errors, {N} warnings |\n| Format | ✅ | All files formatted |\n| Tests | ✅ | {N} passed, 0 failed |\n| Build | ✅ | Compiled successfully |\n\n---\n\n## Type Check\n\n**Command**: `{runner} run type-check`\n**Result**: ✅ Pass\n\n{If issues were fixed:}\n### Issues Fixed\n\n- `src/file.ts:42` - Added missing return type\n- `src/other.ts:15` - Fixed generic constraint\n\n---\n\n## Lint\n\n**Command**: `{runner} run lint`\n**Result**: ✅ Pass\n\n{If issues were fixed:}\n### Issues Fixed\n\n- {N} auto-fixed by `lint:fix`\n- {M} manually fixed\n\n### Remaining Warnings\n\n{List any warnings that weren't fixed, with justification}\n\n---\n\n## Format\n\n**Command**: `{runner} run format:check`\n**Result**: ✅ Pass\n\n{If files were formatted:}\n### Files Formatted\n\n- `src/file.ts`\n- `src/other.ts`\n\n---\n\n## Tests\n\n**Command**: `{runner} test`\n**Result**: ✅ Pass\n\n| Metric | Count |\n|--------|-------|\n| Total tests | {N} |\n| Passed | {N} |\n| Failed | 0 |\n| Skipped | {M} |\n\n{If tests were fixed:}\n### Tests Fixed\n\n- `src/x.test.ts` - Fixed assertion to match new behavior\n\n---\n\n## Build\n\n**Command**: `{runner} run build`\n**Result**: ✅ Pass\n\nBuild output: `dist/` (or as configured)\n\n---\n\n## Files Modified During Validation\n\n{If any files were changed to fix issues:}\n\n| File | Changes |\n|------|---------|\n| `src/file.ts` | Fixed type error |\n| `src/other.ts` | Lint auto-fix |\n\n---\n\n## Next Step\n\nContinue to `archon-finalize-pr` to update PR and mark ready for review.\n```\n\n**PHASE_3_CHECKPOINT:**\n\n- [ ] Validation artifact written\n- [ ] All results documented\n\n---\n\n## Phase 4: OUTPUT - Report Results\n\n### If All Pass:\n\n```markdown\n## Validation Complete ✅\n\n**Workflow ID**: `$WORKFLOW_ID`\n\n### Results\n\n| Check | Status |\n|-------|--------|\n| Type check | ✅ |\n| Lint | ✅ |\n| Format | ✅ |\n| Tests | ✅ ({N} passed) |\n| Build | ✅ |\n\n{If issues were fixed:}\n### Issues Fixed\n\n- {N} type errors fixed\n- {M} lint issues fixed\n- {K} format issues fixed\n\n### Artifact\n\nResults written to: `$ARTIFACTS_DIR/validation.md`\n\n### Next Step\n\nProceed to `archon-finalize-pr` to update PR and mark ready for review.\n```\n\n### If Blocked (unfixable issue):\n\n```markdown\n## Validation Blocked ❌\n\n**Workflow ID**: `$WORKFLOW_ID`\n\n### Failed Check\n\n**{check-name}**: {error description}\n\n### Attempts to Fix\n\n1. {what was tried}\n2. {what was tried}\n\n### Required Action\n\nThis issue requires manual intervention:\n\n{description of what needs to be done}\n\n### Artifact\n\nPartial results written to: `$ARTIFACTS_DIR/validation.md`\n```\n\n---\n\n## Success Criteria\n\n- **TYPE_CHECK_PASS**: `{runner} run type-check` exits 0\n- **LINT_PASS**: `{runner} run lint` exits 0\n- **FORMAT_PASS**: `{runner} run format:check` exits 0\n- **TESTS_PASS**: `{runner} test` all green\n- **BUILD_PASS**: `{runner} run build` exits 0\n- **ARTIFACT_WRITTEN**: Validation results documented\n", + "archon-web-research": "---\ndescription: Research web sources for context relevant to a GitHub issue or feature\nargument-hint: \n---\n\n# Web Research\n\n**Input**: $ARGUMENTS\n**Workflow ID**: $WORKFLOW_ID\n\n---\n\n## Your Mission\n\nSearch the web for information relevant to the issue or feature being worked on. Find official documentation, known issues, best practices, and solutions that will inform implementation.\n\n**Output**: `$ARTIFACTS_DIR/web-research.md`\n\n**Core Principle**: Search strategically, prioritize authoritative sources, cite everything.\n\n---\n\n## Phase 1: PARSE - Understand What to Research\n\n### 1.1 Get Issue Context\n\nIf input looks like a GitHub issue number:\n\n```bash\ngh issue view $ARGUMENTS --json title,body,labels\n```\n\n### 1.2 Identify Research Targets\n\nFrom the issue context, identify:\n\n- Key technologies, libraries, or APIs mentioned\n- Error messages or stack traces to search for\n- Concepts or patterns that need clarification\n- Version-specific documentation needs\n- Existing primitives in the ecosystem — what built-in or library-level abstractions already solve part of this? (avoids reinventing)\n\n### 1.3 Formulate Search Plan\n\nCreate 3-5 targeted search queries:\n\n| Query | Why | Expected Source |\n|-------|-----|-----------------|\n| \"{library} {feature} documentation\" | Official docs | Library website |\n| \"{error message}\" | Known issues | Stack Overflow, GitHub issues |\n| \"{pattern} best practices {year}\" | Current approaches | Blog posts, docs |\n| \"{library} built-in {primitive/feature}\" | Avoid reinventing | Official docs, changelog, migration guides |\n\n**PHASE_1_CHECKPOINT:**\n\n- [ ] Issue context understood\n- [ ] Research targets identified\n- [ ] Search queries formulated\n\n---\n\n## Phase 2: SEARCH - Execute Research\n\n### 2.1 Check for llms.txt\n\nMany sites publish LLM-optimized documentation:\n\n```\nTry fetching https://{domain}/llms.txt for any known site\nRead the result and fetch relevant sub-pages linked within\n```\n\n### 2.2 Search Official Documentation\n\nFor each technology/library involved:\n\n1. Search for official docs with version constraints\n2. Use `site:` operator for known authoritative sources\n3. Look for changelog/release notes for version info\n\n### 2.3 Search for Known Issues\n\nIf the issue involves errors or bugs:\n\n1. Search exact error messages in quotes\n2. Check GitHub issues for the relevant libraries\n3. Look for Stack Overflow answers\n\n### 2.4 Search for Best Practices\n\nIf the issue involves implementation decisions:\n\n1. Search for recognized patterns and approaches\n2. Cross-reference multiple sources\n3. Look for migration guides if changing approaches\n\n**PHASE_2_CHECKPOINT:**\n\n- [ ] At least 3 searches executed\n- [ ] Authoritative sources found\n- [ ] Relevant content extracted\n\n---\n\n## Phase 3: SYNTHESIZE - Compile Findings\n\n### 3.1 Organize by Relevance\n\nFor each finding:\n\n- **Source**: Name and URL\n- **Authority**: Why this source is credible\n- **Key information**: Direct quotes or specific facts\n- **Applies to**: Which part of the issue this informs\n- **Version/date**: Currency of the information\n\n### 3.2 Identify Conflicts or Gaps\n\n- Note any conflicting information between sources\n- Flag outdated content\n- Document what could NOT be found\n\n**PHASE_3_CHECKPOINT:**\n\n- [ ] Findings organized\n- [ ] Conflicts noted\n- [ ] Gaps documented\n\n---\n\n## Phase 4: GENERATE - Write Artifact\n\nWrite to `$ARTIFACTS_DIR/web-research.md`:\n\n```markdown\n# Web Research: $ARGUMENTS\n\n**Researched**: {ISO timestamp}\n**Workflow ID**: $WORKFLOW_ID\n\n---\n\n## Summary\n\n{2-3 sentence overview of key findings}\n\n---\n\n## Findings\n\n### {Source/Topic 1}\n\n**Source**: [{Name}]({URL})\n**Authority**: {Why credible}\n**Relevant to**: {Which part of the issue}\n\n**Key Information**:\n\n- {Finding 1}\n- {Finding 2}\n- {Version/date context}\n\n---\n\n### {Source/Topic 2}\n\n{Same structure...}\n\n---\n\n## Code Examples\n\n{If applicable — actual code from sources with attribution}\n\n```language\n// From [{source}]({url})\n{code example}\n```\n\n---\n\n## Gaps and Conflicts\n\n- {Information that couldn't be found}\n- {Conflicting claims between sources}\n- {Areas needing further investigation}\n\n---\n\n## Recommendations\n\nBased on research:\n\n1. {Recommendation 1 — what approach to take and why}\n2. {Recommendation 2 — what to avoid and why}\n\n---\n\n## Sources\n\n| # | Source | URL | Relevance |\n|---|--------|-----|-----------|\n| 1 | {name} | {url} | {brief relevance} |\n| 2 | {name} | {url} | {brief relevance} |\n```\n\n**PHASE_4_CHECKPOINT:**\n\n- [ ] Artifact written to `$ARTIFACTS_DIR/web-research.md`\n- [ ] All sources cited with URLs\n- [ ] Recommendations actionable\n\n---\n\n## Phase 5: OUTPUT - Report\n\n```markdown\n## Web Research Complete\n\n**Queries**: {n} searches executed\n**Sources**: {n} relevant sources found\n**Artifact**: `$ARTIFACTS_DIR/web-research.md`\n\n### Key Findings\n\n- {Finding 1}\n- {Finding 2}\n- {Finding 3}\n\n### Gaps\n\n- {What couldn't be found, if any}\n```\n\n---\n\n## Quality Standards\n\n| Standard | Requirement |\n|----------|-------------|\n| **Accuracy** | Quote sources exactly, provide direct links |\n| **Relevance** | Focus on what directly addresses the issue |\n| **Currency** | Note publication dates and versions |\n| **Authority** | Prioritize official docs, recognized experts |\n| **Completeness** | Search multiple angles, note gaps |\n| **Transparency** | Flag outdated, conflicting, or uncertain info |\n\n---\n\n## What NOT To Do\n\n- Don't guess when you can search\n- Don't fetch pages without checking search results first\n- Don't ignore publication dates on technical content\n- Don't present a single source as definitive without corroboration\n- Don't skip the Gaps section — be honest about limitations\n\n---\n\n## Success Criteria\n\n- **RESEARCH_EXECUTED**: At least 3 targeted searches completed\n- **SOURCES_CITED**: All findings have source URLs\n- **ARTIFACT_WRITTEN**: Research saved to `$ARTIFACTS_DIR/web-research.md`\n- **ACTIONABLE**: Findings directly inform implementation decisions\n", + "archon-workflow-summary": "---\ndescription: Final workflow summary with decision matrix for follow-up actions\nargument-hint: (no arguments - reads from workflow artifacts)\n---\n\n# Workflow Summary\n\n**Workflow ID**: $WORKFLOW_ID\n\n---\n\n## Your Mission\n\nCreate the final summary report for the workflow run:\n1. Summarize what was implemented vs the plan\n2. List deviations and their rationale\n3. Surface unfixed review findings (MEDIUM/LOW)\n4. Create actionable follow-up recommendations\n5. Post to GitHub PR as a comment\n6. Write artifact for future reference\n\n**Output**: Decision matrix the user can act on quickly.\n\n---\n\n## Phase 1: LOAD - Gather ALL Artifacts\n\n**CRITICAL**: Read EVERY artifact from the workflow run. Miss nothing.\n\n### 1.1 Scan Workflow Artifacts Directory\n\n```bash\n# List all artifacts from this workflow run\nls -la $ARTIFACTS_DIR/\n\n# Read each one\nfor file in $ARTIFACTS_DIR/*.md; do\n echo \"=== $file ===\"\n cat \"$file\"\ndone\n```\n\n**Expected artifacts**:\n- `plan-context.md` - Plan summary, scope limits, acceptance criteria\n- `plan-confirmation.md` - Pattern verification results\n- `implementation.md` - Tasks done, deviations, issues encountered\n- `validation.md` - Test/lint/build results\n- `pr-ready.md` - PR number, URL, final commit\n- `.pr-number` - PR number registry file\n- `.pr-url` - PR URL registry file\n\n### 1.2 Scan Review Artifacts\n\n```bash\n# Read review artifacts from workflow-scoped directory\nls -la $ARTIFACTS_DIR/review/\n\n# Read each review finding\nfor file in $ARTIFACTS_DIR/review/*.md; do\n echo \"=== $file ===\"\n cat \"$file\"\ndone\n```\n\n**Expected review artifacts** (in `runs/$WORKFLOW_ID/review/`):\n- `scope.md` - Files changed, scope limits, focus areas\n- `code-review-findings.md` - Code quality issues\n- `error-handling-findings.md` - Silent failures, catch blocks\n- `test-coverage-findings.md` - Test gaps\n- `comment-quality-findings.md` - Documentation issues\n- `docs-impact-findings.md` - Doc update needs\n- `consolidated-review.md` - Combined findings, priorities\n- `fix-report.md` - What was fixed\n- `sync-report.md` - Rebase/sync status (if applicable)\n\n### 1.3 Extract Key Data\n\n**From plan-context.md**:\n- Plan title and summary\n- Files expected to change\n- **NOT Building (Scope Limits)** - CRITICAL: these are follow-up candidates\n- Acceptance criteria\n\n**From implementation.md**:\n- Tasks completed vs planned\n- Files actually changed\n- **Deviations from plan** - document these prominently\n- Issues encountered during implementation\n\n**From all review findings**:\n- CRITICAL/HIGH issues (should be fixed)\n- **MEDIUM issues** - follow-up candidates\n- **LOW issues** - optional follow-ups\n- Specific recommendations by category\n\n**From fix-report.md**:\n- What was actually fixed\n- What was NOT fixed (and why)\n\n### 1.4 Cross-Reference\n\nCompare across artifacts:\n- Plan vs Implementation: What matched? What deviated?\n- Review findings vs Fix report: What's still open?\n- NOT Building vs Review findings: Did reviewers flag excluded items? (this is expected, note it)\n\n**PHASE_1_CHECKPOINT:**\n\n- [ ] ALL workflow artifacts read\n- [ ] ALL review artifacts read\n- [ ] Deviations extracted\n- [ ] Unfixed issues identified\n- [ ] NOT Building items noted\n\n---\n\n## Phase 2: ANALYZE - Build Follow-Up Matrix\n\n### 2.1 Categorize Follow-Up Items\n\n**From \"NOT Building\" section** - Future work explicitly deferred:\n\n| Item | Rationale | Suggested Follow-Up |\n|------|-----------|---------------------|\n| {excluded item} | {why excluded} | Create issue / Separate PR / Not needed |\n\n**From Implementation Deviations** - Changes that diverged from plan:\n\n| Deviation | Reason | Impact | Follow-Up Needed? |\n|-----------|--------|--------|-------------------|\n| {what changed} | {why} | {low/medium/high} | {yes/no + action} |\n\n**From Unfixed Review Findings** - MEDIUM/LOW severity items:\n\n| Finding | Severity | Category | Suggested Action |\n|---------|----------|----------|------------------|\n| {issue} | MEDIUM | docs | Update CLAUDE.md |\n| {issue} | LOW | test | Add edge case test |\n| {issue} | MEDIUM | error-handling | Log instead of silent |\n\n### 2.2 Prioritize by Effort vs Value\n\n**Quick Wins** (< 5 min, high value):\n- Documentation updates\n- Simple comment additions\n- Missing log statements\n\n**Worth Doing** (medium effort, clear value):\n- Test coverage gaps\n- Error message improvements\n- Type refinements\n\n**Can Defer** (higher effort or lower urgency):\n- Refactoring suggestions\n- Performance optimizations\n- Style improvements\n\n**PHASE_2_CHECKPOINT:**\n\n- [ ] NOT Building items categorized\n- [ ] Deviations assessed\n- [ ] Unfixed findings prioritized\n- [ ] Quick wins identified\n\n---\n\n## Phase 3: GENERATE - Create Decision Matrix\n\n### 3.1 Build Decision Matrix\n\nStructure the output for easy decision-making:\n\n```markdown\n## Follow-Up Decision Matrix\n\n### 🚀 Quick Wins (Can do now, < 5 min each)\n\n| # | Item | Action | Command |\n|---|------|--------|---------|\n| 1 | Update CLAUDE.md with new column | Docs update | `Run docs agent` |\n| 2 | Add missing JSDoc to deactivateSession | Comment | `Auto-fix` |\n\n**Your choice**:\n- [ ] Do all quick wins before merge\n- [ ] Create issues for later\n- [ ] Skip (not needed)\n\n---\n\n### 📋 Suggested GitHub Issues\n\n| # | Title | Labels | From |\n|---|-------|--------|------|\n| 1 | {issue title} | `enhancement`, `docs` | NOT Building |\n| 2 | {issue title} | `bug`, `low-priority` | Review finding |\n\n**Your choice**:\n- [ ] Create all issues\n- [ ] Create selected: {numbers}\n- [ ] Skip issue creation\n\n---\n\n### 📝 Documentation Gaps\n\n| File | Section | Update Needed |\n|------|---------|---------------|\n| CLAUDE.md | Database Schema | Add ended_reason column |\n| $DOCS_DIR/architecture.md | Sessions | Update deactivateSession signature |\n\n**Your choice**:\n- [ ] Send docs agent to fix all\n- [ ] Fix manually after merge\n- [ ] Skip (acceptable as-is)\n\n---\n\n### ⚠️ Deferred Items (from NOT Building)\n\n| Item | Why Deferred | When to Address |\n|------|--------------|-----------------|\n| {item} | {rationale} | {next sprint / never / if needed} |\n\n**These were intentionally excluded** - no action needed unless priorities change.\n```\n\n**PHASE_3_CHECKPOINT:**\n\n- [ ] Decision matrix structured\n- [ ] Quick wins identified\n- [ ] Issues drafted\n- [ ] Docs gaps listed\n\n---\n\n## Phase 4: POST - GitHub PR Comment\n\n### 4.1 Format for GitHub\n\nCreate a PR comment with the summary:\n\n```markdown\n## 🎯 Workflow Summary\n\n**Plan**: `{plan-path}`\n**Status**: ✅ Implementation complete, PR ready for review\n\n---\n\n### Implementation vs Plan\n\n| Metric | Planned | Actual |\n|--------|---------|--------|\n| Files created | {N} | {N} |\n| Files updated | {M} | {M} |\n| Tests added | {K} | {K} |\n| Deviations | - | {count} |\n\n{If deviations:}\n
\n📋 Deviations from Plan ({count})\n\n{List each deviation with reason}\n\n
\n\n---\n\n### Review Summary\n\n| Severity | Found | Fixed | Remaining |\n|----------|-------|-------|-----------|\n| CRITICAL | {N} | {N} | 0 |\n| HIGH | {N} | {N} | 0 |\n| MEDIUM | {N} | {fixed} | {remaining} |\n| LOW | {N} | {fixed} | {remaining} |\n\n---\n\n### 🚀 Quick Wins Before Merge\n\n{If any quick wins identified:}\n\n| Item | Effort | Action |\n|------|--------|--------|\n| {item} | ~2 min | {action} |\n\n**Reply with**: `@archon do quick wins` to auto-fix these.\n\n---\n\n### 📋 Suggested Follow-Up Issues\n\n{If issues suggested:}\n\n| Title | Labels |\n|-------|--------|\n| {title} | {labels} |\n\n**Reply with**: `@archon create follow-up issues` to create these.\n\n---\n\n### 📝 Documentation Updates\n\n{If doc gaps found:}\n\n| File | Update |\n|------|--------|\n| {file} | {what} |\n\n**Reply with**: `@archon update docs` to send a docs agent.\n\n---\n\n
\nℹ️ Deferred Items (NOT Building)\n\nThese were **intentionally excluded** from scope:\n\n{List from NOT Building section}\n\n
\n\n---\n\n**Artifacts**: `$ARTIFACTS_DIR/`\n```\n\n### 4.2 Post to GitHub\n\n```bash\ngh pr comment {pr-number} --body \"{formatted-summary}\"\n```\n\n**PHASE_4_CHECKPOINT:**\n\n- [ ] Summary formatted for GitHub\n- [ ] Comment posted to PR\n\n---\n\n## Phase 5: ARTIFACT - Write Summary\n\n### 5.1 Write Summary Artifact\n\nWrite to `$ARTIFACTS_DIR/workflow-summary.md`:\n\n```markdown\n# Workflow Summary\n\n**Generated**: {YYYY-MM-DD HH:MM}\n**Workflow ID**: $WORKFLOW_ID\n**PR**: #{number}\n\n---\n\n## Execution Summary\n\n| Phase | Status | Notes |\n|-------|--------|-------|\n| Setup | ✅ | Branch ready |\n| Confirm | ✅ | Plan validated |\n| Implement | ✅ | {N} tasks completed |\n| Validate | ✅ | All checks pass |\n| PR | ✅ | #{number} created |\n| Review | ✅ | {N} agents ran |\n| Fixes | ✅ | {N} issues fixed |\n\n---\n\n## Implementation vs Plan\n\n{Detailed comparison}\n\n---\n\n## Deviations\n\n{List with rationale}\n\n---\n\n## Unfixed Review Findings\n\n### MEDIUM Severity\n\n{List}\n\n### LOW Severity\n\n{List}\n\n---\n\n## Follow-Up Recommendations\n\n### GitHub Issues to Create\n\n{List with draft titles/bodies}\n\n### Documentation Updates\n\n{List with specific changes}\n\n### Deferred to Future\n\n{List from NOT Building}\n\n---\n\n## Decision Matrix\n\n{Copy of the decision matrix}\n\n---\n\n## GitHub Comment\n\nPosted to: {PR URL}#comment-{id}\n```\n\n**PHASE_5_CHECKPOINT:**\n\n- [ ] Summary artifact written\n- [ ] All sections complete\n\n---\n\n## Phase 5.5: ARCHIVE - Create Backward-Compatible Symlink\n\n### 5.5.1 Create Symlink for PR-Based Lookup\n\nCreate symlink for backward compatibility with PR-based artifact lookup:\n\n```bash\nPR_NUMBER=$(cat $ARTIFACTS_DIR/.pr-number 2>/dev/null)\nif [ -n \"$PR_NUMBER\" ]; then\n mkdir -p $ARTIFACTS_DIR/../reviews\n ln -sfn ../runs/$WORKFLOW_ID/review $ARTIFACTS_DIR/../reviews/pr-$PR_NUMBER\nfi\n```\n\nThis allows legacy tools to find review artifacts at `$ARTIFACTS_DIR/../reviews/pr-{number}/`.\n\n**PHASE_5.5_CHECKPOINT:**\n\n- [ ] Symlink created (if PR number available)\n\n---\n\n## Phase 6: OUTPUT - Report to User\n\n```markdown\n## Workflow Complete 🎉\n\n**Workflow ID**: `$WORKFLOW_ID`\n**PR**: #{number} - {title}\n\n### Summary\n\n| Metric | Value |\n|--------|-------|\n| Tasks completed | {N}/{N} |\n| Review findings fixed | {N} |\n| Quick wins available | {N} |\n| Follow-up issues suggested | {N} |\n\n### Posted to GitHub\n\nSummary comment added to PR with:\n- Implementation vs plan comparison\n- Deviations documented\n- Decision matrix for follow-ups\n\n### Your Next Steps\n\n1. **Review the PR**: {url}\n2. **Quick wins**: Reply `@archon do quick wins` on PR (or skip)\n3. **Create issues**: Reply `@archon create follow-up issues` (or skip)\n4. **Merge when ready**\n\n### Artifacts\n\n- Summary: `$ARTIFACTS_DIR/workflow-summary.md`\n- All artifacts: `$ARTIFACTS_DIR/`\n```\n\n---\n\n## Success Criteria\n\n- **ARTIFACTS_LOADED**: All workflow artifacts read\n- **MATRIX_CREATED**: Follow-up items categorized and prioritized\n- **GITHUB_POSTED**: Summary comment on PR\n- **ARTIFACT_WRITTEN**: workflow-summary.md created\n- **ACTIONABLE**: User has clear next steps with minimal cognitive load\n", +}; + +// Bundled default workflows (20 total) +export const BUNDLED_WORKFLOWS: Record = { + "archon-adversarial-dev": "name: archon-adversarial-dev\ndescription: |\n Use when: User wants to build a complete application from scratch using adversarial development.\n Triggers: \"adversarial dev\", \"adversarial development\", \"build with adversarial\", \"gan dev\",\n \"adversarial build\", \"build app adversarially\", \"adversarial coding\".\n Does: Three-role GAN-inspired development — Planner creates spec with sprints, then a state-machine\n loop alternates between Generator (builds code) and Evaluator (attacks it) with hard pass/fail\n thresholds. The evaluator's job is to BREAK what the generator builds. If any criterion scores\n below 7/10, the sprint goes back to the generator with adversarial feedback. Stops on sprint\n failure after max retries.\n NOT for: Bug fixes, PR reviews, refactoring existing code, simple one-off tasks.\n\n Based on Anthropic's harness design article for long-running application development.\n Separates planning, building, and evaluation into distinct roles with adversarial tension.\nprovider: claude\nmodel: sonnet\n\nnodes:\n # ─── Phase 1: Planning ───────────────────────────────────────────────\n - id: plan\n prompt: |\n You are a product planning expert. Your job is to take a short user prompt and expand it\n into a comprehensive product specification.\n\n ## User Request\n\n $ARGUMENTS\n\n ## Your Task\n\n Write a comprehensive product specification to the file `$ARTIFACTS_DIR/spec.md` using the Write tool.\n\n The spec MUST include ALL of the following sections:\n\n ### 1. Product Overview\n What the product does, who it's for, core value proposition.\n\n ### 2. Tech Stack\n Specific technologies, frameworks, and libraries. Be opinionated — pick concrete choices,\n not \"a modern framework.\" Include exact package names and versions where relevant.\n\n ### 3. Design Language\n Visual style, specific color hex codes, typography choices, component patterns, spacing system.\n\n ### 4. Feature List\n Every feature organized by priority. Be exhaustive.\n\n ### 5. Sprint Plan\n Features broken into 3-6 sprints, ordered by dependency and importance:\n - **Sprint 1** should establish the foundation (project setup, core data models, basic UI shell)\n - Each subsequent sprint builds on the previous\n - Label each sprint clearly: \"Sprint 1: Foundation\", \"Sprint 2: Core Features\", etc.\n - List the specific features/deliverables for each sprint\n\n Be specific and opinionated. The more concrete the spec (exact API paths, specific color codes,\n named libraries), the better the generator can build and the evaluator can test.\n\n IMPORTANT: Write the spec to `$ARTIFACTS_DIR/spec.md` using the Write tool. Do NOT just output\n it as conversation text.\n allowed_tools: [Read, Write, Glob, Grep]\n\n # ─── Phase 2: Workspace Initialization ───────────────────────────────\n - id: init-workspace\n depends_on: [plan]\n bash: |\n ARTIFACTS=\"$ARTIFACTS_DIR\"\n\n # Create directory structure for harness communication\n mkdir -p \"$ARTIFACTS/contracts\"\n mkdir -p \"$ARTIFACTS/feedback\"\n mkdir -p \"$ARTIFACTS/app\"\n\n # Initialize isolated git repo in app directory\n cd \"$ARTIFACTS/app\"\n git init -q\n git commit --allow-empty -m \"Initial commit: adversarial-dev workspace\" -q\n\n # Extract sprint count from spec (find highest \"Sprint N\" reference)\n SPEC=\"$ARTIFACTS/spec.md\"\n SPRINT_COUNT=3\n if [ -f \"$SPEC\" ]; then\n FOUND=$(grep -ioE 'sprint\\s+[0-9]+' \"$SPEC\" | grep -oE '[0-9]+' | sort -n | tail -1)\n if [ -n \"$FOUND\" ] && [ \"$FOUND\" -ge 1 ] 2>/dev/null; then\n SPRINT_COUNT=$FOUND\n fi\n if [ \"$SPRINT_COUNT\" -gt 10 ]; then\n SPRINT_COUNT=10\n fi\n fi\n\n # Write initial state machine file\n cat > \"$ARTIFACTS/state.json\" << 'STATEEOF'\n {\n \"phase\": \"negotiating\",\n \"sprint\": 1,\n \"totalSprints\": SPRINT_COUNT_PLACEHOLDER,\n \"retry\": 0,\n \"maxRetries\": 3,\n \"passThreshold\": 7,\n \"completedSprints\": [],\n \"status\": \"running\"\n }\n STATEEOF\n sed -i \"s/SPRINT_COUNT_PLACEHOLDER/$SPRINT_COUNT/\" \"$ARTIFACTS/state.json\"\n\n echo \"{\\\"totalSprints\\\": $SPRINT_COUNT, \\\"appDir\\\": \\\"$ARTIFACTS/app\\\", \\\"artifactsDir\\\": \\\"$ARTIFACTS\\\"}\"\n timeout: 30000\n\n # ─── Phase 3: Adversarial Sprint Loop ────────────────────────────────\n #\n # State machine driven by $ARTIFACTS_DIR/state.json\n # Each iteration plays ONE role: negotiator, generator, or evaluator\n # fresh_context ensures genuine separation between roles\n #\n - id: adversarial-sprint\n depends_on: [init-workspace]\n idle_timeout: 600000\n model: claude-opus-4-6[1m]\n loop:\n prompt: |\n # Adversarial Development — Sprint Loop\n\n You are part of a GAN-inspired adversarial development system with three distinct roles.\n Each iteration you play ONE role, determined by the current phase in the state file.\n\n ## FIRST: Read State\n\n Read `$ARTIFACTS_DIR/state.json` to determine:\n - `phase` — which role you play this iteration\n - `sprint` — current sprint number\n - `totalSprints` — how many sprints total\n - `retry` — current retry attempt (0 = first try)\n - `maxRetries` — max retries before hard failure (default 3)\n - `passThreshold` — minimum score to pass (default 7)\n\n Then read `$ARTIFACTS_DIR/spec.md` for product context.\n\n ## Directory Layout\n\n - App source code: `$ARTIFACTS_DIR/app/`\n - Sprint contracts: `$ARTIFACTS_DIR/contracts/sprint-{N}.json`\n - Evaluation feedback: `$ARTIFACTS_DIR/feedback/sprint-{N}-round-{R}.json`\n - State machine: `$ARTIFACTS_DIR/state.json`\n\n ---\n\n ## ROLE: CONTRACT NEGOTIATOR (phase = \"negotiating\")\n\n You negotiate the success criteria for the current sprint. Play BOTH sides sequentially:\n\n **Step 1 — Generator's Proposal:**\n Read the spec carefully. Identify what Sprint {N} should deliver based on the sprint plan.\n Propose a sprint contract with 5-15 specific, testable criteria.\n\n Each criterion MUST be concrete and verifiable. Examples:\n - GOOD: \"GET /api/tasks returns 200 with JSON array; each item has id (number), title (string), status (string), createdAt (ISO date)\"\n - GOOD: \"Clicking the Add Task button opens a modal with title input, priority dropdown (low/medium/high), and due date picker\"\n - BAD: \"The API works well\"\n - BAD: \"Tasks can be managed\"\n\n **Step 2 — Evaluator's Tightening:**\n Now review your proposal as an adversary. For EACH criterion ask:\n - Is it specific enough to test programmatically?\n - What edge cases are missing? (empty inputs, special characters, concurrent requests)\n - Is the bar high enough, or would sloppy code pass?\n\n Tighten vague criteria. Add edge cases. Raise the bar.\n\n **Write the final contract** to `$ARTIFACTS_DIR/contracts/sprint-{N}.json`:\n ```json\n {\n \"sprintNumber\": ,\n \"features\": [\"feature1\", \"feature2\", ...],\n \"criteria\": [\n {\n \"name\": \"short-kebab-name\",\n \"description\": \"Specific, testable description of what must be true\",\n \"threshold\": 7\n }\n ]\n }\n ```\n\n **Update state.json**: Set `\"phase\": \"building\"`. Keep all other fields unchanged.\n\n ---\n\n ## ROLE: GENERATOR (phase = \"building\")\n\n You are a software engineer. Build features that MUST survive an adversarial evaluator\n who will actively try to break your code.\n\n **Read these files:**\n 1. `$ARTIFACTS_DIR/spec.md` — full product spec (design language, tech stack, all features)\n 2. `$ARTIFACTS_DIR/contracts/sprint-{N}.json` — the contract you must satisfy\n 3. If `retry` > 0: read `$ARTIFACTS_DIR/feedback/sprint-{N}-round-{R-1}.json` for the\n evaluator's previous feedback\n\n **If this is a RETRY (retry > 0):**\n Read the feedback CAREFULLY. Every failed criterion must be addressed.\n - If scores were close (5-6) and trending up: REFINE your approach\n - If scores were low (1-4) or the approach is fundamentally broken: PIVOT to a new strategy\n - Address EVERY feedback item — the evaluator WILL check\n - Re-verify each fix by running the code before committing\n\n **Build rules:**\n - All code goes in `$ARTIFACTS_DIR/app/`\n - Build ONE feature at a time, verify it works, then commit:\n ```bash\n cd $ARTIFACTS_DIR/app && git add -A && git commit -m \"feat: description of what was built\"\n ```\n - Install dependencies as needed (npm/bun/pip/etc)\n - Test your code — start the server, hit the endpoints, verify the UI renders\n - Think about what the evaluator will attack: edge cases, error handling, input validation\n - Build defensively — the evaluator's job is to break you\n\n **Update state.json**: Set `\"phase\": \"evaluating\"`. Keep all other fields unchanged.\n\n ---\n\n ## ROLE: EVALUATOR (phase = \"evaluating\")\n\n You are an ADVERSARIAL QA agent. Your mandate is to BREAK what the generator built.\n You are not helpful. You are not generous. You are an attacker.\n\n **CRITICAL CONSTRAINTS:**\n - You are READ-ONLY for source code. NEVER use Write or Edit on files in `$ARTIFACTS_DIR/app/`.\n - You MAY use Bash to run the app, curl endpoints, run test scripts, check behavior.\n - You MUST kill any background processes (servers, watchers) you start BEFORE finishing.\n Use: `pkill -f \"node\\|bun\\|python\\|npm\" 2>/dev/null || true`\n - You MUST score EVERY criterion in the contract. No skipping.\n\n **Scoring guidelines:**\n - **9-10**: Exceptional. Works perfectly including edge cases the contract didn't mention.\n - **7-8**: Solid. Meets the criterion as stated. Minor polish issues at most.\n - **5-6**: Partial. Core functionality exists but fails important edge cases or has bugs.\n - **3-4**: Weak. Barely functional. Major gaps.\n - **1-2**: Broken. Does not work or is not implemented.\n\n Do NOT grade on a curve. Do NOT give benefit of the doubt. A 7 means \"genuinely meets the bar.\"\n If something is broken, say it's broken.\n\n **Read**: `$ARTIFACTS_DIR/contracts/sprint-{N}.json` for the criteria.\n\n **For each criterion:**\n 1. Read the relevant source code\n 2. Run the application (start server, test endpoints, check rendered UI)\n 3. Try to BREAK it — invalid inputs, missing fields, edge cases, error handling gaps\n 4. Score it honestly\n\n **Write evaluation** to `$ARTIFACTS_DIR/feedback/sprint-{N}-round-{R}.json`:\n ```json\n {\n \"passed\": = passThreshold, false otherwise>,\n \"scores\": {\n \"criterion-name\": ,\n ...\n },\n \"feedback\": [\n {\n \"criterion\": \"criterion-name\",\n \"score\": <1-10>,\n \"details\": \"Specific findings. Include file paths, line numbers, exact error messages, curl commands that failed.\"\n }\n ],\n \"overallSummary\": \"What worked, what didn't, what the generator must fix.\"\n }\n ```\n\n **Determine pass/fail** — `passed` is `true` ONLY if every single score >= `passThreshold`.\n\n **Update state.json based on result:**\n\n **If PASSED (all criteria >= threshold):**\n - Add current sprint number to `completedSprints` array\n - If `sprint` < `totalSprints`: set `\"phase\": \"negotiating\"`, increment `\"sprint\"` by 1, set `\"retry\": 0`\n - If `sprint` == `totalSprints`: set `\"phase\": \"complete\"`, set `\"status\": \"complete\"`\n\n **If FAILED:**\n - If `retry` < `maxRetries`: set `\"phase\": \"building\"`, increment `\"retry\"` by 1\n - If `retry` >= `maxRetries`: set `\"phase\": \"failed\"`, set `\"status\": \"failed\"`\n\n **IMPORTANT**: Kill all background processes before finishing:\n ```bash\n pkill -f \"node|bun|python|npm|next|vite|webpack\" 2>/dev/null || true\n ```\n\n ---\n\n ## COMPLETION\n\n After updating state.json, check the `status` field:\n - If `\"status\": \"complete\"` → all sprints passed! Output: `ALL_SPRINTS_COMPLETE`\n - If `\"status\": \"failed\"` → sprint failed after max retries. Output: `ALL_SPRINTS_COMPLETE`\n - If `\"status\": \"running\"` → more work to do. Do NOT output any completion signal.\n\n until: ALL_SPRINTS_COMPLETE\n max_iterations: 60\n fresh_context: true\n until_bash: |\n grep -qE '\"status\"\\s*:\\s*\"(complete|failed)\"' \"$ARTIFACTS_DIR/state.json\"\n\n # ─── Phase 4: Report ─────────────────────────────────────────────────\n - id: report\n depends_on: [adversarial-sprint]\n trigger_rule: all_done\n context: fresh\n model: haiku\n prompt: |\n You are a project reporter. Generate a comprehensive summary of the adversarial development run.\n\n ## Read ALL of these files:\n 1. `$ARTIFACTS_DIR/state.json` — final state (tells you success/failure, sprint count)\n 2. `$ARTIFACTS_DIR/spec.md` — the original product spec\n 3. All files in `$ARTIFACTS_DIR/contracts/` — sprint contracts (use Glob to find them)\n 4. All files in `$ARTIFACTS_DIR/feedback/` — evaluation results (use Glob to find them)\n\n ## Generate a report covering:\n\n ### Build Summary\n - What application was built (from the spec)\n - Final status: did all sprints pass or did it fail? On which sprint?\n - Total sprints completed vs planned\n\n ### Per-Sprint Breakdown\n For each sprint that was attempted:\n - What the contract required (features + key criteria)\n - How many attempts were needed (retry count)\n - Final scores for each criterion\n - Key feedback that drove retries and improvements\n\n ### Quality Metrics\n - Average score across all final-round criteria\n - Which criteria required the most retries\n - Where the adversarial evaluator pushed quality the highest\n\n ### How to Run\n - The application code lives in: `$ARTIFACTS_DIR/app/`\n - Include the tech stack and how to start the app (from the spec)\n - Include any setup steps (install deps, env vars, etc.)\n\n Write this report to `$ARTIFACTS_DIR/report.md` AND output it as your response so the user\n sees it directly.\n allowed_tools: [Read, Write, Glob, Grep]\n", + "archon-architect": "name: archon-architect\ndescription: |\n Use when: User wants an architectural sweep, complexity reduction, or codebase health improvement.\n Triggers: \"architect\", \"simplify codebase\", \"reduce complexity\", \"architectural sweep\",\n \"clean up architecture\", \"codebase health\", \"fix architecture\".\n Does: Scans codebase metrics -> analyzes architecture with principled lens -> plans targeted\n simplifications -> executes fixes with self-review loops (hooks) -> validates -> creates PR.\n NOT for: Single-file fixes, feature development, bug fixes, PR reviews.\n\n DAG workflow showcasing per-node hooks:\n - PostToolUse hooks create organic quality loops (lint after write, self-review)\n - PreToolUse hooks inject architectural principles before changes\n - Different nodes have different trust levels and steering\n\nprovider: claude\n\nnodes:\n # ═══════════════════════════════════════════════════════════════\n # PHASE 1: MEASURE\n # Gather raw metrics — file sizes, complexity hotspots, dependency fan-out\n # ═══════════════════════════════════════════════════════════════\n\n - id: scan-metrics\n bash: |\n echo \"=== FILE SIZE HOTSPOTS (top 30 largest source files) ===\"\n find . -name '*.ts' -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/dist/*' \\\n -exec wc -l {} + 2>/dev/null | sort -rn | head -30\n\n echo \"\"\n echo \"=== IMPORT FAN-OUT (files with most imports) ===\"\n for f in $(find . -name '*.ts' -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/dist/*'); do\n count=$(grep -c \"^import \" \"$f\" 2>/dev/null) || count=0\n if [ \"$count\" -gt 8 ]; then\n echo \"$count imports: $f\"\n fi\n done | sort -rn | head -20\n\n echo \"\"\n echo \"=== EXPORT FAN-OUT (files with most exports) ===\"\n for f in $(find . -name '*.ts' -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/dist/*'); do\n count=$(grep -c \"^export \" \"$f\" 2>/dev/null) || count=0\n if [ \"$count\" -gt 5 ]; then\n echo \"$count exports: $f\"\n fi\n done | sort -rn | head -20\n\n echo \"\"\n echo \"=== FUNCTION LENGTH HOTSPOTS (functions over 50 lines) ===\"\n grep -rn \"^\\(export \\)\\?\\(async \\)\\?function \\|=> {$\" \\\n --include='*.ts' --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist . 2>/dev/null \\\n | head -30\n\n echo \"\"\n echo \"=== TYPE SAFETY GAPS ===\"\n echo \"any usage:\"\n grep -rn \": any\\b\\|as any\\b\" --include='*.ts' --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist . 2>/dev/null | wc -l\n echo \"eslint-disable comments:\"\n grep -rn \"eslint-disable\" --include='*.ts' --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist . 2>/dev/null | wc -l\n timeout: 60000\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 2: ANALYZE\n # Read through hotspots with an architectural lens\n # Hooks inject assessment criteria after every file read\n # ═══════════════════════════════════════════════════════════════\n\n - id: analyze\n prompt: |\n You are a senior software architect performing a codebase health assessment.\n\n ## Codebase Metrics\n\n $scan-metrics.output\n\n ## User Focus\n\n $ARGUMENTS\n\n ## Instructions\n\n 1. Read the top 10-15 files flagged by the metrics above (largest, most imports, most exports)\n 2. For each file, assess the criteria injected after you read it (you'll see them)\n 3. Build a running list of architectural concerns\n 4. Focus on:\n - Modules doing too many things (SRP violations)\n - Abstractions that don't earn their complexity\n - Duplicated patterns that should be consolidated (Rule of Three)\n - God files or god functions\n - Leaky abstractions or tight coupling between layers\n - Dead code or unused exports\n 5. Do NOT suggest changes yet — only diagnose\n\n ## Output\n\n Write a structured assessment to $ARTIFACTS_DIR/architecture-assessment.md with:\n - Executive summary (3-5 sentences)\n - Top findings ranked by impact\n - For each finding: file, what's wrong, why it matters, estimated effort\n depends_on: [scan-metrics]\n context: fresh\n denied_tools: [Write, Edit, Bash]\n hooks:\n PostToolUse:\n - matcher: \"Read\"\n response:\n hookSpecificOutput:\n hookEventName: PostToolUse\n additionalContext: >\n For the file you just read, assess:\n (1) Single responsibility — does this module do exactly one thing?\n (2) Cognitive load — could a new team member understand this in 5 minutes?\n (3) Abstraction value — does every abstraction earn its complexity, or is it premature?\n (4) Dependency direction — does this file depend on things at its own level or below, not above?\n Add any concerns to your running list. Be specific — cite line ranges and function names.\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 3: PLAN\n # Prioritize and scope the changes — pure reasoning, no tools\n # ═══════════════════════════════════════════════════════════════\n\n - id: plan\n prompt: |\n You are planning targeted architectural improvements.\n\n ## Assessment\n\n $analyze.output\n\n ## Principles\n\n - KISS: prefer straightforward over clever\n - YAGNI: remove speculative abstractions\n - Rule of Three: only extract when a pattern appears 3+ times\n - Each change must be independently revertable\n - Do NOT mix refactoring with behavior changes\n - Scope to what can be done safely in one pass (max 5-7 files)\n\n ## Instructions\n\n 1. From the assessment, select the top 3-5 highest-impact, lowest-risk improvements\n 2. For each, write a precise plan: which file, what to change, why\n 3. Order them so each change is independent (no cascading dependencies between changes)\n 4. Estimate blast radius — how many other files are affected\n\n ## Output\n\n Write the plan as a numbered list. Be specific about exactly what code to change.\n Keep it concise — the implement node will follow this literally.\n depends_on: [analyze]\n allowed_tools: [Read]\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 4: EXECUTE\n # Make the changes with hooks creating quality feedback loops\n # ═══════════════════════════════════════════════════════════════\n\n - id: simplify\n prompt: |\n You are implementing targeted architectural simplifications.\n\n ## Plan\n\n $plan.output\n\n ## Rules\n\n - Follow the plan exactly — do not add extra improvements you notice along the way\n - Each change must preserve existing behavior (refactor only, no feature changes)\n - After each file edit, you'll be prompted to validate — follow those instructions\n - If a change turns out to be harder than expected, skip it and move on\n - Commit each logical change separately with a clear commit message\n\n ## Instructions\n\n 1. Work through the plan items in order\n 2. For each item: read the file, make the change, follow the post-edit checklist\n 3. After all changes, do a final `git diff --stat` to verify scope\n depends_on: [plan]\n context: fresh\n hooks:\n PreToolUse:\n - matcher: \"Write|Edit\"\n response:\n hookSpecificOutput:\n hookEventName: PreToolUse\n additionalContext: >\n Before writing: Is this file in your plan? If not, explain why you're\n touching it. Check how many files import from this module — changes to\n widely-imported modules need extra scrutiny.\n PostToolUse:\n - matcher: \"Write|Edit\"\n response:\n systemMessage: >\n You just modified a file. Do these things NOW before moving on:\n 1. Run the type checker to verify your change compiles\n 2. Re-read the file you changed — is it ACTUALLY simpler, or did you just move complexity around?\n 3. State in ONE sentence why this change reduces complexity. If you cannot justify it, revert it.\n - matcher: \"Read\"\n response:\n hookSpecificOutput:\n hookEventName: PostToolUse\n additionalContext: >\n Before modifying this file, consider: will your change reduce or increase\n the number of concepts a reader needs to hold in their head?\n - matcher: \"Bash\"\n response:\n hookSpecificOutput:\n hookEventName: PostToolUse\n additionalContext: >\n Check the exit code. If the command failed, diagnose the root cause\n before attempting a fix. Do not blindly retry.\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 5: VALIDATE\n # Run full validation suite — bash only, cannot edit to \"fix\" failures\n # ═══════════════════════════════════════════════════════════════\n\n - id: validate\n bash: |\n echo \"=== TYPE CHECK ===\"\n bun run type-check 2>&1\n TC_EXIT=$?\n\n echo \"\"\n echo \"=== LINT ===\"\n bun run lint 2>&1\n LINT_EXIT=$?\n\n echo \"\"\n echo \"=== TESTS ===\"\n bun run test 2>&1\n TEST_EXIT=$?\n\n echo \"\"\n echo \"=== RESULTS ===\"\n echo \"Type check: $([ $TC_EXIT -eq 0 ] && echo 'PASS' || echo 'FAIL')\"\n echo \"Lint: $([ $LINT_EXIT -eq 0 ] && echo 'PASS' || echo 'FAIL')\"\n echo \"Tests: $([ $TEST_EXIT -eq 0 ] && echo 'PASS' || echo 'FAIL')\"\n\n # Always exit 0 so downstream nodes can read output and decide\n if [ $TC_EXIT -eq 0 ] && [ $LINT_EXIT -eq 0 ] && [ $TEST_EXIT -eq 0 ]; then\n echo \"VALIDATION_STATUS: PASS\"\n else\n echo \"VALIDATION_STATUS: FAIL\"\n fi\n depends_on: [simplify]\n timeout: 300000\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 6: FIX VALIDATION FAILURES (if any)\n # Only runs if validate failed — focused fix with same quality hooks\n # ═══════════════════════════════════════════════════════════════\n\n - id: fix-failures\n prompt: |\n Review the validation output below.\n\n ## Validation Output\n\n $validate.output\n\n ## Instructions\n\n If the output ends with \"VALIDATION_STATUS: PASS\", respond with\n \"All checks passed — no fixes needed.\" and stop.\n\n If there are failures:\n\n 1. Read the validation failures carefully\n 2. Fix ONLY what's broken — do not make additional improvements\n 3. If a fix requires changing behavior (not just fixing a type/lint error),\n revert the original change instead\n 4. Run the specific failing check after each fix to confirm it passes\n 5. After all fixes, run the full validation suite: `bun run validate`\n depends_on: [validate]\n context: fresh\n hooks:\n PostToolUse:\n - matcher: \"Write|Edit\"\n response:\n systemMessage: >\n You just made a fix. Run the specific failing validation check NOW\n to verify your fix works. Do not batch fixes — verify each one.\n PreToolUse:\n - matcher: \"Write|Edit\"\n response:\n hookSpecificOutput:\n hookEventName: PreToolUse\n additionalContext: >\n You are fixing validation failures only. Do not make any changes\n beyond what's needed to pass the failing checks. If in doubt, revert\n the original change that caused the failure.\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 7: CREATE PR\n # Hooks ensure this node only does git operations\n # ═══════════════════════════════════════════════════════════════\n\n - id: create-pr\n prompt: |\n Create a pull request for the architectural improvements.\n\n ## Context\n\n - Architecture assessment: $analyze.output\n - Plan: $plan.output\n - Validation: $validate.output\n\n ## Instructions\n\n 1. Stage all changes and create a single commit (or verify existing commits)\n 2. Push the branch: `git push -u origin HEAD`\n 3. Check if a PR already exists: `gh pr list --head $(git branch --show-current)`\n 4. Create the PR with:\n - Title: concise description of what was simplified (under 70 chars)\n - Body: use the format below\n 5. Save the PR URL to `$ARTIFACTS_DIR/.pr-url`\n\n ## PR Body Format\n\n ```markdown\n ## Architectural Sweep\n\n **Focus**: $ARGUMENTS\n\n ### Assessment\n\n [3-5 sentence summary from the architecture assessment]\n\n ### Changes\n\n [For each change: what file, what was simplified, why]\n\n ### Validation\n\n - [x] Type check passes\n - [x] Lint passes\n - [x] Tests pass\n - [x] Each change preserves existing behavior\n ```\n depends_on: [fix-failures]\n context: fresh\n hooks:\n PreToolUse:\n - matcher: \"Write|Edit\"\n response:\n hookSpecificOutput:\n hookEventName: PreToolUse\n permissionDecision: deny\n permissionDecisionReason: \"PR creation node — do not modify source files. Use only git and gh commands.\"\n PostToolUse:\n - matcher: \"Bash\"\n response:\n hookSpecificOutput:\n hookEventName: PostToolUse\n additionalContext: >\n Verify this command succeeded. If git push or gh pr create failed,\n read the error message carefully before retrying.\n", + "archon-assist": "name: archon-assist\ndescription: |\n Use when: No other workflow matches the request.\n Handles: Questions, debugging, exploration, one-off tasks, explanations, CI failures, general help.\n Capability: Full Claude Code agent with all tools available.\n Note: Will inform user when assist mode is used for tracking.\n\nnodes:\n - id: assist\n command: archon-assist\n", + "archon-comprehensive-pr-review": "name: archon-comprehensive-pr-review\ndescription: |\n Use when: User wants a comprehensive code review of a pull request with automatic fixes.\n Triggers: \"review this PR\", \"review PR #123\", \"comprehensive review\", \"full PR review\",\n \"review and fix\", \"check this PR\", \"code review\".\n Does: Syncs PR with main (rebase if needed) -> runs 5 specialized review agents in parallel ->\n synthesizes findings -> auto-fixes CRITICAL/HIGH issues -> reports remaining issues.\n NOT for: Quick questions about a PR, checking CI status, simple \"what changed\" queries.\n\n This workflow produces artifacts in $ARTIFACTS_DIR/../reviews/pr-{number}/ and posts\n a comprehensive review comment to the GitHub PR.\n\nnodes:\n - id: scope\n command: archon-pr-review-scope\n\n - id: sync\n command: archon-sync-pr-with-main\n depends_on: [scope]\n\n - id: code-review\n command: archon-code-review-agent\n depends_on: [sync]\n\n - id: error-handling\n command: archon-error-handling-agent\n depends_on: [sync]\n\n - id: test-coverage\n command: archon-test-coverage-agent\n depends_on: [sync]\n\n - id: comment-quality\n command: archon-comment-quality-agent\n depends_on: [sync]\n\n - id: docs-impact\n command: archon-docs-impact-agent\n depends_on: [sync]\n\n - id: synthesize\n command: archon-synthesize-review\n depends_on: [code-review, error-handling, test-coverage, comment-quality, docs-impact]\n trigger_rule: one_success\n\n - id: implement-fixes\n command: archon-implement-review-fixes\n depends_on: [synthesize]\n", + "archon-create-issue": "name: archon-create-issue\ndescription: |\n Use when: User wants to report a bug or problem as a GitHub issue with automated reproduction.\n Triggers: \"create issue\", \"file a bug\", \"report this bug\", \"open an issue for\",\n \"create github issue\", \"report issue\", \"log this bug\".\n Does: Classifies problem area (haiku) -> gathers context in parallel (templates, git state, duplicates) ->\n investigates relevant code -> reproduces the issue using area-specific tools (agent-browser, CLI, DB queries) ->\n gates on reproduction success -> creates issue with full evidence OR reports back if cannot reproduce.\n NOT for: Feature requests, enhancements, or non-bug work. Only for bugs/problems.\n\n Reproduction gating: If the issue cannot be reproduced, the workflow does NOT create an issue.\n Instead, it reports what was tried and suggests next steps to the user.\n\nnodes:\n # ═══════════════════════════════════════════════════════════════\n # PHASE 1: CLASSIFY — Haiku classification of user's problem\n # ═══════════════════════════════════════════════════════════════\n\n - id: classify\n prompt: |\n You are a problem classifier for the Archon codebase. Analyze the user's\n description and determine the issue type and which area of the system is affected.\n\n ## User's Description\n $ARGUMENTS\n\n ## Area Definitions\n | Area | Packages | Indicators |\n |------|----------|------------|\n | web-ui | @archon/web, @archon/server (routes, web adapter) | UI rendering, SSE streaming, React components, browser behavior |\n | api-server | @archon/server (routes, middleware) | HTTP endpoints, response codes, request handling |\n | cli | @archon/cli | CLI commands, workflow invocation from terminal, output formatting |\n | isolation | @archon/isolation, @archon/git | Worktrees, branch operations, cleanup, environment lifecycle |\n | workflows | @archon/workflows | YAML parsing, DAG execution, variable substitution, node types |\n | database | @archon/core (db/) | SQLite/PostgreSQL queries, schema, data integrity, migrations |\n | adapters | @archon/adapters | Slack/Telegram/GitHub/Discord message handling, auth, polling |\n | core | @archon/core (orchestrator, handlers, clients) | Message routing, session management, AI client streaming |\n | other | Any package not covered above | Cross-cutting concerns, build tooling, config, unknown area |\n\n ## Classification Rules\n - Choose the MOST SPECIFIC area. \"SSE disconnects\" = web-ui (not api-server).\n - If ambiguous between two areas, pick the one closer to the user-facing symptom.\n - Use \"other\" only when the problem genuinely doesn't fit any specific area.\n - needs_server: Set to \"true\" if reproducing requires a running Archon server.\n Typically true for: web-ui, api-server, core, adapters.\n Typically false for: cli, isolation, workflows, database.\n For \"other\": use your judgment based on the description.\n - repro_hint: Extract the user's reproduction steps into a concise instruction.\n If no explicit steps given, infer the most likely way to trigger the issue.\n\n Provide reasoning for your classification.\n model: haiku\n allowed_tools: []\n output_format:\n type: object\n properties:\n type:\n type: string\n enum: [\"bug\", \"regression\", \"crash\", \"performance\", \"configuration\"]\n area:\n type: string\n enum: [\"web-ui\", \"api-server\", \"cli\", \"isolation\", \"workflows\", \"database\", \"adapters\", \"core\", \"other\"]\n title:\n type: string\n keywords:\n type: string\n repro_hint:\n type: string\n needs_server:\n type: string\n enum: [\"true\", \"false\"]\n required: [type, area, title, keywords, repro_hint, needs_server]\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 2: PARALLEL CONTEXT GATHERING\n # ═══════════════════════════════════════════════════════════════\n\n - id: fetch-template\n bash: |\n # Search for GitHub issue templates in standard locations\n TEMPLATES_FOUND=0\n\n # Check for issue template directory (YAML-based templates)\n if [ -d \".github/ISSUE_TEMPLATE\" ]; then\n echo \"=== Issue Templates Found ===\"\n for f in .github/ISSUE_TEMPLATE/*.md .github/ISSUE_TEMPLATE/*.yaml .github/ISSUE_TEMPLATE/*.yml; do\n if [ -f \"$f\" ]; then\n TEMPLATES_FOUND=$((TEMPLATES_FOUND + 1))\n echo \"--- Template: $f ---\"\n cat \"$f\"\n echo \"\"\n fi\n done\n fi\n\n # Check for single issue template\n for f in .github/ISSUE_TEMPLATE.md docs/ISSUE_TEMPLATE.md; do\n if [ -f \"$f\" ]; then\n TEMPLATES_FOUND=$((TEMPLATES_FOUND + 1))\n echo \"--- Template: $f ---\"\n cat \"$f\"\n fi\n done\n\n if [ \"$TEMPLATES_FOUND\" -eq 0 ]; then\n echo \"No issue templates found — will use standard format\"\n fi\n depends_on: [classify]\n\n - id: git-context\n bash: |\n echo \"=== Branch ===\"\n git branch --show-current\n\n echo \"=== Recent Commits (last 15) ===\"\n git log --oneline -15\n\n echo \"=== Working Tree Status ===\"\n git status --short\n\n echo \"=== Modified Files (last 3 commits) ===\"\n git diff --name-only HEAD~3..HEAD 2>/dev/null || echo \"(fewer than 3 commits)\"\n\n echo \"=== Environment ===\"\n echo \"Node: $(node --version 2>/dev/null || echo 'N/A')\"\n echo \"Bun: $(bun --version 2>/dev/null || echo 'N/A')\"\n echo \"OS: $(uname -s 2>/dev/null || echo 'Windows') $(uname -r 2>/dev/null || ver 2>/dev/null || echo '')\"\n echo \"Platform: $(uname -m 2>/dev/null || echo 'unknown')\"\n depends_on: [classify]\n\n - id: dedup-check\n bash: |\n KEYWORDS=$classify.output.keywords\n echo \"=== Searching for duplicates: $KEYWORDS ===\"\n\n echo \"--- Open Issues ---\"\n gh issue list --search \"$KEYWORDS\" --state open --limit 5 --json number,title,url,labels 2>/dev/null || echo \"No open matches\"\n\n echo \"--- Recently Closed ---\"\n gh issue list --search \"$KEYWORDS\" --state closed --limit 3 --json number,title,url,labels 2>/dev/null || echo \"No closed matches\"\n depends_on: [classify]\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 3: INVESTIGATE — Search codebase for related code\n # ═══════════════════════════════════════════════════════════════\n\n - id: investigate\n prompt: |\n You are a codebase investigator. Search for code related to the reported problem.\n\n ## Problem\n - **Area**: $classify.output.area\n - **Type**: $classify.output.type\n - **Title**: $classify.output.title\n - **Reproduction hint**: $classify.output.repro_hint\n\n ## Git Context\n $git-context.output\n\n ## Instructions\n\n 1. Based on the area, search the relevant packages:\n - web-ui: `packages/web/src/`, `packages/server/src/adapters/web/`, `packages/server/src/routes/`\n - api-server: `packages/server/src/routes/`, `packages/server/src/`\n - cli: `packages/cli/src/`\n - isolation: `packages/isolation/src/`, `packages/git/src/`\n - workflows: `packages/workflows/src/`\n - database: `packages/core/src/db/`\n - adapters: `packages/adapters/src/`\n - core: `packages/core/src/orchestrator/`, `packages/core/src/handlers/`\n - other: search broadly based on keywords — check `packages/*/src/`, config files, build scripts\n\n 2. Find: entry points, error handling paths, related type definitions, recent changes\n to the affected area (check git log for the specific files).\n\n 3. Write your findings to `$ARTIFACTS_DIR/issue-context.md` with this structure:\n ```\n # Codebase Investigation\n ## Relevant Files\n - `file:line` — description of what's there\n ## Error Handling\n - How errors are currently handled in this area\n ## Recent Changes\n - Any recent commits touching this code\n ## Suspected Root Cause\n - Based on code analysis, where the bug likely is\n ```\n\n Be thorough but focused. Only include files directly relevant to the reported problem.\n depends_on: [classify, git-context]\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 4: REPRODUCE — Area-specific issue reproduction\n # ═══════════════════════════════════════════════════════════════\n\n - id: start-server\n bash: |\n # Allocate a free port using Bun's OS assignment\n PORT=$(bun -e \"const s = Bun.serve({port: 0, fetch: () => new Response('')}); console.log(s.port); s.stop()\")\n echo \"$PORT\" > \"$ARTIFACTS_DIR/.server-port\"\n\n # Start dev server in background\n PORT=$PORT bun run dev:server > \"$ARTIFACTS_DIR/.server-log\" 2>&1 &\n SERVER_PID=$!\n echo \"$SERVER_PID\" > \"$ARTIFACTS_DIR/.server-pid\"\n\n # Wait for server to be ready (up to 30s)\n for i in $(seq 1 30); do\n if curl -s \"http://localhost:$PORT/api/health\" > /dev/null 2>&1; then\n echo \"Server ready on port $PORT (PID: $SERVER_PID)\"\n exit 0\n fi\n sleep 1\n done\n\n echo \"WARNING: Server may not be fully ready after 30s (port $PORT, PID $SERVER_PID)\"\n echo \"Continuing anyway — reproduce node will handle connection errors\"\n depends_on: [classify]\n when: \"$classify.output.needs_server == 'true'\"\n timeout: 45000\n\n - id: reproduce\n prompt: |\n You are an issue reproduction specialist. Your job is to reproduce the reported\n problem and capture evidence (screenshots, command output, error messages).\n\n ## Problem Context\n - **Area**: $classify.output.area\n - **Type**: $classify.output.type\n - **Title**: $classify.output.title\n - **Reproduction hint**: $classify.output.repro_hint\n\n ## Investigation Findings\n $investigate.output\n\n ## Server Info\n If a server was started, read the port from: `cat \"$ARTIFACTS_DIR/.server-port\"`\n If the file doesn't exist, no server is running (area doesn't need one).\n\n ---\n\n ## Reproduction Playbooks\n\n Follow the playbook matching the area. Capture ALL evidence to `$ARTIFACTS_DIR/`.\n\n ### web-ui\n 1. Read the server port: `PORT=$(cat \"$ARTIFACTS_DIR/.server-port\" | tr -d '\\n')`\n 2. Open the app: `agent-browser open http://localhost:$PORT`\n 3. Take a baseline screenshot: `agent-browser screenshot \"$ARTIFACTS_DIR/repro-01-baseline.png\"`\n 4. Get interactive elements: `agent-browser snapshot -i`\n 5. Navigate to the area related to the issue (use @refs from snapshot)\n 6. Perform the actions described in the repro_hint\n 7. Screenshot each significant state: `agent-browser screenshot \"$ARTIFACTS_DIR/repro-02-action.png\"`\n 8. If an error appears, capture it: `agent-browser get text @errorElement`\n 9. Check browser console: `agent-browser console`\n 10. Check for JS errors: `agent-browser errors`\n 11. Final screenshot: `agent-browser screenshot \"$ARTIFACTS_DIR/repro-03-result.png\"`\n 12. Close browser: `agent-browser close`\n\n ### api-server\n 1. Read the server port: `PORT=$(cat \"$ARTIFACTS_DIR/.server-port\" | tr -d '\\n')`\n 2. Create a test conversation: `curl -s -X POST http://localhost:$PORT/api/conversations -H \"Content-Type: application/json\" -d '{}'`\n 3. Hit the problematic endpoint based on the repro_hint\n 4. Capture response codes and bodies: `curl -s -w \"\\nHTTP_CODE: %{http_code}\\n\" ...`\n 5. For SSE issues: `curl -s -N http://localhost:$PORT/api/stream/` (timeout after 10s)\n 6. Check server logs: `cat \"$ARTIFACTS_DIR/.server-log\" | tail -50`\n 7. Save all curl output to `$ARTIFACTS_DIR/repro-api-responses.txt`\n\n ### cli\n 1. Run the CLI command that should trigger the issue\n 2. Capture stdout and stderr separately:\n `bun run cli > \"$ARTIFACTS_DIR/repro-cli-stdout.txt\" 2> \"$ARTIFACTS_DIR/repro-cli-stderr.txt\"; echo \"EXIT_CODE: $?\" >> \"$ARTIFACTS_DIR/repro-cli-stdout.txt\"`\n 3. If workflow-related: `bun run cli workflow list --json > \"$ARTIFACTS_DIR/repro-workflow-list.json\" 2>&1`\n 4. If the command hangs, use timeout: `timeout 30 bun run cli `\n 5. Check for error messages in output\n\n ### isolation\n 1. Check current state: `bun run cli isolation list > \"$ARTIFACTS_DIR/repro-isolation-list.txt\" 2>&1`\n 2. Check git worktrees: `git worktree list > \"$ARTIFACTS_DIR/repro-worktree-list.txt\"`\n 3. Check branches: `git branch -a > \"$ARTIFACTS_DIR/repro-branches.txt\"`\n 4. Try the operation that should fail (based on repro_hint)\n 5. Capture the error output\n 6. Query isolation DB: `sqlite3 ~/.archon/archon.db \"SELECT * FROM remote_agent_isolation_environments ORDER BY created_at DESC LIMIT 10\" > \"$ARTIFACTS_DIR/repro-isolation-db.txt\" 2>&1`\n\n ### workflows\n 1. List workflows: `bun run cli workflow list --json > \"$ARTIFACTS_DIR/repro-workflow-list.json\" 2>&1`\n 2. If a specific workflow is mentioned, try running it:\n `bun run cli workflow run --no-worktree \"test input\" > \"$ARTIFACTS_DIR/repro-workflow-run.txt\" 2>&1`\n 3. If YAML parsing is the issue, try loading the definition directly\n 4. Check for error messages in execution output\n\n ### database\n 1. Check DB exists: `ls -la ~/.archon/archon.db 2>/dev/null`\n 2. Run targeted queries against affected tables:\n - `sqlite3 ~/.archon/archon.db \".schema \" > \"$ARTIFACTS_DIR/repro-db-schema.txt\"`\n - `sqlite3 ~/.archon/archon.db \"SELECT COUNT(*) FROM
\" > \"$ARTIFACTS_DIR/repro-db-counts.txt\"`\n 3. Check for the specific data condition described in the repro_hint\n 4. If PostgreSQL: use `psql $DATABASE_URL -c \"...\"` instead\n\n ### adapters\n 1. Read the server port: `PORT=$(cat \"$ARTIFACTS_DIR/.server-port\" | tr -d '\\n')`\n 2. Check adapter configuration: look for relevant env vars in `.env`\n 3. Check server startup logs: `cat \"$ARTIFACTS_DIR/.server-log\" | grep -i \"adapter\\|slack\\|telegram\\|github\\|discord\" | head -20`\n 4. If the adapter fails to initialize, capture the error\n 5. Test message routing via web API as a proxy:\n `curl -s -X POST http://localhost:$PORT/api/conversations//message -H \"Content-Type: application/json\" -d '{\"message\":\"/status\"}'`\n\n ### core\n 1. Read the server port: `PORT=$(cat \"$ARTIFACTS_DIR/.server-port\" | tr -d '\\n')`\n 2. Create a conversation: `curl -s -X POST http://localhost:$PORT/api/conversations -H \"Content-Type: application/json\" -d '{}'`\n 3. Send a message that triggers the issue:\n `curl -s -X POST http://localhost:$PORT/api/conversations//message -H \"Content-Type: application/json\" -d '{\"message\":\"\"}'`\n 4. Poll for responses: `curl -s http://localhost:$PORT/api/conversations//messages`\n 5. Check session state in DB: `sqlite3 ~/.archon/archon.db \"SELECT * FROM remote_agent_sessions WHERE conversation_id=''\" 2>/dev/null`\n 6. Check server logs: `cat \"$ARTIFACTS_DIR/.server-log\" | tail -50`\n\n ### other\n 1. Run `bun run validate` to check for any obvious failures — capture output:\n `bun run validate > \"$ARTIFACTS_DIR/repro-validate.txt\" 2>&1; echo \"EXIT_CODE: $?\" >> \"$ARTIFACTS_DIR/repro-validate.txt\"`\n 2. Search the codebase for keywords from the repro_hint:\n - Use Grep/Glob to find related files\n - Check recent git log for relevant changes\n 3. If the description implies a build or config issue:\n - Check `package.json` scripts, `tsconfig.json`, `.env.example`\n - Try running the relevant build/dev command\n 4. If the description implies a runtime issue:\n - Start the server (if `.server-port` file exists) and try to trigger the behavior\n - Check logs for errors\n 5. Document everything you tried, even if nothing reproduces clearly\n\n ---\n\n ## Output\n\n After following the playbook, write your findings to `$ARTIFACTS_DIR/reproduction-results.md`:\n\n ```markdown\n # Reproduction Results\n\n ## Status: [REPRODUCED | NOT_REPRODUCED | PARTIAL]\n\n ## Steps Taken\n 1. [step]\n 2. [step]\n\n ## Expected Behavior\n [what should happen]\n\n ## Actual Behavior\n [what actually happened — or \"could not trigger the reported behavior\"]\n\n ## Evidence Files\n - `$ARTIFACTS_DIR/repro-*.png` — screenshots (if web-ui)\n - `$ARTIFACTS_DIR/repro-*.txt` — command output\n - `$ARTIFACTS_DIR/repro-*.json` — structured data\n\n ## Environment\n [OS, versions, relevant config]\n\n ## Notes\n [any additional observations, suspected root cause refinements]\n ```\n\n CRITICAL: The Status line MUST be exactly one of: REPRODUCED, NOT_REPRODUCED, PARTIAL.\n This value is read by a downstream bash node to decide whether to create the issue.\n\n Even if you cannot fully reproduce the issue, document what you tried\n and what you observed. Partial reproduction is still valuable evidence.\n depends_on: [classify, git-context, investigate, start-server]\n context: fresh\n skills:\n - agent-browser\n trigger_rule: one_success\n idle_timeout: 300000\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 5: CLEANUP + GATE\n # ═══════════════════════════════════════════════════════════════\n\n - id: cleanup-server\n bash: |\n SERVER_PID=$(cat \"$ARTIFACTS_DIR/.server-pid\" 2>/dev/null | tr -d '\\n')\n SERVER_PORT=$(cat \"$ARTIFACTS_DIR/.server-port\" 2>/dev/null | tr -d '\\n')\n\n if [ -z \"$SERVER_PID\" ]; then\n echo \"No server was started — skipping cleanup\"\n exit 0\n fi\n\n echo \"Cleaning up server PID $SERVER_PID on port $SERVER_PORT...\"\n\n # Kill by PID (cross-platform)\n kill \"$SERVER_PID\" 2>/dev/null || taskkill //F //T //PID \"$SERVER_PID\" 2>/dev/null || true\n\n # Kill by port (fallback)\n if [ -n \"$SERVER_PORT\" ]; then\n fuser -k \"$SERVER_PORT/tcp\" 2>/dev/null || true\n lsof -ti:\"$SERVER_PORT\" 2>/dev/null | xargs kill -9 2>/dev/null || true\n netstat -ano 2>/dev/null | grep \":$SERVER_PORT \" | grep LISTENING | awk '{print $5}' | sort -u | while read pid; do\n taskkill //F //T //PID \"$pid\" 2>/dev/null || true\n done\n fi\n\n # Close any agent-browser session\n agent-browser close 2>/dev/null || true\n\n sleep 1\n echo \"Cleanup complete\"\n depends_on: [reproduce]\n trigger_rule: all_done\n\n - id: check-reproduction\n bash: |\n # Read the reproduction status from the results file\n if [ ! -f \"$ARTIFACTS_DIR/reproduction-results.md\" ]; then\n echo \"NOT_REPRODUCED\"\n exit 0\n fi\n\n STATUS=$(grep -oE '(NOT_REPRODUCED|REPRODUCED|PARTIAL)' \"$ARTIFACTS_DIR/reproduction-results.md\" | head -1)\n\n if [ -z \"$STATUS\" ]; then\n echo \"NOT_REPRODUCED\"\n else\n echo \"$STATUS\"\n fi\n depends_on: [cleanup-server]\n trigger_rule: all_done\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 6: BRANCH ON REPRODUCTION RESULT\n # ═══════════════════════════════════════════════════════════════\n\n - id: report-failure\n prompt: |\n The issue could not be reproduced. Report this to the user with actionable detail.\n\n ## Problem Description\n - **Title**: $classify.output.title\n - **Area**: $classify.output.area\n - **Type**: $classify.output.type\n - **Reproduction hint**: $classify.output.repro_hint\n\n ## What Was Tried\n $reproduce.output\n\n ## Investigation Findings\n $investigate.output\n\n ## Instructions\n\n Report to the user clearly:\n\n 1. **State upfront**: \"Could not reproduce the reported issue. No GitHub issue was created.\"\n\n 2. **Summarize what was tried**: List the specific steps the reproduce node took,\n based on the area playbook. Be concrete — \"Started server on port X, navigated to Y,\n clicked Z — no error appeared.\"\n\n 3. **Share what was found**: Include relevant findings from the investigation\n (code references, recent changes, suspected areas).\n\n 4. **Suggest next steps**:\n - Ask the user to provide more specific reproduction steps\n - Mention any environment-specific factors that might matter\n (OS, browser, database state, specific data conditions)\n - If the investigation found suspicious code, mention it as a lead\n - Suggest running with debug logging: `LOG_LEVEL=debug bun run dev`\n\n 5. **Offer to retry**: \"If you can provide more specific steps, run the workflow\n again with those details.\"\n\n Do NOT create a GitHub issue. The purpose of this node is to communicate back to the\n user so they can provide better information or investigate manually.\n depends_on: [check-reproduction]\n when: \"$check-reproduction.output == 'NOT_REPRODUCED'\"\n context: fresh\n\n - id: draft-issue\n prompt: |\n You are a technical writer drafting a GitHub issue. Assemble all gathered\n context into a clear, well-structured issue body.\n\n ## Classification\n - **Type**: $classify.output.type\n - **Area**: $classify.output.area\n - **Title**: $classify.output.title\n\n ## Issue Template\n If templates were found, use the most appropriate one as the structure:\n $fetch-template.output\n\n ## Duplicate Check Results\n $dedup-check.output\n\n ## Codebase Investigation\n $investigate.output\n\n ## Reproduction Results\n $reproduce.output\n\n ## Instructions\n\n 1. **Check duplicates first**: If the dedup-check found a clearly matching open issue,\n note this prominently at the top. Still draft the issue but add a note suggesting\n it may be a duplicate of #XYZ.\n\n 2. **Use the template** if one was found for bug reports. Fill every section with real data.\n\n 3. **Structure** (if no template):\n ```markdown\n ## Description\n [Clear 1-2 sentence description]\n\n ## Steps to Reproduce\n [Numbered steps from reproduction results]\n\n ## Expected Behavior\n [What should happen]\n\n ## Actual Behavior\n [What actually happened, with evidence]\n\n ## Environment\n - OS: [from git-context]\n - Bun: [version]\n - Node: [version]\n - Branch: [current branch]\n\n ## Relevant Code\n [Key file:line references from investigation]\n\n ## Additional Context\n [Screenshots, logs, database state — reference artifact files]\n ```\n\n 4. **Include reproduction evidence**:\n - If REPRODUCED: include full steps and all evidence\n - If PARTIAL: include what was observed, note incomplete reproduction\n\n 5. **Suggest labels** based on classification:\n - Area label: `area: web`, `area: cli`, `area: workflows`, etc.\n - Type label: `bug`, `regression`, `performance`, etc.\n\n 6. Write the complete issue body to `$ARTIFACTS_DIR/issue-draft.md`\n\n 7. Write a one-line suggested title to `$ARTIFACTS_DIR/.issue-title`\n\n 8. Write suggested labels (comma-separated) to `$ARTIFACTS_DIR/.issue-labels`\n depends_on: [check-reproduction, fetch-template, dedup-check, investigate]\n when: \"$check-reproduction.output != 'NOT_REPRODUCED'\"\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 7: CREATE ISSUE\n # ═══════════════════════════════════════════════════════════════\n\n - id: create-issue\n prompt: |\n Create the GitHub issue using the drafted content.\n\n ## Instructions\n\n 1. Read the draft: `cat \"$ARTIFACTS_DIR/issue-draft.md\"`\n 2. Read the title: `cat \"$ARTIFACTS_DIR/.issue-title\"`\n 3. Read suggested labels: `cat \"$ARTIFACTS_DIR/.issue-labels\"`\n\n 4. Check which labels actually exist in the repo:\n ```bash\n gh label list --json name -q '.[].name' | head -50\n ```\n Only use labels that exist. Skip any suggested label that doesn't match.\n\n 5. Create the issue:\n ```bash\n gh issue create \\\n --title \"$(cat \"$ARTIFACTS_DIR/.issue-title\")\" \\\n --body-file \"$ARTIFACTS_DIR/issue-draft.md\" \\\n --label \"label1,label2\"\n ```\n\n 6. Capture the result:\n ```bash\n ISSUE_URL=$(gh issue list --limit 1 --json url -q '.[0].url')\n echo \"$ISSUE_URL\" > \"$ARTIFACTS_DIR/.issue-url\"\n ```\n\n 7. Report to the user:\n - Issue URL\n - Title\n - Labels applied\n - Whether duplicates were found\n - Summary of reproduction results (reproduced/partial)\n depends_on: [draft-issue]\n context: fresh\n", + "archon-feature-development": "name: archon-feature-development\ndescription: |\n Use when: Implementing a feature from an existing plan.\n Input: Path to a plan file ($ARTIFACTS_DIR/plan.md) or GitHub issue containing a plan.\n Does: Implements the plan with validation loops -> creates pull request.\n NOT for: Creating plans (plans should be created separately), bug fixes, code reviews.\n\nnodes:\n - id: implement\n command: archon-implement\n model: claude-opus-4-6[1m]\n\n - id: create-pr\n command: archon-create-pr\n depends_on: [implement]\n context: fresh\n", + "archon-fix-github-issue": "name: archon-fix-github-issue\ndescription: |\n Use when: User wants to FIX, RESOLVE, or IMPLEMENT a solution for a GitHub issue.\n Triggers: \"fix this issue\", \"implement issue #123\", \"resolve this bug\", \"fix it\",\n \"fix issue\", \"resolve issue\", \"fix #123\".\n NOT for: Comprehensive multi-agent reviews (use archon-issue-review-full),\n questions about issues, CI failures, PR reviews, general exploration.\n\n DAG workflow that:\n 1. Classifies the issue (bug/feature/enhancement/etc)\n 2. Researches context (web research + codebase exploration via investigate/plan)\n 3. Routes to investigate (bugs) or plan (features) based on classification\n 4. Implements the fix/feature with validation\n 5. Creates a draft PR using the repo's PR template\n 6. Runs smart review (always code review + CLAUDE.md check, conditional additional agents)\n 7. Aggressively self-fixes all findings (tests, docs, error handling)\n 8. Simplifies changed code (implements fixes directly, not just reports)\n 9. Reports results back to the GitHub issue with follow-up suggestions\n\nprovider: claude\nmodel: sonnet\n\nnodes:\n # ═══════════════════════════════════════════════════════════════\n # PHASE 1: FETCH & CLASSIFY\n # ═══════════════════════════════════════════════════════════════\n\n - id: extract-issue-number\n prompt: |\n Find the GitHub issue number for this request.\n\n Request: $ARGUMENTS\n\n Rules:\n - If the message contains an explicit issue number (e.g., \"#709\", \"issue 709\", \"709\"), extract that number.\n - If the message is ambiguous (e.g., \"fix the SQLite timestamp bug\"), use `gh issue list` to search for matching issues and pick the best match.\n\n CRITICAL: Your final output must be ONLY the bare number with no quotes, no markdown, no explanation. Example correct output: 709\n\n - id: fetch-issue\n bash: |\n # Strip quotes, whitespace, markdown backticks from AI output\n ISSUE_NUM=$(echo \"$extract-issue-number.output\" | tr -d \"'\\\"\\`\\n \" | grep -oE '[0-9]+' | head -1)\n if [ -z \"$ISSUE_NUM\" ]; then\n echo \"Failed to extract issue number from: $extract-issue-number.output\" >&2\n exit 1\n fi\n gh issue view \"$ISSUE_NUM\" --json title,body,labels,comments,state,url,author\n depends_on: [extract-issue-number]\n\n - id: classify\n prompt: |\n You are an issue classifier. Analyze the GitHub issue below and determine its type.\n\n ## Issue Content\n\n $fetch-issue.output\n\n ## Classification Rules\n\n | Type | Indicators |\n |------|------------|\n | bug | \"broken\", \"error\", \"crash\", \"doesn't work\", stack traces, regression |\n | feature | \"add\", \"new\", \"support\", \"would be nice\", net-new capability |\n | enhancement | \"improve\", \"better\", \"update existing\", \"extend\", incremental improvement |\n | refactor | \"clean up\", \"simplify\", \"reorganize\", \"restructure\" |\n | chore | \"update deps\", \"upgrade\", \"maintenance\", \"CI/CD\" |\n | documentation | \"docs\", \"readme\", \"clarify\", \"examples\" |\n\n Provide reasoning for your classification.\n depends_on: [fetch-issue]\n model: haiku\n allowed_tools: []\n output_format:\n type: object\n properties:\n issue_type:\n type: string\n enum: [\"bug\", \"feature\", \"enhancement\", \"refactor\", \"chore\", \"documentation\"]\n title:\n type: string\n reasoning:\n type: string\n required: [issue_type, title, reasoning]\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 2: RESEARCH (parallel with PR template fetch)\n # ═══════════════════════════════════════════════════════════════\n\n - id: web-research\n command: archon-web-research\n depends_on: [classify]\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 3: INVESTIGATE (bugs) / PLAN (features)\n # ═══════════════════════════════════════════════════════════════\n\n - id: investigate\n command: archon-investigate-issue\n depends_on: [classify, web-research]\n when: \"$classify.output.issue_type == 'bug'\"\n context: fresh\n\n - id: plan\n command: archon-create-plan\n depends_on: [classify, web-research]\n when: \"$classify.output.issue_type != 'bug'\"\n context: fresh\n\n # Bridge: ensure investigation.md exists for the implement step\n # archon-fix-issue reads from $ARTIFACTS_DIR/investigation.md\n # archon-create-plan writes to $ARTIFACTS_DIR/plan.md\n # This node copies plan.md → investigation.md when the plan path was taken\n - id: bridge-artifacts\n bash: |\n if [ -f \"$ARTIFACTS_DIR/plan.md\" ] && [ ! -f \"$ARTIFACTS_DIR/investigation.md\" ]; then\n cp \"$ARTIFACTS_DIR/plan.md\" \"$ARTIFACTS_DIR/investigation.md\"\n echo \"Bridged plan.md to investigation.md for implement step\"\n elif [ -f \"$ARTIFACTS_DIR/investigation.md\" ]; then\n echo \"investigation.md exists from investigate step\"\n else\n echo \"WARNING: No investigation.md or plan.md found — implement may fail\"\n fi\n depends_on: [investigate, plan]\n trigger_rule: one_success\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 4: IMPLEMENT\n # ═══════════════════════════════════════════════════════════════\n\n - id: implement\n command: archon-fix-issue\n depends_on: [bridge-artifacts]\n context: fresh\n model: claude-opus-4-6[1m]\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 5: VALIDATE\n # ═══════════════════════════════════════════════════════════════\n\n - id: validate\n command: archon-validate\n depends_on: [implement]\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 6: CREATE DRAFT PR\n # ═══════════════════════════════════════════════════════════════\n\n - id: create-pr\n prompt: |\n Create a draft pull request for the current branch.\n\n ## Context\n\n - **Issue**: $ARGUMENTS\n - **Classification**: $classify.output\n - **Issue title**: $classify.output.title\n\n ## Instructions\n\n 1. Check git status — ensure all changes are committed. If uncommitted changes exist, stage and commit them.\n 2. Push the branch: `git push -u origin HEAD`\n 3. Read implementation artifacts from `$ARTIFACTS_DIR/` for context:\n - `$ARTIFACTS_DIR/investigation.md` or `$ARTIFACTS_DIR/plan.md`\n - `$ARTIFACTS_DIR/implementation.md`\n - `$ARTIFACTS_DIR/validation.md`\n 4. Check if a PR already exists for this branch: `gh pr list --head $(git branch --show-current)`\n - If PR exists, skip creation and capture its number\n 5. Look for the project's PR template at `.github/pull_request_template.md`, `.github/PULL_REQUEST_TEMPLATE.md`, or `docs/PULL_REQUEST_TEMPLATE.md`. Read whichever one exists.\n 6. Create a DRAFT PR: `gh pr create --draft --base $BASE_BRANCH`\n - Title: concise, imperative mood, under 70 chars\n - Body: if a PR template was found, fill in **every section** with details from the artifacts. Don't skip sections or leave placeholders. If no template, write a body with summary, changes, validation evidence, and `Fixes #...`.\n - Link to issue: include `Fixes #...` or `Closes #...`\n 7. Capture PR identifiers:\n ```bash\n PR_NUMBER=$(gh pr view --json number -q '.number')\n echo \"$PR_NUMBER\" > \"$ARTIFACTS_DIR/.pr-number\"\n PR_URL=$(gh pr view --json url -q '.url')\n echo \"$PR_URL\" > \"$ARTIFACTS_DIR/.pr-url\"\n ```\n depends_on: [validate]\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 7: REVIEW\n # ═══════════════════════════════════════════════════════════════\n\n - id: review-scope\n command: archon-pr-review-scope\n depends_on: [create-pr]\n context: fresh\n\n - id: review-classify\n prompt: |\n You are a PR review classifier. Analyze the PR scope and determine\n which review agents should run.\n\n ## PR Scope\n\n $review-scope.output\n\n ## Rules\n\n - **Code review**: ALWAYS run. This is mandatory for every PR. It also checks\n the PR against CLAUDE.md rules and project conventions.\n - **Error handling**: Run if the diff touches code with try/catch, error handling,\n async/await, or adds new failure paths.\n - **Test coverage**: Run if the diff touches source code (not just tests, docs, or config).\n - **Comment quality**: Run if the diff adds or modifies comments, docstrings, JSDoc,\n or significant documentation within code files.\n - **Docs impact**: Run if the diff adds/removes/renames public APIs, commands, CLI flags,\n environment variables, or user-facing features.\n\n Provide your reasoning for each decision.\n depends_on: [review-scope]\n model: haiku\n allowed_tools: []\n context: fresh\n output_format:\n type: object\n properties:\n run_code_review:\n type: string\n enum: [\"true\", \"false\"]\n run_error_handling:\n type: string\n enum: [\"true\", \"false\"]\n run_test_coverage:\n type: string\n enum: [\"true\", \"false\"]\n run_comment_quality:\n type: string\n enum: [\"true\", \"false\"]\n run_docs_impact:\n type: string\n enum: [\"true\", \"false\"]\n reasoning:\n type: string\n required:\n - run_code_review\n - run_error_handling\n - run_test_coverage\n - run_comment_quality\n - run_docs_impact\n - reasoning\n\n # Code review always runs — mandatory\n - id: code-review\n command: archon-code-review-agent\n depends_on: [review-classify]\n context: fresh\n\n - id: error-handling\n command: archon-error-handling-agent\n depends_on: [review-classify]\n when: \"$review-classify.output.run_error_handling == 'true'\"\n context: fresh\n\n - id: test-coverage\n command: archon-test-coverage-agent\n depends_on: [review-classify]\n when: \"$review-classify.output.run_test_coverage == 'true'\"\n context: fresh\n\n - id: comment-quality\n command: archon-comment-quality-agent\n depends_on: [review-classify]\n when: \"$review-classify.output.run_comment_quality == 'true'\"\n context: fresh\n\n - id: docs-impact\n command: archon-docs-impact-agent\n depends_on: [review-classify]\n when: \"$review-classify.output.run_docs_impact == 'true'\"\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 8: SYNTHESIZE + SELF-FIX\n # ═══════════════════════════════════════════════════════════════\n\n - id: synthesize\n command: archon-synthesize-review\n depends_on: [code-review, error-handling, test-coverage, comment-quality, docs-impact]\n trigger_rule: one_success\n context: fresh\n\n - id: self-fix\n command: archon-self-fix-all\n depends_on: [synthesize]\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 9: SIMPLIFY\n # ═══════════════════════════════════════════════════════════════\n\n - id: simplify\n command: archon-simplify-changes\n depends_on: [self-fix]\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 10: REPORT\n # ═══════════════════════════════════════════════════════════════\n\n - id: report\n command: archon-issue-completion-report\n depends_on: [simplify]\n context: fresh\n", + "archon-idea-to-pr": "name: archon-idea-to-pr\ndescription: |\n Use when: You have a feature idea or description and want end-to-end development.\n Input: Feature description in natural language, or path to a PRD file\n Output: PR ready for merge with comprehensive review completed\n\n Full workflow:\n 1. Create comprehensive implementation plan with codebase analysis\n 2. Setup branch and extract scope limits\n 3. Verify plan research is still valid\n 4. Implement all tasks with type-checking\n 5. Run full validation suite\n 6. Create PR with template, mark ready\n 7. Comprehensive code review (5 parallel agents with scope limit awareness)\n 8. Synthesize and fix review findings\n 9. Final summary with decision matrix -> GitHub comment + follow-up recommendations\n\n NOT for: Executing existing plans (use archon-plan-to-pr), quick fixes, standalone reviews.\n\nnodes:\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 0: CREATE PLAN\n # ═══════════════════════════════════════════════════════════════════\n\n - id: create-plan\n command: archon-create-plan\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 1: SETUP\n # ═══════════════════════════════════════════════════════════════════\n\n - id: plan-setup\n command: archon-plan-setup\n depends_on: [create-plan]\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 2: CONFIRM PLAN\n # ═══════════════════════════════════════════════════════════════════\n\n - id: confirm-plan\n command: archon-confirm-plan\n depends_on: [plan-setup]\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 3: IMPLEMENT\n # ═══════════════════════════════════════════════════════════════════\n\n - id: implement-tasks\n command: archon-implement-tasks\n depends_on: [confirm-plan]\n context: fresh\n model: claude-opus-4-6[1m]\n\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 4: VALIDATE\n # ═══════════════════════════════════════════════════════════════════\n\n - id: validate\n command: archon-validate\n depends_on: [implement-tasks]\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 5: FINALIZE PR\n # ═══════════════════════════════════════════════════════════════════\n\n - id: finalize-pr\n command: archon-finalize-pr\n depends_on: [validate]\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 6: CODE REVIEW\n # ═══════════════════════════════════════════════════════════════════\n\n - id: review-scope\n command: archon-pr-review-scope\n depends_on: [finalize-pr]\n context: fresh\n\n - id: sync\n command: archon-sync-pr-with-main\n depends_on: [review-scope]\n context: fresh\n\n - id: code-review\n command: archon-code-review-agent\n depends_on: [sync]\n context: fresh\n\n - id: error-handling\n command: archon-error-handling-agent\n depends_on: [sync]\n context: fresh\n\n - id: test-coverage\n command: archon-test-coverage-agent\n depends_on: [sync]\n context: fresh\n\n - id: comment-quality\n command: archon-comment-quality-agent\n depends_on: [sync]\n context: fresh\n\n - id: docs-impact\n command: archon-docs-impact-agent\n depends_on: [sync]\n context: fresh\n\n - id: synthesize\n command: archon-synthesize-review\n depends_on: [code-review, error-handling, test-coverage, comment-quality, docs-impact]\n trigger_rule: one_success\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 7: FIX REVIEW ISSUES\n # ═══════════════════════════════════════════════════════════════════\n\n - id: implement-fixes\n command: archon-implement-review-fixes\n depends_on: [synthesize]\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 8: FINAL SUMMARY & FOLLOW-UP\n # ═══════════════════════════════════════════════════════════════════\n\n - id: workflow-summary\n command: archon-workflow-summary\n depends_on: [implement-fixes]\n context: fresh\n", + "archon-interactive-prd": "name: archon-interactive-prd\ndescription: |\n Use when: User wants to create a PRD through guided conversation.\n Triggers: \"create a prd\", \"new prd\", \"interactive prd\", \"plan a feature\",\n \"product requirements\", \"write a prd\".\n NOT for: Autonomous PRD generation without human input (use archon-ralph-generate).\n\n Interactive workflow that guides the user through problem-first PRD creation:\n 1. Understand the idea → ask foundation questions → wait for answers\n 2. Research market & codebase → ask deep dive questions → wait for answers\n 3. Assess technical feasibility → ask scope questions → wait for answers\n 4. Generate PRD → validate technical claims against codebase → output\n\nprovider: claude\ninteractive: true\n\nnodes:\n # ═══════════════════════════════════════════════════════════════\n # PHASE 1: INITIATE — Understand the idea\n # ═══════════════════════════════════════════════════════════════\n\n - id: initiate\n model: sonnet\n prompt: |\n You are a sharp product manager starting a PRD creation process.\n You think from first principles — start with primitives, not features.\n\n The user wants to build: $ARGUMENTS\n\n If the input is clear, restate your understanding in 2-3 sentences and confirm:\n \"I understand you want to build: {restated understanding}. Is this correct?\"\n\n If the input is vague or empty, ask:\n \"What do you want to build? Describe the product, feature, or capability.\"\n\n Then present the Foundation Questions (all at once — the user will answer in the next step):\n\n **Foundation Questions:**\n\n 1. **Who** has this problem? Be specific — not just \"users\" but what type of person/role?\n 2. **What** problem are they facing? Describe the observable pain, not the assumed need.\n 3. **Why** can't they solve it today? What alternatives exist and why do they fail?\n 4. **Why now?** What changed that makes this worth building?\n 5. **How** will you know if you solved it? What would success look like?\n\n Keep it conversational. Don't generate any PRD content yet.\n\n # ═══════════════════════════════════════════════════════════════\n # GATE 1: User answers foundation questions\n # ═══════════════════════════════════════════════════════════════\n\n - id: foundation-gate\n approval:\n message: \"Answer the foundation questions above. Your answers will guide the research phase.\"\n capture_response: true\n depends_on: [initiate]\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 2: GROUNDING — Research market & codebase\n # ═══════════════════════════════════════════════════════════════\n\n - id: research\n model: sonnet\n prompt: |\n You are researching context for a PRD. Think from first principles —\n what already exists before proposing anything new.\n\n **The idea**: $ARGUMENTS\n\n **User's foundation answers**:\n $foundation-gate.output\n\n Research the landscape:\n\n 1. Search the web for similar products, competitors, and how others solve this problem\n 2. **Explore the codebase deeply** — find related existing functionality, APIs, UI components,\n database tables, and patterns. Read actual files, don't assume. Note exact file paths and\n what each file does.\n 3. Look for common patterns, anti-patterns, and recent trends\n\n **First principles rule**: Before suggesting anything new, verify what already exists.\n If there's an existing API endpoint, UI page, or component that partially solves the\n problem, note it explicitly. The best solution extends what exists, not replaces it.\n\n Present a summary to the user:\n\n **What I found:**\n - {Market insights — similar products, competitor approaches}\n - {What already exists in the codebase — specific files, endpoints, components}\n - {Key insight that might change the approach}\n\n Then ask the **Deep Dive Questions**:\n\n 1. **Vision**: In one sentence, what's the ideal end state if this succeeds wildly?\n 2. **Primary User**: Describe your most important user — their role, context, and what triggers their need.\n 3. **Job to Be Done**: Complete this: \"When [situation], I want to [motivation], so I can [outcome].\"\n 4. **Non-Users**: Who is explicitly NOT the target?\n 5. **Constraints**: What limitations exist? (time, budget, technical, regulatory)\n\n Does the research change or refine your thinking? Answer the deep dive questions.\n depends_on: [foundation-gate]\n\n # ═══════════════════════════════════════════════════════════════\n # GATE 2: User answers deep dive questions\n # ═══════════════════════════════════════════════════════════════\n\n - id: deepdive-gate\n approval:\n message: \"Answer the deep dive questions above (vision, primary user, JTBD, constraints). Add any adjustments from the research.\"\n capture_response: true\n depends_on: [research]\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 3: TECHNICAL GROUNDING — Feasibility from what exists\n # ═══════════════════════════════════════════════════════════════\n\n - id: technical\n model: sonnet\n prompt: |\n You are assessing technical feasibility for a PRD.\n Think from first principles — start with what exists, not what you'd build from scratch.\n\n **The idea**: $ARGUMENTS\n **Foundation answers**: $foundation-gate.output\n **Deep dive answers**: $deepdive-gate.output\n\n **CRITICAL**: Explore the codebase by READING actual files. Do not guess or assume.\n For every claim you make about the codebase, cite the exact file and line.\n\n 1. **What already exists** that partially solves this problem?\n - Read existing API endpoints, DB queries, UI components\n - Note exact function names, table schemas, component names\n - What data is already being collected/stored?\n 2. **What's the smallest change** to the existing system that solves the core problem?\n - Prefer extending existing files over creating new ones\n - Prefer using existing endpoints over creating new ones\n - Prefer adding to existing UI pages over new pages\n 3. **What are the actual primitives** we need?\n - A new DB query? An existing one that needs a parameter?\n - A new component? Or an existing component that needs a prop?\n - A new endpoint? Or an existing endpoint that already returns the data?\n 4. **What's the risk?**\n - Where could this go wrong?\n - What assumptions need validation?\n\n Present a summary:\n\n **What Already Exists (verified by reading code):**\n - {endpoint/component/query} at `{file:line}` — {what it does}\n - {endpoint/component/query} at `{file:line}` — {what it does}\n\n **Smallest Change to Solve the Problem:**\n - {change 1}: {extend/modify} `{file}` — {what to do}\n - {change 2}: {extend/modify} `{file}` — {what to do}\n\n **Technical Context:**\n - Feasibility: {HIGH/MEDIUM/LOW} because {reason}\n - Key risk: {main concern}\n - Estimated phases: {rough breakdown}\n\n Then ask the **Scope Questions**:\n\n 1. **MVP Definition**: What's the absolute minimum to test if this works?\n 2. **Must Have vs Nice to Have**: What 2-3 things MUST be in v1? What can wait?\n 3. **Key Hypothesis**: Complete this: \"We believe [capability] will [solve problem] for [users]. We'll know we're right when [measurable outcome].\"\n 4. **Out of Scope**: What are you explicitly NOT building?\n 5. **Open Questions**: What uncertainties could change the approach?\n depends_on: [deepdive-gate]\n\n # ═══════════════════════════════════════════════════════════════\n # GATE 3: User answers scope questions\n # ═══════════════════════════════════════════════════════════════\n\n - id: scope-gate\n approval:\n message: \"Answer the scope questions above (MVP, must-haves, hypothesis, exclusions). This is the final input before PRD generation.\"\n capture_response: true\n depends_on: [technical]\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 4: GENERATE — Write the PRD\n # ═══════════════════════════════════════════════════════════════\n\n - id: generate\n model: sonnet\n prompt: |\n You are generating a PRD from the user's guided inputs.\n\n **The idea**: $ARGUMENTS\n **Foundation answers**: $foundation-gate.output\n **Deep dive answers**: $deepdive-gate.output\n **Scope answers**: $scope-gate.output\n\n Generate a complete PRD file at `$ARTIFACTS_DIR/prds/{kebab-case-name}.prd.md`.\n\n First create the directory:\n ```bash\n mkdir -p $ARTIFACTS_DIR/prds\n ```\n\n **First principles rule**: Before writing the Technical Approach section, READ the\n actual codebase files you're referencing. Verify:\n - File paths exist\n - Function/component names are correct\n - API endpoints you reference actually exist (or note they need to be created)\n - DB table and column names match the schema\n - Event type names match the constants in the code\n\n The PRD must include ALL of these sections, filled from the user's answers:\n\n 1. **Problem Statement** — from foundation answers (who/what/why)\n 2. **Evidence** — from research findings and user's evidence\n 3. **Proposed Solution** — synthesized from all inputs. Prefer extending existing\n primitives over creating new ones.\n 4. **Key Hypothesis** — from scope answers\n 5. **What We're NOT Building** — from scope answers\n 6. **Success Metrics** — from foundation \"how will you know\" + scope\n 7. **Open Questions** — from scope answers\n 8. **Users & Context** — from deep dive (primary user, JTBD, non-users)\n 9. **Solution Detail** — MoSCoW table from scope must-haves, MVP definition\n 10. **Technical Approach** — from technical feasibility. MUST reference actual\n verified file paths, function names, and schemas. Mark anything unverified\n as \"needs verification\".\n 11. **Implementation Phases** — from technical breakdown, with status table\n and parallel opportunities\n 12. **Decisions Log** — key decisions made during the conversation\n\n **Rules:**\n - If info is missing, write \"TBD — needs research\" not filler\n - Be specific and concrete, not generic\n - Every file path in Technical Approach must be verified by reading the file\n - Prefer \"extend X\" over \"create new Y\" in implementation phases\n\n After writing the file, output the file path only — the validator will check it.\n depends_on: [scope-gate]\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 5: VALIDATE — Check technical claims against codebase\n # ═══════════════════════════════════════════════════════════════\n\n - id: validate\n model: sonnet\n prompt: |\n You are a technical validator checking a PRD for accuracy.\n\n Read the PRD file that was just generated. The generate node output the file path:\n $generate.output\n\n Find the PRD file — check `$ARTIFACTS_DIR/prds/` for the most recently created `.prd.md` file:\n ```bash\n ls -t $ARTIFACTS_DIR/prds/*.prd.md | head -1\n ```\n\n Read the entire PRD, then verify EVERY technical claim against the actual codebase:\n\n **Check 1: File paths** — For every file referenced in \"Technical Approach\" and\n \"Implementation Phases\", verify it exists. If it doesn't, note the correction.\n\n **Check 2: API endpoints** — For every endpoint mentioned, check if it already exists\n in `packages/server/src/routes/api.ts`. If it does, the PRD should say \"extend\" not \"create\".\n If the PRD proposes a new endpoint for data that an existing endpoint already returns,\n flag it.\n\n **Check 3: DB schemas** — For every table/column referenced, verify the actual names\n in the migration files or schema code. Check event type names against the\n `WORKFLOW_EVENT_TYPES` constant.\n\n **Check 4: UI components** — For every component referenced, verify it exists.\n If the PRD proposes a new page but an existing page already serves a similar purpose,\n flag it.\n\n **Check 5: Function/type names** — Verify function names, type names, and interface\n names are correct.\n\n After checking, if there are ANY corrections needed:\n 1. Edit the PRD file directly — fix incorrect names, paths, and references\n 2. Add a `## Validation Notes` section at the bottom documenting what was corrected\n\n If everything checks out, add:\n ```\n ## Validation Notes\n\n All technical references verified against codebase. No corrections needed.\n ```\n\n Output a summary of what was checked and corrected:\n\n ```\n ## PRD Validated\n\n **File**: `{prd-path}`\n **Checks**: {N} file paths, {N} endpoints, {N} DB references, {N} components\n **Corrections**: {count}\n {list corrections if any}\n\n To start implementation: `/prp-plan {prd-path}`\n ```\n depends_on: [generate]\n", + "archon-issue-review-full": "name: archon-issue-review-full\ndescription: |\n Use when: User wants a FULL, COMPREHENSIVE fix + review pipeline for a GitHub issue.\n Triggers: \"full review\", \"comprehensive fix\", \"fix with full review\", \"deep review\", \"issue review full\".\n NOT for: Simple issue fixes (use archon-fix-github-issue instead),\n questions about issues, CI failures, PR reviews, general exploration.\n\n Full workflow:\n 1. Investigate issue -> root cause analysis, implementation plan\n 2. Implement fix -> code changes, tests, PR creation\n 3. Comprehensive review -> 5 parallel agents with scope awareness\n 4. Fix review issues -> address CRITICAL/HIGH findings\n 5. Final summary -> decision matrix, follow-up recommendations\n\nnodes:\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 1: INVESTIGATE\n # ═══════════════════════════════════════════════════════════════════\n\n - id: investigate\n command: archon-investigate-issue\n\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 2: IMPLEMENT\n # ═══════════════════════════════════════════════════════════════════\n\n - id: implement\n command: archon-implement-issue\n depends_on: [investigate]\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 3: CODE REVIEW\n # ═══════════════════════════════════════════════════════════════════\n\n - id: review-scope\n command: archon-pr-review-scope\n depends_on: [implement]\n context: fresh\n\n - id: sync\n command: archon-sync-pr-with-main\n depends_on: [review-scope]\n context: fresh\n\n - id: code-review\n command: archon-code-review-agent\n depends_on: [sync]\n context: fresh\n\n - id: error-handling\n command: archon-error-handling-agent\n depends_on: [sync]\n context: fresh\n\n - id: test-coverage\n command: archon-test-coverage-agent\n depends_on: [sync]\n context: fresh\n\n - id: comment-quality\n command: archon-comment-quality-agent\n depends_on: [sync]\n context: fresh\n\n - id: docs-impact\n command: archon-docs-impact-agent\n depends_on: [sync]\n context: fresh\n\n - id: synthesize\n command: archon-synthesize-review\n depends_on: [code-review, error-handling, test-coverage, comment-quality, docs-impact]\n trigger_rule: one_success\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 4: FIX REVIEW ISSUES\n # ═══════════════════════════════════════════════════════════════════\n\n - id: implement-fixes\n command: archon-implement-review-fixes\n depends_on: [synthesize]\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 5: FINAL SUMMARY\n # ═══════════════════════════════════════════════════════════════════\n\n - id: summary\n command: archon-workflow-summary\n depends_on: [implement-fixes]\n context: fresh\n", + "archon-piv-loop": "name: archon-piv-loop\ndescription: |\n Use when: User wants guided Plan-Implement-Validate development with human-in-the-loop.\n Triggers: \"piv\", \"piv loop\", \"plan implement validate\", \"guided development\",\n \"structured development\", \"build a feature\", \"develop with review\".\n NOT for: Autonomous implementation without planning (use archon-feature-development).\n NOT for: PRD creation (use archon-interactive-prd).\n NOT for: Ralph story-based implementation (use archon-ralph-dag).\n\n Interactive PIV loop workflow — the foundational AI coding methodology:\n 1. EXPLORE: Iterative conversation with human to understand the problem (arbitrary rounds)\n 2. PLAN: Create structured plan -> iterative review & revision (arbitrary rounds)\n 3. IMPLEMENT: Autonomous task-by-task implementation from plan (Ralph loop)\n 4. VALIDATE: Automated code review -> iterative human feedback & fixes (arbitrary rounds)\n\n The PIV loop comes AFTER a PRD exists. Each PIV loop focuses on ONE granular feature or bug fix.\n Input: A description of what to build, a path to an existing plan, or a GitHub issue number.\n\nprovider: claude\ninteractive: true\n\nnodes:\n # ═══════════════════════════════════════════════════════════════\n # PHASE 1: EXPLORE — Iterative exploration with human\n # Understand the idea, explore the codebase, converge on approach\n # Loops until the user says they're ready to create the plan.\n # ═══════════════════════════════════════════════════════════════\n\n - id: explore\n loop:\n prompt: |\n # PIV Loop — Exploration\n\n You are a senior engineering partner in an iterative exploration session.\n Your goal: DEEPLY UNDERSTAND what to build before any code is written.\n\n **User's request**: $ARGUMENTS\n **User's latest input**: $LOOP_USER_INPUT\n\n ---\n\n ## If this is the FIRST iteration (no user input yet):\n\n ### Step 1: Parse the Input\n\n Determine what the user provided:\n\n **If it's a file path** (ends in `.md`, `.plan.md`, or `.prd.md`):\n - Read the file\n - If it's an existing plan → summarize it and ask if they want to refine or proceed\n - If it's a PRD → identify the specific phase/feature to focus on\n\n **If it's a GitHub issue** (`#123` format):\n - Fetch it: `gh issue view {number} --json title,body,labels,comments`\n - Summarize the issue context\n\n **If it's free text**:\n - This is a feature idea or bug description. Use it directly.\n\n ### Step 2: Explore the Codebase\n\n Before asking questions, DO YOUR HOMEWORK:\n\n 1. **Read CLAUDE.md** — understand project conventions, architecture, and constraints\n 2. **Search for related code** — find existing implementations similar to what the user wants\n 3. **Read key files** — understand the current state of code the user wants to change\n 4. **Check recent git history** — `git log --oneline -20` for recent changes in the area\n\n ### Step 3: Present Your Understanding\n\n ```\n ## What I Understand\n\n You want to: {restated understanding in 2-3 sentences}\n\n ## What Already Exists\n\n - {file:line} — {what it does and how it relates}\n - {file:line} — {what it does and how it relates}\n - {pattern/component} — {how it could be extended or reused}\n\n ## Initial Architecture Thoughts\n\n Based on what exists, I'm thinking:\n - {approach 1 — extend existing X}\n - {approach 2 — if approach 1 doesn't work}\n - {key architectural decision that needs your input}\n ```\n\n ### Step 4: Ask Targeted Questions\n\n Ask 4-6 questions focused on DECISIONS, not information gathering:\n - Scope boundaries, architecture preferences, tech decisions\n - Constraints, existing code extension vs fresh build, testing expectations\n - Reference actual code you found — don't ask generic questions\n\n ---\n\n ## If the user has provided input (subsequent iterations):\n\n ### Step 1: Process Their Response\n\n Read their answers carefully. Identify:\n - Decisions they've made\n - Areas they want you to explore further\n - Questions they asked YOU back (answer these with evidence!)\n\n ### Step 2: Do Targeted Research\n\n Based on their response:\n - If they mentioned specific technologies → research best practices\n - If they pointed you to specific code → read it thoroughly\n - If they asked you to explore an area → do a thorough investigation\n - If they made architecture decisions → validate against the codebase\n\n ### Step 3: Present Updated Understanding\n\n Show what you learned, answer their questions with file:line references,\n and present your refined architecture recommendation.\n\n ### Step 4: Converge or Continue\n\n **If there are still important open questions:**\n Ask 2-4 focused questions about remaining ambiguities.\n\n **If the picture is clear and you have enough to create a plan:**\n Present a final implementation summary:\n\n ```\n ## Implementation Summary\n\n ### What We're Building\n {Clear, specific description}\n\n ### Scope Boundary\n - IN: {what's included}\n - OUT: {what's explicitly excluded}\n\n ### Architecture\n - {key decisions}\n\n ### Files That Will Change\n - `{file}` — {what changes and why}\n\n ### Success Criteria\n - [ ] {specific, testable criterion}\n - [ ] All validation passes\n\n ### Key Risks\n - {risk — and mitigation}\n ```\n\n Then tell the user: \"I have a clear picture. Say **ready** and I'll create\n the structured implementation plan, or share any final thoughts.\"\n\n **CRITICAL — READ THIS CAREFULLY**:\n - NEVER output PLAN_READY unless the user's LATEST message contains\n an EXPLICIT phrase like \"ready\", \"create the plan\", \"let's go\", \"proceed\", or \"I'm done\".\n - If the user asked a question → do NOT emit the signal. Answer the question.\n - If the user gave feedback or requested changes → do NOT emit the signal. Address it.\n - If the user said \"also check X\" or \"one more thing\" → do NOT emit the signal. Explore it.\n - If you are unsure whether the user is approving → do NOT emit the signal. Ask them.\n - The ONLY correct time to emit the signal is when the user's message CLEARLY means\n \"stop exploring, I'm ready for you to create the plan.\"\n until: PLAN_READY\n max_iterations: 15\n interactive: true\n gate_message: |\n Answer the questions above, ask me to explore specific areas,\n or say \"ready\" when you're satisfied with the exploration.\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 2: PLAN — Create the structured implementation plan\n # ═══════════════════════════════════════════════════════════════\n\n - id: create-plan\n model: sonnet\n depends_on: [explore]\n context: fresh\n prompt: |\n # PIV Loop — Create Structured Plan\n\n You are creating a structured implementation plan from a completed exploration phase.\n This plan will be the SOLE GUIDE for the implementation agent — it must be complete,\n specific, and actionable.\n\n **Original request**: $ARGUMENTS\n **Final exploration summary**: $explore.output\n\n ---\n\n ## Step 1: Read the Codebase (Again)\n\n Before writing the plan, verify your understanding is current:\n\n 1. **Read CLAUDE.md** — capture all relevant conventions\n 2. **Read every file you plan to change** — note exact current state\n 3. **Read example test files** — understand testing patterns\n 4. **Check for any recent changes** — `git log --oneline -10`\n\n ## Step 2: Determine Plan Location\n\n Generate a kebab-case slug from the feature name.\n Save to `.claude/archon/plans/{slug}.plan.md`.\n\n ```bash\n mkdir -p .claude/archon/plans\n ```\n\n ## Step 3: Write the Plan\n\n Use this template. Fill EVERY section with specific, verified information.\n\n ```markdown\n # Feature: {Title}\n\n ## Summary\n {1-2 sentences: what changes and why}\n\n ## Mission\n {The core goal in one clear statement}\n\n ## Success Criteria\n - [ ] {Specific, testable criterion}\n - [ ] All validation passes (`bun run validate` or equivalent)\n - [ ] No regressions in existing tests\n\n ## Scope\n ### In Scope\n - {What we ARE building}\n ### Out of Scope\n - {What we are NOT building — and why}\n\n ## Codebase Context\n ### Key Files\n | File | Role | Action |\n |------|------|--------|\n | `{path}` | {what it does} | CREATE / UPDATE |\n\n ### Patterns to Follow\n {Actual code snippets from the codebase to mirror}\n\n ## Architecture\n - {Decision 1 — with rationale}\n - {Decision 2 — with rationale}\n\n ## Task List\n Execute in order. Each task is atomic and independently verifiable.\n\n ### Task 1: {ACTION} `{file path}`\n **Action**: CREATE / UPDATE\n **Details**: {Exact changes — specific enough for an agent with no context}\n **Pattern**: Follow `{source file}:{lines}`\n **Validate**: `{command to verify this task}`\n\n ## Testing Strategy\n | Test File | Test Cases | Validates |\n |-----------|-----------|-----------|\n | `{path}` | {cases} | {what it validates} |\n\n ## Validation Commands\n 1. Type check: `{command}`\n 2. Lint: `{command}`\n 3. Tests: `{command}`\n 4. Full validation: `{command}`\n\n ## Risks\n | Risk | Impact | Mitigation |\n |------|--------|------------|\n | {risk} | {HIGH/MED/LOW} | {specific mitigation} |\n ```\n\n ## Step 4: Verify the Plan\n\n 1. Check every file path referenced — verify they exist\n 2. Check every pattern cited — verify the code matches\n 3. Check task ordering — ensure dependencies are respected\n 4. Check completeness — could an agent with NO context implement this?\n\n ## Step 5: Report\n\n ```\n ## Plan Created\n\n **File**: `.claude/archon/plans/{slug}.plan.md`\n **Tasks**: {count}\n **Files to change**: {count}\n\n Key decisions:\n - {decision 1}\n - {decision 2}\n\n Please review the plan and provide feedback.\n ```\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 2b: PLAN — Iterative plan refinement\n # Review and revise the plan as many times as needed.\n # ═══════════════════════════════════════════════════════════════\n\n - id: refine-plan\n depends_on: [create-plan]\n loop:\n prompt: |\n # PIV Loop — Plan Refinement\n\n The user is reviewing the implementation plan and providing feedback.\n\n **User's feedback**: $LOOP_USER_INPUT\n\n ---\n\n ## Step 1: Find and Read the Plan\n\n ```bash\n ls -t .claude/archon/plans/*.plan.md 2>/dev/null | head -1\n ```\n\n Read the entire plan file. Also read CLAUDE.md for conventions.\n\n ## Step 2: Process Feedback\n\n **If there is no user feedback yet** (first iteration, $LOOP_USER_INPUT is empty):\n - Read the plan carefully\n - Present a summary of the plan's key decisions and task list\n - Ask the user to review and provide feedback\n - Do NOT emit the completion signal on the first iteration\n\n **If the user EXPLICITLY approved** (said \"approved\", \"looks good\", \"let's go\", etc.):\n - Make no changes\n - Output: \"Plan approved. Proceeding to implementation.\"\n - Signal completion: PLAN_APPROVED\n\n **If the user provided specific feedback:**\n - Parse each piece of feedback\n - Edit the plan file directly:\n - Add/remove/modify tasks as requested\n - Update success criteria if needed\n - Adjust testing strategy if needed\n - Re-verify file paths and patterns after changes\n\n **CRITICAL**: NEVER emit PLAN_APPROVED unless the user's latest\n message EXPLICITLY says \"approved\", \"looks good\", \"ship it\", or similar approval.\n Questions, feedback, and requests for changes are NOT approval.\n\n ## Step 3: Show Changes\n\n ```\n ## Plan Revised\n\n Changes made:\n - {change 1}\n - {change 2}\n\n Updated stats:\n - Tasks: {count}\n - Files to change: {count}\n\n Review the updated plan and provide more feedback, or say \"approved\" to proceed.\n ```\n until: PLAN_APPROVED\n max_iterations: 10\n interactive: true\n gate_message: |\n Review the plan document. Provide specific feedback on what to change,\n or say \"approved\" to begin implementation.\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 3: IMPLEMENT — Setup\n # Read the plan, prepare the environment\n # ═══════════════════════════════════════════════════════════════\n\n - id: implement-setup\n depends_on: [refine-plan]\n bash: |\n set -e\n\n PLAN_FILE=$(ls -t .claude/archon/plans/*.plan.md 2>/dev/null | head -1)\n\n if [ -z \"$PLAN_FILE\" ]; then\n echo \"ERROR: No plan file found in .claude/archon/plans/\"\n exit 1\n fi\n\n # Install dependencies if needed\n if [ -f \"bun.lock\" ] || [ -f \"bun.lockb\" ]; then\n echo \"Installing dependencies...\"\n bun install --frozen-lockfile 2>&1 | tail -3\n elif [ -f \"package-lock.json\" ]; then\n npm ci 2>&1 | tail -3\n elif [ -f \"yarn.lock\" ]; then\n yarn install --frozen-lockfile 2>&1 | tail -3\n elif [ -f \"pnpm-lock.yaml\" ]; then\n pnpm install --frozen-lockfile 2>&1 | tail -3\n fi\n\n echo \"BRANCH=$(git branch --show-current)\"\n echo \"GIT_ROOT=$(git rev-parse --show-toplevel)\"\n echo \"PLAN_FILE=$PLAN_FILE\"\n\n echo \"=== PLAN_START ===\"\n cat \"$PLAN_FILE\"\n echo \"\"\n echo \"=== PLAN_END ===\"\n\n TASK_COUNT=$(grep -c \"^### Task [0-9]\" \"$PLAN_FILE\" || true)\n echo \"TASK_COUNT=${TASK_COUNT:-0}\"\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 3b: IMPLEMENT — Task-by-Task Loop (Ralph pattern)\n # Fresh context each iteration. Reads plan from disk.\n # One task per iteration. Validates before committing.\n # ═══════════════════════════════════════════════════════════════\n\n - id: implement\n depends_on: [implement-setup]\n idle_timeout: 600000\n model: claude-opus-4-6[1m]\n loop:\n prompt: |\n # PIV Loop — Implementation Agent\n\n You are an autonomous coding agent in a FRESH session — no memory of previous iterations.\n Your job: Read the plan from disk, implement ONE task, validate, commit, update tracking, exit.\n\n **Golden Rule**: If validation fails, fix it before committing. Never commit broken code.\n\n ---\n\n ## Phase 0: CONTEXT — Load State\n\n The setup node produced this context:\n\n $implement-setup.output\n\n **User's original request**: $USER_MESSAGE\n\n ---\n\n ### 0.1 Parse Plan File\n\n Extract the `PLAN_FILE=...` line from the context above.\n\n ### 0.2 Read Current State (from disk — not from context above)\n\n The context above is a snapshot from before the loop started. Previous iterations\n may have changed things. **You MUST re-read from disk:**\n\n 1. **Read the plan file** — your implementation guide\n 2. **Read progress tracking** — check if `.claude/archon/plans/progress.txt` exists\n 3. **Read CLAUDE.md** — project conventions and constraints\n\n ### 0.3 Check Git State\n\n ```bash\n git log --oneline -10\n git status\n ```\n\n ---\n\n ## Phase 1: SELECT — Pick Next Task\n\n From the plan file, identify tasks by `### Task N:` headers.\n Cross-reference with commits from previous iterations and progress tracking.\n\n **If ALL tasks are complete** → Skip to Phase 5 (Completion).\n\n ### Announce Selection\n\n ```\n -- Task Selected ------------------------------------------------\n Task: {N} — {task title}\n Action: {CREATE / UPDATE}\n File: {file path}\n -----------------------------------------------------------------\n ```\n\n ---\n\n ## Phase 2: IMPLEMENT — Execute the Task\n\n 1. Read the file you're about to change (if it exists)\n 2. Read the pattern file referenced in the plan\n 3. Make changes following the plan EXACTLY\n 4. Type-check after each file: `bun run type-check 2>&1 || true`\n\n ---\n\n ## Phase 3: VALIDATE — Verify the Task\n\n ```bash\n bun run type-check && bun run lint && bun run test && bun run format:check\n ```\n\n If validation fails: fix, re-run (up to 3 attempts). If unfixable, note in progress\n tracking and do NOT commit broken code.\n\n ---\n\n ## Phase 4: COMMIT — Save Changes\n\n ```bash\n git add -A\n git diff --cached --stat\n git commit -m \"$(cat <<'EOF'\n {type}: {task description}\n\n PIV Task {N}: {brief details}\n EOF\n )\"\n ```\n\n Track progress in `.claude/archon/plans/progress.txt`:\n ```\n ## Task {N}: {title} — COMPLETED\n Date: {ISO date}\n Files: {list}\n Commit: {short hash}\n ---\n ```\n\n ---\n\n ## Phase 5: COMPLETE — Check All Tasks\n\n If ALL tasks are done:\n 1. Run full validation: `bun run validate 2>&1`\n 2. Push: `git push -u origin HEAD`\n 3. Signal: `COMPLETE`\n\n If tasks remain, report status and end normally. The loop engine starts a fresh iteration.\n until: COMPLETE\n max_iterations: 15\n fresh_context: true\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 4: VALIDATE — Automated code review\n # Review all changes against the plan\n # ═══════════════════════════════════════════════════════════════\n\n - id: code-review\n model: sonnet\n depends_on: [implement]\n context: fresh\n prompt: |\n # PIV Loop — Automated Code Review\n\n The implementation phase is complete. Review ALL changes against the plan.\n\n **Implementation output**: $implement.output\n\n ---\n\n ## Step 1: Find and Read the Plan\n\n ```bash\n ls -t .claude/archon/plans/*.plan.md 2>/dev/null | head -1\n ```\n\n ## Step 2: Review All Changes\n\n ```bash\n git log --oneline --no-merges $(git merge-base HEAD $BASE_BRANCH)..HEAD\n git diff $BASE_BRANCH..HEAD --stat\n git diff $BASE_BRANCH..HEAD\n ```\n\n ## Step 3: Check Against Plan\n\n For EACH task: was it implemented correctly? Do success criteria hold?\n For EACH file: check quality, security, patterns, CLAUDE.md compliance.\n\n ## Step 4: Run Validation\n\n ```bash\n bun run validate 2>&1 || (bun run type-check && bun run lint && bun run test && bun run format:check)\n ```\n\n ## Step 5: Fix Obvious Issues\n\n Fix type errors, lint warnings, missing imports, formatting. Commit any fixes:\n ```bash\n git add -A && git commit -m \"fix: address code review findings\" 2>/dev/null || true\n ```\n\n ## Step 6: Present Review\n\n ```\n ## Code Review Complete\n\n ### Implementation Status\n | Task | Status | Notes |\n |------|--------|-------|\n | {task} | DONE / PARTIAL / MISSING | {notes} |\n\n ### Validation Results\n - Type-check: PASS / FAIL\n - Lint: PASS / FAIL\n - Tests: PASS / FAIL\n - Format: PASS / FAIL\n\n ### Code Quality Findings\n {Issues found, or \"No issues found.\"}\n\n ### Recommendation\n {READY FOR REVIEW / NEEDS FIXES}\n ```\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 4b: VALIDATE — Iterative human feedback & fixes\n # The user tests the implementation and provides feedback.\n # Loops until the user approves.\n # ═══════════════════════════════════════════════════════════════\n\n - id: fix-feedback\n depends_on: [code-review]\n loop:\n prompt: |\n # PIV Loop — Address Validation Feedback\n\n The human has reviewed the implementation and provided feedback.\n\n **Human's feedback**: $LOOP_USER_INPUT\n\n ---\n\n ## Step 1: Read Context\n\n ```bash\n ls -t .claude/archon/plans/*.plan.md 2>/dev/null | head -1\n ```\n\n Read the plan file and CLAUDE.md for conventions.\n\n ## Step 2: Process Feedback\n\n **If there is no user feedback yet** (first iteration, $LOOP_USER_INPUT is empty):\n - Present the code review results and ask the user to test the implementation\n - Do NOT emit the completion signal on the first iteration\n\n **If the user EXPLICITLY approved** (said \"approved\", \"looks good\", \"ship it\", etc.):\n - Output: \"Implementation approved!\"\n - Signal: VALIDATED\n\n **CRITICAL**: NEVER emit VALIDATED unless the user's latest\n message EXPLICITLY says \"approved\", \"looks good\", \"ship it\", or similar approval.\n\n **If the user provided specific feedback:**\n 1. Read the relevant files\n 2. Understand each issue\n 3. Make the fixes\n 4. Type-check after each change\n\n ## Step 3: Full Validation\n\n ```bash\n bun run validate 2>&1 || (bun run type-check && bun run lint && bun run test && bun run format:check)\n ```\n\n ## Step 4: Commit Fixes\n\n ```bash\n git add -A\n git commit -m \"$(cat <<'EOF'\n fix: address review feedback\n\n Changes:\n - {fix 1}\n - {fix 2}\n EOF\n )\"\n ```\n\n ## Step 5: Report\n\n ```\n ## Feedback Addressed\n\n Changes made:\n - {fix 1}\n - {fix 2}\n\n Validation: {PASS / FAIL with details}\n\n Review again, or say \"approved\" to finalize.\n ```\n until: VALIDATED\n max_iterations: 10\n interactive: true\n gate_message: |\n Test the implementation yourself and review the code changes.\n Provide specific feedback on what needs fixing, or say \"approved\" to finalize.\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 5: FINALIZE — Push, create PR, generate summary\n # ═══════════════════════════════════════════════════════════════\n\n - id: finalize\n model: sonnet\n depends_on: [fix-feedback]\n context: fresh\n prompt: |\n # PIV Loop — Finalize\n\n The implementation has been approved. Push changes and create a PR.\n\n ---\n\n ## Step 1: Push Changes\n\n ```bash\n git push -u origin HEAD 2>&1 || true\n ```\n\n ## Step 2: Generate Summary\n\n ```bash\n git log --oneline --no-merges $(git merge-base HEAD $BASE_BRANCH)..HEAD\n git diff --stat $(git merge-base HEAD $BASE_BRANCH)..HEAD\n ```\n\n Read the plan file and progress tracking for context.\n\n ## Step 3: Create PR (if not already created)\n\n ```bash\n gh pr view HEAD --json url 2>/dev/null || echo \"NO_PR\"\n ```\n\n If no PR exists:\n\n ```bash\n cat .github/pull_request_template.md 2>/dev/null || echo \"NO_TEMPLATE\"\n ```\n\n Create with `gh pr create --draft --base $BASE_BRANCH`:\n - Title from the plan's feature name\n - Body summarizing the implementation\n - Use a HEREDOC for the body\n\n ## Step 4: Output Summary\n\n ```\n ===============================================================\n PIV LOOP — COMPLETE\n ===============================================================\n\n Feature: {from plan}\n Plan: {plan file path}\n Branch: {branch name}\n PR: {url}\n\n -- Tasks Completed -----------------------------------------------\n {list from progress tracking}\n\n -- Commits -------------------------------------------------------\n {git log output}\n\n -- Files Changed -------------------------------------------------\n {git diff --stat output}\n\n -- Validation ----------------------------------------------------\n All checks passed.\n ===============================================================\n ```\n", + "archon-plan-to-pr": "name: archon-plan-to-pr\ndescription: |\n Use when: You have an existing implementation plan and want to execute it end-to-end.\n Input: Path to a plan file ($ARTIFACTS_DIR/plan.md or .agents/plans/*.md)\n Output: PR ready for merge with comprehensive review completed\n\n Full workflow:\n 1. Read plan, setup branch, extract scope limits\n 2. Verify plan research is still valid\n 3. Implement all tasks with type-checking\n 4. Run full validation suite\n 5. Create PR with template, mark ready\n 6. Comprehensive code review (5 parallel agents with scope limit awareness)\n 7. Synthesize and fix review findings\n 8. Final summary with decision matrix -> GitHub comment + follow-up recommendations\n\n NOT for: Creating plans from scratch (use archon-idea-to-pr), quick fixes, standalone reviews.\n\nnodes:\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 1: SETUP\n # ═══════════════════════════════════════════════════════════════════\n\n - id: plan-setup\n command: archon-plan-setup\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 2: CONFIRM PLAN\n # ═══════════════════════════════════════════════════════════════════\n\n - id: confirm-plan\n command: archon-confirm-plan\n depends_on: [plan-setup]\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 3: IMPLEMENT\n # ═══════════════════════════════════════════════════════════════════\n\n - id: implement-tasks\n command: archon-implement-tasks\n depends_on: [confirm-plan]\n context: fresh\n model: claude-opus-4-6[1m]\n\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 4: VALIDATE\n # ═══════════════════════════════════════════════════════════════════\n\n - id: validate\n command: archon-validate\n depends_on: [implement-tasks]\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 5: FINALIZE PR\n # ═══════════════════════════════════════════════════════════════════\n\n - id: finalize-pr\n command: archon-finalize-pr\n depends_on: [validate]\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 6: CODE REVIEW\n # ═══════════════════════════════════════════════════════════════════\n\n - id: review-scope\n command: archon-pr-review-scope\n depends_on: [finalize-pr]\n context: fresh\n\n - id: sync\n command: archon-sync-pr-with-main\n depends_on: [review-scope]\n context: fresh\n\n - id: code-review\n command: archon-code-review-agent\n depends_on: [sync]\n context: fresh\n\n - id: error-handling\n command: archon-error-handling-agent\n depends_on: [sync]\n context: fresh\n\n - id: test-coverage\n command: archon-test-coverage-agent\n depends_on: [sync]\n context: fresh\n\n - id: comment-quality\n command: archon-comment-quality-agent\n depends_on: [sync]\n context: fresh\n\n - id: docs-impact\n command: archon-docs-impact-agent\n depends_on: [sync]\n context: fresh\n\n - id: synthesize\n command: archon-synthesize-review\n depends_on: [code-review, error-handling, test-coverage, comment-quality, docs-impact]\n trigger_rule: one_success\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 7: FIX REVIEW ISSUES\n # ═══════════════════════════════════════════════════════════════════\n\n - id: implement-fixes\n command: archon-implement-review-fixes\n depends_on: [synthesize]\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════════\n # PHASE 8: FINAL SUMMARY & FOLLOW-UP\n # ═══════════════════════════════════════════════════════════════════\n\n - id: workflow-summary\n command: archon-workflow-summary\n depends_on: [implement-fixes]\n context: fresh\n", + "archon-ralph-dag": "name: archon-ralph-dag\ndescription: |\n Use when: User wants to run a Ralph implementation loop.\n Triggers: \"ralph\", \"run ralph\", \"ralph dag\", \"run ralph dag\".\n\n DAG workflow that:\n 1. Detects input: existing prd.json, existing prd.md (needs stories), or raw idea\n 2. Generates prd.md + prd.json if needed (explores codebase, breaks into stories)\n 3. Validates PRD files, reads project context, installs dependencies\n 4. Runs Ralph loop (fresh context per iteration) implementing one story per iteration\n 5. Creates PR and reports completion\n\n Accepts: An idea description, a path to an existing prd.md, or a directory with prd.md + prd.json\n\nprovider: claude\n\nnodes:\n # ═══════════════════════════════════════════════════════════════\n # NODE 1: DETECT INPUT\n # Determines what the user provided: full PRD, partial PRD, or idea\n # ═══════════════════════════════════════════════════════════════\n\n - id: detect-input\n model: haiku\n prompt: |\n # Detect Ralph Input\n\n **User input**: $ARGUMENTS\n\n Determine what the user provided and prepare the PRD directory. Follow these steps exactly:\n\n ## Step 1: Detect worktree\n\n Run `git worktree list --porcelain` to check if you're in a worktree.\n If you see multiple entries, you ARE in a worktree. The first entry (the one without \"branch\" pointing to your current branch) is the **main repo root**. Save it — you'll need it to find files.\n\n ## Step 2: Classify the input\n\n Look at the user input above. It's one of three things:\n\n **Case A — Ralph directory path** (contains `.archon/ralph/`):\n Extract the directory. Check if both `prd.json` and `prd.md` exist there (try locally first, then in the main repo root if in a worktree).\n\n **Case B — File path** (ends in `.md`):\n This is an external PRD file. Find it:\n 1. Try the path as-is (relative to cwd)\n 2. Try it as an absolute path\n 3. If in a worktree, try it relative to the **main repo root** from Step 1\n Once found, read the file to confirm it's a PRD.\n\n **Case C — Free text**:\n Not a file path — it's a feature idea.\n\n ## Step 3: Auto-discover existing ralph PRDs\n\n If the input didn't point to a specific path, check if `.archon/ralph/` contains any `prd.json` files:\n ```bash\n find .archon/ralph -name \"prd.json\" -type f 2>/dev/null\n ```\n\n ## Step 4: Take action based on classification\n\n **If Case A and both files exist** → output `ready` (no further action needed)\n\n **If Case B (external PRD found)**:\n 1. Derive a kebab-case slug from the PRD filename or title (e.g., `workflow-lifecycle-overhaul`)\n 2. Create the ralph directory: `mkdir -p .archon/ralph/{slug}`\n 3. Copy the PRD content to `.archon/ralph/{slug}/prd.md`\n 4. Output `external_prd` with the new prd_dir\n\n **If Case C or auto-discovered ralph dir has prd.md but no prd.json** → output `needs_generation`\n\n ## Output\n\n Your final output MUST be exactly one JSON object:\n ```json\n {\"input_type\": \"ready|external_prd|needs_generation\", \"prd_dir\": \".archon/ralph/{slug}\"}\n ```\n output_format:\n type: object\n properties:\n input_type:\n type: string\n enum: [ready, external_prd, needs_generation]\n prd_dir:\n type: string\n required: [input_type, prd_dir]\n\n # ═══════════════════════════════════════════════════════════════\n # NODE 2: GENERATE PRD\n # Scenario 1: User has an idea → generate prd.md + prd.json\n # Scenario 2: User has prd.md → generate prd.json with stories\n # Skipped if prd.json already exists\n # ═══════════════════════════════════════════════════════════════\n\n - id: generate-prd\n depends_on: [detect-input]\n when: \"$detect-input.output.input_type != 'ready'\"\n command: archon-ralph-generate\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════\n # NODE 3: VALIDATE & SETUP\n # Finds PRD directory, reads all state files, installs deps,\n # verifies the environment is ready for implementation.\n # ═══════════════════════════════════════════════════════════════\n\n - id: validate-prd\n depends_on: [detect-input, generate-prd]\n trigger_rule: one_success\n bash: |\n set -e\n\n # ── 1. Find PRD directory (passed from detect-input) ──────\n PRD_DIR=$detect-input.output.prd_dir\n\n # If detect-input didn't know the PRD dir (generated from scratch), discover it\n if [ -z \"$PRD_DIR\" ] || [ ! -f \"$PRD_DIR/prd.json\" ]; then\n FOUND=$(find .archon/ralph -name \"prd.json\" -type f 2>/dev/null | head -1)\n if [ -n \"$FOUND\" ]; then\n PRD_DIR=$(dirname \"$FOUND\")\n fi\n fi\n\n if [ -z \"$PRD_DIR\" ] || [ ! -f \"$PRD_DIR/prd.json\" ]; then\n echo \"ERROR: No prd.json found after generation step.\"\n echo \"Check the generate-prd node output for errors.\"\n exit 1\n fi\n\n if [ ! -f \"$PRD_DIR/prd.md\" ]; then\n echo \"ERROR: prd.md not found in $PRD_DIR\"\n exit 1\n fi\n\n # ── 2. Install dependencies (worktrees lack node_modules) ──\n if [ -f \"bun.lock\" ] || [ -f \"bun.lockb\" ]; then\n echo \"Installing dependencies (bun)...\"\n bun install --frozen-lockfile 2>&1 | tail -3\n elif [ -f \"package-lock.json\" ]; then\n echo \"Installing dependencies (npm)...\"\n npm ci 2>&1 | tail -3\n elif [ -f \"yarn.lock\" ]; then\n echo \"Installing dependencies (yarn)...\"\n yarn install --frozen-lockfile 2>&1 | tail -3\n elif [ -f \"pnpm-lock.yaml\" ]; then\n echo \"Installing dependencies (pnpm)...\"\n pnpm install --frozen-lockfile 2>&1 | tail -3\n fi\n\n # ── 3. Git state ──────────────────────────────────────────\n echo \"BRANCH=$(git branch --show-current)\"\n echo \"GIT_ROOT=$(git rev-parse --show-toplevel)\"\n\n # ── 4. Output PRD context ─────────────────────────────────\n echo \"PRD_DIR=$PRD_DIR\"\n echo \"=== PRD_JSON_START ===\"\n cat \"$PRD_DIR/prd.json\"\n echo \"\"\n echo \"=== PRD_JSON_END ===\"\n echo \"=== PRD_MD_START ===\"\n cat \"$PRD_DIR/prd.md\"\n echo \"\"\n echo \"=== PRD_MD_END ===\"\n echo \"=== PROGRESS_START ===\"\n if [ -f \"$PRD_DIR/progress.txt\" ]; then\n cat \"$PRD_DIR/progress.txt\"\n else\n echo \"(no progress yet)\"\n fi\n echo \"\"\n echo \"=== PROGRESS_END ===\"\n\n # ── 5. Summary ────────────────────────────────────────────\n TOTAL=$(grep -c '\"passes\"' \"$PRD_DIR/prd.json\" || true)\n DONE=$(grep -c '\"passes\": true' \"$PRD_DIR/prd.json\" || true)\n TOTAL=${TOTAL:-0}\n DONE=${DONE:-0}\n echo \"STORIES_TOTAL=$TOTAL\"\n echo \"STORIES_DONE=$DONE\"\n echo \"STORIES_REMAINING=$(( TOTAL - DONE ))\"\n\n # ═══════════════════════════════════════════════════════════════\n # NODE 4: RALPH IMPLEMENTATION LOOP\n # Fresh context each iteration. Reads PRD state from disk.\n # One story per iteration. Validates before committing.\n # ═══════════════════════════════════════════════════════════════\n\n - id: implement\n depends_on: [validate-prd]\n idle_timeout: 600000\n model: claude-opus-4-6[1m]\n loop:\n prompt: |\n # Ralph Agent — Autonomous Story Implementation\n\n You are an autonomous coding agent in a FRESH session — you have no memory of previous iterations.\n Your job: Read state from disk, implement ONE story, validate, commit, update tracking, exit.\n\n **Golden Rule**: If validation fails, fix it before committing. Never commit broken code. Never skip validation.\n\n ---\n\n ## Phase 0: CONTEXT — Load Project State\n\n The upstream setup node produced this context:\n\n $validate-prd.output\n\n **User message**: $USER_MESSAGE\n\n ---\n\n ### 0.1 Parse PRD Directory\n\n Extract the `PRD_DIR=...` line from the context above. This is the directory containing your PRD files.\n Store this path — use it for ALL file operations below.\n\n ### 0.2 Read Current State (from disk, not from context above)\n\n The context above is a snapshot from before the loop started. Previous iterations may have changed files.\n **You MUST re-read from disk to get the current state:**\n\n 1. **Read `{prd-dir}/progress.txt`** — your only link to previous iterations\n - Check the `## Codebase Patterns` section FIRST for learnings from prior iterations\n - Check recent entries for gotchas to avoid\n 2. **Read `{prd-dir}/prd.json`** — the source of truth for story completion state\n 3. **Read `{prd-dir}/prd.md`** — full requirements, technical patterns, acceptance criteria\n\n ### 0.3 Read Project Rules\n\n ```bash\n cat CLAUDE.md\n ```\n\n Note all coding standards, patterns, and rules. Follow them exactly.\n\n **PHASE_0_CHECKPOINT:**\n - [ ] PRD directory identified\n - [ ] progress.txt read (or noted as absent)\n - [ ] prd.json read — know which stories pass/fail\n - [ ] prd.md read — understand requirements\n - [ ] CLAUDE.md rules noted\n\n ---\n\n ## Phase 1: SELECT — Pick Next Story\n\n ### 1.1 Find Eligible Story\n\n From `prd.json`, find the **highest priority** story where:\n - `passes` is `false`\n - ALL stories in `dependsOn` have `passes: true`\n\n **If ALL stories have `passes: true`** → Skip to Phase 6 (Completion).\n\n **If no eligible stories exist** (all remaining are blocked):\n ```\n BLOCKED: No eligible stories. Remaining stories and their blockers:\n - {story-id}: blocked by {dep-id} (passes: false)\n ```\n End normally. The loop will terminate on max_iterations.\n\n ### 1.2 Announce Selection\n\n ```\n ── Story Selected ──────────────────────────────────\n ID: {story-id}\n Title: {story-title}\n Priority: {priority}\n Dependencies: {deps or \"none\"}\n\n Acceptance Criteria:\n - {criterion 1}\n - {criterion 2}\n - ...\n ────────────────────────────────────────────────────\n ```\n\n After announcing the selected story, emit the story started event:\n ```bash\n bun run cli workflow event emit --run-id $WORKFLOW_ID --type ralph_story_started --data '{\"story_id\":\"{story-id}\",\"title\":\"{story-title}\"}' || true\n ```\n\n **PHASE_1_CHECKPOINT:**\n - [ ] Eligible story found (or all complete / all blocked)\n - [ ] Acceptance criteria understood\n - [ ] Dependencies verified as complete\n\n ---\n\n ## Phase 2: IMPLEMENT — Code the Story\n\n ### 2.1 Explore Before Coding\n\n Before writing any code:\n 1. Read all files you plan to modify — understand current state\n 2. Check `## Codebase Patterns` in progress.txt for discovered patterns\n 3. Look for similar implementations in the codebase to mirror\n 4. Read the `technicalNotes` field from the story in prd.json\n\n ### 2.2 Implementation Rules\n\n **DO:**\n - Implement ONLY the selected story — one story per iteration\n - Follow existing code patterns exactly (naming, structure, imports, error handling)\n - Match the project's coding standards from CLAUDE.md\n - Write or update tests as required by acceptance criteria\n - Keep changes minimal and focused\n\n **DON'T:**\n - Refactor unrelated code\n - Add improvements not in the acceptance criteria\n - Change formatting of lines you didn't modify\n - Install new dependencies without justification from prd.md\n - Touch files unrelated to this story\n - Over-engineer — do the simplest thing that satisfies the criteria\n\n ### 2.3 Verify Types After Each File\n\n After modifying each file, run:\n ```bash\n bun run type-check\n ```\n\n **If types fail:**\n 1. Read the error carefully\n 2. Fix the type issue in your code\n 3. Re-run type-check\n 4. Do NOT proceed to the next file until types pass\n\n **PHASE_2_CHECKPOINT:**\n - [ ] Only the selected story was implemented\n - [ ] Types compile after each file change\n - [ ] Tests written/updated as needed\n - [ ] No unrelated changes\n\n ---\n\n ## Phase 3: VALIDATE — Full Verification\n\n ### 3.1 Static Analysis\n\n ```bash\n bun run type-check && bun run lint\n ```\n\n **Must pass with zero errors and zero warnings.**\n\n **If lint fails:**\n 1. Run `bun run lint:fix` for auto-fixable issues\n 2. Manually fix remaining issues\n 3. Re-run lint\n 4. Proceed only when clean\n\n ### 3.2 Tests\n\n ```bash\n bun run test\n ```\n\n **All tests must pass.**\n\n **If tests fail:**\n 1. Read the failure output\n 2. Determine: bug in your implementation or pre-existing failure?\n 3. If your bug → fix the implementation (not the test)\n 4. If pre-existing → note it but don't fix unrelated tests\n 5. Re-run tests\n 6. Repeat until green\n\n ### 3.3 Format Check\n\n ```bash\n bun run format:check\n ```\n\n **If formatting fails:**\n ```bash\n bun run format\n ```\n\n ### 3.4 Verify Acceptance Criteria\n\n Go through EACH acceptance criterion from the story:\n - Is it satisfied by your implementation?\n - Can you verify it (read the code, run a command, check a file)?\n\n If a criterion is NOT met, go back to Phase 2 and fix it.\n\n **PHASE_3_CHECKPOINT:**\n - [ ] Type-check passes\n - [ ] Lint passes (0 errors, 0 warnings)\n - [ ] All tests pass\n - [ ] Format is clean\n - [ ] Every acceptance criterion verified\n\n ---\n\n ## Phase 4: COMMIT — Save Changes\n\n ### 4.1 Review Staged Changes\n\n ```bash\n git add -A\n git status\n git diff --cached --stat\n ```\n\n Verify only expected files are staged. If unexpected files appear, investigate before committing.\n\n ### 4.2 Write Commit Message\n\n ```bash\n git commit -m \"$(cat <<'EOF'\n feat: {story-title}\n\n Implements {story-id} from PRD.\n\n Changes:\n - {change 1}\n - {change 2}\n - {change 3}\n EOF\n )\"\n ```\n\n **Commit message rules:**\n - Prefix: `feat:` for features, `fix:` for bugs, `refactor:` for refactors\n - Title: the story title (not the PRD name)\n - Body: list the actual changes made\n - Do NOT include AI attribution\n\n **PHASE_4_CHECKPOINT:**\n - [ ] Only expected files committed\n - [ ] Commit message is clear and accurate\n - [ ] Working directory is clean after commit\n\n ---\n\n ## Phase 5: TRACK — Update Progress Files\n\n ### 5.1 Update prd.json\n\n Set `passes: true` and add a note for the completed story:\n\n ```json\n {\n \"id\": \"{story-id}\",\n \"passes\": true,\n \"notes\": \"Implemented in iteration {N}. Files: {list}.\"\n }\n ```\n\n After updating prd.json, emit the story completed event:\n ```bash\n bun run cli workflow event emit --run-id $WORKFLOW_ID --type ralph_story_completed --data '{\"story_id\":\"{story-id}\",\"title\":\"{story-title}\"}' || true\n ```\n\n ### 5.2 Update progress.txt\n\n **Append** to `{prd-dir}/progress.txt`:\n\n ```\n ## {ISO Date} — {story-id}: {story-title}\n\n **Status**: PASSED\n **Files changed**:\n - {file1} — {what changed}\n - {file2} — {what changed}\n\n **Acceptance criteria verified**:\n - [x] {criterion 1}\n - [x] {criterion 2}\n\n **Learnings**:\n - {Any pattern discovered}\n - {Any gotcha encountered}\n - {Any deviation from expected approach}\n\n ---\n ```\n\n ### 5.3 Update Codebase Patterns (if applicable)\n\n If you discovered a **reusable pattern** that future iterations should know about, **prepend** it to the `## Codebase Patterns` section at the TOP of progress.txt.\n\n Format:\n ```\n ## Codebase Patterns\n\n ### {Pattern Name}\n - **Where**: `{file:lines}`\n - **Pattern**: {description}\n - **Example**: `{code snippet}`\n ```\n\n If the `## Codebase Patterns` section doesn't exist yet, create it at the top of the file.\n\n **PHASE_5_CHECKPOINT:**\n - [ ] prd.json updated with `passes: true`\n - [ ] progress.txt appended with iteration details\n - [ ] Codebase patterns updated (if applicable)\n\n ---\n\n ## Phase 6: COMPLETE — Check All Stories\n\n ### 6.1 Re-read prd.json\n\n ```bash\n cat {prd-dir}/prd.json\n ```\n\n Count stories where `passes: false`.\n\n ### 6.2 If ALL Stories Pass\n\n 1. **Push the branch:**\n ```bash\n git push -u origin HEAD\n ```\n\n 2. **Read the PR template:**\n Look for a PR template in the repo — check `.github/pull_request_template.md`, `.github/PULL_REQUEST_TEMPLATE.md`, and `docs/pull_request_template.md`. Read whichever one exists.\n\n If a template was found, fill in **every section** using the context from this implementation. Don't skip sections or leave placeholders — fill them honestly based on the actual changes (summary, architecture, validation evidence, security, compatibility, rollback, etc.).\n\n If no template was found, write a summary with: problem, what changed, stories table, and validation evidence.\n\n 3. **Create a draft PR** using `gh pr create --draft --base $BASE_BRANCH --title \"feat: {PRD feature name}\"` with the filled-in template as the body. Use a HEREDOC for the body.\n\n 4. **Output completion signal:**\n ```\n COMPLETE\n ```\n\n ### 6.3 If Stories Remain\n\n Report status and end normally:\n ```\n ── Iteration Complete ──────────────────────────────\n Story completed: {story-id} — {story-title}\n Stories remaining: {count}\n Next eligible: {next-story-id} — {next-story-title}\n ────────────────────────────────────────────────────\n ```\n\n The loop engine will start the next iteration with a fresh context.\n\n ---\n\n ## Handling Edge Cases\n\n ### Validation fails repeatedly\n - If type-check or tests fail 3+ times on the same error, step back\n - Re-read the acceptance criteria — you may be misunderstanding the requirement\n - Check if the story is too large (needs breaking down)\n - Note the blocker in progress.txt and end the iteration\n\n ### Story is too large for one iteration\n - Implement the minimum viable subset that satisfies the most critical acceptance criteria\n - Set `passes: true` only if ALL criteria are met\n - If you can't meet all criteria, leave `passes: false` and note what's done in progress.txt\n - The next iteration will pick it up and continue\n\n ### Pre-existing test failures\n - If tests were failing BEFORE your changes, note them but don't fix unrelated code\n - Run only the test files related to your changes if the full suite has pre-existing issues\n - Document pre-existing failures in progress.txt\n\n ### Dependency install fails\n - Check if `bun.lock` or equivalent exists\n - Try `bun install` without `--frozen-lockfile`\n - Note the issue in progress.txt\n\n ### Git state is dirty at iteration start\n - This shouldn't happen (fresh worktree), but if it does:\n - Run `git status` to understand what's dirty\n - If it's leftover from a failed previous iteration, commit or stash\n - Never discard changes silently\n\n ### Blocked stories — all remaining have unmet dependencies\n - Report the dependency chain in your output\n - Check if a dependency was incorrectly left as `passes: false`\n - If a dependency should be `passes: true` (the code exists and works), fix prd.json\n - Otherwise, end the iteration — the loop will exhaust max_iterations\n\n ---\n\n ## File Format Reference\n\n ### prd.json Schema\n\n ```json\n {\n \"feature\": \"Feature Name\",\n \"issueNumber\": 123,\n \"userStories\": [\n {\n \"id\": \"US-001\",\n \"title\": \"Short title\",\n \"description\": \"As a..., I want..., so that...\",\n \"acceptanceCriteria\": [\"criterion 1\", \"criterion 2\"],\n \"technicalNotes\": \"Implementation hints\",\n \"dependsOn\": [\"US-000\"],\n \"priority\": 1,\n \"passes\": false,\n \"notes\": \"\"\n }\n ]\n }\n ```\n\n ### progress.txt Format\n\n ```\n ## Codebase Patterns\n\n ### {Pattern Name}\n - Where: `file:lines`\n - Pattern: description\n - Example: `code`\n\n ---\n\n ## {Date} — {story-id}: {title}\n\n **Status**: PASSED\n **Files changed**: ...\n **Acceptance criteria verified**: ...\n **Learnings**: ...\n\n ---\n ```\n\n ---\n\n ## Success Criteria\n\n - **ONE_STORY**: Exactly one story implemented per iteration\n - **VALIDATED**: Type-check + lint + tests + format all pass before commit\n - **COMMITTED**: Changes committed with clear message\n - **TRACKED**: prd.json and progress.txt updated accurately\n - **PATTERNS_SHARED**: Discovered patterns added to progress.txt for future iterations\n - **NO_SCOPE_CREEP**: No unrelated changes, no refactoring, no \"improvements\"\n until: COMPLETE\n max_iterations: 15\n fresh_context: true\n\n # ═══════════════════════════════════════════════════════════════\n # NODE 5: COMPLETION REPORT\n # Reads final state and produces a summary.\n # ═══════════════════════════════════════════════════════════════\n\n - id: report\n depends_on: [implement]\n prompt: |\n # Completion Report\n\n The Ralph implementation loop has finished. Generate a completion report.\n\n ## Context\n\n **Loop output (last iteration):**\n\n $implement.output\n\n **Setup context:**\n\n $validate-prd.output\n\n ---\n\n ## Instructions\n\n ### 1. Read Final State\n\n Extract the `PRD_DIR=...` from the setup context above.\n Read the CURRENT files from disk:\n\n ```bash\n cat {prd-dir}/prd.json\n cat {prd-dir}/progress.txt\n ```\n\n ### 2. Gather Git Info\n\n ```bash\n git log --oneline --no-merges $(git merge-base HEAD $BASE_BRANCH)..HEAD\n git diff --stat $(git merge-base HEAD $BASE_BRANCH)..HEAD\n ```\n\n ### 3. Check PR Status\n\n ```bash\n gh pr view HEAD --json url,number,state 2>/dev/null || echo \"No PR found\"\n ```\n\n ### 4. Generate Report\n\n Output this format:\n\n ```\n ═══════════════════════════════════════════════════════\n RALPH DAG — COMPLETION REPORT\n ═══════════════════════════════════════════════════════\n\n Feature: {feature name from prd.json}\n PRD: {prd-dir}\n Branch: {branch name}\n PR: {url or \"not created\"}\n\n ── Stories ─────────────────────────────────────────\n\n | ID | Title | Status |\n |----|-------|--------|\n {for each story from prd.json}\n\n Total: {N}/{M} stories passing\n\n ── Commits ─────────────────────────────────────────\n\n {git log output}\n\n ── Files Changed ─────────────────────────────────\n\n {git diff --stat output}\n\n ── Patterns Discovered ─────────────────────────────\n\n {from ## Codebase Patterns in progress.txt, or \"None\"}\n\n ═══════════════════════════════════════════════════════\n ```\n\n Keep it factual. No commentary — just the data.\n", + "archon-refactor-safely": "name: archon-refactor-safely\ndescription: |\n Use when: User wants to refactor code safely with continuous validation and behavior preservation.\n Triggers: \"refactor\", \"refactor safely\", \"split this file\", \"extract module\", \"break up\",\n \"decompose\", \"safe refactor\", \"split file\", \"extract into modules\".\n Does: Scans refactoring scope -> analyzes impact (read-only) -> plans ordered task list ->\n executes with type-check hooks after every edit -> validates full suite ->\n verifies behavior preservation (read-only) -> creates PR with before/after comparison.\n NOT for: Bug fixes (use archon-fix-github-issue), feature development (use archon-feature-development),\n general architecture sweeps (use archon-architect), PR reviews.\n\n Key safety features:\n - Analysis and verification nodes are read-only (denied_tools: [Write, Edit, Bash])\n - PreToolUse hooks check if each edit is in the plan\n - PostToolUse hooks force type-check after every file change\n - Behavior verification confirms no logic changes after refactoring\n\nprovider: claude\n\nnodes:\n # ═══════════════════════════════════════════════════════════════\n # PHASE 1: SCAN — Find files matching the refactoring target\n # ═══════════════════════════════════════════════════════════════\n\n - id: scan-scope\n bash: |\n echo \"=== REFACTORING TARGET ===\"\n echo \"User request: $ARGUMENTS\"\n echo \"\"\n\n echo \"=== FILE SIZE ANALYSIS (source files by size) ===\"\n find . -name '*.ts' -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/dist/*' -not -name '*.test.ts' -not -name '*.d.ts' \\\n -exec wc -l {} + 2>/dev/null | sort -rn | head -30\n echo \"\"\n\n echo \"=== FILES OVER 500 LINES ===\"\n find . -name '*.ts' -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/dist/*' -not -name '*.test.ts' -not -name '*.d.ts' \\\n -exec sh -c 'lines=$(wc -l < \"$1\"); if [ \"$lines\" -gt 500 ]; then echo \"$lines $1\"; fi' _ {} \\; 2>/dev/null | sort -rn\n echo \"\"\n\n echo \"=== FUNCTION COUNT PER FILE (top 20) ===\"\n for f in $(find . -name '*.ts' -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/dist/*' -not -name '*.test.ts' -not -name '*.d.ts'); do\n count=$(grep -cE '^\\s*(export\\s+)?(async\\s+)?function\\s|=>\\s*\\{' \"$f\" 2>/dev/null) || count=0\n if [ \"$count\" -gt 5 ]; then\n echo \"$count functions: $f\"\n fi\n done | sort -rn | head -20\n echo \"\"\n\n echo \"=== EXPORT ANALYSIS (files with many exports) ===\"\n for f in $(find . -name '*.ts' -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/dist/*' -not -name '*.test.ts' -not -name '*.d.ts'); do\n count=$(grep -c \"^export \" \"$f\" 2>/dev/null) || count=0\n if [ \"$count\" -gt 5 ]; then\n echo \"$count exports: $f\"\n fi\n done | sort -rn | head -20\n timeout: 60000\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 2: ANALYZE IMPACT — Read-only deep analysis\n # Maps call sites, identifies risk areas, understands dependencies\n # ═══════════════════════════════════════════════════════════════\n\n - id: analyze-impact\n prompt: |\n You are a senior software engineer analyzing code for a safe refactoring.\n\n ## Refactoring Request\n\n $ARGUMENTS\n\n ## Codebase Scan Results\n\n $scan-scope.output\n\n ## Instructions\n\n 1. Identify the PRIMARY file(s) targeted for refactoring based on the user's request\n and the scan results above\n 2. Read each target file thoroughly — understand every function, type, and export\n 3. For each target file, map ALL call sites:\n - Use Grep to find every import of the target file across the codebase\n - Track which specific exports are used and where\n - Note any dynamic imports or re-exports through index files\n 4. Identify risk areas:\n - Functions with complex internal dependencies (shared closures, module-level state)\n - Circular dependencies between functions in the file\n - Any module-level side effects (top-level `const`, initialization code)\n - Exports that are part of the public API vs internal-only\n 5. Check for existing tests:\n - Find test files for the target module(s)\n - Note what's tested and what isn't\n\n ## Output\n\n Write a thorough impact analysis to `$ARTIFACTS_DIR/impact-analysis.md` with:\n\n ### Target Files\n - File path, line count, function count\n - List of all exported symbols with brief descriptions\n\n ### Dependency Map\n - Which files import from the target (with specific imports used)\n - Which files the target imports from\n\n ### Risk Assessment\n - Module-level state or side effects\n - Complex internal dependencies between functions\n - Public API surface that must be preserved exactly\n\n ### Test Coverage\n - Existing test files and what they cover\n - Critical paths that must remain tested\n\n ### Recommended Decomposition Strategy\n - Suggested module boundaries (which functions group together)\n - Rationale for each grouping (cohesion, shared dependencies)\n depends_on: [scan-scope]\n context: fresh\n denied_tools: [Write, Edit, Bash]\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 3: PLAN REFACTOR — Ordered task list with rollback strategy\n # Read-only: produces the plan, does not execute it\n # ═══════════════════════════════════════════════════════════════\n\n - id: plan-refactor\n prompt: |\n You are planning a safe refactoring. You must produce a precise, ordered plan\n that another agent will follow literally.\n\n ## Impact Analysis\n\n $analyze-impact.output\n\n ## Refactoring Goal\n\n $ARGUMENTS\n\n ## Principles\n\n - **Behavior preservation**: The refactoring must NOT change any behavior — only structure\n - **Incremental**: Each step must leave the codebase in a compilable state\n - **Reversible**: Each step can be independently reverted\n - **No mixed concerns**: Do not combine refactoring with bug fixes or improvements\n - **Preserve public API**: All existing exports must remain accessible from the same import paths\n - **Maximum file size**: Target 500 lines or fewer per file after refactoring\n\n ## Instructions\n\n 1. Read the impact analysis from `$ARTIFACTS_DIR/impact-analysis.md`\n 2. Read the target file(s) to understand the current structure\n 3. Design the decomposition:\n - Group related functions into cohesive modules\n - Identify shared utilities, types, and constants\n - Plan the new file structure with descriptive names\n 4. Write an ordered task list where each task is:\n - Independent and leaves code compilable after completion\n - Specific about what to extract and where\n - Clear about import updates needed\n\n ## Output\n\n Write the plan to `$ARTIFACTS_DIR/refactor-plan.md` with:\n\n ### File Structure (Before)\n ```\n [current structure with line counts]\n ```\n\n ### File Structure (After)\n ```\n [planned structure with estimated line counts]\n ```\n\n ### Ordered Tasks\n\n For each task:\n ```\n ## Task N: [brief description]\n\n **Action**: CREATE | EXTRACT | UPDATE\n **Source**: [source file]\n **Target**: [target file]\n **What moves**:\n - function functionName (lines X-Y)\n - type TypeName (lines X-Y)\n\n **Import updates needed**:\n - [file]: change import from [old] to [new]\n\n **Rollback**: [how to undo this specific step]\n ```\n\n ### Validation Commands\n - Type check: `bun run type-check`\n - Lint: `bun run lint`\n - Tests: `bun run test`\n - Format: `bun run format:check`\n depends_on: [analyze-impact]\n context: fresh\n denied_tools: [Write, Edit, Bash]\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 4: EXECUTE REFACTOR — Implements the plan with guardrails\n # Hooks enforce type-check after every edit and plan adherence\n # ═══════════════════════════════════════════════════════════════\n\n - id: execute-refactor\n model: claude-opus-4-6[1m]\n prompt: |\n You are executing a refactoring plan with strict safety guardrails.\n\n ## Plan\n\n Read the full plan from `$ARTIFACTS_DIR/refactor-plan.md` — follow it LITERALLY.\n\n ## Rules\n\n - **Follow the plan exactly** — do not add extra improvements or cleanups\n - **One task at a time** — complete each task fully before starting the next\n - **Type-check after every file change** — you'll be prompted to do this after each edit\n - **Preserve all behavior** — refactoring means moving code, not changing it\n - **Preserve the public API** — if the original file exported something, it must still be\n importable from the same path (use re-exports in the original file if needed)\n - **Update all import sites** — every file that imported from the original must be updated\n - **Commit after each logical task** — one commit per plan task with a clear message\n\n ## Process for Each Task\n\n 1. Read the plan task\n 2. Read the source file to understand current state\n 3. Create the new file (if extracting) with the functions/types being moved\n 4. Update the source file to remove the moved code and add imports from the new file\n 5. Update the original file's exports to re-export from the new module (API preservation)\n 6. Use Grep to find and update ALL import sites across the codebase\n 7. Run `bun run type-check` to verify (you'll be reminded by hooks)\n 8. Commit: `git add -A && git commit -m \"refactor: [task description]\"`\n 9. Move to next task\n\n ## Handling Problems\n\n - If type-check fails after a change: fix it immediately before proceeding\n - If a task is more complex than planned: complete it anyway, note the deviation\n - If you discover the plan missed an import site: update it and note it\n - NEVER skip a task — complete them in order\n depends_on: [plan-refactor]\n context: fresh\n hooks:\n PreToolUse:\n - matcher: \"Write|Edit\"\n response:\n hookSpecificOutput:\n hookEventName: PreToolUse\n additionalContext: >\n Before modifying this file: Is this file in your refactoring plan\n ($ARTIFACTS_DIR/refactor-plan.md)? If it's not a planned target file\n AND not a file that imports from the target, explain why you're touching it.\n Unplanned changes increase risk.\n PostToolUse:\n - matcher: \"Write|Edit\"\n response:\n systemMessage: >\n You just modified a file. STOP and do these things NOW before making any\n other changes:\n 1. Run `bun run type-check` to verify the change compiles\n 2. If type-check fails, fix the error immediately\n 3. Verify you preserved the exact same behavior — no logic changes, only structural moves\n Only proceed to the next change after type-check passes.\n - matcher: \"Bash\"\n response:\n hookSpecificOutput:\n hookEventName: PostToolUse\n additionalContext: >\n Check the exit code. If type-check or any validation failed, fix the issue\n before continuing. Do not accumulate broken state.\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 5: VALIDATE — Full test suite (bash, no AI escape hatch)\n # ═══════════════════════════════════════════════════════════════\n\n - id: validate\n bash: |\n echo \"=== TYPE CHECK ===\"\n bun run type-check 2>&1\n TC_EXIT=$?\n\n echo \"\"\n echo \"=== LINT ===\"\n bun run lint 2>&1\n LINT_EXIT=$?\n\n echo \"\"\n echo \"=== FORMAT CHECK ===\"\n bun run format:check 2>&1\n FMT_EXIT=$?\n\n echo \"\"\n echo \"=== TESTS ===\"\n bun run test 2>&1\n TEST_EXIT=$?\n\n echo \"\"\n echo \"=== FILE SIZE CHECK ===\"\n echo \"Files still over 500 lines:\"\n find . -name '*.ts' -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/dist/*' -not -name '*.test.ts' -not -name '*.d.ts' \\\n -exec sh -c 'lines=$(wc -l < \"$1\"); if [ \"$lines\" -gt 500 ]; then echo \"$lines $1\"; fi' _ {} \\; 2>/dev/null | sort -rn\n echo \"\"\n\n echo \"=== RESULTS ===\"\n echo \"Type check: $([ $TC_EXIT -eq 0 ] && echo 'PASS' || echo 'FAIL')\"\n echo \"Lint: $([ $LINT_EXIT -eq 0 ] && echo 'PASS' || echo 'FAIL')\"\n echo \"Format: $([ $FMT_EXIT -eq 0 ] && echo 'PASS' || echo 'FAIL')\"\n echo \"Tests: $([ $TEST_EXIT -eq 0 ] && echo 'PASS' || echo 'FAIL')\"\n\n if [ $TC_EXIT -eq 0 ] && [ $LINT_EXIT -eq 0 ] && [ $FMT_EXIT -eq 0 ] && [ $TEST_EXIT -eq 0 ]; then\n echo \"VALIDATION_STATUS: PASS\"\n else\n echo \"VALIDATION_STATUS: FAIL\"\n fi\n depends_on: [execute-refactor]\n timeout: 300000\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 6: FIX VALIDATION FAILURES (if any)\n # Only does real work if validation failed\n # ═══════════════════════════════════════════════════════════════\n\n - id: fix-failures\n prompt: |\n Review the validation output below.\n\n ## Validation Output\n\n $validate.output\n\n ## Instructions\n\n If the output ends with \"VALIDATION_STATUS: PASS\", respond with\n \"All checks passed — no fixes needed.\" and stop.\n\n If there are failures:\n\n 1. Read the validation failures carefully\n 2. Fix ONLY what's broken — do not make additional improvements\n 3. If a fix requires changing behavior (not just fixing a type/lint error),\n revert the original change instead\n 4. Run the specific failing check after each fix to confirm it passes\n 5. After all fixes, run the full validation suite: `bun run validate`\n\n If there are files still over 500 lines, note them but do NOT attempt further\n splitting in this node — that would require a new plan cycle.\n depends_on: [validate]\n context: fresh\n hooks:\n PostToolUse:\n - matcher: \"Write|Edit\"\n response:\n systemMessage: >\n You just made a fix. Run the specific failing validation check NOW\n to verify your fix works. Do not batch fixes — verify each one.\n PreToolUse:\n - matcher: \"Write|Edit\"\n response:\n hookSpecificOutput:\n hookEventName: PreToolUse\n additionalContext: >\n You are fixing validation failures only. Do not make any changes\n beyond what's needed to pass the failing checks. If in doubt, revert\n the original change that caused the failure.\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 7: VERIFY BEHAVIOR — Read-only confirmation\n # Ensures the refactoring preserved behavior by tracing call paths\n # ═══════════════════════════════════════════════════════════════\n\n - id: verify-behavior\n prompt: |\n You are a code reviewer verifying that a refactoring preserved exact behavior.\n You can ONLY read files — you cannot make any changes.\n\n ## Refactoring Plan\n\n Read the plan from `$ARTIFACTS_DIR/refactor-plan.md` to understand what was intended.\n\n ## Instructions\n\n 1. Use Grep and Glob to find all files in the new module locations listed in\n the plan, then Read each one. (Note: Bash is denied in this read-only node,\n so use Grep/Glob/Read to discover changes instead of git commands.)\n 2. For each new file created by the refactoring:\n - Verify the extracted functions match the originals exactly (no logic changes)\n - Check that all types and interfaces are preserved\n 3. For the original file(s):\n - Verify re-exports exist for all symbols that were previously exported\n - Confirm no function bodies were changed (only moved)\n 4. For all import sites updated:\n - Verify imports resolve to the correct new locations\n - Check that no import was missed\n 5. Verify the public API is preserved:\n - Any code that imported from the original file should still work unchanged\n - Re-exports in the original file should cover all moved symbols\n\n ## Output\n\n Write your verification report to `$ARTIFACTS_DIR/behavior-verification.md`:\n\n ### Verdict: PASS | FAIL\n\n ### Functions Verified\n | Function | Original Location | New Location | Behavior Preserved |\n |----------|------------------|--------------|-------------------|\n | funcName | file.ts:42 | new-file.ts:10 | Yes/No |\n\n ### Public API Check\n - [ ] All original exports still accessible from original import path\n - [ ] Re-exports correctly configured\n\n ### Import Sites Updated\n - [ ] All N import sites verified\n\n ### Issues Found\n [List any behavior changes detected, or \"None — refactoring is behavior-preserving\"]\n depends_on: [fix-failures]\n context: fresh\n denied_tools: [Write, Edit, Bash]\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 8: CREATE PR — Detailed description with before/after\n # ═══════════════════════════════════════════════════════════════\n\n - id: create-pr\n prompt: |\n Create a pull request for the refactoring.\n\n ## Context\n\n - **Refactoring goal**: $ARGUMENTS\n - **Impact analysis**: Read `$ARTIFACTS_DIR/impact-analysis.md`\n - **Refactoring plan**: Read `$ARTIFACTS_DIR/refactor-plan.md`\n - **Validation**: $validate.output\n - **Behavior verification**: Read `$ARTIFACTS_DIR/behavior-verification.md`\n\n ## Instructions\n\n 1. Stage all changes and create a final commit if there are uncommitted changes\n 2. Push the branch: `git push -u origin HEAD`\n 3. Check if a PR already exists: `gh pr list --head $(git branch --show-current)`\n 4. Create the PR with the format below\n 5. Save the PR URL to `$ARTIFACTS_DIR/.pr-url`\n\n ## PR Format\n\n - **Title**: `refactor: [concise description]` (under 70 chars)\n - **Body**:\n\n ```markdown\n ## Refactoring: [goal]\n\n ### Motivation\n\n [Why this refactoring was needed — file sizes, complexity, maintainability]\n\n ### Before\n\n ```\n [Original file structure with line counts from the plan]\n ```\n\n ### After\n\n ```\n [New file structure with line counts]\n ```\n\n ### Changes\n\n [For each new module: what was extracted and why it's a cohesive unit]\n\n ### Safety\n\n - [x] Type check passes\n - [x] Lint passes\n - [x] Tests pass (all existing tests still green)\n - [x] Public API preserved (re-exports maintain backward compatibility)\n - [x] Behavior verification passed (read-only audit confirmed no logic changes)\n - [x] Each task committed separately for easy review/revert\n\n ### Review Guide\n\n Each commit represents one extraction step. Review commits individually for easiest review.\n All commits are behavior-preserving structural moves.\n ```\n depends_on: [verify-behavior]\n context: fresh\n hooks:\n PreToolUse:\n - matcher: \"Write|Edit\"\n response:\n hookSpecificOutput:\n hookEventName: PreToolUse\n permissionDecision: deny\n permissionDecisionReason: \"PR creation node — do not modify source files. Use only git and gh commands.\"\n PostToolUse:\n - matcher: \"Bash\"\n response:\n hookSpecificOutput:\n hookEventName: PostToolUse\n additionalContext: >\n Verify this command succeeded. If git push or gh pr create failed,\n read the error message carefully before retrying.\n", + "archon-remotion-generate": "name: archon-remotion-generate\ndescription: |\n Use when: User wants to generate or modify a Remotion video composition using AI.\n Triggers: \"create a video\", \"generate video\", \"remotion\", \"make an animation\",\n \"video about\", \"animate\".\n Does: AI writes Remotion React code -> renders preview stills -> renders full video ->\n summarizes the output.\n Requires: A Remotion project in the working directory (src/index.ts, src/Root.tsx).\n Optional: Install the remotion-best-practices skill for higher quality output:\n npx skills add remotion-dev/skills\n\nnodes:\n # ── Layer 0: Check project structure ──────────────────────────────────\n - id: check-project\n bash: |\n if [ ! -f \"src/index.ts\" ] || [ ! -f \"src/Root.tsx\" ]; then\n echo \"ERROR: Not a Remotion project. Expected src/index.ts and src/Root.tsx.\"\n echo \"Run 'npx create-video@latest' first, then run this workflow from that directory.\"\n exit 1\n fi\n echo \"Remotion project detected.\"\n npx remotion compositions src/index.ts 2>&1 | tail -5\n echo \"\"\n echo \"PROJECT_READY\"\n timeout: 60000\n\n # ── Layer 1: Generate composition code ────────────────────────────────\n - id: generate\n prompt: |\n You are working in a Remotion video project. The project root is the current directory.\n\n Find and read the existing composition files to understand the project structure.\n Look in src/ for Root.tsx and any composition components.\n\n Now create or modify the composition to match this request:\n\n $ARGUMENTS\n\n Rules:\n - Use useCurrentFrame() and interpolate()/spring() for ALL animations\n - Never use CSS transitions, Math.random(), setTimeout, or Date.now()\n - Use AbsoluteFill for layout, Sequence for scene timing\n - Use the component from 'remotion' (not native ) for images\n - Keep dimensions 1920x1080 at 30 fps unless the user specifies otherwise\n - Update the Zod schema and defaultProps in Root.tsx if you change props\n - Use even numbers for width/height (required for MP4)\n - Always clamp interpolations: extrapolateLeft: 'clamp', extrapolateRight: 'clamp'\n\n After writing the code, read it back to verify it looks correct.\n depends_on: [check-project]\n skills:\n - remotion-best-practices\n allowed_tools:\n - Read\n - Write\n - Edit\n - Glob\n\n # ── Layer 2: Render preview stills ────────────────────────────────────\n - id: render-preview\n bash: |\n mkdir -p out\n COMP_ID=$(npx remotion compositions src/index.ts 2>&1 | grep -E '^\\S' | head -1 | awk '{print $1}')\n if [ -z \"$COMP_ID\" ]; then\n echo \"RENDER_FAILED: Could not detect composition ID\"\n exit 1\n fi\n echo \"Composition: $COMP_ID\"\n\n DURATION=$(npx remotion compositions src/index.ts 2>&1 | grep -E '^\\S' | head -1 | awk '{print $4}')\n MID_FRAME=$(( ${DURATION:-150} / 2 ))\n LATE_FRAME=$(( ${DURATION:-150} * 3 / 4 ))\n\n echo \"Rendering preview stills at frames 1, $MID_FRAME, $LATE_FRAME...\"\n npx remotion still src/index.ts \"$COMP_ID\" out/preview-early.png --frame=1 2>&1 | tail -2\n npx remotion still src/index.ts \"$COMP_ID\" out/preview-mid.png --frame=$MID_FRAME 2>&1 | tail -2\n npx remotion still src/index.ts \"$COMP_ID\" out/preview-late.png --frame=$LATE_FRAME 2>&1 | tail -2\n RESULT=$?\n\n if [ $RESULT -eq 0 ]; then\n echo \"\"\n echo \"RENDER_SUCCESS\"\n ls -la out/preview-*.png\n else\n echo \"RENDER_FAILED\"\n fi\n depends_on: [generate]\n timeout: 120000\n\n # ── Layer 3: Render full video ────────────────────────────────────────\n - id: render-video\n bash: |\n COMP_ID=$(npx remotion compositions src/index.ts 2>&1 | grep -E '^\\S' | head -1 | awk '{print $1}')\n echo \"Rendering full video: $COMP_ID\"\n npx remotion render src/index.ts \"$COMP_ID\" out/video.mp4 --codec=h264 --crf=18 2>&1 | tail -10\n RESULT=$?\n\n if [ $RESULT -eq 0 ]; then\n echo \"\"\n echo \"VIDEO_RENDER_SUCCESS\"\n ls -la out/video.mp4\n else\n echo \"VIDEO_RENDER_FAILED\"\n fi\n depends_on: [render-preview]\n timeout: 300000\n\n # ── Layer 4: Summary ──────────────────────────────────────────────────\n - id: summary\n prompt: |\n A Remotion video was generated and rendered.\n\n Original request: $ARGUMENTS\n\n Preview render: $render-preview.output\n Video render: $render-video.output\n\n Read the generated composition code and the preview stills (out/preview-early.png,\n out/preview-mid.png, out/preview-late.png) to verify the output.\n\n Summarize:\n 1. What the video contains (based on code and stills)\n 2. Whether the renders succeeded\n 3. Where the output file is (out/video.mp4)\n depends_on: [render-video]\n allowed_tools:\n - Read\n model: haiku\n", + "archon-resolve-conflicts": "name: archon-resolve-conflicts\ndescription: |\n Use when: PR has merge conflicts that need resolution.\n Triggers: \"resolve conflicts\", \"fix merge conflicts\", \"rebase this PR\", \"resolve this\",\n \"fix conflicts\", \"merge conflicts\", \"rebase and fix\".\n Does: Fetches latest base branch -> analyzes conflicts -> auto-resolves simple conflicts ->\n presents options for complex conflicts -> commits and pushes resolution.\n NOT for: PRs without conflicts, general rebasing without conflicts, squashing commits.\n\n This workflow helps resolve merge conflicts by analyzing the conflicting changes,\n automatically resolving where intent is clear, and presenting options for complex conflicts.\n\nnodes:\n - id: resolve\n command: archon-resolve-merge-conflicts\n", + "archon-smart-pr-review": "name: archon-smart-pr-review\ndescription: |\n Use when: User wants a smart, efficient PR review that adapts to PR complexity.\n Triggers: \"smart review\", \"review this PR\", \"review PR #123\", \"efficient review\",\n \"smart PR review\", \"quick review\".\n Does: Gathers PR scope -> classifies complexity -> routes to only relevant review agents ->\n synthesizes findings -> auto-fixes CRITICAL/HIGH issues.\n NOT for: When you explicitly want ALL review agents (use archon-comprehensive-pr-review instead).\n\n Unlike the comprehensive review, this workflow classifies the PR first and only runs\n the review agents that are relevant. A 3-line typo fix skips test-coverage and docs-impact.\n\nnodes:\n - id: scope\n command: archon-pr-review-scope\n\n - id: sync\n command: archon-sync-pr-with-main\n depends_on: [scope]\n\n - id: classify\n prompt: |\n You are a PR complexity classifier. Analyze the PR scope below and determine\n which review agents should run.\n\n ## PR Scope\n $scope.output\n\n ## Rules\n - **Code review**: Always run unless the diff is empty or only touches non-code files\n (e.g. README-only, config-only, or .yaml-only changes).\n - **Error handling**: Run if the diff touches code with try/catch, error handling,\n async/await, or adds new failure paths.\n - **Test coverage**: Run if the diff touches source code (not just tests, docs, or config).\n - **Comment quality**: Run if the diff adds or modifies comments, docstrings, JSDoc,\n or significant documentation within code files.\n - **Docs impact**: Run if the diff adds/removes/renames public APIs, commands, CLI flags,\n environment variables, or user-facing features.\n\n Classify the PR complexity:\n - **trivial**: Typo fixes, formatting, single-line changes, version bumps\n - **small**: 1-3 files, straightforward logic, no architectural changes\n - **medium**: 4-10 files, moderate logic changes, some cross-cutting concerns\n - **large**: 10+ files, architectural changes, new subsystems, complex refactors\n\n Provide your reasoning for each decision.\n depends_on: [scope]\n model: haiku\n allowed_tools: []\n output_format:\n type: object\n properties:\n run_code_review:\n type: string\n enum: [\"true\", \"false\"]\n run_error_handling:\n type: string\n enum: [\"true\", \"false\"]\n run_test_coverage:\n type: string\n enum: [\"true\", \"false\"]\n run_comment_quality:\n type: string\n enum: [\"true\", \"false\"]\n run_docs_impact:\n type: string\n enum: [\"true\", \"false\"]\n complexity:\n type: string\n enum: [\"trivial\", \"small\", \"medium\", \"large\"]\n reasoning:\n type: string\n required:\n - run_code_review\n - run_error_handling\n - run_test_coverage\n - run_comment_quality\n - run_docs_impact\n - complexity\n - reasoning\n\n - id: code-review\n command: archon-code-review-agent\n depends_on: [classify, sync]\n when: \"$classify.output.run_code_review == 'true'\"\n\n - id: error-handling\n command: archon-error-handling-agent\n depends_on: [classify, sync]\n when: \"$classify.output.run_error_handling == 'true'\"\n\n - id: test-coverage\n command: archon-test-coverage-agent\n depends_on: [classify, sync]\n when: \"$classify.output.run_test_coverage == 'true'\"\n\n - id: comment-quality\n command: archon-comment-quality-agent\n depends_on: [classify, sync]\n when: \"$classify.output.run_comment_quality == 'true'\"\n\n - id: docs-impact\n command: archon-docs-impact-agent\n depends_on: [classify, sync]\n when: \"$classify.output.run_docs_impact == 'true'\"\n\n - id: synthesize\n command: archon-synthesize-review\n depends_on: [code-review, error-handling, test-coverage, comment-quality, docs-impact]\n trigger_rule: one_success\n\n - id: implement-fixes\n command: archon-implement-review-fixes\n depends_on: [synthesize]\n\n # Optional: push notification when review completes.\n # To enable, create .archon/mcp/ntfy.json — see docs/mcp-servers.md\n - id: check-ntfy\n bash: \"test -f .archon/mcp/ntfy.json && echo 'true' || echo 'false'\"\n depends_on: [implement-fixes]\n\n - id: notify\n depends_on: [check-ntfy, synthesize, implement-fixes]\n when: \"$check-ntfy.output == 'true'\"\n trigger_rule: all_success\n mcp: .archon/mcp/ntfy.json\n allowed_tools: []\n prompt: |\n Send a push notification summarizing the PR review results.\n\n Review synthesis:\n $synthesize.output\n\n Fix results:\n $implement-fixes.output\n\n Send with:\n - title: \"PR Review Complete\"\n - message: 1-2 sentence summary — verdict and issue count. Short enough for a lock screen.\n - priority: 3 if ready to merge, 4 if needs fixes, 5 if critical issues remain\n", + "archon-test-loop-dag": "name: archon-test-loop-dag\ndescription: |\n Use when: User explicitly says \"test-loop-dag\" or \"run test-loop-dag\".\n IMPORTANT: This is a DAG workflow with a loop node that iterates until completion.\n NOT for: General testing questions or debugging.\n Does: Initializes a counter, iterates until it reaches 3, then reports completion.\n\nnodes:\n - id: setup\n bash: |\n echo \"0\" > .archon/test-loop-dag-counter.txt\n echo \"Counter initialized to 0\"\n\n - id: loop-counter\n depends_on: [setup]\n loop:\n prompt: |\n You are testing the loop node functionality within a DAG workflow.\n\n ## Your Task\n\n 1. Read the file `.archon/test-loop-dag-counter.txt`\n 2. Parse the current counter value\n 3. Increment it by 1\n 4. Write the new value back to the file\n 5. Report the current iteration\n\n ## User Intent\n\n $USER_MESSAGE\n\n ## Completion Criteria\n\n - If the counter reaches 3 or higher, output: COMPLETE\n - Otherwise, just report your progress and end normally\n\n ## Important\n\n Be concise. Just do the task and report the counter value.\n until: COMPLETE\n max_iterations: 5\n fresh_context: false\n\n - id: report\n depends_on: [loop-counter]\n prompt: |\n The loop counter test has completed. The loop node output was:\n\n $loop-counter.output\n\n Read `.archon/test-loop-dag-counter.txt` and confirm the final counter value.\n Report: \"Test loop DAG completed successfully. Final counter: {value}\"\n", + "archon-validate-pr": "name: archon-validate-pr\ndescription: |\n Use when: User wants a thorough PR validation that tests both main (bug present) and feature branch (bug fixed).\n Triggers: \"validate PR\", \"validate pr #123\", \"test this PR\", \"verify PR\", \"full PR validation\",\n \"validate pull request\", \"test PR end-to-end\".\n Does: Fetches PR info -> finds free ports -> parallel code review (main vs feature) ->\n E2E test on main (reproduce bug) -> E2E test on feature (verify fix) -> final verdict report.\n NOT for: Quick code-only reviews (use archon-smart-pr-review), fixing issues, general exploration.\n\n This workflow is designed for running in parallel — each instance finds its own free ports\n to avoid conflicts. Produces artifacts in $ARTIFACTS_DIR/ and posts a validation report.\n\nprovider: claude\nmodel: opus\n\nnodes:\n # ═══════════════════════════════════════════════════════════════\n # PHASE 1: SETUP — Fetch PR info and allocate ports\n # ═══════════════════════════════════════════════════════════════\n\n - id: fetch-pr\n bash: |\n # Extract PR number from arguments\n PR_NUMBER=$(echo \"$ARGUMENTS\" | grep -oE '/pull/[0-9]+' | grep -oE '[0-9]+' | head -1)\n # Fallback: extract first number if no URL path found (e.g., \"validate PR 42\")\n if [ -z \"$PR_NUMBER\" ]; then\n PR_NUMBER=$(echo \"$ARGUMENTS\" | grep -oE '[0-9]+' | head -1)\n fi\n if [ -z \"$PR_NUMBER\" ]; then\n # Try getting PR from current branch\n PR_NUMBER=$(gh pr view --json number -q '.number' 2>/dev/null)\n fi\n\n if [ -z \"$PR_NUMBER\" ]; then\n echo \"ERROR: No PR number found in arguments: $ARGUMENTS\"\n exit 1\n fi\n\n echo \"$PR_NUMBER\" > \"$ARTIFACTS_DIR/.pr-number\"\n\n # Fetch full PR details\n gh pr view \"$PR_NUMBER\" --json number,title,body,url,headRefName,baseRefName,files,additions,deletions,changedFiles,state,author,labels,isDraft\n\n - id: find-ports\n bash: |\n # Use Bun to let the OS pick truly free ports (cross-platform: Linux, macOS, Windows)\n BACKEND_PORT=$(bun -e \"const s = Bun.serve({port: 0, fetch: () => new Response('')}); console.log(s.port); s.stop()\")\n FRONTEND_PORT=$(bun -e \"const s = Bun.serve({port: 0, fetch: () => new Response('')}); console.log(s.port); s.stop()\")\n\n echo \"$BACKEND_PORT\" > \"$ARTIFACTS_DIR/.backend-port\"\n echo \"$FRONTEND_PORT\" > \"$ARTIFACTS_DIR/.frontend-port\"\n\n echo \"BACKEND_PORT=$BACKEND_PORT\"\n echo \"FRONTEND_PORT=$FRONTEND_PORT\"\n\n - id: resolve-paths\n bash: |\n # Resolve canonical repo path (main branch) vs worktree path (feature branch)\n CANONICAL_REPO=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null | sed 's|/\\.git$||')\n WORKTREE_PATH=$(pwd)\n FEATURE_BRANCH=$(git branch --show-current)\n\n # Get PR branch info\n PR_NUMBER=$(cat \"$ARTIFACTS_DIR/.pr-number\")\n PR_HEAD=$(gh pr view \"$PR_NUMBER\" --json headRefName -q '.headRefName')\n PR_BASE=$(gh pr view \"$PR_NUMBER\" --json baseRefName -q '.baseRefName')\n\n echo \"$CANONICAL_REPO\" > \"$ARTIFACTS_DIR/.canonical-repo\"\n echo \"$WORKTREE_PATH\" > \"$ARTIFACTS_DIR/.worktree-path\"\n echo \"$FEATURE_BRANCH\" > \"$ARTIFACTS_DIR/.feature-branch\"\n echo \"$PR_HEAD\" > \"$ARTIFACTS_DIR/.pr-head\"\n echo \"$PR_BASE\" > \"$ARTIFACTS_DIR/.pr-base\"\n\n echo \"CANONICAL_REPO=$CANONICAL_REPO\"\n echo \"WORKTREE_PATH=$WORKTREE_PATH\"\n echo \"FEATURE_BRANCH=$FEATURE_BRANCH\"\n echo \"PR_HEAD=$PR_HEAD\"\n echo \"PR_BASE=$PR_BASE\"\n depends_on: [fetch-pr]\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 2: CODE REVIEW — Parallel analysis of main vs feature\n # ═══════════════════════════════════════════════════════════════\n\n - id: code-review-main\n command: archon-validate-pr-code-review-main\n depends_on: [fetch-pr, resolve-paths]\n context: fresh\n\n - id: code-review-feature\n command: archon-validate-pr-code-review-feature\n depends_on: [fetch-pr, resolve-paths, code-review-main]\n context: fresh\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 3: E2E TESTING — Sequential (after code reviews finish)\n # ═══════════════════════════════════════════════════════════════\n\n - id: classify-testability\n prompt: |\n You are a PR testability classifier. Determine whether this PR's changes can be\n validated via browser E2E testing, or if it requires code-review-only validation.\n\n ## PR Details\n\n $fetch-pr.output\n\n ## Rules\n\n - **e2e_testable**: Changes affect the Web UI (components, hooks, styles, API routes\n that serve the frontend, SSE streaming, layout, user-visible behavior). These can be\n validated by starting Archon and using agent-browser to interact with the UI.\n - **code_review_only**: Changes are purely backend logic, CLI-only, workflow engine,\n database schemas, git operations, build tooling, tests, documentation, or other\n non-UI code. No visual validation possible.\n\n Consider: even if a change is backend, if it affects what the frontend displays\n (e.g., API response format changes, SSE event changes), it IS e2e_testable.\n depends_on: [fetch-pr]\n model: haiku\n allowed_tools: []\n output_format:\n type: object\n properties:\n testable:\n type: string\n enum: [\"e2e_testable\", \"code_review_only\"]\n reasoning:\n type: string\n test_plan:\n type: string\n required: [testable, reasoning, test_plan]\n\n - id: e2e-test-main\n command: archon-validate-pr-e2e-main\n depends_on: [classify-testability, find-ports, resolve-paths, code-review-main, code-review-feature]\n when: \"$classify-testability.output.testable == 'e2e_testable'\"\n context: fresh\n idle_timeout: 1800000\n\n - id: e2e-test-feature\n command: archon-validate-pr-e2e-feature\n depends_on: [e2e-test-main, find-ports, resolve-paths]\n when: \"$classify-testability.output.testable == 'e2e_testable'\"\n context: fresh\n idle_timeout: 1800000\n\n # ═══════════════════════════════════════════════════════════════\n # PHASE 4: FINAL REPORT — Synthesize all findings\n # ═══════════════════════════════════════════════════════════════\n\n - id: cleanup-processes\n bash: |\n # Safety net: kill any orphaned processes from E2E testing\n # This runs after E2E nodes complete (or timeout/fail) to prevent process accumulation\n BACKEND_PORT=$(cat \"$ARTIFACTS_DIR/.backend-port\" 2>/dev/null | tr -d '\\n')\n FRONTEND_PORT=$(cat \"$ARTIFACTS_DIR/.frontend-port\" 2>/dev/null | tr -d '\\n')\n\n if [ -z \"$BACKEND_PORT\" ] || [ -z \"$FRONTEND_PORT\" ]; then\n echo \"No port files found — skipping cleanup\"\n exit 0\n fi\n\n echo \"Cleaning up ports $BACKEND_PORT and $FRONTEND_PORT...\"\n\n # Kill by all recorded PID files\n for pidfile in \"$ARTIFACTS_DIR\"/.e2e-*-pid; do\n if [ -f \"$pidfile\" ]; then\n PID=$(cat \"$pidfile\" | tr -d '\\n')\n echo \"Killing PID $PID from $pidfile\"\n kill \"$PID\" 2>/dev/null || taskkill //F //T //PID \"$PID\" 2>/dev/null || true\n fi\n done\n\n # Kill by port (cross-platform fallback)\n for PORT in $BACKEND_PORT $FRONTEND_PORT; do\n fuser -k \"$PORT/tcp\" 2>/dev/null || true\n lsof -ti:\"$PORT\" 2>/dev/null | xargs kill -9 2>/dev/null || true\n netstat -ano 2>/dev/null | grep \":$PORT \" | grep LISTENING | awk '{print $5}' | sort -u | while read pid; do\n taskkill //F //T //PID \"$pid\" 2>/dev/null || true\n done\n done\n\n # pkill fallback: catch processes that escaped PID/port cleanup\n pkill -f \"PORT=$BACKEND_PORT.*bun\" 2>/dev/null || true\n pkill -f \"vite.*port.*$FRONTEND_PORT\" 2>/dev/null || true\n\n # Close this workflow's browser session only (scoped by session ID)\n BROWSER_SESSION=$(cat \"$ARTIFACTS_DIR/.browser-session\" 2>/dev/null | tr -d '\\n')\n if [ -n \"$BROWSER_SESSION\" ]; then\n agent-browser --session \"$BROWSER_SESSION\" close 2>/dev/null || true\n fi\n\n # Remove main E2E worktree if it still exists (safety net)\n CANONICAL_REPO=$(cat \"$ARTIFACTS_DIR/.canonical-repo\" 2>/dev/null | tr -d '\\n')\n MAIN_E2E_PATH=$(cat \"$ARTIFACTS_DIR/.e2e-main-worktree\" 2>/dev/null | tr -d '\\n')\n if [ -n \"$MAIN_E2E_PATH\" ] && [ -n \"$CANONICAL_REPO\" ] && [ -d \"$MAIN_E2E_PATH\" ]; then\n echo \"Removing leftover main E2E worktree: $MAIN_E2E_PATH\"\n git -C \"$CANONICAL_REPO\" worktree remove \"$MAIN_E2E_PATH\" --force 2>/dev/null || rm -rf \"$MAIN_E2E_PATH\"\n fi\n\n sleep 1\n echo \"Process cleanup complete\"\n depends_on: [e2e-test-main, e2e-test-feature]\n trigger_rule: all_done\n\n - id: final-report\n command: archon-validate-pr-report\n depends_on: [code-review-main, code-review-feature, e2e-test-main, e2e-test-feature, classify-testability, cleanup-processes]\n trigger_rule: all_done\n context: fresh\n", + "archon-workflow-builder": "name: archon-workflow-builder\ndescription: |\n Use when: User wants to create a new custom workflow for their project.\n Triggers: \"build me a workflow\", \"create a workflow\", \"generate a workflow\",\n \"new workflow\", \"make a workflow for\", \"workflow builder\".\n Does: Scans codebase -> extracts intent (JSON) -> generates YAML -> validates -> saves.\n NOT for: Editing existing workflows or creating non-workflow files.\n\nnodes:\n - id: scan-codebase\n bash: |\n echo \"=== Existing Commands ===\"\n if [ -d \".archon/commands\" ]; then\n find .archon/commands -type f -name \"*.md\" 2>/dev/null | head -30\n else\n echo \"(no .archon/commands/ directory)\"\n fi\n\n echo \"\"\n echo \"=== Existing Workflows ===\"\n if [ -d \".archon/workflows\" ]; then\n find .archon/workflows -type f \\( -name \"*.yaml\" -o -name \"*.yml\" \\) 2>/dev/null | head -30\n else\n echo \"(no .archon/workflows/ directory)\"\n fi\n\n echo \"\"\n echo \"=== Package Info ===\"\n if [ -f \"package.json\" ]; then\n grep -E '\"name\"|\"scripts\"' package.json | head -10\n else\n echo \"(no package.json)\"\n fi\n\n echo \"\"\n echo \"=== Project Context (CLAUDE.md first 50 lines) ===\"\n if [ -f \"CLAUDE.md\" ]; then\n head -50 CLAUDE.md\n else\n echo \"(no CLAUDE.md)\"\n fi\n\n - id: extract-intent\n prompt: |\n You are a workflow design classifier. Given a user's description of what they want\n a workflow to do, extract structured intent.\n\n ## User's Request\n $ARGUMENTS\n\n ## Codebase Context\n $scan-codebase.output\n\n ## Instructions\n\n Analyze the user's request and the existing codebase to determine:\n 1. A kebab-case workflow name (e.g., \"lint-and-test\", \"deploy-staging\")\n 2. A description following the Archon pattern (Use when / Triggers / Does / NOT for)\n 3. Trigger phrases the router should match\n 4. A list of proposed nodes with their types and purposes\n 5. Whether this should be a simple DAG or include a loop node\n\n Be specific and concrete. Each proposed node should have a clear type\n (bash, prompt, command, or loop) and a one-line description of what it does.\n model: haiku\n allowed_tools: []\n output_format:\n type: object\n properties:\n workflow_name:\n type: string\n description:\n type: string\n trigger_phrases:\n type: string\n proposed_nodes:\n type: string\n execution_mode:\n type: string\n enum: [\"dag\", \"loop\"]\n required: [workflow_name, description, trigger_phrases, proposed_nodes, execution_mode]\n depends_on: [scan-codebase]\n\n - id: generate-yaml\n prompt: |\n You are an Archon workflow author. Generate a complete, valid workflow YAML file\n based on the structured intent provided.\n\n ## Intent\n - **Name**: $extract-intent.output.workflow_name\n - **Description**: $extract-intent.output.description\n - **Trigger Phrases**: $extract-intent.output.trigger_phrases\n - **Proposed Nodes**: $extract-intent.output.proposed_nodes\n - **Execution Mode**: $extract-intent.output.execution_mode\n\n ## Original User Request\n $ARGUMENTS\n\n ## Archon Workflow YAML Schema Reference\n\n A workflow YAML file has this structure:\n\n ```yaml\n name: workflow-name\n description: |\n Use when: ...\n Triggers: ...\n Does: ...\n NOT for: ...\n\n # Optional top-level settings:\n # provider: claude (or codex)\n # model: sonnet (or haiku, opus, etc.)\n # interactive: true (forces foreground execution in web UI)\n\n nodes:\n - id: node-id-kebab-case\n # Choose ONE of: prompt, bash, command, loop\n\n # --- prompt node (AI-executed) ---\n prompt: |\n Instructions for the AI...\n # Optional: model, allowed_tools, denied_tools, output_format, context, idle_timeout\n\n # --- bash node (shell script, no AI, stdout = $.output) ---\n bash: |\n #!/bin/bash\n set -e\n echo \"result\"\n\n # --- command node (references a .archon/commands/ file) ---\n command: command-name\n\n # --- loop node (iterative AI execution) ---\n loop:\n prompt: |\n Instructions repeated each iteration...\n until: COMPLETION_SIGNAL\n max_iterations: 10\n fresh_context: true # optional: reset context each iteration\n\n # Common options for all node types:\n depends_on: [other-node-id] # DAG edges\n when: \"$.output == 'value'\" # conditional execution\n trigger_rule: all_success # all_success | one_success | all_done\n timeout: 120000 # ms, for bash nodes\n ```\n\n ## Variable Reference\n - `$ARGUMENTS` — user's input text\n - `$ARTIFACTS_DIR` — pre-created directory for workflow artifacts\n - `$.output` — stdout from a bash node or AI response from a prompt node\n - `$.output.field` — JSON field from a node with output_format\n - `$BASE_BRANCH` — base git branch\n\n ## Rules\n 1. The `name:` field MUST match: $extract-intent.output.workflow_name\n 2. The `description:` MUST follow the \"Use when / Triggers / Does / NOT for\" pattern\n 3. Every node MUST have a unique kebab-case `id`\n 4. Use `depends_on` to define execution order\n 5. Use `bash` nodes for deterministic operations (file checks, git commands, installs)\n 6. Use `prompt` nodes for AI reasoning tasks\n 7. Use `output_format` on prompt nodes when downstream nodes need structured data\n 8. Use `allowed_tools: []` on classification/analysis nodes that don't need tools\n 9. Use `denied_tools: [Edit, Bash]` when a node should only use Write (not edit existing files)\n 10. Prefer `model: haiku` for simple classification tasks to save cost\n\n ## Output\n\n Write the complete workflow YAML to: `$ARTIFACTS_DIR/generated-workflow.yaml`\n\n Use the Write tool. Do NOT use Edit or Bash. The file must be valid YAML and follow\n all the patterns above.\n denied_tools: [Edit, Bash]\n depends_on: [extract-intent]\n\n - id: validate-yaml\n bash: |\n FILE=\"$ARTIFACTS_DIR/generated-workflow.yaml\"\n\n if [ ! -f \"$FILE\" ]; then\n echo \"ERROR: generated-workflow.yaml not found at $FILE\"\n exit 1\n fi\n\n if [ ! -s \"$FILE\" ]; then\n echo \"ERROR: generated-workflow.yaml is empty\"\n exit 1\n fi\n\n if ! grep -q \"^name:\" \"$FILE\"; then\n echo \"ERROR: missing 'name:' field\"\n exit 1\n fi\n\n if ! grep -q \"^nodes:\" \"$FILE\"; then\n echo \"ERROR: missing 'nodes:' field\"\n exit 1\n fi\n\n echo \"VALID\"\n depends_on: [generate-yaml]\n\n - id: save-or-report\n prompt: |\n You are a workflow installer. Save the generated workflow and report to the user.\n\n ## Workflow Details\n - **Name**: $extract-intent.output.workflow_name\n - **Trigger Phrases**: $extract-intent.output.trigger_phrases\n\n ## Instructions\n\n 1. Read the generated workflow from `$ARTIFACTS_DIR/generated-workflow.yaml`\n 2. Create the directory `.archon/workflows/` if it doesn't exist (use Bash: `mkdir -p .archon/workflows/`)\n 3. Save the workflow to `.archon/workflows/$extract-intent.output.workflow_name.yaml`\n Use the Write tool to write the file.\n 4. Report to the user:\n - Workflow name and file location\n - Trigger phrases that will invoke it\n - How to run it: `bun run cli workflow run $extract-intent.output.workflow_name \"your input\"`\n - How to test it: `bun run cli validate workflows $extract-intent.output.workflow_name`\n depends_on: [validate-yaml]\n", +}; diff --git a/packages/workflows/src/defaults/bundled-defaults.test.ts b/packages/workflows/src/defaults/bundled-defaults.test.ts index e1e1cb5a..25855d98 100644 --- a/packages/workflows/src/defaults/bundled-defaults.test.ts +++ b/packages/workflows/src/defaults/bundled-defaults.test.ts @@ -1,6 +1,15 @@ import { describe, it, expect } from 'bun:test'; +import { readFileSync, readdirSync } from 'fs'; +import { join } from 'path'; import { isBinaryBuild, BUNDLED_COMMANDS, BUNDLED_WORKFLOWS } from './bundled-defaults'; +// Resolve the on-disk defaults directories relative to this test file so the +// tests work regardless of cwd. From packages/workflows/src/defaults go up +// four levels to the repo root, then into .archon/. +const REPO_ROOT = join(import.meta.dir, '..', '..', '..', '..'); +const COMMANDS_DIR = join(REPO_ROOT, '.archon/commands/defaults'); +const WORKFLOWS_DIR = join(REPO_ROOT, '.archon/workflows/defaults'); + describe('bundled-defaults', () => { describe('isBinaryBuild', () => { it('should return false in dev/test mode', () => { @@ -12,57 +21,54 @@ describe('bundled-defaults', () => { }); }); + describe('bundle completeness', () => { + // These assertions are the canary for bundle drift: if someone adds a + // default file without regenerating bundled-defaults.generated.ts, the + // bundle would be missing in compiled binaries (see #979 context). The + // generator is `scripts/generate-bundled-defaults.ts`, and + // `bun run check:bundled` verifies the generated file is up to date. + + it('BUNDLED_COMMANDS contains every .md file in .archon/commands/defaults/', () => { + const onDisk = readdirSync(COMMANDS_DIR) + .filter(f => f.endsWith('.md')) + .map(f => f.slice(0, -'.md'.length)) + .sort(); + expect(Object.keys(BUNDLED_COMMANDS).sort()).toEqual(onDisk); + }); + + it('BUNDLED_WORKFLOWS contains every .yaml/.yml file in .archon/workflows/defaults/', () => { + const onDisk = readdirSync(WORKFLOWS_DIR) + .filter(f => f.endsWith('.yaml') || f.endsWith('.yml')) + .map(f => f.replace(/\.ya?ml$/, '')) + .sort(); + expect(Object.keys(BUNDLED_WORKFLOWS).sort()).toEqual(onDisk); + }); + + it('bundled content matches on-disk file content (defense against generator corruption)', () => { + for (const [name, content] of Object.entries(BUNDLED_COMMANDS)) { + const diskContent = readFileSync(join(COMMANDS_DIR, `${name}.md`), 'utf-8'); + expect(content).toBe(diskContent); + } + for (const [name, content] of Object.entries(BUNDLED_WORKFLOWS)) { + // Workflows may be .yaml or .yml — prefer .yaml, fall back. + let diskContent: string; + try { + diskContent = readFileSync(join(WORKFLOWS_DIR, `${name}.yaml`), 'utf-8'); + } catch { + diskContent = readFileSync(join(WORKFLOWS_DIR, `${name}.yml`), 'utf-8'); + } + expect(content).toBe(diskContent); + } + }); + }); + describe('BUNDLED_COMMANDS', () => { - it('should have all expected default commands', () => { - const expectedCommands = [ - 'archon-assist', - 'archon-code-review-agent', - 'archon-comment-quality-agent', - 'archon-create-pr', - 'archon-docs-impact-agent', - 'archon-error-handling-agent', - 'archon-implement-issue', - 'archon-implement-review-fixes', - 'archon-implement', - 'archon-investigate-issue', - 'archon-pr-review-scope', - 'archon-ralph-prd', - 'archon-resolve-merge-conflicts', - 'archon-sync-pr-with-main', - 'archon-synthesize-review', - 'archon-test-coverage-agent', - 'archon-validate-pr-code-review-feature', - 'archon-validate-pr-code-review-main', - 'archon-validate-pr-e2e-feature', - 'archon-validate-pr-e2e-main', - 'archon-validate-pr-report', - ]; - - for (const cmd of expectedCommands) { - expect(BUNDLED_COMMANDS).toHaveProperty(cmd); - } - - expect(Object.keys(BUNDLED_COMMANDS)).toHaveLength(21); - }); - - it('should have non-empty content for all commands', () => { - for (const [name, content] of Object.entries(BUNDLED_COMMANDS)) { - expect(content).toBeDefined(); - expect(typeof content).toBe('string'); - expect(content.length).toBeGreaterThan(0); - // Commands should have meaningful content (at least some markdown) + it('every command has meaningful content (>50 chars)', () => { + for (const content of Object.values(BUNDLED_COMMANDS)) { expect(content.length).toBeGreaterThan(50); } }); - it('should have markdown content format', () => { - // Commands are markdown files, should have typical markdown patterns - for (const [name, content] of Object.entries(BUNDLED_COMMANDS)) { - // Should contain some text (not just whitespace) - expect(content.trim().length).toBeGreaterThan(0); - } - }); - it('archon-pr-review-scope should read .pr-number before other discovery', () => { const content = BUNDLED_COMMANDS['archon-pr-review-scope']; expect(content).toContain('$ARTIFACTS_DIR/.pr-number'); @@ -76,36 +82,8 @@ describe('bundled-defaults', () => { }); describe('BUNDLED_WORKFLOWS', () => { - it('should have all expected default workflows', () => { - const expectedWorkflows = [ - 'archon-assist', - 'archon-comprehensive-pr-review', - 'archon-create-issue', - 'archon-feature-development', - 'archon-fix-github-issue', - 'archon-resolve-conflicts', - 'archon-smart-pr-review', - 'archon-validate-pr', - 'archon-remotion-generate', - 'archon-interactive-prd', - 'archon-piv-loop', - 'archon-adversarial-dev', - 'archon-workflow-builder', - ]; - - for (const wf of expectedWorkflows) { - expect(BUNDLED_WORKFLOWS).toHaveProperty(wf); - } - - expect(Object.keys(BUNDLED_WORKFLOWS)).toHaveLength(13); - }); - - it('should have non-empty content for all workflows', () => { - for (const [name, content] of Object.entries(BUNDLED_WORKFLOWS)) { - expect(content).toBeDefined(); - expect(typeof content).toBe('string'); - expect(content.length).toBeGreaterThan(0); - // Workflows should have meaningful YAML content + it('every workflow has meaningful content (>50 chars)', () => { + for (const content of Object.values(BUNDLED_WORKFLOWS)) { expect(content.length).toBeGreaterThan(50); } }); @@ -120,15 +98,10 @@ describe('bundled-defaults', () => { }); it('should have valid YAML structure', () => { - // Workflows are YAML files, should parse without error - for (const [name, content] of Object.entries(BUNDLED_WORKFLOWS)) { - // Should contain 'name:' as all workflows require a name field + for (const content of Object.values(BUNDLED_WORKFLOWS)) { expect(content).toContain('name:'); - // Should contain 'description:' as all workflows require description expect(content).toContain('description:'); - // Should contain nodes: (with optional loop: inside nodes) - const hasNodes = content.includes('nodes:'); - expect(hasNodes).toBe(true); + expect(content.includes('nodes:')).toBe(true); } }); }); diff --git a/packages/workflows/src/defaults/bundled-defaults.ts b/packages/workflows/src/defaults/bundled-defaults.ts index a921171b..bbfcfae7 100644 --- a/packages/workflows/src/defaults/bundled-defaults.ts +++ b/packages/workflows/src/defaults/bundled-defaults.ts @@ -1,108 +1,28 @@ /** - * Bundled default commands and workflows for binary distribution + * Bundled default commands and workflows for binary distribution. * - * These static imports are resolved at compile time and embedded into the binary. - * When running as a standalone binary (without Bun), these provide the default - * commands and workflows without needing filesystem access to the source repo. + * Content lives in `bundled-defaults.generated.ts`, which is regenerated from + * `.archon/{commands,workflows}/defaults/` by `scripts/generate-bundled-defaults.ts`. + * This file is the hand-written facade: it re-exports the records and defines + * the binary-detection helper. * - * Import syntax uses `with { type: 'text' }` to import file contents as strings. + * Why two files: + * - Generated file is pure data — never hand-edited, diff on PRs shows + * exactly which defaults changed. + * - Facade keeps the documented `isBinaryBuild()` wrapper in a file that + * humans own. + * + * Why inline strings (and not `import X from '...file.md' with { type: 'text' }`)? + * - Node cannot load `type: 'text'` import attributes — it's Bun-specific. + * Using plain string literals keeps `@archon/workflows` importable from + * both runtimes, which removes SDK blocker #2. + * - Bun still embeds the data at compile time when building the CLI binary, + * so runtime behavior is unchanged. */ import { BUNDLED_IS_BINARY } from '@archon/paths'; -// ============================================================================= -// Default Commands (21 total) -// ============================================================================= - -import archonAssistCmd from '../../../../.archon/commands/defaults/archon-assist.md' with { type: 'text' }; -import archonCodeReviewAgentCmd from '../../../../.archon/commands/defaults/archon-code-review-agent.md' with { type: 'text' }; -import archonCommentQualityAgentCmd from '../../../../.archon/commands/defaults/archon-comment-quality-agent.md' with { type: 'text' }; -import archonCreatePrCmd from '../../../../.archon/commands/defaults/archon-create-pr.md' with { type: 'text' }; -import archonDocsImpactAgentCmd from '../../../../.archon/commands/defaults/archon-docs-impact-agent.md' with { type: 'text' }; -import archonErrorHandlingAgentCmd from '../../../../.archon/commands/defaults/archon-error-handling-agent.md' with { type: 'text' }; -import archonImplementIssueCmd from '../../../../.archon/commands/defaults/archon-implement-issue.md' with { type: 'text' }; -import archonImplementReviewFixesCmd from '../../../../.archon/commands/defaults/archon-implement-review-fixes.md' with { type: 'text' }; -import archonImplementCmd from '../../../../.archon/commands/defaults/archon-implement.md' with { type: 'text' }; -import archonInvestigateIssueCmd from '../../../../.archon/commands/defaults/archon-investigate-issue.md' with { type: 'text' }; -import archonPrReviewScopeCmd from '../../../../.archon/commands/defaults/archon-pr-review-scope.md' with { type: 'text' }; -import archonRalphPrdCmd from '../../../../.archon/commands/defaults/archon-ralph-prd.md' with { type: 'text' }; -import archonResolveMergeConflictsCmd from '../../../../.archon/commands/defaults/archon-resolve-merge-conflicts.md' with { type: 'text' }; -import archonSyncPrWithMainCmd from '../../../../.archon/commands/defaults/archon-sync-pr-with-main.md' with { type: 'text' }; -import archonSynthesizeReviewCmd from '../../../../.archon/commands/defaults/archon-synthesize-review.md' with { type: 'text' }; -import archonTestCoverageAgentCmd from '../../../../.archon/commands/defaults/archon-test-coverage-agent.md' with { type: 'text' }; -import archonValidatePrCodeReviewFeatureCmd from '../../../../.archon/commands/defaults/archon-validate-pr-code-review-feature.md' with { type: 'text' }; -import archonValidatePrCodeReviewMainCmd from '../../../../.archon/commands/defaults/archon-validate-pr-code-review-main.md' with { type: 'text' }; -import archonValidatePrE2eFeatureCmd from '../../../../.archon/commands/defaults/archon-validate-pr-e2e-feature.md' with { type: 'text' }; -import archonValidatePrE2eMainCmd from '../../../../.archon/commands/defaults/archon-validate-pr-e2e-main.md' with { type: 'text' }; -import archonValidatePrReportCmd from '../../../../.archon/commands/defaults/archon-validate-pr-report.md' with { type: 'text' }; - -// ============================================================================= -// Default Workflows (13 total) -// ============================================================================= - -import archonAssistWf from '../../../../.archon/workflows/defaults/archon-assist.yaml' with { type: 'text' }; -import archonComprehensivePrReviewWf from '../../../../.archon/workflows/defaults/archon-comprehensive-pr-review.yaml' with { type: 'text' }; -import archonCreateIssueWf from '../../../../.archon/workflows/defaults/archon-create-issue.yaml' with { type: 'text' }; -import archonFeatureDevelopmentWf from '../../../../.archon/workflows/defaults/archon-feature-development.yaml' with { type: 'text' }; -import archonFixGithubIssueWf from '../../../../.archon/workflows/defaults/archon-fix-github-issue.yaml' with { type: 'text' }; -import archonResolveConflictsWf from '../../../../.archon/workflows/defaults/archon-resolve-conflicts.yaml' with { type: 'text' }; -import archonSmartPrReviewWf from '../../../../.archon/workflows/defaults/archon-smart-pr-review.yaml' with { type: 'text' }; -import archonValidatePrWf from '../../../../.archon/workflows/defaults/archon-validate-pr.yaml' with { type: 'text' }; -import archonRemotionGenerateWf from '../../../../.archon/workflows/defaults/archon-remotion-generate.yaml' with { type: 'text' }; -import archonInteractivePrdWf from '../../../../.archon/workflows/defaults/archon-interactive-prd.yaml' with { type: 'text' }; -import archonPivLoopWf from '../../../../.archon/workflows/defaults/archon-piv-loop.yaml' with { type: 'text' }; -import archonAdversarialDevWf from '../../../../.archon/workflows/defaults/archon-adversarial-dev.yaml' with { type: 'text' }; -import archonWorkflowBuilderWf from '../../../../.archon/workflows/defaults/archon-workflow-builder.yaml' with { type: 'text' }; - -// ============================================================================= -// Exports -// ============================================================================= - -/** - * Bundled default commands - filename (without extension) -> content - */ -export const BUNDLED_COMMANDS: Record = { - 'archon-assist': archonAssistCmd, - 'archon-code-review-agent': archonCodeReviewAgentCmd, - 'archon-comment-quality-agent': archonCommentQualityAgentCmd, - 'archon-create-pr': archonCreatePrCmd, - 'archon-docs-impact-agent': archonDocsImpactAgentCmd, - 'archon-error-handling-agent': archonErrorHandlingAgentCmd, - 'archon-implement-issue': archonImplementIssueCmd, - 'archon-implement-review-fixes': archonImplementReviewFixesCmd, - 'archon-implement': archonImplementCmd, - 'archon-investigate-issue': archonInvestigateIssueCmd, - 'archon-pr-review-scope': archonPrReviewScopeCmd, - 'archon-ralph-prd': archonRalphPrdCmd, - 'archon-resolve-merge-conflicts': archonResolveMergeConflictsCmd, - 'archon-sync-pr-with-main': archonSyncPrWithMainCmd, - 'archon-synthesize-review': archonSynthesizeReviewCmd, - 'archon-test-coverage-agent': archonTestCoverageAgentCmd, - 'archon-validate-pr-code-review-feature': archonValidatePrCodeReviewFeatureCmd, - 'archon-validate-pr-code-review-main': archonValidatePrCodeReviewMainCmd, - 'archon-validate-pr-e2e-feature': archonValidatePrE2eFeatureCmd, - 'archon-validate-pr-e2e-main': archonValidatePrE2eMainCmd, - 'archon-validate-pr-report': archonValidatePrReportCmd, -}; - -/** - * Bundled default workflows - filename (without extension) -> content - */ -export const BUNDLED_WORKFLOWS: Record = { - 'archon-assist': archonAssistWf, - 'archon-comprehensive-pr-review': archonComprehensivePrReviewWf, - 'archon-create-issue': archonCreateIssueWf, - 'archon-feature-development': archonFeatureDevelopmentWf, - 'archon-fix-github-issue': archonFixGithubIssueWf, - 'archon-resolve-conflicts': archonResolveConflictsWf, - 'archon-smart-pr-review': archonSmartPrReviewWf, - 'archon-validate-pr': archonValidatePrWf, - 'archon-remotion-generate': archonRemotionGenerateWf, - 'archon-interactive-prd': archonInteractivePrdWf, - 'archon-piv-loop': archonPivLoopWf, - 'archon-adversarial-dev': archonAdversarialDevWf, - 'archon-workflow-builder': archonWorkflowBuilderWf, -}; +export { BUNDLED_COMMANDS, BUNDLED_WORKFLOWS } from './bundled-defaults.generated'; /** * Check if the current process is running as a compiled binary (not via Bun CLI). @@ -115,7 +35,7 @@ export const BUNDLED_WORKFLOWS: Record = { * so tests can use `spyOn(bundledDefaults, 'isBinaryBuild').mockReturnValue(...)` * without resorting to `mock.module('@archon/paths', ...)` — which is * process-global and irreversible in Bun and would pollute other test files. - * See `.claude/rules/dx-quirks.md` and `loader.test.ts` for context. + * See `loader.test.ts` for context. */ export function isBinaryBuild(): boolean { return BUNDLED_IS_BINARY; diff --git a/scripts/build-binaries.sh b/scripts/build-binaries.sh index c683c47a..8b9cd086 100755 --- a/scripts/build-binaries.sh +++ b/scripts/build-binaries.sh @@ -21,6 +21,12 @@ OUTFILE="${OUTFILE:-}" echo "Building Archon CLI v${VERSION} (commit: ${GIT_COMMIT})" +# Regenerate bundled defaults from .archon/{commands,workflows}/defaults/ so the +# compiled binary always embeds the current on-disk contents. CI also runs +# `bun run check:bundled` to catch committed drift. +echo "Regenerating bundled defaults..." +bun run scripts/generate-bundled-defaults.ts + # Update build-time constants in source before compiling. # The file is restored via an EXIT trap so the dev tree is never left dirty, # even if `bun build --compile` fails mid-way. See GitHub issue #979. diff --git a/scripts/generate-bundled-defaults.ts b/scripts/generate-bundled-defaults.ts new file mode 100644 index 00000000..afd941cc --- /dev/null +++ b/scripts/generate-bundled-defaults.ts @@ -0,0 +1,172 @@ +#!/usr/bin/env bun +/** + * Regenerates packages/workflows/src/defaults/bundled-defaults.generated.ts from + * the on-disk defaults in .archon/commands/defaults/ and .archon/workflows/defaults/. + * + * Emits inline string literals (via JSON.stringify) rather than Bun's + * `import X from '...' with { type: 'text' }` attributes so the module loads + * in Node too. This fixes two problems at once: + * - bundle drift (hand-maintained import list in bundled-defaults.ts) + * - SDK blocker #2 (type: 'text' import attributes are Bun-specific) + * + * Determinism: filenames are sorted before emission so `bun run check:bundled` + * (which regenerates into memory and compares to the committed file) catches + * unregenerated changes. Wired into `bun run validate` and CI. + * + * Usage: + * bun run scripts/generate-bundled-defaults.ts # write + * bun run scripts/generate-bundled-defaults.ts --check # verify (exit 2 if stale) + * + * Exit codes: + * 0 file generated (and unchanged, if --check) + * 1 unexpected error (missing dir, unreadable source, invalid filename, etc.) + * 2 --check was passed and the file would change + */ +import { access, readFile, readdir, writeFile } from 'fs/promises'; +import { join, resolve } from 'path'; + +const REPO_ROOT = resolve(import.meta.dir, '..'); +const COMMANDS_DIR = join(REPO_ROOT, '.archon/commands/defaults'); +const WORKFLOWS_DIR = join(REPO_ROOT, '.archon/workflows/defaults'); +const OUTPUT_PATH = join( + REPO_ROOT, + 'packages/workflows/src/defaults/bundled-defaults.generated.ts' +); + +const CHECK_ONLY = process.argv.includes('--check'); + +interface BundledFile { + name: string; + content: string; +} + +async function ensureDir(dir: string, label: string): Promise { + try { + await access(dir); + } catch { + throw new Error( + `${label} directory not found: ${dir}\n` + + `Run this script from the repo root (cwd was ${process.cwd()}), ` + + 'or verify the .archon/ tree exists.' + ); + } +} + +async function collectFiles(dir: string, extensions: readonly string[]): Promise { + const entries = await readdir(dir); + const matched = entries + .map(entry => { + const ext = extensions.find(e => entry.endsWith(e)); + return ext ? { entry, ext } : undefined; + }) + .filter((m): m is { entry: string; ext: string } => m !== undefined) + .sort((a, b) => a.entry.localeCompare(b.entry)); + + const files: BundledFile[] = []; + const seen = new Set(); + for (const { entry, ext } of matched) { + const name = entry.slice(0, -ext.length); + if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) { + throw new Error( + `Bundled default has invalid filename "${entry}" in ${dir}. ` + + 'Names must be kebab-case (lowercase letters, digits, hyphens).' + ); + } + if (seen.has(name)) { + throw new Error( + `Bundled default name collision: "${name}" appears with multiple extensions in ${dir}. ` + + 'Keep a single file per name (remove either the .yaml or .yml variant).' + ); + } + seen.add(name); + const content = await readFile(join(dir, entry), 'utf-8'); + if (!content.trim()) { + throw new Error(`Bundled default "${entry}" in ${dir} is empty.`); + } + files.push({ name, content }); + } + return files; +} + +function renderRecord(comment: string, exportName: string, files: BundledFile[]): string { + const entries = files + .map(f => ` ${JSON.stringify(f.name)}: ${JSON.stringify(f.content)},`) + .join('\n'); + return [ + `// ${comment} (${files.length} total)`, + `export const ${exportName}: Record = {`, + entries, + '};', + ].join('\n'); +} + +function renderFile(commands: BundledFile[], workflows: BundledFile[]): string { + const header = [ + '/**', + ' * AUTO-GENERATED — DO NOT EDIT.', + ' *', + ' * Regenerate with: bun run generate:bundled', + ' * Verify up-to-date: bun run check:bundled', + ' *', + ' * Source of truth:', + ' * .archon/commands/defaults/*.md', + ' * .archon/workflows/defaults/*.{yaml,yml}', + ' *', + ' * Contents are inlined as plain string literals (JSON-escaped) so this', + ' * module loads in both Bun and Node. Previous versions used', + " * `import X from '...' with { type: 'text' }` which is Bun-specific.", + ' */', + '', + ].join('\n'); + + return [ + header, + renderRecord('Bundled default commands', 'BUNDLED_COMMANDS', commands), + '', + renderRecord('Bundled default workflows', 'BUNDLED_WORKFLOWS', workflows), + '', + ].join('\n'); +} + +async function main(): Promise { + await Promise.all([ + ensureDir(COMMANDS_DIR, 'Commands defaults'), + ensureDir(WORKFLOWS_DIR, 'Workflows defaults'), + ]); + + const [commands, workflows] = await Promise.all([ + collectFiles(COMMANDS_DIR, ['.md']), + collectFiles(WORKFLOWS_DIR, ['.yaml', '.yml']), + ]); + + const contents = renderFile(commands, workflows); + + if (CHECK_ONLY) { + let existing = ''; + try { + existing = await readFile(OUTPUT_PATH, 'utf-8'); + } catch (e) { + const err = e as NodeJS.ErrnoException; + if (err.code !== 'ENOENT') throw err; + } + if (existing !== contents) { + console.error('bundled-defaults.generated.ts is stale.\n' + 'Run: bun run generate:bundled'); + process.exit(2); + } + console.log( + `bundled-defaults.generated.ts is up to date (${commands.length} commands, ${workflows.length} workflows).` + ); + return; + } + + await writeFile(OUTPUT_PATH, contents, 'utf-8'); + console.log( + `Wrote ${OUTPUT_PATH}\n ${commands.length} commands, ${workflows.length} workflows.` + ); +} + +main().catch((err: unknown) => { + const msg = err instanceof Error ? err.message : String(err); + console.error(msg); + process.exit(1); +}); diff --git a/scripts/tsconfig.json b/scripts/tsconfig.json new file mode 100644 index 00000000..09b9d05b --- /dev/null +++ b/scripts/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "noEmit": true, + "declaration": false, + "declarationMap": false, + "sourceMap": false, + "types": ["bun-types"] + }, + "include": ["*.ts"] +}