
Workflow
- 71 installs
- 15 repo stars
- Updated May 31, 2026
- bntvllnt/agent-skills
Workflow is a Claude Code skill that runs a spec-first, TDD-enforced solo development loop with 10 commands taking an idea from plan to production-ready in a day.
About
Workflow is a Claude skill implementing a high-velocity solo development loop from idea to production in a day. It exposes 10 commands (plan, spike, ship, fix, review, spec-review, focus, done, drop, workflow) and auto-detects intent from context. It is spec-first and TDD-enforced with quality gates for lint, typecheck, build, test, E2E, and coverage. Developers use it to structure feature and bug-fix work with specs and regression tests while keeping deployment under human control.
- 10 commands - plan, spike, ship, fix, review, spec-review, focus, done, drop, workflow
- Spec-first, TDD-enforced ship loop with lint/typecheck/build/test/E2E/coverage quality gates
- Spec tiers from trivial to standard; human controls deployment while the agent codes
Workflow by the numbers
- 71 all-time installs (skills.sh)
- Ranked #934 of 2,715 Automation & Workflows skills by installs in the Skillselion catalog
- Data as of Jul 31, 2026 (Skillselion catalog sync)
workflow capabilities & compatibility
- Capabilities
- planning · tdd · code review · spec review · debugging
- Use cases
- planning · project management · testing
What workflow says it does
High-velocity solo development workflow. Idea to production same-day.
**Spec-first**: All work needs a spec (creates one if missing)
**Anti-regression**: Bug fixes require E2E regression test + anti-cascade diff (BLOCKING)
npx skills add https://github.com/bntvllnt/agent-skills --skill workflowAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 71 |
|---|---|
| repo stars | ★ 15 |
| Last updated | May 31, 2026 |
| Repository | bntvllnt/agent-skills ↗ |
What it does
Run a spec-first, TDD-enforced solo dev loop - plan, ship, fix, review, done - with lint/build/test/E2E quality gates.
Who is it for?
Solo developers who want a spec-first, TDD-gated loop for shipping features and bug fixes.
When should I use this skill?
The user says plan, spec, ship, spike, fix, review, focus, done, drop, or asks what to work on next.
What you get
Same-day delivery with a spec, TDD coverage, quality gates, and an anti-regression test on every bug fix.
- spec file in specs/active
- E2E and regression tests
- retro on done
By the numbers
- 10 commands
- 6 quality gates (lint, typecheck, build, test, E2E, coverage)
- 4 spec tiers
Files
Workflow
High-velocity solo development. Idea to production same-day.
Agent Capabilities
| Capability | Used For | Required | Fallback |
|---|---|---|---|
| File read/write | Specs, config, history | Yes | — |
| Code search (grep/glob) | Discovery, context | Yes | — |
| Shell/command execution | Quality gates (lint, build, test) | Yes | List commands for user to run |
Codebase intelligence (npx codebase-intelligence) | Structural analysis for TS/TSX projects (graph, metrics, blast radius) | No | grep/glob/read (manual exploration) |
| Task/todo tracking | Phase management | Recommended | Track in spec Progress section |
| User interaction | Stuck escalation, risk flags | Recommended | Log decisions in spec Notes |
| Web/doc search | Pattern lookup | No | Use embedded patterns |
Fallback rule: If your agent lacks a capability, use the fallback. Never skip the workflow step — adapt the method.
Commands
| Command | Action | Reference |
|---|---|---|
plan {idea} | Create spec | plan.md |
spike {question} | Time-boxed exploration | spike.md |
ship / ship {idea} | Implement + validate | ship.md |
fix / fix {bug} | Scientific debug + regression fix | fix.md |
review | Portable multi-perspective review spec with line-by-line + rule-by-rule coverage | review.md |
spec-review | Adversarial spec analysis | spec-review.md |
focus | Priority analysis + task proposals | focus.md |
done | Validate + retro + archive | done.md |
drop | Abandon, preserve learnings | drop.md |
workflow | Show state + suggest next | Status (below) |
No flags needed. The agent auto-detects intent from context:
- "review the spec" → manual review pause
- "skip tests" → skip test gate (documented)
- "fix this bug" → dedicated bug fix with regression test
- "emergency fix" → bypass spec ceremony
- "production ready" → production validation
Flow
Features: focus → plan {idea} → ship → [implement/review/fix loop] → done
Bug fixes: fix {bug} → [investigate/TDD/validate] → doneQuick mode (<2h): ship {idea} → done Don't know what to work on: focus
Philosophy
- Spec-first: All work needs a spec (creates one if missing)
- Ship loop: Build → review → fix until clean
- Quality gates: lint → typecheck → build → test → E2E → coverage (auto-detected per project)
- E2E-first testing: Default to E2E tests. Unit tests only for pure functions
- TDD enforced: RED → GREEN → REFACTOR per AC. Tests written before implementation (BLOCKING)
- Mock boundary: Real systems preferred. Mock only third-party APIs without sandbox (last resort)
- AC-driven coverage: Every Must Have + Error AC maps to an E2E test in the scenario registry
- Anti-regression: Bug fixes require E2E regression test + anti-cascade diff (BLOCKING)
- Failure mode testing: Every HIGH/MED failure hypothesis gets a defensive E2E test
- Human controls deployment: Agent codes, you push/deploy
- Done same-day: Scope to what ships today
- Own planning: Never use the host agent's built-in plan mode (EnterPlanMode, etc.). This skill writes real spec files to
specs/active/.
Spec Tiers
| Tier | Size | Spec | Task Tracking |
|---|---|---|---|
| trivial | <5 LOC | None — just do it | No |
| micro | <30 LOC | Inline comment in code | No |
| mini | <100 LOC | Spec file, minimal | Yes (if available) |
| standard | 100+ LOC | Full spec with checklist | Yes (if available) |
Action Router
User input
│
├─ "plan", "spec", "design" → Load references/actions/plan.md
├─ "spike", "explore", "investigate" → Load references/actions/spike.md
├─ "ship", "implement", "build" → Load references/actions/ship.md
├─ "fix", "debug", "repair" → Load references/actions/fix.md
├─ "review", "check code" → Load references/actions/review.md
├─ "review spec", "analyze spec",
│ "challenge spec" → Load references/actions/spec-review.md
├─ "focus", "what should i do",
│ "prioritize", "overwhelmed" → Load references/actions/focus.md
├─ "done", "finish", "complete" → Load references/actions/done.md
├─ "drop", "abandon" → Load references/actions/drop.md
└─ "workflow", "what's next", "what now",
"what's up", "whats up", "status" → Status Action (below)Loading rule: Read the action file BEFORE executing. The action file contains all logic, task templates, and references needed.
Status Action
No separate action file — logic is inline here. Detect current state, suggest next action:
1. Check specs/active/ for active spec
2. Check git status for uncommitted work
3. Check task list for in-progress items
State → Suggestion:
No spec, no changes → "Ready. Run: plan {idea}"
Active spec, no code → "Spec ready. Run: ship"
Active spec, code WIP → "In progress. Run: ship (resumes)"
Active spec, code done → "Ready to close. Run: done"
No spec, dirty tree → "Uncommitted work. Run: ship (creates spec) or done"Output: Follow status-output.md.
Project Structure
specs/
active/ ← Current work (0-1 specs)
backlog/ ← Queued work from focus
shipped/ ← Completed features
dropped/ ← Abandoned with learnings
history.log ← One-line per feature shipped/droppedConfiguration
All behavior is configurable by editing the skill files directly.
| What to change | Edit |
|---|---|
| Action logic, gates, limits | references/actions/{action}.md |
| Output format | references/templates/{action}-output.md |
| Spec structure | references/spec-template.md |
| Quality gate commands/levels | references/quality-gates.md |
| Session resume, stuck detection | references/session-management.md |
References
Actions:
- Plan | Ship | Fix | Review | Spec Review | Focus | Done | Drop | Spike
Output templates:
- Plan + Spec Review | Ship | Fix | Review | Focus | Done | Drop | Spike | Status
Review standards:
- Core portable review spec | Executor patterns | Production Standards
The portable review spec is normative. Executor patterns are optional implementation guidance.
Specs & gates:
- Spec template | Quality gates | Session management | Memory update | Testing automation | E2E scenarios | Codebase intelligence
Patterns:
- Implementation | Planning | Debugging | Decisions | Decomposition | Regression testing
Workflow - High-Velocity Solo Development
Idea to production same-day. Spec-first, quality-gated, pattern-driven.
Install
npx skills add bntvllnt/agent-skills --skill workflowGlobal:
npx skills add bntvllnt/agent-skills --skill workflow -gCommands
| Command | What |
|---|---|
plan {idea} | Create spec with user journey, ACs, scope |
spike {question} | Time-boxed exploration, produces go/no-go |
ship or ship {idea} | Implement with build/review/fix loop |
review | Portable multi-perspective review spec with line-by-line + rule-by-rule coverage |
focus | Scan codebase, prioritize tasks toward production readiness |
done | Validate, retro, archive, propose memory update |
drop | Abandon with learnings preserved |
workflow | Show current state, suggest next action |
No flags needed — the agent auto-detects intent from your natural language (e.g., "review the spec", "skip tests", "emergency fix", "production ready").
Portable review standard
The review command is defined as a core portable review spec:
- the core contract defines what review must cover and what evidence it must emit
- executors are optional implementation patterns that can be single-agent, multi-agent, CI, or human/manual
- the workflow skill should stay runtime-neutral in open source
See:
references/reviews/core-portable-review-spec.mdreferences/reviews/executor-patterns.md
Quickstart
Don't know what to work on? Start with focus:
You: focus
Agent: Scanning codebase against 9 review perspectives...
Goal: Production readiness
Perspective Summary:
Security: 2 gaps (HIGH)
Testability: 3 gaps (MEDIUM)
Reliability: 1 gap (MEDIUM)
Do First:
1. Add input validation to /api/auth endpoints (Security, ~30min)
2. Add error handling to database queries (Reliability, ~1h)
Quick Wins:
3. Add missing test for user creation flow (Testability, ~30min)
Select tasks → specs created in specs/backlog/Here's what a real workflow looks like end-to-end:
You: plan add JWT authentication
Agent: Parsing idea...
Tier: mini (estimated ~80 LOC)
Writing user journey...
ACTOR: Authenticated user
GOAL: Log in with email/password, receive JWT
1. User submits credentials → System validates → User receives token
2. User sends request with token → System verifies → User gets response
E1. Invalid credentials → System returns 401 → User sees error message
Writing acceptance criteria...
AC-1: GIVEN valid credentials WHEN POST /auth/login THEN returns JWT token
AC-2: GIVEN valid JWT WHEN GET /api/protected THEN returns 200
AC-E1: GIVEN invalid credentials WHEN POST /auth/login THEN returns 401
Mapping scope to ACs...
1. Create auth middleware → AC-2
2. Create login endpoint → AC-1, AC-E1
3. Add tests → AC-1, AC-2, AC-E1
Running dev-readiness check...
User journey: PASS
Acceptance criteria: PASS
Scope ↔ AC: PASS (3 scope → 3 ACs, 0 orphans)
Quality checklist: PASS
Dev-ready: READY
Spec: specs/active/2025-01-29-jwt-auth.md
Next: Run `ship` to implement.
You: ship
Agent: Loading spec... mode: LOOP (3 scope items, max 5 iterations)
Iteration 1: Implementing scope item 1 (auth middleware → AC-2)
✓ Created src/middleware/auth.ts
Quick pass: lint ✓ typecheck ✓
Scope item 1 [x]
Iteration 2: Implementing scope item 2 (login endpoint → AC-1, AC-E1)
✓ Created src/routes/auth.ts
Quick pass: lint ✓ typecheck ✓
Scope item 2 [x]
Running dev review (5 core perspectives + Rules when config files exist)...
Correctness: PASS
Security: WARN — add rate limiting to login (medium)
Reliability: PASS
Performance: PASS
DX: PASS
Iteration 3: Implementing scope item 3 (tests → AC-1, AC-2, AC-E1)
✓ Created src/__tests__/auth.test.ts
Quick pass: lint ✓ typecheck ✓
Scope item 3 [x]
Running full pass...
Lint: ✓ Typecheck: ✓ Build: ✓ Tests: 3/3 passing ✓
Exit check:
Must Have ACs: 2/2 ✓ Error ACs: 1/1 ✓ Scope: 3/3 ✓
Gates: green Blockers: 0
CLEAN — Ready. Run `done`.
You: done
Agent: Validating...
All Must Have ACs [x] ✓
All Error ACs [x] ✓
New tests for new behavior ✓ (3 tests added)
Existing tests passing ✓
No lint/typecheck errors ✓
No hardcoded secrets ✓
Retro:
Estimate: 2h → Actual: 1.5h (75%)
Worked: Clean scope-to-AC mapping, no orphan work
Didn't: Missed rate limiting — caught in review
Next time: Add security checklist for auth features
Proposing memory update...
"Auth features should include rate limiting in quality checklist"
→ Update project agent config? [yes/no]
Archived: specs/shipped/2025-01-29-jwt-auth.md
Human actions: commit → push → deploy → verifyUser Journey: Spec to Production
┌─────────────────────────────────────────────────────────────────────┐
│ SPEC TO PRODUCTION │
│ │
│ YOU AGENT OUTPUT │
│ ─── ───── ────── │
│ │
│ "plan add rate limiting" │
│ │ │
│ ├──────────────────▶ Parse idea │
│ Select tier: mini │
│ Write user journey: │
│ ACTOR: API consumer │
│ GOAL: Protected from abuse │
│ 1. Client sends request │
│ 2. System checks rate │
│ 3. Under limit → process │
│ E1. Over limit → 429 + Retry-After │
│ Write ACs (GIVEN/WHEN/THEN) │
│ Map scope ↔ ACs │
│ Quality checklist │
│ Dev-readiness: READY ──────▶ spec file │
│ │
│ "ship" │
│ │ │
│ ├──────────────────▶ Load spec, create tasks │
│ Iteration 1: middleware ──▶ lint ✓ │
│ Iteration 2: config ──────▶ lint ✓ │
│ Dev review (5 core + Rules) │
│ Iteration 3: tests ───────▶ lint ✓ │
│ Full pass: lint ✓ types ✓ │
│ build ✓ test ✓ │
│ Exit: all ACs ✓ ──────────▶ CLEAN │
│ │
│ "also add per-user limits" (MID-LOOP CHANGE) │
│ │ │
│ ├──────────────────▶ PAUSE implementation │
│ Update spec: │
│ + scope item 4: per-user config │
│ + AC-4: GIVEN user config WHEN... │
│ + journey step 4 │
│ Re-check traceability │
│ Update tasks │
│ RESUME loop ───────────────▶ continues │
│ │
│ "done" │
│ │ │
│ ├──────────────────▶ Validate all ACs ✓ │
│ New tests exist ✓ │
│ No lint/type errors ✓ │
│ Retro captured │
│ Memory update proposed │
│ Spec archived ─────────────▶ shipped/ │
│ │
│ YOU (manual) │
│ │ │
│ ├─ git commit + push │
│ ├─ deploy │
│ └─ verify in production │
│ │
└─────────────────────────────────────────────────────────────────────┘Key: The spec is updated at every stage. Mid-loop changes are captured in the spec BEFORE implementation. The spec is always the source of truth.
Reading Order
Start here
│
▼
┌──────────┐ Already know ┌──────────────────────┐
│ README │──── the basics? ──────────▶│ SKILL.md │
│ (you are │ │ (agent instructions) │
│ here) │ └──────────────────────┘
└────┬─────┘
│ Want to understand a phase?
│
├── Focus: references/actions/focus.md
├── Plan: references/actions/plan.md
├── Spike: references/actions/spike.md
├── Ship: references/actions/ship.md
├── Review: references/actions/review.md
├── Done: references/actions/done.md
├── Drop: references/actions/drop.md
└── Memory: references/memory-update.md
│ Need a pattern?
│
├── Building: references/patterns/implementation.md
├── Planning: references/patterns/planning.md
├── Debugging: references/patterns/debugging.md
├── Deciding: references/patterns/decisions.md
└── Decomposing: references/patterns/decomposition.md
│ Want to customize output?
│
├── Focus: references/templates/focus-output.md
├── Plan: references/templates/plan-output.md
├── Spike: references/templates/spike-output.md
├── Ship: references/templates/ship-output.md
├── Review: references/templates/review-output.md
├── Done: references/templates/done-output.md
├── Drop: references/templates/drop-output.md
└── Status: references/templates/status-output.mdYou don't need to read everything. SKILL.md is the only file the agent loads. References are loaded on-demand when a phase triggers.
How It Works
YOU WORKFLOW OUTPUT
────── ──────── ──────
"focus"
│
├───────────────────▶ Scan specs (active/backlog/dropped/shipped)
Ask goal (production/MVP/infra/custom)
Dispatch perspective agents
Rank findings ──────────────────▶ prioritized tasks
│
Select tasks
│
├───────────────────▶ Create specs ───────────────────▶ specs/backlog/
"plan {idea}"
│
├───────────────────▶ Parse idea
User journey (MANDATORY)
Acceptance criteria (MANDATORY)
Scope ↔ AC mapping
Quality checklist
Plan review
Dev-readiness check ──────────▶ specs/active/{slug}.md
│
"ship"
│
├───────────────────▶ Detect mode (ONE-SHOT / LOOP)
Resume state check
┌─────────────────────┐
│ SHIP LOOP │
│ build → review → fix│◄──┐
│ exit check (ACs) │───┘ not clean
│ stuck detection │
└────────┬────────────┘
│ clean
Quality gates ────────────────▶ All ACs + scope [x]
│
"done"
│
├───────────────────▶ Validate (ACs + tests + gates)
Capture retro
Propose memory update ────────▶ Agent config learning
Archive spec ─────────────────▶ specs/shipped/{slug}.md
│
YOU (manual)
│
├─ git commit + push
├─ deploy
└─ verify in productionLifecycle
┌──────────┐ focus ┌──────────┐ plan ┌──────────┐ review? ┌───────────┐
│ UNFOCUSED│────────▶│ IDEA │────────▶│ DRAFT │────────▶│ REVIEWING │
└──────────┘ └──────────┘ └──────────┘ └───────────┘
▲ ▲ │
│ │ revise [?][!] │ ready?
│ └────────────────────┘
│ │
│ ┌──────────┐ ┌───────────┐
│ │IMPLEMENTING│◄───────────── ship ───────│ DEV_READY │
│ └─────┬─────┘ └───────────┘
│ │
│ ┌───────────┐
│ │ SHIP │──── iterate
│ │ LOOP │
│ └─────┬─────┘
│ │ clean │ stuck
│ ┌──────────┐ ┌──────────┐
│ done │ READY │ │ DROPPED │
└──────────────│ │ └──────────┘
└──────────┘ specs/dropped/
│
┌──────────┐
│ SHIPPED │
└──────────┘
specs/shipped/Quality Gates
Quick Pass (per edit) Full Pass (before exit)
┌──────────────────────┐ ┌─────────────────────────────────────────┐
│ LINT ──▶ TYPECHECK │ │ LINT ──▶ TYPECHECK ──▶ BUILD ──▶ TEST │
│(changed) (changed) │ │(changed) (full) (full) (related)│
└──────────────────────┘ └─────────────────────────────────────────┘Review Notation
[?] unclear [!] risk [+] add to scope
[-] cut scope [~] rephrase [ok] approvedCustomization
Edit the skill files directly. Install at user-level or project-level, then modify to match your needs.
workflow/
├── SKILL.md ──────────────────── Task templates, review systems, risk thresholds
├── references/
│ ├── actions/ ← Action logic (what the agent does)
│ │ ├── plan.md ───────────── Spec requirements, dev-readiness gates, review rounds
│ │ ├── ship.md ───────────── Quality gates, iteration limits, exit criteria
│ │ ├── review.md ─────────── Perspectives (add/remove/change levels)
│ │ ├── focus.md ──────────── Codebase scan, perspective weights, ranking formula
│ │ ├── done.md ───────────── Validation checklist, memory update settings
│ │ └── drop.md ───────────── Drop flow
│ │
│ ├── templates/ ← Output templates (what the agent returns to you)
│ │ ├── plan-output.md ────── Spec summary, codebase impact, analysis, readiness
│ │ ├── spike-output.md ───── Decision, findings, next step
│ │ ├── ship-output.md ────── Iteration progress, exit states, spec mutations
│ │ ├── review-output.md ──── Per-file findings, fix actions, verdict
│ │ ├── focus-output.md ───── Ranked tasks, perspective scores, readiness
│ │ ├── done-output.md ────── Validation results, retro, memory updates
│ │ ├── drop-output.md ────── Drop reason, learnings, reusable pieces
│ │ └── status-output.md ──── Current state, progress, suggested next action
│ │
│ ├── spec-template.md ─────── Spec structure, generation rules, validation
│ ├── quality-gates.md ──────── Gate levels (BLOCKING/ADVISORY/SKIP), commands
│ ├── session-management.md ── Progress tracking, resume, stuck detection
│ └── memory-update.md ─────── Memory update protocol, agent config targetsTwo layers of customization:
| Layer | What to edit | Controls |
|---|---|---|
Actions (actions/*.md) | Logic, gates, perspectives, limits | What the agent does |
Templates (templates/*-output.md) | Output format, sections, wording | What the agent returns to you |
Examples
Change what the agent shows after plan: Edit templates/plan-output.md — add/remove sections, change format.
Change what review findings look like: Edit templates/review-output.md — change format, add fields, adjust rules.
Change quality gate commands: Edit quality-gates.md — update auto-detection tables or add explicit commands.
Add review perspectives: Edit actions/review.md — add rows to the perspectives table.
Skip typecheck: Edit quality-gates.md — set Typecheck level to SKIP.
Require manual spec review: Edit actions/plan.md — set manual review gate to BLOCKING.
Change iteration limits: Edit actions/ship.md — update the "Default Iterations by Size" table.
Change memory update behavior: Edit memory-update.md — adjust categories, agent targets, or disable proposals.
---
Key Principles
- Spec = source of truth: Always updated, always reflects reality
- ACs define done: Work finishes when all Must Have + Error ACs pass
- New code = new tests: Every new behavior must have tests (BLOCKING)
- Two review systems: Plan review (specs) + dev review (code)
- Quality gates: Auto-detected, skippable — edit skill files to configure
- Ship loop: Build → review → fix with stuck detection + escalation
- Risk-aware: Agent flags HIGH risk changes for human review
- Context-aware memory updates: Done phase reads existing rules, proposes thinking patterns + coding rules + project rules
- Human controls deployment: Agent codes and validates, you push and deploy
- 16 patterns: Implementation, planning, debugging, decisions, decomposition
- Agent-portable: Capability fallbacks for agents without task tracking or shell access
Done Action
Agent: Load this file when done triggers. Read the user's agent config (global + project rules) before proposing memory updates.Validate, archive spec, capture learnings. Does NOT deploy — that's human-controlled.
---
Step 1: Pre-Ship Validation
Quality Gate
| Check | Required |
|---|---|
| All Must Have ACs passing [x] | Yes (MANDATORY) |
| All Error Criteria ACs passing [x] | Yes (MANDATORY) |
| All scope items checked [x] | Yes |
| Ship exit was CLEAN (not partial/stuck/hard-stop) | Yes |
| New tests for new behavior (E2E default) | Yes (BLOCKING) |
| Existing tests passing | Yes |
| No typecheck/lint errors | Yes |
| No debug statements (console.log, debugger, print, pdb, etc.) | Yes |
| No hardcoded secrets | Yes |
| Can rollback (git revert works, no irreversible migrations) | Yes |
| No unresolved bugs (all fixed or deferred) | Yes |
| E2E scenario registry: 100% Must Have + Error AC coverage | Yes (BLOCKING) |
| TDD proof: every AC has RED_CONFIRMED + GREEN_CONFIRMED | Yes (BLOCKING) |
| Mock boundary: no mocks of own code in new tests | Yes (BLOCKING) |
| Bug regressions: AC-B2 (RED) + AC-B3 (GREEN) + AC-B4 (DIFF) confirmed | Yes (BLOCKING, bug fixes only) |
| Coverage threshold met | Advisory |
| Agent docs updated for critical learnings | Advisory |
New test mandate: Every new behavior MUST have at least one E2E test (unit only for pure functions). Tests must follow TDD: RED_CONFIRMED before GREEN_CONFIRMED. No mocking of own code — real systems required. If E2E infrastructure doesn't exist, propose setting it up. If user declines, document the skip and downgrade E2E gate to ADVISORY.
ACs are the definition of DONE. Scope items track implementation tasks, but ACs determine if the feature actually works as specified in the user journey.
If any check fails: STOP. Show what's remaining. Suggest ship to continue.
Step 1.5: E2E Coverage + TDD Validation (BLOCKING)
validate_e2e_coverage(spec, registry):
# Registry exists?
IF not exists(registry):
IF spec.tier in [trivial, micro]: SKIP
IF spec created before e2e protocol: WARN (advisory)
ELSE: FAIL "E2E registry missing"
# All ACs mapped?
unmapped = [ac for ac in spec.must_have + spec.error_acs if ac not in registry]
IF unmapped: FAIL "Unmapped ACs: {unmapped}"
# TDD proof: RED before GREEN
for entry in registry:
IF entry.status == GREEN_CONFIRMED AND NOT entry.had_red:
FAIL "TDD violation: {entry.ac} — no RED_CONFIRMED before GREEN"
# All BLOCKING entries GREEN?
blocking = [e for e in registry if e.required == BLOCKING]
not_green = [e for e in blocking if e.status != GREEN_CONFIRMED]
IF not_green: FAIL "Incomplete: {not_green}"
# Mock boundary clean?
new_test_files = get_new_test_files(git_diff)
for file in new_test_files:
IF contains_mock_of_own_code(file): FAIL "Mock boundary violation in {file}"
# Bug fix validation
IF spec.is_bug_fix:
IF NOT registry.has("AC-B2") OR registry["AC-B2"].status != GREEN_CONFIRMED:
FAIL "Bug fix missing RED proof (AC-B2)"
IF NOT registry.has("AC-B3") OR registry["AC-B3"].status != GREEN_CONFIRMED:
FAIL "Bug fix missing GREEN proof (AC-B3)"
IF NOT registry.has("AC-B4") OR registry["AC-B4"].status != GREEN_CONFIRMED:
FAIL "Bug fix DIFF not confirmed (AC-B4)"
PASS "100% E2E coverage, TDD proof clean"Unresolved bugs are blocking. All entries in "Encountered Bugs" must be Fixed or Deferred before done.
Production Validation
Additional checks for production deploys:
- Schema validation (if schema files changed)
- Deploy readiness check
- Security audit
- Performance validation
Step 2: Retro (Always Runs)
Analyze the session and capture learnings:
Ship Retro ({DATE})
Estimate vs Actual: {X}h → {Y}h ({accuracy}%) What worked: {insight} What didn't: {insight with root cause} Next time: {specific improvement}
Write retro to: 1. Spec file ## Notes section 2. Project learnings file (if maintained)
Step 3: Record Timestamp
Add done entry to spec Timeline:
| done | {ISO_TIMESTAMP} | {total_duration} | - |
Step 4: Propose Memory Update (Agent Self-Improvement)
Follow the full protocol in memory-update.md: 1. Detect agent type, read correct config files (CLAUDE.md for Claude Code, AGENTS.md for others) 2. Extract learnings (6 categories — including patterns & anti-patterns) 3. Classify & target (user-level vs project-level, route to correct file) 4. Present file-targeted proposals with exact content for user approval
Pattern extraction is critical. Every session produces learnings worth remembering: user preferences (coding style, architecture choices), repeated requests that should become defaults, project knowledge discovered during implementation, and anti-patterns from mistakes or regressions. Capturing these in agent config avoids repeat questions and makes future sessions faster.
If no project agent config exists (no CLAUDE.md or AGENTS.md), propose creating one with initial rules from this session's learnings.
Step 5: CI Integration (Optional)
If the agent has access to CI pipelines (GitHub Actions, GitLab CI, etc.):
1. Push to feature branch (if not already pushed)
2. Wait for CI pipeline to complete
3. Read CI results:
- Build: PASS/FAIL
- Tests: PASS/FAIL (N passing, N failing)
- Lint/typecheck: PASS/FAIL
- Coverage: {percent} (delta from main)
4. Include CI status in validation output
5. If CI fails: treat as validation failure — suggest `ship` to fixCI is ADVISORY by default. Edit this file to make it BLOCKING.
Step 6: Archive Spec
mkdir -p specs/shipped
mv specs/active/{spec-file}.md specs/shipped/
Update spec: status → shipped, shipped → {YYYY-MM-DD}Step 7: Log to History
Append to specs/history.log:
{DATE} | shipped | {slug} | {estimate}h→{actual}h | {duration} | {summary}Step 8: Output
Follow the output template in references/templates/done-output.md.
Covers: validation passed (retro + memory update + next steps) and validation failed.
Express Ship (No Spec)
If no spec exists (one-shot build): 1. Skip spec archival 2. Still run validation 3. Log to history
Never
- Never runs
git push - Never runs deploy commands
- Never makes production changes
Drop Action
Agent: Load this file when drop triggers.Abandon feature, preserve learnings. Nothing is wasted.
---
Step 1: Confirm
Ask before dropping:
- Why dropping? (Categories: too complex, wrong approach, no longer needed, blocked, time constraint)
- Any reusable pieces? (Code, patterns, research)
Step 2: Capture Learnings
Write drop retro to spec Notes:
### Drop Retro ({DATE})
**Reason:** {category} — {details}
**Time spent:** {hours}
**Reusable pieces:**
- {code/pattern/insight that can be reused}
**What we learned:**
- {key insight from the attempt}
**If revisited:**
- {what to do differently next time}Step 3: Record Timestamp
Add drop entry to spec Timeline:
| dropped | {ISO_TIMESTAMP} | {time_spent} | {reason} |Step 4: Archive Spec
mkdir -p specs/dropped
mv specs/active/{spec-file}.md specs/dropped/
Update spec: status → dropped, dropped → {YYYY-MM-DD}Step 5: Log to History
Append to specs/history.log:
{DATE} | dropped | {slug} | {estimate}h→{actual}h | {reason} | {key_learning}Step 6: Output
Follow the output template in references/templates/drop-output.md.
Fix Action
Agent: Load this file whenfixtriggers. Also loadreferences/quality-gates.mdfor gate commands,references/testing-automation.mdfor E2E-first test generation + mock avoidance,references/session-management.mdfor resume/stuck detection, andreferences/rules-discovery.md— fixes must follow project/user rules.
Fix bugs with scientific debugging and anti-cascade TDD. Prevents cascading failures.
---
When to Fix
- User reports a bug (symptom, reproduction steps)
- Bug found during feature implementation (ship's Bug Encounter Protocol hands off here)
- Regression detected in CI or test suite
Bug Classification
| Type | Signal | Approach |
|---|---|---|
| Simple | Clear cause, single file | Skip Phase 1, go directly to Phase 2 |
| Complex | Unclear cause, multiple files, intermittent | Phase 1 (single-agent investigation) then Phase 2 |
| Highly complex | Cross-cutting, multiple possible root causes, reproduces inconsistently | Phase 1 with multi-agent parallel investigation then Phase 2 |
State Machine
CLASSIFY → simple? → BASELINE
CLASSIFY → complex? → INVESTIGATE → CONFIRM → BASELINE
CLASSIFY → highly complex? → INVESTIGATE (parallel agents) → CONVERGE → CONFIRM → BASELINE
BASELINE → RED → GREEN → DIFF → BLOCK
BLOCK [new failures] → ROLLBACK → rethink approach → BASELINE (max 3 cycles → ESCALATE)
BLOCK [no new failures] → SCAN → LEARN → VALIDATE → DONE
INVESTIGATE → all hypotheses eliminated + bisect fails → ESCALATE
ESCALATE → present evidence to user → user decides next stepStates:
| State | Entry condition | Exit condition | Next state |
|---|---|---|---|
| CLASSIFY | Fix triggered | Bug classified | INVESTIGATE (complex/highly complex) or BASELINE (simple) |
| INVESTIGATE | Complex or highly complex bug | Hypotheses tested, candidate root cause identified | CONFIRM (or ESCALATE if exhausted) |
| CONFIRM | Candidate root cause exists | Root cause passes 3-point validation | BASELINE |
| BASELINE | Investigation done (or simple bug) | Full suite results recorded | RED |
| RED | Baseline recorded | Regression test written and FAILS | GREEN |
| GREEN | RED test exists | Fix implemented, regression test PASSES | DIFF |
| DIFF | Fix passes regression test | Full suite re-run, compared to baseline | BLOCK |
| BLOCK | DIFF results available | Decision: new failures or not | SCAN (clean) or ROLLBACK (regressions, max 3) |
| ESCALATE | Investigation exhausted OR 3 rollback cycles | Evidence presented, user decides | User-directed (new approach, defer, or accept risk) |
| SCAN | No new failures | Sibling bugs searched, proposed to user | LEARN |
| LEARN | Scan complete | Spec updated + rules proposed, user approved/declined | VALIDATE |
| VALIDATE | Prevention done | All quality gates pass | DONE |
Phase 1: INVESTIGATE (Complex and Highly Complex Bugs)
Load patterns/debugging.md for full method.
Step 1: SYMPTOM CAPTURE
Collect before doing anything else:
- Exact error message / unexpected behavior
- Steps to reproduce (minimal)
- When it started (last known good state / commit)
- Environment details (OS, runtime version, config)
- Frequency: always / intermittent / onceStep 2: HYPOTHESIS FORMATION
Generate ranked hypotheses:
H1: {most likely cause} (probability: X%)
H2: {second most likely} (probability: Y%)
H3: {least likely} (probability: Z%)
Each hypothesis must:
- Name a specific code path or condition
- Be falsifiable (you can design a test that disproves it)
- State what evidence would CONFIRM vs ELIMINATE itTypeScript projects with CI available (augments code reading):
For suspect function/symbol:
npx codebase-intelligence symbol --json <path> <name>
→ Callers, callees, type info — narrows hypothesis scope
npx codebase-intelligence dependents --json <file>
→ Blast radius — what else could be affected by this bug?
If CI unavailable: use grep for callers/callees
See references/codebase-intelligence.md for full command reference.Step 3: TEST HYPOTHESES
For complex bugs: test each hypothesis sequentially, highest probability first.
For highly complex bugs: if the agent supports parallel execution (sub-agents, concurrent tool calls, or background tasks), investigate multiple hypotheses simultaneously. If not, investigate sequentially but assign a time box per hypothesis to avoid rabbit holes.
TypeScript structural investigation (if CI available):
npx codebase-intelligence processes --json <path>
→ Entry-point execution tracing — identifies code paths through suspect area
npx codebase-intelligence impact --json <path> <symbol>
→ Symbol-level blast radius — what breaks if this symbol behaves differently?
Feed these to investigation agents alongside hypothesis prompts.
If CI unavailable: agents use grep + manual code path tracing.Highly Complex: Parallel Investigation
When the bug is cross-cutting, has multiple plausible root causes, or spans several systems, investigate from multiple perspectives at once.
How to dispatch (adapt to your agent's capabilities):
For each hypothesis, create a focused investigation task:
Task 1: "Investigate H1: {hypothesis}. Search for {pattern} in {area}.
Report: evidence found, CONFIRMED or ELIMINATED, reasoning."
Task 2: "Investigate H2: {hypothesis}. Search for {pattern} in {area}.
Report: evidence found, CONFIRMED or ELIMINATED, reasoning."
Task 3: "Investigate H3: {hypothesis}. Alternatively, explore
{alternative angle — e.g., git history, dependency changes, config drift}.
Report: evidence found, CONFIRMED or ELIMINATED, reasoning."
If agent supports sub-agents or parallel execution → run all tasks simultaneously.
If agent is single-threaded → run sequentially, time-box each to 15 min max.Agent perspective assignments (pick based on bug type):
| Perspective | Focus | When to use |
|---|---|---|
| Code path tracer | Follow execution path, find where behavior diverges | Logic bugs, wrong output |
| State inspector | Track state mutations, find unexpected side effects | State bugs, data corruption |
| History investigator | git log/bisect, find breaking change, review recent commits | Regressions, "it used to work" |
| Dependency auditor | Check dependency versions, breaking changes, API diffs | Post-upgrade bugs, integration issues |
| Concurrency analyzer | Identify shared state, race windows, timing dependencies | Intermittent bugs, deadlocks |
| Environment comparator | Diff configs, env vars, runtime versions across environments | "Works on my machine" bugs |
Convergence protocol:
Collect all agent results → synthesize:
1. Which hypotheses were CONFIRMED? Which ELIMINATED?
2. Do agents agree on root cause? If not, what's the conflict?
3. If conflict → form new hypothesis from combined evidence → test directly
4. If no hypothesis confirmed → escalate to BINARY SEARCH (Step 4)Step 4: BINARY SEARCH (if no hypothesis confirmed)
git bisect or manual binary elimination:
Find last known good commit
Bisect to identify breaking change
Read the breaking commit → form new hypothesis → testStep 5: ESCALATE (if investigation exhausted)
If all hypotheses are eliminated AND binary search fails (or is not possible):
ESCALATE to user with:
1. Summary of all hypotheses tested and evidence
2. What was eliminated and why
3. Remaining unknowns
4. Recommended next steps:
a) Bring in domain expert / pair debug
b) Add instrumentation and wait for recurrence
c) Accept risk and document as known issue
d) Try different investigation angle (user suggests)Do NOT loop back to Step 2 more than once after escalation. If the second round also fails → hard stop, present all evidence, let user decide.
Step 6: ROOT CAUSE CONFIRMATION
Before proceeding to Phase 2, the root cause must pass all 3 validation checks:
Root Cause 3-Point Validation:
1. EXPLAINS: Does it explain ALL observed symptoms (not just some)?
Ask: "If this is the root cause, why does {symptom} happen?"
Every symptom must have an answer. If any symptom is unexplained → dig deeper.
2. PREDICTS: Does it predict the fix?
Ask: "If I change {specific code}, will the bug stop AND no new issues appear?"
Must be able to name the exact change. Vague fixes = wrong root cause.
3. REPRODUCES: Can you make the bug appear and disappear at will?
The reproduction case must:
- FAIL without the fix (proves the root cause triggers the bug)
- PASS with the fix (proves the fix addresses the root cause)
If you can't toggle it → you found a correlation, not the cause.If any check fails: Do NOT proceed to Phase 2. Go back to Step 2 with new evidence and form new hypotheses. If this is the second failed round → ESCALATE (Step 5).
Key rule: Never make a change without a hypothesis for why it will fix the bug.
Phase 2: FIX (Anti-Cascade TDD)
All bug fixes follow this protocol. Full details: regression-testing.md.
1. BASELINE → Run full test suite, record pass/fail counts (BLOCKING)
2. RED → Write E2E regression test reproducing the bug (MUST FAIL) (BLOCKING)
Log RED_CONFIRMED in e2e-scenarios registry
Use real systems — never mock own code (see testing-automation.md mock avoidance hierarchy)
Even if bug is in a "unit-testable" function → E2E proves fix at system level
3. GREEN → Implement fix, E2E regression test MUST PASS (BLOCKING)
Log GREEN_CONFIRMED in e2e-scenarios registry
No mocking own code — real DB, real server, real auth
4. DIFF → Run full test suite again, compare to baseline (BLOCKING)
5. BLOCK → Any NEW failures = fix introduced regressions → roll back, rethink (BLOCKING)
6. SCAN → Check codebase for sibling bugs (same pattern) (advisory)All steps except SCAN are BLOCKING — cannot skip.
DIFF is the anti-cascade mechanism. By comparing full suite results before and after, you catch any regression the fix introduces — before it cascades.
Mock boundary: Regression tests follow the same mock avoidance hierarchy as all tests (see references/testing-automation.md). DENY mocking own application code, own DB, own HTTP endpoints, own auth. ALLOW mocking only third-party APIs without sandbox/Docker/in-memory alternatives.
If fix introduces regressions (DIFF fails):
- Option A: Fix regressions without breaking the original fix
- Option B: Roll back, find a different approach
- Option C: Escalate to user with evidence
ROLLBACK cap: Max 3 BLOCK → ROLLBACK cycles. If the 3rd approach still introduces regressions → ESCALATE. Present all 3 attempts + their regressions to the user. Do not loop indefinitely.
LEARN: Capture Learnings & Prevent Recurrence
After SCAN, capture what was learned so the same class of error doesn't recur. Two sub-steps: update the active spec (if one exists), then propose prevention rules for the agent's config files.
When to run: Non-trivial bugs with a generalizable root cause. When to skip: Trivial bugs (typos, config), emergency/hotfix.
Step 1: Update Active Spec
If the bug relates to an active spec in specs/active/, update it with the fix details.
1a. Check for active spec.
Read specs/active/ directory
Files found? → Continue to 1b
Empty? → Skip to Step 21b. Determine if bug relates to the active spec.
Read the spec file. Check:
- Does the bug affect a scope item in this spec?
- Was the bug found during implementation of this spec?
- Does the fix change behavior described in the spec's ACs?
If YES to any → continue. If NO to all → skip to Step 2.
1c. Log the bug in the spec.
Open the spec file. Find or create ## Encountered Bugs section. Append:
BUG-{N}: {1-line summary}
- **Root cause:** {why it happened}
- **Fix:** {what was changed}
- **Status:** Fixed
- **Regression test:** {test file}:{test name} (E2E)
- **Registry:** AC-B1 through AC-B4 in e2e-scenarios.md — RED_CONFIRMED + GREEN_CONFIRMED1d. Update spec Progress section.
Find the ## Progress table. If the bug blocked a scope item, update its status:
- Was
[!] Blocked→ change to[~] In progressor[x] Complete - Add note:
Fixed via BUG-{N}
1e. Update ACs if fix changed behavior.
If the fix changed how a feature works (not just a bug in implementation):
- Update affected GIVEN/WHEN/THEN ACs to match new behavior
- Add new AC if the fix introduced a new user-observable behavior
- Run traceability check: every scope item maps to an AC, no orphans
Step 2: Propose Prevention Rules
Propose rule updates to the agent's config files so the same class of error doesn't happen again.
When to skip this step: Existing rule already covers it, or root cause is too specific to generalize.
2a. Identify the root cause category.
Look at the confirmed root cause from INVESTIGATE or GREEN phase. Map it:
| Root Cause | Category | Example Rule |
|---|---|---|
| Missing null/undefined check | Coding rule | "Always null-check optional fields before access" |
| Wrong type assumption | Coding rule | "Use discriminated unions, never assume shape" |
| Missing validation at boundary | Quality check | "Validate external input at API boundaries" |
| Incorrect error handling | Anti-pattern | "Never swallow errors in catch blocks" |
| Race condition / shared state | Coding rule | "Wrap shared state mutations in transactions" |
| Missing edge case | Quality check | "Test empty/null/boundary inputs for public functions" |
| Config/env assumption | Quality check | "Validate required env vars at startup" |
2b. Read existing agent rules.
Detect which agent CLI is running, then read all config files at both project and user level. Use the Agent Config Targets table in memory-update.md to resolve the correct file paths for the detected agent.
If the root cause is already covered by an existing rule at any level → SKIP. Do not propose duplicates.
2c. Draft max 2 proposals.
Write each proposal in this exact format:
[{target file} § {section}] {type}: "{rule text}"
_Prevents: {class of error}_Target file routing (resolve via memory-update.md Agent Config Targets table):
- Project-specific patterns → agent's project-level config
- Universal patterns → agent's user-level config
- Unknown agent →
{project}/AGENTS.md(universal fallback)
Categories allowed: rule (coding rules), anti-pattern, quality-check.
See memory-update.md Proposal Format Examples for per-agent targeting (Claude Code, Cursor, Windsurf, Codex, OpenCode, etc.).
2d. Present to user for approval.
If agent has multi-select UI (AskUserQuestion or equivalent):
question: "Save prevention rules from this fix?"
multiSelect: true
options:
- label: "#1 {short summary}"
description: "[{target file} § {section}] {type}: {rule text}"
- label: "#2 {short summary}"
description: "[{target file} § {section}] {type}: {rule text}"If no multi-select UI (fallback):
Prevention rules from this fix:
1. [{target file} § {section}] {type}: "{rule text}"
_Prevents: {class of error}_
2. [{target file} § {section}] {type}: "{rule text}"
_Prevents: {class of error}_
Apply which? [all / 1,2 / none]2e. Apply approved rules.
For each approved proposal: 1. Open the target file 2. Find the target section 3. Append the rule text 4. Confirm write to user
Declined proposals → log in output, take no action.
LEARN Rules
- Max 2 rule proposals per fix
- Advisory, not blocking — user can decline with no gate failure
- Never auto-apply — always get explicit user approval before writing rules
- Never propose vague rules ("be more careful") — must be specific and actionable
- Spec updates don't require approval (they log facts, not opinions)
Phase 3: VALIDATE
Same quality gates as ship. Load references/quality-gates.md.
Full pass (before marking complete — all 6 gates + TDD proof):
| # | Gate | Scope | Level |
|---|---|---|---|
| 1 | Lint | Changed files | BLOCKING |
| 2 | Typecheck | Full project | BLOCKING |
| 3 | Build | Full project | BLOCKING |
| 4 | Test | Related tests + anti-cascade DIFF | BLOCKING |
| 5 | E2E registry | All bug fix ACs (AC-B1 through AC-B4) GREEN_CONFIRMED | BLOCKING |
| 6 | TDD proof | Every GREEN_CONFIRMED has prior RED_CONFIRMED | BLOCKING |
| 7 | Coverage | Advisory — warn on >5% drop | ADVISORY |
Auto-detect tooling from project files. See references/quality-gates.md.
Task Tracking (Use Agent Capabilities)
If your agent has built-in task/todo tracking (TaskCreate, TaskUpdate, etc.), use it to track each phase. Create tasks at the start, update status as you progress.
[ ] Classify bug (simple/complex/highly complex)
[ ] INVESTIGATE: scientific debugging (complex/highly complex)
[ ] CONFIRM: root cause passes 3-point validation
[ ] BASELINE: run full test suite, record results (BLOCKING)
[ ] Create e2e-scenarios.md registry entries for bug fix ACs (AC-B1 through AC-B4)
[ ] RED: write E2E regression test → MUST FAIL → log RED_CONFIRMED (BLOCKING)
[ ] GREEN: implement fix → E2E test MUST PASS → log GREEN_CONFIRMED (BLOCKING)
[ ] DIFF: run full suite, compare to baseline (zero new failures) (BLOCKING)
[ ] Mock audit: verify no mocking of own code in regression test
[ ] SCAN: check codebase for sibling bugs
[ ] LEARN: update spec (if related) + propose prevention rules
[ ] Full pass: lint + typecheck + build + test + E2E registry + TDD proof + coverage
[ ] Output summaryUpdate tasks as you work: mark in-progress when starting, complete when done. One task in-progress at a time.
If agent lacks task tracking: Track progress in the spec's Progress section instead.
Acceptance Criteria
Auto-generate these ACs for any bug fix:
- AC-B1: GIVEN {reproduction steps} WHEN {trigger} THEN bug no longer occurs
- AC-B2: GIVEN E2E regression test WHEN run against unfixed code THEN test FAILS (RED_CONFIRMED in registry)
- AC-B3: GIVEN E2E regression test WHEN run against fixed code THEN test PASSES (GREEN_CONFIRMED in registry)
- AC-B4: GIVEN full test suite WHEN run after fix THEN no NEW failures vs baseline (DIFF clean)AC-B2 + AC-B3 = TDD proof (tracked in e2e-scenarios.md registry). AC-B4 = anti-cascade proof.
All bug fix ACs are registered in e2e-scenarios.md with type prefix AC-BN. See references/e2e-scenarios.md for registry format.
Guard Rails
| Situation | Action |
|---|---|
| No test suite exists | Propose setup (load testing-automation.md for recommendation). If declined, document and downgrade E2E gate to ADVISORY |
| No E2E framework exists | Propose E2E framework setup (Playwright/Cypress/Maestro/Detox per stack). If declined, downgrade E2E gate to ADVISORY for this session |
| Test suite is partial (low coverage) | Warn: "Coverage is low near fix area. Baseline may miss regressions." |
| Tests are flaky (intermittent failures) | Run baseline 2x, use consistent results as anchor. Flag flaky tests. |
| Fix is trivial (typo, config) | Still run BASELINE + DIFF. Skip RED/GREEN only if no testable behavior change. |
| Emergency/hotfix | Run abbreviated: RED + GREEN + DIFF. Skip SCAN. Document skip. |
| User says "skip tests" | Document skip reason. Still run DIFF if suite exists (non-blocking). |
| Non-deterministic bug (race condition, heisenbug) | Use Concurrency analyzer perspective. RED test may need stress/repeated runs. If can't reproduce reliably → document conditions, write best-effort test, note uncertainty. |
| Can't reproduce locally | Skip RED (can't write failing test). Investigate via logs/history/code review. Propose fix based on code analysis. Run DIFF to ensure no regressions. Document that RED was skipped and why. |
| Root cause is in dependency | Document dependency + version. Propose workaround (pin version, patch, or wrapper). Do NOT attempt to fix external code. File upstream issue if applicable. |
| Investigation exhausted (no root cause found) | ESCALATE with all evidence. Do NOT guess-and-fix. Present hypotheses tested + results to user. |
Time Limits
Investigation Time-Box
| Bug Type | Max Investigation Time | Max Hypotheses | Escalation |
|---|---|---|---|
| Simple | N/A (skip Phase 1) | N/A | — |
| Complex | 30 min | 5 | ESCALATE with evidence |
| Highly complex | 60 min | 8 (across all agents) | ESCALATE with evidence |
If time-box expires without confirmed root cause → ESCALATE (Step 5). Do not continue investigating indefinitely.
Fix Iteration Limits
| Bug Complexity | Max ROLLBACK Cycles | Max Total Fix Time |
|---|---|---|
| Simple | 2 | 30 min |
| Complex | 3 | 60 min |
| Highly complex | 3 | 90 min |
Exceeding any limit → ESCALATE to user with all evidence collected.
Spec-First Enforcement
Has spec?
YES → Continue
NO → Estimate size
trivial (<5 LOC) → Fix directly, no spec
micro (<30 LOC) → Create inline comment spec
mini (<100 LOC) → Create spec file (minimal)
standard (100+) → Create full spec (suggest `plan` first)
emergency/hotfix → Skip spec, log reasonSession Management
Uses same state machine as ship (see session-management.md).
Resume detects which phase was last completed:
- No progress → FRESH (start from classify)
- Phase 1 complete → Resume at Phase 2 (BASELINE)
- Mid-Phase 2 → Resume at last completed TDD step
Output
Follow the output template in references/templates/fix-output.md.
Intent Auto-Detection
| User Says | Agent Does |
|---|---|
| "emergency fix", "hotfix" | Skip spec ceremony, abbreviated TDD (RED + GREEN + DIFF) |
| "skip tests", "don't run tests" | Skip test gate (log reason) |
| "fix this too", "also fix" | Run SCAN-style sibling check |
Always document any skipped steps in output.
Never
- Never auto-fix sibling bugs without user approval
- Never auto-apply prevention rules — always propose, user approves (LEARN step)
- Never propose more than 2 prevention rules per fix (LEARN step)
- Never skip BASELINE + DIFF (anti-cascade core)
- Never make a change without a hypothesis (complex bugs)
- Never runs
git push - Never runs deploy commands
- Never makes production changes
- Never runs destructive git commands (
reset --hard,clean -f,push --force)
Focus Action
Agent: Load this file whenfocustriggers. Also loadreferences/reviews/production-standards.md— it provides extended checklists for scanning. Also loadreferences/rules-discovery.md— scan checks existing code against project/user rules.
Scan codebase against review perspectives, surface prioritized tasks toward production readiness. Output: ranked task proposals, user selects, specs created in specs/backlog/.
---
Task Tracking (MANDATORY)
Before starting, create tasks in your agent's built-in task/todo system:
[ ] Detect project (Step 0)
[ ] Scan existing specs (Step 1)
[ ] Ask goal (Step 2)
[ ] Dispatch perspective agents (Step 3)
[ ] Synthesize findings (Step 4)
[ ] Rank and present (Steps 5-6)
[ ] User selects → create specs (Step 7)---
Step 0: Detect Project
Reuse from plan.md:
Check project for:
- Monorepo (turbo.json)
- Package manager (pnpm/yarn/bun/npm from lockfile)
- Test runner (vitest/jest/pytest from config)
- Framework (next/expo/convex from package.json)
- Primary language (from file extensions, tsconfig, pyproject.toml)Also estimate codebase size:
| Size | Files | Agent Count |
|---|---|---|
| Small | <50 source files | 2-3 agents |
| Medium | 50-200 source files | 3-4 agents |
| Large | 200+ source files | 4-5 agents |
Count source files only (exclude node_modules, dist, .git, lockfiles, generated).
TypeScript Structural Snapshot (Optional)
If TypeScript detected (tsconfig.json exists):
Load references/codebase-intelligence.md for detection gate.
Run: npx codebase-intelligence overview --json <project-root>
→ Accurate file/module count (replaces manual estimation)
→ Dependency graph shape informs agent count decision
If CI unavailable: use file count estimation above---
Step 1: Scan Existing Specs
Scan all specs/ subfolders for existing work:
specs/active/ → Tag: [ACTIVE] — current work, show prominently
specs/backlog/ → Tag: [BACKLOG] — queued work, check for overlap with new findings
specs/dropped/ → Tag: [DROPPED] — abandoned, note learnings
specs/shipped/ → Tag: [SHIPPED] — last 10 by modification date only, context onlyFor each spec found, extract:
- Title, status, estimated effort
- Key scope items (what it covers)
Rules:
- If active spec exists, show it first — user may want to finish it before new work
- Dropped specs with relevant learnings: note what was learned, don't re-propose same approach
- Shipped specs: context only, never re-proposed
- Backlog specs that overlap with new findings: tag as
[BACKLOG], link to spec, skip duplicate proposal
---
Step 2: Ask Goal
Use interactive question (AskUserQuestion or equivalent):
What should we focus on?
1. Production readiness — Harden: tests, security, error handling, monitoring
2. MVP / ship value — Quickest path to user-visible value: TODOs, incomplete features, UX gaps
3. Infrastructure — Scale foundation: patterns, deps, type safety, duplication
4. Other — Custom focus (describe)Production readiness is ALWAYS the underlying lens. Goal selection changes weighting, not the baseline. Every scan checks production bar as minimum.
---
Step 3: Dispatch Perspective Agents
Dispatch parallel Explore agents. Each agent scans the codebase against assigned perspectives using checklists from references/reviews/production-standards.md.
This is NOT a diff review — agents scan the WHOLE codebase against perspective checklists.
Agent Assignment by Goal
| Goal | Primary Perspectives (weighted high) | Secondary (still checked) |
|---|---|---|
| Production | Security, Reliability, Observability, Testability | Correctness, Performance, DX, Scalability |
| MVP | Correctness, DX, Performance | Security, Reliability, Testability |
| Infra | Scalability, DX, Testability | Performance, Reliability, Security |
| Custom | Agent picks based on user description | Production baseline always |
Agent Distribution
Distribute 9 perspectives across agents (2-3 perspectives per agent):
Small codebase (2-3 agents):
Agent 1: Security, Reliability, Observability
Agent 2: Correctness, Performance, DX
Agent 3 (if needed): Scalability, Testability, Accessibility
Medium codebase (3-4 agents):
Agent 1: Security, Reliability
Agent 2: Correctness, Performance
Agent 3: DX, Scalability
Agent 4 (if needed): Observability, Testability, Accessibility
Large codebase (4-5 agents):
Agent 1: Security, Reliability
Agent 2: Correctness, Performance
Agent 3: DX, Testability
Agent 4: Scalability, Observability
Agent 5 (if needed): Accessibility + overflowSkip Accessibility unless UI components detected in codebase.
Agent Prompt Template
Each agent receives:
Scan this codebase against the following review perspectives.
You are scanning the WHOLE codebase, not reviewing a diff.
Perspectives assigned: {perspective names}
For each perspective, use this checklist:
{paste extended checklist items from production-standards.md for assigned perspectives}
Instructions:
1. Use Glob to find relevant source files (skip node_modules, dist, .git, generated)
2. Use Grep to search for patterns related to checklist items
3. Use Read to examine files with potential issues
4. For each finding, propose a CONCRETE TASK (not an observation):
- BAD: "Missing error handling detected"
- GOOD: "Add error handling to database queries in src/db/users.ts"
{if TypeScript project with CI available, add to each agent prompt:}
5b. Use these pre-computed structural insights (from codebase-intelligence --json):
- HOTSPOTS: {output of `npx codebase-intelligence hotspots --json --metric complexity --limit 20`}
- DEAD EXPORTS: {output of `npx codebase-intelligence dead-exports --json --limit 20`}
- FORCES: {output of `npx codebase-intelligence forces --json`}
- MODULES: {output of `npx codebase-intelligence modules --json`}
Cross-reference these with your Glob/Grep/Read findings.
Hotspots data replaces sampling strategy for TypeScript files.
5. Score each task:
- Impact: H (affects users/security/data) / M (affects DX/maintainability) / L (cosmetic/minor)
- Effort: L (<1h) / M (1-4h) / H (4h+)
- Risk-if-ignored: H (will cause incidents) / M (will slow team) / L (annoyance)
6. Include file evidence: path:line for each finding
7. Focus on {primary perspectives} — these are weighted highest for the "{goal}" goal
Output format per task:
Task: {actionable task description}
Perspective: {which perspective flagged this}
Impact: H/M/L
Effort: L/M/H
Risk: H/M/L
Evidence: {file:line — brief description}Sampling Strategy (Large Codebases)
For 500+ source files, agents should focus on: 1. Files changed in last 30 days (recent activity = higher relevance) 2. Entry points (main files, route handlers, API endpoints) 3. Critical paths (auth, payments, data mutations) 4. Files with TODOs/FIXMEs/HACKs 5. Files without test coverage (look for missing *.test.* counterparts)
TypeScript projects with CI: hotspots data from codebase-intelligence replaces sampling heuristics for TS/TSX files. Non-TS files in the same project still use the sampling strategy above.
---
Step 4: Synthesize
Collect results from all agents. Process:
1. Deduplicate: Merge tasks pointing at same file/issue from different perspectives 2. Cross-reference with existing specs: If a finding overlaps with a backlog/active spec, tag it [BACKLOG]/[ACTIVE] instead of proposing as new 3. Merge related tasks: Group small tasks into logical units (e.g., "Add error handling to 3 DB query files" → one task) 4. Validate evidence: Ensure file:line references are real (agents may hallucinate)
---
Step 5: Rank
Scoring Formula
score = (w_impact * impact) + (w_effort * (4 - effort)) + (w_risk * risk)Where impact/effort/risk are: H=3, M=2, L=1
Goal Weights
| Goal | w_impact | w_effort | w_risk |
|---|---|---|---|
| Production | 3 | 1 | 5 |
| MVP | 5 | 3 | 1 |
| Infra | 2 | 2 | 2 |
| Custom | 3 | 2 | 3 |
Tier Assignment
Sort by score descending, then group:
| Tier | Criteria | Description |
|---|---|---|
| Do First | High impact + Low effort | Maximum value, minimum cost |
| Plan Next | High impact + Medium/High effort | Needs spec, worth the investment |
| Quick Wins | Medium impact + Low effort | Easy improvements, good momentum |
Cap at 10-15 tasks total. If more found, keep highest-scored.
---
Step 6: Present
Output per references/templates/focus-output.md.
Include:
- Perspective summary (gaps per perspective)
- Existing specs (if any found in Step 1)
- Ranked task tables by tier
- Production readiness score (quick health check per perspective)
- Effort estimates use same calibration as plan.md: aggressive, AI-assisted
---
Step 7: User Selects
Use interactive multi-select (AskUserQuestion multiSelect or equivalent):
Select tasks to plan (select multiple):
1. {task description} (Effort: {est}, Perspective: {name})
2. ...For each selected task:
1. Invoke plan action with the task as the idea 2. Spec created in specs/backlog/ (NOT specs/active/) 3. User manually moves to specs/active/ when ready to ship
If user selects a task that overlaps with existing backlog spec, note it instead of creating duplicate.
---
Edge Cases
| Case | Handle |
|---|---|
| Empty codebase (no source files) | "No code to analyze. Run plan {idea} to start." |
| No findings | "Production-ready baseline met. Run plan {idea} for new features." |
| All tasks >4h effort | Flag: "Large scope tasks — will split during plan phase." |
| Existing spec covers finding | Tag [BACKLOG]/[DROPPED], link to spec, skip duplicate |
| Active spec exists | Show prominently: "Active work in progress — finish first?" |
| Many shipped specs (>10) | Only load last 10 by modification date |
| No test runner detected | Note in testability perspective: "No test infrastructure — propose setup as task" |
---
Lifecycle Position
focus → plan → ship → done → focus (repeat)
│ ▲
└──────────────────────────────┘Focus is the entry point when you don't know what to work on next. It completes the cycle by feeding back into plan.
Plan Action
Agent: Load this file whenplantriggers. Also loadreferences/spec-template.md— it defines spec structure and validation rules. Also loadreferences/rules-discovery.md— plans must respect project/user conventions.
BLOCKING: Never delegate planning to the host agent's built-in plan mode. This skill manages its own planning by writing spec files to specs/active/. Always stay in the agent's normal execution mode — read, write, and execute directly.
Parse idea, create spec, estimate effort. Output: spec file ready for ship.
The spec template (`references/spec-template.md`) is the SINGLE SOURCE OF TRUTH for spec structure, generation rules, and validation. This file defines the orchestration — template defines the content.
---
Task Tracking (MANDATORY for mini/standard)
Before starting planning, create tasks in your agent's built-in task/todo system:
[ ] Parse idea and identify scope
[ ] Discover test environment (read existing tests, identify patterns)
[ ] Codebase impact analysis (read affected code, map dependencies)
[ ] Generate spec (following spec-template.md generation order)
[ ] Generate test strategy (AC mapping + failure mode tests + mock avoidance plan)
[ ] Spec analysis (adversarial review of generated spec)
[ ] Run dev-readiness check (spec-template.md validation rules)
[ ] All dev-readiness gates PASSUpdate tasks as you work. One in-progress at a time.
Step 0: Detect Project + Test Environment
Check project for:
- Monorepo (turbo.json)
- Package manager (pnpm/yarn/bun/npm from lockfile)
- Test runner (vitest/jest/pytest from config)
- E2E framework (playwright/cypress/maestro/detox from config)
- Framework (next/expo/convex from package.json)
Deep test discovery (feeds spec Test Strategy):
- Read 3+ existing test files → understand patterns, conventions, helpers
- Identify: test DB strategy, mock inventory, existing E2E tests, test utilities
- Produce "Test Environment Profile" for spec's Test Strategy section
- If no test infra: flag "not configured" with specific recommendation
- If no E2E infra but unit tests exist: flag "partial — E2E setup needed at ship"TypeScript Structural Analysis (Optional)
If TypeScript detected (tsconfig.json exists):
Load references/codebase-intelligence.md for detection gate and command reference.
Run: npx codebase-intelligence overview --json <project-root>
→ Captures: file count, module count, dependency graph shape, top-level metrics
→ Store as "CI Snapshot" for Codebase Impact section
If CI unavailable: skip — grep/glob/read discovery continues as normalStep 1: Parse Idea
Extract from user input:
- What: Feature/fix description
- Why: Problem being solved
- Who: User persona affected
- Scope signal: Size estimate (trivial/micro/mini/standard)
Step 2: Select Thinking Pattern
| Situation | Pattern |
|---|---|
| Clear requirements | Chain-of-thought — step by step |
| Multiple approaches | Tree-of-thought — enumerate, score, choose |
| After failure | Reflexion — record failure, adjust, retry |
| Large scope | Decomposition — split into independent parts |
Step 3: Generate Spec
Follow `references/spec-template.md` exactly. The template defines:
- Generation order (context → codebase → journey → ACs → scope → checklist → test strategy → risks → state → analysis)
- Per-section generation rules
- Traceability requirements
- Validation rules
Key principle: Read the codebase BEFORE writing the spec. Codebase impact analysis is MANDATORY and informs every section that follows.
TypeScript projects with CI available (augments grep/glob/read, does not replace):
For each file identified in Codebase Impact table:
npx codebase-intelligence file --json <file>
→ Adds: imports, exports, coupling score, complexity
npx codebase-intelligence dependents --json <file>
→ Adds: files affected by changes → populates AFFECTED rows
For key symbols being changed:
npx codebase-intelligence impact --json <symbol>
→ Adds: blast radius data for Breaking Changes assessment
If CI unavailable: use grep for imports/exports, manual trace for dependentsCreate spec file at specs/active/{YYYY-MM-DD}-{slug}.md.
Tier Selection
| Tier | Size | Spec |
|---|---|---|
| trivial | <5 LOC | None — just implement |
| micro | <30 LOC | Inline comment in code |
| mini | <100 LOC | Mini template (see spec-template.md) |
| standard | 100+ LOC | Full template (see spec-template.md) |
Pre-Mortem (Standard Tier)
Assume the feature failed. Why?
For each risk:
Impact: HIGH/MEDIUM/LOW
Likelihood: HIGH/MEDIUM/LOW
Mitigation: What prevents this?
Kill criteria: When do we abandon this approach?For stateful features, include state machine analysis (see spec-template.md).
Step 3.3: Generate Test Strategy (MANDATORY for mini/standard)
After spec generation, before analysis. Write the Test Strategy section into the spec.
1. Include Test Environment Profile from Step 0 discovery
2. Map each AC to test type:
- Pure function (no I/O, no side effects) → unit test
- Everything else → E2E test (default)
3. Map each Error Journey (E1, E2...) → E2E test intention
4. Map each Edge Case (EC1, EC2...) → E2E test intention
5. Mock avoidance plan — for each external dependency:
- Does it have a sandbox/test mode? → use real
- Docker image available? → containerize
- In-memory equivalent? → use it
- None available? → mock with justification
6. Write Test Strategy section into spec (see spec-template.md)Failure hypotheses from Step 3.5 will feed back into Test Strategy (see below).
Step 3.5: Spec Analysis (MANDATORY for mini/standard)
After generating the spec and Test Strategy, run adversarial analysis to populate the Analysis section.
Failure hypothesis → Test Strategy feedback: After analysis generates failure hypotheses, add defensive E2E test for each HIGH/MED hypothesis to the Test Strategy section. Update the Failure Mode Tests table.
Mode by Tier
| Tier | Mode | Agents | Min Requirements |
|---|---|---|---|
| mini | Inline | None (single-agent) | 3 assumptions, 1-2 blind spots, 1 failure hypothesis |
| standard | Parallel sub-agents | 2-3 | 3-5 assumptions, 2-4 blind spots, 3 failure hypotheses |
Mini Mode (inline)
Apply 4 techniques sequentially (single agent, no sub-agents):
1. Challenge assumptions: List 3+ assumptions from the spec. For each: evidence for, against, verdict (VALID/RISKY/WRONG) 2. Find blind spots: What hasn't been considered? 1-2 items with category + impact 3. Failure hypothesis: IF {trigger} THEN {failure} BECAUSE {cause}. At least 1. 4. Reframe: Is this solving the right problem? Confirm or reframe.
Write results directly into spec's ## Analysis section.
Standard Mode (parallel sub-agents)
1. Read the spec's context, scope, codebase impact, and risks 2. Self-select 2-3 analysis perspectives most relevant to THIS spec's domain:
- Always include 1 Skeptic (domain-agnostic adversarial thinker)
- Add 1-2 domain-relevant perspectives (e.g., Security Engineer for auth, UX Designer for UI, Data Engineer for migrations)
3. Launch all perspectives as parallel sub-agents (single message, multiple Task tool calls) 4. Each agent receives: full spec + relevant codebase files from Codebase Impact 5. Each agent produces: assumptions table, blind spots, failure hypotheses, reframe 6. Synthesize: merge findings, deduplicate, rank by severity 7. Write synthesized results into spec's ## Analysis section
Rules
- Cross-reference against actual codebase (not just spec text)
- Every finding must be action-driven:
→ update spec/→ explore/→ question/→ no action - No passive observations — each finding forces a decision
- If analysis reveals spec gaps → update spec before proceeding to Step 4
Step 4: Spec Review
Before finalizing, self-verify:
| Check | Question |
|---|---|
| Clarity | Could another developer implement from this spec alone? |
| Scope | Can this ship today? Anything cuttable? |
| Testability | Is every scope item verifiable? Does every failure mode have a planned test? |
| Test Strategy | Does Test Strategy exist? Are all ACs mapped? Are failure hypotheses covered? |
| Risks | Are kill criteria defined for high risks? |
| Completeness | Quality checklist covers edge cases? |
| Codebase | Did I actually read the code? Are affected files mapped? |
If any check fails, revise the spec before outputting.
Step 5: Manual Review Gate
BLOCKING for standard tier. Pause for human approval before dev-readiness check.
When user requests review ("review the spec", "let me check") or tier is standard, pause for human review before dev.
Review Notation
Reviewers annotate the spec with inline markers:
| Marker | Meaning |
|---|---|
[?] | Unclear — needs clarification |
[!] | Risk — not addressed or underestimated |
[+] | Missing — should be added to scope |
[-] | Cut — remove from scope (over-engineered) |
[~] | Rephrase — intent is right, wording is wrong |
[ok] | Approved — explicitly signed off |
Review Flow
Spec created
│
▼
Present spec for review
│
├─ All [ok], no [?]/[!] ──▶ READY
│
├─ Has [?] or [~] ────────▶ NEEDS_WORK → revise, re-present
│
├─ Has [!] ───────────────▶ NOT_READY → address risks, re-review
│
└─ Has [+] or [-] ────────▶ CONDITIONAL → apply scope changes, re-scoreMax 3 rounds. After round 3: must reach READY or user says "proceed anyway".
Step 6: Dev-Readiness Check
BLOCKING gate before `ship` can start.
Run the validation rules from references/spec-template.md (Validation Rules table). All 14 rules must pass.
Readiness Algorithm
ready_to_dev(spec):
Run all validation rules from spec-template.md
mandatory_fails = rules 1-8 that fail
standard_fails = rules 9-14 that fail
IF len(all_fails) == 0:
RETURN READY
ELIF mandatory_fails:
RETURN NOT_READY (cannot proceed)
ELIF only standard_fails:
RETURN CONDITIONAL (can proceed with acknowledgment)Additional checks (beyond template validation):
# Estimate within same-day
IF estimate > 8h:
WARN "Exceeds same-day. Split or cut scope."
# Risks addressed (standard tier)
IF tier == standard AND unmitigated HIGH risks:
BLOCK "Unmitigated HIGH risks: {list}"
# Dependencies resolved
IF external blockers (APIs, access, data):
BLOCK "Unresolved dependencies: {list}"
# Manual review (if requested)
IF review_required AND verdict != READY:
BLOCK "Spec review not approved"Step 7: Output
Follow the output template in `references/templates/plan-output.md`.
Always return: file path, status, codebase impact, analysis (improvements + gaps + questions + risks), readiness scorecard.
Dev-Readiness State Diagram
plan {idea}
│
▼
┌───────────┐
│ DRAFT │
│ (spec │
│ created) │
└─────┬─────┘
│
┌────────────┼────────────┐
│ │ │
(user asks (auto-check) (trivial/micro)
for review) │ │
│ │ │
▼ ▼ ▼
┌────────────┐ ┌─────────┐ ┌───────┐
│ REVIEWING │ │ CHECKING│ │ READY │──▶ ship
│ (human) │ │ (auto) │ │ (skip)│
└──────┬─────┘ └────┬────┘ └───────┘
│ │
[?][!][-][+] blockers?
│ │
┌────┴────┐ ┌───┴────┐
│ Revise │ │ FIX │
│ (max 3) │ │blockers│
└────┬────┘ └───┬────┘
│ │
▼ ▼
┌────────────┐ ┌─────────┐
│ APPROVED │ │ CLEAR │
│ (verdict: │ │ (0 │
│ READY) │ │ blockers│
└──────┬─────┘ └────┬────┘
│ │
└──────┬──────┘
▼
┌───────────┐
│ DEV_READY │──▶ ship
└───────────┘Tier Bypass
- trivial (<5 LOC): Skip spec creation entirely. Just implement.
- micro (<30 LOC): Inline spec as code comment. No file.
- mini (<100 LOC): Mini template from spec-template.md.
- standard (100+ LOC): Full template from spec-template.md.
- Emergency: User says "emergency fix" or "hotfix" → skip spec, log reason in history.
Review Action
Agent: Load this file whenreviewtriggers or during ship loop review cycles. Also loadreferences/rules-discovery.md— discovered rules become the Rules perspective checklist.
Auto-selecting multi-perspective code review. Runs during ship loop or standalone.
Portability rule: this file defines the review contract, not a specific runtime implementation. Use references/reviews/core-portable-review-spec.md as the normative portable standard. Runtime-specific orchestration is optional and belongs in executor guidance, not in the core contract.
Implementation note: command snippets and tool names in this file are illustrative examples, not mandatory dependencies. Any executor may substitute equivalent mechanisms as long as it preserves the same coverage, rule-checking, and artifact requirements.
---
Step 1: Change Overview (ALWAYS FIRST)
Before any review, build a change map and a line-coverage ledger:
1. git diff --name-status (vs base branch or last review)
2. git diff --unified=0 --no-color ...
→ enumerate every changed hunk with exact line ranges
→ build a ledger per file: added lines, modified lines, deleted lines
3. Per file, classify:
- Category: auth/security | API/public | DB/schema | UI/component |
config/infra | test | docs | internal logic
- Risk: HIGH | MEDIUM | LOW
4. Detect primary language + framework from changed files
5. Detect context signals (see Step 2)
6. **TypeScript structural risk** (if CI available, see `references/codebase-intelligence.md`):
Run: `npx codebase-intelligence changes --json`
→ Augments git diff with coupling score, blast radius, and complexity delta per file
→ Use to refine Risk Classification below (more precise than filename-based heuristics)
If CI unavailable: use filename-based risk classification onlyCore Portable Review Contract (MANDATORY)
See references/reviews/core-portable-review-spec.md for the normative portable contract and references/reviews/executor-patterns.md for optional implementation examples.
This action file describes the workflow-level review policy. It must remain valid whether review is executed by one agent, many agents, a CI system, or a human operator.
Coverage Contract (MANDATORY)
No sampling. No “looks fine overall.” No skipping low-risk hunks.
For review, the agent must prove two kinds of coverage before returning a clean verdict:
1. Line coverage — every changed line range in the diff ledger is checked at least once. 2. Rule coverage — every relevant discovered rule is checked one by one against the changed scope.
Minimum enforcement:
For each changed file:
For each changed hunk / line range:
assign ≥1 perspective owner
inspect the exact changed lines, not just surrounding file context
For each relevant discovered rule:
check it explicitly against each changed file/hunk it applies to
record: PASS | WARN | FAIL | NOT_APPLICABLEIf any changed line range has no explicit review coverage, or any relevant rule is left unchecked, the review must emit a blocking process finding:
{file}:{line or range} — FAIL [Process] Changed lines not explicitly reviewed
Fix: Review the uncovered lines and record perspective coverageRisk Classification
| Risk | File Categories |
|---|---|
| HIGH | auth, payments, DB schema/migrations, public API, delete operations, crypto |
| MEDIUM | config, new dependencies, performance-critical paths, CI/CD, infrastructure |
| LOW | internal logic, tests, docs, formatting, comments, private utilities |
Output: Change Map
| File | Changed lines | Category | Risk | Language |
|------|---------------|----------|------|----------|This table appears in the review output (see references/templates/review-output.md).
---
Step 2: Auto-Select Mode
Mode is determined by signals from the change map. Agent selects — not the user.
| Signal | Mode |
|---|---|
| 1-2 files, all LOW risk, no API changes | Quick |
| 3-5 files OR any MEDIUM risk | Standard |
| 6+ files OR any HIGH risk file | Deep |
| Deploy context detected (see below) | Production |
Deploy Context Signals (ANY ONE triggers Production)
- User said: "production ready", "pre-deploy", "deploy", "release", "production review"
- Merging to main/master branch (detected from git context)
- Ship loop exit check (final review before
done) - Changed files include: CI/CD config, Dockerfile, k8s manifests, terraform
- User explicitly requests: "review production"
Multiple signals: highest mode wins.
Announce selection before reviewing:
Review mode: {MODE} — {reason}Example: Review mode: Deep — HIGH risk file detected (src/api/auth.ts: auth/security)
---
Step 3: Execute Review
Rules Discovery (MANDATORY — Before Perspective Dispatch)
Load references/rules-discovery.md and execute Steps 1-4. This discovers project/user agent config files, extracts rules, filters for relevance against the change map, and classifies severity. The discovered rules become the checklist for the Rules perspective (#10).
No config files found or no relevant rules → skip Rules perspective entirely.
Important: rules are not satisfied by a global statement like “follow project rules.” The review must check each relevant rule individually and mark it PASS/WARN/FAIL/NOT_APPLICABLE against the changed scope.
Quick Mode
- Perspectives: Core 5 + Rules (if rules files exist)
- Checklist depth: 6 items per perspective (key questions below)
- Context loaded: This file only
Standard Mode
- Perspectives: Core 5 + Rules (if rules files exist) + auto-triggered conditionals
- Checklist depth: 6 items per perspective
- Context loaded: This file only
- Conditional triggers:
| Perspective | Triggers On |
|---|---|
| Scalability | Shared state, DB queries, multi-instance deployment, pub/sub, queues |
| Observability | Production service, background job, API endpoint, webhook handler |
| Testability | Complex branching (>=3 paths), critical business logic, stateful flows |
| Accessibility | UI components, forms, navigation, interactive elements |
Structural Context (TypeScript projects with CI or equivalent tooling)
Before dispatching perspectives in Standard/Deep/Production modes, gather structural data when compatible tooling exists.
Example implementation:
For each changed TS/TSX file:
npx codebase-intelligence dependents --json <file>
→ Consumer awareness: who imports this? What could break?
npx codebase-intelligence forces --json
→ Cohesion/coupling metrics for architectural review
Include in perspective agent context alongside file contents and diff.
If CI unavailable: perspectives rely on file contents + grep-based import tracing.Deep Mode
- Perspectives: All 9 + Rules (if rules files exist)
- Checklist depth: 6 items per perspective
- Context loaded: This file only
Production Mode
- Perspectives: All 9 + Rules (if rules files exist; ambiguous rule signals → FAIL)
- Checklist depth: 15-20 items per perspective (extended checklists)
- Context loaded: This file +
references/reviews/production-standards.md - Additional: Expert personas, company bar evaluation, language-specific overlay
Production execution (example implementation):
1. Load references/reviews/production-standards.md
2. IF WebSearch/web capabilities available:
Search in parallel:
"{language} production code review checklist {year} best practices"
"{framework} production best practices {year} common mistakes"
"{language} anti-patterns production code {year}"
Synthesize into language-specific overlay
ELSE:
Use fallback language standards from production-standards.md Section D
3. Per perspective:
a. Adopt expert persona (Section B)
b. Apply extended checklist (Section C)
c. Apply language-specific overlay (dynamic or fallback)
d. Evaluate against production bar (Section A)
4. Output with production format (BLOCKS_PRODUCTION severity)---
Perspectives
Core (Always Active)
| # | Perspective | Key Questions |
|---|---|---|
| 1 | Correctness | Does it do the right thing? Edge cases? Regressions? |
| 2 | Security | Input validated? Auth correct? Secrets safe? No injection? |
| 3 | Reliability | Error paths handled? Graceful degradation? Timeouts? Cleanup? |
| 4 | Performance | N+1 queries? Unnecessary computation? Bundle impact? Hot path? |
| 5 | DX | Readable? Good names? Actionable errors? Types guide usage? |
Rules (Active When Rules Files Exist)
| # | Perspective | Trigger | Key Questions |
|---|---|---|---|
| 10 | Rules | Any agent config found (AGENTS.md, CLAUDE.md, .cursorrules, codex.md, .opencode/config, etc.) | Violates project conventions? Contradicts user rules? Ignores documented anti-patterns? |
The Rules perspective uses discovered rules as its checklist (not a built-in checklist). Each finding cites the source file and violated rule text.
Conditional (Add When Triggered)
| # | Perspective | Trigger | Key Questions |
|---|---|---|---|
| 6 | Scalability | Shared state, DB, multi-instance | Thread safe? Works at 10x? Horizontally scalable? |
| 7 | Observability | Production service, background job | Structured logging? Metrics? Traceable? Health signals? |
| 8 | Testability | Complex branching, critical logic | Tests exist? Assert behavior not implementation? Coverage gaps? |
| 9 | Accessibility | UI components | Semantic HTML? Keyboard nav? Screen reader? Contrast? |
---
Execution (All Modes)
For each active perspective:
1. Read all changed files
2. Use the diff ledger to inspect every changed line range owned by that perspective
3. Evaluate against perspective checklist (depth matches mode)
4. Classify findings:
- PASS: Meets criteria (not shown in output)
- WARN: Concern, not blocking (severity: low/medium/high)
- FAIL: Must fix before shipping (BLOCKING)
- BLOCKS_PRODUCTION: Violates production bar (Production mode only)
5. Update coverage ledger for the reviewed line rangesRun perspectives in parallel when possible.
Parallelism is optional. Executors may review sequentially or in parallel as long as they preserve the same coverage and artifact requirements.
After all perspectives complete:
1. Verify every changed line range is covered
2. Verify every relevant rule has an explicit verdict
3. Emit FAIL [Process] for each uncovered line range or unchecked rule
4. Only return CLEAN / WARNINGS_ONLY when both coverage checks are complete and the output includes the rule coverage ledger---
Output
Follow references/templates/review-output.md for the human-readable summary.
In addition, emit a machine-readable artifact equivalent to the schema in references/reviews/core-portable-review-spec.md.
Key format: {file}:{line} — {severity} [{perspective}] {description} + Fix: {action}.
Process coverage gaps use the same format with [Process] as the perspective.
Production mode adds: Standard: {Company} — {rule violated} line under BLOCKS_PRODUCTION findings.
---
Iteration Limit
Max 3 review iterations per ship cycle. If still blocking after 3:
- Present remaining issues to user
- User decides: fix, defer, or accept risk
---
Review Triggers (During Ship Loop)
| Condition | Review? |
|---|---|
| Every 2-3 implementation iterations | Yes (auto-select) |
| Before exit check | Yes (auto-select, leans Production) |
User requests review | Yes (auto-select, user can override mode) |
| Security-sensitive code changed | Yes (auto-select, min Standard) |
| Public API changed | Yes (auto-select, min Standard) |
Ship Action
Agent: Load this file whenshiptriggers. Also loadreferences/quality-gates.mdfor gate commands,references/session-management.mdfor resume/stuck detection, andreferences/rules-discovery.md— code must follow project/user rules.
Implement features with a build/review/fix loop. Handles both quick one-shot and iterative spec-driven work.
Bug fix? Use the fix action instead. See fix.md.
---
Mode Detection
Active spec in specs/active/?
YES → LOOP mode (iterate until spec complete)
NO → ONE-SHOT mode (create inline spec, implement, validate)Task Tracking (MANDATORY for mini/standard)
Before starting any implementation, create tasks in your agent's built-in task/todo system. Track what to build AND what to validate.
Create these tasks at the start of each ship cycle:
[ ] {scope item 1} → AC-{N}
[ ] {scope item 2} → AC-{N}
[ ] ...
[ ] Create e2e-scenarios.md registry from spec ACs
[ ] Generate E2E tests (TDD: RED before implementation)
[ ] Quick pass: lint + typecheck (changed files)
[ ] Review: run perspectives
[ ] Fix BLOCKING issues
[ ] Full pass: lint (changed) + typecheck (full) + build (full) + test (related) + E2E (registry) + coverage (advisory)
[ ] Exit check: all Must Have ACs + Error ACs + scope items + e2e_coverage passingUpdate tasks as you work: mark in-progress when starting, complete when done. One task in-progress at a time.
Phase 0: Setup
1. Detect project stack (monorepo, framework, test runner, linter, E2E framework) 1b. TypeScript structural analysis (if tsconfig.json detected): Load references/codebase-intelligence.md, run detection gate. Run: npx codebase-intelligence overview --json <project-root> → Augments stack detection with module structure, dependency graph, file metrics. If CI unavailable: proceed with standard stack detection only. 2. Validate test environment:
- Load spec's Test Strategy (from plan phase, if exists)
- If no Test Strategy: run test setup discovery now (load references/testing-automation.md)
- If no E2E infra detected: PROPOSE setup to user with specific recommendation
- If user declines: document, downgrade E2E gate to ADVISORY for this session
- If user accepts: install + configure before first iteration
- Validate mock avoidance plan: check if proposed mocks can use real alternatives
3. Load active spec (if LOOP mode) or create inline spec (ONE-SHOT) 4. Detect resume state (see session-management.md):
- FRESH: No prior work — start from beginning
- RESUMING: Prior progress found — resume from last checkpoint
- STUCK: Multiple failed iterations — escalate
- READY_FOR_DONE: All scope complete — suggest
done
Spec-First Enforcement
Has spec?
YES → Continue
NO → Estimate size
trivial (<5 LOC) → Implement directly, no spec
micro (<30 LOC) → Create inline comment spec
mini (<100 LOC) → Create spec file (minimal)
standard (100+) → Create full spec (suggest `plan` first)
emergency/hotfix → Skip spec, log reasonONE-SHOT Flow
For quick fixes and small features without an active spec:
1. Analyze scope (files affected, estimated LOC)
1b. **TypeScript scope analysis** (if CI available):
`npx codebase-intelligence dependents --json <file>` for each affected file → reveals non-obvious consumers.
For refactoring: `npx codebase-intelligence rename --json <path> <symbol>` → discovers all references before changes.
If CI unavailable: use grep for scope analysis.
2. Run test setup discovery (load references/testing-automation.md)
3. Create plan (brief, inline)
4. Write E2E test for key behavior (RED — MUST FAIL)
5. Implement
6. Run E2E test (GREEN — MUST PASS)
7. Quality gates (lint → typecheck → build → test → E2E → coverage)
8. Self-review (re-read all changes)
9. Output summaryLOOP Flow (Ship Loop)
Core iteration algorithm for spec-driven work:
iteration = 0
max_iterations = spec.max_iterations OR default_by_size()
stuck_threshold = max(3, max_iterations / 2)
WHILE iteration < max_iterations:
iteration++
# 1. SELECT
Pick next unchecked scope item
# 1b. TDD-ENFORCED TEST GENERATION (BEFORE implementation)
Load ACs + Test Strategy for current scope item
Create e2e-scenarios.md registry entries if not exists (iteration 1)
Write E2E test asserting correct behavior (use real systems per mock avoidance hierarchy)
Run test → MUST FAIL (RED). Log RED_CONFIRMED in registry.
If PASS → wrong test — rewrite to test new behavior
Implement scope item (minimal — just enough to pass)
Run test → MUST PASS (GREEN). Log GREEN_CONFIRMED in registry.
If FAIL → fix implementation, not test
Refactor if needed → re-run → still PASS
Mock audit: if any mock added, verify it follows avoidance hierarchy
Run quick quality pass (lint + typecheck on changed files)
Mark scope item [x] if passing
# 2. REVIEW (every 2-3 iterations or on request)
Run multi-perspective review (see actions/review.md)
Collect issues: BLOCKING vs WARN
# 3. FIX
Fix all BLOCKING issues
Log WARN issues in spec notes
# 4. EXIT CHECK
all_must_have_acs = all Must Have ACs checked [x]
all_error_acs = all Error Criteria ACs checked [x]
all_scope_complete = all spec scope items checked [x]
quality_clean = lint + typecheck + build + test all pass
e2e_coverage = all BLOCKING e2e-scenarios entries GREEN_CONFIRMED
tdd_proof = every GREEN_CONFIRMED has prior RED_CONFIRMED
no_blockers = no BLOCKING review issues
IF all_must_have_acs AND all_error_acs AND all_scope_complete
AND quality_clean AND e2e_coverage AND tdd_proof AND no_blockers:
EXIT → clean (suggest `done`)
# ACs are the source of truth for "is work done?"
# Scope items track implementation progress.
# Both must be complete.
# 5. STUCK DETECTION
progress = scope_items_completed / total_scope_items
IF iteration >= stuck_threshold AND progress < 0.5:
ESCALATE (see Stuck Escalation below)Default Iterations by Size
| Size | Max Iterations | Stuck Threshold |
|---|---|---|
| mini | 5 | 3 |
| standard (small) | 8 | 4 |
| standard (medium) | 12 | 6 |
| standard (large) | 20 | 10 |
Quality Gates (Per Iteration)
Quick pass (after each edit batch):
- Lint changed files
- Typecheck changed files
E2E pass (after each scope item TDD cycle):
- Verify RED_CONFIRMED logged for current AC
- Verify GREEN_CONFIRMED logged after implementation
- Mock audit: no new mocks of own code
Full pass (before exit):
- Lint changed files
- Typecheck full project
- Build full project
- Test related tests
- E2E registry validation (all BLOCKING entries GREEN_CONFIRMED)
- TDD proof (every GREEN has prior RED)
- Coverage check (advisory — warn on >5% drop)
Auto-detect tooling from project files. See references/quality-gates.md.
Stuck Escalation
Three levels, triggered by lack of progress:
| Level | Trigger | Action |
|---|---|---|
| Warning | At stuck_threshold, progress < 50% | Log warning, continue |
| Pause | 2 iterations after warning, no progress | Present options to user |
| Hard stop | At max_iterations | Force exit with summary |
Pause options: 1. Continue with different approach 2. Reduce scope (cut items) 3. Defer to next session 4. Drop feature entirely
Bug Encounter Protocol
When a bug is found during feature implementation:
1. Log bug in spec under "## Encountered Bugs"
Format: BUG-{N}: {summary} | Status: Investigating/Fixed/Deferred
2. Classify: blocks current scope item? (Y/N)
3. If blocking: pause ship, run `fix` action (see fix.md)
4. If non-blocking: defer, continue with scope
5. All bugs must be Fixed or Deferred before `done`Resume after fix: When the fix action completes, it updates the spec's Encountered Bugs section and Progress table (LEARN step). Ship resumes automatically:
fix completes → spec updated with BUG-{N} status: Fixed
→ ship detects RESUMING state (session-management.md)
→ reads spec Progress section
→ finds first non-[x] scope item
→ continues implementation from that point
→ runs quick quality pass before continuingThe handoff is seamless because both actions share the same spec file and session management state machine.
Review Integration
Review runs automatically during ship loop. Perspectives:
Core (always): Correctness, Security, Reliability, Performance, DX Conditional: Scalability, Observability, Testability, Accessibility
See actions/review.md for full perspective details.
Progress Tracking
Update spec after each iteration:
## Progress
| Item | Status | Iteration |
|------|--------|-----------|
| Scope item 1 | [x] Complete | 2 |
| Scope item 2 | [~] In progress | 3 |
| Scope item 3 | [ ] Pending | - |Output
Follow the output template in references/templates/ship-output.md.
Covers: iteration output, 4 exit states (clean/partial/stuck/hard stop), spec mutation output.
Exit states:
| State | Condition |
|---|---|
| Clean | All Must Have + Error ACs pass, all scope done, gates green (6 gates), e2e_coverage 100%, tdd_proof clean, no blockers |
| Partial | Scope done but ACs failing |
| Stuck | Hit stuck threshold, user chose to stop |
| Hard stop | Hit max iterations |
Risk Flag System
After each implementation step, assess risk level of changes:
For each changed file, check:
Auth/security logic? → HIGH
DB schema/migration? → HIGH
Payment/billing? → HIGH
Public API contract? → HIGH
Delete/destructive op? → HIGH
Config/environment? → MEDIUM
New dependency? → MEDIUM
Performance-critical path? → MEDIUM
Internal refactor? → LOW
Tests/docs only? → LOW
Highest risk across all changes = overall risk| Risk | Action |
|---|---|
| LOW | Continue autonomously |
| MEDIUM | Note in spec, mention in self-review |
| HIGH | PAUSE. Present to user: what changed, what could go wrong, recommendation. User approves before continuing. |
Configurable by editing this file directly.
Production Validation
Concrete checks for production deploys. Run these in addition to standard gates.
Auto-detect and run (if tooling exists):
1. Dependency vulnerability scan
npm audit / pnpm audit / yarn audit / pip-audit / cargo audit
Level: BLOCKING (critical/high), ADVISORY (moderate/low)
2. Security scan
Check for: hardcoded secrets, SQL injection patterns,
XSS vectors, open redirects, insecure dependencies
Level: BLOCKING
3. Build verification
Full production build (not dev build)
Command: {framework build command} with production flags
Level: BLOCKING
4. Smoke test (if test infrastructure supports it)
Start server, hit health endpoint, verify response
Level: ADVISORY
5. Bundle/artifact size check
Compare to previous build if baseline exists
Level: ADVISORY (warn if >20% increase)
6. Schema validation (if schema files changed)
Verify migration is reversible
Check for breaking changes in API contracts
Level: BLOCKINGIntent Auto-Detection
No flags needed. The agent detects intent from natural language:
| User Says | Agent Does |
|---|---|
| "emergency fix", "hotfix" | Route to fix action with abbreviated mode |
| "skip tests", "don't run tests" | Skip test gate (log reason) |
| "skip review" | Skip review perspectives |
| "deploy to production", "production ready" | Run production validation |
| "force it", "proceed anyway" | Proceed past CONDITIONAL readiness |
Always document any skipped gates in output.
Parallel Execution
When scope items are independent (no shared files), they can be implemented in parallel if your agent supports multi-tool or concurrent execution.
Check: Do scope items share files in Codebase Impact?
NO shared files → parallelizable (implement simultaneously)
YES shared files → sequential (implement in order)
Parallel rules:
- Each parallel item gets its own quick pass
- Merge results before running full pass
- If parallel items conflict at merge → resolve, re-run quick pass
- Review runs once after all parallel items completeSpec Mutation Protocol (Mid-Loop Changes)
When user requests scope changes during the ship loop:
User: "also add X" / "change Y to Z" / "remove W"
│
├─ 1. PAUSE current implementation
├─ 2. UPDATE SPEC FILE:
│ - Add/modify/remove scope items
│ - Add/modify acceptance criteria (GIVEN/WHEN/THEN)
│ - Update user journey if flow changes
│ - Re-run traceability check (scope ↔ AC, no orphans)
│ - Update Progress section
├─ 3. UPDATE TASKS: create new, delete obsolete
├─ 4. RE-ASSESS: does change affect tier, iteration limit, or risk?
├─ 5. RESUME ship loop with updated scope
│
└─ RULE: Never implement untracked work.
If it's not in the spec, update the spec first.The spec is the SINGLE SOURCE OF TRUTH. It must reflect reality at all times.
Never
- Never runs
git push - Never runs deploy commands
- Never makes production changes
- Never runs destructive git commands (
reset --hard,clean -f,push --force)
Spec Review Action
Agent: Load this file whenspec-reviewtriggers. Also load the active spec fromspecs/active/andreferences/rules-discovery.md— spec must not propose patterns that violate project/user rules.
Deep adversarial analysis of an active spec. Standalone — no dependency on analyze skill.
Triggers: "review spec", "analyze spec", "challenge spec", "spec-review"
---
Steps
Step 1: Load Spec + Context
1. Find active spec in specs/active/ 2. Read the full spec 3. Read codebase files listed in the spec's ## Codebase Impact section 4. If no active spec → error: "No active spec found. Run plan {idea} first."
Step 2: Select Perspectives (Dynamic)
Read the spec's context, scope, codebase impact, and risks. Autonomously select 3-6 expert perspectives most relevant to THIS spec's domain.
Selection process:
1. Identify the spec's domains from its content (code, SEO, marketing, data, infra, UX, legal, business, ops, content, security, performance, accessibility, etc.) 2. Select 3-6 perspectives that would catch the most blind spots for THESE domains 3. Always include 1 Skeptic (domain-agnostic adversarial thinker) 4. Present selected perspectives to user before launching
Examples:
| Spec Domain | Selected Perspectives |
|---|---|
| SEO migration | SEO Specialist, Content Strategist, Web Performance Engineer, Skeptic |
| Auth system | Security Engineer, API Consumer, UX Designer, Skeptic |
| Pricing page | Conversion Optimizer, Frontend Engineer, A/B Testing Analyst, Skeptic |
| Database migration | Data Engineer, Reliability Engineer, DBA, Skeptic |
| CLI tool | Developer Advocate, Systems Engineer, Skeptic |
Min 3, max 6 perspectives.
Step 3: Launch Parallel Analysis
Launch ALL perspectives as parallel sub-agents (single message, multiple Task tool calls).
Each sub-agent receives this prompt:
You are a {Role}. Review this spec adversarially.
SPEC:
{full spec content}
CONTEXT:
{codebase files from Codebase Impact, or domain context if not code-focused}
Answer these 4 questions:
1. ASSUMPTIONS: What's assumed that could be wrong?
| Assumption | Evidence For | Evidence Against | Verdict |
|------------|-------------|-----------------|---------|
(min 2 per perspective)
2. BLIND SPOTS: What hasn't been considered?
- 2-3 items with [category] + why it matters
3. FAILURE HYPOTHESES:
| IF | THEN | BECAUSE | Severity |
(1-3 per perspective)
4. THE REAL QUESTION: Is this solving the right problem from your perspective?
Every finding must end with action: → update spec / → explore / → question / → no actionStep 4: Synthesize
1. Collect all perspective outputs 2. Deduplicate findings (merge similar assumptions/blind spots) 3. Rank by severity (HIGH → MED → LOW) 4. Aggregate into structured report
Step 5: Output Report
Follow plan-output.md (unified template for both plan and spec-review).
Step 6: Merge (Optional)
If user says "merge" or "apply":
- Update the spec's
## Analysissection with synthesized findings - Add new risks to
## Riskstable - Add new ACs if findings warrant them
- Note in spec's
## Notes: "Spec review applied: {date}"
---
Task Tracking
[ ] Load active spec + codebase context
[ ] Select and present perspectives
[ ] Launch parallel perspective agents
[ ] Synthesize findings into report
[ ] Present report (optionally merge into spec)---
Rules
- Standalone: No dependency on analyze skill or any external tool
- Action-driven: Every finding must force a decision (update/explore/question/no action)
- Codebase-grounded: Cross-reference against actual code, not just spec text
- Parallel execution: All perspectives run simultaneously (single message, multiple Task calls)
- No passive observations: "This could be a problem" is not allowed. "IF X THEN Y → update spec" is.
Spike Action
Agent: Load this file when spike triggers.Time-boxed exploration. Answers a question, produces go/no-go. NOT a shippable feature.
---
When to Spike
- Unknown technology: "Can we use X for this?"
- Feasibility: "Is this approach even possible?"
- Performance: "Will this be fast enough?"
- Integration: "Does X work with Y?"
- Architecture: "Which pattern fits best?"
Flow
spike {question}
│
▼
┌──────────────────────────┐
│ 1. DEFINE │
│ Question: {what} │
│ Time box: {hours} │
│ Success: {go criteria} │
│ Kill: {stop criteria} │
└────────────┬─────────────┘
│
▼
┌──────────────────────────┐
│ 2. EXPLORE │
│ Research / prototype │
│ Track findings │
│ Check kill criteria │
└────────────┬─────────────┘
│
▼
┌──────────────────────────┐
│ 3. DECIDE │
│ GO / NO-GO / UNCLEAR │
│ Evidence summary │
│ Next step │
└──────────────────────────┘Task Template
[ ] Define question and success/kill criteria
[ ] Set time box (default 1h, max 4h)
[ ] Explore: research and prototype
[ ] Document findings
[ ] Decision: GO / NO-GO / NEEDS_MORE_INFO
[ ] Clean up: delete prototype code
[ ] Log to historyOutput
Follow the output template in references/templates/spike-output.md.
Rules
- Spike code is THROWAWAY. Delete before proceeding.
- Never ship spike code directly. If GO, start fresh with
plan. - Time box is hard. If kill criteria hit, stop immediately.
- Log spike to
specs/history.log:
{DATE} | spike | {slug} | {time}h | {GO/NO-GO} | {key finding}Codebase Intelligence (TypeScript Structural Analysis)
Agent: Load this file when working with a TypeScript codebase. Provides graph-based structural analysis via CLI.
Method: CLI via npx. TypeScript codebases only.
---
Documentation (Single Source of Truth)
Command reference, flags, metrics, data model, and tool selection guide live in the upstream repo — not here. Fetch the appropriate doc before first use:
| Doc | URL | When to Use |
|---|---|---|
| llms.txt (summary) | https://raw.githubusercontent.com/bntvllnt/codebase-intelligence/main/llms.txt | Quick orientation — commands, capabilities, tool selection |
| llms-full.txt (complete) | https://raw.githubusercontent.com/bntvllnt/codebase-intelligence/main/llms-full.txt | Full reference — architecture, data model, metrics, all CLI syntax, flags |
Fetch once per session using WebFetch or curl. These files are always up-to-date with the latest release.
---
Detection Gate
Before using any command, verify both conditions:
1. tsconfig.json exists at project root (or nearest parent)
→ If missing: NOT a TypeScript project — skip all CI commands
2. npx codebase-intelligence --help exits successfully
→ If fails: CI not available — fall back to grep/glob/readCache detection result per session. Do not re-check on every command.
---
Invocation Pattern
npx codebase-intelligence <command> <path> [flags] --jsonAlways use --json for machine-readable output. Timeout: 30s per command. Non-zero exit or timeout = silent fallback to grep/glob/read.
---
Quick Reference (Common Workflows)
For full command syntax and flags, see llms-full.txt above.
| Question | Command |
|---|---|
| What does this codebase look like? | npx codebase-intelligence overview ./src --json |
| What are the riskiest files? | npx codebase-intelligence hotspots ./src --metric complexity --json |
| Tell me about file X | npx codebase-intelligence file ./src <file> --json |
| What breaks if I change file X? | npx codebase-intelligence dependents ./src <file> --json |
| What breaks if I change function X? | npx codebase-intelligence impact ./src <symbol> --json |
| Who calls this function? | npx codebase-intelligence symbol ./src <name> --json |
| What changed + risk? | npx codebase-intelligence changes ./src --json |
| Find unused exports | npx codebase-intelligence dead-exports ./src --json |
| Module architecture | npx codebase-intelligence modules ./src --json |
| Architectural tensions | npx codebase-intelligence forces ./src --json |
| Find all references for rename | npx codebase-intelligence rename ./src <oldName> <newName> --json |
| Execution flow tracing | npx codebase-intelligence processes ./src --json |
| File community clusters | npx codebase-intelligence clusters ./src --json |
---
Fallback (When CI Unavailable)
Every CI command has a grep/glob/read equivalent. If CI is unavailable or fails, fall back silently:
| CI Command | Fallback |
|---|---|
overview | find + manual file counting |
dependents | Grep for import references |
symbol | Grep for function references |
impact | Manual call chain tracing |
hotspots | Manual code review |
changes | git diff + manual risk classification |
file | Read + manual analysis |
forces | Manual architecture review |
dead-exports | Grep for unused exports |
modules | Grep for import paths |
rename | Grep + find-replace |
processes | Manual code path tracing |
clusters | Manual folder analysis |
groups | ls + manual inspection |
search | Grep tool |
---
Cache
- Auto-stored in
.code-visualizer/directory at project root - Use
--forceto rebuild after significant structural changes - Recommend adding
.code-visualizer/to.gitignore
---
Error Handling
Command fails or times out (30s)?
→ Log silently, fall back to grep/glob/read equivalent
→ Never surface CI errors to user
→ Never block workflow on CI availabilityE2E Scenario Registry
Agent: Created at ship iteration 1 for specs with ACs. Validated by done. Archived with spec. Exempt for trivial/micro tier specs.AC-to-test traceability with TDD proof tracking. Every Must Have + Error AC maps to an E2E test with RED → GREEN confirmation.
---
Registry Template
| AC | Description | Test File | TDD Status | Notes |
|---|---|---|---|---|
| AC-1 | {AC description} | {path/to/test.spec.ts} | PENDING | |
| AC-E1 | {Error AC description} | {path/to/test.spec.ts} | RED_CONFIRMED | Fails as expected |
| FH-1 | {Failure hypothesis test} | {path/to/test.spec.ts} | GREEN_CONFIRMED | Defensive test passes |
TDD Status Values
| Status | Meaning | Transition |
|---|---|---|
| PENDING | Test not yet written | → RED_CONFIRMED (test written + fails) |
| RED_CONFIRMED | Test written, confirmed FAILING against current code | → GREEN_CONFIRMED (impl done + passes) |
| GREEN_CONFIRMED | Implementation done, test PASSING | Terminal |
| SKIP | Explicitly skipped with documented reason | Terminal |
BLOCKING rule: GREEN_CONFIRMED requires RED_CONFIRMED first. A test that never failed is not TDD.
AC Types in Registry
| Prefix | Source | Required |
|---|---|---|
| AC-{N} | Must Have acceptance criteria | BLOCKING |
| AC-E{N} | Error Criteria | BLOCKING |
| AC-S{N} | Should Have | Advisory |
| AC-B{N} | Bug fix ACs (B1-B4) | BLOCKING (for bug fixes) |
| FH-{N} | Failure hypothesis defensive test | BLOCKING (HIGH/MED severity) |
| EC-{N} | Edge case test | Advisory |
Lifecycle
plan → spec has ACs + Error Journeys + Failure Hypotheses
↓
ship (iteration 1) → create e2e-scenarios.md from spec
↓
ship (per scope item) → write test (RED) → implement → run test (GREEN)
↓
ship (exit check) → validate registry: all BLOCKING entries GREEN_CONFIRMED
↓
done (Step 1.5) → final validation: 100% Must Have + Error AC coverage
↓
done (archive) → move with spec to specs/shipped/Creation (ship iteration 1)
For each Must Have AC → add registry entry (PENDING)
For each Error AC → add registry entry (PENDING)
For each HIGH/MED Failure Hypothesis → add registry entry (PENDING)
For each Error Journey → verify AC-E covers it (no separate entry needed)
For each Edge Case → add registry entry (PENDING, advisory)Validation Algorithm
validate_registry(registry):
# 1. Unmapped check
unmapped = [ac for ac in spec.must_have_acs + spec.error_acs
if ac not in registry]
IF unmapped: FAIL "ACs not in registry: {unmapped}"
# 2. TDD proof check
no_red = [entry for entry in registry
if entry.status == GREEN_CONFIRMED
and not entry.had_red_confirmed]
IF no_red: FAIL "GREEN without RED proof: {no_red}"
# 3. Status check (BLOCKING entries only)
blocking = [entry for entry in registry
if entry.required == BLOCKING]
not_green = [e for e in blocking if e.status != GREEN_CONFIRMED]
IF not_green: FAIL "Not all BLOCKING entries GREEN: {not_green}"
# 4. Coverage percentage
total_blocking = len(blocking)
green_blocking = len([e for e in blocking if e.status == GREEN_CONFIRMED])
coverage = green_blocking / total_blocking * 100
IF coverage == 100: PASS
ELSE: FAIL "{coverage}% coverage — need 100% BLOCKING"Filled Example
# E2E Scenario Registry — User Authentication
| AC | Description | Test File | TDD Status | Notes |
|----|-------------|-----------|------------|-------|
| AC-1 | GIVEN valid credentials WHEN login THEN redirected to dashboard | tests/e2e/auth.spec.ts:12 | GREEN_CONFIRMED | |
| AC-2 | GIVEN new user WHEN signup THEN account created + welcome email | tests/e2e/auth.spec.ts:34 | GREEN_CONFIRMED | |
| AC-E1 | GIVEN invalid password WHEN login THEN error "Invalid credentials" | tests/e2e/auth.spec.ts:56 | GREEN_CONFIRMED | |
| AC-E2 | GIVEN expired session WHEN API call THEN redirect to login | tests/e2e/auth.spec.ts:78 | RED_CONFIRMED | Impl in progress |
| FH-1 | IF concurrent login attempts THEN no session corruption | tests/e2e/auth.spec.ts:90 | GREEN_CONFIRMED | Defensive test |
| EC-1 | Empty email field → validation error shown | tests/e2e/auth.spec.ts:102 | GREEN_CONFIRMED | Advisory |
**Coverage:** 5/5 BLOCKING entries GREEN_CONFIRMED (100%)
**TDD Proof:** All GREEN entries have prior RED_CONFIRMEDRegistry Location
Store in spec directory alongside the spec file:
specs/
active/
2024-01-15-user-auth.md ← spec
2024-01-15-user-auth-e2e.md ← this registryNaming: {spec-slug}-e2e.md
Backward Compatibility
- Existing specs without registry:
doneStep 1.5 → WARN (advisory), not FAIL - New specs (created after this protocol): registry is BLOCKING
- Bug fix specs: registry contains AC-B1 through AC-B4 entries
Anti-Patterns (NEVER)
- NEVER mark GREEN_CONFIRMED without prior RED_CONFIRMED (not TDD)
- NEVER skip BLOCKING entries without documented escape hatch
- NEVER create registry without reading the spec's ACs first
- NEVER leave registry entries as PENDING at ship exit
- NEVER delete registry entries — mark SKIP with reason instead
Decision Patterns
Second-Order Thinking
Think 2-3 steps ahead. "And then what?"
When: Architecture decisions, technology choices, process changes.
Decision: {what you're choosing}
First-order effects (immediate):
+ {benefit}
- {cost}
Second-order effects (weeks later):
+ {downstream benefit}
- {downstream cost}
Third-order effects (months later):
+ {compounding benefit}
- {compounding cost}Template:
| Order | Positive | Negative |
|-------|----------|----------|
| 1st (now) | {immediate win} | {immediate cost} |
| 2nd (weeks) | {downstream win} | {downstream cost} |
| 3rd (months) | {compounding win} | {compounding cost} |Common traps:
- Optimizing for first-order only (short-term thinking)
- Ignoring negative second-order effects (hidden costs)
- Assuming positive effects compound but negative ones don't
---
Reversibility Test
Classify decisions as one-way or two-way doors.
When: Any significant technical decision. Default mental model.
Type 1 (one-way door): Irreversible or very costly to reverse.
- Database schema in production with data
- Public API contract with external consumers
- Framework/language choice for large codebase
- Deleting user data
→ Slow down. Gather more information. Get review. Prototype first.
Type 2 (two-way door): Easily reversible, low cost to change.
- Internal API design (refactorable)
- UI layout (shippable, measurable)
- Library choice for isolated feature
- Feature flag rollout
→ Decide fast. Ship, measure, adjust. Don't over-analyze.
Classification questions: 1. What does it cost to reverse this? (hours? days? weeks?) 2. Who is affected if we reverse? (just us? users? partners?) 3. Is data involved? (data migrations are expensive) 4. Are external contracts involved? (APIs, integrations)
Effort matching:
Type 1: hours of analysis → days of implementation
Type 2: minutes of analysis → hours of implementation---
Opportunity Cost
Every choice excludes alternatives. What are you NOT doing?
When: Prioritization, resource allocation, scope decisions.
Option A: {what you'd do}
Value: {expected outcome}
Cost: {time + resources}
Value/hour: {value ÷ hours}
Option B: {alternative}
Value: {expected outcome}
Cost: {time + resources}
Value/hour: {value ÷ hours}
Opportunity cost of A = Value of best alternative not chosenCommon traps:
- Sunk cost: "We already spent 3 days on this" → Irrelevant. Only future costs matter.
- Urgency bias: "This is urgent!" → Urgent ≠ important. What's the actual deadline?
- Completion bias: "We're 80% done" → Is the remaining 20% worth finishing vs switching?
- Default bias: "We've always done it this way" → Is there a better way now?
Quick test: "If I hadn't started this, would I start it today given what I know now?" If no → consider dropping (see actions/drop.md).
Drop Output Template
Edit this file to customize what the agent returns after drop. Decision logic: actions/drop.md.
---
## Dropped: {title}
**Reason:** {category} — {details}
**Time invested:** {hours}
**Spec:** `specs/dropped/{filename}`
**Reusable:** {what can be salvaged — or "Nothing"}
**Key learning:** {most important insight}
**If revisited:** {different approach to try}