Skill: oleg-schmidt/glittercowboy (version 1.0.0)

--- name: gsd description: Get Shit Done - Full project planning and execution workflow. Handles project initialization with deep context gathering, automated research, roadmap creation, phase planning, and execution with verification. user-invocable: true --- <objective> GSD (Get Shit Done) provides a complete workflow for taking projects from idea to execution through systematic planning, research, and phase-based development. **Full workflow port from Claude Code** - Includes: - Deep questioning and context gathering - Automated domain research (4 parallel researchers) - Requirements definition and scoping - Roadmap creation with phase structure - Phase planning with research and verification - Wave-based parallel execution - Goal-backward verification This is the complete GSD system, not a simplified version. </objective> <intake> What would you like to do? **Core workflow commands:** - **new-project** - Initialize a new project with deep context gathering, research, requirements, and roadmap - **plan-phase [N]** - Create execution plans for a phase (with optional research) - **execute-phase [N]** - Execute all plans in a phase with wave-based parallelization - **progress** - Check project status and intelligently route to next action - **debug [issue]** - Systematic debugging with persistent state across context resets - **quick** - Execute ad-hoc tasks with GSD guarantees but skip optional agents - **discuss-phase [N]** - Gather context through adaptive questioning before planning - **verify-work [N]** - Validate built features through conversational UAT - **map-codebase** - Analyze existing codebase for brownfield projects - **pause-work** - Create handoff when pausing mid-phase - **resume-work** - Resume from previous session with full context - **add-todo [desc]** - Capture idea or task for later - **check-todos [area]** - List and work on pending todos - **add-phase <desc>** - Add phase to end of milestone - **insert-phase <after> <desc>** - Insert urgent decimal phase - **remove-phase <N>** - Remove future phase and renumber - **new-milestone [name]** - Start new milestone cycle - **complete-milestone <ver>** - Archive milestone and tag - **audit-milestone [ver]** - Verify milestone completion - **settings** - Configure workflow toggles and model profile **Flags:** - `plan-phase [N] --research` - Force re-research before planning - `plan-phase [N] --skip-research` - Skip research, plan directly - `plan-phase [N] --gaps` - Gap closure mode (after verification finds issues) - `plan-phase [N] --skip-verify` - Skip plan verification loop - `execute-phase [N] --gaps-only` - Execute only gap closure plans **Usage:** - `/gsd new-project` - Start a new project - `/gsd plan-phase 1` - Plan phase 1 - `/gsd execute-phase 1` - Execute phase 1 - `/gsd progress` - Check where you are and what's next - `/gsd debug "button doesn't work"` - Start debugging session - `/gsd quick` - Quick ad-hoc task without full ceremony - Or just tell me what you want and I'll guide you through GSD **What GSD does:** 1. **Deep questioning** - Understand what you're building through conversation 2. **Research** - 4 parallel researchers investigate domain (stack, features, architecture, pitfalls) 3. **Requirements** - Define v1 scope through feature selection 4. **Roadmap** - Derive phases from requirements (not imposed structure) 5. **Phase planning** - Create executable plans with tasks, dependencies, verification 6. **Execution** - Run plans in parallel waves with per-task commits 7. **Verification** - Check must_haves against actual codebase </intake> <routing> Based on user input, route to appropriate workflow: | Intent | Workflow | |--------|----------| | "new project", "initialize", "start project" | workflows/new-project.md | | "new-project" (explicit) | workflows/new-project.md | | "plan phase", "plan-phase", "create plan" | workflows/plan-phase.md | | "execute phase", "execute-phase", "start work" | workflows/execute-phase.md | | "progress", "status", "where am I" | workflows/progress.md | | "debug", "investigate", "bug", "issue" | workflows/debug.md | | "quick", "quick task", "ad-hoc" | workflows/quick.md | | "discuss phase", "discuss-phase", "context" | workflows/discuss-phase.md | | "verify", "verify-work", "UAT", "test" | workflows/verify-work.md | | "map codebase", "map-codebase", "analyze code" | workflows/map-codebase.md | | "pause", "pause-work", "stop work" | workflows/pause-work.md | | "resume", "resume-work", "continue" | workflows/resume-work.md | | "add todo", "add-todo", "capture" | workflows/add-todo.md | | "check todos", "check-todos", "todos", "list todos" | workflows/check-todos.md | | "add phase", "add-phase" | workflows/add-phase.md | | "insert phase", "insert-phase", "urgent phase" | workflows/insert-phase.md | | "remove phase", "remove-phase", "delete phase" | workflows/remove-phase.md | | "new milestone", "new-milestone", "next milestone" | workflows/new-milestone.md | | "complete milestone", "complete-milestone", "archive" | workflows/complete-milestone.md | | "audit milestone", "audit-milestone", "audit" | workflows/audit-milestone.md | | "settings", "config", "configure" | workflows/settings.md | </routing> <architecture> ## Workflow Files Located in `workflows/`: - **new-project.md** - Full project initialization workflow - **plan-phase.md** - Phase planning with research and verification - **execute-phase.md** - Wave-based execution orchestrator - **progress.md** - Status check and intelligent routing to next action - **debug.md** - Systematic debugging with persistent state - **quick.md** - Ad-hoc tasks with GSD guarantees, skip optional agents - **discuss-phase.md** - Gather context through adaptive questioning - **verify-work.md** - Conversational UAT to validate built features - **map-codebase.md** - Parallel codebase analysis for brownfield projects - **pause-work.md** - Create handoff when pausing mid-phase - **resume-work.md** - Resume with full context restoration - **add-todo.md** - Capture ideas/tasks for later - **check-todos.md** - List and work on pending todos - **add-phase.md** - Add phase to end of milestone - **insert-phase.md** - Insert urgent decimal phase - **remove-phase.md** - Remove future phase and renumber - **new-milestone.md** - Start new milestone cycle - **complete-milestone.md** - Archive milestone and tag - **audit-milestone.md** - Verify milestone completion - **settings.md** - Configure workflow toggles ## Agent Files Located in `agents/`: - **gsd-project-researcher.md** - Research domain ecosystem (stack, features, architecture, pitfalls) - **gsd-phase-researcher.md** - Research how to implement a specific phase - **gsd-research-synthesizer.md** - Synthesize parallel research into cohesive SUMMARY.md - **gsd-roadmapper.md** - Create roadmap from requirements and research - **gsd-planner.md** - Create detailed execution plans for a phase - **gsd-plan-checker.md** - Verify plans will achieve phase goal before execution - **gsd-executor.md** - Execute a single plan with task-by-task commits - **gsd-verifier.md** - Verify phase goal achieved by checking must_haves against codebase - **gsd-debugger.md** - Investigate bugs using scientific method with persistent state - **gsd-codebase-mapper.md** - Analyze existing codebase for brownfield projects - **gsd-integration-checker.md** - Verify cross-phase integration and E2E flows ## Reference Files Located in `references/`: - **questioning.md** - Deep questioning techniques and context checklist - **ui-brand.md** - UI/UX principles and brand guidelines ## Templates Located in `templates/`: - **project.md** - PROJECT.md template - **requirements.md** - REQUIREMENTS.md template - **research-project/** - Research output templates (STACK, FEATURES, ARCHITECTURE, PITFALLS, SUMMARY) ## Workflow Pattern GSD uses orchestrator + subagent pattern: 1. **Orchestrator** (workflow) - Stays in main context, spawns subagents, routes flow 2. **Subagents** (agents) - Fresh context, focused task, return structured result 3. **Iteration** - Verification loops (planner → checker → planner) until quality gates pass This allows: - Lean orchestrator context (~15%) - Fresh context per subagent (100%) - Parallel execution (4 researchers, multiple plans in wave) - Verification before wasting execution time </architecture> <success_criteria> - User can initialize new projects via `/gsd new-project` - Full workflow executes: questioning → research → requirements → roadmap - Phase planning includes research and verification loop - Phase execution uses wave-based parallelization - Verification checks must_haves against actual code - `.planning/` directory structure created with all artifacts - Clear next steps provided at each stage </success_criteria>

path: _meta.json
content: {
  "owner": "glittercowboy",
  "slug": "gsd",
  "displayName": "gsd",
  "latest": {
    "version": "1.1.0",
    "publishedAt": 1769804057549,
    "commit": "https://github.com/clawdbot/skills/commit/8259809127dfe2a1ccc98089efc172657a9f4096"
  },
  "history": []
}


path: workflows/add-phase.md
content: ---
name: gsd:add-phase
description: Add phase to end of current milestone in roadmap
argument-hint: "<description>"
allowed-tools:
  - Read
  - Write
  - Bash
---

<objective>
Add a new integer phase to the end of the current milestone in the roadmap.
Automatically calculates next phase number based on existing phases.
</objective>

<process>

## Step 1: Parse Arguments

```bash
if [ -z "$ARGUMENTS" ]; then
  echo "ERROR: Phase description required"
  echo "Usage: /gsd add-phase <description>"
  exit 1
fi
DESCRIPTION="$ARGUMENTS"
```

## Step 2: Load Roadmap

```bash
if [ ! -f .planning/ROADMAP.md ]; then
  echo "ERROR: No roadmap found. Run /gsd new-project first."
  exit 1
fi
```

## Step 3: Calculate Next Phase Number

Find highest integer phase, add 1:

```bash
# Extract phase numbers, find max integer
LAST_PHASE=$(grep -oE "Phase [0-9]+" .planning/ROADMAP.md | grep -oE "[0-9]+" | sort -n | tail -1)
NEXT_PHASE=$((LAST_PHASE + 1))
PADDED=$(printf "%02d" $NEXT_PHASE)
```

## Step 4: Generate Slug

```bash
slug=$(echo "$DESCRIPTION" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/--*/-/g' | sed 's/^-//;s/-$//')
```

## Step 5: Create Phase Directory

```bash
mkdir -p ".planning/phases/${PADDED}-${slug}"
```

## Step 6: Update ROADMAP.md

Add new phase entry at end of current milestone:

```markdown
### Phase {N}: {Description}

**Goal:** [To be planned]
**Depends on:** Phase {N-1}

Plans:
- [ ] TBD (run /gsd plan-phase {N})
```

## Step 7: Update STATE.md

Add to "Roadmap Evolution" section:
```
- Phase {N} added: {description}
```

## Step 8: Confirm

```
---

## ✓ Phase {N} Added

**{description}**
Directory: .planning/phases/{PADDED}-{slug}/

**▶ Next:** `/gsd plan-phase {N}`

---
```

</process>

<success_criteria>
- [ ] Phase directory created
- [ ] ROADMAP.md updated
- [ ] STATE.md updated
- [ ] User informed of next steps
</success_criteria>


path: workflows/add-todo.md
content: ---
name: gsd:add-todo
description: Capture idea or task as todo from current conversation context
argument-hint: "[optional description]"
allowed-tools:
  - Read
  - Write
  - Bash
  - Glob
---

<objective>
Capture an idea, task, or issue that surfaces during a GSD session as a structured todo for later work.

Enables "thought → capture → continue" flow without losing context or derailing current work.
</objective>

<context>
@.planning/STATE.md
</context>

<process>

## Step 1: Ensure Directory Structure

```bash
mkdir -p .planning/todos/pending .planning/todos/done
```

## Step 2: Check Existing Areas

```bash
ls .planning/todos/pending/*.md 2>/dev/null | xargs -I {} grep "^area:" {} 2>/dev/null | cut -d' ' -f2 | sort -u
```

Note existing areas for consistency.

## Step 3: Extract Content

**With arguments:** Use as the title/focus.
- `/gsd add-todo Add auth token refresh` → title = "Add auth token refresh"

**Without arguments:** Ask user: "What todo do you want to capture?"

Formulate:
- `title`: 3-10 word descriptive title (action verb preferred)
- `problem`: What's wrong or why this is needed
- `solution`: Approach hints or "TBD" if just an idea
- `files`: Relevant paths mentioned

## Step 4: Infer Area

Infer area from file paths or content:

| Pattern | Area |
|---------|------|
| `src/api/*`, `api/*` | `api` |
| `src/components/*`, `src/ui/*` | `ui` |
| `src/auth/*`, `auth/*` | `auth` |
| `src/db/*`, `database/*` | `database` |
| `tests/*`, `__tests__/*` | `testing` |
| `docs/*` | `docs` |
| `.planning/*` | `planning` |
| No files or unclear | `general` |

## Step 5: Check for Duplicates

```bash
grep -l -i "[key words from title]" .planning/todos/pending/*.md 2>/dev/null
```

If potential duplicate found:
- Read the existing todo
- Ask: "Similar todo exists: [title]. Skip, replace, or add anyway?"

## Step 6: Create Todo File

```bash
timestamp=$(date "+%Y-%m-%dT%H:%M")
date_prefix=$(date "+%Y-%m-%d")
slug=$(echo "$TITLE" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/--*/-/g' | cut -c1-40)
```

Write to `.planning/todos/pending/${date_prefix}-${slug}.md`:

```markdown
---
created: {timestamp}
title: {title}
area: {area}
files:
  - {file:lines}
---

## Problem

{problem description - enough context for future Claude to understand}

## Solution

{approach hints or "TBD"}
```

## Step 7: Update STATE.md

If `.planning/STATE.md` exists:

```bash
TODO_COUNT=$(ls .planning/todos/pending/*.md 2>/dev/null | wc -l)
```

Update "### Pending Todos" section with new count.

## Step 8: Commit

```bash
COMMIT_PLANNING_DOCS=$(cat .planning/config.json 2>/dev/null | grep -o '"commit_docs"[[:space:]]*:[[:space:]]*[^,}]*' | grep -o 'true\|false' || echo "true")

if [ "$COMMIT_PLANNING_DOCS" = "true" ]; then
  git add ".planning/todos/pending/${date_prefix}-${slug}.md"
  [ -f .planning/STATE.md ] && git add .planning/STATE.md
  git commit -m "docs: capture todo - ${TITLE}

Area: ${AREA}"
fi
```

## Step 9: Confirm

```
---

## ✓ Todo Saved

**.planning/todos/pending/{filename}**

**{title}**
Area: {area}
Files: {count} referenced

---

Would you like to:

1. Continue with current work
2. Add another todo
3. View all todos (`/gsd check-todos`)

---
```

</process>

<anti_patterns>
- Don't create todos for work in current plan
- Don't create elaborate solution sections — captures ideas, not plans
- Don't block on missing information — "TBD" is fine
</anti_patterns>

<success_criteria>
- [ ] Directory structure exists
- [ ] Todo file created with valid frontmatter
- [ ] Problem section has enough context
- [ ] No duplicates (checked and resolved)
- [ ] Area consistent with existing todos
- [ ] STATE.md updated if exists
- [ ] Todo committed to git
</success_criteria>


path: workflows/audit-milestone.md
content: ---
name: gsd:audit-milestone
description: Audit milestone completion against original intent
argument-hint: "[version]"
allowed-tools:
  - Read
  - Glob
  - Grep
  - Bash
  - Write
---

<objective>
Verify milestone achieved its definition of done.
Checks requirements coverage, cross-phase integration, E2E flows.
</objective>

<execution_context>
@/usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-integration-checker.md
</execution_context>

<process>

## Step 1: Determine Scope

```bash
# Get all phase directories
ls -d .planning/phases/*/
```

- Parse version from arguments or detect current
- Identify all phases in scope
- Extract milestone definition of done

## Step 2: Read Phase Verifications

For each phase:
```bash
cat .planning/phases/*-*/*-VERIFICATION.md
```

Extract:
- Status (passed/gaps_found)
- Critical gaps
- Tech debt
- Requirements coverage

Flag unverified phases as blockers.

## Step 3: Spawn Integration Checker

```
sessions_spawn(
    task="First, read /usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-integration-checker.md

Check cross-phase integration and E2E flows for milestone.

Phases: {phase_dirs}
Phase exports: {from SUMMARYs}

Verify wiring and flows.",
    label="Integration check",
    cleanup="keep"
)
```

## Step 4: Check Requirements Coverage

For each requirement in REQUIREMENTS.md:
- Find owning phase
- Check verification status
- Mark: satisfied | partial | unsatisfied

## Step 5: Create Audit Report

Write `.planning/v{version}-MILESTONE-AUDIT.md`:

```yaml
---
milestone: {version}
audited: {timestamp}
status: passed | gaps_found | tech_debt
scores:
  requirements: N/M
  phases: N/M
  integration: N/M
  flows: N/M
gaps:
  requirements: [...]
  integration: [...]
tech_debt:
  - phase: XX-name
    items: [...]
---
```

## Step 6: Route Based on Status

**If passed:**
```
## ✓ Audit Passed

All requirements met, integration verified.

**▶ Next:** `/gsd complete-milestone {version}`
```

**If gaps_found:**
```
## ⚠ Gaps Found

{N} critical issues need resolution.

**▶ Next:** `/gsd plan-phase --gaps` for affected phases
```

**If tech_debt:**
```
## ⚡ Tech Debt Found

No blockers, but {N} items deferred.

**▶ Options:**
- `/gsd complete-milestone` — accept debt
- Address debt first
```

</process>

<success_criteria>
- [ ] All phases checked for VERIFICATION.md
- [ ] Integration checker spawned
- [ ] Requirements coverage calculated
- [ ] Audit report created
- [ ] Clear routing based on status
</success_criteria>


path: workflows/check-todos.md
content: ---
name: gsd:check-todos
description: List pending todos and select one to work on
argument-hint: "[area filter]"
allowed-tools:
  - Read
  - Write
  - Bash
  - Glob
---

<objective>
List all pending todos, allow selection, load full context for the selected todo, and route to appropriate action.

Enables reviewing captured ideas and deciding what to work on next.
</objective>

<context>
@.planning/STATE.md
@.planning/ROADMAP.md
</context>

<process>

## Step 1: Check for Todos

```bash
TODO_COUNT=$(ls .planning/todos/pending/*.md 2>/dev/null | wc -l | tr -d ' ')
echo "Pending todos: $TODO_COUNT"
```

If count is 0:

```
No pending todos.

Todos are captured during work sessions with `/gsd add-todo`.

---

Would you like to:

1. Continue with current phase (`/gsd progress`)
2. Add a todo now (`/gsd add-todo`)

---
```

Exit.

## Step 2: Parse Area Filter

Check for area filter in arguments:
- `/gsd check-todos` → show all
- `/gsd check-todos api` → filter to area:api only

## Step 3: List Todos

```bash
for file in .planning/todos/pending/*.md; do
  created=$(grep "^created:" "$file" | cut -d' ' -f2)
  title=$(grep "^title:" "$file" | cut -d':' -f2- | xargs)
  area=$(grep "^area:" "$file" | cut -d' ' -f2)
  echo "$created|$title|$area|$file"
done | sort
```

Apply area filter if specified. Display as numbered list:

```
## Pending Todos

1. **Add auth token refresh** (api, 2d ago)
2. **Fix modal z-index issue** (ui, 1d ago)
3. **Refactor database connection pool** (database, 5h ago)

---

Reply with a number to view details, or:
- `/gsd check-todos [area]` to filter by area
- `q` to exit

---
```

Format age as relative time (Xd ago, Xh ago).

## Step 4: Handle Selection

Wait for user to reply with a number.

If valid: load selected todo, proceed.
If invalid: "Invalid selection. Reply with a number (1-{N}) or `q` to exit."

## Step 5: Load Full Context

Read the todo file completely. Display:

```
## {title}

**Area:** {area}
**Created:** {date} ({relative time} ago)
**Files:** {list or "None"}

### Problem

{problem section content}

### Solution

{solution section content}
```

## Step 6: Check Roadmap Match

```bash
ls .planning/ROADMAP.md 2>/dev/null && echo "Roadmap exists"
```

If roadmap exists:
- Check if todo's area matches an upcoming phase
- Note any match for action options

## Step 7: Offer Actions

**If todo maps to a roadmap phase:**

```
This todo relates to **Phase {N}: {name}**.

What would you like to do?

1. **Work on it now** — move to done, start working
2. **Add to phase plan** — include when planning Phase {N}
3. **Brainstorm approach** — think through before deciding
4. **Put it back** — return to list
```

**If no roadmap match:**

```
What would you like to do?

1. **Work on it now** — move to done, start working
2. **Create a quick task** — `/gsd quick` with this scope
3. **Brainstorm approach** — think through before deciding
4. **Put it back** — return to list
```

## Step 8: Execute Action

**Work on it now:**
```bash
mv ".planning/todos/pending/{filename}" ".planning/todos/done/"
```
Update STATE.md todo count. Present problem/solution context. Begin work.

**Add to phase plan:**
Note todo reference. Keep in pending. Return to list.

**Create quick task:**
Route to `/gsd quick` with todo context.

**Brainstorm approach:**
Keep in pending. Start discussion about problem and approaches.

**Put it back:**
Return to list.

## Step 9: Update STATE.md

After any action that changes todo count:

```bash
TODO_COUNT=$(ls .planning/todos/pending/*.md 2>/dev/null | wc -l)
```

Update STATE.md "### Pending Todos" section.

## Step 10: Commit if Moved

If todo was moved to done/:

```bash
COMMIT_PLANNING_DOCS=$(cat .planning/config.json 2>/dev/null | grep -o '"commit_docs"[[:space:]]*:[[:space:]]*[^,}]*' | grep -o 'true\|false' || echo "true")

if [ "$COMMIT_PLANNING_DOCS" = "true" ]; then
  git add ".planning/todos/done/{filename}"
  [ -f .planning/STATE.md ] && git add .planning/STATE.md
  git commit -m "docs: start work on todo - {title}"
fi
```

</process>

<anti_patterns>
- Don't delete todos — move to done/ when work begins
- Don't start work without moving to done/ first
</anti_patterns>

<success_criteria>
- [ ] All pending todos listed with title, area, age
- [ ] Area filter applied if specified
- [ ] Selected todo's full context loaded
- [ ] Roadmap context checked for phase match
- [ ] Appropriate actions offered
- [ ] Selected action executed
- [ ] STATE.md updated if todo count changed
- [ ] Changes committed to git
</success_criteria>


path: workflows/complete-milestone.md
content: ---
name: gsd:complete-milestone
description: Archive completed milestone and prepare for next version
argument-hint: "<version>"
allowed-tools:
  - Read
  - Write
  - Bash
---

<objective>
Archive milestone, create git tag, prepare for next version.
Creates historical record in .planning/milestones/.
</objective>

<process>

## Step 0: Pre-flight Check

```bash
# Check for audit
if [ ! -f ".planning/v${VERSION}-MILESTONE-AUDIT.md" ]; then
  echo "⚠ No audit found. Run /gsd audit-milestone first."
fi
```

## Step 1: Verify Readiness

```bash
# Check all phases have SUMMARY.md
for dir in .planning/phases/*/; do
  if ! ls "$dir"*-SUMMARY.md 2>/dev/null | grep -q .; then
    echo "Phase $(basename $dir) incomplete"
  fi
done
```

Present milestone stats, confirm.

## Step 2: Gather Stats

- Count phases, plans, tasks
- Calculate timeline from git log
- Extract key accomplishments from SUMMARYs

## Step 3: Archive Milestone

Create `.planning/milestones/v{version}-ROADMAP.md`:
- Full phase details from ROADMAP.md

Create `.planning/milestones/v{version}-REQUIREMENTS.md`:
- Requirements with outcomes

## Step 4: Update ROADMAP.md

Collapse completed milestone to one-line:

```markdown
## Completed: v{version}

See [v{version}-ROADMAP.md](./milestones/v{version}-ROADMAP.md)
```

## Step 5: Delete REQUIREMENTS.md

```bash
rm .planning/REQUIREMENTS.md
# Fresh one created by /gsd new-milestone
```

## Step 6: Update PROJECT.md

Add "Current State" section with shipped version.

## Step 7: Commit and Tag

```bash
git add .planning/
git commit -m "chore: archive v{version} milestone"
git tag -a "v{version}" -m "{milestone summary}"
```

## Step 8: Done

```
---

## 🎉 Milestone v{version} Complete

Archived to: .planning/milestones/
Git tag: v{version}

**▶ Next:** `/gsd new-milestone` — start next version

---
```

</process>

<success_criteria>
- [ ] All phases verified complete
- [ ] Milestone archived
- [ ] ROADMAP.md collapsed
- [ ] REQUIREMENTS.md deleted
- [ ] Git tag created
</success_criteria>


path: workflows/debug.md
content: ---
name: gsd:debug
description: Systematic debugging with persistent state across context resets
argument-hint: "[issue description]"
allowed-tools:
  - Read
  - Bash
  - Write
  - Edit
---

<objective>
Debug issues using scientific method with subagent isolation.

**Orchestrator role:** Gather symptoms, spawn gsd-debugger agent, handle checkpoints, spawn continuations.

**Why subagent:** Investigation burns context fast (reading files, forming hypotheses, testing). Fresh context per investigation. Main context stays lean for user interaction.
</objective>

<execution_context>
@/usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-debugger.md
</execution_context>

<context>
User's issue: $ARGUMENTS

Check for active sessions:
```bash
ls .planning/debug/*.md 2>/dev/null | grep -v resolved | head -5
```
</context>

<process>

## 0. Resolve Model Profile

Read model profile for agent spawning:

```bash
MODEL_PROFILE=$(cat .planning/config.json 2>/dev/null | grep -o '"model_profile"[[:space:]]*:[[:space:]]*"[^"]*"' | grep -o '"[^"]*"$' | tr -d '"' || echo "balanced")
```

Default to "balanced" if not set.

**Model lookup table:**

| Agent | quality | balanced | budget |
|-------|---------|----------|--------|
| gsd-debugger | opus | sonnet | sonnet |

## 1. Check Active Sessions

If active sessions exist AND no $ARGUMENTS:
- List sessions with status, hypothesis, next action
- User picks number to resume OR describes new issue

If $ARGUMENTS provided OR user describes new issue:
- Continue to symptom gathering

## 2. Gather Symptoms (if new issue)

Ask user for each:

1. **Expected behavior** - What should happen?
2. **Actual behavior** - What happens instead?
3. **Error messages** - Any errors? (paste or describe)
4. **Timeline** - When did this start? Ever worked?
5. **Reproduction** - How do you trigger it?

After all gathered, confirm ready to investigate.

## 3. Spawn gsd-debugger Agent

Generate slug from issue description:
```bash
slug=$(echo "$ISSUE" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/--*/-/g' | sed 's/^-//;s/-$//' | cut -c1-30)
```

Fill prompt and spawn:

```
sessions_spawn(
    task="First, read /usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-debugger.md for your role and instructions.

<objective>
Investigate issue: {slug}

**Summary:** {trigger}
</objective>

<symptoms>
expected: {expected}
actual: {actual}
errors: {errors}
reproduction: {reproduction}
timeline: {timeline}
</symptoms>

<mode>
symptoms_prefilled: true
goal: find_and_fix
</mode>

<debug_file>
Create: .planning/debug/{slug}.md
</debug_file>
",
    label="Debug {slug}",
    model="{debugger_model}",
    cleanup="keep"
)
```

## 4. Handle Agent Return

**If `## ROOT CAUSE FOUND`:**
- Display root cause and evidence summary
- Offer options:
  - "Fix now" - spawn fix subagent
  - "Plan fix" - suggest /gsd plan-phase --gaps
  - "Manual fix" - done

**If `## DEBUG COMPLETE`:**
- Display fix applied and verification
- Show files changed and commit hash

**If `## CHECKPOINT REACHED`:**
- Present checkpoint details to user
- Get user response
- Spawn continuation agent (see step 5)

**If `## INVESTIGATION INCONCLUSIVE`:**
- Show what was checked and eliminated
- Offer options:
  - "Continue investigating" - spawn new agent with additional context
  - "Manual investigation" - done
  - "Add more context" - gather more symptoms, spawn again

## 5. Spawn Continuation Agent (After Checkpoint)

When user responds to checkpoint, spawn fresh agent:

```
sessions_spawn(
    task="First, read /usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-debugger.md for your role and instructions.

<objective>
Continue debugging {slug}. Evidence is in the debug file.
</objective>

<prior_state>
Debug file: .planning/debug/{slug}.md
</prior_state>

<checkpoint_response>
**Type:** {checkpoint_type}
**Response:** {user_response}
</checkpoint_response>

<mode>
goal: find_and_fix
</mode>
",
    label="Continue debug {slug}",
    model="{debugger_model}",
    cleanup="keep"
)
```

</process>

<offer_next>
After debug completes:

```
---

## 🔧 Debug Complete

**Issue:** {slug}
**Root Cause:** {from debug file}
**Fix:** {applied or suggested}

---

**Next:**
- `/gsd progress` — check project status
- `/gsd quick` — quick ad-hoc task

---
```
</offer_next>

<success_criteria>
- [ ] Active sessions checked
- [ ] Symptoms gathered (if new)
- [ ] gsd-debugger spawned with context
- [ ] Checkpoints handled correctly
- [ ] Root cause confirmed before fixing
- [ ] Debug file persists for resume after context reset
</success_criteria>


path: workflows/design-system.md
content: ---
name: gsd:design-system
description: Establish project-wide design foundation through conversation
argument-hint: ""
allowed-tools:
  - Read
  - Write
  - Edit
  - Bash
  - WebFetch
  - AskUserQuestion
---

<objective>
Create a project-wide design system through conversational discovery. This establishes the visual foundation that all UI work in the project respects.

**When to use:**
- Starting a new project with UI
- Before first UI phase
- When visual direction needs definition
- When suggested after /gsd:new-project
</objective>

<execution_context>
@/usr/lib/node_modules/clawdbot/skills/gsd/references/ui-principles.md
@/usr/lib/node_modules/clawdbot/skills/gsd/templates/design-system.md
</execution_context>

<context>
@.planning/DESIGN-SYSTEM.md (if exists)
</context>

<process>

## Phase 1: Display Banner

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 GSD ► DESIGN SYSTEM
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```

## Phase 2: Check Existing

Check if design system exists:

```bash
if [[ -f ".planning/DESIGN-SYSTEM.md" ]]; then
  echo "EXISTS"
else
  echo "NEW"
fi
```

**If exists:**
Ask via AskUserQuestion:
- header: "Existing"
- question: "A design system already exists. What would you like to do?"
- options:
  - "Review and update" - Refine the existing system
  - "Start fresh" - Replace with new design system
  - "Cancel" - Keep current system

If "Cancel" → exit workflow

## Phase 3: Detect Framework

Detect project framework for context:

```bash
if [[ -f "package.json" ]]; then
  if grep -q '"next"' package.json; then
    echo "Next.js (React)"
  elif grep -q '"react"' package.json; then
    echo "React"
  fi
elif ls *.xcodeproj 2>/dev/null || [[ -f "Package.swift" ]]; then
  echo "SwiftUI"
elif [[ -f "requirements.txt" ]]; then
  echo "Python"
else
  echo "HTML/CSS"
fi
```

Store framework for later reference.

## Phase 4: Visual References

Ask via AskUserQuestion:
- header: "References"
- question: "Do you have visual references to guide the design direction?"
- options:
  - "Yes, I have images/screenshots" - I'll provide files or paste images
  - "Yes, I have website URLs" - I'll share sites I like
  - "Both" - I have images and URLs
  - "No, start from description" - I'll describe what I want

**If user provides references:**
- For images: Use Read tool to analyze, extract:
  - Color palette
  - Typography style
  - Spacing patterns
  - Component styles
  - Overall aesthetic

- For URLs: Use WebFetch to analyze, extract:
  - Visual patterns
  - Design language
  - Component approaches

Summarize findings:
"From your references, I see: [summary of extracted aesthetic patterns]"

## Phase 5: Aesthetic Direction

Ask inline (freeform):

"What's the overall vibe you're going for? Describe the feeling you want users to have."

Wait for response.

Then probe with AskUserQuestion:
- header: "Style"
- question: "Which best describes your target aesthetic?"
- options:
  - "Clean & minimal" - Lots of whitespace, subtle, typography-focused
  - "Bold & energetic" - High contrast, strong colors, dynamic
  - "Warm & friendly" - Rounded corners, soft colors, approachable
  - "Dark & sophisticated" - Dark mode primary, elegant, professional

Follow up based on selection to refine.

## Phase 6: Color Exploration

Ask via AskUserQuestion:
- header: "Colors"
- question: "Do you have brand colors, or should we create a palette?"
- options:
  - "I have brand colors" - I'll provide hex values
  - "Create from scratch" - Help me build a palette
  - "Derive from references" - Use colors from my visual references

**If brand colors provided:**
Collect primary, secondary, accent colors.

**If creating from scratch:**
Ask about:
- Preferred hue family (blues, greens, purples, etc.)
- Saturation preference (vibrant vs muted)
- Build complementary palette

**If deriving from references:**
Extract dominant colors from provided images/URLs.

Present proposed palette for approval.

## Phase 7: Typography

Ask via AskUserQuestion:
- header: "Typography"
- question: "Font preference?"
- options:
  - "System fonts" - Native OS fonts (fast, reliable)
  - "Inter / Clean sans" - Modern, highly legible
  - "Custom / I have fonts" - I'll specify fonts
  - "Suggest based on aesthetic" - Match to my chosen style

Build type scale based on selection.

## Phase 8: Component Style

Ask via AskUserQuestion:
- header: "Components"
- question: "Component style preference?"
- options:
  - "Rounded & soft" - Large border radius, gentle shadows
  - "Sharp & precise" - Small or no radius, crisp edges
  - "Mixed" - Rounded buttons, sharp cards (or vice versa)

Determine:
- Border radius scale
- Shadow approach
- Border usage

## Phase 9: Spacing System

Based on aesthetic choices, propose spacing system:

"Based on your [aesthetic] direction, I recommend:
- Base unit: [4px or 8px]
- Scale: [list values]
- Section spacing: [value]"

Ask if adjustments needed.

## Phase 10: Generate Design System

Generate `.planning/DESIGN-SYSTEM.md` using template:
@/usr/lib/node_modules/clawdbot/skills/gsd/templates/design-system.md

Include:
- All discovered aesthetic preferences
- Color palette with tokens
- Typography scale with framework-specific values
- Spacing system
- Component patterns appropriate to detected framework
- Implementation notes for the framework

## Phase 11: Present Result

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 GSD ► DESIGN SYSTEM CREATED ✓
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

## Summary

**Aesthetic:** {description}
**Framework:** {framework}
**Primary color:** {primary}

## File Created

`.planning/DESIGN-SYSTEM.md`

───────────────────────────────────────────────────────────────

## What's Next

This design system will be automatically loaded when you:
- Run `/gsd:discuss-design {phase}` for phase-specific UI
- Plan phases with UI components

To view or edit:
```bash
cat .planning/DESIGN-SYSTEM.md
```

───────────────────────────────────────────────────────────────
```

</process>

<success_criteria>
- [ ] User's aesthetic vision understood
- [ ] Visual references analyzed (if provided)
- [ ] Color palette defined
- [ ] Typography system established
- [ ] Spacing scale determined
- [ ] Component patterns documented
- [ ] DESIGN-SYSTEM.md created
- [ ] User knows how system integrates with GSD
</success_criteria>


path: workflows/diagnose-issues.md
content: ---
name: gsd:diagnose-issues
description: Orchestrate parallel debug agents to investigate UAT gaps and find root causes
argument-hint: ""
allowed-tools:
  - Read
  - Write
  - Bash
  - Task
---

<objective>
Orchestrate parallel debug agents to investigate UAT gaps and find root causes.

After UAT finds gaps, spawn one debug agent per gap. Each agent investigates autonomously with symptoms pre-filled from UAT. Collect root causes, update UAT.md gaps with diagnosis, then hand off to plan-phase --gaps with actual diagnoses.

Orchestrator stays lean: parse gaps, spawn agents, collect results, update UAT.

**Core Principle: Diagnose before planning fixes.**

UAT tells us WHAT is broken (symptoms). Debug agents find WHY (root cause). plan-phase --gaps then creates targeted fixes based on actual causes, not guesses.

Without diagnosis: "Comment doesn't refresh" → guess at fix → maybe wrong
With diagnosis: "Comment doesn't refresh" → "useEffect missing dependency" → precise fix
</objective>

<execution_context>
@/usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-debugger.md
@/usr/lib/node_modules/clawdbot/skills/gsd/templates/debug-subagent-prompt.md
</execution_context>

<context>
DEBUG_DIR=.planning/debug

Debug files use the `.planning/debug/` path (hidden directory with leading dot).

@.planning/STATE.md
</context>

<process>

## Phase 1: Parse Gaps

**Extract gaps from UAT.md:**

Read the "Gaps" section (YAML format):
```yaml
- truth: "Comment appears immediately after submission"
  status: failed
  reason: "User reported: works but doesn't show until I refresh the page"
  severity: major
  test: 2
  artifacts: []
  missing: []
```

For each gap, also read the corresponding test from "Tests" section to get full context.

Build gap list:
```
gaps = [
  {truth: "Comment appears immediately...", severity: "major", test_num: 2, reason: "..."},
  {truth: "Reply button positioned correctly...", severity: "minor", test_num: 5, reason: "..."},
  ...
]
```

## Phase 2: Report Plan

**Report diagnosis plan to user:**

```
## Diagnosing {N} Gaps

Spawning parallel debug agents to investigate root causes:

| Gap (Truth) | Severity |
|-------------|----------|
| Comment appears immediately after submission | major |
| Reply button positioned correctly | minor |
| Delete removes comment | blocker |

Each agent will:
1. Create DEBUG-{slug}.md with symptoms pre-filled
2. Investigate autonomously (read code, form hypotheses, test)
3. Return root cause

This runs in parallel - all gaps investigated simultaneously.
```

## Phase 3: Spawn Agents

**Spawn debug agents in parallel:**

For each gap, fill the debug-subagent-prompt template and spawn:

```
Task(
  prompt=filled_debug_subagent_prompt,
  subagent_type="general-purpose",
  description="Debug: {truth_short}"
)
```

**All agents spawn in single message** (parallel execution).

Template placeholders:
- `{truth}`: The expected behavior that failed
- `{expected}`: From UAT test
- `{actual}`: Verbatim user description from reason field
- `{errors}`: Any error messages from UAT (or "None reported")
- `{reproduction}`: "Test {test_num} in UAT"
- `{timeline}`: "Discovered during UAT"
- `{goal}`: `find_root_cause_only` (UAT flow - plan-phase --gaps handles fixes)
- `{slug}`: Generated from truth

## Phase 4: Collect Results

**Collect root causes from agents:**

Each agent returns with:
```
## ROOT CAUSE FOUND

**Debug Session:** ${DEBUG_DIR}/{slug}.md

**Root Cause:** {specific cause with evidence}

**Evidence Summary:**
- {key finding 1}
- {key finding 2}
- {key finding 3}

**Files Involved:**
- {file1}: {what's wrong}
- {file2}: {related issue}

**Suggested Fix Direction:** {brief hint for plan-phase --gaps}
```

Parse each return to extract:
- root_cause: The diagnosed cause
- files: Files involved
- debug_path: Path to debug session file
- suggested_fix: Hint for gap closure plan

If agent returns `## INVESTIGATION INCONCLUSIVE`:
- root_cause: "Investigation inconclusive - manual review needed"
- Note which issue needs manual attention
- Include remaining possibilities from agent return

## Phase 5: Update UAT

**Update UAT.md gaps with diagnosis:**

For each gap in the Gaps section, add artifacts and missing fields:

```yaml
- truth: "Comment appears immediately after submission"
  status: failed
  reason: "User reported: works but doesn't show until I refresh the page"
  severity: major
  test: 2
  root_cause: "useEffect in CommentList.tsx missing commentCount dependency"
  artifacts:
    - path: "src/components/CommentList.tsx"
      issue: "useEffect missing dependency"
  missing:
    - "Add commentCount to useEffect dependency array"
    - "Trigger re-render when new comment added"
  debug_session: .planning/debug/comment-not-refreshing.md
```

Update status in frontmatter to "diagnosed".

**Check planning config:**

```bash
COMMIT_PLANNING_DOCS=$(cat .planning/config.json 2>/dev/null | grep -o '"commit_docs"[[:space:]]*:[[:space:]]*[^,}]*' | grep -o 'true\|false' || echo "true")
git check-ignore -q .planning 2>/dev/null && COMMIT_PLANNING_DOCS=false
```

**If `COMMIT_PLANNING_DOCS=false`:** Skip git operations

**If `COMMIT_PLANNING_DOCS=true` (default):**

Commit the updated UAT.md:
```bash
git add ".planning/phases/XX-name/{phase}-UAT.md"
git commit -m "docs({phase}): add root causes from diagnosis"
```

## Phase 6: Report Results

**Report diagnosis results and hand off:**

Display:
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 GSD ► DIAGNOSIS COMPLETE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

| Gap (Truth) | Root Cause | Files |
|-------------|------------|-------|
| Comment appears immediately | useEffect missing dependency | CommentList.tsx |
| Reply button positioned correctly | CSS flex order incorrect | ReplyButton.tsx |
| Delete removes comment | API missing auth header | api/comments.ts |

Debug sessions: ${DEBUG_DIR}/

Proceeding to plan fixes...
```

Return to verify-work orchestrator for automatic planning.
Do NOT offer manual next steps - verify-work handles the rest.

</process>

<failure_handling>
**Agent fails to find root cause:**
- Mark gap as "needs manual review"
- Continue with other gaps
- Report incomplete diagnosis

**Agent times out:**
- Check DEBUG-{slug}.md for partial progress
- Can resume with /gsd:debug

**All agents fail:**
- Something systemic (permissions, git, etc.)
- Report for manual investigation
- Fall back to plan-phase --gaps without root causes (less precise)
</failure_handling>

<success_criteria>
- [ ] Gaps parsed from UAT.md
- [ ] Debug agents spawned in parallel
- [ ] Root causes collected from all agents
- [ ] UAT.md gaps updated with artifacts and missing
- [ ] Debug sessions saved to ${DEBUG_DIR}/
- [ ] Hand off to verify-work for automatic planning
</success_criteria>


path: workflows/discovery-phase.md
content: ---
name: gsd:discovery-phase
description: Execute discovery at the appropriate depth level before planning
argument-hint: "<depth: verify|standard|deep>"
allowed-tools:
  - Read
  - Write
  - Bash
  - WebSearch
  - WebFetch
  - AskUserQuestion
---

<objective>
Execute discovery at the appropriate depth level.
Produces DISCOVERY.md (for Level 2-3) that informs PLAN.md creation.

Called from plan-phase.md's mandatory_discovery step with a depth parameter.

NOTE: For comprehensive ecosystem research ("how do experts build this"), use /gsd:research-phase instead, which produces RESEARCH.md.

**Depth Levels:**

| Level | Name         | Time      | Output                                       | When                                      |
| ----- | ------------ | --------- | -------------------------------------------- | ----------------------------------------- |
| 1     | Quick Verify | 2-5 min   | No file, proceed with verified knowledge     | Single library, confirming current syntax |
| 2     | Standard     | 15-30 min | DISCOVERY.md                                 | Choosing between options, new integration |
| 3     | Deep Dive    | 1+ hour   | Detailed DISCOVERY.md with validation gates  | Architectural decisions, novel problems   |
</objective>

<execution_context>
@/usr/lib/node_modules/clawdbot/skills/gsd/templates/discovery.md
</execution_context>

<context>
**Source Hierarchy - MANDATORY: Context7 BEFORE WebSearch**

Claude's training data is 6-18 months stale. Always verify.

1. **Context7 MCP FIRST** - Current docs, no hallucination
2. **Official docs** - When Context7 lacks coverage
3. **WebSearch LAST** - For comparisons and trends only

@.planning/ROADMAP.md
@.planning/STATE.md
</context>

<process>

## Phase 1: Determine Depth

Check the depth parameter passed from plan-phase.md:
- `depth=verify` → Level 1 (Quick Verification)
- `depth=standard` → Level 2 (Standard Discovery)
- `depth=deep` → Level 3 (Deep Dive)

Route to appropriate level workflow below.

## Phase 2a: Level 1 Quick Verify (2-5 minutes)

For: Single known library, confirming syntax/version still correct.

**Process:**

1. Resolve library in Context7:

   ```
   mcp__context7__resolve-library-id with libraryName: "[library]"
   ```

2. Fetch relevant docs:

   ```
   mcp__context7__get-library-docs with:
   - context7CompatibleLibraryID: [from step 1]
   - topic: [specific concern]
   ```

3. Verify:

   - Current version matches expectations
   - API syntax unchanged
   - No breaking changes in recent versions

4. **If verified:** Return to plan-phase.md with confirmation. No DISCOVERY.md needed.

5. **If concerns found:** Escalate to Level 2.

**Output:** Verbal confirmation to proceed, or escalation to Level 2.

## Phase 2b: Level 2 Standard (15-30 minutes)

For: Choosing between options, new external integration.

**Process:**

1. **Identify what to discover:**

   - What options exist?
   - What are the key comparison criteria?
   - What's our specific use case?

2. **Context7 for each option:**

   ```
   For each library/framework:
   - mcp__context7__resolve-library-id
   - mcp__context7__get-library-docs (mode: "code" for API, "info" for concepts)
   ```

3. **Official docs** for anything Context7 lacks.

4. **WebSearch** for comparisons:

   - "[option A] vs [option B] {current_year}"
   - "[option] known issues"
   - "[option] with [our stack]"

5. **Cross-verify:** Any WebSearch finding → confirm with Context7/official docs.

6. **Create DISCOVERY.md** using template structure:

   - Summary with recommendation
   - Key findings per option
   - Code examples from Context7
   - Confidence level (should be MEDIUM-HIGH for Level 2)

7. Return to plan-phase.md.

**Output:** `.planning/phases/XX-name/DISCOVERY.md`

## Phase 2c: Level 3 Deep Dive (1+ hour)

For: Architectural decisions, novel problems, high-risk choices.

**Process:**

1. **Scope the discovery** using template:

   - Define clear scope
   - Define include/exclude boundaries
   - List specific questions to answer

2. **Exhaustive Context7 research:**

   - All relevant libraries
   - Related patterns and concepts
   - Multiple topics per library if needed

3. **Official documentation deep read:**

   - Architecture guides
   - Best practices sections
   - Migration/upgrade guides
   - Known limitations

4. **WebSearch for ecosystem context:**

   - How others solved similar problems
   - Production experiences
   - Gotchas and anti-patterns
   - Recent changes/announcements

5. **Cross-verify ALL findings:**

   - Every WebSearch claim → verify with authoritative source
   - Mark what's verified vs assumed
   - Flag contradictions

6. **Create comprehensive DISCOVERY.md:**

   - Full structure from template
   - Quality report with source attribution
   - Confidence by finding
   - If LOW confidence on any critical finding → add validation checkpoints

7. **Confidence gate:** If overall confidence is LOW, present options before proceeding.

8. Return to plan-phase.md.

**Output:** `.planning/phases/XX-name/DISCOVERY.md` (comprehensive)

## Phase 3: Identify Unknowns

**For Level 2-3:** Define what we need to learn.

Ask: What do we need to learn before we can plan this phase?

- Technology choices?
- Best practices?
- API patterns?
- Architecture approach?

## Phase 4: Create Discovery Scope

Use template structure.

Include:

- Clear discovery objective
- Scoped include/exclude lists
- Source preferences (official docs, Context7, current year)
- Output structure for DISCOVERY.md

## Phase 5: Execute Discovery

Run the discovery:
- Use web search for current info
- Use Context7 MCP for library docs
- Prefer current year sources
- Structure findings per template

## Phase 6: Create Discovery Output

Write `.planning/phases/XX-name/DISCOVERY.md`:
- Summary with recommendation
- Key findings with sources
- Code examples if applicable
- Metadata (confidence, dependencies, open questions, assumptions)

## Phase 7: Confidence Gate

After creating DISCOVERY.md, check confidence level.

If confidence is LOW:
Use AskUserQuestion:

- header: "Low Confidence"
- question: "Discovery confidence is LOW: [reason]. How would you like to proceed?"
- options:
  - "Dig deeper" - Do more research before planning
  - "Proceed anyway" - Accept uncertainty, plan with caveats
  - "Pause" - I need to think about this

If confidence is MEDIUM:
Inline: "Discovery complete (medium confidence). [brief reason]. Proceed to planning?"

If confidence is HIGH:
Proceed directly, just note: "Discovery complete (high confidence)."

## Phase 8: Open Questions Gate

If DISCOVERY.md has open_questions:

Present them inline:
"Open questions from discovery:

- [Question 1]
- [Question 2]

These may affect implementation. Acknowledge and proceed? (yes / address first)"

If "address first": Gather user input on questions, update discovery.

## Phase 9: Offer Next

```
Discovery complete: .planning/phases/XX-name/DISCOVERY.md
Recommendation: [one-liner]
Confidence: [level]

What's next?

1. Discuss phase context (/gsd:discuss-phase [current-phase])
2. Create phase plan (/gsd:plan-phase [current-phase])
3. Refine discovery (dig deeper)
4. Review discovery
```

NOTE: DISCOVERY.md is NOT committed separately. It will be committed with phase completion.

</process>

<success_criteria>
**Level 1 (Quick Verify):**
- [ ] Context7 consulted for library/topic
- [ ] Current state verified or concerns escalated
- [ ] Verbal confirmation to proceed (no files)

**Level 2 (Standard):**
- [ ] Context7 consulted for all options
- [ ] WebSearch findings cross-verified
- [ ] DISCOVERY.md created with recommendation
- [ ] Confidence level MEDIUM or higher
- [ ] Ready to inform PLAN.md creation

**Level 3 (Deep Dive):**
- [ ] Discovery scope defined
- [ ] Context7 exhaustively consulted
- [ ] All WebSearch findings verified against authoritative sources
- [ ] DISCOVERY.md created with comprehensive analysis
- [ ] Quality report with source attribution
- [ ] If LOW confidence findings → validation checkpoints defined
- [ ] Confidence gate passed
- [ ] Ready to inform PLAN.md creation
</success_criteria>


path: workflows/discuss-design.md
content: ---
name: gsd:discuss-design
description: Design phase-specific UI through conversation, then generate mockups
argument-hint: "<phase-number>"
allowed-tools:
  - Read
  - Write
  - Edit
  - Bash
  - Task
  - WebFetch
  - AskUserQuestion
---

<objective>
Design phase-specific UI elements through conversation before planning. Creates mockups for visual review, ensuring design decisions are made before implementation time is spent.

**When to use:**
- Before planning a phase with UI components
- When you want to visualize before coding
- When UI decisions need iteration
- To create component mockups for review
</objective>

<execution_context>
@/usr/lib/node_modules/clawdbot/skills/gsd/references/ui-principles.md
@/usr/lib/node_modules/clawdbot/skills/gsd/references/framework-patterns.md
@/usr/lib/node_modules/clawdbot/skills/gsd/templates/phase-design.md
@/usr/lib/node_modules/clawdbot/skills/gsd/agents/design-specialist.md
</execution_context>

<context>
Phase number: $ARGUMENTS

@.planning/DESIGN-SYSTEM.md (if exists)
@.planning/ROADMAP.md
</context>

<process>

## Phase 1: Display Banner

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 GSD ► DISCUSS DESIGN
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```

## Phase 2: Parse Phase

Extract phase number from argument.

If no phase provided:
```bash
# List available phases
ls -d .planning/phases/*/ 2>/dev/null | head -10
```

Ask via AskUserQuestion:
- header: "Phase"
- question: "Which phase are you designing for?"
- options: [list phases found, or freeform input]

Load phase details from ROADMAP.md:
```bash
grep -A 20 "^## Phase ${PHASE_NUM}" .planning/ROADMAP.md
```

## Phase 3: Load Design System

Check for project design system:

```bash
if [[ -f ".planning/DESIGN-SYSTEM.md" ]]; then
  echo "Design system found - loading as context"
  # Read and summarize key points
else
  echo "No design system - will use ui-principles defaults"
fi
```

If design system exists, load and summarize key constraints:
- Color palette
- Typography scale
- Component patterns
- Framework-specific notes

## Phase 4: Detect Framework

```bash
if [[ -f "package.json" ]]; then
  if grep -q '"next"' package.json; then
    FRAMEWORK="nextjs"
  elif grep -q '"react"' package.json; then
    FRAMEWORK="react"
  fi
elif ls *.xcodeproj 2>/dev/null || [[ -f "Package.swift" ]]; then
  FRAMEWORK="swift"
elif [[ -f "requirements.txt" ]]; then
  FRAMEWORK="python"
else
  FRAMEWORK="html"
fi
```

State: "I'll create {FRAMEWORK} mockups for this phase."

## Phase 5: Phase Context

Display phase summary:

```
## Phase {number}: {name}

**Goal:** {phase goal from roadmap}

**Relevant requirements:**
{requirements that involve UI}
```

Ask inline (freeform):
"What UI elements does this phase need? Describe the screens, components, or interactions you're envisioning."

Wait for response.

## Phase 6: Visual References

Ask via AskUserQuestion:
- header: "References"
- question: "Do you have visual references for this specific phase?"
- options:
  - "Yes, images/screenshots" - I'll provide files
  - "Yes, URLs" - I'll share example sites
  - "Both" - Images and URLs
  - "No, use design system" - Work from existing system

**If references provided:**
Analyze and extract:
- Specific component patterns
- Layout approaches
- Interaction patterns

"From your references, I see: [analysis]"

## Phase 7: Component Discovery

Based on user description, identify components needed.

For each component, ask follow-up questions:
- "For the {component}, what states should it have?"
- "What data does it display?"
- "What actions can users take?"

Use 4-then-check pattern:
After ~4 questions, ask:
- header: "More?"
- question: "More questions about {component}, or move on?"
- options:
  - "More questions" - I want to clarify further
  - "Move on" - I've said enough

Continue until all components understood.

## Phase 8: Layout Discussion

Ask about layout:
- "How should these components be arranged?"
- "What's the primary action on this screen?"
- "How does it behave on mobile?"

Probe for:
- Content hierarchy
- Navigation patterns
- Responsive behavior

## Phase 9: Interaction Discussion

For interactive components:
- "What happens when user clicks {action}?"
- "How should loading states look?"
- "What error states are possible?"

Document:
- User flows
- State transitions
- Feedback patterns

## Phase 10: Design Summary

Present design summary:

```
## Design Summary: Phase {number}

### Components
{list with brief specs}

### Layout
{layout description}

### Interactions
{key interactions}

### States
{loading, error, empty states}
```

Ask via AskUserQuestion:
- header: "Ready?"
- question: "Ready to generate mockups?"
- options:
  - "Generate mockups" - Create the visual files
  - "Adjust design" - I want to change something
  - "Add more" - I have more components to discuss

## Phase 11: Generate Mockups

Create phase directory:
```bash
PHASE_DIR=".planning/phases/${PHASE_NUM}-${PHASE_NAME}"
mkdir -p "$PHASE_DIR/mockups"
```

Spawn design specialist agent:

Task(
  prompt="@/usr/lib/node_modules/clawdbot/skills/gsd/agents/design-specialist.md

  <context>
  **Phase:** {phase_number} - {phase_name}
  **Framework:** {detected_framework}
  **Design System:** @.planning/DESIGN-SYSTEM.md

  **Components to create:**
  {component_specs}

  **Layout:**
  {layout_description}

  **States:**
  {state_requirements}
  </context>

  Create mockups in: {PHASE_DIR}/mockups/",
  subagent_type="general-purpose",
  model="sonnet",
  description="Generate phase mockups"
)

## Phase 12: Review Mockups

After mockups generated, present for review:

```
## Mockups Created

{list of files}

### Preview

Run:
{preview command based on framework}
```

Ask via AskUserQuestion:
- header: "Review"
- question: "Review the mockups. What's the verdict?"
- options:
  - "Approved" - These look good, proceed
  - "Iterate" - I want changes
  - "Major revision" - Start fresh on specific components

**If "Iterate":**
Ask what changes needed, update mockups, re-present.

Loop until "Approved".

## Phase 13: Create Design Doc

Generate phase design document:

Write `.planning/phases/{phase}/${PHASE}-DESIGN.md` using template:
@/usr/lib/node_modules/clawdbot/skills/gsd/templates/phase-design.md

Include:
- All component specs
- Layout decisions
- State definitions
- Mockup file references
- Implementation notes

## Phase 14: Present Result

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 GSD ► DESIGN COMPLETE ✓
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

## Phase {number}: {name}

**Components designed:** {count}
**Mockups created:** {count}
**Status:** Approved

### Files

| File | Purpose |
|------|---------|
| {PHASE}-DESIGN.md | Design specifications |
{mockup_files}

───────────────────────────────────────────────────────────────

## What's Next

The design is ready for implementation.

Option 1: Plan the phase
  /gsd:plan-phase {phase_number}

Option 2: View mockups
  {preview_command}

Option 3: Edit design
  Open .planning/phases/{phase}/${PHASE}-DESIGN.md

The planner will automatically load {PHASE}-DESIGN.md as context.

───────────────────────────────────────────────────────────────
```

</process>

<success_criteria>
- [ ] Phase requirements understood
- [ ] Design system loaded (if exists)
- [ ] All UI components identified
- [ ] Component specs complete with states
- [ ] Layout documented
- [ ] Mockups generated in framework-appropriate format
- [ ] User approved mockups
- [ ] {PHASE}-DESIGN.md created
- [ ] User knows next steps
</success_criteria>


path: workflows/discuss-phase.md
content: ---
name: gsd:discuss-phase
description: Gather phase context through adaptive questioning before planning
argument-hint: "<phase>"
allowed-tools:
  - Read
  - Write
  - Bash
  - Glob
  - Grep
---

<objective>
Extract implementation decisions that downstream agents need — researcher and planner will use CONTEXT.md to know what to investigate and what choices are locked.

**How it works:**
1. Analyze the phase to identify gray areas (UI, UX, behavior, etc.)
2. Present gray areas — user selects which to discuss
3. Deep-dive each selected area until satisfied
4. Create CONTEXT.md with decisions that guide research and planning

**Output:** `{phase}-CONTEXT.md` — decisions clear enough that downstream agents can act without asking the user again
</objective>

<execution_context>
@/usr/lib/node_modules/clawdbot/skills/gsd/templates/context.md
</execution_context>

<context>
Phase number: $ARGUMENTS (required)

**Load project state:**
@.planning/STATE.md

**Load roadmap:**
@.planning/ROADMAP.md
</context>

<process>

## Step 1: Validate Phase

```bash
PHASE=$ARGUMENTS
if [ -z "$PHASE" ]; then
  echo "ERROR: Phase number required. Usage: /gsd discuss-phase 3"
  exit 1
fi

# Normalize phase number
PADDED_PHASE=$(printf "%02d" ${PHASE} 2>/dev/null || echo "${PHASE}")

# Check roadmap for phase
grep -E "Phase ${PHASE}:|Phase ${PADDED_PHASE}:" .planning/ROADMAP.md
```

If not found: Error with available phases.

## Step 2: Check for Existing CONTEXT.md

```bash
PHASE_DIR=$(ls -d .planning/phases/${PADDED_PHASE}-* .planning/phases/${PHASE}-* 2>/dev/null | head -1)
ls "${PHASE_DIR}"/*-CONTEXT.md 2>/dev/null
```

**If CONTEXT.md exists:**
- Show current contents
- Ask: "Update this context, view and continue, or skip?"
- If skip → offer `/gsd plan-phase`

## Step 3: Analyze Phase for Gray Areas

Read the phase goal from ROADMAP.md. Analyze what kind of work this is:

**Domain detection:**
- Something users SEE → layout, density, interactions, states
- Something users CALL → responses, errors, auth, versioning
- Something users RUN → output format, flags, modes, error handling
- Something users READ → structure, tone, depth, flow
- Something being ORGANIZED → criteria, grouping, naming, exceptions

**Generate 3-4 phase-specific gray areas:**

Don't use generic categories. Generate questions specific to THIS phase:

Bad: "UI decisions"
Good: "How dense should the dashboard layout be? (compact vs spacious)"

Bad: "Error handling"
Good: "What happens when the payment fails mid-checkout?"

## Step 4: Present Gray Areas

Show the gray areas:

```
## Gray Areas for Phase {N}: {Name}

I've identified some decisions that would help planning:

1. **{Area 1}** — {brief description}
2. **{Area 2}** — {brief description}
3. **{Area 3}** — {brief description}

Which would you like to discuss? (numbers, or "all")
```

## Step 5: Deep-Dive Each Selected Area

For each selected area:

1. Ask 4 probing questions about the area
2. After answers, ask: "More questions about {area}, or move to next?"
3. If more → ask 4 more, repeat
4. If next → move to next area

**Probing question types:**
- "What should happen when...?"
- "How should this look/feel/behave?"
- "What's the priority between X and Y?"
- "Any specific examples you have in mind?"

## Step 6: Handle Scope Creep

**CRITICAL: Scope guardrail**

If user suggests capabilities outside the phase:

```
That sounds like its own phase. I'll capture it for later:
→ "{user's idea}"

For this phase, let's focus on {phase goal from ROADMAP}.
```

Track deferred ideas to include in CONTEXT.md.

## Step 7: Write CONTEXT.md

Create `${PHASE_DIR}/${PADDED_PHASE}-CONTEXT.md`:

```markdown
# Phase {N}: {Name} - Context

**Gathered:** {date}

## Decisions

{For each area discussed, capture the decisions made}

### {Area 1}
- {Decision 1}
- {Decision 2}

### {Area 2}
- {Decision 1}

## Claude's Discretion

{Things user didn't specify — Claude can decide during planning}

- {Item 1}
- {Item 2}

## Deferred Ideas

{Scope creep captured but not acted on}

- {Idea 1} — suggested during discussion
- {Idea 2}

---
*Context gathered for phase planning*
```

## Step 8: Commit and Offer Next Steps

```bash
git add "${PHASE_DIR}/${PADDED_PHASE}-CONTEXT.md"
git commit -m "docs(${PHASE}): gather phase context

Discussed: {areas discussed}
Decisions captured for planning."
```

Offer next steps:

```
---

## ✓ Context Gathered

**Phase {N}: {Name}**
Context: ${PHASE_DIR}/${PADDED_PHASE}-CONTEXT.md

**▶ Next Up**

`/gsd plan-phase {N}` — create execution plans

---
```

</process>

<success_criteria>
- [ ] Gray areas identified through intelligent analysis
- [ ] User chose which areas to discuss
- [ ] Each selected area explored until satisfied
- [ ] Scope creep redirected to deferred ideas
- [ ] CONTEXT.md captures decisions, not vague vision
- [ ] User knows next steps
</success_criteria>


path: workflows/execute-phase.md
content: ---
name: gsd:execute-phase
description: Execute all plans in a phase with wave-based parallelization
argument-hint: "<phase-number> [--gaps-only]"
allowed-tools:
  - Read
  - Write
  - Edit
  - Glob
  - Grep
  - Bash
  - Task
  - TodoWrite
  - AskUserQuestion
---

<objective>
Execute all plans in a phase using wave-based parallel execution.

Orchestrator stays lean: discover plans, analyze dependencies, group into waves, spawn subagents, collect results. Each subagent loads the full execute-plan context and handles its own plan.

Context budget: ~15% orchestrator, 100% fresh per subagent.
</objective>

<execution_context>
@/usr/lib/node_modules/clawdbot/skills/gsd/references/ui-brand.md
@/usr/lib/node_modules/clawdbot/skills/gsd/workflows/execute-phase.md
</execution_context>

<context>
Phase: $ARGUMENTS

**Flags:**
- `--gaps-only` — Execute only gap closure plans (plans with `gap_closure: true` in frontmatter). Use after verify-work creates fix plans.

@.planning/ROADMAP.md
@.planning/STATE.md
</context>

<process>
0. **Resolve Model Profile**

   Read model profile for agent spawning:
   ```bash
   MODEL_PROFILE=$(cat .planning/config.json 2>/dev/null | grep -o '"model_profile"[[:space:]]*:[[:space:]]*"[^"]*"' | grep -o '"[^"]*"$' | tr -d '"' || echo "balanced")
   ```

   Default to "balanced" if not set.

   **Model lookup table:**

   | Agent | quality | balanced | budget |
   |-------|---------|----------|--------|
   | gsd-executor | opus | sonnet | sonnet |
   | gsd-verifier | sonnet | sonnet | haiku |

   Store resolved models for use in Task calls below.

1. **Validate phase exists**
   - Find phase directory matching argument
   - Count PLAN.md files
   - Error if no plans found

2. **Discover plans**
   - List all *-PLAN.md files in phase directory
   - Check which have *-SUMMARY.md (already complete)
   - If `--gaps-only`: filter to only plans with `gap_closure: true`
   - Build list of incomplete plans

3. **Group by wave**
   - Read `wave` from each plan's frontmatter
   - Group plans by wave number
   - Report wave structure to user

4. **Execute waves**
   For each wave in order:
   - Spawn `gsd-executor` for each plan in wave (parallel Task calls)
   - Wait for completion (Task blocks)
   - Verify SUMMARYs created
   - Proceed to next wave

5. **Aggregate results**
   - Collect summaries from all plans
   - Report phase completion status

6. **Commit any orchestrator corrections**
   Check for uncommitted changes before verification:
   ```bash
   git status --porcelain
   ```

   **If changes exist:** Orchestrator made corrections between executor completions. Commit them:
   ```bash
   git add -u && git commit -m "fix({phase}): orchestrator corrections"
   ```

   **If clean:** Continue to verification.

7. **Verify phase goal**
   Check config: `WORKFLOW_VERIFIER=$(cat .planning/config.json 2>/dev/null | grep -o '"verifier"[[:space:]]*:[[:space:]]*[^,}]*' | grep -o 'true\|false' || echo "true")`

   **If `workflow.verifier` is `false`:** Skip to step 8 (treat as passed).

   **Otherwise:**
   - Spawn `gsd-verifier` subagent with phase directory and goal
   - Verifier checks must_haves against actual codebase (not SUMMARY claims)
   - Creates VERIFICATION.md with detailed report
   - Route by status:
     - `passed` → continue to step 8
     - `human_needed` → present items, get approval or feedback
     - `gaps_found` → present gaps, offer `/gsd:plan-phase {X} --gaps`

8. **Update roadmap and state**
   - Update ROADMAP.md, STATE.md

9. **Update requirements**
   Mark phase requirements as Complete:
   - Read ROADMAP.md, find this phase's `Requirements:` line (e.g., "AUTH-01, AUTH-02")
   - Read REQUIREMENTS.md traceability table
   - For each REQ-ID in this phase: change Status from "Pending" to "Complete"
   - Write updated REQUIREMENTS.md
   - Skip if: REQUIREMENTS.md doesn't exist, or phase has no Requirements line

10. **Commit phase completion**
    Check `COMMIT_PLANNING_DOCS` from config.json (default: true).
    If false: Skip git operations for .planning/ files.
    If true: Bundle all phase metadata updates in one commit:
    - Stage: `git add .planning/ROADMAP.md .planning/STATE.md`
    - Stage REQUIREMENTS.md if updated: `git add .planning/REQUIREMENTS.md`
    - Commit: `docs({phase}): complete {phase-name} phase`

11. **Offer next steps**
    - Route to next action (see `<offer_next>`)
</process>

<offer_next>
Output this markdown directly (not as a code block). Route based on status:

| Status | Route |
|--------|-------|
| `gaps_found` | Route C (gap closure) |
| `human_needed` | Present checklist, then re-route based on approval |
| `passed` + more phases | Route A (next phase) |
| `passed` + last phase | Route B (milestone complete) |

---

**Route A: Phase verified, more phases remain**

🚀 **GSD → Phase {Z} Complete** ✓

**Phase {Z}: {Name}**

{Y} plans executed
Goal verified ✓

**▶ Next Up**

**Phase {Z+1}: {Name}** — {Goal from ROADMAP.md}

`/gsd:discuss-phase {Z+1}` — gather context and clarify approach

`/clear` first → fresh context window

**Also available:**
- `/gsd:plan-phase {Z+1}` — skip discussion, plan directly
- `/gsd:verify-work {Z}` — manual acceptance testing before continuing

---

**Route B: Phase verified, milestone complete**

🚀 **GSD → Milestone Complete** 🎉

**v1.0**

{N} phases completed
All phase goals verified ✓

**▶ Next Up**

**Audit milestone** — verify requirements, cross-phase integration, E2E flows

`/gsd:audit-milestone`

`/clear` first → fresh context window

**Also available:**
- `/gsd:verify-work` — manual acceptance testing
- `/gsd:complete-milestone` — skip audit, archive directly

---

**Route C: Gaps found — need additional planning**

🚀 **GSD → Phase {Z} Gaps Found** ⚠️

**Phase {Z}: {Name}**

Score: {N}/{M} must-haves verified
Report: `.planning/phases/{phase_dir}/{phase}-VERIFICATION.md`

**What's Missing:**

{Extract gap summaries from VERIFICATION.md}

**▶ Next Up**

**Plan gap closure** — create additional plans to complete the phase

`/gsd:plan-phase {Z} --gaps`

`/clear` first → fresh context window

**Also available:**
- `cat .planning/phases/{phase_dir}/{phase}-VERIFICATION.md` — see full report
- `/gsd:verify-work {Z}` — manual testing before planning

---

After user runs /gsd:plan-phase {Z} --gaps:
1. Planner reads VERIFICATION.md gaps
2. Creates plans 04, 05, etc. to close gaps
3. User runs /gsd:execute-phase {Z} again
4. Execute-phase runs incomplete plans (04, 05...)
5. Verifier runs again → loop until passed
</offer_next>

<wave_execution>
**Parallel spawning:**

Before spawning, read file contents. The `@` syntax does not work across Task() boundaries.

```bash
# Read each plan and STATE.md
PLAN_01_CONTENT=$(cat "{plan_01_path}")
PLAN_02_CONTENT=$(cat "{plan_02_path}")
PLAN_03_CONTENT=$(cat "{plan_03_path}")
STATE_CONTENT=$(cat .planning/STATE.md)
```

Spawn all plans in a wave with a single message containing multiple Task calls, with inlined content:

```
sessions_spawn(
    task="Execute plan at {plan_01_path}\n\nPlan:\n{plan_01_content}\n\nProject state:\n{state_content}", subagent_type="gsd-executor", model="{executor_model}")
sessions_spawn(
    task="Execute plan at {plan_02_path}\n\nPlan:\n{plan_02_content}\n\nProject state:\n{state_content}", subagent_type="gsd-executor", model="{executor_model}")
sessions_spawn(
    task="Execute plan at {plan_03_path}\n\nPlan:\n{plan_03_content}\n\nProject state:\n{state_content}", subagent_type="gsd-executor", model="{executor_model}")
```

All three run in parallel. Task tool blocks until all complete.

**No polling.** No background agents. No TaskOutput loops.
</wave_execution>

<checkpoint_handling>
Plans with `autonomous: false` have checkpoints. The execute-phase.md workflow handles the full checkpoint flow:
- Subagent pauses at checkpoint, returns structured state
- Orchestrator presents to user, collects response
- Spawns fresh continuation agent (not resume)

See `@/usr/lib/node_modules/clawdbot/skills/gsd/workflows/execute-phase.md` step `checkpoint_handling` for complete details.
</checkpoint_handling>

<deviation_rules>
During execution, handle discoveries automatically:

1. **Auto-fix bugs** - Fix immediately, document in Summary
2. **Auto-add critical** - Security/correctness gaps, add and document
3. **Auto-fix blockers** - Can't proceed without fix, do it and document
4. **Ask about architectural** - Major structural changes, stop and ask user

Only rule 4 requires user intervention.
</deviation_rules>

<commit_rules>
**Per-Task Commits:**

After each task completes:
1. Stage only files modified by that task
2. Commit with format: `{type}({phase}-{plan}): {task-name}`
3. Types: feat, fix, test, refactor, perf, chore
4. Record commit hash for SUMMARY.md

**Plan Metadata Commit:**

After all tasks in a plan complete:
1. Stage plan artifacts only: PLAN.md, SUMMARY.md
2. Commit with format: `docs({phase}-{plan}): complete [plan-name] plan`
3. NO code files (already committed per-task)

**Phase Completion Commit:**

After all plans in phase complete (step 7):
1. Stage: ROADMAP.md, STATE.md, REQUIREMENTS.md (if updated), VERIFICATION.md
2. Commit with format: `docs({phase}): complete {phase-name} phase`
3. Bundles all phase-level state updates in one commit

**NEVER use:**
- `git add .`
- `git add -A`
- `git add src/` or any broad directory

**Always stage files individually.**
</commit_rules>

<success_criteria>
- [ ] All incomplete plans in phase executed
- [ ] Each plan has SUMMARY.md
- [ ] Phase goal verified (must_haves checked against codebase)
- [ ] VERIFICATION.md created in phase directory
- [ ] STATE.md reflects phase completion
- [ ] ROADMAP.md updated
- [ ] REQUIREMENTS.md updated (phase requirements marked Complete)
- [ ] User informed of next steps
</success_criteria>


path: workflows/execute-plan-auth.md
content: ---
name: gsd:execute-plan-auth
description: Authentication gate handling for execute-plan workflow
argument-hint: ""
allowed-tools:
  - Read
  - Bash
  - AskUserQuestion
---

<objective>
Authentication gate handling for execute-plan.md. Load this file dynamically when an authentication error is encountered during task execution.

**Trigger:** Load this file when CLI/API returns authentication errors:
- "Error: Not authenticated", "Not logged in", "Unauthorized", "401", "403"
- "Authentication required", "Invalid API key", "Missing credentials"
- "Please run {tool} login" or "Set {ENV_VAR} environment variable"
</objective>

<execution_context>
This is an extension to execute-plan.md, loaded dynamically when auth errors occur.
</execution_context>

<context>
Current task context from execute-plan.md
</context>

<process>

## Authentication Gate Protocol

**When you encounter authentication errors during `type="auto"` task execution:**

This is NOT a failure. Authentication gates are expected and normal. Handle them dynamically:

**Authentication error indicators:**

- CLI returns: "Error: Not authenticated", "Not logged in", "Unauthorized", "401", "403"
- API returns: "Authentication required", "Invalid API key", "Missing credentials"
- Command fails with: "Please run {tool} login" or "Set {ENV_VAR} environment variable"

## Phase 1: Recognize Auth Gate

Recognize it's an auth gate - Not a bug, just needs credentials.

## Phase 2: Stop Current Task

STOP current task execution - Don't retry repeatedly.

## Phase 3: Create Dynamic Checkpoint

Present it to user immediately with exact authentication steps:

```
╔═══════════════════════════════════════════════════════╗
║  CHECKPOINT: Action Required                          ║
╚═══════════════════════════════════════════════════════╝

Progress: {X}/{Y} tasks complete
Task: Authenticate {service} CLI

Attempted: {command}
Error: {error message}

What you need to do:
  1. Run: {auth command}
  2. {additional steps}

I'll verify: {verification command}

────────────────────────────────────────────────────────
→ YOUR ACTION: Type "done" when authenticated
────────────────────────────────────────────────────────
```

## Phase 4: Wait for User

Wait for user to authenticate - Let them complete auth flow.

## Phase 5: Verify Authentication

```bash
# Run verification command
{verification_command}
```

Test that credentials are valid.

## Phase 6: Retry Original Task

Resume automation where you left off.

## Phase 7: Continue Normally

Don't treat this as an error in Summary.

## Common Services Auth Patterns

| Service | Auth Error Pattern | Auth Command | Verification |
|---------|-------------------|--------------|--------------|
| Vercel | "Not authenticated" | `vercel login` | `vercel whoami` |
| Netlify | "Not logged in" | `netlify login` | `netlify status` |
| AWS | "Unable to locate credentials" | `aws configure` | `aws sts get-caller-identity` |
| GCP | "Could not load the default credentials" | `gcloud auth login` | `gcloud auth list` |
| Supabase | "Not logged in" | `supabase login` | `supabase projects list` |
| Stripe | "No API key provided" | Set STRIPE_SECRET_KEY | `stripe config --list` |
| Railway | "Not authenticated" | `railway login` | `railway whoami` |
| Fly.io | "Not logged in" | `fly auth login` | `fly auth whoami` |
| Convex | "Not authenticated" | `npx convex login` | `npx convex dashboard` |
| Cloudflare | "Authentication error" | `wrangler login` | `wrangler whoami` |

## Summary Documentation

Document authentication gates as normal flow, not deviations:

```markdown
## Authentication Gates

During execution, I encountered authentication requirements:

1. Task 3: Vercel CLI required authentication
   - Paused for `vercel login`
   - Resumed after authentication
   - Deployed successfully

These are normal gates, not errors.
```

</process>

<key_principles>
- Authentication gates are NOT failures or bugs
- They're expected interaction points during first-time setup
- Handle them gracefully and continue automation after unblocked
- Don't mark tasks as "failed" or "incomplete" due to auth gates
- Document them as normal flow, separate from deviations
</key_principles>

<success_criteria>
- [ ] Auth error recognized as gate, not failure
- [ ] Clear instructions provided to user
- [ ] Verification command run after user completes auth
- [ ] Original task retried and completed
- [ ] Documented in Summary as normal flow
</success_criteria>


path: workflows/execute-plan-checkpoints.md
content: ---
name: gsd:execute-plan-checkpoints
description: Checkpoint handling extension for execute-plan workflow
argument-hint: ""
allowed-tools:
  - Read
  - Write
  - Bash
  - Task
  - AskUserQuestion
---

<objective>
Checkpoint handling extension for execute-plan.md. Load this file when a plan contains checkpoints.

**Detection:**
```bash
grep -q 'type="checkpoint' .planning/phases/XX-name/{phase}-{plan}-PLAN.md && echo "has_checkpoints"
```
</objective>

<execution_context>
This is an extension to execute-plan.md, loaded when plans have checkpoints.
</execution_context>

<context>
Current plan context from execute-plan.md
</context>

<process>

## Phase 1: Parse Segments

**Intelligent segmentation: Parse plan into execution segments.**

Plans are divided into segments by checkpoints. Each segment is routed to optimal execution context (subagent or main).

**1. Check for checkpoints:**

```bash
grep -n "type=\"checkpoint" .planning/phases/XX-name/{phase}-{plan}-PLAN.md
```

**2. Analyze execution strategy:**

**If NO checkpoints found:**

- **Fully autonomous plan** - spawn single subagent for entire plan
- Subagent gets fresh 200k context, executes all tasks, creates SUMMARY, commits
- Main context: Just orchestration (~5% usage)

**If checkpoints found, parse into segments:**

Segment = tasks between checkpoints

**Segment routing rules:**

```
IF segment has no prior checkpoint:
  → SUBAGENT (first segment, nothing to depend on)

IF segment follows checkpoint:human-verify:
  → SUBAGENT (verification is just confirmation)

IF segment follows checkpoint:decision OR checkpoint:human-action:
  → MAIN CONTEXT (next tasks need the decision/result)
```

**3. Execution patterns:**

**Pattern A: Fully autonomous (no checkpoints)**
```
Spawn subagent → execute all tasks → SUMMARY → commit → report back
```

**Pattern B: Segmented with verify-only checkpoints**
```
Segment 1: Spawn subagent → execute → report back
Checkpoint: Main context → verify → continue
Segment 2: Spawn NEW subagent → execute → report back
Aggregate results → SUMMARY → commit
```

**Pattern C: Decision-dependent (must stay in main)**
```
Execute entirely in main context
No segmentation benefit
```

## Phase 2: Init Agent Tracking

Before spawning any subagents, set up tracking infrastructure:

```bash
# Create agent history file if doesn't exist
if [ ! -f .planning/agent-history.json ]; then
  echo '{"version":"1.0","max_entries":50,"entries":[]}' > .planning/agent-history.json
fi

# Clear any stale current-agent-id
rm -f .planning/current-agent-id.txt
```

**Check for interrupted agents:**

```bash
if [ -f .planning/current-agent-id.txt ]; then
  INTERRUPTED_ID=$(cat .planning/current-agent-id.txt)
  echo "Found interrupted agent: $INTERRUPTED_ID"
fi
```

If interrupted agent found:
- Present to user: "Previous session was interrupted. Resume agent [ID] or start fresh?"

## Phase 3: Checkpoint Protocol

When encountering `type="checkpoint:*"`:

**Display checkpoint clearly:**

```
╔═══════════════════════════════════════════════════════╗
║  CHECKPOINT: [Type]                                   ║
╚═══════════════════════════════════════════════════════╝

Progress: {X}/{Y} tasks complete
Task: [task name]

[Display task-specific content based on type]

────────────────────────────────────────────────────────
→ YOUR ACTION: [Resume signal instruction]
────────────────────────────────────────────────────────
```

**For checkpoint:human-verify (90% of checkpoints):**

```
Built: [what was automated - deployed, built, configured]

How to verify:
  1. [Step 1 - exact command/URL]
  2. [Step 2 - what to check]
  3. [Step 3 - expected behavior]

────────────────────────────────────────────────────────
→ YOUR ACTION: Type "approved" or describe issues
────────────────────────────────────────────────────────
```

**For checkpoint:decision (9% of checkpoints):**

```
Decision needed: [decision]

Context: [why this matters]

Options:
1. [option-id]: [name]
   Pros: [pros]
   Cons: [cons]

2. [option-id]: [name]
   Pros: [pros]
   Cons: [cons]

[Resume signal - e.g., "Select: option-id"]
```

**For checkpoint:human-action (1% - rare):**

```
I automated: [what Claude already did via CLI/API]

Need your help with: [the ONE thing with no CLI/API]

Instructions:
[Single unavoidable step]

I'll verify after: [verification]

[Resume signal - e.g., "Type 'done' when complete"]
```

**After displaying:** WAIT for user response. Do NOT hallucinate completion.

## Phase 4: Segment Execution

**For segmented plans (Pattern B):**

Execute segment-by-segment:

```
For each autonomous segment:
  Spawn subagent with prompt: "Execute tasks [X-Y] from plan. Do NOT create SUMMARY or commit."

  Wait for subagent completion
  Track agent_id in current-agent-id.txt
  Update agent-history.json

For each checkpoint:
  Execute in main context
  Wait for user interaction
  Continue to next segment

After all segments complete:
  Aggregate all results
  Create SUMMARY.md
  Commit with all changes
```

## Phase 5: Return for Orchestrator

**When spawned by an orchestrator and hitting a checkpoint:**

Return to the orchestrator with structured checkpoint state:

```markdown
## CHECKPOINT REACHED

**Type:** {type}
**Plan:** {phase}-{plan}
**Progress:** {X}/{Y} tasks complete

### Completed Tasks

| Task | Name | Commit | Files |
|------|------|--------|-------|
| 1 | {name} | {hash} | {files} |

### Current Task

**Task {N}:** {name}
**Status:** blocked
**Blocked by:** {reason}

### Checkpoint Details

{User-facing content}

### Awaiting

{What needed from user}
```

The orchestrator will:
1. Parse your structured return
2. Present checkpoint details to the user
3. Spawn a FRESH continuation agent

</process>

<success_criteria>
- [ ] Plan analyzed for checkpoint structure
- [ ] Execution pattern determined (A/B/C)
- [ ] Agent tracking initialized
- [ ] Checkpoints displayed with clear instructions
- [ ] User response awaited before continuing
- [ ] Segments executed with fresh subagents
- [ ] Results aggregated correctly
</success_criteria>


path: workflows/execute-plan.md
content: ---
name: gsd:execute-plan
description: Execute a phase plan (PLAN.md) and create the outcome summary (SUMMARY.md)
argument-hint: ""
allowed-tools:
  - Read
  - Write
  - Edit
  - Bash
  - Task
  - AskUserQuestion
---

<objective>
Execute a phase prompt (PLAN.md) and create the outcome summary (SUMMARY.md).
</objective>

<execution_context>
@/usr/lib/node_modules/clawdbot/skills/gsd/references/git-integration.md
@/usr/lib/node_modules/clawdbot/skills/gsd/references/deviation-rules.md
@/usr/lib/node_modules/clawdbot/skills/gsd/templates/summary.md
</execution_context>

<context>
Read STATE.md before any operation to load project context.
Read config.json for planning behavior settings.

@.planning/STATE.md
@.planning/config.json

**Conditional Loading:**

**If plan has checkpoints** (detect with: `grep -q 'type="checkpoint' PLAN.md`):
@/usr/lib/node_modules/clawdbot/skills/gsd/workflows/execute-plan-checkpoints.md

**If authentication error encountered during execution:**
@/usr/lib/node_modules/clawdbot/skills/gsd/workflows/execute-plan-auth.md
</context>

<process>

## Phase 1: Resolve Model Profile

Read model profile for agent spawning:

```bash
MODEL_PROFILE=$(cat .planning/config.json 2>/dev/null | grep -o '"model_profile"[[:space:]]*:[[:space:]]*"[^"]*"' | grep -o '"[^"]*"$' | tr -d '"' || echo "balanced")
```

Default to "balanced" if not set.

**Model lookup table:**

| Agent | quality | balanced | budget |
|-------|---------|----------|--------|
| gsd-executor | opus | sonnet | sonnet |

## Phase 2: Load Project State

Before any operation, read project state:

```bash
cat .planning/STATE.md 2>/dev/null
```

**If file exists:** Parse and internalize:

- Current position (phase, plan, status)
- Accumulated decisions (constraints on this execution)
- Blockers/concerns (things to watch for)
- Brief alignment status

**If file missing but .planning/ exists:**

```
STATE.md missing but planning artifacts exist.
Options:
1. Reconstruct from existing artifacts
2. Continue without project state (may lose accumulated context)
```

**If .planning/ doesn't exist:** Error - project not initialized.

**Load planning config:**

```bash
COMMIT_PLANNING_DOCS=$(cat .planning/config.json 2>/dev/null | grep -o '"commit_docs"[[:space:]]*:[[:space:]]*[^,}]*' | grep -o 'true\|false' || echo "true")
git check-ignore -q .planning 2>/dev/null && COMMIT_PLANNING_DOCS=false
```

Store `COMMIT_PLANNING_DOCS` for use in git operations.

## Phase 3: Identify Plan

Find the next plan to execute:
- Check roadmap for "In progress" phase
- Find plans in that phase directory
- Identify first plan without corresponding SUMMARY

```bash
cat .planning/ROADMAP.md
ls .planning/phases/XX-name/*-PLAN.md 2>/dev/null | sort
ls .planning/phases/XX-name/*-SUMMARY.md 2>/dev/null | sort
```

**Logic:**

- If `01-01-PLAN.md` exists but `01-01-SUMMARY.md` doesn't → execute 01-01
- If `01-01-SUMMARY.md` exists but `01-02-SUMMARY.md` doesn't → execute 01-02
- Pattern: Find first PLAN file without matching SUMMARY file

**Check for checkpoints:**

```bash
HAS_CHECKPOINTS=$(grep -q 'type="checkpoint' .planning/phases/XX-name/{phase}-{plan}-PLAN.md && echo "true" || echo "false")
```

If `HAS_CHECKPOINTS=true`, load execute-plan-checkpoints.md for checkpoint handling logic.

## Phase 4: Record Start Time

Record execution start time for performance tracking:

```bash
PLAN_START_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
PLAN_START_EPOCH=$(date +%s)
```

## Phase 5: Load Prompt

Read the plan prompt:
```bash
cat .planning/phases/XX-name/{phase}-{plan}-PLAN.md
```

This IS the execution instructions. Follow it exactly.

**If plan references CONTEXT.md:**
The CONTEXT.md file provides the user's vision for this phase.

## Phase 6: Previous Phase Check

Before executing, check if previous phase had issues:

```bash
ls .planning/phases/*/SUMMARY.md 2>/dev/null | sort -r | head -2 | tail -1
```

If previous phase SUMMARY.md has "Issues Encountered" != "None":

Use AskUserQuestion:

- header: "Previous Issues"
- question: "Previous phase had unresolved items: [summary]. How to proceed?"
- options:
  - "Proceed anyway" - Issues won't block this phase
  - "Address first" - Let's resolve before continuing
  - "Review previous" - Show me the full summary

## Phase 7: Execute

Execute each task in the prompt. **Deviations are normal** - handle them using deviation rules.

1. Read the @context files listed in the prompt

2. For each task:

   **If `type="auto"`:**

   - Work toward task completion
   - **If CLI/API returns authentication error:** Load execute-plan-auth.md
   - **When you discover additional work not in plan:** Apply deviation rules automatically
   - Run the verification
   - Confirm done criteria met
   - **Commit the task** (one commit per task)
   - Track task completion and commit hash for Summary documentation
   - Continue to next task

   **If `type="checkpoint:*"`:**

   - STOP immediately (do not continue to next task)
   - Execute checkpoint_protocol (see execute-plan-checkpoints.md)
   - Wait for user response
   - Only after user confirmation: continue to next task

3. Run overall verification checks from `<verification>` section
4. Confirm all success criteria from `<success_criteria>` section met
5. Document all deviations in Summary

## Phase 8: Task Commit Protocol

After each task completes:

**1. Stage only task-related files:**

```bash
git add src/api/auth.ts
git add src/types/user.ts
```

**2. Commit with proper message:**

Format: `{type}({phase}-{plan}): {task-name-or-description}`

```bash
git commit -m "{type}({phase}-{plan}): {concise task description}

- {key change 1}
- {key change 2}
"
```

**3. Record commit hash:**

```bash
TASK_COMMIT=$(git rev-parse --short HEAD)
```

## Phase 9: Record Completion Time

```bash
PLAN_END_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
PLAN_END_EPOCH=$(date +%s)

DURATION_SEC=$(( PLAN_END_EPOCH - PLAN_START_EPOCH ))
DURATION_MIN=$(( DURATION_SEC / 60 ))
```

## Phase 10: Create Summary

Create `{phase}-{plan}-SUMMARY.md` in phase directory.
Use template: @/usr/lib/node_modules/clawdbot/skills/gsd/templates/summary.md

**Title format:** `# Phase [X] Plan [Y]: [Name] Summary`

The one-liner must be SUBSTANTIVE:

- Good: "JWT auth with refresh rotation using jose library"
- Bad: "Authentication implemented"

**Include performance data:**

- Duration
- Started / Completed timestamps
- Tasks completed count
- Files modified count

## Phase 11: Update STATE.md

Update Current Position section:

```markdown
Phase: [current] of [total] ([phase name])
Plan: [just completed] of [total in phase]
Status: [In progress / Phase complete]
Last activity: [today] - Completed {phase}-{plan}-PLAN.md

Progress: [progress bar]
```

## Phase 12: Update ROADMAP

Update the roadmap file:

**If more plans remain in this phase:**
- Update plan count: "2/3 plans complete"
- Keep phase status as "In progress"

**If this was the last plan in the phase:**
- Mark phase complete: status → "Complete"
- Add completion date

## Phase 13: Git Commit Metadata

Commit execution metadata (SUMMARY + STATE + ROADMAP):

**If `COMMIT_PLANNING_DOCS=true`:**

```bash
git add .planning/phases/XX-name/{phase}-{plan}-SUMMARY.md
git add .planning/STATE.md
git add .planning/ROADMAP.md
git commit -m "docs({phase}-{plan}): complete [plan-name] plan

Tasks completed: [N]/[N]
- [Task 1 name]
- [Task 2 name]

SUMMARY: .planning/phases/XX-name/{phase}-{plan}-SUMMARY.md
"
```

## Phase 14: Offer Next

**Verify remaining work before presenting next steps.**

**Step 1: Count plans and summaries in current phase**

```bash
ls -1 .planning/phases/[current-phase-dir]/*-PLAN.md 2>/dev/null | wc -l
ls -1 .planning/phases/[current-phase-dir]/*-SUMMARY.md 2>/dev/null | wc -l
```

**Route A: More plans remain in this phase**

```
Plan {phase}-{plan} complete.
Summary: .planning/phases/{phase-dir}/{phase}-{plan}-SUMMARY.md

{Y} of {X} plans complete for Phase {Z}.

---

## ▶ Next Up

**{phase}-{next-plan}: [Plan Name]** — [objective]

`/gsd:execute-phase {phase}`

<sub>`/clear` first → fresh context window</sub>

---
```

**Route B: Phase complete, more phases remain**

```
Plan {phase}-{plan} complete.

## ✓ Phase {Z}: {Phase Name} Complete

All {Y} plans finished.

---

## ▶ Next Up

**Phase {Z+1}: {Next Phase Name}** — {Goal}

`/gsd:plan-phase {Z+1}`

<sub>`/clear` first → fresh context window</sub>

---
```

**Route C: Milestone complete**

```
🎉 MILESTONE COMPLETE!

All {N} phases complete! Milestone is 100% done.

---

## ▶ Next Up

**Complete Milestone** — archive and prepare for next

`/gsd:complete-milestone`

---
```

</process>

<success_criteria>
- [ ] All tasks from PLAN.md completed
- [ ] All verifications pass
- [ ] SUMMARY.md created with substantive content
- [ ] STATE.md updated (position, decisions, issues, session)
- [ ] ROADMAP.md updated
- [ ] If codebase map exists: map updated with execution changes
</success_criteria>


path: workflows/insert-phase.md
content: ---
name: gsd:insert-phase
description: Insert urgent work as decimal phase (e.g., 7.1) between existing phases
argument-hint: "<after> <description>"
allowed-tools:
  - Read
  - Write
  - Bash
---

<objective>
Insert a decimal phase for urgent work discovered mid-milestone.
Uses decimal numbering (7.1, 7.2) to preserve logical sequence.
</objective>

<process>

## Step 1: Parse Arguments

```bash
if [ $# -lt 2 ]; then
  echo "ERROR: Both phase number and description required"
  echo "Usage: /gsd insert-phase <after> <description>"
  echo "Example: /gsd insert-phase 7 Fix critical auth bug"
  exit 1
fi

AFTER_PHASE=$1
shift
DESCRIPTION="$*"
```

## Step 2: Verify Target Phase Exists

```bash
grep -q "Phase ${AFTER_PHASE}:" .planning/ROADMAP.md || {
  echo "ERROR: Phase ${AFTER_PHASE} not found"
  exit 1
}
```

## Step 3: Find Next Decimal

```bash
# Find existing decimals (7.1, 7.2, etc.)
EXISTING=$(grep -oE "Phase ${AFTER_PHASE}\.[0-9]+" .planning/ROADMAP.md | grep -oE "\.[0-9]+" | sort -n | tail -1)
if [ -z "$EXISTING" ]; then
  NEXT_DECIMAL=1
else
  NEXT_DECIMAL=$((${EXISTING#.} + 1))
fi
DECIMAL_PHASE="${AFTER_PHASE}.${NEXT_DECIMAL}"
PADDED=$(printf "%02d.%d" $AFTER_PHASE $NEXT_DECIMAL)
```

## Step 4: Generate Slug

```bash
slug=$(echo "$DESCRIPTION" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/--*/-/g' | sed 's/^-//;s/-$//')
```

## Step 5: Create Phase Directory

```bash
mkdir -p ".planning/phases/${PADDED}-${slug}"
```

## Step 6: Update ROADMAP.md

Insert after target phase with (INSERTED) marker:

```markdown
### Phase {N.M}: {Description} (INSERTED)

**Goal:** [Urgent work - to be planned]
**Depends on:** Phase {N}

Plans:
- [ ] TBD (run /gsd plan-phase {N.M})
```

## Step 7: Update STATE.md

```
- Phase {N.M} inserted after Phase {N}: {description} (URGENT)
```

## Step 8: Confirm

```
---

## ✓ Phase {N.M} Inserted

**{description}** (URGENT)
After: Phase {N}
Directory: .planning/phases/{PADDED}-{slug}/

**▶ Next:** `/gsd plan-phase {N.M}`

---
```

</process>

<success_criteria>
- [ ] Decimal phase created
- [ ] ROADMAP.md updated with (INSERTED) marker
- [ ] Phase inserted in correct position
- [ ] User informed of next steps
</success_criteria>


path: workflows/list-phase-assumptions.md
content: ---
name: gsd:list-phase-assumptions
description: Surface Claude's assumptions about a phase before planning
argument-hint: "<phase-number>"
allowed-tools:
  - Read
  - Bash
  - AskUserQuestion
---

<objective>
Surface Claude's assumptions about a phase before planning, enabling users to correct misconceptions early.

Key difference from discuss-phase: This is ANALYSIS of what Claude thinks, not INTAKE of what user knows. No file output - purely conversational to prompt discussion.
</objective>

<execution_context>
No external references needed - this is analysis based on project context.
</execution_context>

<context>
Phase number: $ARGUMENTS (required)

@.planning/ROADMAP.md
@.planning/STATE.md
</context>

<process>

## Phase 1: Validate Phase

**If argument missing:**

```
Error: Phase number required.

Usage: /gsd:list-phase-assumptions [phase-number]
Example: /gsd:list-phase-assumptions 3
```

Exit workflow.

**If argument provided:**
Validate phase exists in roadmap:

```bash
cat .planning/ROADMAP.md | grep -i "Phase ${PHASE}"
```

**If phase not found:**

```
Error: Phase ${PHASE} not found in roadmap.

Available phases:
[list phases from roadmap]
```

Exit workflow.

**If phase found:**
Parse phase details from roadmap:

- Phase number
- Phase name
- Phase description/goal
- Any scope details mentioned

Continue to analyze phase.

## Phase 2: Analyze Phase

Based on roadmap description and project context, identify assumptions across five areas:

**1. Technical Approach:**
What libraries, frameworks, patterns, or tools would Claude use?
- "I'd use X library because..."
- "I'd follow Y pattern because..."
- "I'd structure this as Z because..."

**2. Implementation Order:**
What would Claude build first, second, third?
- "I'd start with X because it's foundational"
- "Then Y because it depends on X"
- "Finally Z because..."

**3. Scope Boundaries:**
What's included vs excluded in Claude's interpretation?
- "This phase includes: A, B, C"
- "This phase does NOT include: D, E, F"
- "Boundary ambiguities: G could go either way"

**4. Risk Areas:**
Where does Claude expect complexity or challenges?
- "The tricky part is X because..."
- "Potential issues: Y, Z"
- "I'd watch out for..."

**5. Dependencies:**
What does Claude assume exists or needs to be in place?
- "This assumes X from previous phases"
- "External dependencies: Y, Z"
- "This will be consumed by..."

Be honest about uncertainty. Mark assumptions with confidence levels:
- "Fairly confident: ..." (clear from roadmap)
- "Assuming: ..." (reasonable inference)
- "Unclear: ..." (could go multiple ways)

## Phase 3: Present Assumptions

Present assumptions in a clear, scannable format:

```
## My Assumptions for Phase ${PHASE}: ${PHASE_NAME}

### Technical Approach
[List assumptions about how to implement]

### Implementation Order
[List assumptions about sequencing]

### Scope Boundaries
**In scope:** [what's included]
**Out of scope:** [what's excluded]
**Ambiguous:** [what could go either way]

### Risk Areas
[List anticipated challenges]

### Dependencies
**From prior phases:** [what's needed]
**External:** [third-party needs]
**Feeds into:** [what future phases need from this]

---

**What do you think?**

Are these assumptions accurate? Let me know:
- What I got right
- What I got wrong
- What I'm missing
```

Wait for user response.

## Phase 4: Gather Feedback

**If user provides corrections:**

Acknowledge the corrections:

```
Key corrections:
- [correction 1]
- [correction 2]

This changes my understanding significantly. [Summarize new understanding]
```

**If user confirms assumptions:**

```
Assumptions validated.
```

Continue to offer next steps.

## Phase 5: Offer Next

Present next steps:

```
What's next?

1. Discuss context (/gsd:discuss-phase ${PHASE}) - Let me ask you questions to build comprehensive context

2. Plan this phase (/gsd:plan-phase ${PHASE}) - Create detailed execution plans

3. Re-examine assumptions - I'll analyze again with your corrections

4. Done for now
```

Wait for user selection.

If "Discuss context": Note that CONTEXT.md will incorporate any corrections discussed here
If "Plan this phase": Proceed knowing assumptions are understood
If "Re-examine": Return to analyze phase with updated understanding

</process>

<success_criteria>
- [ ] Phase number validated against roadmap
- [ ] Assumptions surfaced across five areas: technical approach, implementation order, scope, risks, dependencies
- [ ] Confidence levels marked where appropriate
- [ ] "What do you think?" prompt presented
- [ ] User feedback acknowledged
- [ ] Clear next steps offered
</success_criteria>


path: workflows/map-codebase.md
content: ---
name: gsd:map-codebase
description: Analyze codebase with parallel mapper agents to produce .planning/codebase/ documents
argument-hint: "[optional: specific area to map, e.g., 'api' or 'auth']"
allowed-tools:
  - Read
  - Bash
  - Glob
  - Grep
  - Write
---

<objective>
Analyze existing codebase using parallel gsd-codebase-mapper agents to produce structured codebase documents.

Each mapper agent explores a focus area and **writes documents directly** to `.planning/codebase/`. The orchestrator only receives confirmations, keeping context usage minimal.

Output: .planning/codebase/ folder with 7 structured documents about the codebase state.
</objective>

<execution_context>
@/usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-codebase-mapper.md
</execution_context>

<context>
Focus area: $ARGUMENTS (optional - if provided, tells agents to focus on specific subsystem)

**This command can run:**
- Before /gsd new-project (brownfield codebases) - creates codebase map first
- After /gsd new-project (greenfield codebases) - updates codebase map as code evolves
- Anytime to refresh codebase understanding
</context>

<when_to_use>
**Use map-codebase for:**
- Brownfield projects before initialization (understand existing code first)
- Refreshing codebase map after significant changes
- Onboarding to an unfamiliar codebase
- Before major refactoring (understand current state)

**Skip map-codebase for:**
- Greenfield projects with no code yet (nothing to map)
- Trivial codebases (<5 files)
</when_to_use>

<process>

## Step 1: Check for Existing Codebase Map

```bash
if [ -d .planning/codebase ]; then
  echo "Codebase map already exists:"
  ls -la .planning/codebase/
  echo ""
  echo "Options: refresh (overwrite), skip, or view"
fi
```

If exists: Ask user to refresh, skip, or view existing.

## Step 2: Create Directory Structure

```bash
mkdir -p .planning/codebase
```

## Step 3: Resolve Model Profile

```bash
MODEL_PROFILE=$(cat .planning/config.json 2>/dev/null | grep -o '"model_profile"[[:space:]]*:[[:space:]]*"[^"]*"' | grep -o '"[^"]*"$' | tr -d '"' || echo "balanced")
```

**Model lookup table:**

| Agent | quality | balanced | budget |
|-------|---------|----------|--------|
| gsd-codebase-mapper | sonnet | sonnet | haiku |

## Step 4: Spawn 4 Parallel Mapper Agents

Display:
```
Mapping codebase with 4 parallel agents...
  → tech (STACK.md, INTEGRATIONS.md)
  → arch (ARCHITECTURE.md, STRUCTURE.md)
  → quality (CONVENTIONS.md, TESTING.md)
  → concerns (CONCERNS.md)
```

Spawn all 4 in parallel:

```
sessions_spawn(
    task="First, read /usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-codebase-mapper.md for your role and instructions.

<focus>tech</focus>

Analyze the codebase technology stack and external integrations.
Write directly to:
- .planning/codebase/STACK.md
- .planning/codebase/INTEGRATIONS.md

Return confirmation only (not document contents).
",
    label="Map codebase: tech",
    model="{mapper_model}",
    cleanup="keep"
)

sessions_spawn(
    task="First, read /usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-codebase-mapper.md for your role and instructions.

<focus>arch</focus>

Analyze the codebase architecture and file structure.
Write directly to:
- .planning/codebase/ARCHITECTURE.md
- .planning/codebase/STRUCTURE.md

Return confirmation only (not document contents).
",
    label="Map codebase: arch",
    model="{mapper_model}",
    cleanup="keep"
)

sessions_spawn(
    task="First, read /usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-codebase-mapper.md for your role and instructions.

<focus>quality</focus>

Analyze the codebase coding conventions and testing patterns.
Write directly to:
- .planning/codebase/CONVENTIONS.md
- .planning/codebase/TESTING.md

Return confirmation only (not document contents).
",
    label="Map codebase: quality",
    model="{mapper_model}",
    cleanup="keep"
)

sessions_spawn(
    task="First, read /usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-codebase-mapper.md for your role and instructions.

<focus>concerns</focus>

Analyze the codebase for technical debt and issues.
Write directly to:
- .planning/codebase/CONCERNS.md

Return confirmation only (not document contents).
",
    label="Map codebase: concerns",
    model="{mapper_model}",
    cleanup="keep"
)
```

## Step 5: Verify All Documents Created

After agents complete:

```bash
echo "Verifying codebase documents..."
for doc in STACK INTEGRATIONS ARCHITECTURE STRUCTURE CONVENTIONS TESTING CONCERNS; do
  if [ -f ".planning/codebase/${doc}.md" ]; then
    lines=$(wc -l < ".planning/codebase/${doc}.md")
    echo "✓ ${doc}.md (${lines} lines)"
  else
    echo "✗ ${doc}.md MISSING"
  fi
done
```

If any missing: Report which agents failed.

## Step 6: Commit Codebase Map

```bash
git add .planning/codebase/
git commit -m "docs: map existing codebase

Created 7 codebase documents:
- STACK.md, INTEGRATIONS.md (tech)
- ARCHITECTURE.md, STRUCTURE.md (arch)
- CONVENTIONS.md, TESTING.md (quality)
- CONCERNS.md (concerns)"
```

## Step 7: Offer Next Steps

```
---

## ✓ Codebase Mapped

**.planning/codebase/** created with 7 documents:

| Document | Lines | Focus |
|----------|-------|-------|
| STACK.md | {N} | Languages, frameworks, dependencies |
| INTEGRATIONS.md | {N} | External services, APIs |
| ARCHITECTURE.md | {N} | Patterns, layers, data flow |
| STRUCTURE.md | {N} | Directory layout, key files |
| CONVENTIONS.md | {N} | Coding standards, style |
| TESTING.md | {N} | Test setup, patterns |
| CONCERNS.md | {N} | Tech debt, issues |

**▶ Next Up**

`/gsd new-project` — initialize project with codebase context

---
```

</process>

<success_criteria>
- [ ] .planning/codebase/ directory created
- [ ] All 7 codebase documents written by mapper agents
- [ ] Documents follow template structure
- [ ] Parallel agents completed without errors
- [ ] Codebase map committed
- [ ] User knows next steps
</success_criteria>


path: workflows/new-milestone.md
content: ---
name: gsd:new-milestone
description: Start a new milestone cycle — update PROJECT.md and route to requirements
argument-hint: "[milestone name]"
allowed-tools:
  - Read
  - Write
  - Bash
---

<objective>
Start a new milestone through unified flow: questioning → research → requirements → roadmap.
Brownfield equivalent of new-project. Project exists, this adds next milestone.
</objective>

<process>

## Step 1: Load Context

```bash
cat .planning/PROJECT.md
cat .planning/MILESTONES.md 2>/dev/null
cat .planning/STATE.md
```

- Extract what shipped previously
- Note pending todos and blockers

## Step 2: Gather Milestone Goals

If no arguments, ask: "What do you want to build next?"

Explore:
- Target features
- Priorities
- Constraints
- Scope boundaries

## Step 3: Determine Version

Parse last version from MILESTONES.md:
- v1.0 → suggest v1.1
- Or v2.0 for major changes

Confirm with user.

## Step 4: Update PROJECT.md

Add section:

```markdown
## Current Milestone: v{X.Y} {Name}

**Goal:** {One sentence}

**Target features:**
- {Feature 1}
- {Feature 2}
```

## Step 5: Update STATE.md

```markdown
## Current Position

Phase: Not started (defining requirements)
Status: Defining requirements
Last activity: {today} — Milestone v{X.Y} started
```

## Step 6: Commit

```bash
git add .planning/PROJECT.md .planning/STATE.md
git commit -m "docs: start milestone v{X.Y} {Name}"
```

## Step 7: Research Decision

Ask: "Research domain for new features?"
- Yes → spawn 4 parallel researchers (focus on NEW features only)
- No → proceed to requirements

## Step 8: Route to Requirements

Continue with requirements definition (same as new-project Phase 7).

## Step 9: Route to Roadmap

Spawn gsd-roadmapper with:
- Phase numbering continues from last milestone
- Focus on NEW requirements only

## Step 10: Done

```
---

## ✓ Milestone v{X.Y} Initialized

**{Name}**

{N} phases | {M} requirements

**▶ Next:** `/gsd plan-phase {first-phase}`

---
```

</process>

<success_criteria>
- [ ] PROJECT.md updated with new milestone
- [ ] STATE.md reset for new milestone
- [ ] Research completed (if selected)
- [ ] Requirements defined
- [ ] Roadmap created (continues phase numbering)
</success_criteria>


path: workflows/new-project-full.md
content: ---
name: gsd:new-project-full
description: Initialize a new project with deep context gathering and PROJECT.md (extended version)
allowed-tools:
  - Read
  - Write
  - Bash
  - Task
  - AskUserQuestion
---

<objective>

Initialize a new project through unified flow: questioning → research (optional) → requirements → roadmap.

This is the most leveraged moment in any project. Deep questioning here means better plans, better execution, better outcomes. One command takes you from idea to ready-for-planning.

**Creates:**
- `.planning/PROJECT.md` — project context
- `.planning/config.json` — workflow preferences
- `.planning/research/` — domain research (optional)
- `.planning/REQUIREMENTS.md` — scoped requirements
- `.planning/ROADMAP.md` — phase structure
- `.planning/STATE.md` — project memory

**After this command:** Run `/gsd plan-phase 1` to start execution.

</objective>

<execution_context>

Need to port:
- references/questioning.md
- references/ui-brand.md
- templates/project.md
- templates/requirements.md

</execution_context>

<process>

[Full workflow from original - to be continued in next message due to length]

</process>


path: workflows/new-project.md
content: ---
name: gsd:new-project
description: Initialize a new project with deep context gathering and PROJECT.md
allowed-tools:
  - Read
  - Bash
  - Write
  - Task
  - AskUserQuestion
---

<objective>

Initialize a new project through unified flow: questioning → research (optional) → requirements → roadmap.

This is the most leveraged moment in any project. Deep questioning here means better plans, better execution, better outcomes. One command takes you from idea to ready-for-planning.

**Creates:**
- `.planning/PROJECT.md` — project context
- `.planning/config.json` — workflow preferences
- `.planning/research/` — domain research (optional)
- `.planning/REQUIREMENTS.md` — scoped requirements
- `.planning/ROADMAP.md` — phase structure
- `.planning/STATE.md` — project memory

**After this command:** Run `/gsd:plan-phase 1` to start execution.

</objective>

<execution_context>

@/usr/lib/node_modules/clawdbot/skills/gsd/references/questioning.md
@/usr/lib/node_modules/clawdbot/skills/gsd/references/ui-brand.md
@/usr/lib/node_modules/clawdbot/skills/gsd/templates/project.md
@/usr/lib/node_modules/clawdbot/skills/gsd/templates/requirements.md

</execution_context>

<process>

## Phase 1: Setup

**MANDATORY FIRST STEP — Execute these checks before ANY user interaction:**

1. **Abort if project exists:**
   ```bash
   [ -f .planning/PROJECT.md ] && echo "ERROR: Project already initialized. Use /gsd:progress" && exit 1
   ```

2. **Initialize git repo in THIS directory** (required even if inside a parent repo):
   ```bash
   if [ -d .git ] || [ -f .git ]; then
       echo "Git repo exists in current directory"
   else
       git init
       echo "Initialized new git repo"
   fi
   ```

3. **Detect existing code (brownfield detection):**
   ```bash
   CODE_FILES=$(find . -name "*.ts" -o -name "*.js" -o -name "*.py" -o -name "*.go" -o -name "*.rs" -o -name "*.swift" -o -name "*.java" 2>/dev/null | grep -v node_modules | grep -v .git | head -20)
   HAS_PACKAGE=$([ -f package.json ] || [ -f requirements.txt ] || [ -f Cargo.toml ] || [ -f go.mod ] || [ -f Package.swift ] && echo "yes")
   HAS_CODEBASE_MAP=$([ -d .planning/codebase ] && echo "yes")
   ```

   **You MUST run all bash commands above using the Bash tool before proceeding.**

## Phase 2: Brownfield Offer

**If existing code detected and .planning/codebase/ doesn't exist:**

Check the results from setup step:
- If `CODE_FILES` is non-empty OR `HAS_PACKAGE` is "yes"
- AND `HAS_CODEBASE_MAP` is NOT "yes"

Use AskUserQuestion:
- header: "Existing Code"
- question: "I detected existing code in this directory. Would you like to map the codebase first?"
- options:
  - "Map codebase first" — Run /gsd:map-codebase to understand existing architecture (Recommended)
  - "Skip mapping" — Proceed with project initialization

**If "Map codebase first":**
```
Run `/gsd:map-codebase` first, then return to `/gsd:new-project`
```
Exit command.

**If "Skip mapping":** Continue to Phase 3.

**If no existing code detected OR codebase already mapped:** Continue to Phase 3.

## Phase 3: Deep Questioning

**Display stage banner:**

🚀 **GSD → Questioning**

**Open the conversation:**

Ask inline (freeform, NOT AskUserQuestion):

"What do you want to build?"

Wait for their response. This gives you the context needed to ask intelligent follow-up questions.

**Follow the thread:**

Based on what they said, ask follow-up questions that dig into their response. Use AskUserQuestion with options that probe what they mentioned — interpretations, clarifications, concrete examples.

Keep following threads. Each answer opens new threads to explore. Ask about:
- What excited them
- What problem sparked this
- What they mean by vague terms
- What it would actually look like
- What's already decided

Consult `questioning.md` for techniques:
- Challenge vagueness
- Make abstract concrete
- Surface assumptions
- Find edges
- Reveal motivation

**Check context (background, not out loud):**

As you go, mentally check the context checklist from `questioning.md`. If gaps remain, weave questions naturally. Don't suddenly switch to checklist mode.

**Decision gate:**

When you could write a clear PROJECT.md, use AskUserQuestion:

- header: "Ready?"
- question: "I think I understand what you're after. Ready to create PROJECT.md?"
- options:
  - "Create PROJECT.md" — Let's move forward
  - "Keep exploring" — I want to share more / ask me more

If "Keep exploring" — ask what they want to add, or identify gaps and probe naturally.

Loop until "Create PROJECT.md" selected.

## Phase 4: Write PROJECT.md

Synthesize all context into `.planning/PROJECT.md` using the template from `templates/project.md`.

**For greenfield projects:**

Initialize requirements as hypotheses:

```markdown
## Requirements

### Validated

(None yet — ship to validate)

### Active

- [ ] [Requirement 1]
- [ ] [Requirement 2]
- [ ] [Requirement 3]

### Out of Scope

- [Exclusion 1] — [why]
- [Exclusion 2] — [why]
```

All Active requirements are hypotheses until shipped and validated.

**For brownfield projects (codebase map exists):**

Infer Validated requirements from existing code:

1. Read `.planning/codebase/ARCHITECTURE.md` and `STACK.md`
2. Identify what the codebase already does
3. These become the initial Validated set

```markdown
## Requirements

### Validated

- ✓ [Existing capability 1] — existing
- ✓ [Existing capability 2] — existing
- ✓ [Existing capability 3] — existing

### Active

- [ ] [New requirement 1]
- [ ] [New requirement 2]

### Out of Scope

- [Exclusion 1] — [why]
```

**Key Decisions:**

Initialize with any decisions made during questioning:

```markdown
## Key Decisions

| Decision | Rationale | Outcome |
|----------|-----------|---------|
| [Choice from questioning] | [Why] | — Pending |
```

**Last updated footer:**

```markdown
---
*Last updated: [date] after initialization*
```

Do not compress. Capture everything gathered.

**Commit PROJECT.md:**

```bash
mkdir -p .planning
git add .planning/PROJECT.md
git commit -m "$(cat <<'EOF'
docs: initialize project

[One-liner from PROJECT.md What This Is section]
EOF
)"
```

## Phase 5: Workflow Preferences

**Round 1 — Core workflow settings (4 questions):**

```
questions: [
  {
    header: "Mode",
    question: "How do you want to work?",
    multiSelect: false,
    options: [
      { label: "YOLO (Recommended)", description: "Auto-approve, just execute" },
      { label: "Interactive", description: "Confirm at each step" }
    ]
  },
  {
    header: "Depth",
    question: "How thorough should planning be?",
    multiSelect: false,
    options: [
      { label: "Quick", description: "Ship fast (3-5 phases, 1-3 plans each)" },
      { label: "Standard", description: "Balanced scope and speed (5-8 phases, 3-5 plans each)" },
      { label: "Comprehensive", description: "Thorough coverage (8-12 phases, 5-10 plans each)" }
    ]
  },
  {
    header: "Execution",
    question: "Run plans in parallel?",
    multiSelect: false,
    options: [
      { label: "Parallel (Recommended)", description: "Independent plans run simultaneously" },
      { label: "Sequential", description: "One plan at a time" }
    ]
  },
  {
    header: "Git Tracking",
    question: "Commit planning docs to git?",
    multiSelect: false,
    options: [
      { label: "Yes (Recommended)", description: "Planning docs tracked in version control" },
      { label: "No", description: "Keep .planning/ local-only (add to .gitignore)" }
    ]
  }
]
```

**Round 2 — Workflow agents:**

These spawn additional agents during planning/execution. They add tokens and time but improve quality.

| Agent | When it runs | What it does |
|-------|--------------|--------------|
| **Researcher** | Before planning each phase | Investigates domain, finds patterns, surfaces gotchas |
| **Plan Checker** | After plan is created | Verifies plan actually achieves the phase goal |
| **Verifier** | After phase execution | Confirms must-haves were delivered |

All recommended for important projects. Skip for quick experiments.

```
questions: [
  {
    header: "Research",
    question: "Research before planning each phase? (adds tokens/time)",
    multiSelect: false,
    options: [
      { label: "Yes (Recommended)", description: "Investigate domain, find patterns, surface gotchas" },
      { label: "No", description: "Plan directly from requirements" }
    ]
  },
  {
    header: "Plan Check",
    question: "Verify plans will achieve their goals? (adds tokens/time)",
    multiSelect: false,
    options: [
      { label: "Yes (Recommended)", description: "Catch gaps before execution starts" },
      { label: "No", description: "Execute plans without verification" }
    ]
  },
  {
    header: "Verifier",
    question: "Verify work satisfies requirements after each phase? (adds tokens/time)",
    multiSelect: false,
    options: [
      { label: "Yes (Recommended)", description: "Confirm deliverables match phase goals" },
      { label: "No", description: "Trust execution, skip verification" }
    ]
  },
  {
    header: "Planning Quality",
    question: "How thorough should planning agents be?",
    multiSelect: false,
    options: [
      { label: "Balanced (Recommended)", description: "Good quality/cost for planning agents" },
      { label: "Quality", description: "Deeper analysis, higher cost" },
      { label: "Budget", description: "Faster, lower cost" }
    ]
  }
]
```

Create `.planning/config.json` with all settings:

```json
{
  "mode": "yolo|interactive",
  "depth": "quick|standard|comprehensive",
  "parallelization": true|false,
  "commit_docs": true|false,
  "model_profile": "balanced|quality|budget",
  "workflow": {
    "research": true|false,
    "plan_check": true|false,
    "verifier": true|false
  },
  "autopilot": {
    "checkpoint_mode": "queue|skip",
    "max_retries": 3,
    "budget_limit_usd": 0,
    "notify_webhook": "",
    "model": "default"
  }
}
```

**Autopilot settings (defaults shown):**
- `checkpoint_mode`: How to handle plans needing human input
  - `queue`: Write to `.planning/checkpoints/pending/`, continue with other work
  - `skip`: Skip non-autonomous plans entirely
- `max_retries`: Retry count before marking phase as failed (default: 3)
- `budget_limit_usd`: Stop if estimated cost exceeds this (0 = unlimited)
- `notify_webhook`: URL to POST notifications (empty = disabled)

**If commit_docs = No:**
- Set `commit_docs: false` in config.json
- Add `.planning/` to `.gitignore` (create if needed)

**If commit_docs = Yes:**
- Add autopilot transient files to `.gitignore`:
  ```
  # GSD autopilot (transient files)
  .planning/autopilot.sh
  .planning/autopilot.lock
  .planning/logs/
  .planning/checkpoints/
  ```

**Commit config.json:**

```bash
git add .planning/config.json
git commit -m "$(cat <<'EOF'
chore: add project config

Mode: [chosen mode]
Depth: [chosen depth]
Parallelization: [enabled/disabled]
Workflow agents: research=[on/off], plan_check=[on/off], verifier=[on/off]
EOF
)"
```

**Note:** Run `/gsd:settings` anytime to update these preferences.

## Phase 5.5: Resolve Model Profile

Read model profile for agent spawning:

```bash
MODEL_PROFILE=$(cat .planning/config.json 2>/dev/null | grep -o '"model_profile"[[:space:]]*:[[:space:]]*"[^"]*"' | grep -o '"[^"]*"$' | tr -d '"' || echo "balanced")
```

Default to "balanced" if not set.

**Model lookup table:**

| Agent | quality | balanced | budget |
|-------|---------|----------|--------|
| gsd-project-researcher | opus | sonnet | haiku |
| gsd-research-synthesizer | sonnet | sonnet | haiku |
| gsd-roadmapper | opus | sonnet | sonnet |

Store resolved models for use in Task calls below.

## Phase 6: Research Decision

Use AskUserQuestion:
- header: "Research"
- question: "Research the domain ecosystem before defining requirements?"
- options:
  - "Research first (Recommended)" — Discover standard stacks, expected features, architecture patterns
  - "Skip research" — I know this domain well, go straight to requirements

**If "Research first":**

Display stage banner:
🚀 **GSD → Researching**

Researching [domain] ecosystem...

Create research directory:
```bash
mkdir -p .planning/research
```

**Determine milestone context:**

Check if this is greenfield or subsequent milestone:
- If no "Validated" requirements in PROJECT.md → Greenfield (building from scratch)
- If "Validated" requirements exist → Subsequent milestone (adding to existing app)

Display spawning indicator:
```
◆ Spawning 4 researchers in parallel...
  → Stack research
  → Features research
  → Architecture research
  → Pitfalls research
```

Spawn 4 parallel gsd-project-researcher agents with rich context:

```
sessions_spawn(
    task="""First, read /usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-project-researcher.md for your role and instructions.

<research_type>
Project Research — Stack dimension for [domain].
</research_type>

<milestone_context>
[greenfield OR subsequent]

Greenfield: Research the standard stack for building [domain] from scratch.
Subsequent: Research what's needed to add [target features] to an existing [domain] app. Don't re-research the existing system.
</milestone_context>

<question>
What's the standard 2025 stack for [domain]?
</question>

<project_context>
[PROJECT.md summary - core value, constraints, what they're building]
</project_context>

<downstream_consumer>
Your STACK.md feeds into roadmap creation. Be prescriptive:
- Specific libraries with versions
- Clear rationale for each choice
- What NOT to use and why
</downstream_consumer>

<quality_gate>
- [ ] Versions are current (verify with Context7/official docs, not training data)
- [ ] Rationale explains WHY, not just WHAT
- [ ] Confidence levels assigned to each recommendation
</quality_gate>

<output>
Write to: .planning/research/STACK.md
Use template: /usr/lib/node_modules/clawdbot/skills/gsd/templates/research-project/STACK.md
</output>
",
    label="Stack research",
    cleanup="keep")

sessions_spawn(
    task="First, read /usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-project-researcher.md for your role and instructions.

<research_type>
Project Research — Features dimension for [domain].
</research_type>

<milestone_context>
[greenfield OR subsequent]

Greenfield: What features do [domain] products have? What's table stakes vs differentiating?
Subsequent: How do [target features] typically work? What's expected behavior?
</milestone_context>

<question>
What features do [domain] products have? What's table stakes vs differentiating?
</question>

<project_context>
[PROJECT.md summary]
</project_context>

<downstream_consumer>
Your FEATURES.md feeds into requirements definition. Categorize clearly:
- Table stakes (must have or users leave)
- Differentiators (competitive advantage)
- Anti-features (things to deliberately NOT build)
</downstream_consumer>

<quality_gate>
- [ ] Categories are clear (table stakes vs differentiators vs anti-features)
- [ ] Complexity noted for each feature
- [ ] Dependencies between features identified
</quality_gate>

<output>
Write to: .planning/research/FEATURES.md
Use template: /usr/lib/node_modules/clawdbot/skills/gsd/templates/research-project/FEATURES.md
</output>
",
    label="Features research",
    cleanup="keep")

sessions_spawn(
    task="First, read /usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-project-researcher.md for your role and instructions.

<research_type>
Project Research — Architecture dimension for [domain].
</research_type>

<milestone_context>
[greenfield OR subsequent]

Greenfield: How are [domain] systems typically structured? What are major components?
Subsequent: How do [target features] integrate with existing [domain] architecture?
</milestone_context>

<question>
How are [domain] systems typically structured? What are major components?
</question>

<project_context>
[PROJECT.md summary]
</project_context>

<downstream_consumer>
Your ARCHITECTURE.md informs phase structure in roadmap. Include:
- Component boundaries (what talks to what)
- Data flow (how information moves)
- Suggested build order (dependencies between components)
</downstream_consumer>

<quality_gate>
- [ ] Components clearly defined with boundaries
- [ ] Data flow direction explicit
- [ ] Build order implications noted
</quality_gate>

<output>
Write to: .planning/research/ARCHITECTURE.md
Use template: /usr/lib/node_modules/clawdbot/skills/gsd/templates/research-project/ARCHITECTURE.md
</output>
",
    label="Architecture research",
    cleanup="keep")

sessions_spawn(
    task="First, read /usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-project-researcher.md for your role and instructions.

<research_type>
Project Research — Pitfalls dimension for [domain].
</research_type>

<milestone_context>
[greenfield OR subsequent]

Greenfield: What do [domain] projects commonly get wrong? Critical mistakes?
Subsequent: What are common mistakes when adding [target features] to [domain]?
</milestone_context>

<question>
What do [domain] projects commonly get wrong? Critical mistakes?
</question>

<project_context>
[PROJECT.md summary]
</project_context>

<downstream_consumer>
Your PITFALLS.md prevents mistakes in roadmap/planning. For each pitfall:
- Warning signs (how to detect early)
- Prevention strategy (how to avoid)
- Which phase should address it
</downstream_consumer>

<quality_gate>
- [ ] Pitfalls are specific to this domain (not generic advice)
- [ ] Prevention strategies are actionable
- [ ] Phase mapping included where relevant
</quality_gate>

<output>
Write to: .planning/research/PITFALLS.md
Use template: /usr/lib/node_modules/clawdbot/skills/gsd/templates/research-project/PITFALLS.md
</output>
",
    label="Pitfalls research",
    cleanup="keep")
```

After all 4 agents complete, spawn synthesizer to create SUMMARY.md:

```
sessions_spawn(
    task="
<task>
Synthesize research outputs into SUMMARY.md.
</task>

<research_files>
Read these files:
- .planning/research/STACK.md
- .planning/research/FEATURES.md
- .planning/research/ARCHITECTURE.md
- .planning/research/PITFALLS.md
</research_files>

<output>
Write to: .planning/research/SUMMARY.md
Use template: /usr/lib/node_modules/clawdbot/skills/gsd/templates/research-project/SUMMARY.md
Commit after writing.
</output>
",
    label="Synthesize research",
    cleanup="keep")
```

Display research complete banner and key findings:
🚀 **GSD → Research Complete** ✓

**Key Findings:**

**Stack:** [from SUMMARY.md]
**Table Stakes:** [from SUMMARY.md]
**Watch Out For:** [from SUMMARY.md]

Files: `.planning/research/`

**If "Skip research":** Continue to Phase 7.

## Phase 7: Define Requirements

Display stage banner:
🚀 **GSD → Defining Requirements**

**Load context:**

Read PROJECT.md and extract:
- Core value (the ONE thing that must work)
- Stated constraints (budget, timeline, tech limitations)
- Any explicit scope boundaries

**If research exists:** Read research/FEATURES.md and extract feature categories.

**Present features by category:**

```
Here are the features for [domain]:

## Authentication
**Table stakes:**
- Sign up with email/password
- Email verification
- Password reset
- Session management

**Differentiators:**
- Magic link login
- OAuth (Google, GitHub)
- 2FA

**Research notes:** [any relevant notes]

---

## [Next Category]
...
```

**If no research:** Gather requirements through conversation instead.

Ask: "What are the main things users need to be able to do?"

For each capability mentioned:
- Ask clarifying questions to make it specific
- Probe for related capabilities
- Group into categories

**Scope each category:**

For each category, use AskUserQuestion:

- header: "[Category name]"
- question: "Which [category] features are in v1?"
- multiSelect: true
- options:
  - "[Feature 1]" — [brief description]
  - "[Feature 2]" — [brief description]
  - "[Feature 3]" — [brief description]
  - "None for v1" — Defer entire category

Track responses:
- Selected features → v1 requirements
- Unselected table stakes → v2 (users expect these)
- Unselected differentiators → out of scope

**Identify gaps:**

Use AskUserQuestion:
- header: "Additions"
- question: "Any requirements research missed? (Features specific to your vision)"
- options:
  - "No, research covered it" — Proceed
  - "Yes, let me add some" — Capture additions

**Validate core value:**

Cross-check requirements against Core Value from PROJECT.md. If gaps detected, surface them.

**Generate REQUIREMENTS.md:**

Create `.planning/REQUIREMENTS.md` with:
- v1 Requirements grouped by category (checkboxes, REQ-IDs)
- v2 Requirements (deferred)
- Out of Scope (explicit exclusions with reasoning)
- Traceability section (empty, filled by roadmap)

**REQ-ID format:** `[CATEGORY]-[NUMBER]` (AUTH-01, CONTENT-02)

**Requirement quality criteria:**

Good requirements are:
- **Specific and testable:** "User can reset password via email link" (not "Handle password reset")
- **User-centric:** "User can X" (not "System does Y")
- **Atomic:** One capability per requirement (not "User can login and manage profile")
- **Independent:** Minimal dependencies on other requirements

Reject vague requirements. Push for specificity:
- "Handle authentication" → "User can log in with email/password and stay logged in across sessions"
- "Support sharing" → "User can share post via link that opens in recipient's browser"

**Present full requirements list:**

Show every requirement (not counts) for user confirmation:

```
## v1 Requirements

### Authentication
- [ ] **AUTH-01**: User can create account with email/password
- [ ] **AUTH-02**: User can log in and stay logged in across sessions
- [ ] **AUTH-03**: User can log out from any page

### Content
- [ ] **CONT-01**: User can create posts with text
- [ ] **CONT-02**: User can edit their own posts

[... full list ...]

---

Does this capture what you're building? (yes / adjust)
```

If "adjust": Return to scoping.

**Commit requirements:**

```bash
git add .planning/REQUIREMENTS.md
git commit -m "$(cat <<'EOF'
docs: define v1 requirements

[X] requirements across [N] categories
[Y] requirements deferred to v2
EOF
)"
```

## Phase 8: Create Roadmap

Display stage banner:
🚀 **GSD → Creating Roadmap**

◆ Spawning roadmapper...

Spawn gsd-roadmapper agent with context:

```
sessions_spawn(
    task="
<planning_context>

**Project:**
@.planning/PROJECT.md

**Requirements:**
@.planning/REQUIREMENTS.md

**Research (if exists):**
@.planning/research/SUMMARY.md

**Config:**
@.planning/config.json

</planning_context>

<instructions>
Create roadmap:
1. Derive phases from requirements (don't impose structure)
2. Map every v1 requirement to exactly one phase
3. Derive 2-5 success criteria per phase (observable user behaviors)
4. Validate 100% coverage
5. Write files immediately (ROADMAP.md, STATE.md, update REQUIREMENTS.md traceability)
6. Return ROADMAP CREATED with summary

Write files first, then return. This ensures artifacts persist even if context is lost.
</instructions>
",
    label="Create roadmap",
    cleanup="keep")
```

**Handle roadmapper return:**

**If `## ROADMAP BLOCKED`:**
- Present blocker information
- Work with user to resolve
- Re-spawn when resolved

**If `## ROADMAP CREATED`:**

Read the created ROADMAP.md and present it nicely inline:

```
---

## Proposed Roadmap

**[N] phases** | **[X] requirements mapped** | All v1 requirements covered ✓

| # | Phase | Goal | Requirements | Success Criteria |
|---|-------|------|--------------|------------------|
| 1 | [Name] | [Goal] | [REQ-IDs] | [count] |
| 2 | [Name] | [Goal] | [REQ-IDs] | [count] |
| 3 | [Name] | [Goal] | [REQ-IDs] | [count] |
...

### Phase Details

**Phase 1: [Name]**
Goal: [goal]
Requirements: [REQ-IDs]
Success criteria:
1. [criterion]
2. [criterion]
3. [criterion]

**Phase 2: [Name]**
Goal: [goal]
Requirements: [REQ-IDs]
Success criteria:
1. [criterion]
2. [criterion]

[... continue for all phases ...]

---
```

**CRITICAL: Ask for approval before committing:**

Use AskUserQuestion:
- header: "Roadmap"
- question: "Does this roadmap structure work for you?"
- options:
  - "Approve" — Commit and continue
  - "Adjust phases" — Tell me what to change
  - "Review full file" — Show raw ROADMAP.md

**If "Approve":** Continue to commit.

**If "Adjust phases":**
- Get user's adjustment notes
- Re-spawn roadmapper with revision context:
  ```
  sessions_spawn(
    task="
  <revision>
  User feedback on roadmap:
  [user's notes]

  Current ROADMAP.md: @.planning/ROADMAP.md

  Update the roadmap based on feedback. Edit files in place.
  Return ROADMAP REVISED with changes made.
  </revision>
  """,
    label="Revise roadmap",
    cleanup="keep"
)
  ```
- Present revised roadmap
- Loop until user approves

**If "Review full file":** Display raw `cat .planning/ROADMAP.md`, then re-ask.

**Commit roadmap (after approval):**

```bash
git add .planning/ROADMAP.md .planning/STATE.md .planning/REQUIREMENTS.md
git commit -m "$(cat <<'EOF'
docs: create roadmap ([N] phases)

Phases:
1. [phase-name]: [requirements covered]
2. [phase-name]: [requirements covered]
...

All v1 requirements mapped to phases.
EOF
)"
```

## Phase 10: Done

Present completion with next steps:

🚀 **GSD → Project Initialized** ✓

**[Project Name]**

| Artifact       | Location                    |
|----------------|-----------------------------|
| Project        | `.planning/PROJECT.md`      |
| Config         | `.planning/config.json`     |
| Research       | `.planning/research/`       |
| Requirements   | `.planning/REQUIREMENTS.md` |
| Roadmap        | `.planning/ROADMAP.md`      |

**[N] phases** | **[X] requirements** | Ready to build ✓

**Optional:** If your project has UI, establish design foundations first:

`/gsd:design-system` — conversational design system creation

Use AskUserQuestion to offer next steps:

- header: "Next"
- question: "How would you like to proceed?"
- options:
  - "Run autopilot" — Execute entire milestone autonomously (Recommended)
  - "Plan phase 1" — Start with manual phase-by-phase execution
  - "Discuss phase 1" — Gather context before planning
  - "Create design system" — Establish visual foundations first (UI projects)

**If "Run autopilot":**
```
/gsd:autopilot
```
Route to autopilot command.

**If "Plan phase 1":**
```
───────────────────────────────────────────────────────────────

## ▶ Next Up

**Phase 1: [Phase Name]** — [Goal from ROADMAP.md]

/gsd:plan-phase 1

<sub>/clear first → fresh context window</sub>

───────────────────────────────────────────────────────────────
```

**If "Discuss phase 1":**
```
───────────────────────────────────────────────────────────────

## ▶ Next Up

**Phase 1: [Phase Name]** — [Goal from ROADMAP.md]

/gsd:discuss-phase 1 — gather context and clarify approach

<sub>/clear first → fresh context window</sub>

───────────────────────────────────────────────────────────────

**Also available:**
- /gsd:plan-phase 1 — skip discussion, plan directly
- /gsd:autopilot — execute entire milestone autonomously

───────────────────────────────────────────────────────────────
```

**If "Create design system":**
```
───────────────────────────────────────────────────────────────

## ▶ Design System

Establish visual foundations before building UI phases.

/gsd:design-system

<sub>/clear first → fresh context window</sub>

───────────────────────────────────────────────────────────────

After design system is created, continue with:
- /gsd:discuss-design 1 — design phase-specific UI
- /gsd:plan-phase 1 — plan the first phase

───────────────────────────────────────────────────────────────
```

</process>

<output>

- `.planning/PROJECT.md`
- `.planning/config.json`
- `.planning/research/` (if research selected)
  - `STACK.md`
  - `FEATURES.md`
  - `ARCHITECTURE.md`
  - `PITFALLS.md`
  - `SUMMARY.md`
- `.planning/REQUIREMENTS.md`
- `.planning/ROADMAP.md`
- `.planning/STATE.md`

</output>

<success_criteria>

- [ ] .planning/ directory created
- [ ] Git repo initialized
- [ ] Brownfield detection completed
- [ ] Deep questioning completed (threads followed, not rushed)
- [ ] PROJECT.md captures full context → **committed**
- [ ] config.json has workflow mode, depth, parallelization → **committed**
- [ ] Research completed (if selected) — 4 parallel agents spawned → **committed**
- [ ] Requirements gathered (from research or conversation)
- [ ] User scoped each category (v1/v2/out of scope)
- [ ] REQUIREMENTS.md created with REQ-IDs → **committed**
- [ ] gsd-roadmapper spawned with context
- [ ] Roadmap files written immediately (not draft)
- [ ] User feedback incorporated (if any)
- [ ] ROADMAP.md created with phases, requirement mappings, success criteria
- [ ] STATE.md initialized
- [ ] REQUIREMENTS.md traceability updated
- [ ] User knows next step is `/gsd:discuss-phase 1`

**Atomic commits:** Each phase commits its artifacts immediately. If context is lost, artifacts persist.

</success_criteria>


path: workflows/pause-work.md
content: ---
name: gsd:pause-work
description: Create context handoff when pausing work mid-phase
allowed-tools:
  - Read
  - Write
  - Bash
---

<objective>
Create `.continue-here.md` handoff file to preserve complete work state across sessions.

Enables seamless resumption in fresh session with full context restoration.
</objective>

<context>
@.planning/STATE.md
</context>

<process>

## Step 1: Find Current Phase

```bash
# Find most recently modified phase directory
PHASE_DIR=$(ls -td .planning/phases/*/ 2>/dev/null | head -1)
PHASE_NAME=$(basename "$PHASE_DIR")
echo "Current phase: $PHASE_NAME"
```

## Step 2: Gather Complete State

Collect for handoff:

1. **Current position**: Which phase, which plan, which task
2. **Work completed**: What got done this session
3. **Work remaining**: What's left in current plan/phase
4. **Decisions made**: Key decisions and rationale
5. **Blockers/issues**: Anything stuck
6. **Mental context**: The approach, next steps
7. **Files modified**: What's changed but not committed

Ask user for clarifications if needed:
- "What were you working on?"
- "Any blockers or issues?"
- "What should be done next?"

## Step 3: Write Handoff File

Write to `.planning/phases/${PHASE_NAME}/.continue-here.md`:

```markdown
---
phase: {PHASE_NAME}
task: {current_task}
total_tasks: {total}
status: in_progress
last_updated: {timestamp}
---

## Current State

[Where exactly are we? Immediate context]

## Completed Work

- Task 1: [name] - Done
- Task 2: [name] - Done
- Task 3: [name] - In progress, [what's done]

## Remaining Work

- Task 3: [what's left]
- Task 4: Not started
- Task 5: Not started

## Decisions Made

- Decided to use [X] because [reason]
- Chose [approach] over [alternative] because [reason]

## Blockers

- [Blocker 1]: [status/workaround]

## Context

[Mental state, what were you thinking, the plan]

## Next Action

Start with: [specific first action when resuming]
```

Be specific enough for a fresh Claude to understand immediately.

## Step 4: Commit as WIP

```bash
COMMIT_PLANNING_DOCS=$(cat .planning/config.json 2>/dev/null | grep -o '"commit_docs"[[:space:]]*:[[:space:]]*[^,}]*' | grep -o 'true\|false' || echo "true")

if [ "$COMMIT_PLANNING_DOCS" = "true" ]; then
  git add ".planning/phases/${PHASE_NAME}/.continue-here.md"
  git commit -m "wip: ${PHASE_NAME} paused at task ${TASK}/${TOTAL}"
fi
```

## Step 5: Confirm

```
---

## ✓ Handoff Created

**.planning/phases/{PHASE_NAME}/.continue-here.md**

Current state:
- Phase: {PHASE_NAME}
- Task: {X} of {Y}
- Status: in_progress

To resume: `/gsd resume-work`

---
```

</process>

<success_criteria>
- [ ] .continue-here.md created in correct phase directory
- [ ] All sections filled with specific content
- [ ] Committed as WIP
- [ ] User knows location and how to resume
</success_criteria>


path: workflows/plan-phase.md
content: ---
name: gsd:plan-phase
description: Create detailed execution plan for a phase (PLAN.md) with verification loop
argument-hint: "[phase] [--research] [--skip-research] [--gaps] [--skip-verify]"
agent: gsd-planner
allowed-tools:
  - Read
  - Write
  - Bash
  - Glob
  - Grep
  - Task
  - WebFetch
  - mcp__context7__*
---

<execution_context>
@/usr/lib/node_modules/clawdbot/skills/gsd/references/ui-brand.md
</execution_context>

<objective>
Create executable phase prompts (PLAN.md files) for a roadmap phase with integrated research and verification.

**Default flow:** Research (if needed) → Plan → Verify → Done

**Orchestrator role:** Parse arguments, validate phase, research domain (unless skipped or exists), spawn gsd-planner agent, verify plans with gsd-plan-checker, iterate until plans pass or max iterations reached, present results.

**Why subagents:** Research and planning burn context fast. Verification uses fresh context. User sees the flow between agents in main context.
</objective>

<context>
Phase number: $ARGUMENTS (optional - auto-detects next unplanned phase if not provided)

**Flags:**
- `--research` — Force re-research even if RESEARCH.md exists
- `--skip-research` — Skip research entirely, go straight to planning
- `--gaps` — Gap closure mode (reads VERIFICATION.md, skips research)
- `--skip-verify` — Skip planner → checker verification loop

Normalize phase input in step 2 before any directory lookups.
</context>

<process>

## 1. Validate Environment and Resolve Model Profile

```bash
ls .planning/ 2>/dev/null
```

**If not found:** Error - user should run `/gsd:new-project` first.

**Resolve model profile for agent spawning:**

```bash
MODEL_PROFILE=$(cat .planning/config.json 2>/dev/null | grep -o '"model_profile"[[:space:]]*:[[:space:]]*"[^"]*"' | grep -o '"[^"]*"$' | tr -d '"' || echo "balanced")
```

Default to "balanced" if not set.

**Model lookup table:**

| Agent | quality | balanced | budget |
|-------|---------|----------|--------|
| gsd-phase-researcher | opus | sonnet | haiku |
| gsd-planner | opus | opus | sonnet |
| gsd-plan-checker | sonnet | sonnet | haiku |

Store resolved models for use in Task calls below.

## 2. Parse and Normalize Arguments

Extract from $ARGUMENTS:

- Phase number (integer or decimal like `2.1`)
- `--research` flag to force re-research
- `--skip-research` flag to skip research
- `--gaps` flag for gap closure mode
- `--skip-verify` flag to bypass verification loop

**If no phase number:** Detect next unplanned phase from roadmap.

**Normalize phase to zero-padded format:**

```bash
# Normalize phase number (8 → 08, but preserve decimals like 2.1 → 02.1)
if [[ "$PHASE" =~ ^[0-9]+$ ]]; then
  PHASE=$(printf "%02d" "$PHASE")
elif [[ "$PHASE" =~ ^([0-9]+)\.([0-9]+)$ ]]; then
  PHASE=$(printf "%02d.%s" "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}")
fi
```

**Check for existing research and plans:**

```bash
ls .planning/phases/${PHASE}-*/*-RESEARCH.md 2>/dev/null
ls .planning/phases/${PHASE}-*/*-PLAN.md 2>/dev/null
```

## 3. Validate Phase

```bash
grep -A5 "Phase ${PHASE}:" .planning/ROADMAP.md 2>/dev/null
```

**If not found:** Error with available phases. **If found:** Extract phase number, name, description.

## 4. Ensure Phase Directory Exists

```bash
# PHASE is already normalized (08, 02.1, etc.) from step 2
PHASE_DIR=$(ls -d .planning/phases/${PHASE}-* 2>/dev/null | head -1)
if [ -z "$PHASE_DIR" ]; then
  # Create phase directory from roadmap name
  PHASE_NAME=$(grep "Phase ${PHASE}:" .planning/ROADMAP.md | sed 's/.*Phase [0-9]*: //' | tr '[:upper:]' '[:lower:]' | tr ' ' '-')
  mkdir -p ".planning/phases/${PHASE}-${PHASE_NAME}"
  PHASE_DIR=".planning/phases/${PHASE}-${PHASE_NAME}"
fi
```

## 5. Handle Research

**If `--gaps` flag:** Skip research (gap closure uses VERIFICATION.md instead).

**If `--skip-research` flag:** Skip to step 6.

**Check config for research setting:**

```bash
WORKFLOW_RESEARCH=$(cat .planning/config.json 2>/dev/null | grep -o '"research"[[:space:]]*:[[:space:]]*[^,}]*' | grep -o 'true\|false' || echo "true")
```

**If `workflow.research` is `false` AND `--research` flag NOT set:** Skip to step 6.

**Otherwise:**

Check for existing research:

```bash
ls "${PHASE_DIR}"/*-RESEARCH.md 2>/dev/null
```

**If RESEARCH.md exists AND `--research` flag NOT set:**
- Display: `Using existing research: ${PHASE_DIR}/${PHASE}-RESEARCH.md`
- Skip to step 6

**If RESEARCH.md missing OR `--research` flag set:**

Display stage banner:
🚀 **GSD → Researching Phase {X}**

◆ Spawning researcher...

Proceed to spawn researcher

### Spawn gsd-phase-researcher

Gather context for research prompt:

```bash
# Get phase description from roadmap
PHASE_DESC=$(grep -A3 "Phase ${PHASE}:" .planning/ROADMAP.md)

# Get requirements if they exist
REQUIREMENTS=$(cat .planning/REQUIREMENTS.md 2>/dev/null | grep -A100 "## Requirements" | head -50)

# Get prior decisions from STATE.md
DECISIONS=$(grep -A20 "### Decisions Made" .planning/STATE.md 2>/dev/null)

# Get phase context if exists
PHASE_CONTEXT=$(cat "${PHASE_DIR}"/*-CONTEXT.md 2>/dev/null)
```

Fill research prompt and spawn:

```markdown
<objective>
Research how to implement Phase {phase_number}: {phase_name}

Answer: "What do I need to know to PLAN this phase well?"
</objective>

<context>
**Phase description:**
{phase_description}

**Requirements (if any):**
{requirements}

**Prior decisions:**
{decisions}

**Phase context (if any):**
{phase_context}
</context>

<output>
Write research findings to: {phase_dir}/{phase}-RESEARCH.md
</output>
```

```
sessions_spawn(
    task="First, read /usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-phase-researcher.md for your role and instructions.\n\n" + research_prompt,
    label="Research Phase {phase}",
    cleanup="keep"
)
```

### Handle Researcher Return

**`## RESEARCH COMPLETE`:**
- Display: `Research complete. Proceeding to planning...`
- Continue to step 6

**`## RESEARCH BLOCKED`:**
- Display blocker information
- Offer: 1) Provide more context, 2) Skip research and plan anyway, 3) Abort
- Wait for user response

## 6. Check Existing Plans

```bash
ls "${PHASE_DIR}"/*-PLAN.md 2>/dev/null
```

**If exists:** Offer: 1) Continue planning (add more plans), 2) View existing, 3) Replan from scratch. Wait for response.

## 7. Read Context Files

Read and store context file contents for the planner agent. The `@` syntax does not work across Task() boundaries - content must be inlined.

```bash
# Read required files
STATE_CONTENT=$(cat .planning/STATE.md)
ROADMAP_CONTENT=$(cat .planning/ROADMAP.md)

# Read optional files (empty string if missing)
REQUIREMENTS_CONTENT=$(cat .planning/REQUIREMENTS.md 2>/dev/null)
CONTEXT_CONTENT=$(cat "${PHASE_DIR}"/*-CONTEXT.md 2>/dev/null)
RESEARCH_CONTENT=$(cat "${PHASE_DIR}"/*-RESEARCH.md 2>/dev/null)

# Design context (from /gsd:discuss-design)
DESIGN_CONTENT=$(cat "${PHASE_DIR}"/*-DESIGN.md 2>/dev/null)
DESIGN_SYSTEM_CONTENT=$(cat .planning/DESIGN-SYSTEM.md 2>/dev/null)

# Gap closure files (only if --gaps mode)
VERIFICATION_CONTENT=$(cat "${PHASE_DIR}"/*-VERIFICATION.md 2>/dev/null)
UAT_CONTENT=$(cat "${PHASE_DIR}"/*-UAT.md 2>/dev/null)
```

**If DESIGN.md exists:** Display `Using phase design: ${PHASE_DIR}/${PHASE}-DESIGN.md`

## 8. Spawn gsd-planner Agent

Display stage banner:
🚀 **GSD → Planning Phase {X}**

◆ Spawning planner...

Fill prompt with inlined content and spawn:

```markdown
<planning_context>

**Phase:** {phase_number}
**Mode:** {standard | gap_closure}

**Project State:**
{state_content}

**Roadmap:**
{roadmap_content}

**Requirements (if exists):**
{requirements_content}

**Phase Context (if exists):**
{context_content}

**Research (if exists):**
{research_content}

**Design System (if exists):**
{design_system_content}

**Phase Design (if exists):**
{design_content}

**Gap Closure (if --gaps mode):**
{verification_content}
{uat_content}

</planning_context>

<downstream_consumer>
Output consumed by /gsd:execute-phase
Plans must be executable prompts with:

- Frontmatter (wave, depends_on, files_modified, autonomous)
- Tasks in XML format
- Verification criteria
- must_haves for goal-backward verification
</downstream_consumer>

<quality_gate>
Before returning PLANNING COMPLETE:

- [ ] PLAN.md files created in phase directory
- [ ] Each plan has valid frontmatter
- [ ] Tasks are specific and actionable
- [ ] Dependencies correctly identified
- [ ] Waves assigned for parallel execution
- [ ] must_haves derived from phase goal
</quality_gate>
```

```
sessions_spawn(
    task="First, read /usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-planner.md for your role and instructions.\n\n",
    label="Plan Phase {phase}",
    cleanup="keep"
)
```

## 9. Handle Planner Return

Parse planner output:

**`## PLANNING COMPLETE`:**
- Display: `Planner created {N} plan(s). Files on disk.`
- If `--skip-verify`: Skip to step 13
- Check config: `WORKFLOW_PLAN_CHECK=$(cat .planning/config.json 2>/dev/null | grep -o '"plan_check"[[:space:]]*:[[:space:]]*[^,}]*' | grep -o 'true\|false' || echo "true")`
- If `workflow.plan_check` is `false`: Skip to step 13
- Otherwise: Proceed to step 10

**`## CHECKPOINT REACHED`:**
- Present to user, get response, spawn continuation (see step 12)

**`## PLANNING INCONCLUSIVE`:**
- Show what was attempted
- Offer: Add context, Retry, Manual
- Wait for user response

## 10. Spawn gsd-plan-checker Agent

Display:
🚀 **GSD → Verifying Plans**

◆ Spawning plan checker...

Read plans and requirements for the checker:

```bash
# Read all plans in phase directory
PLANS_CONTENT=$(cat "${PHASE_DIR}"/*-PLAN.md 2>/dev/null)

# Read requirements (reuse from step 7 if available)
REQUIREMENTS_CONTENT=$(cat .planning/REQUIREMENTS.md 2>/dev/null)
```

Fill checker prompt with inlined content and spawn:

```markdown
<verification_context>

**Phase:** {phase_number}
**Phase Goal:** {goal from ROADMAP}

**Plans to verify:**
{plans_content}

**Requirements (if exists):**
{requirements_content}

</verification_context>

<expected_output>
Return one of:
- ## VERIFICATION PASSED — all checks pass
- ## ISSUES FOUND — structured issue list
</expected_output>
```

```
sessions_spawn(
  task=checker_prompt,
  label="Verify Phase {phase} plans",
  cleanup="keep"
)
```

## 11. Handle Checker Return

**If `## VERIFICATION PASSED`:**
- Display: `Plans verified. Ready for execution.`
- Proceed to step 13

**If `## ISSUES FOUND`:**
- Display: `Checker found issues:`
- List issues from checker output
- Check iteration count
- Proceed to step 12

## 12. Revision Loop (Max 3 Iterations)

Track: `iteration_count` (starts at 1 after initial plan + check)

**If iteration_count < 3:**

Display: `Sending back to planner for revision... (iteration {N}/3)`

Read current plans for revision context:

```bash
PLANS_CONTENT=$(cat "${PHASE_DIR}"/*-PLAN.md 2>/dev/null)
```

Spawn gsd-planner with revision prompt:

```markdown
<revision_context>

**Phase:** {phase_number}
**Mode:** revision

**Existing plans:**
{plans_content}

**Checker issues:**
{structured_issues_from_checker}

</revision_context>

<instructions>
Make targeted updates to address checker issues.
Do NOT replan from scratch unless issues are fundamental.
Return what changed.
</instructions>
```

```
sessions_spawn(
    task="First, read /usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-planner.md for your role and instructions.\n\n",
    label="Revise Phase {phase} plans",
    cleanup="keep"
)
```

- After planner returns → spawn checker again (step 10)
- Increment iteration_count

**If iteration_count >= 3:**

Display: `Max iterations reached. {N} issues remain:`
- List remaining issues

Offer options:
1. Force proceed (execute despite issues)
2. Provide guidance (user gives direction, retry)
3. Abandon (exit planning)

Wait for user response.

## 13. Present Final Status

Route to `<offer_next>`.

</process>

<offer_next>
**Check autopilot mode first:**

```bash
echo $GSD_AUTOPILOT
```

**If GSD_AUTOPILOT=1 (autopilot mode):**

Output minimal plain text confirmation:

```
Phase {X} planned: {N} plan(s) ready
```

Then stop. Do NOT output the "Next Up" section or any guidance.

**Otherwise (interactive mode):**

Output this markdown directly (not as a code block):

🚀 **GSD → Phase {X} Planned** ✓

**Phase {X}: {Name}** — {N} plan(s) in {M} wave(s)

| Wave | Plans | What it builds |
|------|-------|----------------|
| 1    | 01, 02 | [objectives] |
| 2    | 03     | [objective]  |

Research: {Completed | Used existing | Skipped}
Verification: {Passed | Passed with override | Skipped}

**▶ Next Up**

**Execute Phase {X}** — run all {N} plans

`/gsd:execute-phase {X}`

`/clear` first → fresh context window

**Also available:**
- `cat .planning/phases/{phase-dir}/*-PLAN.md` — review plans
- `/gsd:plan-phase {X} --research` — re-research first
</offer_next>

<success_criteria>
- [ ] .planning/ directory validated
- [ ] Phase validated against roadmap
- [ ] Phase directory created if needed
- [ ] Research completed (unless --skip-research or --gaps or exists)
- [ ] gsd-phase-researcher spawned if research needed
- [ ] Existing plans checked
- [ ] gsd-planner spawned with context (including RESEARCH.md, DESIGN.md if available)
- [ ] Plans created (PLANNING COMPLETE or CHECKPOINT handled)
- [ ] gsd-plan-checker spawned (unless --skip-verify)
- [ ] Verification passed OR user override OR max iterations with user decision
- [ ] User sees status between agent spawns
- [ ] User knows next steps (execute or review)
</success_criteria>


path: workflows/progress.md
content: ---
name: gsd:progress
description: Check project progress, show context, and route to next action (execute or plan)
allowed-tools:
  - Read
  - Bash
  - Grep
  - Glob
---

<objective>
Check project progress, summarize recent work and what's ahead, then intelligently route to the next action - either executing an existing plan or creating the next one.

Provides situational awareness before continuing work.
</objective>

<process>

<step name="verify">
**Verify planning structure exists:**

Use Bash (not Glob) to check—Glob respects .gitignore but .planning/ is often gitignored:

```bash
test -d .planning && echo "exists" || echo "missing"
```

If no `.planning/` directory:

```
No planning structure found.

Run /gsd new-project to start a new project.
```

Exit.

If missing STATE.md: suggest `/gsd new-project`.

**If ROADMAP.md missing but PROJECT.md exists:**

This means a milestone was completed and archived. Go to **Route F** (between milestones).

If missing both ROADMAP.md and PROJECT.md: suggest `/gsd new-project`.
</step>

<step name="load">
**Load full project context:**

- Read `.planning/STATE.md` for living memory (position, decisions, issues)
- Read `.planning/ROADMAP.md` for phase structure and objectives
- Read `.planning/PROJECT.md` for current state (What This Is, Core Value, Requirements)
- Read `.planning/config.json` for settings (model_profile, workflow toggles)
</step>

<step name="recent">
**Gather recent work context:**

- Find the 2-3 most recent SUMMARY.md files
- Extract from each: what was accomplished, key decisions, any issues logged
- This shows "what we've been working on"
</step>

<step name="position">
**Parse current position:**

- From STATE.md: current phase, plan number, status
- Calculate: total plans, completed plans, remaining plans
- Note any blockers or concerns
- Check for CONTEXT.md: For phases without PLAN.md files, check if `{phase}-CONTEXT.md` exists in phase directory
- Count pending todos: `ls .planning/todos/pending/*.md 2>/dev/null | wc -l`
- Check for active debug sessions: `ls .planning/debug/*.md 2>/dev/null | grep -v resolved | wc -l`
</step>

<step name="report">
**Present rich status report:**

```
# [Project Name]

**Progress:** [████████░░] 8/10 plans complete
**Profile:** [quality/balanced/budget]

## Recent Work
- [Phase X, Plan Y]: [what was accomplished - 1 line]
- [Phase X, Plan Z]: [what was accomplished - 1 line]

## Current Position
Phase [N] of [total]: [phase-name]
Plan [M] of [phase-total]: [status]
CONTEXT: [✓ if CONTEXT.md exists | - if not]

## Key Decisions Made
- [decision 1 from STATE.md]
- [decision 2]

## Blockers/Concerns
- [any blockers or concerns from STATE.md]

## Pending Todos
- [count] pending

## Active Debug Sessions
- [count] active — /gsd debug to continue
(Only show this section if count > 0)

## What's Next
[Next phase/plan objective from ROADMAP]
```

</step>

<step name="route">
**Determine next action based on verified counts.**

**Step 1: Count plans, summaries, and issues in current phase**

List files in the current phase directory:

```bash
ls -1 .planning/phases/[current-phase-dir]/*-PLAN.md 2>/dev/null | wc -l
ls -1 .planning/phases/[current-phase-dir]/*-SUMMARY.md 2>/dev/null | wc -l
ls -1 .planning/phases/[current-phase-dir]/*-UAT.md 2>/dev/null | wc -l
```

State: "This phase has {X} plans, {Y} summaries."

**Step 2: Route based on counts**

| Condition | Meaning | Action |
|-----------|---------|--------|
| summaries < plans | Unexecuted plans exist | Go to **Route A** |
| summaries = plans AND plans > 0 | Phase complete | Go to Step 3 |
| plans = 0 | Phase not yet planned | Go to **Route B** |

---

**Route A: Unexecuted plan exists**

Find the first PLAN.md without matching SUMMARY.md.
Read its `<objective>` section.

```
---

## ▶ Next Up

**{phase}-{plan}: [Plan Name]** — [objective summary from PLAN.md]

`/gsd execute-phase {phase}`

---
```

---

**Route B: Phase needs planning**

Check if `{phase}-CONTEXT.md` exists in phase directory.

**If CONTEXT.md exists:**

```
---

## ▶ Next Up

**Phase {N}: {Name}** — {Goal from ROADMAP.md}
<sub>✓ Context gathered, ready to plan</sub>

`/gsd plan-phase {phase-number}`

---
```

**If CONTEXT.md does NOT exist:**

```
---

## ▶ Next Up

**Phase {N}: {Name}** — {Goal from ROADMAP.md}

`/gsd plan-phase {phase}` — plan directly

---
```

---

**Step 3: Check milestone status (only when phase complete)**

Read ROADMAP.md and identify:
1. Current phase number
2. All phase numbers in the current milestone section

Count total phases and identify the highest phase number.

**Route based on milestone status:**

| Condition | Meaning | Action |
|-----------|---------|--------|
| current phase < highest phase | More phases remain | Go to **Route C** |
| current phase = highest phase | Milestone complete | Go to **Route D** |

---

**Route C: Phase complete, more phases remain**

Read ROADMAP.md to get the next phase's name and goal.

```
---

## ✓ Phase {Z} Complete

## ▶ Next Up

**Phase {Z+1}: {Name}** — {Goal from ROADMAP.md}

`/gsd plan-phase {Z+1}` — plan next phase

---
```

---

**Route D: Milestone complete**

```
---

## 🎉 Milestone Complete

All {N} phases finished!

---
```

---

**Route F: Between milestones (ROADMAP.md missing, PROJECT.md exists)**

A milestone was completed and archived. Ready to start the next milestone cycle.

```
---

## ✓ Milestone Complete

Ready to plan the next milestone.

## ▶ Next Up

**Start Next Project/Milestone**

`/gsd new-project`

---
```

</step>

<step name="edge_cases">
**Handle edge cases:**

- Phase complete but next phase not planned → offer `/gsd plan-phase [next]`
- All work complete → offer milestone completion
- Blockers present → highlight before offering to continue
</step>

</process>

<success_criteria>
- [ ] Rich context provided (recent work, decisions, issues)
- [ ] Current position clear with visual progress
- [ ] What's next clearly explained
- [ ] Smart routing: /gsd execute-phase if plans exist, /gsd plan-phase if not
- [ ] Seamless handoff to appropriate gsd command
</success_criteria>


path: workflows/quick.md
content: ---
name: gsd:quick
description: Execute a quick task with GSD guarantees (atomic commits, state tracking) but skip optional agents
argument-hint: ""
allowed-tools:
  - Read
  - Write
  - Edit
  - Glob
  - Grep
  - Bash
---

<objective>
Execute small, ad-hoc tasks with GSD guarantees (atomic commits, STATE.md tracking) while skipping optional agents (research, plan-checker, verifier).

Quick mode is the same system with a shorter path:
- Spawns gsd-planner (quick mode) + gsd-executor(s)
- Skips gsd-phase-researcher, gsd-plan-checker, gsd-verifier
- Quick tasks live in `.planning/quick/` separate from planned phases
- Updates STATE.md "Quick Tasks Completed" table (NOT ROADMAP.md)

Use when: You know exactly what to do and the task is small enough to not need research or verification.
</objective>

<execution_context>
@/usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-planner.md
@/usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-executor.md
</execution_context>

<context>
@.planning/STATE.md
</context>

<process>

## Step 0: Resolve Model Profile

Read model profile for agent spawning:

```bash
MODEL_PROFILE=$(cat .planning/config.json 2>/dev/null | grep -o '"model_profile"[[:space:]]*:[[:space:]]*"[^"]*"' | grep -o '"[^"]*"$' | tr -d '"' || echo "balanced")
```

Default to "balanced" if not set.

**Model lookup table:**

| Agent | quality | balanced | budget |
|-------|---------|----------|--------|
| gsd-planner | opus | opus | sonnet |
| gsd-executor | opus | sonnet | sonnet |

---

## Step 1: Pre-flight validation

Check that an active GSD project exists:

```bash
if [ ! -f .planning/ROADMAP.md ]; then
  echo "Quick mode requires an active project with ROADMAP.md."
  echo "Run /gsd new-project first."
  exit 1
fi
```

If validation fails, stop immediately with the error message.

Quick tasks can run mid-phase - validation only checks ROADMAP.md exists, not phase status.

---

## Step 2: Get task description

Ask user: "What do you want to do?"

Store response as `$DESCRIPTION`.

If empty, re-prompt: "Please provide a task description."

Generate slug from description:
```bash
slug=$(echo "$DESCRIPTION" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/--*/-/g' | sed 's/^-//;s/-$//' | cut -c1-40)
```

---

## Step 3: Calculate next quick task number

Ensure `.planning/quick/` directory exists and find the next sequential number:

```bash
# Ensure .planning/quick/ exists
mkdir -p .planning/quick

# Find highest existing number and increment
last=$(ls -1d .planning/quick/[0-9][0-9][0-9]-* 2>/dev/null | sort -r | head -1 | xargs -I{} basename {} | grep -oE '^[0-9]+')

if [ -z "$last" ]; then
  next_num="001"
else
  next_num=$(printf "%03d" $((10#$last + 1)))
fi
```

---

## Step 4: Create quick task directory

Create the directory for this quick task:

```bash
QUICK_DIR=".planning/quick/${next_num}-${slug}"
mkdir -p "$QUICK_DIR"
```

Report to user:
```
Creating quick task ${next_num}: ${DESCRIPTION}
Directory: ${QUICK_DIR}
```

---

## Step 5: Spawn planner (quick mode)

Read STATE.md content for context:

```bash
STATE_CONTENT=$(cat .planning/STATE.md 2>/dev/null)
```

Spawn gsd-planner with quick mode context:

```
sessions_spawn(
    task="First, read /usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-planner.md for your role and instructions.

<planning_context>

**Mode:** quick
**Directory:** ${QUICK_DIR}
**Description:** ${DESCRIPTION}

**Project State:**
${STATE_CONTENT}

</planning_context>

<constraints>
- Create a SINGLE plan with 1-3 focused tasks
- Quick tasks should be atomic and self-contained
- No research phase, no checker phase
- Target ~30% context usage (simple, focused)
</constraints>

<output>
Write plan to: ${QUICK_DIR}/${next_num}-PLAN.md
Return: ## PLANNING COMPLETE with plan path
</output>
",
    label="Quick plan: ${DESCRIPTION}",
    model="{planner_model}",
    cleanup="keep"
)
```

After planner returns:
1. Verify plan exists at `${QUICK_DIR}/${next_num}-PLAN.md`
2. Report: "Plan created: ${QUICK_DIR}/${next_num}-PLAN.md"

If plan not found, error: "Planner failed to create ${next_num}-PLAN.md"

---

## Step 6: Spawn executor

Read plan content:

```bash
PLAN_CONTENT=$(cat "${QUICK_DIR}/${next_num}-PLAN.md")
```

Spawn gsd-executor with plan:

```
sessions_spawn(
    task="First, read /usr/lib/node_modules/clawdbot/skills/gsd/agents/gsd-executor.md for your role and instructions.

Execute quick task ${next_num}.

<plan>
${PLAN_CONTENT}
</plan>

<project_state>
${STATE_CONTENT}
</project_state>

<constraints>
- Execute all tasks in the plan
- Commit each task atomically
- Create summary at: ${QUICK_DIR}/${next_num}-SUMMARY.md
- Do NOT update ROADMAP.md (quick tasks are separate from planned phases)
</constraints>
",
    label="Execute: ${DESCRIPTION}",
    model="{executor_model}",
    cleanup="keep"
)
```

After executor returns:
1. Verify summary exists at `${QUICK_DIR}/${next_num}-SUMMARY.md`
2. Extract commit hash from executor output
3. Report completion status

---

## Step 7: Update STATE.md

Update STATE.md with quick task completion record.

**7a. Check if "Quick Tasks Completed" section exists:**

Read STATE.md and check for `### Quick Tasks Completed` section.

**7b. If section doesn't exist, create it:**

Insert after `### Blockers/Concerns` section:

```markdown
### Quick Tasks Completed

| # | Description | Date | Commit | Directory |
|---|-------------|------|--------|-----------|
```

**7c. Append new row to table:**

```markdown
| ${next_num} | ${DESCRIPTION} | $(date +%Y-%m-%d) | ${commit_hash} | [${next_num}-${slug}](./quick/${next_num}-${slug}/) |
```

Use Edit tool to make these changes atomically.

---

## Step 8: Final commit and completion

Stage and commit quick task artifacts:

```bash
# Stage quick task artifacts
git add ${QUICK_DIR}/${next_num}-PLAN.md
git add ${QUICK_DIR}/${next_num}-SUMMARY.md
git add .planning/STATE.md

# Commit with quick task format
git commit -m "docs(quick-${next_num}): ${DESCRIPTION}

Quick task completed."
```

Get final commit hash:
```bash
commit_hash=$(git rev-parse --short HEAD)
```

Display completion output:

```
---

## ✓ Quick Task Complete

**Quick Task ${next_num}:** ${DESCRIPTION}

Summary: ${QUICK_DIR}/${next_num}-SUMMARY.md
Commit: ${commit_hash}

---

Ready for next task: `/gsd quick`
```

</process>

<success_criteria>
- [ ] ROADMAP.md validation passes
- [ ] User provides task description
- [ ] Slug generated (lowercase, hyphens, max 40 chars)
- [ ] Next number calculated (001, 002, 003...)
- [ ] Directory created at `.planning/quick/NNN-slug/`
- [ ] `${next_num}-PLAN.md` created by planner
- [ ] `${next_num}-SUMMARY.md` created by executor
- [ ] STATE.md updated with quick task row
- [ ] Artifacts committed
</success_criteria>


path: workflows/remove-phase.md
content: ---
name: gsd:remove-phase
description: Remove a future phase from roadmap and renumber subsequent phases
argument-hint: "<phase-number>"
allowed-tools:
  - Read
  - Write
  - Bash
  - Glob
---

<objective>
Remove an unstarted future phase and renumber all subsequent phases.
Git commit serves as historical record.
</objective>

<process>

## Step 1: Parse Arguments

```bash
if [ -z "$ARGUMENTS" ]; then
  echo "ERROR: Phase number required"
  echo "Usage: /gsd remove-phase <phase-number>"
  exit 1
fi
TARGET=$ARGUMENTS
```

## Step 2: Validate Phase Exists

```bash
grep -q "Phase ${TARGET}:" .planning/ROADMAP.md || {
  echo "ERROR: Phase ${TARGET} not found"
  exit 1
}
```

## Step 3: Validate Future Phase

```bash
# Get current phase from STATE.md
CURRENT=$(grep "Phase:" .planning/STATE.md | grep -oE "[0-9]+" | head -1)
if [ "$TARGET" -le "$CURRENT" ]; then
  echo "ERROR: Can only remove future phases (current: $CURRENT)"
  exit 1
fi
```

## Step 4: Check No Completed Work

```bash
if ls .planning/phases/${TARGET}-*/*-SUMMARY.md 2>/dev/null | grep -q .; then
  echo "ERROR: Phase has completed work (SUMMARY.md exists)"
  exit 1
fi
```

## Step 5: Gather Info & Confirm

Extract phase name, list what will be renumbered:

```
Removing Phase {TARGET}: {Name}

This will:
- Delete: .planning/phases/{TARGET}-{slug}/
- Renumber subsequent phases

Proceed? (yes to confirm)
```

## Step 6: Delete Phase Directory

```bash
rm -rf .planning/phases/${TARGET}-*/
```

## Step 7: Renumber Subsequent Phases

For each phase > TARGET (in reverse order):
```bash
# Rename directories: 18 → 17, 19 → 18, etc.
for dir in $(ls -d .planning/phases/*/ | sort -rV); do
  # Extract phase number, rename if > TARGET
done
```

## Step 8: Update ROADMAP.md

- Remove phase section
- Renumber all subsequent phases
- Update dependency references

## Step 9: Update STATE.md

Update phase count and progress.

## Step 10: Commit

```bash
git add .planning/
git commit -m "chore: remove phase ${TARGET} (${PHASE_NAME})"
```

## Step 11: Confirm

```
---

## ✓ Phase {TARGET} Removed

**{Name}** deleted and subsequent phases renumbered.

Commit: chore: remove phase {TARGET}

**▶ Next:** `/gsd progress`

---
```

</process>

<success_criteria>
- [ ] Phase validated as future/unstarted
- [ ] Directory deleted
- [ ] Subsequent phases renumbered
- [ ] ROADMAP.md and STATE.md updated
- [ ] Changes committed
</success_criteria>


path: workflows/resume-project.md
content: ---
name: gsd:resume-project
description: Instantly restore full project context for session continuation
argument-hint: ""
allowed-tools:
  - Read
  - Write
  - Bash
  - Task
  - AskUserQuestion
---

<objective>
Instantly restore full project context so "Where were we?" has an immediate, complete answer.

**Trigger - Use this workflow when:**
- Starting a new session on an existing project
- User says "continue", "what's next", "where were we", "resume"
- Any planning operation when .planning/ already exists
- User returns after time away from project
</objective>

<execution_context>
@/usr/lib/node_modules/clawdbot/skills/gsd/references/continuation-format.md
</execution_context>

<context>
@.planning/STATE.md
@.planning/ROADMAP.md
@.planning/PROJECT.md
</context>

<process>

## Phase 1: Detect Existing Project

Check if this is an existing project:

```bash
ls .planning/STATE.md 2>/dev/null && echo "Project exists"
ls .planning/ROADMAP.md 2>/dev/null && echo "Roadmap exists"
ls .planning/PROJECT.md 2>/dev/null && echo "Project file exists"
```

**If STATE.md exists:** Proceed to load state
**If only ROADMAP.md/PROJECT.md exist:** Offer to reconstruct STATE.md
**If .planning/ doesn't exist:** This is a new project - route to /gsd:new-project

## Phase 2: Load State

Read and parse STATE.md, then PROJECT.md:

```bash
cat .planning/STATE.md
cat .planning/PROJECT.md
```

**From STATE.md extract:**

- **Project Reference**: Core value and current focus
- **Current Position**: Phase X of Y, Plan A of B, Status
- **Progress**: Visual progress bar
- **Recent Decisions**: Key decisions affecting current work
- **Pending Todos**: Ideas captured during sessions
- **Blockers/Concerns**: Issues carried forward
- **Session Continuity**: Where we left off, any resume files

**From PROJECT.md extract:**

- **What This Is**: Current accurate description
- **Requirements**: Validated, Active, Out of Scope
- **Key Decisions**: Full decision log with outcomes
- **Constraints**: Hard limits on implementation

## Phase 3: Check Incomplete Work

Look for incomplete work that needs attention:

```bash
# Check for continue-here files (mid-plan resumption)
ls .planning/phases/*/.continue-here*.md 2>/dev/null

# Check for plans without summaries (incomplete execution)
for plan in .planning/phases/*/*-PLAN.md; do
  summary="${plan/PLAN/SUMMARY}"
  [ ! -f "$summary" ] && echo "Incomplete: $plan"
done 2>/dev/null

# Check for interrupted agents
if [ -f .planning/current-agent-id.txt ] && [ -s .planning/current-agent-id.txt ]; then
  AGENT_ID=$(cat .planning/current-agent-id.txt | tr -d '\n')
  echo "Interrupted agent: $AGENT_ID"
fi
```

**If .continue-here file exists:**
- This is a mid-plan resumption point
- Flag: "Found mid-plan checkpoint"

**If PLAN without SUMMARY exists:**
- Execution was started but not completed
- Flag: "Found incomplete plan execution"

**If interrupted agent found:**
- Subagent was spawned but session ended before completion
- Flag: "Found interrupted agent"

## Phase 4: Present Status

Present complete project status to user:

```
╔══════════════════════════════════════════════════════════════╗
║  PROJECT STATUS                                               ║
╠══════════════════════════════════════════════════════════════╣
║  Building: [one-liner from PROJECT.md "What This Is"]         ║
║                                                               ║
║  Phase: [X] of [Y] - [Phase name]                            ║
║  Plan:  [A] of [B] - [Status]                                ║
║  Progress: [██████░░░░] XX%                                  ║
║                                                               ║
║  Last activity: [date] - [what happened]                     ║
╚══════════════════════════════════════════════════════════════╝

[If incomplete work found:]
⚠️  Incomplete work detected:
    - [.continue-here file or incomplete plan]

[If interrupted agent found:]
⚠️  Interrupted agent detected:
    Agent ID: [id]
    Task: [task description from agent-history.json]

[If pending todos exist:]
📋 [N] pending todos — /gsd:check-todos to review

[If blockers exist:]
⚠️  Carried concerns:
    - [blocker 1]
    - [blocker 2]
```

## Phase 5: Determine Next Action

Based on project state, determine the most logical next action:

**If interrupted agent exists:**
→ Primary: Resume interrupted agent
→ Option: Start fresh

**If .continue-here file exists:**
→ Primary: Resume from checkpoint
→ Option: Start fresh on current plan

**If incomplete plan (PLAN without SUMMARY):**
→ Primary: Complete the incomplete plan
→ Option: Abandon and move on

**If phase in progress, all plans complete:**
→ Primary: Transition to next phase
→ Option: Review completed work

**If phase ready to plan:**
→ Check if CONTEXT.md exists for this phase:
- If CONTEXT.md missing: Primary: Discuss phase vision
- If CONTEXT.md exists: Primary: Plan the phase

**If phase ready to execute:**
→ Primary: Execute next plan
→ Option: Review the plan first

## Phase 6: Offer Options

Present contextual options based on project state:

```
What would you like to do?

[Primary action based on state]
1. {Primary action}

[Secondary options:]
2. Review current phase status
3. Check pending todos ([N] pending)
4. Review brief alignment
5. Something else
```

Wait for user selection.

## Phase 7: Route to Workflow

Based on user selection, route to appropriate workflow:

- **Execute plan** → Show command for user to run after clearing:
  ```
  ---

  ## ▶ Next Up

  **{phase}-{plan}: [Plan Name]** — [objective]

  `/gsd:execute-phase {phase}`

  <sub>`/clear` first → fresh context window</sub>

  ---
  ```

- **Plan phase** → Show command for user to run after clearing:
  ```
  ---

  ## ▶ Next Up

  **Phase [N]: [Name]** — [Goal]

  `/gsd:plan-phase [phase-number]`

  <sub>`/clear` first → fresh context window</sub>

  ---
  ```

- **Transition** → /gsd:transition
- **Check todos** → Read .planning/todos/pending/, present summary
- **Something else** → Ask what they need

## Phase 8: Update Session

Before proceeding, update session continuity in STATE.md:

```markdown
## Session Continuity

Last session: [now]
Stopped at: Session resumed, proceeding to [action]
Resume file: [updated if applicable]
```

</process>

<reconstruction>
If STATE.md is missing but other artifacts exist:

"STATE.md missing. Reconstructing from artifacts..."

1. Read PROJECT.md → Extract "What This Is" and Core Value
2. Read ROADMAP.md → Determine phases, find current position
3. Scan *-SUMMARY.md files → Extract decisions, concerns
4. Count pending todos in .planning/todos/pending/
5. Check for .continue-here files → Session continuity

Reconstruct and write STATE.md, then proceed normally.
</reconstruction>

<quick_resume>
If user says "continue" or "go":
- Load state silently
- Determine primary action
- Execute immediately without presenting options

"Continuing from [state]... [action]"
</quick_resume>

<success_criteria>
- [ ] STATE.md loaded (or reconstructed)
- [ ] Incomplete work detected and flagged
- [ ] Clear status presented to user
- [ ] Contextual next actions offered
- [ ] User knows exactly where project stands
- [ ] Session continuity updated
</success_criteria>


path: workflows/resume-work.md
content: ---
name: gsd:resume-work
description: Resume work from previous session with full context restoration
allowed-tools:
  - Read
  - Bash
  - Write
---

<objective>
Restore complete project context and resume work seamlessly from previous session.

Handles:
- STATE.md loading
- Checkpoint detection (.continue-here files)
- Incomplete work detection (PLAN without SUMMARY)
- Status presentation
- Context-aware next action routing
</objective>

<context>
@.planning/STATE.md
@.planning/ROADMAP.md
</context>

<process>

## Step 1: Verify Project Exists

```bash
if [ ! -d .planning ]; then
  echo "No project found. Run /gsd new-project to start."
  exit 1
fi
```

## Step 2: Load STATE.md

```bash
if [ -f .planning/STATE.md ]; then
  cat .planning/STATE.md
else
  echo "STATE.md missing - will reconstruct from artifacts"
fi
```

If missing: Reconstruct from ROADMAP.md, SUMMARY.md files, etc.

## Step 3: Check for Checkpoints

```bash
# Find any .continue-here.md files
CHECKPOINTS=$(find .planning/phases -name ".continue-here.md" 2>/dev/null)
if [ -n "$CHECKPOINTS" ]; then
  echo "Found checkpoints:"
  echo "$CHECKPOINTS"
fi
```

If checkpoint found:
- Read the checkpoint file
- Present the captured state
- Offer to continue from checkpoint

## Step 4: Check for Incomplete Work

```bash
# Find PLAN.md files without matching SUMMARY.md
for plan in .planning/phases/*/*-PLAN.md; do
  summary="${plan/-PLAN.md/-SUMMARY.md}"
  if [ ! -f "$summary" ]; then
    echo "Incomplete: $plan"
  fi
done
```

## Step 5: Present Status

```
---

## Project Status

**Project:** {from PROJECT.md}
**Current Phase:** {from STATE.md}

### Checkpoint Found (if any)

{Content from .continue-here.md}

### Incomplete Work (if any)

- Phase X, Plan Y: Not executed

### Recent Activity

{From STATE.md or recent SUMMARY.md}

---
```

## Step 6: Offer Next Actions

**If checkpoint exists:**

```
**▶ Resume from Checkpoint**

{Next action from .continue-here.md}

Ready to continue? (yes to proceed)

---

**Or:**
- `/gsd progress` — full status overview
- `/gsd execute-phase {N}` — execute incomplete plans
```

**If no checkpoint but incomplete work:**

```
**▶ Continue Work**

Incomplete plans found in Phase {N}.

`/gsd execute-phase {N}` — execute remaining plans

---
```

**If nothing pending:**

```
**▶ What's Next**

All current work complete.

`/gsd progress` — see what's next

---
```

## Step 7: Update Session Continuity

If resuming from checkpoint, update STATE.md:

```markdown
### Session Continuity

- Resumed: {timestamp}
- From checkpoint: {phase}/.continue-here.md
- Previous session: {info from checkpoint}
```

</process>

<success_criteria>
- [ ] Project existence verified
- [ ] STATE.md loaded or reconstructed
- [ ] Checkpoints detected and presented
- [ ] Incomplete work identified
- [ ] Clear status presented
- [ ] Appropriate next action offered
</success_criteria>


path: workflows/settings.md
content: ---
name: gsd:settings
description: Configure GSD workflow toggles and model profile
allowed-tools:
  - Read
  - Write
---

<objective>
Configure workflow agents (on/off) and model profile interactively.
Updates `.planning/config.json`.
</objective>

<process>

## Step 1: Validate Environment

```bash
if [ ! -f .planning/config.json ]; then
  echo "ERROR: No config found. Run /gsd new-project first."
  exit 1
fi
```

## Step 2: Read Current Config

```bash
cat .planning/config.json
```

Parse current values:
- `model_profile` (quality/balanced/budget)
- `workflow.research` (true/false)
- `workflow.plan_check` (true/false)
- `workflow.verifier` (true/false)

## Step 3: Present Settings

Ask user for each setting:

**Model Profile:**
- Quality — Opus everywhere (highest cost)
- Balanced — Opus for planning, Sonnet for execution (recommended)
- Budget — Sonnet/Haiku (lowest cost)

**Workflow Agents:**
- Research — Spawn researcher before planning?
- Plan Check — Verify plans before execution?
- Verifier — Verify phase completion?

## Step 4: Update Config

```json
{
  "model_profile": "balanced",
  "workflow": {
    "research": true,
    "plan_check": true,
    "verifier": true
  }
}
```

## Step 5: Confirm

```
---

## ✓ Settings Updated

| Setting | Value |
|---------|-------|
| Model Profile | {profile} |
| Research | {On/Off} |
| Plan Check | {On/Off} |
| Verifier | {On/Off} |

These apply to future plan-phase and execute-phase runs.

---
```

</process>

<success_criteria>
- [ ] Current config read
- [ ] User selected settings
- [ ] Config updated
- [ ] Changes confirmed
</success_criteria>


path: workflows/transition.md
content: ---
name: gsd:transition
description: Mark current phase complete and advance to next phase
argument-hint: ""
allowed-tools:
  - Read
  - Write
  - Edit
  - Bash
  - AskUserQuestion
---

<objective>
Mark current phase complete and advance to next. This is the natural point where progress tracking and PROJECT.md evolution happen.

"Planning next phase" = "current phase is done"
</objective>

<execution_context>
@/usr/lib/node_modules/clawdbot/skills/gsd/references/git-integration.md
</execution_context>

<context>
**Read these files NOW:**

@.planning/STATE.md
@.planning/PROJECT.md
@.planning/ROADMAP.md
</context>

<process>

## Phase 1: Load Project State

Before transition, read project state:

```bash
cat .planning/STATE.md 2>/dev/null
cat .planning/PROJECT.md 2>/dev/null
```

Parse current position to verify we're transitioning the right phase.

## Phase 2: Verify Completion

Check current phase has all plan summaries:

```bash
ls .planning/phases/XX-current/*-PLAN.md 2>/dev/null | sort
ls .planning/phases/XX-current/*-SUMMARY.md 2>/dev/null | sort
```

**If all plans complete:**

Check config mode and proceed accordingly.

**If plans incomplete:**

**SAFETY RAIL: always_confirm_destructive applies here.**

Present:

```
Phase [X] has incomplete plans:
- {phase}-01-SUMMARY.md ✓ Complete
- {phase}-02-SUMMARY.md ✗ Missing
- {phase}-03-SUMMARY.md ✗ Missing

⚠️ Safety rail: Skipping plans requires confirmation (destructive action)

Options:
1. Continue current phase (execute remaining plans)
2. Mark complete anyway (skip remaining plans)
3. Review what's left
```

Wait for user decision.

## Phase 3: Cleanup Handoff

Check for lingering handoffs:

```bash
ls .planning/phases/XX-current/.continue-here*.md 2>/dev/null
```

If found, delete them — phase is complete, handoffs are stale.

## Phase 4: Update Roadmap

Update the roadmap file:

- Mark current phase: `[x] Complete`
- Add completion date
- Update plan count to final (e.g., "3/3 plans complete")
- Update Progress table
- Keep next phase as `[ ] Not started`

**Example:**

```markdown
## Phases

- [x] Phase 1: Foundation (completed 2025-01-15)
- [ ] Phase 2: Authentication ← Next
- [ ] Phase 3: Core Features

## Progress

| Phase             | Plans Complete | Status      | Completed  |
| ----------------- | -------------- | ----------- | ---------- |
| 1. Foundation     | 3/3            | Complete    | 2025-01-15 |
| 2. Authentication | 0/2            | Not started | -          |
| 3. Core Features  | 0/1            | Not started | -          |
```

## Phase 5: Evolve Project

Evolve PROJECT.md to reflect learnings from completed phase.

**Read phase summaries:**

```bash
cat .planning/phases/XX-current/*-SUMMARY.md
```

**Assess requirement changes:**

1. **Requirements validated?**
   - Move to Validated with phase reference: `- ✓ [Requirement] — Phase X`

2. **Requirements invalidated?**
   - Move to Out of Scope with reason

3. **Requirements emerged?**
   - Add to Active: `- [ ] [New requirement]`

4. **Decisions to log?**
   - Add to Key Decisions table with outcome

5. **"What This Is" still accurate?**
   - Update if the product has meaningfully changed

**Update "Last updated" footer:**

```markdown
---
*Last updated: [date] after Phase [X]*
```

## Phase 6: Update STATE.md Position

Update Current Position section:

```markdown
Phase: [next] of [total] ([Next phase name])
Plan: Not started
Status: Ready to plan
Last activity: [today] — Phase [X] complete, transitioned to Phase [X+1]

Progress: [updated progress bar]
```

## Phase 7: Update Project Reference

Update Project Reference section in STATE.md:

```markdown
## Project Reference

See: .planning/PROJECT.md (updated [today])

**Core value:** [Current core value]
**Current focus:** [Next phase name]
```

## Phase 8: Review Accumulated Context

**Decisions:**
- Note recent decisions from this phase (3-5 max)
- Full log lives in PROJECT.md

**Blockers/Concerns:**
- If addressed in this phase: Remove from list
- If still relevant: Keep with phase prefix
- Add any new concerns from completed phase

## Phase 9: Update Session Continuity

```markdown
Last session: [today]
Stopped at: Phase [X] complete, ready to plan Phase [X+1]
Resume file: None
```

## Phase 10: Offer Next Phase

**Verify milestone status before presenting next steps.**

**Step 1: Read ROADMAP.md and identify phases in current milestone**

Count total phases and identify the highest phase number.

**Step 2: Route based on milestone status**

**Route A: More phases remain in milestone**

```
## ✓ Phase [X] Complete

---

## ▶ Next Up

**Phase [X+1]: [Name]** — [Goal from ROADMAP.md]

`/gsd:plan-phase [X+1]`

<sub>`/clear` first → fresh context window</sub>

---

**Also available:**
- `/gsd:discuss-phase [X+1]` — gather context first
- `/gsd:research-phase [X+1]` — investigate unknowns
- Review roadmap

---
```

**Route B: Milestone complete (all phases done)**

```
## ✓ Phase {X}: {Phase Name} Complete

🎉 Milestone {version} is 100% complete — all {N} phases finished!

---

## ▶ Next Up

**Complete Milestone {version}** — archive and prepare for next

`/gsd:complete-milestone {version}`

<sub>`/clear` first → fresh context window</sub>

---
```

</process>

<partial_completion>
If user wants to move on but phase isn't fully complete:

```
Phase [X] has incomplete plans:
- {phase}-02-PLAN.md (not executed)
- {phase}-03-PLAN.md (not executed)

Options:
1. Mark complete anyway (plans weren't needed)
2. Defer work to later phase
3. Stay and finish current phase
```

Respect user judgment — they know if work matters.

**If marking complete with incomplete plans:**
- Update ROADMAP: "2/3 plans complete" (not "3/3")
- Note in transition message which plans were skipped
</partial_completion>

<success_criteria>
- [ ] Current phase plan summaries verified (all exist or user chose to skip)
- [ ] Any stale handoffs deleted
- [ ] ROADMAP.md updated with completion status and plan count
- [ ] PROJECT.md evolved (requirements, decisions, description if needed)
- [ ] STATE.md updated (position, project reference, context, session)
- [ ] Progress table updated
- [ ] User knows next steps
</success_criteria>


path: workflows/verify-phase.md
content: ---
name: gsd:verify-phase
description: Verify phase goal achievement through goal-backward analysis
argument-hint: "<phase-number>"
allowed-tools:
  - Read
  - Write
  - Bash
  - Task
---

<objective>
Verify phase goal achievement through goal-backward analysis. Check that the codebase actually delivers what the phase promised, not just that tasks were completed.

This workflow is executed by a verification subagent spawned from execute-phase.md.

**Core Principle: Task completion ≠ Goal achievement**

A task "create chat component" can be marked complete when the component is a placeholder. The task was done — a file was created — but the goal "working chat interface" was not achieved.

Goal-backward verification starts from the outcome and works backwards:
1. What must be TRUE for the goal to be achieved?
2. What must EXIST for those truths to hold?
3. What must be WIRED for those artifacts to function?

Then verify each level against the actual codebase.
</objective>

<execution_context>
@/usr/lib/node_modules/clawdbot/skills/gsd/references/verification-patterns.md
@/usr/lib/node_modules/clawdbot/skills/gsd/templates/verification-report.md
</execution_context>

<context>
Phase number: $ARGUMENTS

@.planning/STATE.md
@.planning/ROADMAP.md
</context>

<process>

## Phase 1: Load Context

**Gather all verification context:**

```bash
# Phase directory (match both zero-padded and unpadded)
PADDED_PHASE=$(printf "%02d" ${PHASE_ARG} 2>/dev/null || echo "${PHASE_ARG}")
PHASE_DIR=$(ls -d .planning/phases/${PADDED_PHASE}-* .planning/phases/${PHASE_ARG}-* 2>/dev/null | head -1)

# Phase goal from ROADMAP
grep -A 5 "Phase ${PHASE_NUM}" .planning/ROADMAP.md

# Requirements mapped to this phase
grep -E "^| ${PHASE_NUM}" .planning/REQUIREMENTS.md 2>/dev/null

# All SUMMARY files (claims to verify)
ls "$PHASE_DIR"/*-SUMMARY.md 2>/dev/null

# All PLAN files (for must_haves in frontmatter)
ls "$PHASE_DIR"/*-PLAN.md 2>/dev/null
```

**Extract phase goal:** Parse ROADMAP.md for this phase's goal/description.

## Phase 2: Establish Must-Haves

**Option A: Must-haves in PLAN frontmatter**

Check if any PLAN.md has `must_haves`:

```bash
grep -l "must_haves:" "$PHASE_DIR"/*-PLAN.md 2>/dev/null
```

If found, extract and use:
```yaml
must_haves:
  truths:
    - "User can see existing messages"
    - "User can send a message"
  artifacts:
    - path: "src/components/Chat.tsx"
      provides: "Message list rendering"
  key_links:
    - from: "Chat.tsx"
      to: "api/chat"
      via: "fetch in useEffect"
```

**Option B: Derive from phase goal**

If no must_haves, derive using goal-backward process:

1. **State the goal:** From ROADMAP.md
2. **Derive truths:** What must be TRUE? (3-7 observable behaviors)
3. **Derive artifacts:** What must EXIST? (concrete files)
4. **Derive key links:** What must be CONNECTED? (critical wiring)

## Phase 3: Verify Truths

**For each observable truth, determine if codebase enables it.**

**Verification status:**
- ✓ VERIFIED: All supporting artifacts pass all checks
- ✗ FAILED: Supporting artifacts missing, stub, or unwired
- ? UNCERTAIN: Can't verify programmatically

**For each truth:**
1. Identify supporting artifacts
2. Check artifact status
3. Check wiring status
4. Determine truth status

## Phase 4: Verify Artifacts

**For each required artifact, verify three levels:**

### Level 1: Existence
```bash
[ -f "$path" ] && echo "EXISTS" || echo "MISSING"
```

### Level 2: Substantive

**Line count check:**
```bash
lines=$(wc -l < "$path" 2>/dev/null || echo 0)
```

Minimum lines by type:
- Component: 15+ lines
- API route: 10+ lines
- Schema model: 5+ lines

**Stub pattern check:**
```bash
grep -c -E "TODO|FIXME|placeholder|not implemented" "$path"
```

### Level 3: Wired

**Import check:**
```bash
grep -r "import.*$artifact_name" src/ --include="*.ts" --include="*.tsx" | wc -l
```

**Usage check:**
```bash
grep -r "$artifact_name" src/ --include="*.ts" --include="*.tsx" | grep -v "import" | wc -l
```

### Final artifact status

| Exists | Substantive | Wired | Status |
|--------|-------------|-------|--------|
| ✓ | ✓ | ✓ | ✓ VERIFIED |
| ✓ | ✓ | ✗ | ⚠️ ORPHANED |
| ✓ | ✗ | - | ✗ STUB |
| ✗ | - | - | ✗ MISSING |

## Phase 5: Verify Wiring

**Verify key links between artifacts.**

### Pattern: Component → API
```bash
grep -E "fetch\(['\"].*$api_path|axios\.(get|post).*$api_path" "$component"
```

### Pattern: API → Database
```bash
grep -E "prisma\.$model|db\.$model" "$route"
```

### Pattern: Form → Handler
```bash
grep -E "onSubmit=\{|handleSubmit" "$component"
```

## Phase 6: Verify Requirements

**Check requirements coverage if REQUIREMENTS.md exists.**

```bash
grep -E "Phase ${PHASE_NUM}" .planning/REQUIREMENTS.md 2>/dev/null
```

For each requirement:
1. Identify which truths/artifacts support it
2. Determine status based on supporting infrastructure

## Phase 7: Scan Anti-Patterns

Identify files modified in this phase:
```bash
grep -E "^\- \`" "$PHASE_DIR"/*-SUMMARY.md | sed 's/.*`\([^`]*\)`.*/\1/' | sort -u
```

Run anti-pattern detection:
- TODO/FIXME comments
- Placeholder content
- Empty implementations
- Console.log only implementations

Categorize findings:
- 🛑 Blocker: Prevents goal achievement
- ⚠️ Warning: Indicates incomplete
- ℹ️ Info: Notable but not problematic

## Phase 8: Identify Human Verification

Flag items that need human verification:

**Always needs human:**
- Visual appearance
- User flow completion
- Real-time behavior
- External service integration
- Performance feel
- Error message clarity

## Phase 9: Determine Status

**Status: passed**
- All truths VERIFIED
- All artifacts pass level 1-3
- All key links WIRED
- No blocker anti-patterns

**Status: gaps_found**
- One or more truths FAILED
- OR artifacts MISSING/STUB
- OR key links NOT_WIRED
- OR blocker anti-patterns found

**Status: human_needed**
- All automated checks pass
- BUT items flagged for human verification

**Calculate score:**
```
score = (verified_truths / total_truths)
```

## Phase 10: Generate Fix Plans

**If gaps_found, recommend fix plans.**

1. **Identify gap clusters:**
   - API stub + component not wired → "Wire frontend to backend"
   - Multiple artifacts missing → "Complete core implementation"

2. **Generate plan recommendations:**
```markdown
### {phase}-{next}-PLAN.md: {Fix Name}

**Objective:** {What this fixes}

**Tasks:**
1. {Task to fix gap 1}
2. {Task to fix gap 2}
3. Re-verify phase goal

**Estimated scope:** {Small / Medium}
```

## Phase 11: Create Report

Generate VERIFICATION.md:

```bash
REPORT_PATH="$PHASE_DIR/${PHASE_NUM}-VERIFICATION.md"
```

Fill template sections:
1. Frontmatter
2. Goal Achievement table
3. Required Artifacts table
4. Key Link Verification table
5. Requirements Coverage
6. Anti-Patterns Found
7. Human Verification Required
8. Gaps Summary
9. Recommended Fix Plans
10. Verification Metadata

## Phase 12: Return to Orchestrator

**Return format:**

```markdown
## Verification Complete

**Status:** {passed | gaps_found | human_needed}
**Score:** {N}/{M} must-haves verified
**Report:** .planning/phases/{phase_dir}/{phase}-VERIFICATION.md

{If passed:}
All must-haves verified. Phase goal achieved. Ready to proceed.

{If gaps_found:}
### Gaps Found
{N} critical gaps blocking goal achievement

### Recommended Fixes
{N} fix plans recommended

{If human_needed:}
### Human Verification Required
{N} items need human testing
```

The orchestrator will:
- If `passed`: Continue to update_roadmap
- If `gaps_found`: Create and execute fix plans, then re-verify
- If `human_needed`: Present items to user

</process>

<success_criteria>
- [ ] Must-haves established (from frontmatter or derived)
- [ ] All truths verified with status and evidence
- [ ] All artifacts checked at all three levels
- [ ] All key links verified
- [ ] Requirements coverage assessed (if applicable)
- [ ] Anti-patterns scanned and categorized
- [ ] Human verification items identified
- [ ] Overall status determined
- [ ] Fix plans generated (if gaps_found)
- [ ] VERIFICATION.md created with complete report
- [ ] Results returned to orchestrator
</success_criteria>


path: templates/config.json
content: {
  "mode": "interactive",
  "depth": "standard",
  "workflow": {
    "research": true,
    "plan_check": true,
    "verifier": true
  },
  "planning": {
    "commit_docs": true,
    "search_gitignored": false
  },
  "parallelization": {
    "enabled": true,
    "plan_level": true,
    "task_level": false,
    "skip_checkpoints": true,
    "max_concurrent_agents": 3,
    "min_plans_for_parallel": 2
  },
  "gates": {
    "confirm_project": true,
    "confirm_phases": true,
    "confirm_roadmap": true,
    "confirm_breakdown": true,
    "confirm_plan": true,
    "execute_next_plan": true,
    "issues_review": true,
    "confirm_transition": true
  },
  "safety": {
    "always_confirm_destructive": true,
    "always_confirm_external_services": true
  }
}


path: templates/context.md
content: # Phase [X]: [Name] - Context

**Gathered:** [date]

## Decisions

[Captured decisions from discussion, organized by area]

### [Area 1]
- [Decision 1]
- [Decision 2]

### [Area 2]
- [Decision 1]

## Claude's Discretion

[Things user didn't specify — Claude can decide during planning]

- [Item 1]
- [Item 2]

## Deferred Ideas

[Scope creep captured but not acted on — may become future phases]

- [Idea 1] — suggested during discussion
- [Idea 2]

---
*Context gathered for phase planning*


Security scan verdicts — ClawScan: suspicious | static analysis: suspicious | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)