agentleFS
drafthqdrafthq/draft/skills/implement/SKILL.md

implement

Skill40 starsChanged 4 months agoMITView on GitHub

Canonical implementation parent command. Executes the active track task-by-task using TDD and verification gates, and routes to status, coverage, or revert when the user asks for progress, measurement, or rollback explicitly.

191 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use setup-ts-deep-modules, ask-matt and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • liufeng1976Skill

    setup-ts-deep-modules

    Wire dependency-cruiser into a TypeScript repo so each package is a deep module — implementation hidden in subfolders, reachable only through its entry-point files. User-invoked.

    Also in 43 projects that use this

  • GoogleSkill

    ask-matt

    Ask which skill or flow fits your situation. A router over the skills in this repo.

    Also in 91 projects that use this

  • RoentekSkill

    loop-me

    Grill me about specs for the workflows I want to build, within this workspace.

    Also in 50 projects that use this

  • AWSSkill

    to-questionnaire

    Turn a decision you can't fully answer into a questionnaire for someone else to fill in.

    Also in 88 projects that use this

  • ryotaroh180105Skill

    claude-handoff

    Hand the current conversation off to a fresh background agent that picks up the work immediately.

    Also in 42 projects that use this

  • GoogleSkill

    to-spec

    Turn the current conversation into a spec and publish it to the project issue tracker — no interview, just synthesis of what you've already discussed.

    Also in 168 projects that use this

  • +3 more from google

The file

Show its rules and text

We split this skill into the rules it gives an agent

118 rules. 0 are common, 75 are distinctive, and 43 are very specific to this project.

  • 0

    Common

    Most of the 171 edited versions we read keep these.

  • 75

    Distinctive

    This author's own choices. Worth a look.

  • 43

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    If the user invokes explicit child intent, route directly:

    line 49
  2. Distinctive:

    run review and verification gates at phase boundaries

    line 69
  3. Very specific:

    Do not make the user remember status or coverage in the happy path just to continue safe execution.

    line 72
  4. Distinctive:

    Before loading implementation context, check whether the request is really:

    line 78
  5. Distinctive:

    If one of these applies, route directly to the specialist workflow and stop this baseline implementation flow.

    line 113
  6. Very specific:

    Read the track's spec.md for requirements

    line 120
  7. Very specific:

    Read the track's plan.md for task list

    line 121
  8. Very specific:

    Read draft/workflow.md for TDD and commit preferences

    line 122
  9. Very specific:

    Read draft/tech-stack.md for technical context

    line 123
  10. Very specific:

    Read draft/guardrails.md (if exists) for hard guardrails and learned conventions

    line 124
  11. Distinctive:

    If relevant design context exists → Enable architecture mode (Story, Execution State, Skeletons)

    line 128
  12. Distinctive:

    If neither exists → Standard TDD workflow

    line 129
  13. Very specific:

    Read the ## INVARIANTS section (and ## CONCURRENCY if present)

    line 131
  14. Distinctive:

    Keep matching invariants as active constraints for this task — these govern code generation, not just review

    line 133
  15. Distinctive:

    If invariants reference lock ordering, fail-closed behavior, or data integrity rules: these are non-negotiable during implementation

    line 134
  16. Very specific:

    Run "$DRAFT_TOOLS/hotspot-rank.sh" --repo .

    line 148
  17. Distinctive:

    If modifying a hotspot file (high fanIn), warn: "This task modifies {file} (fanIn={N}).

    line 149
  18. Very specific:

    Update the track's entry in draft/tracks.md from [ ] to [~] In Progress

    line 152
  19. Distinctive:

    If no active track found:

    line 154
  20. Distinctive:

    Run once, before the first task of a new track:

    line 168
  21. Very specific:

    Verify at least one task in plan.md references or addresses it

    line 174
  22. Distinctive:

    If an AC has no corresponding task, flag it: "⚠️ AC: '[criterion]' has no task in plan.md"

    line 175
  23. Distinctive:

    If they differ: "⚠️ Spec and plan were synced to different commits — verify they are still aligned."

    line 182
  24. Distinctive:

    Before starting TDD cycle for the first task:

    line 199
  25. Distinctive:

    Check for testing strategy:

    line 201
  26. Distinctive:

    If found: load coverage targets, test boundaries, and strategy into TDD context

    line 204
  27. Very specific:

    If not found and TDD is enabled: suggest "Run /draft:testing-strategy to define test approach"

    line 205
  28. Very specific:

    If track type is bugfix (from metadata.json):

    line 209
  29. Distinctive:

    IMPORTANT: If blocked task found, notify user:

    line 226
  30. Distinctive:

    Do NOT attempt to implement blocked tasks

    line 231
  31. Very specific:

    If resuming [~] task, check for partial work.

    line 233
  32. Distinctive:

    After choosing the next task, check whether baseline implementation should remain in build mode or whether it should surface another …

    line 237
  33. Distinctive:

    If the track has:

    line 241
  34. Distinctive:

    no obvious next runnable task

    line 244
  35. Distinctive:

    If the implementation is at one of these points:

    line 253
  36. Very specific:

    If the selected task is blocked because earlier implementation appears invalid, conflicting, or partially reverted, /draft:implement should …

    line 272
  37. Very specific:

    Activation: Only runs when .ai-context.md, graph-primary architecture.md, or track hld.md/lld.md exists.

    line 276
  38. Distinctive:

    When the next task involves creating or substantially modifying a code file:

    line 278
  39. Distinctive:

    Check if file already has a Story comment: - If yes, skip this step

    line 280
  40. Distinctive:

    Read the Story (from Step 2.5) to understand the Input -> Output path

    line 325
  41. Distinctive:

    Create stubs with complete signatures (all parameters, return types)

    line 355
  42. Very specific:

    No implementation bodies — use // TODO, pass, unimplemented!(), etc.

    line 357
  43. Very specific:

    Follow naming conventions from tech-stack.md

    line 359
  44. Distinctive:

    When your implementation hits any of these triggers, use the corresponding pattern.

    line 371
  45. Distinctive:

    When refactoring code that lacks tests, write characterization tests first to capture current behavior as a baseline.

    line 446
  46. Distinctive:

    Iron Law: No production code without a failing test first.

    line 450
  47. Distinctive:

    No shared mutable state between test cases — each test sets up its own state

    line 464
  48. Distinctive:

    No logic in tests: no conditionals, loops, or try/catch in test code — tests should be trivially readable

    line 466
  49. Distinctive:

    Test behavior, not implementation: verify observable outcomes, not internal method calls

    line 468
  50. Distinctive:

    After writing example-based tests, consider property-based tests for pure functions (algebraic properties, round-trip serialization, sort …

    line 473
  51. Distinctive:

    Test passes immediately (testing wrong thing)

    line 503
  52. Very specific:

    Activation: Only when .ai-context.md or architecture.md exists (track-level or project-level).

    line 519
  53. Distinctive:

    If the implementation diff for a task exceeds ~200 lines:

    line 521
  54. Distinctive:

    STOP: after ~200 lines of implementation

    line 523
  55. Distinctive:

    CHECKPOINT (MANDATORY): Wait for developer approval of the chunk

    line 525
  56. Very specific:

    Commit the approved chunk: feat(<track_id>): <task description> (chunk N)

    line 526
  57. Distinctive:

    Iron Law: Every completed task gets its own commit.

    line 536
  58. Distinctive:

    After completing each task:

    line 538
  59. Distinctive:

    If any trigger is present but the pattern wasn't applied: fix it now

    line 542
  60. Distinctive:

    Commit FIRST (REQUIRED - non-negotiable):

    line 545
  61. Distinctive:

    Verify staged changes exist before committing: git diff --cached --quiet.

    line 548
  62. Very specific:

    If a Jira ticket is linked in spec.md, reference it in the commit body: Refs: <JIRA_ID>.

    line 550
  63. Distinctive:

    Do NOT proceed to the next task without committing

    line 552
  64. Distinctive:

    Do NOT batch multiple tasks into one commit

    line 553
  65. Very specific:

    Add the commit SHA next to the task: [x] Task description (abc1234)

    line 557
  66. Very specific:

    Read back plan.md - confirm task marked [x] with SHA

    line 564
  67. Very specific:

    Read back metadata.json - confirm tasks.completed incremented

    line 565
  68. Distinctive:

    If EITHER verification fails:

    line 566
  69. Very specific:

    Add recovery message: "State update failed after commit <SHA>.

    line 568
  70. Very specific:

    If .ai-context.md or graph-primary architecture.md (or track hld/lld) exists:

    line 571
  71. Distinctive:

    Update module status markers where applicable.

    line 572
  72. Very specific:

    If updating project-level draft/.ai-context.md: also update YAML frontmatter and run the Condensation Subroutine to keep it in sync.

    line 574
  73. Distinctive:

    Iron Law: No completion claims without fresh verification evidence.

    line 578
  74. Very specific:

    Before marking ANY task/phase/track complete:

    line 580
  75. Very specific:

    If NO: Keep task as [~], state actual status

    line 586
  76. Very specific:

    If YES: Show evidence, then mark [x]

    line 587
  77. Very specific:

    When all tasks in a phase are [x]:

    line 601
  78. Distinctive:

    Verify all requirements for this phase are implemented

    line 615
  79. Distinctive:

    Check acceptance criteria coverage

    line 616
  80. Distinctive:

    Verify code follows project patterns (tech-stack.md)

    line 621
  81. Distinctive:

    Check error handling is appropriate

    line 622
  82. Distinctive:

    Verify tests cover real logic

    line 623
  83. Very specific:

    If quick-review chosen, invoke /draft:quick-review with the phase's changed files.

    line 639
  84. Distinctive:

    Run verification steps from plan (tests, builds)

    line 641
  85. Distinctive:

    If review passes (no Critical issues):

    line 643
  86. Distinctive:

    Update phase status in plan

    line 644
  87. Distinctive:

    If Critical/Important issues found:

    line 648
  88. Distinctive:

    Document issues in plan.md

    line 649
  89. Very specific:

    After a phase passes review, refresh metadata.json.impact so future tracks can detect overlap with this work.

    line 654
  90. Very specific:

    Compute downstream blast radius (graph-aware, optional): If draft/graph/schema.yaml exists, for each file in files_touched query (this runs …

    line 664
  91. Distinctive:

    When all phases complete:

    line 682
  92. Very specific:

    Read draft/workflow.md review configuration

    line 685
  93. Distinctive:

    Check if auto-review enabled:

    line 686
  94. Very specific:

    If enabled, run /draft:review track <track_id>

    line 693
  95. Distinctive:

    If block-on-failure enabled AND critical issues found → HALT, require fixes

    line 695
  96. Very specific:

    Update plan.md status to [x] Completed

    line 698
  97. Very specific:

    Read back plan.md - confirm status [x] Completed

    line 705
  98. Very specific:

    Read back draft/tracks.md - confirm track in Completed section with completion date

    line 707
  99. Distinctive:

    If ANY file shows inconsistent state:

    line 708
  100. Distinctive:

    Do NOT announce completion until all three files verified consistent

    line 712
  101. Distinctive:

    All acceptance criteria from spec.md should be verified.

    line 727
  102. Distinctive:

    Add reason in plan.md

    line 736
  103. Very specific:

    REQUIRED: Follow systematic debugging process (see core/agents/debugger.md)

    line 737
  104. Distinctive:

    Investigate: - Read errors, reproduce, trace (NO fixes yet)

    line 738
  105. Distinctive:

    Do NOT attempt random fixes

    line 742
  106. Distinctive:

    Document root cause when found

    line 743
  107. Very specific:

    Recommended: Instead of inline debugging, invoke /draft:debug skill for a structured session:

    line 745
  108. Distinctive:

    Don't mark complete

    line 755
  109. Distinctive:

    Follow systematic debugging process above

    line 756
  110. Distinctive:

    Don't proceed with assumptions

    line 764
  111. Distinctive:

    When you encounter a shortcut, workaround, or known-imperfect solution during implementation:

    line 770
  112. Very specific:

    Add an entry to the ## Tech Debt section at the bottom of plan.md

    line 772
  113. Distinctive:

    Only log genuine debt — intentional shortcuts with known consequences.

    line 792
  114. Distinctive:

    After each task, report:

    line 798
  115. Distinctive:

    After announcing track completion, suggest relevant follow-ups based on context:

    line 813
  116. Very specific:

    If Jira ticket linked, sync via core/shared/jira-sync.md:

    line 842
  117. Very specific:

    If implementing a bug track and draft/tracks/<id>/rca.md exists:

    line 848
  118. Distinctive:

    After fix: update rca.md "Proposed Fix" section with actual fix details

    line 852

“Common” is measured: kept by at least 6 in 10 of the 171 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Implement Track

Implement tasks from the active track's plan following the TDD workflow.

/draft:implement is the canonical implementation parent.

It owns the common execution loop and absorbs three adjacent commands when appropriate:

  • /draft:status
  • /draft:coverage
  • /draft:revert

Red Flags - STOP if you're

  • Implementing without an approved spec and plan
  • Skipping TDD cycle when workflow.md has TDD enabled
  • Marking a task [x] without fresh verification evidence
  • Batching multiple tasks into a single commit
  • Proceeding past a phase boundary without running the three-stage review
  • Writing production code before a failing test (when TDD is strict)
  • Assuming a test passes without actually running it

Verify before you mark complete. One task, one commit.

Constraints

Draft skills are designed for single-agent, single-track execution. Do not run multiple Draft commands concurrently on the same track.


Parent Contract

/draft:implement owns four execution jobs:

  1. Build the next task → baseline /draft:implement
  2. Show current execution state → /draft:status
  3. Measure implementation completeness via coverage → /draft:coverage
  4. Undo implementation safely → /draft:revert

Most developers should only need /draft:implement in the common path.

Explicit Child Modes

If the user invokes explicit child intent, route directly:

  • /draft:implement status → follow /draft:status
  • /draft:implement coverage → follow /draft:coverage
  • /draft:implement revert → follow /draft:revert

Examples:

  • /draft:implement status
  • /draft:implement coverage src/auth
  • /draft:implement revert phase 2

Explicit child mode always wins over the baseline implementation workflow.

Bare /draft:implement

Without an explicit child mode, /draft:implement should:

  • continue the active track's next task
  • surface blocked-task conditions immediately
  • run review and verification gates at phase boundaries
  • suggest or attach coverage only when the implementation state justifies it

Do not make the user remember status or coverage in the happy path just to continue safe execution.


Step 0: Route Explicit Child Modes

Before loading implementation context, check whether the request is really:

  • progress inspection
  • coverage measurement
  • rollback / undo

Route to /draft:status

Route when the user asks:

  • status
  • progress
  • what's left
  • where am I

Route to /draft:coverage

Route when the user asks:

  • coverage
  • measure tests
  • how much is covered
  • coverage for <module/path>

Route to /draft:revert

Route when the user asks:

  • revert
  • undo
  • roll back
  • revert task
  • revert phase
  • revert track

If one of these applies, route directly to the specialist workflow and stop this baseline implementation flow.


Step 1: Load Context

  1. Find active track from draft/tracks.md (look for [~] In Progress or first [ ] track)
  2. Read the track's spec.md for requirements
  3. Read the track's plan.md for task list
  4. Read draft/workflow.md for TDD and commit preferences
  5. Read draft/tech-stack.md for technical context
  6. Read draft/guardrails.md (if exists) for hard guardrails and learned conventions
  7. Check for architecture context:
    • Project-level: draft/.ai-context.md (preferred) or draft/architecture.md (graph-primary)
    • Track-level design docs: draft/tracks/<id>/hld.md (+ lld.md when present)
    • If relevant design context exists → Enable architecture mode (Story, Execution State, Skeletons)
    • If neither exists → Standard TDD workflow
  8. Load production invariants (if draft/.ai-context.md exists):
    • Read the ## INVARIANTS section (and ## CONCURRENCY if present)
    • Identify which invariants reference files this task will modify (same file or same module)
    • Keep matching invariants as active constraints for this task — these govern code generation, not just review
    • If invariants reference lock ordering, fail-closed behavior, or data integrity rules: these are non-negotiable during implementation
  9. Load graph context (if draft/graph/schema.yaml exists):

    First resolve the bundled helpers:

    # Locate Draft's bundled helpers (cwd is the user's project; ${CLAUDE_PLUGIN_ROOT}
    # is not exported into skill Bash). See core/shared/tool-resolver.md.
    DRAFT_TOOLS="${DRAFT_PLUGIN_ROOT:-$(cat ~/.cache/draft/plugin-root 2>/dev/null)}/scripts/tools"
    [ -d "$DRAFT_TOOLS" ] || DRAFT_TOOLS="$(ls -d ~/.claude/plugins/cache/*/draft/*/scripts/tools 2>/dev/null | sort -V | tail -1)"
    [ -d "$DRAFT_TOOLS" ] || DRAFT_TOOLS="$(ls -d ~/.claude/plugins/marketplaces/*draft*/scripts/tools 2>/dev/null | tail -1)"
    [ -d "$DRAFT_TOOLS" ] || DRAFT_TOOLS="$PWD/scripts/tools"
    • Run "$DRAFT_TOOLS/hotspot-rank.sh" --repo . — check if any files this task will modify appear as hotspots
    • If modifying a hotspot file (high fanIn), warn: "This task modifies {file} (fanIn={N}). Changes here affect many downstream files. Consider running a graph impact query."
    • Query "$DRAFT_TOOLS/graph-impact.sh"/"$DRAFT_TOOLS/graph-callers.sh" for the module(s) being modified — gives file-level dependency context
    • See core/shared/graph-query.md for on-demand query subroutines (callers, impact)
  10. Update the track's entry in draft/tracks.md from [ ] to [~] In Progress

If no active track found:

  • Tell user: "No active track found. Run /draft:plan to create or resume planned work."

Architecture / Design Mode Activation:

  • Automatically enabled when .ai-context.md, graph-primary architecture.md, or track hld.md/lld.md exists.
  • Project-level context from /draft:init.
  • Track-level design docs from /draft:decompose.

Step 1.5: Readiness Gate (Fresh Start Only)

Skip if: Any task in plan.md is already [x] — the track is in progress, this check has already passed.

Run once, before the first task of a new track:

AC Coverage Check

For each acceptance criterion in spec.md:

  • Verify at least one task in plan.md references or addresses it
  • If an AC has no corresponding task, flag it: "⚠️ AC: '[criterion]' has no task in plan.md"

Sync Check (if .ai-context.md exists)

Compare the synced_to_commit values in the YAML frontmatter of spec.md and plan.md.

  • Skip if either file has no YAML frontmatter or no synced_to_commit field (quick-mode tracks omit it).
  • If they differ: "⚠️ Spec and plan were synced to different commits — verify they are still aligned."

Result

Issues found: List them, then ask:

Readiness issues found (see above). Proceed anyway or update first? [proceed/update]
  • proceed → add a ## Notes entry in plan.md listing the issues, then continue to Step 2
  • update → stop here and let the user refine spec or plan before re-running

No issues: Print Readiness check passed. and continue to Step 2.

Step 1.7: Testing Strategy Loading

Before starting TDD cycle for the first task:

  1. Check for testing strategy:
    • Track-level: draft/tracks/<id>/testing-strategy.md
    • Project-level: draft/testing-strategy.md or draft/testing-strategy-latest.md
  2. If found: load coverage targets, test boundaries, and strategy into TDD context
  3. If not found and TDD is enabled: suggest "Run /draft:testing-strategy to define test approach"

Bug Track Test Guardrail

If track type is bugfix (from metadata.json):

BEFORE writing any test file:
  ASK: "This is a bug fix track. Want me to write tests as part of the fix? [Y/n]"
  If declined: skip TDD cycle, note in plan.md: "Tests: developer-handled"

Step 2: Find Next Task

Scan plan.md for the first uncompleted task:

  • [ ] = Pending (pick this one)
  • [~] = In Progress (resume this one)
  • [x] = Completed (skip)
  • [!] = Blocked (skip - requires manual intervention)

IMPORTANT: If blocked task found, notify user:

  • "Task [task description] is marked [!] Blocked"
  • Show the blocked task details and recovery message
  • "Resolve the blockage manually before continuing implementation"
  • Do NOT attempt to implement blocked tasks

If resuming [~] task, check for partial work.

Implementation-State Escalations

After choosing the next task, check whether baseline implementation should remain in build mode or whether it should surface another execution helper.

Escalate to Status-Style Summary

If the track has:

  • many blocked tasks
  • no obvious next runnable task
  • conflicting in-progress markers

then present a concise status summary before proceeding so the user can see the execution state clearly.

This does not require fully routing to /draft:status; it is an implementation-owned checkpoint.

Escalate to Coverage Guidance

If the implementation is at one of these points:

  • phase just completed
  • track just completed
  • high-risk module just changed and tests exist but coverage is unknown

then /draft:implement should suggest coverage or auto-attach it when the workflow and user intent imply measurement is expected.

Examples:

Implementation checkpoint:
- Phase 2 is complete
- Next recommended action: /draft:implement coverage
- Reason: high-risk auth code changed and coverage has not been measured for this phase

Escalate to Revert Guidance

If the selected task is blocked because earlier implementation appears invalid, conflicting, or partially reverted, /draft:implement should recommend /draft:implement revert explicitly rather than pushing forward blindly.

Step 2.5: Write Story (Architecture Mode Only)

Activation: Only runs when .ai-context.md, graph-primary architecture.md, or track hld.md/lld.md exists.

When the next task involves creating or substantially modifying a code file:

  1. Check if file already has a Story comment - If yes, skip this step
  2. Skip for trivial tasks - Config files, type definitions, simple one-liners
  3. Write a natural-language algorithm description as a comment block at the top of the target file

Story Format

// Story: [Module/File Name]
//
// Input:  [what this module/function receives]
// Process:
//   1. [first algorithmic step]
//   2. [second algorithmic step]
//   3. [third algorithmic step]
// Output: [what this module/function produces]
//
// Dependencies: [what this module relies on]
// Side effects: [any mutations, I/O, or external calls]

Adapt comment syntax to the language (# for Python, /* */ for CSS, etc.).

CHECKPOINT (MANDATORY)

STOP. Present the Story to the developer for review.

  • Developer may refine, modify, or rewrite the Story
  • Do NOT proceed to execution state or implementation until Story is approved
  • Developer can say "skip" to bypass this checkpoint for the current task

See core/agents/architect.md for story writing guidelines.


Step 3: Execute Task

Step 3.0: Design Before Code (Architecture Mode Only)

Activation: Only runs when .ai-context.md, graph-primary architecture.md, or track hld.md/lld.md exists. Skip for trivial tasks - Config updates, type-only changes, single-function tasks where the design is obvious.

3.0a. Execution State Design

Study the control flow for the task and propose intermediate state variables:

  1. Read the Story (from Step 2.5) to understand the Input -> Output path
  2. Study similar patterns in the existing codebase
  3. Check .ai-context.md Data Lifecycle — Align execution state with documented state machines (valid states/transitions), storage topology (which tier data targets), and data transformation chain (shape changes at boundaries)
  4. Check .ai-context.md Critical Paths — Identify where this task sits in documented write/read/async paths. Note consistency boundaries and failure recovery expectations.
  5. Propose execution state: input state, intermediate state, output state, error state

Present in this format:

EXECUTION STATE: [Task/Module Name]
─────────────────────────────────────────────────────────
Input State:
  - variableName: Type — purpose

Intermediate State:
  - variableName: Type — purpose

Output State:
  - variableName: Type — purpose

Error State:
  - variableName: Type — purpose

CHECKPOINT (MANDATORY): Present execution state to developer. Wait for approval. Developer may add, remove, or modify state variables. Developer can say "skip" to bypass.

3.0b. Function Skeleton Generation

Generate function/method stubs based on the approved execution state:

  1. Create stubs with complete signatures (all parameters, return types)
  2. Include a one-line docstring describing purpose and when it's called
  3. No implementation bodies — use // TODO, pass, unimplemented!(), etc.
  4. Order functions to match control flow sequence
  5. Follow naming conventions from tech-stack.md

CHECKPOINT (MANDATORY): Present skeletons to developer. Wait for approval. Developer may rename functions, change signatures, add/remove methods. Developer can say "skip" to bypass.

See core/agents/architect.md for execution state and skeleton guidelines.


Step 3.0c: Production Robustness Patterns (REQUIRED)

Applies to all code generation — architecture mode or not. These patterns are generation directives, not a post-hoc checklist. Apply them while writing code, not after.

When your implementation hits any of these triggers, use the corresponding pattern. Do not write code that violates these and plan to "fix it later."

Atomicity

TriggerRequired Pattern
Multi-step state mutation (DB + memory, multiple records)Wrap in transaction or try/finally with rollback on failure
File writeWrite to temp file + atomic rename to target path. Never write directly to the target.
DB write paired with in-memory state updateDB-first: persist to DB, update memory only on DB success. Never update memory optimistically.
Resource acquisition (locks, file handles, connections, capital)Release in finally / defer / RAII — never rely on happy-path-only cleanup

Isolation

TriggerRequired Pattern
Method mutates shared/instance stateAcquire the class's or module's existing lock before mutation
Lifecycle operations (start/stop/reset/reconnect)Use a dedicated lifecycle lock, separate from data locks
Returning internal state to callersReturn a deep copy or frozen snapshot — never a mutable reference to internal state
Acquiring a second lock while holding oneFollow documented lock ordering. If no ordering exists, do not nest locks — restructure to acquire sequentially.
DB I/O while holding a state lockMove DB I/O outside the lock scope. Lock only the in-memory mutation, not the I/O.

Durability

TriggerRequired Pattern
Critical state that must survive crashesEnsure state is recoverable from DB/disk alone — no reliance on in-memory-only state for recovery
Async DB write (fire-and-forget)Await the write. Check return value or propagate exceptions. No fire-and-forget on data persistence.
Event log / audit trail / fill historyUse append-only pattern where specified by architecture

Defensive Boundaries

TriggerRequired Pattern
External numeric data used in arithmeticGuard with isFinite() / isnan() / equivalent before any calculation
External API/webhook response consumedValidate expected fields exist and have correct types before accessing nested properties
SQL query with dynamic valuesParameterized queries only — zero string interpolation for values
Dynamic column names, table names, or identifiers in SQLValidate against an explicit allowlist — never pass user-controlled strings as identifiers

Idempotency

TriggerRequired Pattern
Operation that may be retried (network calls, queue consumers, webhook handlers)Use a dedup key (UUID, request ID, fill ID) — check-before-write or upsert
State transition (status changes, lifecycle events)Validate the transition is legal from the current state. Reject terminal→terminal transitions.
Alert / notification emissionDedup on (alert_type, entity_id, time_window) to prevent re-firing on retries

Fail-Closed

TriggerRequired Pattern
Error path or exception handler that determines access/actionDefault to the safe/restrictive/deny state — never default to permissive on error
Missing data, null, or undefined where a decision depends on itTreat as deny/reject/skip — not as allow/proceed
Config or feature flag missing/unparseableUse the restrictive default — system runs in safe mode, not open mode

Resilience

TriggerRequired Pattern
Any retry logicExponential backoff with jitter — never fixed-interval or immediate retries. Prevents retry storms.
Cache population under high concurrencyCache stampede prevention: use probabilistic early expiration or request coalescing to prevent thundering herd
External dependency call (HTTP, RPC, DB to external service)Circuit breaker pattern: track failure rate, open circuit on threshold, allow periodic probes to recover
Non-critical dependency failureGraceful degradation: return cached/default/partial result rather than failing the entire request

Enforcement: These patterns override convenience. If following a pattern makes the code more verbose, that's correct — the verbosity is the safety. If a pattern is genuinely N/A for the current task (e.g., no DB in a pure utility function), skip it — only apply relevant patterns.

If project invariants were loaded in Step 1: Cross-reference them here. Project-specific invariants (lock ordering, concurrency model, consistency boundaries) take precedence over these general patterns when they conflict.


Step 3.1: Implement (TDD Workflow)

For each task, follow this workflow based on workflow.md. If skeletons were generated in Step 3.0b, fill them in using the TDD cycle below.

Characterization Testing (Refactoring Existing Code Without Tests)

When refactoring code that lacks tests, write characterization tests first to capture current behavior as a baseline. Identify seams (interfaces for test doubles, swappable imports), record actual outputs for representative inputs, then proceed with the TDD cycle for new behavior.

If TDD Enabled

Iron Law: No production code without a failing test first.

3a. RED - Write Failing Test

1. Create/update test file as specified in task
2. Write test that captures the requirement
3. RUN test - VERIFY it FAILS (not syntax error, actual assertion failure)
4. Show test output with failure
5. Announce: "Test failing as expected: [failure message]"

Test Quality Checklist (REQUIRED for every test):

  • No shared mutable state between test cases — each test sets up its own state
  • Assertion density: every test must have at least one meaningful assertion (not just assertTrue(true))
  • No logic in tests: no conditionals, loops, or try/catch in test code — tests should be trivially readable
  • DAMP over DRY: prefer descriptive and meaningful test names and setup over deduplication
  • Test behavior, not implementation: verify observable outcomes, not internal method calls
  • One behavior per test: each test should verify exactly one logical behavior
  • Reference: Google SWE Book Ch. 12, Google Testing Blog "Test Behavior, Not Implementation"

Property-Based Testing Checkpoint: After writing example-based tests, consider property-based tests for pure functions (algebraic properties, round-trip serialization, sort invariants). Not mandatory — skip if properties are not obvious.

3b. GREEN - Implement Minimum Code

1. Write MINIMUM code to make test pass (no extras)
2. RUN test - VERIFY it PASSES
3. Show test output with pass
4. Announce: "Test passing: [evidence]"

Observability Prompts (consider during implementation): Structured logging at decision points, metrics for latency-sensitive ops, tracing at service boundaries, error classification (transient vs permanent). Use engineering judgment — not mandatory for every task.

Contract Testing Checkpoint (Service Boundaries Only): For new API endpoints or service-to-service interfaces, suggest consumer-driven contract tests. Skip for purely internal modules.

3c. REFACTOR - Clean with Tests Green

1. Review code for improvements
2. Refactor while keeping tests green
3. RUN all related tests after each change
4. Show final test output
5. Announce: "Refactoring complete, all tests passing: [evidence]"

Red Flags - STOP and restart the cycle if:

  • About to write code before test exists
  • Test passes immediately (testing wrong thing)
  • Thinking "just this once" or "too simple to test"
  • Running tests mentally instead of actually executing

If TDD Not Enabled

3a. Implement

1. Implement the task as specified
2. Test manually or run existing tests
3. Announce: "Implementation complete"

Implementation Chunk Limit (Architecture Mode Only)

Activation: Only when .ai-context.md or architecture.md exists (track-level or project-level).

If the implementation diff for a task exceeds ~200 lines:

  1. STOP after ~200 lines of implementation
  2. Present the chunk for developer review
  3. CHECKPOINT (MANDATORY): Wait for developer approval of the chunk
  4. Commit the approved chunk: feat(<track_id>): <task description> (chunk N)
  5. Continue with the next chunk
  6. Repeat until the task is fully implemented

This prevents large, unreviewable code drops. Each chunk should be a coherent, reviewable unit.


Step 4: Update Progress & Commit

Iron Law: Every completed task gets its own commit. No batching. No skipping.

After completing each task:

  1. Quick robustness scan (30-second check before committing):
    • Scan the code you just wrote against the Step 3.0c triggers
    • If any trigger is present but the pattern wasn't applied: fix it now
    • This is a rapid pattern-match, not a full review — you should have applied these during generation, this catches anything missed
  2. Commit FIRST (REQUIRED - non-negotiable):
    • Stage only files changed by this task (never git add .)
    • git add <specific files>
    • Verify staged changes exist before committing: git diff --cached --quiet. If nothing staged, skip the commit step.
    • git commit -m "type(<track_id>): task description" (Conventional Commits — see core/shared/vcs-commands.md)
    • If a Jira ticket is linked in spec.md, reference it in the commit body: Refs: <JIRA_ID>.
    • Get commit SHA: git rev-parse --short HEAD
    • Do NOT proceed to the next task without committing
    • Do NOT batch multiple tasks into one commit
  3. Update plan.md:
    • Change [ ] to [x] for the completed task
    • Add the commit SHA next to the task: [x] Task description (abc1234)
  4. Update metadata.json:
    • Increment tasks.completed
    • Update updated timestamp
  5. Verify state updates (CRITICAL):
    • Read back plan.md - confirm task marked [x] with SHA
    • Read back metadata.json - confirm tasks.completed incremented
    • If EITHER verification fails:
      • Mark task as [!] Blocked in plan.md
      • Add recovery message: "State update failed after commit <SHA>. Recovery: manually edit plan.md line X to mark [x], update metadata.json tasks.completed to Y"
      • HALT - require manual intervention before continuing
  6. If .ai-context.md or graph-primary architecture.md (or track hld/lld) exists:
    • Update module status markers where applicable.
    • Fill in Story placeholders with the approved story from Step 2.5
    • If updating project-level draft/.ai-context.md: also update YAML frontmatter and run the Condensation Subroutine to keep it in sync.

Verification Gate (REQUIRED)

Iron Law: No completion claims without fresh verification evidence.

Before marking ANY task/phase/track complete:

  1. IDENTIFY: What command proves this claim? (test, build, lint)
  2. RUN: Execute the FULL command (fresh, complete run)
  3. READ: Full output, check exit code
  4. VERIFY: Does output confirm the claim?
    • If NO: Keep task as [~], state actual status
    • If YES: Show evidence, then mark [x]

Red Flags - STOP if you're thinking:

  • "Should pass", "probably works"
  • Satisfaction before running verification
  • About to mark [x] without fresh evidence from this session
  • "I already tested earlier"
  • "This is a simple change, no need to verify"

Step 5: Phase Boundary Check

When all tasks in a phase are [x]:

  1. Announce: "Phase N complete. Running three-stage review."

Three-Stage Review (REQUIRED)

Stage 1: Automated Validation

  • Fast static checks: architecture conformance, dead code, circular dependencies, performance anti-patterns. Review for common security anti-patterns (OWASP top 10). For automated checks, use language-specific tools (e.g., npm audit for JS, bandit for Python, cargo audit for Rust).
  • If critical issues found: List them, return to implementation

Stage 2: Spec Compliance (only if Stage 1 passes)

  • Load track's spec.md
  • Verify all requirements for this phase are implemented
  • Check acceptance criteria coverage
  • If gaps found: List them, return to implementation

Stage 3: Code Quality (only if Stage 2 passes)

  • Verify code follows project patterns (tech-stack.md)
  • Check error handling is appropriate
  • Verify tests cover real logic
  • Classify issues: Critical (must fix) > Important (should fix) > Minor (note)

See core/agents/reviewer.md for detailed review process.

Quick Review Alternative

At phase boundaries, offer the lightweight alternative:

"Phase {N} complete. Review options:
  1. Full three-stage review (recommended) — spec compliance + security + quality
  2. /draft:quick-review — lightweight 4-dimension check (faster)
  Choose [1/2, default: 1]:"

If quick-review chosen, invoke /draft:quick-review with the phase's changed files.

  1. Run verification steps from plan (tests, builds)
  2. Present review findings to user
  3. If review passes (no Critical issues):
    • Update phase status in plan
    • Update metadata.json phases.completed
    • Refresh blast-radius memory (see "Impact Memory" subsection below)
    • Proceed to next phase
  4. If Critical/Important issues found:
    • Document issues in plan.md
    • Fix before proceeding (don't skip)

Impact Memory (blast-radius snapshot)

After a phase passes review, refresh metadata.json.impact so future tracks can detect overlap with this work.

  1. Compute touched files: From plan.md, find the first commit SHA recorded for this track (earliest [x] line with (<sha>)). Run:

    git diff --name-only <first_sha>^..HEAD

    That is the files_touched list. Derive modules_touched as the unique top-level path segments (e.g. auth/login.go → auth).

  2. Compute downstream blast radius (graph-aware, optional): If draft/graph/schema.yaml exists, for each file in files_touched query (this runs in its own Bash session — re-resolve the helpers):

    DRAFT_TOOLS="${DRAFT_PLUGIN_ROOT:-$(cat ~/.cache/draft/plugin-root 2>/dev/null)}/scripts/tools"
    [ -d "$DRAFT_TOOLS" ] || DRAFT_TOOLS="$(ls -d ~/.claude/plugins/cache/*/draft/*/scripts/tools 2>/dev/null | sort -V | tail -1)"
    [ -d "$DRAFT_TOOLS" ] || DRAFT_TOOLS="$(ls -d ~/.claude/plugins/marketplaces/*draft*/scripts/tools 2>/dev/null | tail -1)"
    [ -d "$DRAFT_TOOLS" ] || DRAFT_TOOLS="$PWD/scripts/tools"
    "$DRAFT_TOOLS/graph-impact.sh" --repo . --file <path>

    Aggregate across all files: downstream_files = count of the union of each query's downstream_files array, downstream_modules = union of affected_modules, max_depth = max across queries, by_category = sum of each query's by_category. If the graph is absent, leave these fields as zeros / empty arrays — the snapshot still records the directly-touched files.

  3. Write metadata.json with the populated impact block and computed_at set to the current timestamp.

This snapshot is consumed by /draft:new-track to surface overlap warnings when a new track touches the same modules as a recently completed track.

Step 6: Track Completion

When all phases complete:

  1. Run review (if enabled):
    • Read draft/workflow.md review configuration
    • Check if auto-review enabled:

      ## Review Settings
      - [x] Auto-review at track completion
    • If enabled, run /draft:review track <track_id>
    • Check review results:
      • If block-on-failure enabled AND critical issues found → HALT, require fixes
      • Otherwise, document warnings and continue
  2. Update plan.md status to [x] Completed
  3. Update metadata.json status to "completed"
  4. Update draft/tracks.md:
    • Move from Active to Completed section
    • Add completion date
  5. Verify completion state consistency (CRITICAL):
    • Read back plan.md - confirm status [x] Completed
    • Read back metadata.json - confirm status "completed"
    • Read back draft/tracks.md - confirm track in Completed section with completion date
    • If ANY file shows inconsistent state:
      • ERROR: "Track completion partially failed"
      • Report: "plan.md: <status>, metadata.json: <status>, tracks.md: <section>"
      • Provide recovery: "Manually complete updates: [list specific edits needed]"
      • Do NOT announce completion until all three files verified consistent
  6. Announce: "Track <track_id> completed!

Summary:

  • Phases: N/N
  • Tasks: M/M
  • Duration: [if tracked]

[If review ran:] Review: PASS | PASS WITH NOTES | FAIL Report: draft/tracks/<track_id>/review-report-latest.md

All acceptance criteria from spec.md should be verified.

Next: Run /draft:status to see project overview."

Error Handling

If blocked:

  • Mark task as [!] Blocked
  • Add reason in plan.md
  • REQUIRED: Follow systematic debugging process (see core/agents/debugger.md)
    1. Investigate - Read errors, reproduce, trace (NO fixes yet)
    2. Analyze - Find similar working code, list differences
    3. Hypothesize - Single hypothesis, smallest test
    4. Implement - Regression test first, then fix
  • Do NOT attempt random fixes
  • Document root cause when found

Recommended: Instead of inline debugging, invoke /draft:debug skill for a structured session:

"Task blocked: {description}. Run /draft:debug for structured investigation? [Y/n]"

The debug skill provides: Reproduce → Isolate → Diagnose → Fix methodology with debug report output.

If test fails unexpectedly:

  • Don't mark complete
  • Follow systematic debugging process above
  • Announce failure details with root cause analysis
  • Show evidence when resolved

If unsure about implementation:

  • Ask clarifying questions
  • Reference spec.md for requirements
  • Don't proceed with assumptions

Tech Debt Log

During implementation, track technical debt decisions in the track's plan.md:

When you encounter a shortcut, workaround, or known-imperfect solution during implementation:

  1. Add an entry to the ## Tech Debt section at the bottom of plan.md
  2. Use this format:
## Tech Debt

| ID | Location | Description | Severity | Payback Trigger |
|----|----------|-------------|----------|-----------------|
| TD-1 | `src/api/handler.ts:45` | Hardcoded timeout instead of config | Low | When adding config system |
| TD-2 | `src/auth/session.ts:12` | In-memory session store | Medium | Before horizontal scaling |

Severity levels:

  • Low — Cosmetic or minor maintainability issue
  • Medium — Will cause problems at scale or in specific scenarios
  • High — Actively impeding development or risking production issues

Payback Trigger — The condition or event that should trigger debt repayment (e.g., "before launch", "when adding feature X", "before scaling past N users").

Only log genuine debt — intentional shortcuts with known consequences. Not everything imperfect is debt.


Progress Reporting

After each task, report:

Task: [description]
Status: Complete
Phase Progress: N/M tasks
Overall: X% complete

Cross-Skill Dispatch

At Track Completion (Step 6)

After announcing track completion, suggest relevant follow-ups based on context:

If track modifies production code:

"Track complete! Consider:
  → /draft:deploy-checklist — Pre-deployment verification"

If track added new APIs/services/components:

  → /draft:documentation — Update documentation for new components"

If implementation contains TODO/FIXME/HACK comments:

  → /draft:tech-debt — Catalog any new technical debt introduced"

If new patterns or dependencies not in tech-stack.md:

  → /draft:adr — Document this design decision"

Jira Sync at Completion

If Jira ticket linked, sync via core/shared/jira-sync.md:

  • Post comment: "[draft] implementation-complete: All {n} tasks done. Ready for review."

Bug Track with rca.md

If implementing a bug track and draft/tracks/<id>/rca.md exists:

  • Load rca.md as context for the implementation
  • Reference root cause, blast radius, and prevention items during fix
  • After fix: update rca.md "Proposed Fix" section with actual fix details

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.