Spec-Driven Development: specifications compiled into executable, verifiable behavior

GitHub stars
19

Install

/plugin install tasker@tasker-marketplace

Run it inside Claude Code after adding the marketplace with /plugin marketplace add Dowwie/tasker.

Contents

Discovered from source

Skills 3

Execute Workflow

CRITICAL: This is the EXECUTE skill. Only use this after /plan has completed and task files exist in .tasker/tasks/. If no tasks exist, tell the user to run /tasker:plan first.

IMPORTANT: All tasker working files are in $TARGET_DIR/.tasker/. Do NOT create or use any other directories like project-planning/, planning/, or schemas/ at the target project root. The .tasker/ directory is the ONLY location for tasker artifacts (including .tasker/schemas/ for JSON schemas).

Execute a task DAG via isolated subagents. This is Phase 3 of the tasker workflow:

/specify → /plan → /execute

Input Requirements

  • Task DAG from /plan: .tasker/tasks/T001.json, T002.json, etc.
  • State file: .tasker/state.json with phase = "ready" or "executing"

Output

  • Working implementation in target directory
  • Task results: .tasker/bundles/T001-result.json, etc.
  • Evaluation report: .tasker/reports/evaluation-report.txt

MANDATORY FIRST STEP: Ask for Target Project Directory

ALWAYS ask for target_dir FIRST before anything else. No guessing, no inference from CWD.

Use AskUserQuestion to ask:

What is the target project directory?

Free-form text input. User must provide an absolute or relative path.

After target_dir is confirmed:

TARGET_DIR="<user-provided-path>"
# Convert to absolute path
TARGET_DIR=$(cd "$TARGET_DIR" 2>/dev/null && pwd)

TASKER_DIR="$TARGET_DIR/.tasker"

# Verify .tasker/ exists and has state
if [ ! -f "$TASKER_DIR/state.json" ]; then
    echo "Error: No tasker session found at $TASKER_DIR"
    echo "Run /plan first to create a task plan."
    exit 1
fi

Execute Prerequisites

# Verify planning is complete
tasker state status
# Phase must be: ready, executing, or have tasks

Git Repository Initialization (MANDATORY)

Before any implementation begins, check if the target repository has git initialized. If not, initialize it:

./scripts/ensure-git.sh "$TARGET_DIR"

Why this is required:

  • Enables automatic commit hooks to track changes per task
  • Provides audit trail of all implementation changes
  • Required for the post-task-commit hook to function

Recovery on Start (CRITICAL)

Before starting the execute loop, always check for and recover from a previous crash:

# Check for existing checkpoint from previous run
tasker state checkpoint status

# If checkpoint exists and is active, recover
tasker state checkpoint recover

# This will:
# 1. Find tasks that completed (have result files) but weren't acknowledged
# 2. Identify orphaned tasks (still "running" with no result file)
# 3. Update checkpoint state accordingly

If orphaned tasks are found, ask user:

Found 3 orphaned tasks from previous run:
- T019, T011, T006

Options:
1. Retry orphaned tasks (reset to pending)
2. Skip orphaned tasks (mark failed)
3. Abort and investigate

To retry orphaned tasks:

tasker state task retry T019
tasker state task retry T011
tasker state task retry T006
tasker state checkpoint clear

Execute Loop

CRITICAL CONSTRAINTS:

  • Max 3 parallel executors - More causes orchestrator context exhaustion
  • Task-executors are self-completing - They update state and write results directly
  • Checkpoint before spawning - Track batch for crash recovery
  • Minimal returns - Executors return only T001: SUCCESS or T001: FAILED - reason

Loop Steps

Repeat until no more tasks or halt requested:

Step 0: Check for Halt

  • Use Bash: tasker state check-halt
  • If exit code is non-zero, halt was requested:
    • Run tasker state checkpoint complete
    • Generate and display evaluation report (see "Evaluation Report" section)
    • Run tasker state confirm-halt
    • Exit loop

Step 1: Get Ready Tasks

  • Use Bash: tasker state ready
  • If no ready tasks:
    • Run tasker state advance
    • If successful: all tasks complete! Clear checkpoint, generate and display evaluation report, exit loop
    • If no progress: check for blockers with tasker state status, exit loop

Step 2: Select Batch

  • Take up to 3 task IDs from ready tasks

Step 3: Generate and Validate Bundles For each task in batch:

  • Use Bash: tasker bundle generate {TASK_ID}
  • Use Bash: tasker bundle validate-integrity {TASK_ID}
  • If integrity fails (exit code 1): fail the task with tasker state task fail {TASK_ID} "Bundle integrity validation failed" --category dependency
  • If integrity warns (exit code 2): regenerate bundle

Step 4: Create Checkpoint

  • Use Bash: tasker state checkpoint create {TASK_IDs...}

Step 5: Mark Tasks Started For each valid task:

  • Use Bash: tasker state task start {TASK_ID}

Step 6: Spawn Executors in Parallel Use the Task tool to spawn task-executor subagents for ALL valid tasks in a SINGLE message (parallel execution):

Execute task {TASK_ID}

TASKER_DIR: {absolute path to .tasker directory}
Bundle: {TASKER_DIR}/bundles/{TASK_ID}-bundle.json

Wait for all executors to return. Each returns only: {TASK_ID}: SUCCESS or {TASK_ID}: FAILED - reason

Step 7: Update Checkpoint For each task in batch:

  • Use Bash: tasker state checkpoint update {TASK_ID} {status}

Step 8: Complete Checkpoint

  • Use Bash: tasker state checkpoint complete

Step 9: Check for Halt After Batch

  • Use Bash: tasker state check-halt
  • If halted: generate and display evaluation report, confirm halt, exit loop

Step 10: Continue to Next Batch


Post-Execution Commit (Defense in Depth)

Task file commits are handled automatically by a Claude Code hook, ensuring commits happen regardless of executor behavior.

Hook Configuration

Configured in .claude/settings.local.json:

"PostToolUse": [
  {
    "matcher": "Task",
    "hooks": [
      {
        "type": "command",
        "command": ".claude/hooks/post-task-commit.sh",
        "timeout": 30
      }
    ]
  }
]

Subagent Spawn Template

Spawn task-executor with self-contained bundle. Executors are self-completing - they update state and write results directly, returning only a minimal status line.

Execute task [TASK_ID]

## Logging (MANDATORY)

```bash
./scripts/log-activity.sh INFO task-executor start "Executing task [TASK_ID]"
./scripts/log-activity.sh INFO task-executor decision "What decision and why"
./scripts/log-activity.sh INFO task-executor complete "Outcome description"

TASKER_DIR: {absolute path to .tasker directory} Bundle: {TASKER_DIR}/bundles/[TASK_ID]-bundle.json

The bundle contains everything you need:

  • Task definition and acceptance criteria
  • Expanded behavior details (what to implement)
  • File paths and purposes
  • Target directory
  • Constraints and patterns to follow
  • Dependencies (files from prior tasks)

Self-Completion Protocol (CRITICAL)

You are responsible for updating state and persisting results. Do NOT rely on the orchestrator.

On Success:

  1. Track all files you created/modified
  2. Call: tasker state task complete [TASK_ID] --created file1 file2 --modified file3
  3. Write result file: {TASKER_DIR}/bundles/[TASK_ID]-result.json
  4. Return ONLY this line: [TASK_ID]: SUCCESS

On Failure:

  1. Call: tasker state task fail [TASK_ID] "error message" --category <cat> --retryable
  2. Write result file with error details
  3. Return ONLY this line: [TASK_ID]: FAILED - <one-line reason>

Result File Schema

Write to {TASKER_DIR}/bundles/[TASK_ID]-result.json:

{
  "version": "1.0",
  "task_id": "[TASK_ID]",
  "name": "Task name from bundle",
  "status": "success|failed",
  "started_at": "ISO timestamp",
  "completed_at": "ISO timestamp",
  "files": {
    "created": ["path1", "path2"],
    "modified": ["path3"]
  },
  "verification": {
    "verdict": "PASS|FAIL",
    "criteria": [
      {"name": "criterion", "status": "PASS|FAIL", "evidence": "..."}
    ]
  },
  "error": {
    "category": "dependency|compilation|test|validation|runtime",
    "message": "...",
    "retryable": true
  },
  "notes": "Any decisions or observations"
}

Workflow Summary

  1. Read the bundle file - it has ALL context
  2. Implement behaviors in specified files
  3. Run acceptance criteria verification
  4. Call tasker state to update task status
  5. Write detailed result to bundles/[TASK_ID]-result.json
  6. Return ONE LINE status to orchestrator

IMPORTANT: Use the TASKER_DIR absolute path provided. Do NOT use relative paths.


---

## Bundle Contents

The bundle (`{TASKER_DIR}/bundles/T001-bundle.json`) includes:

| Field | Purpose |
|-------|---------|
| `task_id`, `name` | Task identification |
| `target_dir` | Where to write code |
| `behaviors` | Expanded behavior details (not just IDs) |
| `files` | Paths, actions, purposes, layers |
| `acceptance_criteria` | Verification commands |
| `constraints` | Tech stack, patterns, testing |
| `dependencies.files` | Files from prior tasks to read |
| `context` | Domain, capability, spec reference |
| `state_machine` | FSM context for adherence verification (if present) |

Generate bundles with:
```bash
tasker bundle generate T001       # Single task
tasker bundle generate-ready      # All ready tasks

Execute Options

CommandBehavior
/executeInteractive, one task at a time
/execute T005Execute specific task only
/execute --batchAll ready tasks, no prompts
/execute --parallel 3Up to 3 tasks simultaneously

Graceful Halt and Resume

The executor supports graceful halt via two mechanisms:

1. STOP File (Recommended for External Control)

Create a STOP file in the .tasker/ directory:

touch .tasker/STOP

The executor checks for this file before starting each new task and after completing each task. When detected:

  1. Current task (if running) completes normally
  2. No new tasks are started
  3. State is saved with halt information
  4. Clean exit with instructions to resume

2. User Message (For Interactive Sessions)

If a user sends "STOP" during an interactive /execute session, the orchestrator should:

  1. Call tasker state halt user_message
  2. Allow current task to complete
  3. Exit gracefully

Resuming Execution

To resume after a halt:

# Check current halt status
tasker state halt-status

# Clear halt and resume
tasker state resume

# Then run /execute again

FSM Coverage Report (After Execution Completes)

After all tasks complete, generate the execution coverage report:

tasker fsm validate execute-coverage-report \
    {TASKER_DIR}/artifacts/fsm/index.json \
    {TASKER_DIR}/bundles \
    --output {TASKER_DIR}/artifacts/fsm-coverage.execute.json

This report includes:

  • Which transitions were verified during execution
  • Evidence type for each transition (test, runtime_assertion, manual)
  • Which invariants were enforced
  • Pointers to tasks and acceptance criteria that provide evidence

Evaluation Report (After Completion)

MANDATORY: After all tasks complete (or execution halts), generate AND DISPLAY the evaluation report.

Step 1: Generate the report

Use Bash tool:

  • tasker evaluate --output {TASKER_DIR}/reports/evaluation-report.txt
  • tasker evaluate --format json --output {TASKER_DIR}/reports/evaluation-report.json

Step 2: Read and display the report

CRITICAL: Use the Read tool to read {TASKER_DIR}/reports/evaluation-report.txt and display its full contents to the user. Do NOT just say "report generated" - show the actual report.

The report includes:

  • Planning Quality - plan verdict and issues at planning time
  • Execution Summary - completed/failed/blocked/skipped counts
  • First-Attempt Success Rate - measures spec quality
  • Verification Breakdown - criteria pass/partial/fail, code quality scores
  • Cost Analysis - total tokens, total cost, per-task cost
  • Failure Analysis - which tasks failed and why (if any)
  • Improvement Patterns - common issues for process improvement

Step 3: Summarize key outcomes

After displaying the report, provide a brief summary:

  • Total tasks completed vs failed
  • Any notable failures or issues requiring attention
  • Suggested next steps (e.g., "run tests", "review changes", "check logs")

Archive Execution Artifacts (After Completion)

After execution completes (all tasks done or halted), archive execution artifacts:

tasker archive execution {project_name}

This creates:

archive/{project_name}/execution/{timestamp}/
├── bundles/        # Task bundles and result files
├── logs/           # Activity logs
├── state.json      # State snapshot
└── archive-manifest.json

State Commands Reference

# Execution
tasker state ready               # List ready tasks
tasker state task start <id>     # Mark running
tasker state task complete <id>  # Mark done
tasker state task fail <id> <e>  # Mark failed
tasker state load-tasks          # Reload from files

# Halt / Resume
tasker state halt [reason]       # Request graceful halt
tasker state check-halt          # Check if halted (exit 1 = halted)
tasker state confirm-halt        # Confirm halt completed
tasker state halt-status         # Show halt status
tasker state resume              # Clear halt, resume execution

# Checkpoint (Crash Recovery)
tasker state checkpoint create <t1> [t2 ...]  # Create batch checkpoint
tasker state checkpoint update <id> <status>  # Update task
tasker state checkpoint complete              # Mark batch done
tasker state checkpoint status                # Show current checkpoint
tasker state checkpoint recover               # Recover orphaned tasks
tasker state checkpoint clear                 # Remove checkpoint

# Bundles
tasker bundle generate <id>      # Generate bundle for task
tasker bundle generate-ready     # Generate all ready bundles
tasker bundle validate <id>      # Validate bundle against schema
tasker bundle validate-integrity <id>  # Check deps + checksums
tasker bundle list               # List existing bundles
tasker bundle clean              # Remove all bundles

Error Recovery

If task fails:

  1. tasker state task fail marks it failed
  2. Rollback triggered (created files deleted, modified files restored)
  3. Dependent tasks auto-blocked
  4. Other ready tasks can continue
  5. User can retry later: fix issue, then tasker state task retry again

Plan Workflow

CRITICAL: This is the PLAN skill. Do NOT call Skill(execute) or Skill(tasker:execute). Follow the instructions below directly.

IMPORTANT: All tasker working files go in $TARGET_DIR/.tasker/. Do NOT create any other directories like project-planning/, planning/, or schemas/ at the target project root. The .tasker/ directory is the ONLY location for tasker artifacts (including .tasker/schemas/ for JSON schemas).

Decompose a specification into an executable task DAG. This is Phase 2 of the tasker workflow:

/specify → /plan → /execute

Input Requirements

  • Spec from /specify: {TARGET}/docs/specs/<slug>.md
  • Capability Map: {TARGET}/docs/specs/<slug>.capabilities.json
  • FSM Artifacts (optional): {TARGET}/docs/state-machines/<slug>/

Output

  • Task DAG: .tasker/tasks/T001.json, T002.json, etc.
  • Physical Map: .tasker/artifacts/physical-map.json
  • Validation Report: .tasker/reports/task-validation-report.md

MANDATORY FIRST STEP: Ask for Target Project Directory

ALWAYS ask for target_dir FIRST before anything else. No guessing, no inference from CWD.

Step 1: Ask for Target Directory

Use AskUserQuestion to ask:

What is the target project directory?

Free-form text input. User must provide an absolute or relative path.

Validation:

TARGET_DIR="<user-provided-path>"
# Convert to absolute path
TARGET_DIR=$(cd "$TARGET_DIR" 2>/dev/null && pwd || echo "$TARGET_DIR")

if [ ! -d "$TARGET_DIR" ]; then
    # For new projects, check parent exists
    PARENT=$(dirname "$TARGET_DIR")
    if [ -d "$PARENT" ]; then
        echo "Directory will be created: $TARGET_DIR"
        mkdir -p "$TARGET_DIR"
    else
        echo "Error: Parent directory does not exist: $PARENT"
        # Re-ask for target_dir
    fi
fi

Step 2: Check for Existing Session and Initialize

After target_dir is confirmed, check for existing .tasker/ state:

TASKER_DIR="$TARGET_DIR/.tasker"
if [ -f "$TASKER_DIR/state.json" ]; then
    echo "Found existing tasker session at $TASKER_DIR"
    echo "Resuming from saved state..."
    # Read phase from state.json and resume
    tasker state status
else
    echo "No existing session. Initializing..."
    # Initialize directory structure
fi

Step 3: Detect Specs (Automatic)

Specs are REQUIRED for /plan to proceed. Check $TARGET_DIR/docs/specs/ for specs from /specify:

SPEC_DIR="$TARGET_DIR/docs/specs"

# Find spec files (from /specify workflow)
SPEC_FILES=$(find "$SPEC_DIR" -maxdepth 1 -name "*.md" 2>/dev/null)
CAP_MAPS=$(find "$SPEC_DIR" -maxdepth 1 -name "*.capabilities.json" 2>/dev/null)

if [ -n "$SPEC_FILES" ]; then
    echo "=== Specs found ==="
    echo "$SPEC_FILES"

    # Use the first spec (or only spec)
    SPEC_PATH=$(echo "$SPEC_FILES" | head -1)
    SPEC_SLUG=$(basename "$SPEC_PATH" .md)

    # Check for matching capability map
    CAP_MAP="$SPEC_DIR/${SPEC_SLUG}.capabilities.json"
    if [ -f "$CAP_MAP" ]; then
        echo "Capability map found: $CAP_MAP"
        echo "Can skip logic-architect phase"
    fi
else
    echo "No specs found in $SPEC_DIR"
    # BLOCK - see below
fi

If spec found:

Proceed to Step 4. No user question needed.

If NO spec found — BLOCK and offer /specify:

/plan CANNOT proceed without specs. Present this to the user:

## Specs Required

Planning requires a specification to decompose into tasks. Without a spec, there's nothing to plan.

**Would you like to create a spec now using `/specify`?**

The `/specify` workflow will guide you through:
1. Defining goals and scope
2. Clarifying requirements through structured questions
3. Extracting capabilities and behaviors
4. Producing a spec ready for `/plan`

Ask using AskUserQuestion:

Would you like to run /specify to create a spec now?

Options:

  • Yes, start /specify — Begin the specification workflow
  • No, I'll provide a spec later — Exit /plan for now

Step 4: Detect Project Type (Automatic)

Do not ask the user — infer project type from target directory:

# Check if target directory has source code
SOURCE_FILES=$(find "$TARGET_DIR" \( -name "*.py" -o -name "*.ts" -o -name "*.js" -o -name "*.go" -o -name "*.rs" -o -name "*.java" \) \
    -not -path "*node_modules*" -not -path "*__pycache__*" -not -path "*.venv*" -not -path "*/.git/*" 2>/dev/null | head -5)

if [ -n "$SOURCE_FILES" ]; then
    PROJECT_TYPE="existing"
    echo "Detected existing project with source files"
else
    PROJECT_TYPE="new"
    echo "New project (no existing source files)"
fi
  • Existing project → Proceed to Step 5 (project analysis)
  • New project → Skip to Step 6 (tech stack)

Step 5: Existing Project Analysis (if PROJECT_TYPE=existing)

If enhancing an existing project, you MUST analyze the target directory BEFORE proceeding to ingestion. This analysis is CRITICAL - sub-agents cannot see the codebase, so you must extract and pass this context to them.

# Check directory exists
if [ ! -d "$TARGET_DIR" ]; then
    echo "Error: Target directory does not exist"
    exit 1
fi

# Analyze structure (capture output for context)
echo "=== Project Structure ==="
tree -L 3 -I 'node_modules|__pycache__|.git|venv|.venv|dist|build|.pytest_cache' "$TARGET_DIR" 2>/dev/null || \
    find "$TARGET_DIR" -maxdepth 3 -type f | head -50

# Identify key configuration files
echo "=== Key Configuration Files ==="
for f in package.json pyproject.toml Cargo.toml go.mod Makefile requirements.txt setup.py tsconfig.json; do
    [ -f "$TARGET_DIR/$f" ] && echo "Found: $f"
done

# Detect source layout patterns
echo "=== Source Layout ==="
for d in src lib app pkg cmd internal; do
    [ -d "$TARGET_DIR/$d" ] && echo "Found directory: $d/"
done

# Detect test layout
echo "=== Test Layout ==="
for d in tests test spec __tests__; do
    [ -d "$TARGET_DIR/$d" ] && echo "Found test directory: $d/"
done

# Sample existing code files to understand patterns
echo "=== Code Samples ==="
find "$TARGET_DIR" \( -name "*.py" -o -name "*.ts" -o -name "*.js" -o -name "*.go" -o -name "*.rs" \) \
    -not -path "*node_modules*" -not -path "*__pycache__*" -not -path "*.venv*" | head -10

Read key files to understand patterns:

# Read config files to understand dependencies and structure
[ -f "$TARGET_DIR/pyproject.toml" ] && cat "$TARGET_DIR/pyproject.toml"
[ -f "$TARGET_DIR/package.json" ] && cat "$TARGET_DIR/package.json"

# Sample a few source files to understand coding patterns
# (naming conventions, import style, architecture patterns)

Step 6: Store Discovery Context

CRITICAL: You must retain this analysis for passing to sub-agents. Store it as a structured context block:

PROJECT_CONTEXT = """
Directory: {TARGET_DIR}
Project Type: existing
Stack: {detected stack}
Source Layout: {layout pattern}
Test Layout: {test pattern}

Key Patterns:
- {pattern 1}
- {pattern 2}
- {pattern 3}

Integration Requirements:
- {requirement 1}
- {requirement 2}
"""

This PROJECT_CONTEXT MUST be included in every sub-agent spawn prompt (logic-architect, physical-architect, task-author). Without it, sub-agents will design solutions that conflict with existing code.


Directory Initialization

CRITICAL: After obtaining target_dir, initialize the .tasker/ directory structure. Sub-agents assume directories already exist.

TASKER_DIR="$TARGET_DIR/.tasker"
mkdir -p "$TASKER_DIR"/{artifacts,inputs,tasks,reports,bundles,logs}

This creates:

  • $TARGET_DIR/.tasker/artifacts/ - For capability-map.json, physical-map.json
  • $TARGET_DIR/.tasker/inputs/ - For spec.md
  • $TARGET_DIR/.tasker/tasks/ - For T001.json, T002.json, etc.
  • $TARGET_DIR/.tasker/reports/ - For task-validation-report.md
  • $TARGET_DIR/.tasker/bundles/ - For execution bundles
  • $TARGET_DIR/.tasker/logs/ - For activity logging

Runtime Logging (MANDATORY)

All orchestrator activity and sub-agent activity MUST be logged using ./scripts/log-activity.sh.

./scripts/log-activity.sh <LEVEL> <AGENT> <EVENT> "<MESSAGE>"

Parameters:

  • LEVEL: INFO, WARN, ERROR
  • AGENT: orchestrator, logic-architect, physical-architect, task-author, etc.
  • EVENT: start, decision, tool, complete, spawn, spawn-complete, phase-transition, validation
  • MESSAGE: Description of the activity

Skip Phases for /specify-Generated Specs

If the spec came from /specify workflow, it has already been reviewed AND capabilities have been extracted. Check for artifacts:

# Derive capability map path from spec path
SPEC_DIR=$(dirname "$SPEC_PATH")
SPEC_SLUG=$(basename "$SPEC_PATH" .md)
CAPABILITY_MAP="${SPEC_DIR}/${SPEC_SLUG}.capabilities.json"

if [ -f "$CAPABILITY_MAP" ]; then
    echo "Capability map found from /specify workflow: $CAPABILITY_MAP"
    echo "Copying artifacts and skipping to physical phase..."

    # Copy artifacts to .tasker/ directory
    cp "$CAPABILITY_MAP" "$TASKER_DIR/artifacts/capability-map.json"

    # Check for FSM artifacts from /specify workflow
    FSM_DIR="${SPEC_DIR}/../state-machines/${SPEC_SLUG}"
    if [ -d "$FSM_DIR" ]; then
        echo "FSM artifacts found from /specify workflow: $FSM_DIR"
        mkdir -p "$TASKER_DIR/artifacts/fsm"
        cp -r "$FSM_DIR"/* "$TASKER_DIR/artifacts/fsm/"
    fi

    # Skip spec_review AND logical phases - advance directly to physical
    tasker state set-phase physical
fi

Skip phases when /specify artifacts exist:

  • spec_review - Skipped (already done by /specify Phase 7)
  • logical - Skipped (capability map already exists from /specify Phase 3)

Plan Phase Dispatch

# Initialize if no state exists
if [ ! -f "$TASKER_DIR/state.json" ]; then
    tasker state init "$TARGET_DIR"
fi

# Check current phase
tasker state status
PhaseAgentOutputValidationSkip if
ingestion(none)inputs/spec.md (verbatim)File exists—
spec_reviewspec-reviewerartifacts/spec-review.jsonAll critical resolved/specify artifacts exist
logicallogic-architectartifacts/capability-map.jsonvalidate capability_map/specify artifacts exist
physicalphysical-architectartifacts/physical-map.jsonvalidate physical_map—
definitiontask-authortasks/*.jsonload-tasks—
validationtask-plan-verifierValidation reportvalidate-tasks <verdict>—
sequencingplan-auditorUpdated task phasesDAG is valid—
ready(done)Planning complete——

Plan Loop

while phase not in ["ready", "executing", "complete"]:
    1. Query current phase
    2. Spawn appropriate agent WITH FULL CONTEXT (see spawn templates below)
    3. Wait for agent to complete
    4. **VERIFY OUTPUT EXISTS** (critical - see below)
       - DO NOT log spawn-complete until file verified
       - DO NOT proceed to validation until file verified
    5. If file missing: RE-SPAWN agent immediately (see recovery below)
    6. Validate output:
       - For artifacts: tasker state validate <artifact>
       - For task validation: tasker state validate-tasks <verdict>
    7. If valid: tasker state advance
    8. If invalid: Tell agent to fix, re-validate

CRITICAL: Never log "spawn-complete: SUCCESS" until the output file is verified to exist!


Output Verification Before Validation

MANDATORY STEP: After each agent completes, you MUST verify its output file exists before attempting validation.

# After logic-architect completes:
if [ ! -f $TASKER_DIR/artifacts/capability-map.json ]; then
    echo "ERROR: capability-map.json not written. Agent must retry."
fi

# After physical-architect completes:
if [ ! -f $TASKER_DIR/artifacts/physical-map.json ]; then
    echo "ERROR: physical-map.json not written. Agent must retry."
fi

# After task-author completes:
task_count=$(ls $TASKER_DIR/tasks/*.json 2>/dev/null | wc -l)
if [ "$task_count" -eq 0 ]; then
    echo "ERROR: No task files written. Agent must retry."
fi

Recovery procedure: If file doesn't exist:

  1. Check if directory exists: ls -la $TASKER_DIR/artifacts/
  2. Re-spawn the agent with explicit reminder to use Write tool

Agent Spawn Templates

CRITICAL: Each sub-agent is context-isolated. They CANNOT see the orchestrator's conversation. You MUST pass ALL relevant context explicitly in the spawn prompt.

Physical Phase: physical-architect

Map behaviors to concrete file paths.

## Logging (MANDATORY)

./scripts/log-activity.sh INFO physical-architect start "Mapping behaviors to file paths"

## Context

TASKER_DIR: {absolute path to .tasker directory}
Target Directory: {TARGET_DIR}
Project Type: {new | existing}
Tech Stack: {from spec or inferred}

## Project Context (CRITICAL for existing projects)

{INSERT FULL PROJECT_CONTEXT HERE}

## Your Task

1. Read {TASKER_DIR}/artifacts/capability-map.json
2. **For existing projects:** Map behaviors to paths that FIT the existing structure
3. For new projects: Establish clean, conventional structure
4. **CRITICAL: Use the Write tool** to save to {TASKER_DIR}/artifacts/physical-map.json
5. **Verify file exists**: `ls -la {TASKER_DIR}/artifacts/physical-map.json`
6. Validate with: `cd {TASKER_DIR}/.. && tasker state validate physical_map`

Definition Phase: task-author

Create individual task files from the physical map.

## Logging (MANDATORY)

./scripts/log-activity.sh INFO task-author start "Creating task files"

## Context

TASKER_DIR: {absolute path to .tasker directory}
Target Directory: {TARGET_DIR}
Project Type: {new | existing}

## Project Context (for existing projects)

{INSERT FULL PROJECT_CONTEXT HERE}

## Your Task

1. Read {TASKER_DIR}/artifacts/physical-map.json
2. Read {TASKER_DIR}/artifacts/capability-map.json (for behavior details)
3. **Check for FSM artifacts**: If {TASKER_DIR}/artifacts/fsm/index.json exists, add FSM context to tasks
4. **CRITICAL: Use the Write tool** to save each task file to {TASKER_DIR}/tasks/T001.json, etc.
5. **Verify files exist**: `ls -la {TASKER_DIR}/tasks/`
6. Load tasks with: `cd {TASKER_DIR}/.. && tasker state load-tasks`

Validation Phase: task-plan-verifier

Verify task definitions for planning

## Logging (MANDATORY)

./scripts/log-activity.sh INFO task-plan-verifier start "Verifying task definitions"

## Context

TASKER_DIR: {absolute path to .tasker directory}
Spec: {TASKER_DIR}/inputs/spec.md
Capability Map: {TASKER_DIR}/artifacts/capability-map.json
Tasks Directory: {TASKER_DIR}/tasks/

## Required Command

Register verdict using: tasker state validate-tasks <VERDICT> "<summary>"

Sequencing Phase: plan-auditor

Assign phases to tasks and validate the dependency graph.

## Logging (MANDATORY)

./scripts/log-activity.sh INFO plan-auditor start "Assigning phases and validating DAG"

## Context

TASKER_DIR: {absolute path to .tasker directory}

## Your Task

1. Read {TASKER_DIR}/tasks/*.json
2. Read {TASKER_DIR}/artifacts/capability-map.json (for steel thread flows)
3. Build dependency graph
4. Assign phases (1: foundations, 2: steel thread, 3+: features)
5. **CRITICAL: Update task files** using Write tool
6. Validate DAG (no cycles, deps in earlier phases)
7. Run: cd {TASKER_DIR}/.. && tasker state load-tasks

Plan Completion

When phase reaches "ready":

## Planning Complete ✓

**Tasks:** 24
**Phases:** 4
**Steel Thread:** T001 → T003 → T007 → T012

Run `/execute` to begin implementation.

Archive Planning Artifacts (Automatic)

After planning completes, archive the artifacts:

tasker archive planning {project_name}

State Commands Reference

# General
tasker state status          # Current phase, task counts
tasker state advance         # Try to advance phase

# Planning
tasker state init <dir>      # Initialize new plan
tasker state validate <art>  # Validate artifact
tasker state validate-tasks <verdict> [summary]  # Register task validation result
tasker state load-tasks      # Reload from files

Error Recovery

If agent produces invalid output:

  1. Validation fails (tasker state validate returns non-zero)
  2. Report errors to agent
  3. Agent fixes and re-outputs
  4. Re-validate
  5. Only advance on success

Specify Workflow

IMPORTANT: All tasker working files go in $TARGET_DIR/.tasker/. Do NOT create any other directories like project-planning/, planning/, or schemas/ at the target project root. The .tasker/ directory is the ONLY location for tasker artifacts (including .tasker/schemas/ for JSON schemas).

An agent-driven interactive workflow that transforms ideas into actionable specifications with extracted capabilities, ready for /plan to decompose into tasks.

Core Principles

  1. Workflows and invariants before architecture - Never discuss implementation until behavior is clear
  2. Decision-dense, not prose-dense - Bullet points over paragraphs
  3. No guessing — Uncertainty becomes Open Questions
  4. Minimal facilitation — Decide only when required
  5. Specs are living; ADRs are historical
  6. Less is more — Avoid ceremony

Artifacts

Required Outputs (in TARGET project)

  • README — {TARGET}/README.md (project overview - what it is, how to use it)
  • Spec Packet — {TARGET}/docs/specs/<slug>.md (human-readable)
  • Capability Map — {TARGET}/docs/specs/<slug>.capabilities.json (machine-readable, for /plan)
  • Behavior Model (FSM) — {TARGET}/docs/state-machines/<slug>/ (state machine artifacts, for /plan and /execute)
  • ADR files — {TARGET}/docs/adrs/ADR-####-<slug>.md (0..N)

Working Files (in target project's .tasker/)

  • Session state — $TARGET_DIR/.tasker/state.json (persistent, primary resume source)
  • Spec draft — $TARGET_DIR/.tasker/spec-draft.md (working draft, written incrementally)
  • Discovery file — $TARGET_DIR/.tasker/clarify-session.md (append-only log)
  • Stock-takes — $TARGET_DIR/.tasker/stock-takes.md (append-only log of vision evolution)
  • Decision registry — $TARGET_DIR/.tasker/decisions.json (index of decisions/ADRs)
  • Spec Review — $TARGET_DIR/.tasker/spec-review.json (weakness analysis)

Archive

After completion, artifacts can be archived using tasker archive for post-hoc analysis.


MANDATORY: Phase Order

Initialization → Scope → Clarification Loop (Discovery) → Synthesis → Architecture Sketch → Decisions/ADRs → Gate → Spec Review → Export

NEVER skip or reorder these phases.


Phase 0 — Initialization

Goal

Establish project context and session state before specification work begins.

STEP 1: Auto-Detect Session State (MANDATORY FIRST)

Before asking the user anything, check for existing session state files.

1a. Determine Target Directory

Check in order:

  1. If user provided a path in their message, use that
  2. If CWD contains .tasker/state.json, use CWD
  3. Otherwise, ask:
What is the target project directory?

1b. Check for Existing Session

TARGET_DIR="<determined-path>"
STATE_FILE="$TARGET_DIR/.tasker/state.json"

if [ -f "$STATE_FILE" ]; then
    # Read state to determine if session is in progress
    PHASE=$(jq -r '.phase.current' "$STATE_FILE")
    if [ "$PHASE" != "complete" ] && [ "$PHASE" != "null" ]; then
        echo "RESUME: Found active session at phase '$PHASE'"
        # AUTO-RESUME - skip to Step 1c
    else
        echo "NEW: Previous session completed. Starting fresh."
        # Proceed to Step 2 (new session)
    fi
else
    echo "NEW: No existing session found."
    # Proceed to Step 2 (new session)
fi

1c. Auto-Resume Protocol (if active session found)

If .tasker/state.json exists and phase.current != "complete":

  1. Read state.json to get current phase and step
  2. Inform user (no question needed):
    Resuming specification session for "{spec_session.spec_slug}"
    Current phase: {phase.current}, step: {phase.step}
    
  3. Read required working files for the current phase (see Resume Protocol section)
  4. Jump directly to the current phase - do NOT re-run earlier phases

This is automatic. Do not ask the user whether to resume.


STEP 2: New Session Setup (only if no active session)

2a. No Guessing on Reference Materials

You MUST NOT:

  • Scan directories to infer what files exist
  • Guess spec locations from directory structure
  • Read files to detect existing specs
  • Make any assumptions about what the user has

The user tells you everything. You ask, they answer.

2b. Ask About Reference Materials

Ask using AskUserQuestion:

Do you have existing specification reference materials (PRDs, requirements docs, design docs, etc.)?

Options:

  • No reference materials — Starting from scratch
  • Yes, I have reference materials — I'll provide the location(s)

If "Yes, I have reference materials":

Ask for the location(s):

Where are your reference materials located? (Provide path(s) - can be files or directories)

Free-form text input. User provides path(s) (e.g., docs/specs/, requirements.md, PRD.pdf).

Validate path exists:

EXISTING_SPEC_PATH="<user-provided-path>"
if [ ! -e "$TARGET_DIR/$EXISTING_SPEC_PATH" ] && [ ! -e "$EXISTING_SPEC_PATH" ]; then
    echo "Warning: Path not found. Please verify the path."
fi

2c. Initialize Session State

Create .tasker/ directory structure in target project:

TASKER_DIR="$TARGET_DIR/.tasker"
mkdir -p "$TASKER_DIR"/{inputs,artifacts,tasks,bundles,reports,fsm-draft,adrs-draft}

Create $TARGET_DIR/.tasker/state.json:

{
  "version": "3.0",
  "target_dir": "<absolute-path>",
  "phase": {
    "current": "initialization",
    "completed": [],
    "step": null
  },
  "created_at": "<timestamp>",
  "updated_at": "<timestamp>",
  "spec_session": {
    "project_type": "new|existing",
    "existing_spec_path": "<path-from-step-2-or-null>",
    "spec_slug": "<slug>",
    "spec_path": "<target>/docs/specs/<slug>.md",
    "started_at": "<timestamp>",
    "resumed_from": null
  },
  "scope": null,
  "clarify": null,
  "synthesis": null,
  "architecture": null,
  "decisions": null,
  "review": null
}

CRITICAL: Update state.json after EVERY significant action. This enables resume from any point.

The phase-specific state objects are populated as each phase progresses (see phase definitions below).

If user provided existing spec path in Step 2b, store it in spec_session.existing_spec_path for reference during Scope phase.

Output (New Session Only)

For new sessions (Step 2 path):

  • .tasker/ directory structure created in target project
  • Session state initialized in $TARGET_DIR/.tasker/state.json
  • Existing spec path captured (if provided)
  • Proceed to Phase 1 (Scope)

For resumed sessions (Step 1c path):

  • State already exists - no initialization needed
  • Jump directly to phase.current phase
  • Read working files as specified in Resume Protocol

Phase 1 — Scope

Goal

Establish bounds before discovery.

Pre-Scope: Load Existing Spec (if provided)

If spec_session.existing_spec_path was set during initialization:

  1. Read the existing spec file to understand prior context
  2. Extract initial answers for the scope questions below (Goal, Non-goals, Done means)
  3. Present extracted context to user for confirmation/refinement rather than asking from scratch
if [ -n "$EXISTING_SPEC_PATH" ]; then
    echo "Loading existing spec from: $EXISTING_SPEC_PATH"
    # Read and analyze existing spec
    # Pre-fill scope questions with extracted information
fi

Required Questions (AskUserQuestion)

Ask these questions using AskUserQuestion tool with structured options. If existing spec was loaded, present extracted answers for confirmation rather than blank questions:

Question 1: Goal

What are we building?

Free-form text input.

Question 2: Non-goals

What is explicitly OUT of scope?

Free-form text input (allow multiple items).

Question 3: Done Means

What are the acceptance bullets? (When is this "done"?)

Free-form text input (allow multiple items).

Question 4: Tech Stack

What tech stack should be used?

Free-form text input. Examples:

  • "Python 3.12+ with FastAPI, PostgreSQL, Redis"
  • "TypeScript, Next.js, Prisma, Supabase"
  • "Go with Chi router, SQLite"
  • "Whatever fits best" (let /specify recommend based on requirements)

If user says "whatever fits best" or similar:

  • Note this for Phase 2 (Clarify) to recommend based on gathered requirements
  • Ask clarifying questions: "Any language preferences?", "Cloud provider constraints?", "Team expertise?"

Question 5: Entry Point (CRITICAL for W8/I6 compliance)

How will users invoke this? What makes it available?

Options to present:

  • CLI command — User runs a command (specify command name)
  • API endpoint — User calls an HTTP endpoint (specify URL pattern)
  • Claude Code skill — User invokes /skillname (specify trigger)
  • Library/module — No direct invocation, imported by other code
  • Other — Custom activation mechanism

If user selects CLI/API/Skill: Follow up: "What specific steps are needed to make this available to users?"

If user selects Library/module: Note in spec: "Installation & Activation: N/A - library/module only"

Why this matters: Specs that describe invocation without activation mechanism cause W8 weakness and I6 invariant failure. Capturing this early prevents dead entry points.

Output

1. Update State (MANDATORY)

Update $TARGET_DIR/.tasker/state.json:

{
  "phase": {
    "current": "scope",
    "completed": ["initialization"],
    "step": "complete"
  },
  "updated_at": "<timestamp>",
  "scope": {
    "goal": "<user-provided-goal>",
    "non_goals": ["<item1>", "<item2>"],
    "done_means": ["<criterion1>", "<criterion2>"],
    "tech_stack": "<tech-stack-or-TBD>",
    "entry_point": {
      "type": "cli|api|skill|library|other",
      "trigger": "<command-name or /skillname or endpoint>",
      "activation_steps": ["<step1>", "<step2>"]
    },
    "completed_at": "<timestamp>"
  }
}

2. Write Spec Draft (MANDATORY)

Write initial spec sections to $TARGET_DIR/.tasker/spec-draft.md:

# Spec: {Title}

## Goal
{goal from scope}

## Non-goals
{non_goals from scope}

## Done means
{done_means from scope}

## Tech Stack
{tech_stack from scope}

## Installation & Activation
**Entry Point:** {entry_point.trigger from scope}
**Type:** {entry_point.type from scope}

**Activation Steps:**
{entry_point.activation_steps from scope, numbered list}

**Verification:**
<!-- To be filled in during Clarify or Synthesis -->

<!-- Remaining sections will be added by subsequent phases -->

IMPORTANT: All spec content is built in this file, NOT in conversation context. Read from this file when you need prior spec content.


Phase 2 — Clarify (Ralph Iterative Discovery Loop)

Purpose

Exhaustively gather requirements via structured questioning.

Setup

1. Initialize Clarify State in state.json (MANDATORY)

Update $TARGET_DIR/.tasker/state.json:

{
  "phase": {
    "current": "clarify",
    "completed": ["initialization", "scope"],
    "step": "starting"
  },
  "updated_at": "<timestamp>",
  "clarify": {
    "current_category": "core_requirements",
    "current_round": 1,
    "categories": {
      "core_requirements": { "status": "not_started", "rounds": 0 },
      "users_context": { "status": "not_started", "rounds": 0 },
      "integrations": { "status": "not_started", "rounds": 0 },
      "edge_cases": { "status": "not_started", "rounds": 0 },
      "quality_attributes": { "status": "not_started", "rounds": 0 },
      "existing_patterns": { "status": "not_started", "rounds": 0 },
      "preferences": { "status": "not_started", "rounds": 0 }
    },
    "pending_followups": [],
    "requirements_count": 0,
    "stock_takes_count": 0,
    "started_at": "<timestamp>"
  }
}

2. Create Discovery File

Create $TARGET_DIR/.tasker/clarify-session.md:

# Discovery: {TOPIC}
Started: {timestamp}

## Category Status

| Category | Status | Rounds | Notes |
|----------|--------|--------|-------|
| Core requirements | ○ Not Started | 0 | — |
| Users & context | ○ Not Started | 0 | — |
| Integrations | ○ Not Started | 0 | — |
| Edge cases | ○ Not Started | 0 | — |
| Quality attributes | ○ Not Started | 0 | — |
| Existing patterns | ○ Not Started | 0 | — |
| Preferences | ○ Not Started | 0 | — |

## Discovery Rounds

3. Create Stock-Takes File

Create $TARGET_DIR/.tasker/stock-takes.md:

# Stock-Takes: {TOPIC}
Started: {timestamp}

This file tracks how the vision evolves as discovery progresses.

---

CRITICAL: Resume Capability

On resume (after compaction or restart):

  1. Read $TARGET_DIR/.tasker/state.json to get clarify state
  2. Read $TARGET_DIR/.tasker/clarify-session.md to get discovery history
  3. Resume from clarify.current_category and clarify.current_round
  4. If clarify.pending_followups is non-empty, continue follow-up loop first

DO NOT rely on conversation context for clarify progress. Always read from files.

Loop Rules

  • No iteration cap - Continue until goals are met

  • Category Focus Mode - Work on ONE category at a time until it's complete or explicitly deferred

  • Each iteration:

    1. Read discovery file
    2. Select ONE incomplete category to focus on (priority: Core requirements → Users & context → Integrations → Edge cases → Quality attributes → Existing patterns → Preferences)
    3. Ask 2–4 questions within that focused category
    4. Get user answers
    5. Run Follow-up Sub-loop (see below) - validate and drill down on answers
    6. Only after follow-ups are complete: update discovery file, extract requirements, update category status
    7. Repeat within same category until goal is met OR user says "move on from this category"
  • Clarity Before Progress - If user response is anything except a direct answer (counter-question, confusion, pushback, tangential), provide clarification FIRST. Do NOT present new questions until prior questions have direct answers.

  • Stop ONLY when:

    • ALL category goals are met (see checklist), OR
    • User says "enough", "stop", "move on", or similar

Follow-up Sub-loop (MANDATORY)

After receiving answers to a question round, DO NOT immediately move to the next round. First, validate each answer:

Answer Validation Triggers

For each answer, check if follow-up is required:

TriggerExampleRequired Follow-up
Vague quantifier"several users", "a few endpoints""How many specifically?"
Undefined scope"and so on", "etc.", "things like that""Can you list all items explicitly?"
Weak commitment"probably", "maybe", "I think""Is this confirmed or uncertain?"
Missing specifics"fast response", "secure""What's the specific target? (e.g., <100ms)"
Deferred knowledge"I'm not sure", "don't know yet""Should we make a default assumption, or is this blocking?"
Contradicts earlier answerConflicts with prior round"Earlier you said X, now Y. Which is correct?"

Sub-loop Process

For each answer in current round:
  1. Check against validation triggers
  2. If trigger found:
     a. Add to pending_followups in state.json
     b. Ask ONE follow-up question (not batched)
     c. Wait for response
     d. Remove from pending_followups, re-validate the new response
     e. Repeat until answer is concrete OR user explicitly defers
  3. Only after ALL answers validated → proceed to next round

MANDATORY: Persist Follow-up State

Before asking a follow-up question, update state.json:

{
  "clarify": {
    "pending_followups": [
      {
        "question_id": "Q3.2",
        "original_answer": "<user's vague answer>",
        "trigger": "vague_quantifier",
        "followup_question": "<the follow-up question being asked>"
      }
    ]
  }
}

After receiving follow-up response, remove from pending_followups and update the round in clarify-session.md.

Follow-up Question Format

Use AskUserQuestion with context from the original answer:

{
  "question": "You mentioned '{user_quote}'. {specific_follow_up_question}",
  "header": "Clarify",
  "options": [
    {"label": "Specify", "description": "I'll provide a specific answer"},
    {"label": "Not critical", "description": "This detail isn't important for the spec"},
    {"label": "Defer", "description": "I don't know yet, note as open question"}
  ]
}

Handling Non-Direct Responses (MANDATORY)

If the user's response is anything other than a direct answer, assume clarification is required. Do NOT present new questions until the original question is resolved.

Response TypeExampleRequired Action
Counter-question"What do you mean by X?"Answer their question, then re-ask yours
Confusion"I'm not sure what you're asking"Rephrase the question with more context
Pushback"Why do you need to know that?"Explain why this matters for the spec
TangentialTalks about something elseAcknowledge, then redirect to the question
Partial answerAnswers part, ignores restNote the partial, ask about the unanswered part
Meta-comment"This is getting detailed"Acknowledge, offer to simplify or defer

Process:

1. Detect non-direct response
2. Address the user's concern/question FIRST
3. Only after clarity achieved → re-present the original question (or confirm it's now answered)
4. Do NOT batch new questions until all prior questions have direct answers

Example:

Agent: "What authentication method should users use?"
User: "What options are there?"

[NON-DIRECT: User asked a counter-question]

Agent: "Common options are: (1) Email/password, (2) OAuth (Google, GitHub),
       (3) Magic link, (4) SSO/SAML. Which fits your use case?"
User: "Email/password for now, maybe OAuth later."

[NOW DIRECT: Can proceed]

When NOT to Follow Up

  • User explicitly says "that's all I know" or "let's move on"
  • The answer is already concrete and specific
  • The detail is genuinely non-blocking (implementation detail, not spec-level)
  • You've already asked 2 follow-ups on the same answer (avoid interrogation)

Example Interaction

Agent: "What integrations are required?"
User: "We need to connect to a few external services and maybe some APIs."

[FOLLOW-UP REQUIRED: "a few" is vague, "maybe" is weak commitment]

Agent: "You mentioned 'a few external services'. Can you list all the external systems this will integrate with?"
User: "Stripe for payments, SendGrid for email, and our internal user service."

[ANSWER NOW CONCRETE: specific services named]

Agent: "You said 'maybe some APIs'. Are there additional API integrations beyond Stripe, SendGrid, and the user service?"
User: "No, that's all."

[CATEGORY GOAL PROGRESS: Integrations now has concrete list]

Category Checklist (Goal-Driven Coverage)

Each category has concrete "done" criteria. Track completion in the discovery file.

CategoryGoal (Done When)
Core requirementsPrimary workflows enumerated with inputs, outputs, and happy path steps
Users & contextUser roles identified, expertise levels known, access patterns clear
Integrations / boundariesAll external systems named, data flows mapped, API contracts sketched
Edge cases / failuresError handling defined for each workflow step, retry/fallback behavior specified
Quality attributesPerformance targets have numbers (or explicit "not critical"), security requirements stated
Existing patternsRelevant prior art identified OR confirmed none exists, conventions to follow listed
Preferences / constraintsTech stack decided, deployment target known, timeline/resource constraints stated

Tracking Format

Update discovery file with completion status:

## Category Status

| Category | Status | Notes |
|----------|--------|-------|
| Core requirements | ✓ Complete | 3 workflows defined |
| Users & context | ✓ Complete | 2 roles: admin, user |
| Integrations | ⋯ In Progress | DB confirmed, auth TBD |
| Edge cases | ○ Not Started | — |
| Quality attributes | ○ Not Started | — |
| Existing patterns | ✓ Complete | Follow auth module pattern |
| Preferences | ⋯ In Progress | Python confirmed, framework TBD |

Completion Criteria

A category is complete when:

  1. The goal condition is satisfied (see table above)
  2. User has confirmed or provided the information
  3. All answers have passed follow-up validation (no vague quantifiers, no weak commitments, no undefined scope)
  4. No obvious follow-up questions remain for that category
  5. User has explicitly confirmed or the agent has verified understanding

Do NOT mark complete if:

  • User said "I don't know" without a fallback decision
  • Information is vague (e.g., "fast" instead of "<100ms")
  • Dependencies on other categories are unresolved
  • Follow-up validation has not been run on all answers
  • Any answer contains unresolved triggers (vague quantifiers, weak commitments, etc.)

Category Transition Rules

Before moving to a new category:

  1. Summarize what was learned in the current category
  2. Confirm with user: "I've captured X, Y, Z for [category]. Does that cover everything, or is there more?"
  3. Run Stock-Take (see below)
  4. Only then move to the next incomplete category

This prevents the feeling of being "rushed" through categories.

Stock-Taking (Big Picture Synthesis)

Purpose

As questions are answered and categories complete, periodically synthesize the "big picture" - what's emerging, the shape of the vision. This helps users see how their answers are building toward something coherent and provides calibration moments.

Trigger

Stock-take is triggered after each category completes (before transitioning to the next category). This creates a natural rhythm of ~5-7 stock-takes during Phase 2.

Content

A stock-take is NOT a list of answers. It's a synthesis of meaning - what's taking shape:

  1. What we're building (1-2 sentences, evolving as understanding deepens)
  2. Key constraints/boundaries that have emerged from answers
  3. The shape becoming visible (patterns, tensions, tradeoffs surfacing)
  4. Direction check - light confirmation the vision still feels right

Format

**Taking stock** (after {category_name}):

{1-3 sentence synthesis of what's emerging - not a summary of answers, but the picture forming}

{Any notable patterns, tensions, or tradeoffs becoming visible}

Does this still capture where we're heading?

Example

After completing "Integrations" category:

Taking stock (after Integrations):

We're building a CLI skill system where specs drive task decomposition. The emphasis is on preventing incomplete handoffs - every behavior must trace back to stated requirements. The system is self-contained except for Git (for state persistence) and Claude Code (as the execution runtime).

There's tension between thoroughness and workflow friction that keeps surfacing - users want comprehensive specs but not interrogation.

Does this still capture where we're heading?

Tone

  • Reflective, not interrogative
  • Synthesizing, not summarizing
  • Calibrating, not gate-checking

The question at the end is light - "Does this still feel right?" not "Please confirm items 1-7."

Process

After category completion:

  1. Read accumulated state from spec-draft.md (scope), clarify-session.md (discovery so far)
  2. Synthesize the emerging picture (not regurgitate answers)
  3. Present the stock-take to user
  4. Listen for any course correction or "that's not quite right"
  5. Append to $TARGET_DIR/.tasker/stock-takes.md
  6. Update state.json with stock_takes_count

Stock-Takes File Format

Append each stock-take to $TARGET_DIR/.tasker/stock-takes.md:

---

## Stock-Take {N} — After {Category Name}
*{timestamp}*

{The synthesis content}

**User response:** {confirmed | adjusted: brief note}

---

State Update

After each stock-take, update state.json:

{
  "clarify": {
    "stock_takes_count": N
  },
  "updated_at": "<timestamp>"
}

When NOT to Stock-Take

  • Early exit: If user says "move on" mid-category, skip stock-take for that category
  • Minor category: If a category yielded very little new information, stock-take can be brief or combined with next
  • User impatience: If user explicitly wants to skip calibration, respect that

AskUserQuestion Format

Primary Questions (Category-Focused)

Use AskUserQuestion with 2-4 questions per iteration, all within the same category:

questions:
  - question: "How should the system handle [specific scenario]?"
    header: "Edge case"  # Keep headers consistent within a round
    options:
      - label: "Option A"
        description: "Description of approach A"
      - label: "Option B"
        description: "Description of approach B"
    multiSelect: false

IMPORTANT: Do NOT mix categories in a single question batch. If you're asking about "Edge cases", all 2-4 questions should be about edge cases.

Follow-up Questions (Single Question)

For follow-ups during the validation sub-loop, ask ONE question at a time:

questions:
  - question: "You mentioned '{user_quote}'. Can you be more specific about X?"
    header: "Clarify"
    options:
      - label: "Specify"
        description: "I'll provide details"
      - label: "Not critical"
        description: "This isn't spec-relevant"
      - label: "Defer"
        description: "Note as open question"
    multiSelect: false

Open-ended Questions

For open-ended questions, use free-form with context:

questions:
  - question: "What integrations are required?"
    header: "Integrations"
    options:
      - label: "REST API"
        description: "Standard HTTP/JSON endpoints"
      - label: "Database direct"
        description: "Direct database access"
      - label: "Message queue"
        description: "Async via queue (Kafka, RabbitMQ, etc.)"
    multiSelect: true

Updating Discovery File AND State (MANDATORY)

After each Q&A round AND its follow-ups are complete:

1. Append to Discovery File

Append to $TARGET_DIR/.tasker/clarify-session.md:

### Round N — [Category Name]

**Questions:**
1. [Question text]
2. [Question text]

**Answers:**
1. [User's answer]
2. [User's answer]

**Follow-ups:**
- Q1 follow-up: "[follow-up question]" → "[user response]"
- Q2: No follow-up needed (answer was specific)

**Requirements Discovered:**
- REQ-NNN: [Req 1]
- REQ-NNN: [Req 2]

**Category Status:** [✓ Complete | ⋯ In Progress | User deferred]

2. Update State (MANDATORY after every round)

Update $TARGET_DIR/.tasker/state.json:

{
  "phase": {
    "step": "round_N_complete"
  },
  "updated_at": "<timestamp>",
  "clarify": {
    "current_category": "<category>",
    "current_round": N+1,
    "categories": {
      "<category>": { "status": "in_progress|complete", "rounds": N }
    },
    "pending_followups": [],
    "requirements_count": <total REQ count>
  }
}

3. Update Category Status Table

Also update the Category Status table at the top of clarify-session.md to reflect current state.

NOTE: Do NOT proceed to next round until both files are updated. This ensures resumability.

Completion Signal

When ALL category goals are met:

  1. Verify all categories show "✓ Complete" in the status table
  2. Confirm no blocking questions remain
  3. Update state.json:
{
  "phase": {
    "current": "clarify",
    "completed": ["initialization", "scope"],
    "step": "complete"
  },
  "updated_at": "<timestamp>",
  "clarify": {
    "status": "complete",
    "completed_at": "<timestamp>",
    "categories": { /* all marked complete */ },
    "requirements_count": <final count>
  }
}
  1. Output:
<promise>CLARIFIED</promise>

If user requests early exit: Accept it, mark incomplete categories in state.json with status: "deferred", and note in discovery file for Phase 3 to flag as assumptions.


Phase 3 — Synthesis (Derived, Not Asked)

Purpose

Derive structured requirements AND capabilities from discovery. No new information introduced here.

This phase produces TWO outputs:

  1. Spec sections (human-readable) - Workflows, invariants, interfaces
  2. Capability map (machine-readable) - For /plan to consume

CRITICAL: State-Driven, Not Context-Driven

On entry to Phase 3:

  1. Read $TARGET_DIR/.tasker/state.json to confirm clarify.status == "complete"
  2. Read $TARGET_DIR/.tasker/clarify-session.md for ALL discovery content
  3. Read $TARGET_DIR/.tasker/spec-draft.md for existing spec sections (Goal, Non-goals, etc.)

DO NOT rely on conversation context for discovery content. Read from files.

Initialize Synthesis State

Update $TARGET_DIR/.tasker/state.json:

{
  "phase": {
    "current": "synthesis",
    "completed": ["initialization", "scope", "clarify"],
    "step": "starting"
  },
  "updated_at": "<timestamp>",
  "synthesis": {
    "status": "in_progress",
    "spec_sections": {
      "workflows": false,
      "invariants": false,
      "interfaces": false,
      "open_questions": false
    },
    "capability_map": {
      "domains_count": 0,
      "capabilities_count": 0,
      "behaviors_count": 0,
      "steel_thread_identified": false
    },
    "fsm": {
      "machines_count": 0,
      "states_count": 0,
      "transitions_count": 0,
      "invariants_validated": false
    }
  }
}

Process

  1. Read $TARGET_DIR/.tasker/clarify-session.md completely
  2. Extract and organize into spec sections (update spec-draft.md after each)
  3. Decompose into capabilities using I.P.S.O.A. taxonomy
  4. Everything must trace to a specific discovery answer

Part A: Spec Sections

Workflows

Numbered steps with variants and failures:

## Workflows

### 1. [Primary Workflow Name]
1. User initiates X
2. System validates Y
3. System performs Z
4. System returns result

**Variants:**
- If [condition], then [alternative flow]

**Failures:**
- If [error], then [error handling]

**Postconditions:**
- [State after completion]

Invariants

Bulleted rules that must ALWAYS hold:

## Invariants
- [Rule that must never be violated]
- [Another invariant]

Interfaces

Only if a boundary exists:

## Interfaces
- [Interface description]

(or "No new/changed interfaces" if none)

Open Questions

Classified by blocking status:

## Open Questions

### Blocking
- [Question that affects workflows/invariants/interfaces]

### Non-blocking
- [Question about internal preferences only]

Part A Output: Update Files (MANDATORY)

After synthesizing each spec section:

1. Append section to $TARGET_DIR/.tasker/spec-draft.md:

## Workflows
[Synthesized workflows content]

## Invariants
[Synthesized invariants content]

## Interfaces
[Synthesized interfaces content]

## Open Questions
[Synthesized open questions content]

2. Update state.json after EACH section:

{
  "synthesis": {
    "spec_sections": {
      "workflows": true,
      "invariants": true,
      "interfaces": false,
      "open_questions": false
    }
  },
  "updated_at": "<timestamp>"
}

Part A.5: Behavior Model Compilation (FSM)

After synthesizing Workflows, Invariants, and Interfaces, compile the Behavior Model (state machine).

Purpose

The FSM serves two purposes:

  1. QA during implementation - Shapes acceptance criteria, enables transition/guard coverage verification
  2. Documentation - Human-readable diagrams for ongoing system understanding

CRITICAL INVARIANT: Canonical Truth

FSM JSON is canonical; Mermaid is generated. /plan and /execute must fail if required transitions and invariants lack coverage evidence.

  • Canonical artifacts: *.states.json, *.transitions.json, index.json
  • Derived artifacts: *.mmd (Mermaid diagrams) - generated ONLY from canonical JSON
  • NEVER manually edit .mmd files - regenerate from JSON using fsm-mermaid.py
  • If Mermaid is ever edited manually, the system loses machine trust

Compilation Steps

  1. Identify Steel Thread Flow: The primary end-to-end workflow
  2. Derive States: Convert workflow steps to business states
    • Initial state from workflow trigger
    • Normal states from step postconditions
    • Success terminal from workflow completion
    • Failure terminals from failure clauses
  3. Derive Transitions: Convert step sequences, variants, and failures
    • Happy path: step N → step N+1
    • Variants: conditional branches with guards
    • Failures: error transitions to failure states
  4. Link Guards to Invariants: Map spec invariants to transition guards
  5. Validate Completeness: Run I1-I6 checks (see below)
  6. Resolve Ambiguity: Use AskUserQuestion for any gaps

Completeness Invariants

The FSM MUST satisfy these invariants:

IDInvariantCheck
I1Steel Thread FSM mandatoryAt least one machine for primary workflow
I2Behavior-firstNo architecture dependencies required
I3CompletenessInitial state, terminals, no dead ends
I4Guard-Invariant linkageEvery guard links to an invariant ID
I5No silent ambiguityVague terms resolved or flagged as Open Questions
I6Precondition reachabilityIf initial transition requires external trigger (e.g., "user invokes X"), the preconditions for that trigger must be specified in the spec

I6 Detailed Check: If the first transition's trigger describes user invocation (e.g., "user runs /command", "user invokes skill"):

  1. Check if spec has "Installation & Activation" section
  2. Verify the activation mechanism makes the trigger possible
  3. If missing, flag as W8 weakness (missing activation requirements)

Example I6 failure:

  • FSM starts: Idle --[user invokes /kx]--> Running
  • Spec has NO section explaining how /kx becomes available
  • I6 FAILS: "Precondition for initial transition 'user invokes /kx' not reachable - no activation mechanism specified"

Complexity Triggers (Splitting Rules)

Create additional machines based on structural heuristics, not just state count:

State Count Triggers:

  • Steel Thread exceeds 12 states → split into domain-level sub-machines
  • Any machine exceeds 20 states → mandatory split

Structural Triggers (split even with fewer states):

  • Divergent user journeys: Two or more distinct journeys that share only an initial prefix, then branch into unrelated flows → separate machines for each journey
  • Unrelated failure clusters: Multiple failure states that handle different categories of errors (e.g., validation errors vs. system errors vs. business rule violations) → group related failures into their own machines
  • Mixed abstraction levels: Machine combines business lifecycle states (e.g., Order: Created → Paid → Shipped) with UI microstates (e.g., Modal: Open → Editing → Validating) → separate business lifecycle from UI state machines
  • Cross-boundary workflows: Workflow that spans multiple bounded contexts or domains → domain-level machine for each context

Hierarchy Guidelines:

  • steel_thread level: Primary end-to-end flow
  • domain level: Sub-flows within a bounded context
  • entity level: Lifecycle states for a specific entity

Ambiguity Resolution

If the compiler detects ambiguous workflow language, use AskUserQuestion:

{
  "question": "The workflow step '{step}' has ambiguous outcome. What business state results?",
  "header": "FSM State",
  "options": [
    {"label": "Define state", "description": "I'll provide the state name"},
    {"label": "Same as previous", "description": "Remains in current state"},
    {"label": "Terminal success", "description": "Workflow completes successfully"},
    {"label": "Terminal failure", "description": "Workflow fails with error"}
  ]
}

FSM Working Files (Written Incrementally)

During synthesis, write FSM drafts to $TARGET_DIR/.tasker/fsm-draft/:

  • index.json - Machine list, hierarchy, primary machine
  • steel-thread.states.json - State definitions (S1, S2, ...)
  • steel-thread.transitions.json - Transition definitions (TR1, TR2, ...)
  • steel-thread.notes.md - Ambiguity resolutions and rationale

Update state.json after each FSM file:

{
  "synthesis": {
    "fsm": {
      "machines_count": 1,
      "states_count": 8,
      "transitions_count": 12,
      "files_written": ["index.json", "steel-thread.states.json"],
      "invariants_validated": false
    }
  },
  "updated_at": "<timestamp>"
}

FSM Final Output Structure

Final FSM artifacts are exported to {TARGET}/docs/state-machines/<slug>/ in Phase 8:

  • index.json - Machine list, hierarchy, primary machine
  • steel-thread.states.json - State definitions (S1, S2, ...)
  • steel-thread.transitions.json - Transition definitions (TR1, TR2, ...)
  • steel-thread.mmd - Mermaid stateDiagram-v2 for visualization (DERIVED from JSON)
  • steel-thread.notes.md - Ambiguity resolutions and rationale

ID Conventions (FSM-specific)

  • Machines: M1, M2, M3...
  • States: S1, S2, S3...
  • Transitions: TR1, TR2, TR3...

Traceability (Spec Provenance - MANDATORY)

Every state and transition MUST have a spec_ref pointing to the specific workflow step, variant, or failure that defined it. This prevents "FSM hallucination" where states/transitions are invented without spec basis.

Required for each state:

  • spec_ref.quote - Verbatim text from the spec that defines this state
  • spec_ref.location - Section reference (e.g., "Workflow 1, Step 3")

Required for each transition:

  • spec_ref.quote - Verbatim text from the spec that defines this transition
  • spec_ref.location - Section reference (e.g., "Workflow 1, Variant 2")

If no spec text exists for an element:

  1. The element should NOT be created (likely FSM hallucination)
  2. Or, use AskUserQuestion to get clarification and document the decision

Part B: Capability Extraction

Extract capabilities from the synthesized workflows using I.P.S.O.A. decomposition.

I.P.S.O.A. Behavior Taxonomy

For each capability, identify behaviors by type:

TypeDescriptionExamples
InputValidation, parsing, authenticationValidate email format, parse JSON body
ProcessCalculations, decisions, transformationsCalculate total, apply discount rules
StateDatabase reads/writes, cache operationsSave order, fetch user profile
OutputResponses, events, notificationsReturn JSON, emit event, send email
ActivationRegistration, installation, deploymentRegister skill, deploy endpoint, write config

Activation Behaviors

If the spec describes user invocation (e.g., "user runs /command"), extract activation behaviors:

  • Registration: Skill/plugin registration with runtime
  • Installation: CLI or package installation steps
  • Deployment: API endpoint or service deployment
  • Configuration: Config files or environment setup

Missing activation = coverage gap. If spec says "user invokes X" but doesn't specify how X becomes available, add to coverage.gaps.

Domain Grouping

Group related capabilities into domains:

  • Authentication - Login, logout, session management
  • User Management - Profile, preferences, settings
  • Core Feature - The primary business capability
  • etc.

Steel Thread Identification

Identify the steel thread - the minimal end-to-end flow that proves the system works:

  • Mark one flow as is_steel_thread: true
  • This becomes the critical path for Phase 1 implementation

Capability Map Working File

During synthesis, write capability map draft to $TARGET_DIR/.tasker/capability-map-draft.json.

Update state.json as you build the map:

{
  "synthesis": {
    "capability_map": {
      "domains_count": 3,
      "capabilities_count": 8,
      "behaviors_count": 24,
      "steel_thread_identified": true,
      "draft_written": true
    }
  },
  "updated_at": "<timestamp>"
}

Capability Map Final Output

In Phase 8, write final to {TARGET}/docs/specs/<slug>.capabilities.json:

{
  "version": "1.0",
  "spec_checksum": "<first 16 chars of SHA256 of spec>",

  "domains": [
    {
      "id": "D1",
      "name": "Authentication",
      "description": "User identity and access",
      "capabilities": [
        {
          "id": "C1",
          "name": "User Login",
          "discovery_ref": "Round 3, Q2: User confirmed email/password auth",
          "behaviors": [
            {"id": "B1", "name": "ValidateCredentials", "type": "input", "description": "Check email/password format"},
            {"id": "B2", "name": "VerifyPassword", "type": "process", "description": "Compare hash"},
            {"id": "B3", "name": "CreateSession", "type": "state", "description": "Store session"},
            {"id": "B4", "name": "ReturnToken", "type": "output", "description": "JWT response"}
          ]
        }
      ]
    }
  ],

  "flows": [
    {
      "id": "F1",
      "name": "Login Flow",
      "is_steel_thread": true,
      "steps": [
        {"order": 1, "behavior_id": "B1", "description": "Validate input"},
        {"order": 2, "behavior_id": "B2", "description": "Check password"},
        {"order": 3, "behavior_id": "B3", "description": "Create session"},
        {"order": 4, "behavior_id": "B4", "description": "Return JWT"}
      ]
    }
  ],

  "invariants": [
    {"id": "I1", "description": "Passwords must never be logged", "discovery_ref": "Round 5, Q1"}
  ],

  "coverage": {
    "total_requirements": 15,
    "covered_requirements": 15,
    "gaps": []
  }
}

ID Conventions

  • Domains: D1, D2, D3...
  • Capabilities: C1, C2, C3...
  • Behaviors: B1, B2, B3...
  • Flows: F1, F2, F3...
  • Invariants: I1, I2, I3...

Traceability

Every capability and invariant MUST have a discovery_ref pointing to the specific round and question in $TARGET_DIR/.tasker/clarify-session.md that established it.

Synthesis Complete: Update State

After all synthesis outputs are complete, update state.json:

{
  "phase": {
    "current": "synthesis",
    "completed": ["initialization", "scope", "clarify"],
    "step": "complete"
  },
  "updated_at": "<timestamp>",
  "synthesis": {
    "status": "complete",
    "completed_at": "<timestamp>",
    "spec_sections": { "workflows": true, "invariants": true, "interfaces": true, "open_questions": true },
    "capability_map": { "domains_count": N, "capabilities_count": N, "behaviors_count": N, "steel_thread_identified": true, "draft_written": true },
    "fsm": { "machines_count": N, "states_count": N, "transitions_count": N, "invariants_validated": true }
  }
}

CRITICAL: Resume From Synthesis

On resume (after compaction or restart):

  1. Read $TARGET_DIR/.tasker/state.json to get synthesis state
  2. If synthesis.spec_sections shows incomplete sections, read spec-draft.md and continue
  3. If synthesis.capability_map.draft_written is false, continue building from capability-map-draft.json
  4. If synthesis.fsm.invariants_validated is false, continue FSM work from fsm-draft/

Phase 4 — Architecture Sketch

Rule

Architecture MUST come AFTER workflows, invariants, interfaces.

Initialize Architecture State

Update $TARGET_DIR/.tasker/state.json:

{
  "phase": {
    "current": "architecture",
    "completed": ["initialization", "scope", "clarify", "synthesis"],
    "step": "starting"
  },
  "updated_at": "<timestamp>",
  "architecture": {
    "status": "in_progress",
    "user_provided": false,
    "agent_proposed": false
  }
}

CRITICAL: Read Prior State

On entry:

  1. Read $TARGET_DIR/.tasker/spec-draft.md to understand synthesized workflows
  2. Architecture sketch should align with the workflows defined

Process

Use AskUserQuestion to either:

Option A: Ask for sketch

questions:
  - question: "Can you provide a brief architecture sketch for this feature?"
    header: "Architecture"
    options:
      - label: "I'll describe it"
        description: "User provides architecture overview"
      - label: "Propose one"
        description: "Agent proposes architecture for review"

Option B: Propose and confirm Present a brief sketch and ask for confirmation/edits.

Output

1. Update spec-draft.md

Append Architecture sketch section to $TARGET_DIR/.tasker/spec-draft.md:

## Architecture sketch
- **Components touched:** [list]
- **Responsibilities:** [brief description]
- **Failure handling:** [brief description]

Keep this SHORT. No essays.

2. Update State

Update $TARGET_DIR/.tasker/state.json:

{
  "phase": {
    "step": "complete"
  },
  "updated_at": "<timestamp>",
  "architecture": {
    "status": "complete",
    "completed_at": "<timestamp>",
    "user_provided": true|false,
    "agent_proposed": true|false
  }
}

Phase 5 — Decisions & ADRs

Initialize Decisions State

Update $TARGET_DIR/.tasker/state.json:

{
  "phase": {
    "current": "decisions",
    "completed": ["initialization", "scope", "clarify", "synthesis", "architecture"],
    "step": "starting"
  },
  "updated_at": "<timestamp>",
  "decisions": {
    "status": "in_progress",
    "count": 0,
    "pending": 0
  }
}

CRITICAL: Read Prior State

On entry:

  1. Read $TARGET_DIR/.tasker/spec-draft.md to identify decision points from workflows/invariants
  2. Read $TARGET_DIR/.tasker/clarify-session.md for context on requirements

ADR Trigger

Create ADR if ANY of these are true:

  • Hard to reverse
  • Reusable standard
  • Tradeoff-heavy
  • Cross-cutting
  • NFR-impacting

If none apply → record decision in spec only.

Decision Facilitation Rules

FACILITATE a decision ONLY IF ALL are true:

  1. ADR-worthy (meets trigger above)
  2. Not already decided (no existing ADR, no explicit user preference)
  3. Blocking workflows, invariants, or interfaces

DO NOT FACILITATE if ANY are true:

  • Already decided
  • Local / reversible / implementation detail
  • Non-blocking
  • User not ready to decide
  • Too many options (>3)
  • Premature (behavior not defined yet)

Facilitation Format

If facilitation is allowed:

questions:
  - question: "How should we approach [decision topic]?"
    header: "Decision"
    options:
      - label: "Option A: [Name]"
        description: "Consequences: [1], [2]"
      - label: "Option B: [Name]"
        description: "Consequences: [1], [2]"
      - label: "Need more info"
        description: "Defer decision, add to Open Questions"

Outcomes

  • User chooses option → Write decision to spec-draft.md + create ADR (Accepted)
  • User says "need more info" → Add as Blocking Open Question (no ADR yet)

Update state.json after each decision:

{
  "decisions": {
    "count": 2,
    "pending": 1
  },
  "updated_at": "<timestamp>"
}

Decision Registry

Write decision index to $TARGET_DIR/.tasker/decisions.json:

{
  "decisions": [
    { "id": "DEC-001", "title": "Authentication method", "adr": "ADR-0001-auth-method.md" },
    { "id": "DEC-002", "title": "Database choice", "adr": "ADR-0002-database-choice.md" },
    { "id": "DEC-003", "title": "Error handling strategy", "adr": null }
  ]
}
  • adr is the filename if ADR-worthy, null if inline decision only
  • ADR files contain full decision context and rationale

Usage pattern: Always consult decisions.json first to find relevant decisions by title. Only read a specific ADR file when you need the full details. Never scan adrs-draft/ directory to discover what decisions exist.

ADR Working Files

Write ADR drafts to $TARGET_DIR/.tasker/adrs-draft/:

  • ADR-0001-auth-method.md
  • ADR-0002-database-choice.md

Final ADRs are exported to {TARGET}/docs/adrs/ in Phase 8.

ADR Template

Write ADRs to {TARGET}/docs/adrs/ADR-####-<slug>.md:

# ADR-####: {Title}

**Status:** Accepted
**Date:** {YYYY-MM-DD}

## Applies To
- [Spec: Feature A](../specs/feature-a.md)
- [Spec: Feature B](../specs/feature-b.md)

## Context
[Why this decision was needed - reference specific discovery round if applicable]

## Decision
[What was decided]

## Alternatives Considered
| Alternative | Pros | Cons | Why Not Chosen |
|-------------|------|------|----------------|
| [Alt 1] | ... | ... | ... |
| [Alt 2] | ... | ... | ... |

## Consequences
- [Consequence 1]
- [Consequence 2]

## Related
- Supersedes: (none | ADR-XXXX)
- Related ADRs: (none | ADR-XXXX, ADR-YYYY)

ADR Rules:

  • ADRs are immutable once Accepted
  • Changes require a new ADR that supersedes the old
  • ADRs can apply to multiple specs (many-to-many relationship)
  • When creating a new spec that uses an existing ADR, update the ADR's "Applies To" section

Decisions Complete: Update State

After all decisions are resolved, update state.json:

{
  "phase": {
    "step": "complete"
  },
  "updated_at": "<timestamp>",
  "decisions": {
    "status": "complete",
    "completed_at": "<timestamp>",
    "count": 3,
    "pending": 0
  }
}

Also append Decisions section to $TARGET_DIR/.tasker/spec-draft.md.


Phase 6 — Handoff-Ready Gate

CRITICAL: State-Driven Gate Check

On entry to Phase 6:

  1. Read $TARGET_DIR/.tasker/state.json to verify all prior phases complete
  2. Read $TARGET_DIR/.tasker/spec-draft.md to verify all sections exist
  3. Read $TARGET_DIR/.tasker/fsm-draft/ to verify FSM compiled
  4. Read $TARGET_DIR/.tasker/capability-map-draft.json to verify capability map exists

DO NOT rely on conversation context. All gate checks use persisted files.

Update state.json:

{
  "phase": {
    "current": "gate",
    "completed": ["initialization", "scope", "clarify", "synthesis", "architecture", "decisions"],
    "step": "checking"
  },
  "updated_at": "<timestamp>"
}

Preliminary Check (ALL must pass)

CheckRequirementVerify By
Phases completeAll phases 1-5 completed in orderstate.json phase.completed array
No blocking questionsZero Blocking Open Questionsspec-draft.md Open Questions section
Interfaces presentInterfaces section exists (even if "none")spec-draft.md
Decisions presentDecisions section existsspec-draft.md
Workflows definedAt least one workflow with variants/failuresspec-draft.md
Invariants statedAt least one invariantspec-draft.md
FSM compiledSteel Thread FSM compiled with I1-I6 passingfsm-draft/index.json

Spec Completeness Check (Checklist C1-C11)

Run the checklist verification against the current spec draft:

tasker spec checklist /tmp/claude/spec-draft.md

This verifies the spec contains all expected sections:

CategoryCritical Items (must pass)
C2: Data ModelTables defined, fields typed, constraints stated
C3: APIEndpoints listed, request/response schemas, auth requirements
C4: BehaviorObservable behaviors, business rules
C7: SecurityAuthentication mechanism, authorization rules

Handling Checklist Gaps

For critical missing items (marked with *):

  1. If the spec SHOULD have this content → return to Phase 2 (Clarify) to gather requirements
  2. If the spec legitimately doesn't need this → document as N/A with rationale

Example checklist failure:

## Gate FAILED - Incomplete Spec

Checklist verification found critical gaps:

- [✗] C2.4*: Constraints stated (UNIQUE, CHECK, FK)?
  → Data model section exists but no constraints defined

- [✗] C3.2*: Request schemas defined?
  → API endpoints listed but request bodies not specified

Action: Return to Phase 2 to clarify data constraints and API request formats.

Gate Result: Update State

If Gate PASSES:

{
  "phase": {
    "current": "gate",
    "step": "passed"
  },
  "updated_at": "<timestamp>"
}

If Gate FAILS:

Update state.json with blockers:

{
  "phase": {
    "current": "gate",
    "step": "failed"
  },
  "updated_at": "<timestamp>",
  "gate_blockers": [
    { "type": "blocking_question", "detail": "Rate limiting across tenants" },
    { "type": "missing_section", "detail": "Interfaces" },
    { "type": "checklist_gap", "detail": "C2.4: No database constraints" }
  ]
}
  1. List exact blockers
  2. STOP - do not proceed to spec review
  3. Tell user what must be resolved

Example:

## Gate FAILED

Cannot proceed. The following must be resolved:

1. **Blocking Open Questions:**
   - How should rate limiting work across tenants?
   - What is the retry policy for failed webhooks?

2. **Missing Sections:**
   - Interfaces section not present

3. **Checklist Gaps (Critical):**
   - C2.4: No database constraints defined
   - C3.2: API request schemas missing

Phase 7 — Spec Review (MANDATORY)

Purpose

Run automated weakness detection to catch issues before export. This is the final quality gate.

Initialize Review State

Update $TARGET_DIR/.tasker/state.json:

{
  "phase": {
    "current": "review",
    "completed": ["initialization", "scope", "clarify", "synthesis", "architecture", "decisions", "gate"],
    "step": "starting"
  },
  "updated_at": "<timestamp>",
  "review": {
    "status": "in_progress",
    "weaknesses_found": 0,
    "weaknesses_resolved": 0,
    "critical_remaining": 0
  }
}

CRITICAL: Read From Files

On entry to Phase 7:

  1. The spec draft is already in $TARGET_DIR/.tasker/spec-draft.md - use this file
  2. Do NOT build spec from conversation context

Process

Step 1: Copy Spec Draft for Analysis

The spec draft already exists at $TARGET_DIR/.tasker/spec-draft.md. Copy to temp for analysis:

cp "$TARGET_DIR/.tasker/spec-draft.md" /tmp/claude/spec-draft.md

Step 2: Run Weakness Detection

tasker spec review /tmp/claude/spec-draft.md

This detects:

  • W1: Non-behavioral requirements - DDL/schema not stated as behavior
  • W2: Implicit requirements - Constraints assumed but not explicit
  • W3: Cross-cutting concerns - Config, observability, lifecycle
  • W4: Missing acceptance criteria - Qualitative terms without metrics
  • W5: Fragmented requirements - Cross-references needing consolidation
  • W6: Contradictions - Conflicting statements
  • W7: Ambiguity - Vague quantifiers, undefined scope, weak requirements, passive voice
  • W8: Missing activation requirements - Spec describes invocation without specifying how to make it invocable (e.g., "user runs /command" without defining how the command becomes available)
  • CK-*: Checklist gaps - Critical missing content from C1-C11 categories

W7 Ambiguity patterns include:

  • Vague quantifiers ("some", "many", "several")
  • Undefined scope ("etc.", "and so on")
  • Vague conditionals ("if applicable", "when appropriate")
  • Weak requirements ("may", "might", "could")
  • Passive voice hiding actor ("is handled", "will be processed")
  • Vague timing ("quickly", "soon", "eventually")
  • Subjective qualifiers ("reasonable", "appropriate")
  • Unquantified limits ("large", "fast", "slow")

Step 3: Handle Critical Weaknesses

For CRITICAL weaknesses (W1, W6, W7 with weak requirements), engage user:

W1: Non-Behavioral Requirements
{
  "question": "The spec contains DDL/schema that isn't stated as behavioral requirement: '{spec_quote}'. How should this be treated?",
  "header": "DDL Mandate",
  "options": [
    {"label": "DB-level required", "description": "MUST be implemented as database-level constraint"},
    {"label": "App-layer OK", "description": "Application-layer validation is sufficient"},
    {"label": "Documentation only", "description": "This is reference documentation, not a requirement"}
  ]
}
W6: Contradictions
{
  "question": "Conflicting statements found: {description}. Which is authoritative?",
  "header": "Conflict",
  "options": [
    {"label": "First statement", "description": "{first_quote}"},
    {"label": "Second statement", "description": "{second_quote}"},
    {"label": "Clarify", "description": "I'll provide clarification"}
  ]
}
W7: Ambiguity

Each W7 weakness includes a clarifying question. Use AskUserQuestion with the auto-generated question:

{
  "question": "{weakness.question or weakness.suggested_resolution}",
  "header": "Clarify",
  "options": [
    {"label": "Specify value", "description": "I'll provide a specific value/definition"},
    {"label": "Not required", "description": "This is not a hard requirement"},
    {"label": "Use default", "description": "Use a sensible default"}
  ]
}

Example clarifying questions by ambiguity type:

  • Vague quantifier: "How many specifically? Provide a number or range."
  • Weak requirement: "Is this required or optional? If optional, under what conditions?"
  • Vague timing: "What is the specific timing? (e.g., <100ms, every 5 minutes)"
  • Passive voice: "What component/system performs this action?"
W8: Missing Activation Requirements

Detected when the spec describes invocation (e.g., "user runs /command", "user invokes the skill") without specifying how that invocation becomes possible.

{
  "question": "The spec describes '{invocation_description}' but doesn't specify how this becomes invocable. What makes this available to users?",
  "header": "Activation",
  "options": [
    {"label": "Registration required", "description": "I'll specify what registration/installation is needed"},
    {"label": "Built-in", "description": "This is provided by the runtime environment (document which)"},
    {"label": "Documentation only", "description": "Activation is out of scope - add to Non-goals"}
  ]
}

W8 patterns to detect:

  • "User invokes X" or "User runs X" without installation/registration steps
  • Entry points described without activation mechanism
  • Commands or APIs referenced without deployment/registration
  • Skills or plugins described without installation instructions

If user selects "Registration required", follow up:

{
  "question": "What specific steps or files are needed to make '{invocation}' available?",
  "header": "Activation Steps",
  "options": [
    {"label": "Config file", "description": "A configuration file registers this (specify format/location)"},
    {"label": "CLI install", "description": "A CLI command installs this (specify command)"},
    {"label": "Auto-discovery", "description": "The runtime auto-discovers this (specify convention)"},
    {"label": "Manual setup", "description": "Manual steps are required (I'll document them)"}
  ]
}
CK-*: Checklist Gaps

For critical checklist gaps that weren't caught in Phase 6 Gate:

{
  "question": "The spec is missing {checklist_item}. Should this be added?",
  "header": "Missing Content",
  "options": [
    {"label": "Add it", "description": "I'll provide the missing information"},
    {"label": "N/A", "description": "This spec doesn't need this (document why)"},
    {"label": "Defer", "description": "Address in a follow-up spec"}
  ]
}

Step 4: Record and Apply Resolutions

For each resolved weakness:


View the full specify on GitHub

Commands 3

Execute

Execute tasks from a completed plan using isolated subagents.

IMPORTANT: Follow the instructions in the tasker:execute skill directly. Do NOT invoke any other skill.

The execute workflow:

  1. Asks for the target project directory
  2. Verifies planning is complete
  3. Runs task-executor subagents for each ready task
  4. Handles checkpointing and crash recovery

Plan

Decompose a specification into an executable task DAG.

IMPORTANT: Follow the instructions in the tasker:plan skill directly. Do NOT invoke any other skill.

The plan workflow guides you through:

  1. Asking for the target project directory
  2. Detecting specs from /specify workflow
  3. Running planning agents (physical-architect, task-author, task-plan-verifier, plan-auditor)
  4. Producing a task DAG ready for /execute

Use the tasker:specify skill to run the interactive specification workflow.

Agents 8

Logic Architect (v2)

Extract capabilities from specification and decompose into behaviors.

Relationship with /specify

Preferred workflow: Use /specify to develop specs interactively. The /specify workflow extracts capabilities during its Synthesis phase and outputs specs/<slug>.capabilities.json.

When this agent runs:

  • If spec came from /specify → This agent is skipped (capability map already exists)
  • If spec is raw/external → This agent runs to extract capabilities

The /plan orchestrator checks for existing capability maps and skips this agent when found.


MANDATORY FIRST ACTION - DO THIS IMMEDIATELY

Before reading the spec, before any analysis, your FIRST tool call MUST be Write.

Write this placeholder to {TASKER_DIR}/artifacts/capability-map.json:

{"version": "1.0", "status": "in_progress", "domains": [], "flows": [], "coverage": {"total_requirements": 0, "covered_requirements": 0, "gaps": []}}

WHY: Outputting JSON to this conversation does NOT create a file. Only the Write tool creates files. If you skip this step, you WILL fail.

After writing the placeholder, verify it exists:

ls -la {TASKER_DIR}/artifacts/capability-map.json

Only proceed to analysis after confirming the file exists.


Output Contract

You MUST write valid JSON to {TASKER_DIR}/artifacts/capability-map.json.

The JSON MUST validate against schemas/capability-map.schema.json.

Workflow (MANDATORY order):

  1. WRITE PLACEHOLDER (your first action - see above)
  2. READ the spec from {TASKER_DIR}/inputs/spec.md
  3. ANALYZE using I.P.S.O. decomposition (see below)
  4. OVERWRITE the file with your complete analysis using the Write tool
  5. VALIDATE: cd {TASKER_DIR}/.. && tasker state validate capability_map
  6. If validation fails: Fix the JSON, Write again, re-validate

Note: The orchestrator has already created all required directories. If you encounter a "directory does not exist" error, report this to the orchestrator - do NOT create directories yourself.


Input

From Orchestrator Spawn Prompt: You will receive context including:

  • TASKER_DIR - Absolute path to .tasker directory (e.g., /Users/foo/my-project/.tasker)
  • Target directory (where code will be written)
  • Project type (new or existing)
  • Tech stack constraints (if any)
  • Existing project analysis (if enhancing an existing codebase)

From File: Read {TASKER_DIR}/inputs/spec.md

Important: The spec may be in any format (freeform, PRD, bullet list, etc.). Do not expect structured sections. Extract requirements from whatever format is provided.

Phase Filtering (Critical)

The spec may contain content for multiple development phases. You MUST only extract capabilities for Phase 1.

Phase Detection Rules

  1. Implicit Phase 1: Any content NOT under a "Phase N" heading is Phase 1
  2. Explicit Phase 2+: Content under headings like "Phase 2", "Phase 3", "## Phase 2", "### Future Phase", etc.

Examples of Phase Markers to EXCLUDE

## Phase 2
## Phase 2: Advanced Features
### Phase 3 - Future Work
# Phase 2 Requirements
**Phase 2:**

What to Do

  1. Scan the spec for phase markers before extracting capabilities
  2. Identify sections that belong to Phase 2 or later
  3. Skip all content under Phase 2+ headings
  4. Document excluded phases in the phase_filtering section of output

Phase Filtering Output

Add a phase_filtering section to your output:

{
  "phase_filtering": {
    "active_phase": 1,
    "excluded_phases": [
      {
        "phase": 2,
        "heading": "## Phase 2: Advanced Features",
        "location": "line 145",
        "summary": "OAuth integration, SSO, admin dashboard"
      }
    ],
    "total_excluded_requirements": 8
  }
}

If no phase markers are found, output:

{
  "phase_filtering": {
    "active_phase": 1,
    "excluded_phases": [],
    "total_excluded_requirements": 0
  }
}

I.P.S.O.A. Decomposition (Behavior Taxonomy)

For each capability, identify behaviors:

  • Input: Validation, parsing, authentication
  • Process: Calculations, decisions, transformations
  • State: Database reads/writes, cache operations
  • Output: Responses, events, notifications
  • Activation: Registration, installation, deployment, configuration that makes the system invocable

Activation Behaviors (CRITICAL for Entry Points)

If the spec describes user invocation (e.g., "user runs /command"), you MUST extract activation behaviors:

Activation TypeExample Behaviors
Skill registrationRegisterSkill, ConfigureSkillTrigger
CLI installationInstallCommand, RegisterCommandAlias
API deploymentDeployEndpoint, RegisterRoute
Plugin loadingLoadPlugin, InitializePlugin
ConfigurationWriteConfigFile, SetEnvironmentVariable

If spec lacks activation details but describes invocation: Flag as coverage gap. The capability map's coverage.gaps should include: "Missing activation mechanism for [invocation description]"

Output Structure

{
  "version": "1.0",
  "spec_checksum": "<first 16 chars of SHA256 of spec.md>",

  "domains": [
    {
      "id": "D1",
      "name": "Authentication",
      "description": "User identity and access",
      "capabilities": [
        {
          "id": "C1",
          "name": "User Login",
          "spec_ref": {
            "quote": "Users must be able to log in with email and password",
            "location": "paragraph 3"
          },
          "behaviors": [
            {"id": "B1", "name": "ValidateCredentials", "type": "input", "description": "Check email/password format"},
            {"id": "B2", "name": "VerifyPassword", "type": "process", "description": "Compare hash"},
            {"id": "B3", "name": "CreateSession", "type": "state", "description": "Store session in Redis"},
            {"id": "B4", "name": "ReturnToken", "type": "output", "description": "JWT response"}
          ]
        }
      ]
    },
    {
      "id": "D2",
      "name": "System Bootstrap",
      "description": "Installation and activation",
      "capabilities": [
        {
          "id": "C2",
          "name": "Skill Registration",
          "spec_ref": {
            "quote": "User invokes /myskill to start the workflow",
            "location": "Entry Point section"
          },
          "behaviors": [
            {"id": "B5", "name": "CreateSkillConfig", "type": "activation", "description": "Write skill definition to .claude/settings.local.json"},
            {"id": "B6", "name": "RegisterTrigger", "type": "activation", "description": "Configure /myskill as command trigger"}
          ]
        }
      ]
    }
  ],

  "flows": [
    {
      "id": "F1",
      "name": "Login Flow",
      "is_steel_thread": true,
      "steps": [
        {"order": 1, "behavior_id": "B1", "description": "Validate input"},
        {"order": 2, "behavior_id": "B2", "description": "Check password"},
        {"order": 3, "behavior_id": "B3", "description": "Create session"},
        {"order": 4, "behavior_id": "B4", "description": "Return JWT"}
      ]
    }
  ],

  "coverage": {
    "total_requirements": 15,
    "covered_requirements": 15,
    "gaps": []
  }
}

Spec Reference Format

The spec_ref field supports content-based traceability for any spec format:

"spec_ref": {
  "quote": "exact text from spec that defines this requirement",
  "location": "optional: line number, paragraph, bullet point, etc."
}

Examples:

// For a structured doc
{"quote": "The system shall authenticate users via OAuth2", "location": "Section 3.1"}

// For a bullet list
{"quote": "- user login with email/password", "location": "line 15"}

// For freeform prose
{"quote": "we need users to be able to sign in", "location": "paragraph 2"}

// For meeting notes
{"quote": "John said auth is critical for MVP", "location": "near end"}

The quote provides 100% traceability - it IS the spec content. The location is best-effort.

ID Conventions

  • Domains: D1, D2, D3...
  • Capabilities: C1, C2, C3...
  • Behaviors: B1, B2, B3...
  • Flows: F1, F2, F3...

Final Checklist

STOP. Before declaring done, verify ALL of these:

File Existence (CRITICAL)

  • Placeholder was written as FIRST action
  • Final JSON was written using Write tool to {TASKER_DIR}/artifacts/capability-map.json
  • File exists: ls -la {TASKER_DIR}/artifacts/capability-map.json shows the file
  • Validation passes: cd {TASKER_DIR}/.. && tasker state validate capability_map

Content Quality

  • Phase markers identified and Phase 2+ content excluded
  • phase_filtering section documents any excluded phases
  • Every Phase 1 spec requirement maps to behaviors
  • Every capability has a spec_ref with a quoted snippet from the spec
  • Every behavior has correct type (input/process/state/output)
  • Steel thread flow identified
  • Coverage gaps documented (Phase 1 only)

If ls shows "No such file", you have NOT written the file. Use the Write tool NOW.

Physical Architect (v2)

Map behaviors to concrete file paths.

Output Contract

You MUST write valid JSON to {TASKER_DIR}/artifacts/physical-map.json.

**CRITICAL - YOUR TASK IS NOT COMPLETE UNTIL YOU DO ALL OF THESE:

  1. You MUST use the Write tool to save the file. Do NOT just output JSON to the conversation.
  2. You MUST use the TASKER_DIR absolute path provided in the spawn context. Do NOT use relative paths like .tasker/.
  3. You MUST verify the file exists after writing by running: ls -la {TASKER_DIR}/artifacts/physical-map.json
  4. You MUST run validation: cd {TASKER_DIR}/.. && tasker state validate physical_map

If the file doesn't exist after Write, you have FAILED. Try again.**

Required Steps (in order):

  1. Write the file using the Write tool to {TASKER_DIR}/artifacts/physical-map.json

    Note: The orchestrator has already created all required directories. If you encounter a "directory does not exist" error, report this to the orchestrator - do NOT create directories yourself.

  2. Validate the output:

    cd {TASKER_DIR}/.. && tasker state validate physical_map
    
  3. If validation fails: Read the error, fix the JSON, write again, re-validate

Input

From Orchestrator Spawn Prompt: You will receive context including:

  • TASKER_DIR - Absolute path to .tasker directory (e.g., /Users/foo/my-project/.tasker)
  • Target directory (where code will be written)
  • Project type (new or existing)
  • Tech stack constraints (if any)
  • Existing project analysis (if enhancing an existing codebase)
  • Key patterns to follow (if existing project)

From Files:

  • {TASKER_DIR}/artifacts/capability-map.json
  • {TASKER_DIR}/inputs/constraints.md (if exists)

Phase Filtering (Critical)

The capability-map includes a phase_filtering section that documents which phases were excluded from planning. You MUST:

  1. Check the phase_filtering section in capability-map.json
  2. Only map behaviors that are included in the capability-map (Phase 1 only)
  3. Propagate phase info to your output for downstream verification

Phase Filtering Output

Include phase filtering metadata in your output:

{
  "phase_filtering": {
    "active_phase": 1,
    "source": "capability-map.json",
    "behaviors_mapped": 15,
    "note": "Only Phase 1 behaviors mapped per capability-map phase_filtering"
  }
}

Important: Do NOT add behaviors that don't exist in the capability-map. The logic-architect has already filtered to Phase 1 only.

Output Structure

{
  "version": "1.0",
  "target_dir": "/path/to/target",
  "capability_map_checksum": "<for change detection>",
  
  "file_mapping": [
    {
      "behavior_id": "B1",
      "behavior_name": "ValidateCredentials",
      "files": [
        {
          "path": "src/auth/validator.py",
          "action": "create",
          "layer": "domain",
          "purpose": "Credential validation logic"
        }
      ],
      "tests": [
        {
          "path": "tests/auth/test_validator.py",
          "action": "create"
        }
      ]
    }
  ],
  
  "cross_cutting": [
    {
      "concern": "logging",
      "files": [
        {"path": "src/core/logging.py", "action": "create", "purpose": "Structured logger setup"}
      ]
    },
    {
      "concern": "auth_middleware",
      "files": [
        {"path": "src/middleware/auth.py", "action": "create", "purpose": "JWT validation"}
      ]
    }
  ],
  
  "infrastructure": [
    {"path": "Dockerfile", "action": "create", "purpose": "Container build"},
    {"path": ".github/workflows/ci.yml", "action": "create", "purpose": "CI pipeline"}
  ],
  
  "summary": {
    "total_behaviors": 15,
    "total_files": 32,
    "files_to_create": 28,
    "files_to_modify": 4
  }
}

Layer Classification

  • api - Controllers, routes, handlers
  • domain - Services, business logic
  • data - Repositories, migrations, models
  • infra - Config, logging, middleware

Cross-Cutting Injection

Add files for:

  • Logging/observability
  • Authentication middleware
  • Error handling
  • Health checks
  • Configuration management

Checklist

Before declaring done:

  • Verified capability-map phase_filtering section
  • Only Phase 1 behaviors from capability-map are mapped
  • phase_filtering metadata included in output
  • Every behavior has file mapping
  • Every file has layer classification
  • Test files for all domain/api files
  • Cross-cutting concerns added
  • Infrastructure files added
  • File written using Write tool to {TASKER_DIR}/artifacts/physical-map.json (absolute path!)
  • JSON validates: cd {TASKER_DIR}/.. && tasker state validate physical_map

Plan Auditor (v2)

Sequence tasks into phases and validate the dependency graph.

Input

You receive from orchestrator:

TASKER_DIR: {absolute path to .tasker directory, e.g., /Users/foo/my-project/.tasker}

CRITICAL: Use the TASKER_DIR absolute path provided. Do NOT use relative paths like .tasker/.

Files to read (using absolute paths):

  • {TASKER_DIR}/tasks/*.json - Individual task files
  • {TASKER_DIR}/artifacts/capability-map.json - For steel thread flows

Process

1. Build Dependency Graph

# Load all tasks (use absolute TASKER_DIR path)
for task in {TASKER_DIR}/tasks/*.json; do
  # Extract id, dependencies
done

# Verify no cycles (topological sort possible)

2. Identify Steel Thread

From capability-map.json flows where is_steel_thread: true:

  • Mark those tasks with "steel_thread": true in context
  • These get phase 2 priority

3. Assign Phases

Phase 1: Foundations

  • Tasks with no dependencies
  • Infrastructure setup
  • Base types/interfaces

Phase 2: Steel Thread

  • Minimum viable path
  • Must touch all layers

Phase 3+: Features

  • Remaining tasks grouped by:
    • Domain affinity
    • Dependency chains

4. Update Task Files

CRITICAL: You must update the task files using the Write tool or jq. Do NOT just output JSON to the conversation.

For each task, update the phase field. Two approaches:

Option A: Using Write tool (preferred)

  1. Read the task file
  2. Update the phase in memory
  3. Write the full JSON back using the Write tool to {TASKER_DIR}/tasks/T001.json (absolute path!)

Option B: Using jq (shell)

# Read task, update phase, write back (use absolute TASKER_DIR path)
jq '.phase = 2' {TASKER_DIR}/tasks/T001.json > /tmp/T001.json && \
  mv /tmp/T001.json {TASKER_DIR}/tasks/T001.json

Verify each update:

cat {TASKER_DIR}/tasks/T001.json | jq '.phase'

5. Validate

  • No circular dependencies
  • All dependencies in earlier phases
  • Steel thread is contiguous

Output

Update existing task files with:

  • Correct phase assignment
  • steel_thread flag in context

Create summary:

echo "Phase assignments complete"
cd {TASKER_DIR}/.. && tasker state load-tasks  # Reload with new phases

Checklist

Before declaring done:

  • All tasks have phase assigned
  • Task files updated using Write tool or jq to {TASKER_DIR}/tasks/ (absolute paths!)
  • No circular dependencies
  • Steel thread tasks identified
  • Backward pass validates (deps in earlier phases)
  • Run: cd {TASKER_DIR}/.. && tasker state load-tasks (verify success)

Spec Reviewer (Phase 7 of /specify)

Analyze specification for weakness categories before export. Persist weaknesses and engage user for resolution.

Integration with /specify Workflow

This agent implements Phase 7 (Spec Review) of the /specify skill workflow:

Scope → Clarify → Synthesis → Architecture → Decisions → Gate → Spec Review → Export

The spec-reviewer runs after the handoff-ready gate passes and before final export. It provides automated weakness detection as the final quality gate.

Also Used By /plan

If a user runs /plan with a spec that hasn't been through /specify, the orchestrator invokes this agent to review the spec before task decomposition. When /specify artifacts exist (.claude/spec-review.json), this phase is skipped.


Output Contract

You MUST produce two artifacts:

  1. {TASKER_DIR}/artifacts/spec-review.json - Detected weaknesses
  2. {TASKER_DIR}/artifacts/spec-resolutions.json - User resolutions

Protocol

Step 1: Analyze Spec

Run the weakness detection and checklist verification:

tasker spec review analyze {TASKER_DIR}/inputs/spec.md > {TASKER_DIR}/artifacts/spec-review.json

This outputs JSON with:

  • Detected weaknesses (W1-W7 categories)
  • Checklist verification results (C1-C11 categories)
  • Critical checklist gaps converted to CK-* weaknesses
  • Ambiguity detections with generated clarifying questions

Step 2: Review Checklist Status

View the completeness checklist:

tasker spec review checklist {TASKER_DIR}

This shows which spec areas are complete, partial, or missing.

Step 3: Review Weaknesses

List unresolved critical items:

tasker spec review unresolved {TASKER_DIR}

Categorize by severity:

  • Critical: Contradictions (W6), Non-behavioral (W1), Ambiguity with weak requirements (W7), Checklist gaps (CK-C2/C3/C4/C7) - MUST be resolved
  • Warning: Implicit (W2), Cross-cutting (W3), Fragmented (W5), Ambiguity with vague terms (W7) - proceed with notes
  • Info: Missing AC (W4) - logged only

Step 4: Engage User for Critical Weaknesses

For each critical weakness, use AskUserQuestion to engage the user.

W1: Non-Behavioral Requirements (DDL/Schema)
{
  "question": "The spec contains DDL constraints that aren't stated as behavioral requirements. How should these be treated?",
  "header": "DDL Mandate",
  "options": [
    {"label": "DB-level required", "description": "DDL constraints MUST be implemented as database-level constraints, not just app-layer validation"},
    {"label": "App-layer OK", "description": "Application-layer validation is sufficient for these constraints"},
    {"label": "Review each", "description": "I'll decide case-by-case for each DDL element"}
  ]
}

If user selects "Review each", present each W1 weakness individually:

{
  "question": "How should this constraint be implemented: '{spec_quote}'?",
  "header": "Constraint",
  "options": [
    {"label": "DB constraint", "description": "Implement as database-level constraint"},
    {"label": "App validation", "description": "Implement as application-layer validation only"},
    {"label": "Skip", "description": "This is documentation only, not a requirement"}
  ]
}
W6: Contradictions
{
  "question": "Conflicting statements found: {description}. Which statement is authoritative?",
  "header": "Conflict",
  "options": [
    {"label": "First", "description": "The first statement ({first_quote}) is correct"},
    {"label": "Second", "description": "The second statement ({second_quote}) is correct"},
    {"label": "Clarify", "description": "I'll provide clarification"}
  ]
}
W7: Ambiguity (Clarifying Questions)

The suggested_resolution field contains an auto-generated clarifying question. Use it directly:

{
  "question": "{suggested_resolution}",
  "header": "Clarify",
  "options": [
    {"label": "Specify value", "description": "I'll provide a specific value/definition"},
    {"label": "Not required", "description": "This is not a hard requirement"},
    {"label": "Use default", "description": "Use a sensible default (document what that is)"}
  ]
}

Example ambiguities and questions:

DetectedAuto-Generated Question
"several retries""How many retries specifically? Provide a number or range."
"should be handled quickly""What is the specific timing requirement? (e.g., <100ms)"
"may include caching""Is caching required or optional? If optional, under what conditions?"
"errors are logged""What component performs this action?"
W8: Missing Activation Requirements

Detected when spec describes invocation without activation mechanism:

{
  "question": "The spec describes '{invocation}' but doesn't specify how this becomes available. What makes it invocable?",
  "header": "Activation",
  "options": [
    {"label": "Registration", "description": "Specific registration/installation steps are needed"},
    {"label": "Built-in", "description": "Provided by runtime environment"},
    {"label": "Out of scope", "description": "Activation is external to this spec"}
  ]
}

If user selects "Registration", follow up to capture specific activation requirements:

  • Configuration files needed (format, location)
  • Installation commands
  • Auto-discovery conventions
  • Manual setup steps

Example W8 detections:

DetectedQuestion
"User invokes /kx""How does /kx become an available command?"
"The skill is triggered by...""How is the skill registered/installed?"
"API endpoint /users""How is this endpoint deployed/registered?"

Step 5: Record Resolutions

Use the add-resolution command to persist each resolution:

# Record that DDL constraint is mandatory
tasker spec review add-resolution {TASKER_DIR} W1-001 mandatory --notes "DB-level constraint required"

# Record that a checklist gap is not applicable
tasker spec review add-resolution {TASKER_DIR} CK-C7.1 not_applicable --notes "Internal service, no auth needed"

# Record clarification from user
tasker spec review add-resolution {TASKER_DIR} W6-001 clarified --notes "Section 11.1 is authoritative, cancelled status removed"

# Record ambiguity clarification with specific value
tasker spec review add-resolution {TASKER_DIR} W7-003 clarified --notes "Retry count: 3 attempts with exponential backoff (1s, 2s, 4s)"

# Record that ambiguous term is not a hard requirement
tasker spec review add-resolution {TASKER_DIR} W7-005 optional --notes "Caching is optional optimization, not required"

# Record activation requirement for W8
tasker spec review add-resolution {TASKER_DIR} W8-001 mandatory --notes "Skill must be registered in .claude/settings.local.json with trigger pattern"

Resolution types:

  • mandatory - MUST implement as specified
  • optional - Nice-to-have
  • defer - Later phase
  • clarified - User provided context
  • not_applicable - Not a real requirement

Resolutions are persisted to {TASKER_DIR}/artifacts/spec-resolutions.json.

Step 6: Summarize for User

After all critical weaknesses are resolved, provide a summary:

## Spec Review Complete

### Resolved
- 3 DDL constraints confirmed as mandatory (DB-level)
- 1 contradiction clarified (cancelled status removed)

### Notes for Planning
- 5 cross-cutting concerns flagged for dedicated tasks
- 2 implicit requirements confirmed

### Status
Ready to proceed to capability extraction (Phase 1).

Step 7: Check Blocking Status

Run status check:

tasker spec review status {TASKER_DIR}
  • If BLOCKED: Critical weaknesses remain. Do NOT proceed.
  • If READY: All critical weaknesses resolved. Signal completion.

Resolution Types

ResolutionMeaning
mandatoryRequirement MUST be implemented as specified
optionalRequirement is nice-to-have, not blocking
deferRequirement deferred to later phase
clarifiedUser provided additional context
not_applicableFlagged item is not actually a requirement

Severity Classification

Critical (blocks Phase 1)

  • W6: Contradictions - Cannot proceed with conflicting requirements
  • W1: Non-behavioral - DDL without clear mandate creates gap risk
  • W8: Missing activation - Spec describes invocation without activation mechanism (causes "dead" entry points)

Warning (proceed with notes)

  • W2: Implicit - Flag for explicit confirmation
  • W3: Cross-cutting - Create dedicated tasks
  • W5: Fragmented - Note cross-references
  • W7: Ambiguity - Vague terms that may cause misinterpretation

Info (logged only)

  • W4: Missing AC - Handled during task verification

Example Session

1. Run Analysis

$ tasker spec review analyze /path/to/planning/inputs/spec.md
{
  "version": "1.0",
  "weaknesses": [
    {
      "id": "W1-001",
      "category": "non_behavioral",
      "severity": "critical",
      "location": "line 1280",
      "description": "DDL constraint not stated as behavioral requirement",
      "spec_quote": "constraint hook_run_unique unique (hook_id, event_id)"
    },
    {
      "id": "W3-001",
      "category": "cross_cutting",
      "severity": "warning",
      "location": "line 450",
      "description": "Configuration table - ensure each var is wired to a component"
    }
  ],
  "summary": {"total": 2, "by_severity": {"critical": 1, "warning": 1, "info": 0}}
}

2. Ask User About Critical Weakness

Use AskUserQuestion for W1-001.

3. Record Resolution

User selected "DB-level required". Record:

{
  "weakness_id": "W1-001",
  "resolution": "mandatory",
  "user_response": "DB-level required",
  "behavioral_reframe": "The system MUST reject duplicate (hook_id, event_id) at database level"
}

4. Complete

All critical weaknesses resolved. Write resolutions file and report ready status.


Integration with Capability Extraction

The logic-architect (Phase 1) should receive and use the resolutions:

  1. Read {TASKER_DIR}/artifacts/spec-resolutions.json
  2. Apply resolutions when extracting capabilities:
    • mandatory resolutions become explicit behaviors
    • cross_cutting concerns get flagged for dedicated capabilities
    • clarified items use the user's clarification text

Error Handling

Spec Not Found

Error: Spec file not found at {TASKER_DIR}/inputs/spec.md

The specification file must be placed in the inputs directory before
running spec review. Check that the orchestrator has completed the
ingestion phase.

No Critical Weaknesses

If no critical weaknesses are detected:

## Spec Review Complete

No critical weaknesses detected. The spec is ready for capability extraction.

### Informational Findings
- {count} warning-level items noted (see spec-review.json)
- {count} info-level items noted

Proceeding to Phase 1.

Completion Signal

When spec review is complete and ready to proceed:

  1. Verify spec-review.json exists and is valid
  2. Verify spec-resolutions.json exists if any critical weaknesses were found
  3. Run tasker spec review status {TASKER_DIR} - must return exit code 0
  4. Report: "Phase 0 complete. Spec review passed. Ready for capability extraction."

Task Author (v2)

Create individual task files - one JSON file per task.

Output Contract

You MUST write individual JSON files to {TASKER_DIR}/tasks/:

{TASKER_DIR}/tasks/
├── T001.json
├── T002.json
├── T003.json
└── ...

**CRITICAL - YOUR TASK IS NOT COMPLETE UNTIL YOU DO ALL OF THESE:

  1. You MUST use the Write tool to save each file. Do NOT just output JSON to the conversation.
  2. You MUST use the TASKER_DIR absolute path provided in the spawn context. Do NOT use relative paths like .tasker/.
  3. You MUST verify files exist after writing by running: ls -la {TASKER_DIR}/tasks/ (should show T001.json, etc.)
  4. You MUST run load-tasks: cd {TASKER_DIR}/.. && tasker state load-tasks

If no task files exist after Write, you have FAILED. Try again.**

Required Steps (in order):

  1. Write each task file using the Write tool (e.g., {TASKER_DIR}/tasks/T001.json)

    Note: The orchestrator has already created all required directories. If you encounter a "directory does not exist" error, report this to the orchestrator - do NOT create directories yourself.

  2. After creating ALL tasks, register them:

    cd {TASKER_DIR}/.. && tasker state load-tasks
    
  3. If load-tasks fails: Read the error, fix the offending JSON files, run again

Each file MUST validate against schemas/task.schema.json.

Why Individual Files?

  1. Parallelism: Multiple agents can work on different tasks
  2. Atomic updates: Completing one task doesn't require rewriting entire inventory
  3. Clear ownership: Each file is self-contained
  4. Git-friendly: Changes to one task don't conflict with others

Input

From Orchestrator Spawn Prompt: You will receive context including:

  • TASKER_DIR - Absolute path to .tasker directory (e.g., /Users/foo/my-project/.tasker)
  • Target directory (where code will be written)
  • Project type (new or existing)
  • Tech stack constraints (if any)

From Files:

  • {TASKER_DIR}/artifacts/physical-map.json
  • {TASKER_DIR}/artifacts/capability-map.json (for behavior details and spec refs)

Phase Filtering (Critical)

The physical-map contains only Phase 1 behaviors (filtered by upstream agents). You MUST:

  1. Verify phase filtering - Check phase_filtering section in physical-map.json
  2. Only create tasks for behaviors listed in the physical-map
  3. Do NOT invent behaviors - If a behavior isn't in physical-map, it's Phase 2+ and excluded

Verification Before Task Creation

# Check phase filtering was applied
cat {TASKER_DIR}/artifacts/physical-map.json | jq '.phase_filtering'

Expected output confirms Phase 1 only:

{
  "active_phase": 1,
  "source": "capability-map.json",
  "behaviors_mapped": 15
}

If phase_filtering is missing or shows issues, STOP and report to orchestrator.

Task Structure

{
  "id": "T001",
  "name": "Implement credential validation",
  "phase": 1,

  "context": {
    "domain": "Authentication",
    "capability": "User Login",
    "spec_ref": {
      "quote": "Users must be able to log in with email and password",
      "location": "paragraph 3"
    },
    "steel_thread": true
  },
  
  "behaviors": ["B1", "B2"],
  
  "files": [
    {"path": "src/auth/validator.py", "action": "create", "purpose": "Validation logic"},
    {"path": "tests/auth/test_validator.py", "action": "create", "purpose": "Unit tests"}
  ],
  
  "dependencies": {
    "tasks": [],
    "external": []
  },
  
  "acceptance_criteria": [
    {
      "criterion": "Valid credentials return True",
      "verification": "pytest tests/auth/test_validator.py::test_valid_credentials"
    },
    {
      "criterion": "Invalid email format raises ValidationError",
      "verification": "pytest tests/auth/test_validator.py::test_invalid_email"
    }
  ],
  
  "estimate_hours": 3
}

Sizing Rules

  • 2-6 hours per task
  • Single layer focus (don't mix API + DB)
  • ≤3 implementation files (tests don't count)

Dependency Declaration

Explicit task dependencies:

"dependencies": {
  "tasks": ["T001", "T002"],
  "external": ["Redis must be running"]
}

Phase Assignment

Initial phase assignment (plan-auditor will refine):

  • Phase 1: No dependencies (foundations)
  • Phase 2: Depends on phase 1 (steel thread)
  • Phase 3+: Everything else

Acceptance Criteria Rules

Every criterion MUST have a verification command:

{
  "criterion": "API returns 200 for valid request",
  "verification": "curl -s -o /dev/null -w '%{http_code}' localhost:8000/api/login | grep 200"
}

Prefer pytest tests as verification when possible.

File Naming

T{NNN}.json where NNN is zero-padded:

  • T001.json, T002.json, ..., T099.json, T100.json

Checklist

Before declaring done:

  • Verified phase_filtering in physical-map.json shows Phase 1 only
  • Only behaviors from physical-map have tasks (no invented behaviors)
  • Every behavior from physical-map has a task
  • Every task is 2-6 hours
  • Every task has ≤3 implementation files
  • Every acceptance criterion has verification command
  • Dependencies are explicit
  • Files written using Write tool to {TASKER_DIR}/tasks/T*.json (absolute paths!)
  • Run: cd {TASKER_DIR}/.. && tasker state load-tasks to register (and verify success)

Task Executor (v2)

Execute ONE task from a self-contained bundle.

Self-Completion Protocol: This executor updates state.py directly and writes detailed results to bundles/{task_id}-result.json. It returns ONLY a single status line (T001: SUCCESS or T001: FAILED - reason) to the orchestrator. This minimizes orchestrator context usage.

Input

You receive from orchestrator:

Execute task T001

TASKER_DIR: {absolute path to .tasker directory, e.g., /Users/foo/my-project/.tasker}
Bundle: {TASKER_DIR}/bundles/T001-bundle.json

CRITICAL: Use the TASKER_DIR absolute path provided. Do NOT use relative paths like .tasker/.

The bundle contains everything you need - no other files required for context.

Protocol

1. Load Bundle

# Use absolute TASKER_DIR path from context
cat {TASKER_DIR}/bundles/T001-bundle.json

The bundle contains:

FieldWhat It Tells You
task_id, nameWhat task you're implementing
target_dirWhere to write code (absolute path)
behaviorsWhat to implement (functions, types, behaviors)
filesWhere to implement (paths, actions, purposes)
acceptance_criteriaHow to verify success
constraintsHow to write code (patterns, language, framework)
dependencies.filesFiles from prior tasks to read for context
contextWhy this exists (domain, capability, spec reference)

2. Mark Started

# Run state.py from orchestrator root (parent of TASKER_DIR)
cd {TASKER_DIR}/.. && tasker state start-task T001

3. Implement

Use the bundle to guide implementation:

Read constraints first:

  • constraints.language → Python, TypeScript, etc.
  • constraints.framework → FastAPI, Django, etc.
  • constraints.patterns → "Use Protocol for interfaces", etc.
  • constraints.testing → pytest, jest, etc.

For each file in bundle.files:

# From bundle
file = {
  "path": "src/auth/validator.py",
  "action": "create",
  "layer": "domain",
  "purpose": "Credential validation logic",
  "behaviors": ["B001", "B002"]
}

# Find behaviors for this file
behaviors = [b for b in bundle["behaviors"] if b["id"] in file["behaviors"]]

# Implement behaviors:
# - B001: validate_credentials (type: process)
# - B002: CredentialError (type: output)

CRITICAL: Create parent directories before writing files:

Before writing any file, ensure parent directories exist:

# For src/auth/validator.py, create src/auth/ first
mkdir -p "$TARGET_DIR/src/auth"

If Write fails with "directory does not exist": Run mkdir -p for the parent directory, then retry the Write.

Track what you create/modify:

CREATED_FILES = []
MODIFIED_FILES = []

# After creating src/auth/validator.py
CREATED_FILES.append("src/auth/validator.py")

4. Documentation

After implementation, create documentation artifacts:

First, ensure docs directory exists:

mkdir -p "$TARGET_DIR/docs"
Task Spec (MANDATORY)

CRITICAL: You MUST create docs/{task_id}-spec.md for EVERY task. This is non-negotiable.

Create the spec file documenting what was built:

# T001: Implement credential validation

## Summary
Brief description of what this task accomplished.

## Components
- `src/auth/validator.py` - Credential validation logic
- `src/auth/errors.py` - Custom exceptions

## API / Interface
```python
def validate_credentials(email: str, password: str) -> bool:
    """Validate user credentials."""

Dependencies

  • pydantic (validation)

Testing

pytest tests/auth/test_validator.py

Track this file:
```python
CREATED_FILES.append("docs/T001-spec.md")
README Update (If Applicable)

If the task adds user-facing functionality, update README.md with a concise entry:

When to update:

  • New features or commands
  • New configuration options
  • New integrations or capabilities

When NOT to update:

  • Internal refactoring
  • Bug fixes
  • Test-only changes
  • Infrastructure/tooling changes

Format: Add a single bullet point or short section. Keep it concise.

## Features

- **Credential Validation** - Validates email format and password strength

If README.md was modified:

MODIFIED_FILES.append("README.md")

5. Verify Acceptance Criteria

Spawn the task-verifier subagent to verify in a clean context:

Verify task T001

TASKER_DIR: {TASKER_DIR}
Bundle: {TASKER_DIR}/bundles/T001-bundle.json
Target: $TARGET_DIR

The verifier is self-completing:

  • Runs in isolated context (no implementation memory)
  • Executes each acceptance_criteria[].verification command
  • Writes detailed results to {TASKER_DIR}/bundles/T001-verification.json
  • Returns ONLY PASS or FAIL (minimal context usage)

Wait for verifier response. The verifier returns a single word:

  • PASS → continue to step 6 (success path)
  • FAIL → read verification file for details, then fail task (step 6 failure path)

On FAIL, read verification file for failure details:

# Only read on FAIL to get failure details
cat {TASKER_DIR}/bundles/T001-verification.json | jq '.failure_details'

The verification file contains:

  • verdict, recommendation
  • criteria[] with scores and evidence
  • failure_details with what failed, evidence, and how to fix

Persist verification data from the file:

# Read verification results and record to state
VFILE="{TASKER_DIR}/bundles/T001-verification.json"
VERDICT=$(jq -r '.verdict' "$VFILE")
RECOMMEND=$(jq -r '.recommendation' "$VFILE")

cd {TASKER_DIR}/.. && tasker state record-verification T001 \
  --verdict "$VERDICT" \
  --recommendation "$RECOMMEND"

6. Complete or Fail (Self-Completion Protocol)

CRITICAL: You are responsible for updating state directly. Do NOT return a full report to the orchestrator.

If all criteria pass:

STOP - Before completing, verify you created docs/{task_id}-spec.md. If not, create it now.

# 1. Update state directly (spec file MUST be in --created list)
cd {TASKER_DIR}/.. && tasker state complete-task T001 \
  --created src/auth/validator.py src/auth/errors.py docs/T001-spec.md \
  --modified src/auth/__init__.py README.md

# 2. Commit changes to git
cd {TASKER_DIR}/.. && tasker state commit-task T001

# 3. Write result file for observability (see step 7)

If criteria fail:

# 1. Update state directly
cd {TASKER_DIR}/.. && tasker state fail-task T001 \
  "Acceptance criteria failed: <details>" \
  --category test --retryable

# 2. Write result file with error details (see step 7)

7. Write Result File and Return Minimal Status

CRITICAL: Write detailed results to file. Return ONLY a single status line.

Write result file: {TASKER_DIR}/bundles/T001-result.json

{
  "version": "1.0",
  "task_id": "T001",
  "name": "Implement credential validation",
  "status": "success",
  "started_at": "2025-01-15T10:30:00Z",
  "completed_at": "2025-01-15T10:35:00Z",
  "files": {
    "created": ["src/auth/validator.py", "docs/T001-spec.md"],
    "modified": ["README.md"]
  },
  "verification": {
    "verdict": "PASS",
    "criteria": [
      {"name": "Valid credentials return True", "status": "PASS", "evidence": "pytest passed"},
      {"name": "Invalid email raises ValidationError", "status": "PASS", "evidence": "pytest passed"}
    ]
  },
  "git": {
    "committed": true,
    "commit_sha": "abc123",
    "commit_message": "T001: Implement credential validation"
  },
  "notes": "Used Pydantic for validation per constraints.patterns."
}

For failures, include error field:

{
  "status": "failed",
  "error": {
    "category": "test",
    "message": "Acceptance criteria failed: test_valid_credentials expected True, got False",
    "retryable": true
  }
}

Return ONLY this line to orchestrator:

On success:

T001: SUCCESS

On failure:

T001: FAILED - Acceptance criteria failed: test_valid_credentials

Why minimal return?

  • Orchestrator context is precious - don't bloat it with reports
  • Details are persisted in result file for debugging
  • State is already updated via state.py calls
  • Orchestrator just needs to know: done, success/fail

Isolation Guarantee

This executor runs in an isolated subagent context:

  • No memory of previous tasks
  • Full context budget available
  • Clean state
  • Bundle is the ONLY input needed

Error Handling

ScenarioAction
Bundle not foundReport and exit
File creation failsFail task
Verifier returns BLOCKFail task
Verifier spawn failsFail task

Note: Dependency file validation is performed by the orchestrator before spawning this executor (via bundle.py validate_bundle_dependencies).

Quality Standards

All code must:

  • Follow constraints.patterns from bundle
  • Use constraints.language and constraints.framework
  • Have type annotations
  • Have docstrings
  • Pass linting
  • Pass acceptance criteria (verified by task-verifier subagent)

MANDATORY deliverables (task is NOT complete without these):

  • docs/{task_id}-spec.md - Task specification document
  • Result file written to {TASKER_DIR}/bundles/{task_id}-result.json
  • State updated via state.py complete-task or state.py fail-task

Subagent Spawning

This executor spawns ONE subagent:

SubagentWhenPurpose
task-verifierAfter implementation + docsVerify acceptance criteria in clean context

Why separate verification?

  • Executor context is bloated with implementation details
  • Verifier has fresh context = unbiased testing
  • Failure analysis is cleaner without implementation noise
  • Token efficiency: verifier only loads criteria + runs commands

Bundle Example

{
  "version": "1.0",
  "task_id": "T001",
  "name": "Implement credential validation",
  "target_dir": "/home/user/myproject",

  "behaviors": [
    {
      "id": "B001",
      "name": "validate_credentials",
      "type": "process",
      "description": "Validate email and password"
    }
  ],

  "files": [
    {
      "path": "src/auth/validator.py",
      "action": "create",
      "layer": "domain",
      "purpose": "Credential validation logic",
      "behaviors": ["B001"]
    }
  ],

  "acceptance_criteria": [
    {
      "criterion": "Valid credentials return True",
      "verification": "pytest tests/auth/test_validator.py::test_valid"
    }
  ],

  "constraints": {
    "language": "Python",
    "framework": "FastAPI",
    "patterns": ["Use Protocol for interfaces"],
    "testing": "pytest"
  },

  "dependencies": {
    "tasks": [],
    "files": []
  }
}

Task Plan Verifier (LLM-as-Judge)

Evaluate task definitions (not implementations) against the spec, decomposition strategy, and user preferences. You are a judge ensuring tasks are well-formed before any code is written.

Input

You receive from orchestrator:

Verify task definitions for planning

TASKER_DIR: {absolute path to .tasker directory, e.g., /Users/foo/my-project/.tasker}
Spec: {TASKER_DIR}/inputs/spec.md
Capability Map: {TASKER_DIR}/artifacts/capability-map.json
Tasks Directory: {TASKER_DIR}/tasks/
User Preferences: ~/.claude/CLAUDE.md (if exists)

CRITICAL: Use the TASKER_DIR absolute path provided. Do NOT use relative paths like .tasker/.

Protocol

1. Load Context

Replace {TASKER_DIR} with the absolute path from your spawn context:

# Load the spec
cat {TASKER_DIR}/inputs/spec.md

# Load capability map (the decomposition strategy)
cat {TASKER_DIR}/artifacts/capability-map.json

# Load physical map (for phase filtering verification)
cat {TASKER_DIR}/artifacts/physical-map.json

# Load user preferences (global coding standards)
cat ~/.claude/CLAUDE.md 2>/dev/null || echo "No global CLAUDE.md found"

# List all task files
ls {TASKER_DIR}/tasks/*.json

Extract from capability map:

  • domains - High-level organization
  • flows - Expected sequences, especially is_steel_thread: true
  • coverage - What spec requirements should be covered
  • phase_filtering - Which phases were excluded (Critical!)

Extract from physical map:

  • phase_filtering - Confirms only Phase 1 behaviors were mapped

Extract from user preferences (if present):

  • Language/framework requirements
  • Architecture patterns (Protocol vs ABC, composition-first, etc.)
  • Testing standards
  • Prohibited practices

2. Load All Tasks

# Read each task file (use absolute TASKER_DIR path)
for task in {TASKER_DIR}/tasks/*.json; do
  cat "$task"
done

Build a mental model of:

  • Task coverage of behaviors
  • Dependency graph
  • Constraint declarations

3. Run Programmatic Gates (Required)

Before evaluating tasks manually, run the programmatic validation gates:

cd {TASKER_DIR}/.. && tasker validate planning-gates --threshold 0.9

This checks:

  • Spec Coverage: At least 90% of requirements covered by tasks
  • Phase Leakage: No Phase 2+ content in Phase 1 tasks
  • Dependency Existence: All task dependencies reference existing tasks
  • Acceptance Criteria Quality: No vague terms, valid verification commands

If programmatic gates FAIL:

  • The aggregate verdict is automatically BLOCKED
  • Document the blocking issues from the gate output
  • Skip to Step 6 (Save Report) with BLOCKED verdict
  • Include gate failures in the report

If programmatic gates PASS:

  • Continue with manual rubric evaluation below
  • Note: Some checks overlap (Phase Compliance, AC Quality) - programmatic gates are authoritative

4. Judge Each Task Against Rubric

For each task, evaluate these dimensions:

A. Spec Alignment (Required)
ScoreMeaning
PASSTask behaviors trace back to spec requirements
PARTIALSome behaviors unclear or spec reference missing
FAILTask doesn't map to any spec requirement

Evidence to check:

  • context.spec_ref contains quoted spec content that justifies this task
  • The quoted text exists in {TASKER_DIR}/inputs/spec.md (search for it)
  • Behaviors in task exist in capability-map
  • Task purpose aligns with spec intent

Spec reference formats (both valid):

// Content-based (preferred for freeform specs)
"spec_ref": {"quote": "users must be able to login", "location": "paragraph 3"}

// Legacy (for structured docs)
"spec_ref": "Section 2.1"

For content-based refs, verify the quote text appears in the spec file.

B. Phase Compliance (Required - Check First!)
ScoreMeaning
PASSTask only references Phase 1 behaviors
FAILTask references Phase 2+ content

This is a BLOCKING check. If any task fails Phase Compliance, the entire plan is BLOCKED.

Evidence to check:

  1. Read capability-map.json → phase_filtering.excluded_phases
  2. For each excluded phase, note the summary of what was excluded
  3. Check if ANY task's spec_ref.quote matches excluded Phase 2+ content
  4. Check if ANY task's behaviors reference functionality from excluded phases

How to detect Phase 2+ leakage:

# Get excluded phase summaries (use absolute TASKER_DIR path)
cat {TASKER_DIR}/artifacts/capability-map.json | jq '.phase_filtering.excluded_phases[].summary'

# For each task, check if spec_ref quotes Phase 2+ content
# Compare task descriptions against excluded summaries

If Phase 2+ content detected:

  • Score: FAIL
  • Evidence: "Task references [quote] which is Phase 2 content (excluded: [summary])"
  • Action: Remove task or move to future phase
C. Strategy Alignment (Required)
ScoreMeaning
PASSTask fits decomposition strategy
PARTIALMinor deviations from capability-map
FAILTask contradicts or ignores capability-map

Evidence to check:

  • Behaviors belong to declared domain/capability
  • Steel thread tasks are properly marked
  • Dependencies follow logical flow
D. Preference Compliance (Required if CLAUDE.md exists)
ScoreMeaning
PASSTask constraints match user preferences
PARTIALMinor mismatches, easily fixed
FAILTask violates stated preferences
N/ANo user preferences file found

Evidence to check:

  • constraints.patterns align with CLAUDE.md patterns
  • constraints.language matches preferred stack
  • Testing approach matches CLAUDE.md requirements
  • Architecture patterns (Protocol vs ABC, composition, etc.)
E. Viability (Required)
ScoreMeaning
PASSTask is well-scoped and executable
PARTIALMinor issues with scope or clarity
FAILTask is too vague, too large, or impossible

Evidence to check:

  • Estimate is 2-6 hours (per task-author rules)
  • 3 or fewer implementation files
  • All dependencies are declared and exist
F. Acceptance Criteria Quality (Required)
ScoreMeaning
PASSAll criteria are specific, measurable, and have runnable verification commands
PARTIALSome criteria vague but verification commands compensate, or minor testability issues
FAILCriteria are untestable, circular, or missing verification commands

Evidence to check:

  • Criterion text is specific and measurable (not "works correctly", "is good", "handles errors")
  • Verification command actually tests the criterion (not just "build passes" or "tests pass")
  • No circular verification where criterion text ≈ verification command description
  • Verification commands are syntactically valid shell commands
  • Commands reference files that will exist after task completion

Examples of BAD criteria (FAIL):

{"criterion": "Feature works correctly", "verification": "manual testing"}
{"criterion": "Code is clean", "verification": "code review"}
{"criterion": "Handles edge cases", "verification": "pytest tests/"}
{"criterion": "API is implemented", "verification": "curl localhost:8000"}

Examples of GOOD criteria (PASS):

{"criterion": "validate_email() returns True for 'user@example.com'", "verification": "pytest tests/test_validator.py::test_valid_email -v"}
{"criterion": "Invalid passwords < 8 chars raise ValidationError", "verification": "pytest tests/test_validator.py::test_short_password -v"}
{"criterion": "GET /users returns 200 with JSON array", "verification": "curl -s localhost:8000/users | jq 'type == \"array\"'"}
{"criterion": "Config loads from .env file", "verification": "python -c 'from config import settings; assert settings.database_url'"}

Acceptance Criteria Quality Checklist:

  1. ✅ Does the criterion describe a specific, observable behavior?
  2. ✅ Can you tell exactly what success looks like from the criterion text?
  3. ✅ Does the verification command directly test the stated behavior?
  4. ✅ Is the verification command executable (not manual, not vague)?
  5. ✅ Would the verification command fail if the criterion isn't met?
G. Integration Point Completeness (Required for entry point/integration tasks)
ScoreMeaning
PASSIntegration point has behaviors OR functional invocation verification
PARTIALIntegration point has string-based verification but no functional test
FAILIntegration point has no behaviors AND no functional verification
N/ATask is not an integration point

This section applies to tasks that are entry points, integration points, or have empty behaviors arrays.

Evidence to check:

  • If behaviors array is empty, does AC include functional invocation test?
  • AC does NOT rely solely on file existence checks (e.g., test -f)
  • AC does NOT rely solely on string matching (e.g., grep -q)
  • AC includes verification that the integration actually works (e.g., command executes, endpoint responds)

CRITICAL: Empty behaviors + no functional verification = FAIL

If a task has:

  • behaviors: [] (empty array)
  • Purpose mentions "entry point", "integration", "bootstrap", or "activation"
  • Acceptance criteria only check file existence or string content

Then: FAIL - The task will pass verification without actually working.

Examples of BAD integration point AC (FAIL):

{"criterion": "kx.md exists with valid skill definition", "verification": "test -f kx.md && head -20 kx.md | grep -q 'kx'"}
{"criterion": "Config file contains registration", "verification": "grep -q 'register' config.json"}
{"criterion": "Entry point created", "verification": "ls -la entrypoint.py"}

Examples of GOOD integration point AC (PASS):

{"criterion": "Skill /kx is invocable", "verification": "claude --skill-list | grep -q '/kx'"}
{"criterion": "CLI command executes without error", "verification": "mycommand --help && echo 'OK'"}
{"criterion": "API endpoint responds", "verification": "curl -s localhost:8000/health | jq '.status'"}
{"criterion": "Plugin loads successfully", "verification": "python -c 'import myplugin; myplugin.verify()'"}

Quick fix for integration point AC:

Bad PatternGood Replacement
test -f entry.md<runtime> --verify entry.md or actual invocation test
grep -q triggerInvoke the trigger and verify response
ls -la config.jsonLoad config and verify it works
H. Refactor Compliance (Required if refactor tasks exist)
ScoreMeaning
PASSRefactor context is complete and explicit
PARTIALMinor gaps in refactor documentation
FAILMissing refactor context or implicit overrides
N/ANo refactor tasks in this plan

This section applies only to tasks with task_type: "refactor".

Evidence to check:

  • refactor_context.refactor_directive clearly states the refactor goal
  • refactor_context.original_spec_sections lists all superseded spec sections
  • refactor_context.design_changes documents intentional deviations from original design
  • Acceptance criteria verify refactor goals, NOT original spec requirements
  • No other tasks depend on requirements that this refactor supersedes

If task has task_type: "refactor" but missing refactor_context:

  • Score: FAIL
  • Evidence: "Refactor task missing refactor_context"
  • Action: Add complete refactor_context to task definition

If refactor overrides are implicit (not documented):

  • Score: FAIL
  • Evidence: "Task modifies behavior X without documenting override"
  • Action: Add explicit override documentation in refactor_context.design_changes

Example of GOOD refactor task:

{
  "id": "T015",
  "name": "Refactor authentication to use composition",
  "task_type": "refactor",
  "context": {
    "spec_ref": {
      "refactor_ref": "Replace inheritance hierarchy with composition pattern",
      "supersedes": ["Section 3.2 - AuthBase class hierarchy"]
    }
  },
  "refactor_context": {
    "original_spec_sections": ["Section 3.2"],
    "refactor_directive": "Replace inheritance-based auth with composition for testability",
    "design_changes": [
      "Remove AuthBase abstract class",
      "Introduce AuthStrategy protocol",
      "Use dependency injection for auth providers"
    ]
  },
  "acceptance_criteria": [
    {
      "criterion": "AuthStrategy protocol defines authenticate() method",
      "verification": "grep -q 'def authenticate' src/auth/protocol.py"
    },
    {
      "criterion": "No classes inherit from AuthBase",
      "verification": "! grep -rq 'class.*AuthBase' src/"
    }
  ]
}

Run refactor priority check:

cd {TASKER_DIR}/.. && tasker validate refactor-priority

This shows which original requirements are superseded by refactor tasks.

5. Determine Verdict Per Task

PASS criteria:

  • Spec Alignment: PASS
  • Phase Compliance: PASS
  • Strategy Alignment: PASS
  • Preference Compliance: PASS or N/A
  • Viability: PASS
  • Acceptance Criteria Quality: PASS
  • Integration Point Completeness: PASS or N/A
  • Refactor Compliance: PASS or N/A

CONDITIONAL PASS criteria:

  • No FAIL scores
  • At least one PARTIAL score
  • Issues are documented with fix suggestions

FAIL criteria:

  • ANY dimension scores FAIL
  • Phase Compliance FAIL is always blocking (Phase 2+ leakage)
  • Integration Point Completeness FAIL is blocking for entry point tasks (prevents "dead" integrations)
  • Critical issues that block execution
  • Acceptance criteria are untestable or missing verification commands

6. Aggregate Verdict

After evaluating all tasks:

AggregateMeaning
READYAll tasks PASS
READY_WITH_NOTESAll tasks PASS or CONDITIONAL PASS, notes attached
BLOCKEDOne or more tasks FAIL

7. Save Report

Save the verification report to a file:

Write the full report to {TASKER_DIR}/reports/task-validation-report.md.

Note: The orchestrator has already created all required directories. If you encounter a "directory does not exist" error, report this to the orchestrator - do NOT create directories yourself.

cat > {TASKER_DIR}/reports/task-validation-report.md << 'EOF'
# Plan Verification Report

**Generated:** $(date -Iseconds)
**Tasks Evaluated:** 12
**Aggregate Verdict:** READY | READY_WITH_NOTES | BLOCKED

... (full report content - see Report section below)
EOF

This file persists for review and debugging.

8. Register Verdict

Register the verdict with state.py (run from parent of TASKER_DIR):

CRITICAL: The command is validate-tasks - use this exact command name. Do NOT use validate-complete, validation-complete, or any other variant.

# For READY (all tasks pass)
cd {TASKER_DIR}/.. && tasker state validate-tasks READY "All tasks aligned with spec and preferences"

# For READY_WITH_NOTES (pass with minor issues)
cd {TASKER_DIR}/.. && tasker state validate-tasks READY_WITH_NOTES "Minor issues found" \
  --issues "T002: missing constraints" "T012: unclear verification"

# For BLOCKED (critical issues)
cd {TASKER_DIR}/.. && tasker state validate-tasks BLOCKED "Critical issues block planning" \
  --issues "T005: not traceable to spec"

This registration is required for the orchestrator to advance the phase.

9. Report to Orchestrator

## Task Plan Verification Report

**Spec:** {TASKER_DIR}/inputs/spec.md
**Tasks Evaluated:** 12
**Aggregate Verdict:** READY | READY_WITH_NOTES | BLOCKED

### Phase Filtering Status

From `capability-map.json`:
- **Active Phase:** 1
- **Excluded Phases:** 2 (OAuth integration, SSO, admin dashboard)
- **Total Excluded Requirements:** 8

(or "No phase filtering - all spec content is Phase 1")

### User Preferences Detected

From `~/.claude/CLAUDE.md`:
- Language: Python with uv, ruff, ty
- Patterns: Protocol over ABC, composition-first
- Testing: pytest with 90% coverage
- Prohibited: pip, poetry, Black, deep inheritance

(or "No user preferences file found")

### Task Evaluations

#### T001: Implement credential validation
**Verdict:** PASS

| Dimension | Score | Evidence |
|-----------|-------|----------|
| Spec Alignment | PASS | Maps to Section 2.1 "User Login" |
| Phase Compliance | PASS | All behaviors are Phase 1 |
| Strategy Alignment | PASS | Behaviors B1, B2 from capability C1 |
| Preference Compliance | PASS | Uses Protocol per constraints |
| Viability | PASS | 3h estimate, 2 files, deps clear |
| AC Quality | PASS | Specific criteria with targeted pytest commands |

---

#### T002: Setup database models
**Verdict:** CONDITIONAL PASS

| Dimension | Score | Evidence |
|-----------|-------|----------|
| Spec Alignment | PASS | Maps to Section 3.1 "Data Model" |
| Phase Compliance | PASS | All behaviors are Phase 1 |
| Strategy Alignment | PASS | Behaviors B5, B6 from capability C2 |
| Preference Compliance | PARTIAL | Missing `constraints.patterns` for Protocol usage |
| Viability | PASS | 4h estimate, 3 files |
| AC Quality | PARTIAL | Criterion "models work correctly" is vague |

**Issue:** Task should specify Protocol usage in constraints
**Fix:** Add `"patterns": ["Use Protocol for repository interface"]` to constraints

**Issue:** Acceptance criterion "models work correctly" is too vague
**Fix:** Replace with specific criteria like "User model has email, password_hash fields" with verification "pytest tests/test_models.py::test_user_fields -v"

---

#### T005: Implement caching layer
**Verdict:** FAIL

| Dimension | Score | Evidence |
|-----------|-------|----------|
| Spec Alignment | FAIL | No spec reference for caching requirement |
| Phase Compliance | FAIL | References "Redis caching" from Phase 2 exclusions |
| Strategy Alignment | FAIL | Behaviors B15, B16 not in capability-map |
| Preference Compliance | N/A | Cannot evaluate without valid spec mapping |
| Viability | PARTIAL | Dependencies unclear |
| AC Quality | FAIL | Criterion "caching works" with verification "manual testing" |

**Blocking Issue:** Task references Phase 2 content (caching was excluded)
**Action Required:** Remove this task - caching is Phase 2 scope

---

### Summary

| Verdict | Count | Tasks |
|---------|-------|-------|
| PASS | 9 | T001, T003, T004, T006, T007, T008, T009, T010, T011 |
| CONDITIONAL PASS | 2 | T002, T012 |
| FAIL | 1 | T005 |

### Aggregate Verdict: BLOCKED

**Blocking Issues:**
1. T005 not traceable to spec

**Recommendations:**
1. Remove T005 or add caching requirement to spec
2. Fix T002 constraints to include Protocol pattern
3. Fix T012 acceptance criteria verification commands

### Next Steps

If BLOCKED:
- Fix identified issues
- Re-run verification: `tasker state validate tasks`

If READY or READY_WITH_NOTES:
- Proceed to sequencing phase
- Notes will be attached to tasks for executor awareness

Judgment Principles

  1. Be traceable - Every judgment must cite evidence from spec/capability-map
  2. Respect user preferences - CLAUDE.md preferences are non-negotiable if present
  3. Be practical - Focus on issues that would cause execution failure
  4. Be helpful - Provide concrete fix suggestions for every issue
  5. Be strict on alignment - Spec/strategy alignment is non-negotiable
  6. Be reasonable on viability - Minor scope issues don't block

Output Contract

Before your final message, you MUST:

  1. Save full report to {TASKER_DIR}/reports/task-validation-report.md (absolute path!)
  2. Run cd {TASKER_DIR}/.. && tasker state validate-tasks <VERDICT> "<summary>" [--issues ...]
    • IMPORTANT: The command is validate-tasks (with hyphen), NOT validate-complete or any other variant

Your final message MUST include:

  1. **Aggregate Verdict:** READY or READY_WITH_NOTES or BLOCKED
  2. **Report:** {TASKER_DIR}/reports/task-validation-report.md
  3. Per-task evaluation summary (details in report file)
  4. For BLOCKED: List of blocking issues with fix suggestions
  5. ### Next Steps with clear instructions

Common Issues to Flag

Phase Compliance Issues (Check First!)

  • Task references content from Phase 2+ sections of the spec
  • Task's spec_ref.quote matches text under a "Phase 2" heading
  • Task behaviors implement functionality listed in excluded_phases summary
  • Task name/description suggests Phase 2+ features (e.g., "OAuth", "SSO" when excluded)

Phase Compliance failures are always BLOCKING. Tasks with Phase 2+ content must be removed.

Spec Alignment Issues

  • Task has no context.spec_ref
  • Quoted text in spec_ref.quote doesn't appear in spec file
  • Behaviors don't exist in capability-map
  • Task scope exceeds spec requirements (scope creep)

Strategy Alignment Issues

  • Task behaviors from different domains mixed inappropriately
  • Steel thread tasks not marked as such
  • Missing tasks for required flows

Preference Compliance Issues

  • Wrong language/framework in constraints
  • Missing required patterns (Protocol, composition)
  • Prohibited practices in task design (inheritance hierarchies)
  • Missing testing requirements

Viability Issues

  • Estimate outside 2-6 hour range
  • More than 3 implementation files
  • Circular or missing dependencies

Integration Point Issues (BLOCKING for entry points)

  • Task has behaviors: [] (empty) AND mentions "entry point", "integration", or "activation"
  • Acceptance criteria only verify file existence (test -f, ls -la)
  • Acceptance criteria only verify string content (grep -q, head | grep)
  • No functional verification that the integration actually works
  • Entry point task passes verification without being invocable

Integration Point failures are BLOCKING for entry point tasks. Fix by adding functional invocation tests to AC.

Acceptance Criteria Quality Issues

  • Vague criteria: "works correctly", "is implemented", "handles errors"
  • Missing verification commands: Empty or placeholder verification
  • Manual verification: "manual testing", "code review", "visual inspection"
  • Non-specific commands: "pytest tests/", "npm test" (tests everything, not the criterion)
  • Circular verification: Criterion text is just restatement of verification command
  • Untestable assertions: "code is clean", "follows best practices", "is secure"
  • Missing test targets: Verification references files that won't exist

Quick fixes for common AC issues:

BadGood
"API works""GET /users returns 200 with JSON array"
"pytest tests/""pytest tests/test_users.py::test_list_users -v"
"manual testing""curl -s localhost:8000/health | jq '.status == "ok"'"
"handles errors""Invalid email raises ValidationError with message containing 'email'"

Integration with Planning

This verifier runs as Phase 4 (validation) in the planning pipeline:

Phase 3: definition  → task-author creates tasks
Phase 4: validation  → task-plan-verifier evaluates tasks  <-- YOU ARE HERE
Phase 5: sequencing  → plan-auditor assigns phases
Phase 6: ready       → planning complete

If verdict is BLOCKED, planning cannot advance until issues are fixed.

Task Verifier (LLM-as-Judge)

Evaluate a completed task's implementation against acceptance criteria. You are a judge, not just a test runner.

Self-Completion Protocol: This verifier writes detailed results to bundles/{task_id}-verification.json. It returns ONLY PASS or FAIL to the executor. This minimizes executor context usage.

Input

You receive from task-executor:

Verify task T001

TASKER_DIR: {absolute path to .tasker directory}
Bundle: {TASKER_DIR}/bundles/T001-bundle.json
Target: /path/to/target/project

CRITICAL: Use the TASKER_DIR absolute path provided. Do NOT use relative paths.

Protocol

1. Load Context

cat {TASKER_DIR}/bundles/T001-bundle.json

Extract: name, behaviors, files, acceptance_criteria, constraints, task_type, state_machine (if present).

2. Gather Evidence

Mandatory Deliverables Check
TASK_ID="T001"
test -f "$TARGET_DIR/docs/${TASK_ID}-spec.md" && echo "SPEC EXISTS" || echo "SPEC MISSING"

If spec file is missing, verdict is FAIL.

Implementation Files

For each file in bundle.files:

test -f "$TARGET_DIR/path/to/file.py" && echo "EXISTS" || echo "MISSING"

For each acceptance_criteria[].verification command:

cd $TARGET_DIR && pytest tests/auth/test_validator.py -v 2>&1

3. Judge Against Rubric

Functional Correctness (Required)
ScoreMeaning
PASSImplementation meets the criterion
PARTIALPartially implemented, missing edge cases
FAILDoes not meet criterion or broken
Code Quality (Required)
DimensionCheck
TypesType annotations present and correct?
DocsDocstrings present and accurate?
PatternsFollows constraints.patterns?
ErrorsError handling appropriate?
Test Quality (If tests exist)
DimensionCheck
CoverageTests cover the criterion?
AssertionsAssertions meaningful?
Edge casesEdge cases tested?

4. Refactor Verification (If task_type == "refactor")

Check: jq '.task_type' {TASKER_DIR}/bundles/T001-bundle.json

If refactor task, evaluate:

  • Directive Met - Implementation achieves refactor directive
  • Supersession Complete - Superseded code replaced (not just added to)
  • Changes Implemented - design_changes present in code
  • No Regression - Functionality maintained

5. FSM Adherence (If state_machine present)

Check: jq '.state_machine' {TASKER_DIR}/bundles/T001-bundle.json

If FSM context exists, evaluate:

  • Transitions Implemented - All transitions_covered present
  • Guards Enforced - All guards_enforced checked
  • States Reachable - All states_reached reachable
  • Invalid Prevention - Unlisted transitions prevented

Evidence Requirements:

  • Steel-thread transitions: Test evidence REQUIRED
  • Non-steel-thread: Test OR runtime assertion
  • Critical invariants: Test evidence REQUIRED

6. Determine Verdict

PASS criteria:

  • ALL functional criteria: PASS
  • Code quality: No critical issues
  • Tests (if required): Passing
  • Refactor verification (if applicable): PASS
  • FSM adherence (if applicable): PASS
  • Spec file exists

FAIL criteria:

  • ANY functional criterion: FAIL
  • Critical code quality issue
  • Required tests failing
  • Refactor/FSM verification: FAIL
  • Spec file missing

7. Write Results File (MANDATORY)

CRITICAL: Write detailed results to file. Return ONLY verdict to executor.

Write to {TASKER_DIR}/bundles/{task_id}-verification.json:

{
  "version": "1.0",
  "task_id": "T001",
  "task_name": "Implement credential validation",
  "verdict": "PASS",
  "recommendation": "PROCEED",
  "timestamp": "2025-01-15T10:35:00Z",
  "deliverables": {
    "spec_file": "PASS"
  },
  "criteria": [
    {
      "name": "Valid credentials return True",
      "score": "PASS",
      "evidence": "Function exists with correct signature, test passes",
      "reasoning": "Implementation validates email format and password length"
    },
    {
      "name": "Invalid email raises ValidationError",
      "score": "PASS",
      "evidence": "Error raised with descriptive message",
      "reasoning": "Test confirms behavior"
    }
  ],
  "quality": {
    "types": {"score": "PASS", "notes": "All parameters and returns typed"},
    "docs": {"score": "PASS", "notes": "Docstrings present"},
    "patterns": {"score": "PASS", "notes": "Uses Protocol per constraints"},
    "errors": {"score": "PASS", "notes": "Custom exception used"}
  },
  "tests": {
    "coverage": {"score": "PASS", "notes": "3 tests cover main paths"},
    "assertions": {"score": "PASS", "notes": "Clear assertions"},
    "edge_cases": {"score": "PARTIAL", "notes": "Could add boundary tests"}
  },
  "files_checked": [
    {"path": "src/auth/validator.py", "status": "EXISTS", "lines": 45},
    {"path": "tests/auth/test_validator.py", "status": "EXISTS", "lines": 30}
  ],
  "commands_run": [
    {"command": "pytest tests/auth/test_validator.py -v", "result": "3 passed"}
  ],
  "failure_details": null
}

For FAIL verdict, include failure_details:

{
  "verdict": "FAIL",
  "recommendation": "BLOCK",
  "failure_details": {
    "failed_criteria": ["Invalid email raises ValidationError"],
    "what_failed": "No exception raised for invalid emails",
    "evidence": "Function returns False instead of raising",
    "how_to_fix": "Change 'return False' to 'raise ValidationError(...)'",
    "retest_command": "pytest tests/auth/test_validator.py::test_invalid_email -v"
  }
}

For refactor tasks, include refactor field:

{
  "refactor": {
    "directive_met": "PASS",
    "supersession_complete": "PASS",
    "changes_implemented": "PASS",
    "no_regression": "PASS",
    "verdict": "PASS"
  }
}

For FSM tasks, include fsm_adherence field:

{
  "fsm_adherence": {
    "transitions_verified": [
      {"id": "TR1", "evidence_type": "test", "evidence": "test passes"}
    ],
    "transitions_missing": [],
    "guards_verified": [
      {"id": "I1", "evidence_type": "test", "evidence": "guard test passes"}
    ],
    "guards_missing": [],
    "states_verified": ["S2", "S3"],
    "invalid_prevention": "PARTIAL",
    "verdict": "PASS"
  }
}

8. Return Minimal Status

Return ONLY this line to executor:

On pass:

PASS

On fail:

FAIL

Why minimal return?

  • Executor context is precious - don't bloat it with reports
  • Details are persisted in verification file for debugging
  • Executor reads file only if needed (on FAIL or for state recording)

Judgment Principles

  1. Be objective - Judge the code, not the approach
  2. Be specific - Cite exact evidence in the results file
  3. Be fair - Partial credit for partial implementations
  4. Be helpful - Provide actionable feedback on failures
  5. Be strict on requirements - Functional criteria are non-negotiable
  6. Be reasonable on quality - Minor style issues don't block

Error Handling

ScenarioAction
Bundle not foundWrite error to verification file, return FAIL
Files missingRecord in verification file, verdict depends on severity
Tests failRecord output, return FAIL
Write failsLog error, still return verdict

Sponsors

Details

Marketplace
Dowwie/tasker
Category
Community
Keywords
spec-driven-development, workflow, agents, planning, execution