Spectacular skills/commands library for spec-anchored development and parallel task execution

version
3.2.0
GitHub stars
20

Install

/plugin install spectacular@spectacular

Run it inside Claude Code after adding the marketplace with /plugin marketplace add arittr/spectacular.

Contents

Discovered from source

Skills 14

Task Decomposition

Create an execution-ready plan from a feature specification with automatic phase grouping based on file dependencies.

When to use: After completing a feature spec with /spectacular:spec, to create an implementation plan.

Announce: "I'm using the Task Decomposition skill to create an execution plan."

Input

User will provide: /spectacular:plan {spec-path}

Example: /spectacular:plan @specs/a1b2c3-magic-link-auth/spec.md

Where a1b2c3 is the runId and magic-link-auth is the feature slug.

Multi-Repo Support

Detecting Multi-Repo Mode

Check if workspace contains multiple repos:

# Detect workspace mode (same as writing-specs skill)
REPO_COUNT=$(find . -maxdepth 2 -name ".git" -type d 2>/dev/null | wc -l | tr -d ' ')
if [ "$REPO_COUNT" -gt 1 ]; then
  echo "Multi-repo workspace detected ($REPO_COUNT repos)"
  WORKSPACE_MODE="multi-repo"
  # List detected repos
  REPOS=$(find . -maxdepth 2 -name ".git" -type d | xargs -I{} dirname {} | sed 's|^\./||' | tr '\n' ' ')
  echo "Available repos: $REPOS"
else
  echo "Single-repo mode"
  WORKSPACE_MODE="single-repo"
fi

Multi-Repo Task Format

In multi-repo mode, each task MUST specify which repo it belongs to:

### Task 1.1: Add user_preferences table

**Repo**: backend
**Files**:
- prisma/schema.prisma
- prisma/migrations/*

**Constitution**: @backend/docs/constitutions/current/

Single-Repo Task Format (unchanged)

### Task 1.1: Add user_preferences table

**Files**:
- prisma/schema.prisma
- prisma/migrations/*

**Constitution**: @docs/constitutions/current/

Full Workflow

Step 0: Extract Run ID and Feature Slug from Spec

First action: Read the spec and extract the RUN_ID from frontmatter and determine the spec directory.

# Extract runId from spec frontmatter
RUN_ID=$(grep "^runId:" {spec-path} | awk '{print $2}')
echo "RUN_ID: $RUN_ID"

# Extract feature slug from the spec path
# Path pattern: .../specs/{runId}-{feature-slug}/spec.md
# Use sed to extract directory name without nested command substitution
SPEC_PATH="{spec-path}"
DIR_NAME=$(echo "$SPEC_PATH" | sed 's|^.*specs/||; s|/spec.md$||')
FEATURE_SLUG=$(echo "$DIR_NAME" | sed "s/^${RUN_ID}-//")
echo "FEATURE_SLUG: $FEATURE_SLUG"

CRITICAL: Execute this entire block as a single multi-line Bash tool call. The comment on the first line is REQUIRED - without it, command substitution $(...) causes parse errors.

If RUN_ID not found: Generate one now (for backwards compatibility with old specs):

# Generate timestamp-based hash for unique ID
TIMESTAMP=$(date +%s)
RUN_ID=$(echo "{feature-name}-$TIMESTAMP" | shasum -a 256 | head -c 6)
echo "Generated RUN_ID: $RUN_ID (spec missing runId)"

CRITICAL: Execute this entire block as a single multi-line Bash tool call. The comment on the first line is REQUIRED - without it, command substitution $(...) causes parse errors.

Spec Directory Pattern: Specs follow the pattern: specs/{run-id}-{feature-slug}/spec.md Plans are generated at: specs/{run-id}-{feature-slug}/plan.md

Announce: "Using RUN_ID: {run-id} for {feature-slug} implementation"

Step 0.5: Switch to Worktree Context

Second action: After extracting RUN_ID, switch to the worktree created by /spectacular:spec.

# Get absolute repo root to avoid recursive paths
REPO_ROOT=$(git rev-parse --show-toplevel)

# Check if already in correct worktree (avoid double cd)
CURRENT_DIR=$(pwd)
if [[ "$CURRENT_DIR" == "${REPO_ROOT}/.worktrees/${RUN_ID}-main" ]] || [[ "$CURRENT_DIR" == *"/.worktrees/${RUN_ID}-main" ]]; then
  echo "Already in worktree ${RUN_ID}-main"
else
  # Switch to worktree using absolute path
  cd "${REPO_ROOT}/.worktrees/${RUN_ID}-main"
fi

CRITICAL: Execute this entire block as a single multi-line Bash tool call. The comment on the first line is REQUIRED - without it, command substitution $(...) causes parse errors.

If worktree doesn't exist: Error immediately with clear message:

**Worktree Not Found**

The worktree for RUN_ID {run-id} doesn't exist.

Run `/spectacular:spec {feature}` first to create the workspace.

Expected worktree: .worktrees/{run-id}-main/

IMPORTANT: All subsequent operations happen in the worktree context.

  • Spec is read from: .worktrees/{run-id}-main/specs/{run-id}-{feature-slug}/spec.md
  • Plan will be written to: .worktrees/{run-id}-main/specs/{run-id}-{feature-slug}/plan.md
  • No fallback to main repo (worktree is required)

Step 1: Dispatch Subagent for Task Decomposition

Announce: "Dispatching subagent to generate execution plan from spec."

IMPORTANT: Delegate plan generation to a subagent to avoid context bloat. The subagent will read the spec, analyze tasks, and generate the plan in its isolated context.

Use the Task tool with general-purpose subagent type:

ROLE: Plan generation subagent for spectacular workflow

TASK: Generate execution plan from feature specification

SPEC_PATH: .worktrees/{run-id}-main/specs/{run-id}-{feature-slug}/spec.md
RUN_ID: {run-id}
FEATURE_SLUG: {feature-slug}

IMPLEMENTATION:

**Announce:** "I'm performing task decomposition to create an execution plan."

Follow the Task Decomposition Process below to analyze the spec and generate a plan.

**The process will:**

1. Read the spec from SPEC_PATH above
2. Extract or design tasks (handles specs with OR without Implementation Plan section)
3. Validate task quality (no XL tasks, explicit files, proper chunking)
4. Analyze file dependencies between tasks
5. Group tasks into phases (sequential or parallel)
6. Calculate execution time estimates with parallelization savings
7. Generate plan.md in the spec directory

**Critical validations:**
- XL tasks (>8h) -> Must split before planning
- Missing files -> Must specify exact paths
- Missing acceptance criteria -> Must add 3-5 criteria
- Wildcard patterns -> Must be explicit
- Too many S tasks (>30%) -> Bundle into thematic M/L tasks

**Plan output location:**
.worktrees/{run-id}-main/specs/{run-id}-{feature-slug}/plan.md

**Plan frontmatter must include:**
```yaml
---
runId: {run-id}
feature: {feature-slug}
created: YYYY-MM-DD
status: ready
---

After plan generation: Report back to orchestrator with:

  • Plan location
  • Summary of phases and tasks
  • Parallelization time savings
  • Any validation issues encountered

If validation fails, report issues clearly so user can fix spec and re-run.


**Wait for subagent completion** before proceeding to Step 2.

### Step 2: Review Plan Output

After subagent completes, review the generated plan:

```bash
cat specs/{run-id}-{feature-slug}/plan.md

Verify:

  • Phase strategies make sense (parallel for independent tasks)
  • Dependencies are correct (based on file overlaps)
  • No XL tasks (all split into M or smaller)
  • Time savings calculation looks reasonable

Step 2.5: Commit Plan to Worktree

After plan generation and review, commit the plan to the {run-id}-main branch in the worktree:

cd .worktrees/${RUN_ID}-main
git add specs/
git commit -m "plan: add ${FEATURE_SLUG} implementation plan [${RUN_ID}]"

This ensures the plan is tracked in the worktree branch and doesn't affect the main repo.

Step 3: Report to User

IMPORTANT: After reporting completion, STOP HERE. Do not proceed to execution automatically. The user must review the plan and explicitly run /spectacular:execute when ready.

Provide comprehensive summary:

**Execution Plan Generated & Committed**

**RUN_ID**: {run-id}
**Feature**: {feature-slug}
**Location**: .worktrees/{run-id}-main/specs/{run-id}-{feature-slug}/plan.md
**Branch**: {run-id}-main (committed in worktree)

## Plan Summary

**Phases**: {count}

- Sequential: {count} phases ({tasks} tasks)
- Parallel: {count} phases ({tasks} tasks)

**Tasks**: {total-count}

- L (4-8h): {count}
- M (2-4h): {count}
- S (1-2h): {count}

## Time Estimates

**Sequential Execution**: {hours}h
**With Parallelization**: {hours}h
**Time Savings**: {hours}h ({percent}% faster)

## Parallelization Opportunities

{For each parallel phase:}

- **Phase {id}**: {task-count} tasks can run simultaneously
  - Tasks: {task-names}
  - Time: {sequential}h -> {parallel}h
  - Savings: {hours}h

## Next Steps (User Actions - DO NOT AUTO-EXECUTE)

**The plan command is complete. The following are suggestions for the user, not instructions to execute automatically.**

### 1. Review the Plan

```bash
cat .worktrees/{run-id}-main/specs/{run-id}-{feature-slug}/plan.md
```

Verify task breakdown, dependencies, and estimates are correct.

### 2. Execute the Plan (when ready)

```bash
/spectacular:execute @.worktrees/{run-id}-main/specs/{run-id}-{feature-slug}/plan.md
```

This is a separate command. Only run after reviewing the plan.

### 3. Modify Plan (if needed)

```bash
# Edit the plan file directly
vim .worktrees/{run-id}-main/specs/{run-id}-{feature-slug}/plan.md

# Commit changes
cd .worktrees/{run-id}-main
git add specs/
git commit -m "plan: adjust task breakdown [${RUN_ID}]"

# Then execute
/spectacular:execute @.worktrees/{run-id}-main/specs/{run-id}-{feature-slug}/plan.md
```


Task Decomposition Process

This section details how to transform a feature specification into a structured implementation plan. The subagent dispatched in Step 1 follows this process.

PR-Sized Chunks Philosophy

Tasks should be PR-sized, thematically coherent units - not mechanical file-by-file splits.

Think like a senior engineer:

  • Bad: "Add schema" + "Install dependency" + "Add routes" (3 tiny tasks)
  • Good: "Database Foundation" (schema + migration + dependencies as one unit)

Task chunking principles:

  1. Thematic Coherence - Task represents a complete "thing"

    • Complete subsystem (agent system with tools + config + types)
    • Complete layer (all service methods for a feature)
    • Complete feature slice (UI flow from form to preview to confirm)
  2. Natural PR Size - Reviewable in one sitting (4-7h)

    • M (3-5h): Sweet spot for most tasks
    • L (5-7h): Complex but coherent units (full UI layer, complete API surface)
    • S (1-2h): Rare - only for truly standalone work
  3. Logical Boundaries - Clear separation points

    • Layer boundaries (Models, Services, Actions, UI)
    • Subsystem boundaries (Agent, Import Service, API)
    • Feature boundaries (Auth, Import, Dashboard)
  4. Stackable - Dependencies flow cleanly

    • Database -> Logic -> API -> UI
    • Foundation -> Core -> Integration

Good chunking examples:

GOOD: PR-sized, thematic chunks
- Task 1: Database Foundation (M - 4h)
  - Schema changes + migration + dependency install
  - One coherent "foundation" PR

- Task 2: Agent System (L - 6h)
  - Agent config + tools + schemas + types
  - Complete agent subsystem as a unit

- Task 3: Import Service Layer (M - 4h)
  - All service methods + business logic
  - Clean layer boundary

- Task 4: API Surface (L - 6h)
  - Server actions + SSE route
  - Complete API interface

- Task 5: Import UI (L - 7h)
  - All components + page + integration
  - Complete user-facing feature

Total: 5 tasks, 27h
Each task is a reviewable PR that adds value
BAD: Too granular, mechanical splits
- Task 1: Add schema fields (S - 2h)
- Task 2: Create migration (S - 1h)
- Task 3: Install dependency (S - 1h)
- Task 4: Create agent config (M - 3h)
- Task 5: Create fetch tool (S - 1h)
- Task 6: Create schemas (S - 2h)
- Task 7: Create service (M - 4h)
- Task 8: Create actions (M - 3h)
- Task 9: Create SSE route (M - 3h)
- Task 10: Create form component (S - 2h)
- Task 11: Create progress component (S - 2h)
- Task 12: Create preview component (M - 2h)
- Task 13: Add routes (S - 1h)
- Task 14: Integrate components (S - 1h)

Total: 14 tasks, 28h
Too many tiny PRs, no coherent units

Bundling heuristics:

If you're creating S tasks, ask:

  • Can this bundle with a related M task?
  • Does this complete a subsystem or layer?
  • Would a senior engineer create a separate PR for this?

Common bundling patterns:

  • Schema + migration + dependencies -> "Database Foundation"
  • Agent + tools + schemas -> "Agent System"
  • Service + helper functions -> "Service Layer"
  • Actions + API routes -> "API Layer"
  • All UI components for a flow -> "UI Layer"

Decomposition Step 1: Read Spec and Extract/Design Tasks

Read the spec file and extract tasks. The spec may provide tasks in two ways:

Option A: Spec has "Implementation Plan" section (structured task breakdown)

  • Extract tasks directly from this section
  • Each task should have: ID, description, files, complexity, acceptance criteria

Option B: Spec has no "Implementation Plan" (lean spec - requirements only)

  • Analyze the requirements and design task breakdown yourself
  • Look at: Functional Requirements, Architecture section, Files to Create/Modify
  • Design PR-sized chunks following the chunking philosophy above
  • Create tasks that implement all requirements

For each task (extracted or designed), capture:

  • Task ID (from heading)
  • Description (what to implement)
  • Repo (multi-repo only - which repo this task belongs to)
  • Files (explicit paths from spec)
  • Complexity (S/M/L/XL - estimated hours)
  • Acceptance Criteria (checklist items)
  • Implementation Steps (detailed steps)

Example extraction:

Spec has:

### Task 1: Database Schema

**Complexity**: M (2-4h)
**Files**:

- prisma/schema.prisma
- prisma/migrations/

**Description**: Add VerificationToken model for Auth.js...

**Acceptance**:

- [ ] Model matches Auth.js spec
- [ ] Migration runs cleanly

Extract to:
{
id: "task-1-database-schema",
description: "Add VerificationToken model",
files: ["prisma/schema.prisma", "prisma/migrations/"],
complexity: "M",
estimated_hours: 3,
acceptance_criteria: [...],
steps: [...]
}

Multi-repo task extraction:

For each task, also capture:

  • Repo (multi-repo only): Which repo this task belongs to
{
  id: "task-1-1-database",
  repo: "backend",  // NEW FIELD - required in multi-repo mode
  files: ["prisma/schema.prisma"],
  ...
}

Validation in multi-repo mode:

  • Every task MUST have a repo field
  • Repo must be one of the detected repos in workspace
  • Files are relative to the repo root (not workspace root)

Decomposition Step 2: Validate Task Quality & Chunking

For each task, check for quality issues:

CRITICAL (must fix):

  • XL complexity (>8h) -> Must split into M/L tasks
  • No files specified -> Must add explicit file paths
  • No acceptance criteria -> Must add 3-5 testable criteria
  • Wildcard patterns (src/**/*.ts) -> Must use explicit paths
  • Too many S tasks (>30% of total) -> Bundle into thematic M/L tasks

HIGH (strongly recommend):

  • Standalone S task that could bundle with related work
  • L complexity (5-8h) -> Verify it's a coherent unit, not arbitrary split
  • 10 files -> Likely too large, consider splitting by subsystem

  • <50 char description -> Add more detail about what subsystem/layer this completes
  • <3 acceptance criteria -> Add more specific criteria

Chunking validation:

  • If task is S (1-2h), verify it's truly standalone:

    • Can't be bundled with schema/migration/dependencies?
    • Can't be bundled with related service/action/component?
    • Would a senior engineer create a separate PR for this?
  • If >50% of tasks are S, that's a red flag:

    • Likely too granular
    • Missing thematic coherence
    • Bundle related S tasks into M tasks

If CRITICAL issues found:

  • STOP and report issues to user
  • User must update spec or adjust chunking
  • Re-run skill after fixes

If only HIGH issues:

  • Report warnings
  • Offer to continue or fix

Decomposition Step 3: Analyze File Dependencies

Build dependency graph by analyzing file overlaps:

Algorithm:

For each task T1:
  For each task T2 (where T2 appears after T1):
    shared_files = intersection(T1.files, T2.files)

    If shared_files is not empty:
      T2.dependencies.add(T1.id)
      T2.dependency_reason = "Shares files: {shared_files}"

Example:

Task 1: ["prisma/schema.prisma"]
Task 2: ["src/lib/models/auth.ts"]
Task 3: ["prisma/schema.prisma", "src/types/auth.ts"]

Analysis:
- Task 2: No dependencies (no shared files with Task 1)
- Task 3: Depends on Task 1 (shares prisma/schema.prisma)

Architectural dependencies: Also add dependencies based on layer order:

  • Models -> Services -> Actions -> UI
  • Database -> Types -> Logic -> API -> Components

Cross-repo dependency analysis:

In multi-repo mode, tasks in DIFFERENT repos are automatically independent (no file conflicts possible):

Task A: repo: backend, files: [src/api.ts]
Task B: repo: frontend, files: [src/api.ts]

Analysis: INDEPENDENT (different repos, even same filename)

Tasks in the SAME repo follow normal dependency rules:

Task A: repo: backend, files: [prisma/schema.prisma]
Task B: repo: backend, files: [prisma/schema.prisma, src/models.ts]

Analysis: Task B depends on Task A (same repo, shared file)

Cross-repo sequential dependencies:

Some tasks have logical dependencies across repos (not file-based):

Task A: repo: shared-lib, files: [src/types.ts]  # Defines shared types
Task B: repo: backend, files: [src/api.ts]       # Uses shared types

Analysis: Task B should run after Task A (API depends on shared types)

Mark these with explicit depends_on in the plan.

Decomposition Step 4: Group into Phases

Group tasks into phases using dependency graph:

Phase grouping algorithm:

1. Start with tasks that have no dependencies (roots)
2. Group all independent roots into Phase 1
3. Remove roots from graph
4. Repeat until all tasks grouped

For each phase:
  - If all tasks independent: strategy = "parallel"
  - If any dependencies exist: strategy = "sequential"

Example:

Tasks:
- Task 1: [] (no deps)
- Task 2: [] (no deps)
- Task 3: [task-1, task-2]
- Task 4: [task-3]

Grouping:
Phase 1: [Task 1, Task 2] - parallel (independent)
Phase 2: [Task 3] - sequential (waits for Phase 1)
Phase 3: [Task 4] - sequential (waits for Phase 2)

Decomposition Step 5: Calculate Execution Estimates

For each phase, calculate:

  • Sequential time: Sum of all task hours
  • Parallel time: Max of all task hours (if parallel strategy)
  • Time savings: Sequential - Parallel

Example:

Phase 2 (parallel):
- Task A: 3h
- Task B: 2h
- Task C: 4h

Sequential: 3 + 2 + 4 = 9h
Parallel: max(3, 2, 4) = 4h
Savings: 9 - 4 = 5h (56% faster)

Decomposition Step 6: Generate plan.md

Write plan to {spec-directory}/plan.md:

Single-repo template:

# Feature: {Feature Name} - Implementation Plan

> **Generated by:** Task Decomposition skill
> **From spec:** {spec-path}
> **Created:** {date}

## Execution Summary

- **Total Tasks**: {count}
- **Total Phases**: {count}
- **Sequential Time**: {hours}h
- **Parallel Time**: {hours}h
- **Time Savings**: {hours}h ({percent}%)

**Parallel Opportunities:**

- Phase {id}: {task-count} tasks ({hours}h saved)

---

## Phase {N}: {Phase Name}

**Strategy**: {sequential|parallel}
**Reason**: {why this strategy}

### Task {ID}: {Name}

**Files**:

- {file-path-1}
- {file-path-2}

**Complexity**: {S|M|L} ({hours}h)

**Dependencies**: {[task-ids] or "None"}

**Description**:
{What to implement and why}

**Implementation Steps**:

1. {step-1}
2. {step-2}
3. {step-3}

**Acceptance Criteria**:

- [ ] {criterion-1}
- [ ] {criterion-2}
- [ ] {criterion-3}

**Mandatory Patterns**:

> **Constitution**: All code must follow @docs/constitutions/current/

See architecture.md for layer boundaries and patterns.md for required patterns.

**TDD**: Follow `test-driven-development` skill (write test first, watch fail, minimal code, watch pass)

**Quality Gates**:

```bash
pnpm biome check --write .
pnpm test {test-files}
```

{Repeat for all tasks in all phases}

Multi-repo plan template:

# Feature: {Feature Name} - Implementation Plan

> **Generated by:** Task Decomposition skill
> **From spec:** {spec-path}
> **Created:** {date}
> **Workspace Mode:** multi-repo
> **Repos:** backend, frontend, shared-lib

## Execution Summary

- **Total Tasks**: {count}
- **Total Phases**: {count}
- **Sequential Time**: {hours}h
- **Parallel Time**: {hours}h
- **Time Savings**: {hours}h ({percent}%)

**Parallel Opportunities:**

- Phase {id}: {task-count} tasks ({hours}h saved)

---

## Phase {N}: {Phase Name}

**Strategy**: {sequential|parallel}
**Repos in phase**: {list of repos with tasks in this phase}

### Task {ID}: {Name}

**Repo**: {repo-name}
**Files**:

- {file-path-1}
- {file-path-2}

**Constitution**: @{repo-name}/docs/constitutions/current/

**Complexity**: {S|M|L} ({hours}h)

**Dependencies**: {[task-ids] or "None"}
**Cross-repo dependencies**: {[task-ids in other repos] or "None"}

**Description**:
{What to implement and why}

**Implementation Steps**:

1. {step-1}
2. {step-2}
3. {step-3}

**Acceptance Criteria**:

- [ ] {criterion-1}
- [ ] {criterion-2}
- [ ] {criterion-3}

**Mandatory Patterns**:

> **Constitution**: All code must follow @{repo-name}/docs/constitutions/current/

See architecture.md for layer boundaries and patterns.md for required patterns.

**TDD**: Follow `test-driven-development` skill (write test first, watch fail, minimal code, watch pass)

**Quality Gates**:

```bash
cd {repo-name}
pnpm biome check --write .
pnpm test {test-files}
```

{Repeat for all tasks in all phases}


### Decomposition Step 7: Report to Orchestrator

After generating plan, report back to orchestrator with:

**Single-repo report:**

```markdown
Task Decomposition Complete

**Plan Location**: specs/{run-id}-{feature-slug}/plan.md

## Breakdown
- Phases: {count}
- Tasks: {count}
- Complexity: {XL}: {n}, {L}: {n}, {M}: {n}, {S}: {n}

## Execution Strategy
- Sequential Phases: {count} ({tasks} tasks)
- Parallel Phases: {count} ({tasks} tasks)

## Time Estimates
- Sequential Execution: {hours}h
- With Parallelization: {hours}h
- **Time Savings: {hours}h ({percent}% faster)**
```

**Multi-repo report:**

```markdown
Task Decomposition Complete

**Plan Location**: specs/{run-id}-{feature-slug}/plan.md
**Workspace Mode**: multi-repo

## Per-Repo Breakdown

| Repo | Tasks | Hours |
|------|-------|-------|
| backend | 4 | 12h |
| frontend | 3 | 9h |
| shared-lib | 1 | 2h |

## Execution Strategy
- Sequential Phases: {count} ({tasks} tasks)
- Parallel Phases: {count} ({tasks} tasks)

## Cross-Repo Parallelization
- Phase 2: backend + frontend tasks run in parallel (different repos)
- Time saved: 6h (tasks execute simultaneously in separate repos)

## Time Estimates
- Sequential Execution: {hours}h
- With Parallelization: {hours}h
- **Time Savings: {hours}h ({percent}% faster)**

Quality Rules

Task Sizing (PR-focused):

  • S (1-2h): Rare - only truly standalone work (e.g., config-only changes)
    • Most S tasks should bundle into M
    • Ask: "Would a senior engineer PR this alone?"
  • M (3-5h): Sweet spot - most tasks should be this size
    • Complete subsystem, layer, or feature slice
    • Reviewable in one sitting
    • Thematically coherent unit
  • L (5-7h): Complex coherent units (use for major subsystems)
    • Full UI layer with all components
    • Complete API surface (actions + routes)
    • Major feature integration
  • XL (>8h): NEVER - always split into M/L tasks

Chunking Standards:

  • <30% S tasks is a red flag (too granular)
  • Most tasks should be M (60-80%)
  • Some L tasks for major units (10-30%)
  • Rare S tasks for truly standalone work (<10%)

File Specificity:

  • Good: src/lib/models/auth.ts
  • Good: src/components/auth/LoginForm.tsx
  • Bad: src/**/*.ts (too vague)
  • Bad: src/lib/models/ (specify exact files)

Acceptance Criteria:

  • 3-5 specific, testable criteria
  • Quantifiable (tests pass, build succeeds, API returns 200)
  • Not vague ("works well", "is good")
  • Not too many (>7 - task is too large)

Dependencies:

  • Minimal (only true blockers)
  • Explicit reasons (shares file X)
  • No circular dependencies
  • Not over-constrained (everything depends on everything)

Error Handling

Missing Worktree

If the worktree doesn't exist when trying to switch context:

**Worktree Not Found**

The worktree for RUN_ID {run-id} doesn't exist at .worktrees/{run-id}-main/

This means `/spectacular:spec` hasn't been run yet for this feature.

## Resolution

1. Run `/spectacular:spec {feature-description}` first to create the worktree
2. Then run `/spectacular:plan @.worktrees/{run-id}-main/specs/{run-id}-{feature-slug}/spec.md`

Or if you have an existing spec in the main repo, it needs to be migrated to a worktree first.

Validation Failures

If the skill finds quality issues:

**Plan Generation Failed - Spec Quality Issues**

The spec has issues that prevent task decomposition:

**CRITICAL Issues** (must fix):
- Task 3: XL complexity (12h estimated) - split into M/L tasks
- Task 5: No files specified - add explicit file paths
- Task 7: No acceptance criteria - add 3-5 testable criteria
- Too many S tasks (5 of 8 = 63%) - bundle into thematic M/L tasks

**HIGH Issues** (strongly recommend):
- Task 2 (S - 1h): "Add routes" - bundle with UI components task
- Task 4 (S - 2h): "Create schemas" - bundle with agent or service task
- Task 6: Wildcard pattern `src/**/*.ts` - specify exact files

## Fix These Issues

1. Edit the spec at {spec-path}
2. Address all CRITICAL issues (required)
3. Consider fixing HIGH issues (recommended)
4. Bundle S tasks into thematic M/L tasks for better PR structure
5. Re-run: `/spectacular:plan @{spec-path}`

No Tasks Found

If spec has no "Implementation Plan" section and insufficient detail:

**Cannot Generate Plan - No Tasks Found**

The spec at {spec-path} doesn't have an "Implementation Plan" section with tasks,
and lacks sufficient detail to design tasks automatically.

The spec must have either:
- An "Implementation Plan" section with tasks, OR
- Sufficient requirements and architecture details to design tasks

Current spec has:
- Functional Requirements: [YES/NO]
- Architecture section: [YES/NO]
- Files to create/modify: [YES/NO]

Use `/spectacular:spec` to generate a complete spec with task breakdown first:

```bash
/spectacular:spec "your feature description"

Then run /spectacular:plan on the generated spec.


### Circular Dependencies

If tasks have circular dependencies:

```markdown
**Circular Dependencies Detected**

The task dependency graph has cycles:
- Task A depends on Task B
- Task B depends on Task C
- Task C depends on Task A

This makes execution impossible.

## Resolution

Review the task file dependencies in the spec:
1. Check which files each task modifies
2. Ensure dependencies flow in one direction
3. Consider splitting tasks to break cycles
4. Re-run `/spectacular:plan` after fixing

Integration with Other Skills

Before: Use brainstorming and spec-feature to create complete spec

After: Use /spectacular:execute command to run plan with subagent-driven-development

Pairs with:

  • subagent-driven-development - Executes individual tasks
  • finishing-a-development-branch - Completes implementation

Project-Specific Configuration

For projects with a constitution, reference it in every task:

Constitution: All tasks MUST follow @docs/constitutions/current/

Every task must include:

  • Reference to constitution for architecture (layer boundaries, dependencies)
  • Reference to constitution for patterns (validation, state management, etc.)
  • Quality gates (linting, testing, building)

Quality gates:

pnpm biome check --write .
pnpm test

Important Notes

  • Automatic strategy selection - Skill analyzes dependencies and chooses sequential vs parallel
  • File-based dependencies - Tasks sharing files must run sequentially
  • Quality gates - Validates before generating (prevents bad plans)
  • Architecture adherence - All tasks must follow project constitution at @docs/constitutions/current/

Executing Parallel Phase

Overview

Parallel phases enable TRUE concurrent execution via isolated git worktrees, not just logical independence.

Critical distinction: Worktrees are not an optimization to prevent file conflicts. They're the ARCHITECTURE that enables multiple subagents to work simultaneously.

When to Use

Use this skill when execute command encounters a phase marked "Parallel" in plan.md:

  • ✅ Always use for N≥2 tasks
  • ✅ Always use for N=1 (maintains architecture consistency)
  • ✅ Even when files don't overlap
  • ✅ Even under time pressure
  • ✅ Even with disk space pressure

Never skip worktrees for parallel phases. No exceptions.

The Iron Law

PARALLEL PHASE = WORKTREES + SUBAGENTS

Violations of this law:

  • ❌ Execute in main worktree ("files don't overlap")
  • ❌ Skip worktrees for N=1 ("basically sequential")
  • ❌ Use sequential strategy ("simpler")

All of these destroy the parallel execution architecture.

Multi-Repo Support

Receiving Multi-Repo Context

The orchestrator passes this context for multi-repo execution:

  • WORKSPACE_MODE: "multi-repo" or "single-repo"
  • WORKSPACE_ROOT: Absolute path to workspace
  • Per-task TASK_REPO from plan

Multi-Repo Worktree Creation

In multi-repo mode, create worktrees INSIDE each task's repo:

Single-repo (current):

git worktree add .worktrees/${RUN_ID}-task-${PHASE}-${TASK} ...

Multi-repo (new):

# Worktree goes inside the task's repo
cd ${TASK_REPO}
git worktree add .worktrees/${RUN_ID}-task-${PHASE}-${TASK} ...
cd ${WORKSPACE_ROOT}

Per-Repo Setup Commands

In multi-repo mode, read setup commands from each task's repo:

# Single-repo: Read from project root CLAUDE.md
INSTALL_CMD=$(grep -A1 "**install**:" CLAUDE.md | tail -1)

# Multi-repo: Read from task's repo CLAUDE.md
INSTALL_CMD=$(grep -A1 "**install**:" ${TASK_REPO}/CLAUDE.md | tail -1)

Per-Repo Constitution

Pass the correct constitution path to subagents:

# Single-repo
CONSTITUTION="@docs/constitutions/current/"

# Multi-repo
CONSTITUTION="@${TASK_REPO}/docs/constitutions/current/"

Rationalization Table

Predictable shortcuts you WILL be tempted to make. DO NOT make them.

TemptationWhy It's WrongWhat To Do
"The spec is too long, I'll just read the task description"Task = WHAT files + verification. Spec = WHY architecture + requirements. Missing spec → drift.Read the full spec. It's 2-5 minutes that prevents hours of rework.
"I already read the constitution, that's enough context"Constitution = HOW to code. Spec = WHAT to build. Both needed for anchored implementation.Read constitution AND spec, every time.
"The acceptance criteria are clear, I don't need the spec"Acceptance criteria = tests pass, files exist. Spec = user flow, business logic, edge cases.Acceptance criteria verify implementation. Spec defines requirements.
"I'm a subagent in a parallel phase, other tasks probably read the spec"Each parallel subagent has isolated context. Other tasks' spec reading doesn't transfer.Every subagent reads spec independently. No assumptions.
"The spec doesn't exist / I can't find it"If spec missing, STOP and report error. Never proceed without spec.Check specs/{run-id}-{feature-slug}/spec.md. If missing, fail loudly.
"I'll implement first, then check spec to verify"Spec informs design decisions. Checking after implementation means rework.Read spec BEFORE writing any code.

If you find yourself thinking "I can skip the spec because..." - STOP. You're rationalizing. Read the spec.

The Process

Announce: "I'm using executing-parallel-phase to orchestrate {N} concurrent tasks in Phase {phase-id}."

Step 1: Pre-Conditions Verification (MANDATORY)

Before ANY worktree creation, verify the environment is correct:

Multi-repo pre-conditions:

if [ "$WORKSPACE_MODE" = "multi-repo" ]; then
  # Verify each task's repo exists
  for TASK_REPO in ${TASK_REPOS}; do
    if [ ! -d "${WORKSPACE_ROOT}/${TASK_REPO}/.git" ]; then
      echo "❌ Error: Repo not found: ${TASK_REPO}"
      exit 1
    fi
    echo "✅ Verified repo: ${TASK_REPO}"
  done

  # No main worktree to verify in multi-repo mode
  echo "✅ Multi-repo mode: Worktrees created per-task in each repo"

  # Verify workspace root
  if [ ! -d "${WORKSPACE_ROOT}" ]; then
    echo "❌ Error: Workspace root not found: ${WORKSPACE_ROOT}"
    exit 1
  fi
  echo "✅ Workspace root verified: ${WORKSPACE_ROOT}"
fi

Single-repo mode: Continue with existing pre-condition checks:

if [ "$WORKSPACE_MODE" != "multi-repo" ]; then
  # Get main repo root
  REPO_ROOT=$(git rev-parse --show-toplevel)
  CURRENT=$(pwd)

  # Check 1: Verify orchestrator is in main repo root
  if [ "$CURRENT" != "$REPO_ROOT" ]; then
    echo "❌ Error: Orchestrator must run from main repo root"
    echo "Current: $CURRENT"
    echo "Expected: $REPO_ROOT"
    echo ""
    echo "Return to main repo: cd $REPO_ROOT"
    exit 1
  fi

  echo "✅ Orchestrator location verified: Main repo root"

  # Check 2: Verify main worktree exists
  if [ ! -d .worktrees/{runid}-main ]; then
    echo "❌ Error: Main worktree not found at .worktrees/{runid}-main"
    echo "Run /spectacular:spec first to create the workspace."
    exit 1
  fi

  # Check 3: Verify main branch exists
  if ! git rev-parse --verify {runid}-main >/dev/null 2>&1; then
    echo "❌ Error: Branch {runid}-main does not exist"
    echo "Spec must be created before executing parallel phase."
    exit 1
  fi

  # Check 4: Verify we're on correct base branch for this phase
  CURRENT_BRANCH=$(git -C .worktrees/{runid}-main branch --show-current)
  EXPECTED_BASE="{expected-base-branch}"  # From plan: previous phase's last task, or {runid}-main for Phase 1

  if [ "$CURRENT_BRANCH" != "$EXPECTED_BASE" ]; then
    echo "❌ Error: Phase {phase-id} starting from unexpected branch"
    echo "   Current: $CURRENT_BRANCH"
    echo "   Expected: $EXPECTED_BASE"
    echo ""
    echo "Parallel phases must start from the correct base branch."
    echo "All parallel tasks will stack onto: $CURRENT_BRANCH"
    echo ""
    echo "If $CURRENT_BRANCH is wrong, the entire phase will be misplaced in the stack."
    echo ""
    echo "To fix:"
    echo "1. Verify previous phase completed: git log --oneline $EXPECTED_BASE"
    echo "2. Switch to correct base: cd .worktrees/{runid}-main && git checkout $EXPECTED_BASE"
    echo "3. Re-run /spectacular:execute"
    exit 1
  fi

  echo "✅ Phase {phase-id} starting from correct base: $CURRENT_BRANCH"
  echo "✅ Pre-conditions verified - safe to create task worktrees"
fi

Why mandatory:

  • Prevents nested worktrees from wrong location (9f92a8 regression)
  • Catches upstream drift (execute.md or other skill left orchestrator in wrong place)
  • Catches missing prerequisites before wasting time on worktree creation
  • Provides clear error messages for common setup issues

Red flag: "Skip verification to save time" - NO. 20ms verification saves hours of debugging.

Step 1.5: Check for Existing Work (Resume Support)

Before creating worktrees, check if tasks are already complete:

Multi-repo resume check:

if [ "$WORKSPACE_MODE" = "multi-repo" ]; then
  COMPLETED_TASKS=()
  PENDING_TASKS=()

  for TASK_ID in ${TASK_IDS}; do
    TASK_REPO="${TASK_REPOS[$TASK_ID]}"
    cd ${WORKSPACE_ROOT}/${TASK_REPO}

    # Use pattern matching to find branch (short-name varies)
    BRANCH_PATTERN="${RUN_ID}-task-${TASK_ID}-"
    BRANCH_NAME=$(git branch | grep "^  ${BRANCH_PATTERN}" | sed 's/^  //' | head -n1)

    if [ -n "$BRANCH_NAME" ]; then
      echo "✓ Task ${TASK_ID} (${TASK_REPO}) already complete: $BRANCH_NAME"
      COMPLETED_TASKS+=("$TASK_ID")
    else
      PENDING_TASKS+=("$TASK_ID")
    fi

    cd ${WORKSPACE_ROOT}
  done

  if [ ${#PENDING_TASKS[@]} -eq 0 ]; then
    echo "✅ All tasks already complete, skipping to stacking"
    # Jump to Step 6 (Stacking)
  else
    echo "📋 Resuming: ${#COMPLETED_TASKS[@]} complete, ${#PENDING_TASKS[@]} pending"
    echo "Will execute tasks: ${PENDING_TASKS[*]}"
  fi
fi

Single-repo resume check:

if [ "$WORKSPACE_MODE" != "multi-repo" ]; then
  COMPLETED_TASKS=()
  PENDING_TASKS=()

  for TASK_ID in {task-ids}; do
    # Use pattern matching to find branch (short-name varies)
    BRANCH_PATTERN="{runid}-task-{phase-id}-${TASK_ID}-"
    BRANCH_NAME=$(git branch | grep "^  ${BRANCH_PATTERN}" | sed 's/^  //' | head -n1)

    if [ -n "$BRANCH_NAME" ]; then
      echo "✓ Task ${TASK_ID} already complete: $BRANCH_NAME"
      COMPLETED_TASKS+=("$TASK_ID")
    else
      PENDING_TASKS+=("$TASK_ID")
    fi
  done

  if [ ${#PENDING_TASKS[@]} -eq 0 ]; then
    echo "✅ All tasks already complete, skipping to stacking"
    # Jump to Step 6 (Stacking)
  else
    echo "📋 Resuming: ${#COMPLETED_TASKS[@]} complete, ${#PENDING_TASKS[@]} pending"
    echo "Will execute tasks: ${PENDING_TASKS[*]}"
  fi
fi

Why check: Enables resume after fixing failed tasks. Avoids re-executing successful tasks, which wastes time and can cause conflicts.

Red flags:

  • "Always create all worktrees" - NO. Wastes resources on already-completed work.
  • "Trust orchestrator state" - NO. Branches are source of truth.

Step 2: Create Worktrees (BEFORE Subagents)

Create isolated worktree for EACH PENDING task (skip completed tasks):

Multi-repo worktree creation:

For each task, create worktree in the task's repo:

if [ "$WORKSPACE_MODE" = "multi-repo" ]; then
  for TASK_ID in "${PENDING_TASKS[@]}"; do
    # Get task's repo from plan
    TASK_REPO="${TASK_REPOS[$TASK_ID]}"  # e.g., "backend"

    # Get base branch for this repo (each repo may have different base)
    cd ${WORKSPACE_ROOT}/${TASK_REPO}
    BASE_BRANCH=$(git branch --show-current)

    # Create worktree inside task's repo
    git worktree add ".worktrees/${RUN_ID}-task-${TASK_ID}" --detach "$BASE_BRANCH"
    echo "✅ Created ${TASK_REPO}/.worktrees/${RUN_ID}-task-${TASK_ID} (detached HEAD)"

    cd ${WORKSPACE_ROOT}
  done

  # Verify all worktrees created across repos
  for TASK_ID in "${PENDING_TASKS[@]}"; do
    TASK_REPO="${TASK_REPOS[$TASK_ID]}"
    if [ ! -d "${WORKSPACE_ROOT}/${TASK_REPO}/.worktrees/${RUN_ID}-task-${TASK_ID}" ]; then
      echo "❌ Error: Worktree not found: ${TASK_REPO}/.worktrees/${RUN_ID}-task-${TASK_ID}"
      exit 1
    fi
  done
  echo "✅ Created ${#PENDING_TASKS[@]} worktrees across repos for parallel execution"
fi

Parallel tasks across repos: Tasks in DIFFERENT repos can truly execute simultaneously:

  • Task 2.1 (backend) creates .worktrees/ in backend/
  • Task 2.2 (frontend) creates .worktrees/ in frontend/
  • No git conflicts - completely independent repos

Single-repo worktree creation:

if [ "$WORKSPACE_MODE" != "multi-repo" ]; then
  # Get base branch from main worktree
  BASE_BRANCH=$(git -C .worktrees/{runid}-main branch --show-current)

  # Create worktrees only for pending tasks (from Step 1.5)
  for TASK_ID in "${PENDING_TASKS[@]}"; do
    git worktree add ".worktrees/{runid}-task-${TASK_ID}" --detach "$BASE_BRANCH"
    echo "✅ Created .worktrees/{runid}-task-${TASK_ID} (detached HEAD)"
  done

  # Verify all worktrees created
  git worktree list | grep "{runid}-task-"

  CREATED_COUNT=$(git worktree list | grep -c "{runid}-task-")
  EXPECTED_COUNT=${#PENDING_TASKS[@]}

  if [ $CREATED_COUNT -ne $EXPECTED_COUNT ]; then
    echo "❌ Error: Expected $EXPECTED_COUNT worktrees, found $CREATED_COUNT"
    exit 1
  fi

  echo "✅ Created $CREATED_COUNT worktrees for parallel execution"
fi

Why --detach: Git doesn't allow same branch in multiple worktrees. Detached HEAD enables parallel worktrees.

Red flags:

  • "Only 1 task, skip worktrees" - NO. N=1 still uses architecture.
  • "Files don't overlap, skip isolation" - NO. Isolation enables parallelism, not prevents conflicts.

Step 3: Install Dependencies Per Worktree

Each PENDING worktree needs its own dependencies (skip completed tasks):

Multi-repo dependency installation:

if [ "$WORKSPACE_MODE" = "multi-repo" ]; then
  for TASK_ID in "${PENDING_TASKS[@]}"; do
    TASK_REPO="${TASK_REPOS[$TASK_ID]}"
    WORKTREE_PATH="${WORKSPACE_ROOT}/${TASK_REPO}/.worktrees/${RUN_ID}-task-${TASK_ID}"

    # Read setup commands from task's repo CLAUDE.md
    REPO_CLAUDE_MD="${WORKSPACE_ROOT}/${TASK_REPO}/CLAUDE.md"
    INSTALL_CMD=$(grep -A1 "**install**:" ${REPO_CLAUDE_MD} | tail -1 | sed 's/^- //')
    POSTINSTALL_CMD=$(grep -A1 "**postinstall**:" ${REPO_CLAUDE_MD} | tail -1 | sed 's/^- //')

    # Check for dependency marker (varies by ecosystem)
    if [ ! -d ${WORKTREE_PATH}/node_modules ] && [ ! -d ${WORKTREE_PATH}/venv ] && [ ! -d ${WORKTREE_PATH}/vendor ]; then
      echo "📦 Installing dependencies in ${TASK_REPO} worktree for Task ${TASK_ID}..."
      bash -c "cd ${WORKTREE_PATH} && ${INSTALL_CMD}"
      if [ -n "${POSTINSTALL_CMD}" ]; then
        bash -c "cd ${WORKTREE_PATH} && ${POSTINSTALL_CMD}"
      fi
    fi
  done
fi

Single-repo dependency installation:

if [ "$WORKSPACE_MODE" != "multi-repo" ]; then
  for TASK_ID in "${PENDING_TASKS[@]}"; do
    if [ ! -d .worktrees/{runid}-task-${TASK_ID}/node_modules ]; then
      bash -c "cd .worktrees/{runid}-task-${TASK_ID} && {install-command} && {postinstall-command}"
    fi
  done
fi

Why per-worktree: Isolated worktrees can't share node_modules.

Why bash -c: Orchestrator stays in main repo. Subshell navigates to worktree and exits after commands complete.

Why per-repo CLAUDE.md: In multi-repo mode, each repo may have different package managers, languages, or setup requirements. The frontend repo might use pnpm install while the backend uses pip install -r requirements.txt.

Red flag: "Share node_modules for efficiency" - Breaks isolation and causes race conditions.

Step 3.5: Extract Phase Context (Before Dispatching)

Before spawning subagents, extract phase boundaries from plan:

The orchestrator already parsed the plan in execute.md Step 1. Extract:

  • Current phase number and name
  • Tasks in THIS phase (what TO implement)
  • Tasks in LATER phases (what NOT to implement)

Format for subagent context:

PHASE CONTEXT:
- Phase {current-phase-id}/{total-phases}: {phase-name}
- This phase includes: Task {task-ids-in-this-phase}

LATER PHASES (DO NOT IMPLEMENT):
- Phase {next-phase}: {phase-name} - {task-summary}
- Phase {next+1}: {phase-name} - {task-summary}
...

If implementing work beyond this phase's tasks, STOP and report scope violation.

Why critical: Spec describes WHAT to build (entire feature). Plan describes HOW/WHEN (phase breakdown). Subagents need both to avoid scope creep.

Step 4: Dispatch Parallel Tasks

CRITICAL: Single message with multiple Task tool calls (true parallelism):

Only dispatch for PENDING tasks (from Step 1.5). Completed tasks already have branches and should not be re-executed.

Multi-repo subagent context:

When dispatching subagents in multi-repo mode, include per-task repo context:

WORKSPACE_MODE: multi-repo
WORKSPACE_ROOT: /home/user/workspace
TASK_REPO: backend
WORKTREE_PATH: backend/.worktrees/${RUN_ID}-task-2-1
CONSTITUTION: @backend/docs/constitutions/current/
SETUP_COMMANDS: (from backend/CLAUDE.md)

The subagent works entirely within its repo's worktree.

For each pending task, spawn subagent with embedded instructions (dispatch ALL in single message):

Task(Implement Task {task-id}: {task-name})

ROLE: Implement Task {task-id} in isolated worktree (parallel phase)

WORKSPACE MODE: {workspace-mode}  # "multi-repo" or "single-repo"
WORKSPACE ROOT: {workspace-root}  # Only in multi-repo mode
TASK REPO: {task-repo}            # Only in multi-repo mode (e.g., "backend")
WORKTREE: {worktree-path}         # Multi-repo: {task-repo}/.worktrees/{run-id}-task-{task-id}
                                  # Single-repo: .worktrees/{run-id}-task-{task-id}

TASK: {task-name}
FILES: {files-list}
ACCEPTANCE CRITERIA: {criteria}

PHASE BOUNDARIES:
===== PHASE BOUNDARIES - CRITICAL =====

Phase {current-phase-id}/{total-phases}: {phase-name}
This phase includes ONLY: Task {task-ids-in-this-phase}

DO NOT CREATE ANY FILES from later phases.

Later phases (DO NOT CREATE):
- Phase {next-phase}: {phase-name} - {task-summary}
  ❌ NO implementation files
  ❌ NO stub functions (even with TODOs)
  ❌ NO type definitions or interfaces
  ❌ NO test scaffolding or temporary code

If tempted to create ANY file from later phases, STOP.
"Not fully implemented" = violation.
"Just types/stubs/tests" = violation.
"Temporary/for testing" = violation.

==========================================

CONTEXT REFERENCES:
- Spec: specs/{run-id}-{feature-slug}/spec.md
- Constitution (multi-repo): {task-repo}/docs/constitutions/current/
- Constitution (single-repo): docs/constitutions/current/
- Plan: specs/{run-id}-{feature-slug}/plan.md
- Worktree: {worktree-path}

INSTRUCTIONS:

1. Navigate to isolated worktree:
   # Multi-repo mode:
   cd {workspace-root}/{task-repo}/.worktrees/{run-id}-task-{task-id}
   # Single-repo mode:
   cd .worktrees/{run-id}-task-{task-id}

2. Read constitution (if exists):
   # Multi-repo: {task-repo}/docs/constitutions/current/
   # Single-repo: docs/constitutions/current/

3. Read feature specification: specs/{run-id}-{feature-slug}/spec.md

   This provides:
   - WHAT to build (requirements, user flows)
   - WHY decisions were made (architecture rationale)
   - HOW features integrate (system boundaries)

   The spec is your source of truth for architectural decisions.
   Constitution tells you HOW to code. Spec tells you WHAT to build.

4. VERIFY PHASE SCOPE before implementing:
   - Read the PHASE BOUNDARIES section above
   - Confirm this task belongs to Phase {current-phase-id}
   - If tempted to implement later phase work, STOP
   - The plan exists for a reason - respect phase boundaries

5. Implement task following spec + constitution + phase boundaries

6. Run quality checks with exit code validation:

   **CRITICAL**: Use heredoc to prevent bash parsing errors:

   # Quality commands come from the task's repo CLAUDE.md in multi-repo mode
   bash <<'EOF'
   {test-command}   # e.g., npm test, pytest, go test
   if [ $? -ne 0 ]; then
     echo "❌ Tests failed"
     exit 1
   fi

   {lint-command}   # e.g., npm run lint, ruff check, golangci-lint
   if [ $? -ne 0 ]; then
     echo "❌ Lint failed"
     exit 1
   fi

   {build-command}  # e.g., npm run build, python -m build, go build
   if [ $? -ne 0 ]; then
     echo "❌ Build failed"
     exit 1
   fi
   EOF

   **Why heredoc**: Prevents parsing errors when commands are wrapped by orchestrator.

7. Create branch and detach HEAD using verification skill:

   Skill: phase-task-verification

   Parameters:
   - RUN_ID: {run-id}
   - TASK_ID: {phase}-{task}
   - TASK_NAME: {short-name}
   - COMMIT_MESSAGE: "[Task {phase}.{task}] {task-name}"
   - MODE: parallel

   The verification skill will:
   a) Stage changes with git add .
   b) Create branch with gs branch create
   c) Detach HEAD with git switch --detach
   d) Verify HEAD is detached (makes branch accessible in parent repo)

8. Report completion

CRITICAL:
- Work in {worktree-path}, NOT main repo or workspace root
- Do NOT stay on branch - verification skill detaches HEAD
- Do NOT create additional worktrees
- Do NOT implement work from later phases (check PHASE BOUNDARIES above)
- In multi-repo mode, branches are created in task's repo, not workspace root

Parallel dispatch: All pending tasks dispatched in single message (true concurrency).

Red flags:

  • "I'll just do it myself" - NO. Subagents provide fresh context.
  • "Execute sequentially in main worktree" - NO. Destroys parallelism.
  • "Spec mentions feature X, I'll implement it now" - NO. Check phase boundaries first.
  • "I'll run git add myself" - NO. Let subagent use phase-task-verification skill.

Step 5: Verify Completion (BEFORE Stacking)

Check ALL task branches exist AND have commits (includes both previously completed and newly created):

Multi-repo verification:

if [ "$WORKSPACE_MODE" = "multi-repo" ]; then
  COMPLETED_TASKS=()
  FAILED_TASKS=()

  for TASK_ID in ${TASK_IDS}; do
    TASK_REPO="${TASK_REPOS[$TASK_ID]}"
    cd ${WORKSPACE_ROOT}/${TASK_REPO}

    # Get base branch for this repo
    BASE_BRANCH=$(git branch --show-current)
    BASE_SHA=$(git rev-parse "$BASE_BRANCH")

    # Use pattern matching to find branch
    BRANCH_PATTERN="${RUN_ID}-task-${TASK_ID}-"
    BRANCH_NAME=$(git branch | grep "^  ${BRANCH_PATTERN}" | sed 's/^  //' | head -n1)

    if [ -z "$BRANCH_NAME" ]; then
      FAILED_TASKS+=("Task ${TASK_ID} (${TASK_REPO}): Branch not found")
      cd ${WORKSPACE_ROOT}
      continue
    fi

    # Verify branch has commits beyond base
    BRANCH_SHA=$(git rev-parse "$BRANCH_NAME")
    if [ "$BRANCH_SHA" = "$BASE_SHA" ]; then
      FAILED_TASKS+=("Task ${TASK_ID} (${TASK_REPO}): Branch '$BRANCH_NAME' has no commits")
      cd ${WORKSPACE_ROOT}
      continue
    fi

    COMPLETED_TASKS+=("Task ${TASK_ID} (${TASK_REPO}): $BRANCH_NAME @ $BRANCH_SHA")
    cd ${WORKSPACE_ROOT}
  done

  if [ ${#FAILED_TASKS[@]} -gt 0 ]; then
    echo "❌ Phase {phase-id} execution failed"
    echo ""
    echo "Completed tasks:"
    for task in "${COMPLETED_TASKS[@]}"; do
      echo "  ✅ $task"
    done
    echo ""
    echo "Failed tasks:"
    for task in "${FAILED_TASKS[@]}"; do
      echo "  ❌ $task"
    done
    echo ""
    echo "To resume:"
    echo "1. Review subagent output above for failure details"
    echo "2. Fix failed task(s) in {task-repo}/.worktrees/${RUN_ID}-task-{task-id}"
    echo "3. Re-run /spectacular:execute to complete phase"
    exit 1
  fi

  echo "✅ All tasks completed with valid commits across repos"
fi

Single-repo verification:

if [ "$WORKSPACE_MODE" != "multi-repo" ]; then
  COMPLETED_TASKS=()
  FAILED_TASKS=()

  # Get base commit to verify branches have new work
  BASE_BRANCH=$(git -C .worktrees/{runid}-main branch --show-current)
  BASE_SHA=$(git rev-parse "$BASE_BRANCH")

  # Check ALL task IDs, not just pending - need to verify complete set exists
  for TASK_ID in {task-ids}; do
    # Use pattern matching to find branch (short-name varies)
    BRANCH_PATTERN="{runid}-task-{phase-id}-${TASK_ID}-"
    BRANCH_NAME=$(git branch | grep "^  ${BRANCH_PATTERN}" | sed 's/^  //' | head -n1)

    if [ -z "$BRANCH_NAME" ]; then
      FAILED_TASKS+=("Task ${TASK_ID}: Branch not found")
      continue
    fi

    # Verify branch has commits beyond base
    BRANCH_SHA=$(git rev-parse "$BRANCH_NAME")
    if [ "$BRANCH_SHA" = "$BASE_SHA" ]; then
      FAILED_TASKS+=("Task ${TASK_ID}: Branch '$BRANCH_NAME' has no commits (still at base $BASE_SHA)")
      continue
    fi

    COMPLETED_TASKS+=("Task ${TASK_ID}: $BRANCH_NAME @ $BRANCH_SHA")
  done

  if [ ${#FAILED_TASKS[@]} -gt 0 ]; then
    echo "❌ Phase {phase-id} execution failed"
    echo ""
    echo "Completed tasks:"
    for task in "${COMPLETED_TASKS[@]}"; do
      echo "  ✅ $task"
    done
    echo ""
    echo "Failed tasks:"
    for task in "${FAILED_TASKS[@]}"; do
      echo "  ❌ $task"
    done
    echo ""
    echo "Common causes:"
    echo "- Subagent failed to implement task (check output above)"
    echo "- Quality checks blocked commit (test/lint/build failures)"
    echo "- git add . found no changes (implementation missing)"
    echo "- gs branch create failed (check git-spice errors)"
    echo ""
    echo "To resume:"
    echo "1. Review subagent output above for failure details"
    echo "2. Fix failed task(s) in .worktrees/{runid}-task-{task-id}"
    echo "3. Run quality checks manually to verify fixes"
    echo "4. Create branch manually: gs branch create {runid}-task-{phase-id}-{task-id}-{name} -m 'message'"
    echo "5. Re-run /spectacular:execute to complete phase"
    exit 1
  fi

  echo "✅ All {task-count} tasks completed with valid commits"
fi

Why verify: Agents can fail. Quality checks can block commits. Verify branches exist before stacking.

Red flags:

  • "Agents said success, skip check" - NO. Agent reports ≠ branch existence.
  • "Trust but don't verify" - NO. Verify preconditions.

Step 6: Stack Branches Linearly (BEFORE Cleanup)

Multi-repo stacking:

Each repo has its own stack. After parallel phase:

if [ "$WORKSPACE_MODE" = "multi-repo" ]; then
  # Group tasks by repo
  declare -A REPO_TASKS
  for TASK_ID in ${TASK_IDS}; do
    TASK_REPO="${TASK_REPOS[$TASK_ID]}"
    REPO_TASKS[$TASK_REPO]+="${TASK_ID} "
  done

  # Stack branches within each repo
  for REPO in "${!REPO_TASKS[@]}"; do
    echo "📋 Stacking branches in ${REPO}..."
    cd ${WORKSPACE_ROOT}/${REPO}

    # Get tasks for this repo
    TASKS=(${REPO_TASKS[$REPO]})

    # Get base branch for this repo
    BASE_BRANCH=$(git branch --show-current)

    # Ensure base branch is tracked
    if ! gs branch track --show "$BASE_BRANCH" >/dev/null 2>&1; then
      echo "⏺ Base branch not tracked yet, tracking now: $BASE_BRANCH"
      git checkout "$BASE_BRANCH"
      gs branch track
    fi

    # Stack this repo's task branches
    for i in "${!TASKS[@]}"; do
      TASK_ID="${TASKS[$i]}"
      BRANCH="${RUN_ID}-task-${TASK_ID}"

      if [ $i -eq 0 ]; then
        git checkout "$BRANCH"
        gs branch track
        gs upstack onto "$BASE_BRANCH"
      else
        PREV_TASK="${TASKS[$((i-1))]}"
        PREV_BRANCH="${RUN_ID}-task-${PREV_TASK}"
        git checkout "$BRANCH"
        gs branch track
        gs upstack onto "$PREV_BRANCH"
      fi
    done

    echo "✅ ${REPO} stack complete:"
    gs log short
    echo ""

    cd ${WORKSPACE_ROOT}
  done

  echo "✅ All repo stacks complete"
fi

Note: Cannot stack across repos (git-spice limitation). Each repo maintains its own linear stack.

Single-repo stacking:

Use loop-based algorithm for any N (orchestrator stays in main repo):

if [ "$WORKSPACE_MODE" != "multi-repo" ]; then
  # Stack branches in main worktree using heredoc (orchestrator doesn't cd)
  bash <<'EOF'
  cd .worktrees/{runid}-main

  # Get base branch (what parallel tasks should stack onto)
  BASE_BRANCH=$(git branch --show-current)

  # Ensure base branch is tracked before stacking onto it
  # (Sequential phases may have created branches without tracking)
  if ! gs branch track --show "$BASE_BRANCH" >/dev/null 2>&1; then
    echo "⏺ Base branch not tracked yet, tracking now: $BASE_BRANCH"
    git checkout "$BASE_BRANCH"
    gs branch track
  fi

  TASK_BRANCHES=( {array-of-branch-names} )
  TASK_COUNT=${#TASK_BRANCHES[@]}

  # Handle N=1 edge case
  if [ $TASK_COUNT -eq 1 ]; then
    git checkout "${TASK_BRANCHES[0]}"
    gs branch track
    gs upstack onto "$BASE_BRANCH"  # Explicitly set base for single parallel task
  else
    # Handle N≥2
    for i in "${!TASK_BRANCHES[@]}"; do
      BRANCH="${TASK_BRANCHES[$i]}"

      if [ $i -eq 0 ]; then
        # First task: track + upstack onto base branch (from previous phase)
        git checkout "$BRANCH"
        gs branch track
        gs upstack onto "$BASE_BRANCH"  # Connect to previous phase's work
      else
        # Subsequent: track + upstack onto previous
        PREV_BRANCH="${TASK_BRANCHES[$((i-1))]}"
        git checkout "$BRANCH"
        gs branch track
        gs upstack onto "$PREV_BRANCH"
      fi
    done
  fi

  # Leave main worktree on last branch for next phase continuity
  # Sequential phases will naturally stack on this branch

  # Display stack
  echo "📋 Stack after parallel phase:"
  gs log short
  echo ""

  # Verify stack correctness (catch duplicate commits)
  echo "🔍 Verifying stack integrity..."
  STACK_VALID=1
  declare -A SEEN_COMMITS

  for BRANCH in "${TASK_BRANCHES[@]}"; do
    BRANCH_SHA=$(git rev-parse "$BRANCH")

    # Check if this commit SHA was already seen
    if [ -n "${SEEN_COMMITS[$BRANCH_SHA]}" ]; then
      echo "❌ ERROR: Stack integrity violation"
      echo "   Branch '$BRANCH' points to commit $BRANCH_SHA"
      echo "   But '${SEEN_COMMITS[$BRANCH_SHA]}' already points to that commit"
      echo ""
      echo "This means one of these branches has no unique commits."
      echo "Possible causes:"
      echo "- Subagent failed to commit work"
      echo "- Quality checks blocked commit"
      echo "- Branch creation succeeded but commit failed"
      STACK_VALID=0
      break
    fi

    SEEN_COMMITS[$BRANCH_SHA]="$BRANCH"
    echo "  ✓ $BRANCH @ $BRANCH_SHA"
  done

  if [ $STACK_VALID -eq 0 ]; then
    echo ""
    echo "❌ Stack verification FAILED - preserving worktrees for debugging"
    echo ""
    echo "To investigate:"
    echo "1. Check branch commits: git log --oneline $BRANCH"
    echo "2. Check worktree state: ls -la .worktrees/"
    echo "3. Review subagent output for failed task"
    echo "4. Fix manually, then re-run /spectacular:execute"
    exit 1
  fi

  echo "✅ Stack integrity verified - all branches have unique commits"
EOF
fi

Why heredoc: Orchestrator stays in main repo. Heredoc creates subshell that navigates to worktree and exits.

Why before cleanup: Need worktrees accessible for debugging if stacking fails.

Why verify stack: Catches duplicate commits (two branches pointing to same SHA) which indicates missing work.

Red flag: "Clean up first to free disk space" - NO. Stacking MUST happen first, and verification before cleanup.

Step 7: Clean Up Worktrees (AFTER Stacking)

IMPORTANT: This step only runs if Step 5 verification passes. If any task fails, Step 5 exits with code 1, aborting the workflow. Failed task worktrees are preserved for debugging.

Multi-repo cleanup:

Remove worktrees from each repo:

if [ "$WORKSPACE_MODE" = "multi-repo" ]; then
  for TASK_ID in ${TASK_IDS}; do
    TASK_REPO="${TASK_REPOS[$TASK_ID]}"
    cd ${WORKSPACE_ROOT}/${TASK_REPO}
    git worktree remove ".worktrees/${RUN_ID}-task-${TASK_ID}" --force
    echo "✅ Removed ${TASK_REPO}/.worktrees/${RUN_ID}-task-${TASK_ID}"
    cd ${WORKSPACE_ROOT}
  done

  # Verify cleanup across all repos
  for REPO in ${REPOS_WITH_TASKS}; do
    REMAINING=$(cd ${WORKSPACE_ROOT}/${REPO} && git worktree list | grep "${RUN_ID}-task-" || true)
    if [ -n "$REMAINING" ]; then
      echo "⚠️  Worktrees remain in ${REPO}: $REMAINING"
    fi
  done
  echo "✅ Multi-repo worktree cleanup complete"
fi

Single-repo cleanup:

if [ "$WORKSPACE_MODE" != "multi-repo" ]; then
  for TASK_ID in {task-ids}; do
    git worktree remove ".worktrees/{runid}-task-${TASK_ID}"
  done

  # Verify cleanup
  git worktree list | grep "{runid}-task-"
  # Should be empty
fi

Why after stacking: Branches must be stacked and verified before destroying evidence.

Why conditional: Failed worktrees must be preserved so users can debug, fix, and manually create branches before resuming.

Step 8: Code Review (Binary Quality Gate)

Check review frequency setting (from execute.md Step 1.7):

REVIEW_FREQUENCY=${REVIEW_FREQUENCY:-per-phase}

If REVIEW_FREQUENCY is "end-only" or "skip":

Skipping per-phase code review (frequency: {REVIEW_FREQUENCY})
Phase {N} complete - proceeding to next phase

Mark phase complete and continue to next phase.

If REVIEW_FREQUENCY is "optimize":

Analyze the completed phase to decide if code review is needed:

High-risk indicators (REVIEW REQUIRED):

  • Schema or migration changes
  • Authentication/authorization logic
  • External API integrations or webhooks
  • Foundation phases (Phase 1-2 establishing patterns)
  • 3+ parallel tasks (coordination complexity)
  • New architectural patterns introduced
  • Security-sensitive code (payment, PII, access control)
  • Complex business logic with multiple edge cases
  • Changes affecting multiple layers (database → API → UI)

Low-risk indicators (SKIP REVIEW):

  • Pure UI component additions (no state/logic)
  • Documentation or comment updates
  • Test additions without implementation changes
  • Refactoring with existing test coverage
  • Isolated utility functions
  • Configuration file updates (non-security)

Analyze this phase:

  • Phase number: {N}
  • Tasks completed in parallel: {task-list}
  • Files modified across tasks: {file-list}
  • Types of changes: {describe changes}

Decision: If ANY high-risk indicator present → Proceed to code review below If ONLY low-risk indicators → Skip review:

✓ Phase {N} assessed as low-risk - skipping review (optimize mode)
  Reasoning: {brief explanation of why low-risk}
Phase {N} complete - proceeding to next phase

If REVIEW_FREQUENCY is "per-phase" OR optimize mode decided to review:

Use requesting-code-review skill to call code-reviewer agent, then parse results STRICTLY:

CRITICAL - AUTONOMOUS EXECUTION (NO USER PROMPTS):

This is an automated execution workflow. Code review rejections trigger automatic fix loops, NOT user prompts.

NEVER ask user what to do, even if:

  • Issues seem "architectural" or "require product decisions"
  • Scope creep with passing quality checks (implement less, not ask)
  • Multiple rejections (use escalation limit at 3, not ask user)
  • Uncertain how to fix (fix subagent figures it out with spec + constitution context)
  • Code works but violates plan (plan violation = failure, auto-fix to plan)

Autonomous execution means AUTONOMOUS. User prompts break automation and violate this skill.

  1. Dispatch code review:

    Skill tool: requesting-code-review
    
    Context provided to reviewer:
    - WORKTREE: .worktrees/{runid}-main
    - PHASE: {phase-number}
    - TASKS: {task-list}
    - BASE_BRANCH: {base-branch-name}
    - SPEC: specs/{run-id}-{feature-slug}/spec.md
    - PLAN: specs/{run-id}-{feature-slug}/plan.md (for phase boundary validation)
    
    **CRITICAL - EXHAUSTIVE FIRST-PASS REVIEW:**
    
    This is your ONLY opportunity to find issues. Re-review is for verifying fixes, NOT discovering new problems.
    
    Check EVERYTHING in this single review:
    □ Implementation correctness - logic bugs, edge cases, error handling, race conditions
    □ Test correctness - expectations match actual behavior, coverage is complete, no false positives
    □ Cross-file consistency - logic coherent across all files, no contradictions
    □ Architectural soundness - follows patterns, proper separation of concerns, no coupling issues
    □ Scope adherence - implements ONLY Phase {phase-number} work, no later-phase implementations
    □ Constitution compliance - follows all project standards and conventions
    
    Find ALL issues NOW. If you catch yourself thinking "I'll check that in re-review" - STOP. Check it NOW.
    
    Binary verdict required: "Ready to merge? Yes" (only if EVERYTHING passes) or "Ready to merge? No" (list ALL issues found)
    
  2. Parse output using binary algorithm:

    Read the code review output and search for "Ready to merge?" field:

    • ✅ "Ready to merge? Yes" → APPROVED

      • Announce: "✅ Code review APPROVED - Phase {N} complete, proceeding"
      • Continue to next phase
    • ❌ "Ready to merge? No" → REJECTED

      • STOP execution
      • Report: "❌ Code review REJECTED - critical issues found"
      • List all Critical and Important issues from review
      • Dispatch fix subagent IMMEDIATELY (no user prompt, no questions)
      • Go to step 5 (re-review after fixes)
    • ❌ "Ready to merge? With fixes" → REJECTED

      • STOP execution
      • Report: "❌ Code review requires fixes before proceeding"
      • List all issues from review
      • Dispatch fix subagent IMMEDIATELY (no user prompt, no questions)
      • Go to step 5 (re-review after fixes)
    • ⚠️ No output / empty response → RETRY ONCE

      • Warn: "⚠️ Code review returned no output - retrying once"
      • This may be a transient issue (timeout, connection error)
      • Go to step 3 (retry review)
      • If retry ALSO has no output → FAILURE (go to step 4)
    • ❌ Soft language (e.g., "APPROVED WITH MINOR SUGGESTIONS") → REJECTED

      • STOP execution
      • Report: "❌ Code review used soft language instead of binary verdict"
      • Warn: "Binary gate requires explicit 'Ready to merge? Yes'"
      • Go to step 3 (re-review)
    • ⚠️ Missing "Ready to merge?" field → RETRY ONCE

      • Warn: "⚠️ Code review output missing 'Ready to merge?' field - retrying once"
      • This may be a transient issue (network glitch, model error)
      • Go to step 3 (retry review)
      • If retry ALSO missing field → FAILURE (go to step 4)
  3. Retry review (if malformed output):

    • Dispatch requesting-code-review skill again with same parameters
    • Parse retry output using step 2 binary algorithm
    • If retry succeeds with "Ready to merge? Yes":
      • Announce: "✅ Code review APPROVED (retry succeeded) - Phase {N} complete, proceeding"
      • Continue to next phase
    • If retry returns valid verdict (No/With fixes):
      • Follow normal REJECTED flow (fix issues, re-review)
    • If retry ALSO has missing "Ready to merge?" field:
      • Go to step 4 (both attempts failed)
  4. Both attempts malformed (FAILURE):

    • STOP execution immediately
    • Report: "❌ Code review failed twice with malformed output"
    • Display excerpts from both attempts for debugging
    • Suggest: "Review agent may not be following template - check code-reviewer skill"
    • DO NOT hallucinate issues from malformed text
    • DO NOT dispatch fix subagents
    • Fail execution
  5. Re-review loop (if REJECTED with valid verdict):

    Initialize iteration tracking:

    REJECTION_COUNT=0
    

    On each rejection:

    REJECTION_COUNT=$((REJECTION_COUNT + 1))
    
    # Check escalation limit
    if [ $REJECTION_COUNT -gt 3 ]; then
      echo "⚠️  Code review rejected $REJECTION_COUNT times"
      echo ""
      echo "Issues may require architectural changes beyond subagent scope."
      echo "Reporting to user for manual intervention:"
      echo ""
      # Display all issues from latest review
      # Suggest: Review architectural assumptions, may need spec revision
      exit 1
    fi
    
    # Dispatch fix subagent
    echo "🔧 Dispatching fix subagent to address issues (attempt $REJECTION_COUNT)..."
    
    # Use Task tool to dispatch fix subagent:
    Task(Fix Phase {N} code review issues)
    Prompt: Fix the following issues found in Phase {N} code review:
    
    {List all issues from review output with severity (Critical/Important/Minor) and file locations}
    
    CONTEXT FOR FIXES:
    
    1. Read constitution (if exists): docs/constitutions/current/
    
    2. Read feature specification: specs/{run-id}-{feature-slug}/spec.md
    
       The spec provides architectural context for fixes:
       - WHY decisions were made (rationale for current implementation)
       - HOW features should integrate (system boundaries)
       - WHAT requirements must be met (acceptance criteria)
    
    3. Read implementation plan: specs/{run-id}-{feature-slug}/plan.md
    
       The plan provides phase boundaries and scope:
       - WHEN to implement features (which phase owns what)
       - WHAT tasks belong to Phase {N} (scope boundaries)
       - WHAT tasks belong to later phases (do NOT implement)
    
       **If scope creep detected (implemented work from later phases):**
       - Roll back to Phase {N} scope ONLY
       - Remove implementations that belong to later phases
       - Keep ONLY the work defined in Phase {N} tasks
       - The plan exists for a reason - respect phase boundaries
    
    4. Apply fixes following spec + constitution + plan boundaries
    
    CRITICAL: Work in .worktrees/{runid}-main
    CRITICAL: Amend existing branch or add new commit (do NOT create new branch)
    CRITICAL: Run all quality checks before completion (test, lint, build)
    CRITICAL: Verify all issues resolved before reporting completion
    CRITICAL: If scope creep, implement LESS not ask user what to keep
    
    # After fix completes
    echo "⏺ Re-reviewing Phase {N} after fixes (iteration $((REJECTION_COUNT + 1)))..."
    # Return to step 1 (dispatch review again)
    

    On approval after fixes:

    echo "✅ Code review APPROVED (after $REJECTION_COUNT fix iteration(s)) - Phase {N} complete"
    

    Escalation triggers:

    • After 3 rejections: Stop and report to user
    • Prevents infinite loops on unsolvable architectural problems
    • User can review, adjust spec, or proceed manually

Critical: Only "Ready to merge? Yes" allows proceeding. Everything else stops execution.

Phase completion:

  • If REVIEW_FREQUENCY="per-phase": Phase complete ONLY when:
    • ✅ All branches created
    • ✅ Linear stack verified
    • ✅ Worktrees cleaned up
    • ✅ Code review returns "Ready to merge? Yes"
  • If REVIEW_FREQUENCY="end-only" or "skip": Phase complete when:
    • ✅ All branches created
    • ✅ Linear stack verified
    • ✅ Worktrees cleaned up
    • (Code review skipped)

Rationalization Table

ExcuseReality
"Only 1 task, skip worktrees"N=1 still uses parallel architecture. No special case.
"Files don't overlap, skip isolation"Worktrees enable parallelism, not prevent conflicts.
"Already spent 30min on setup"Sunk cost fallacy. Worktrees ARE the parallel execution.
"Simpler to execute sequentially"Simplicity ≠ correctness. Parallel phase = worktrees.
"Agents said success, skip verification"Agent reports ≠ branch existence. Verify preconditions.
"Disk space pressure, clean up first"Stacking must happen before cleanup. No exceptions.
"Git commands work from anywhere"TRUE, but path resolution is CWD-relative. Verify location.
"I'll just do it myself"Subagents provide fresh context and true parallelism.
"Worktrees are overhead"Worktrees ARE the product. Parallelism is the value.
"Review rejected, let me ask user what to do"Autonomous execution means automatic fixes. No asking.
"Issues are complex, user should decide"Fix subagent handles complexity. That's the architecture.
"Safer to get user input before fixing"Re-review provides safety. Fix, review, repeat until clean.
"Scope creep but quality passes, ask user to choose"Plan violation = failure. Fix subagent removes extra scope automatically.
"Work is done correctly, just ahead of schedule"Phases exist for review isolation. Implement less, not merge early.
"Spec mentions feature X, might as well implement now"Spec = WHAT to build total. Plan = WHEN to build each piece. Check phase.

Red Flags - STOP and Follow Process

If you're thinking ANY of these, you're about to violate the skill:

  • "This is basically sequential with N=1"
  • "Files don't conflict, isolation unnecessary"
  • "Worktree creation takes too long"
  • "Already behind schedule, skip setup"
  • "Agents succeeded, no need to verify"
  • "Disk space warning, clean up now"
  • "Current directory looks right"
  • "Relative paths are cleaner"

All of these mean: STOP. Follow the process exactly.

Common Mistakes

Mistake 1: Treating Parallel as "Logically Independent"

Wrong mental model: "Parallel means tasks are independent, so I can execute them sequentially in one worktree."

Correct model: "Parallel means tasks execute CONCURRENTLY via multiple subagents in isolated worktrees."

Impact: Destroys parallelism. Turns 3-hour calendar time into 9-hour sequential execution.

Mistake 2: Efficiency Optimization

Wrong mental model: "Worktrees are overhead when files don't overlap."

Correct model: "Worktrees are the architecture. Without them, no concurrent execution exists."

Impact: Sequential execution disguised as parallel. No time savings.

Mistake 3: Cleanup Sequencing

Wrong mental model: "Branches exist independently of worktrees, so cleanup order doesn't matter."

Correct model: "Stacking before cleanup allows debugging if stacking fails and runs integration tests on complete stack."

Impact: Can't debug stacking failures. Premature cleanup destroys evidence.

Quick Reference

Mandatory sequence (no variations):

  1. Verify location (main repo root)
  2. Create worktrees (ALL tasks, including N=1)
  3. Install dependencies (per worktree)
  4. Spawn subagents (parallel dispatch)
  5. Verify branches exist (before stacking)
  6. Stack branches (before cleanup)
  7. Clean up worktrees (after stacking)
  8. Code review

Never skip. Never reorder. No exceptions.

The Bottom Line

Parallel phases use worktrees. Always. Even N=1. Even when files don't overlap. Even under pressure.

If you're not creating worktrees, you're not executing parallel phases - you're executing sequential phases incorrectly labeled as parallel.

The skill is the architecture. Follow it exactly.

Executing Plans

Overview

This skill orchestrates the execution of implementation plans generated by the decomposing-tasks skill. It handles the complete lifecycle of plan execution including worktree verification, resume detection, phase-by-phase execution (sequential or parallel), quality verification, and final stack completion.

When to Use

Use this skill when:

  • Executing an implementation plan from /spectacular:execute
  • Resuming interrupted plan execution
  • Orchestrating multi-phase feature implementation

Announce: "I'm using executing-plan to orchestrate implementation of the plan."

Architecture

The execute command uses an orchestrator-with-embedded-instructions architecture for cognitive load reduction:

Orchestrator Skills (executing-sequential-phase, executing-parallel-phase)

  • Responsibilities: Setup, worktree management, dispatch coordination, code review orchestration
  • Size: ~464 lines (sequential), ~850 lines (parallel)
  • Dispatches: Task tool with embedded execution instructions (~150 lines per task)
  • Focus: Manages workflow lifecycle, embeds focused task instructions for subagents

Verification Skill (phase-task-verification)

  • Responsibilities: Shared git operations (add, branch create, HEAD verify, detach)
  • Size: ~92 lines
  • Used by: Task subagents via Skill tool (both sequential and parallel)
  • Focus: Eliminates duplication of branch creation/verification logic

Cognitive Load Reduction:

  • Original: 750-line monolithic skills (orchestration + task + verification mixed)
  • Current: Subagents receive ~150 lines of focused task execution instructions via Task tool
  • Benefit: 80% reduction in content subagents must parse (only see task instructions, not orchestration)
  • Verification: Shared 92-line skill eliminates duplication

Maintainability benefit: Orchestrator features (resume support, enhanced error recovery, verification improvements) can be added without affecting task execution instructions. Subagents receive focused, consistent instructions while orchestrators handle workflow complexity.

Testing framework: This plugin uses Test-Driven Development for workflow documentation. See tests/README.md and CLAUDE.md for the complete testing system. All changes to commands and skills must pass the test suite before committing.

Available Skills

Skills are referenced on-demand when you encounter the relevant step. Do not pre-read all skills upfront.

Phase Execution (read when you encounter the phase type):

  • executing-parallel-phase - Mandatory workflow for parallel phases (Step 2)
  • executing-sequential-phase - Mandatory workflow for sequential phases (Step 2)

Support Skills (read as needed when referenced):

  • understanding-cross-phase-stacking - Reference before starting any phase (explains base branch inheritance)
  • validating-setup-commands - Reference if CLAUDE.md setup validation needed (Step 1.5)
  • using-git-spice - Reference for git-spice command syntax (as needed)
  • requesting-code-review - Reference after each phase completes (Step 2)
  • verification-before-completion - Reference before claiming completion (Step 3)
  • finishing-a-development-branch - Reference after all phases complete (Step 4)
  • troubleshooting-execute - Reference if execution fails (error recovery)
  • using-git-worktrees - Reference if worktree issues occur (diagnostics)

Multi-Repo Support

Detecting Multi-Repo Mode

At the start of execution, detect workspace mode:

# Detect workspace mode
REPO_COUNT=$(find . -maxdepth 2 -name ".git" -type d 2>/dev/null | wc -l | tr -d ' ')
if [ "$REPO_COUNT" -gt 1 ]; then
  echo "Multi-repo workspace detected ($REPO_COUNT repos)"
  WORKSPACE_MODE="multi-repo"
  REPOS=$(find . -maxdepth 2 -name ".git" -type d | xargs -I{} dirname {} | sed 's|^\./||' | tr '\n' ' ')
  echo "Available repos: $REPOS"
else
  echo "Single-repo mode"
  WORKSPACE_MODE="single-repo"
fi

Multi-Repo Execution Differences

AspectSingle-RepoMulti-Repo
Worktree.worktrees/{runId}-main/Per-task: {repo}/.worktrees/{runId}-task-X-Y/
Spec locationspecs/{runId}-{feature}/./specs/{runId}-{feature}/ (workspace root)
Setup commandsOne CLAUDE.mdPer-repo CLAUDE.md
Constitution@docs/constitutions/current/@{repo}/docs/constitutions/current/
Git-spice stackSingle stackPer-repo stacks

Passing Repo Context to Phase Skills

When dispatching phase execution, include repo context:

**Multi-repo context for phase:**
- WORKSPACE_MODE: multi-repo
- WORKSPACE_ROOT: {absolute path}
- Task repos: {list of repos with tasks in this phase}
- Per-task repo: extracted from plan's `**Repo**: {repo}` field

The Process

Input

User will provide: /spectacular:execute {plan-path}

Example: /spectacular:execute @specs/a1b2c3-magic-link-auth/plan.md

Where a1b2c3 is the runId and magic-link-auth is the feature slug.

Step 0a: Extract Run ID from Plan

User provided plan path: The user gave you a plan path like .worktrees/3a00a7-main/specs/3a00a7-agent-standardization-refactor/plan.md

Extract RUN_ID from the path:

The RUN_ID is the first segment of the spec directory name (before the first dash).

For example:

  • Path: .worktrees/3a00a7-main/specs/3a00a7-agent-standardization-refactor/plan.md
  • Directory: 3a00a7-agent-standardization-refactor
  • RUN_ID: 3a00a7
# Extract RUN_ID and FEATURE_SLUG from plan path (replace {the-plan-path-user-provided} with actual path)
PLAN_PATH="{the-plan-path-user-provided}"
DIR_NAME=$(echo "$PLAN_PATH" | sed 's|^.*specs/||; s|/plan.md$||')
RUN_ID=$(echo "$DIR_NAME" | cut -d'-' -f1)
FEATURE_SLUG=$(echo "$DIR_NAME" | cut -d'-' -f2-)

echo "Extracted RUN_ID: $RUN_ID"
echo "Extracted FEATURE_SLUG: $FEATURE_SLUG"

# Verify RUN_ID and FEATURE_SLUG are not empty
if [ -z "$RUN_ID" ]; then
  echo "Error: Could not extract RUN_ID from plan path: $PLAN_PATH"
  exit 1
fi

if [ -z "$FEATURE_SLUG" ]; then
  echo "Error: Could not extract FEATURE_SLUG from plan path: $PLAN_PATH"
  exit 1
fi

CRITICAL: Execute this entire block as a single multi-line Bash tool call. The comment on the first line is REQUIRED - without it, command substitution $(...) causes parse errors.

Store RUN_ID and FEATURE_SLUG for use in:

  • Branch naming: {run-id}-task-X-Y-name
  • Filtering: git branch | grep "^ {run-id}-"
  • Spec path: specs/{run-id}-{feature-slug}/spec.md
  • Cleanup: Identify which branches/specs belong to this run

Announce: "Executing with RUN_ID: {run-id}, FEATURE_SLUG: {feature-slug}"

Step 0b: Verify Worktree Exists

Multi-repo mode: Skip worktree verification at orchestrator level. Each task will create its own worktree in its repo during phase execution.

if [ "$WORKSPACE_MODE" = "multi-repo" ]; then
  echo "Multi-repo mode: Worktrees created per-task during execution"
  # Verify spec exists at workspace root
  if [ ! -f "specs/${RUN_ID}-${FEATURE_SLUG}/plan.md" ]; then
    echo "Error: Plan not found at specs/${RUN_ID}-${FEATURE_SLUG}/plan.md"
    exit 1
  fi
  echo "Plan verified: specs/${RUN_ID}-${FEATURE_SLUG}/plan.md"
fi

Single-repo mode: Continue with existing worktree verification.

After extracting RUN_ID, verify the worktree exists:

# Get absolute repo root (stay in main repo, don't cd into worktree)
REPO_ROOT=$(git rev-parse --show-toplevel)

# Verify worktree exists
if [ ! -d "$REPO_ROOT/.worktrees/${RUN_ID}-main" ]; then
  echo "Error: Worktree not found at .worktrees/${RUN_ID}-main"
  echo "Run /spectacular:spec first to create the workspace."
  exit 1
fi

# Verify it's a valid worktree
git worktree list | grep "${RUN_ID}-main"

IMPORTANT: Orchestrator stays in main repo. All worktree operations use git -C .worktrees/{run-id}-main or absolute paths.

This ensures task worktrees are created at the same level as {run-id}-main, not nested inside it.

Announce: "Verified worktree exists: .worktrees/{run-id}-main/"

Step 0c: Check for Existing Work

Check if implementation work already exists:

# Get repo root
REPO_ROOT=$(git rev-parse --show-toplevel)

# Check current branch in main worktree
CURRENT_BRANCH=$(git -C "$REPO_ROOT/.worktrees/${RUN_ID}-main" branch --show-current 2>/dev/null || echo "")

# Count existing task branches for this RUN_ID
EXISTING_TASKS=$(git branch 2>/dev/null | grep -c "^  ${RUN_ID}-task-" || echo "0")

# Report status
if [ "$EXISTING_TASKS" -gt 0 ]; then
  echo "Found $EXISTING_TASKS existing task branch(es) for RUN_ID: $RUN_ID"
  echo "   Current branch: $CURRENT_BRANCH"
  echo ""
  echo "Resuming from current state. The execution will:"
  echo "- Sequential phases: Continue from current branch"
  echo "- Parallel phases: Skip completed tasks, run remaining"
  echo ""
else
  echo "No existing work found - starting fresh execution"
  echo ""
fi

CRITICAL: Execute this entire block as a single multi-line Bash tool call. The comment on the first line is REQUIRED - without it, command substitution $(...) causes parse errors.

Resume behavior:

  • If EXISTING_TASKS > 0: Execution continues from current state in main worktree
  • If EXISTING_TASKS = 0: Execution starts from Phase 1, Task 1
  • Main worktree current branch indicates progress (latest completed work)

Note: Orchestrator proceeds immediately to Step 1. Phase execution logic in Step 2 handles resume by checking current branch and existing task branches.

Step 1: Read and Parse Plan

Read the plan file and extract:

  • Feature name
  • All phases (with strategy: sequential or parallel)
  • All tasks within each phase

For each task, extract and format:

  • Task ID and name
  • Files to modify (explicit paths)
  • Acceptance criteria (bullet points)
  • Dependencies (which tasks must complete first)

Store extracted task info for subagent prompts (saves ~1000 tokens per subagent):

Task 4.2:
Name: Integrate prompts module into generator
Files: - src/generator.ts - src/types.ts
Acceptance Criteria: - Import PromptService from prompts module - Replace manual prompt construction with PromptService.getCommitPrompt() - Update tests to mock PromptService - All tests pass
Dependencies: Task 4.1 (fallback logic removed)

Multi-repo plan parsing:

For multi-repo plans, also extract the repo field from each task:

Task 4.2:
Name: Integrate prompts module into generator
Repo: backend  # NEW - required in multi-repo mode
Files: - src/generator.ts - src/types.ts
Acceptance Criteria: - Import PromptService from prompts module - Replace manual prompt construction with PromptService.getCommitPrompt() - Update tests to mock PromptService - All tests pass
Dependencies: Task 4.1 (fallback logic removed)

Pass repo information to phase execution skills.

Verify plan structure:

  • Has phases with clear strategies
  • All tasks have files specified
  • All tasks have acceptance criteria
  • Dependencies make sense

Step 1.5: Validate Setup Commands (REQUIRED)

Use the validating-setup-commands skill:

This skill validates that CLAUDE.md defines required setup commands BEFORE creating worktrees. It provides clear error messages with examples if missing.

The skill will extract and return:

  • INSTALL_CMD - Required dependency installation command
  • POSTINSTALL_CMD - Optional post-install command (codegen, etc.)

Store these commands for use in dependency installation steps throughout execution.

Step 1.6: Detect Project Commands (Optional)

Optionally detect project-specific quality check commands for subagents to use.

This is optional - most projects define commands in CLAUDE.md that subagents can discover.

If you want to provide hints, check for common patterns:

  • TypeScript/JavaScript: package.json scripts
  • Python: pytest, ruff, black
  • Go: go test, golangci-lint
  • Rust: cargo test, cargo clippy

If detected, mention in subagent prompts:

  • TEST_CMD - Command to run tests
  • LINT_CMD - Command to run linting
  • FORMAT_CMD - Command to format code
  • BUILD_CMD - Command to build project

If not detected, subagents will check CLAUDE.md or skip quality checks with warning.

IMPORTANT: Do NOT read constitution files here. Let subagents read them as needed to reduce orchestrator token usage.

Step 1.7: Configure Code Review Frequency

Determine when to run code reviews:

# Check if REVIEW_FREQUENCY env var is set
REVIEW_FREQUENCY=${REVIEW_FREQUENCY:-}

If not set, prompt user for preference:

If REVIEW_FREQUENCY is empty, use AskUserQuestion tool to prompt:

Question: "How frequently should code reviews run during execution?"
Header: "Review Frequency"
Options:
  1. "After each phase"
     Description: "Run code review after every phase completes (safest - catches errors early, prevents compounding issues)"
  2. "Optimize automatically"
     Description: "Let Claude decide when to review based on phase risk/complexity (RECOMMENDED - balances speed and quality)"
  3. "Only at end"
     Description: "Skip per-phase reviews, run one review after all phases complete (faster, but errors may compound)"
  4. "Skip reviews"
     Description: "No automated code reviews (fastest, but requires manual review before merging)"

Store user choice:

  • Option 1 -> REVIEW_FREQUENCY="per-phase"
  • Option 2 -> REVIEW_FREQUENCY="optimize"
  • Option 3 -> REVIEW_FREQUENCY="end-only"
  • Option 4 -> REVIEW_FREQUENCY="skip"

Announce decision:

Code review frequency: {REVIEW_FREQUENCY}

Note: This setting applies to all phases in this execution. Phase skills check REVIEW_FREQUENCY to determine whether to run code review step.

Step 2: Execute Phases

If resuming: Start from the incomplete phase/task identified in Step 0.

For each phase in the plan, execute based on strategy:

Multi-repo phase execution:

When dispatching phase skills, include:

  • WORKSPACE_MODE: "multi-repo" or "single-repo"
  • WORKSPACE_ROOT: Absolute path to workspace
  • For each task: TASK_REPO field from plan

Example dispatch context:

WORKSPACE_MODE: multi-repo
WORKSPACE_ROOT: /home/user/workspace
Phase 2 tasks:
- Task 2.1: repo=backend
- Task 2.2: repo=frontend
- Task 2.3: repo=frontend

Phase skills use this to:

  • Create worktrees in the correct repo
  • Read CLAUDE.md from the task's repo
  • Read constitution from the task's repo

Code Review Gates: Phase execution skills check REVIEW_FREQUENCY (set in Step 1.7) to determine when to run code reviews:

  • per-phase: Review after each phase before proceeding
  • optimize: LLM decides whether to review based on phase risk/complexity
  • end-only: Skip per-phase reviews, review once after all phases
  • skip: No automated reviews (manual review required)
Cross-Phase Stacking

Use the understanding-cross-phase-stacking skill:

This skill explains how sequential and parallel phases automatically chain together through base branch inheritance. Key concepts:

  • Main worktree tracks progress (current branch = latest completed work)
  • Parallel phases inherit from current branch (not original base)
  • Natural chaining creates linear stack across all phases

Read this skill before starting any new phase to understand how phases build on each other.

Sequential Phase Strategy

Use the executing-sequential-phase skill:

This skill provides the complete workflow for executing sequential phases. Key concepts:

  • Execute tasks one-by-one in existing {runid}-main worktree
  • Trust natural git-spice stacking (no manual gs upstack onto)
  • Tasks build on each other cumulatively
  • Stay on task branches for automatic stacking

The skill includes detailed subagent prompts, quality check sequences, and code review integration.

CRITICAL: When dispatching subagents, substitute {run-id} and {feature-slug} with the values extracted in Step 0a. Subagents need these to read the spec at specs/{run-id}-{feature-slug}/spec.md.

Parallel Phase Strategy

Use the executing-parallel-phase skill:

This skill provides the complete mandatory workflow for executing parallel phases. Key requirements:

  • Create isolated worktrees for EACH task (even N=1)
  • Install dependencies per worktree
  • Spawn parallel subagents in single message
  • Verify completion before stacking
  • Stack branches linearly, then cleanup worktrees
  • Code review after stacking

The skill includes the 8-step mandatory sequence, verification checks, N=1 edge case handling, and stacking algorithm.

CRITICAL: When dispatching subagents, substitute {run-id} and {feature-slug} with the values extracted in Step 0a. Subagents need these to read the spec at specs/{run-id}-{feature-slug}/spec.md.

Step 3: Verify Completion

After all phases execute successfully:

Use the verification-before-completion skill:

This skill enforces verification BEFORE claiming work is done.

Required verifications (if commands detected):

# Run full test suite
if [ -n "$TEST_CMD" ]; then
  $TEST_CMD || { echo "Tests failed"; exit 1; }
fi

# Run linting
if [ -n "$LINT_CMD" ]; then
  $LINT_CMD || { echo "Linting failed"; exit 1; }
fi

# Run production build
if [ -n "$BUILD_CMD" ]; then
  $BUILD_CMD || { echo "Build failed"; exit 1; }
fi

# Verify all detected checks passed
echo "All quality checks passed - ready to complete"

If no commands detected:

Warning: No test/lint/build commands found in project.
Add to CLAUDE.md or constitution/testing.md for automated quality gates.
Proceeding without verification - manual review recommended.

Critical: Evidence before assertions. Never claim "tests pass" without running them.

Step 4: Finish Stack

After verification passes:

Use the finishing-a-development-branch skill to:

  1. Review all changes
  2. Choose next action:
    • Submit stack as PRs: gs stack submit (per using-git-spice skill)
    • Continue with dependent feature: gs branch create
    • Mark complete and sync: gs repo sync

Step 5: Final Report

Multi-repo final report:

Feature Implementation Complete

**RUN_ID**: {run-id}
**Feature**: {feature-name}
**Workspace Mode**: multi-repo
**Workspace Root**: {path}

## Per-Repo Summary

| Repo | Tasks | Branches | Status |
|------|-------|----------|--------|
| backend | 4 | 4 | Complete |
| frontend | 3 | 3 | Complete |
| shared-lib | 1 | 1 | Complete |

## Branch Stacks (per-repo)

**backend:**
- {runId}-task-1-1-database
- {runId}-task-2-1-api

**frontend:**
- {runId}-task-2-2-hook
- {runId}-task-2-3-ui

## Next Steps

### Submit PRs (per-repo)
```bash
cd backend && gs stack submit
cd ../frontend && gs stack submit

**Single-repo final report:**

```markdown
Feature Implementation Complete

**RUN_ID**: {run-id}
**Feature**: {feature-name}
**Worktree**: .worktrees/{run-id}-main/
**Stack**: {count} task branches (all stacked on {run-id}-main)

## Execution Summary

**Phases Completed**: {count}

- Sequential: {count} phases
- Parallel: {count} phases

**Tasks Completed**: {count}
**Commits**: {count}

**Isolation**: All work completed in worktree. Main repo unchanged.

## Parallelization Results

{For each parallel phase:}
**Phase {id}**: {task-count} tasks in parallel

- Estimated sequential time: {hours}h
- Actual parallel time: {hours}h
- Time saved: {hours}h

**Total Time Saved**: {hours}h ({percent}%)

## Quality Checks

Quality checks are project-specific (detected from CLAUDE.md, constitution, or common patterns):

- Tests passing (if `TEST_CMD` detected)
- Linting clean (if `LINT_CMD` detected)
- Formatting applied (if `FORMAT_CMD` detected)
- Build successful (if `BUILD_CMD` detected)

If no commands detected, quality gates are skipped with warning to user.
- {total-commits} commits across {branch-count} task branches

## Next Steps

### Review Changes (from main repo)

```bash
# All these commands work from main repo root
gs log short                      # View all branches and commits in stack
gs log long                       # Detailed view with commit messages
git branch | grep "^  {run-id}-"  # List all branches for this run

# To see changes in worktree:
cd .worktrees/{run-id}-main
git diff main..HEAD               # See all changes in current stack
cd ../..                          # Return to main repo

Submit for Review (from main repo)

# git-spice commands work from main repo
gs stack submit  # Submits entire stack as PRs (per using-git-spice skill)

Or Continue with Dependent Feature (from worktree)

cd .worktrees/{run-id}-main       # Navigate to worktree
gs branch create  # Creates new branch stacked on current
cd ../..                          # Return to main repo when done

Cleanup Worktree (after PRs merged)

# From main repo root:
git worktree remove .worktrees/{run-id}-main

# Optional: Delete the {run-id}-main branch
git branch -d {run-id}-main

Important: Main repo remains unchanged. All work is in the worktree and task branches.


## Error Handling

**Use the `troubleshooting-execute` skill:**

This skill provides comprehensive diagnostic and recovery strategies for execute command failures:
- Phase execution failures (sequential and parallel)
- Parallel agent failures with 4 recovery options
- Merge conflicts during stacking
- Worktree not found errors
- Parallel task worktree creation failures

The skill includes diagnostic commands, recovery strategies, and prevention guidelines.

Consult this skill when execution fails or produces unexpected results.

## Important Notes

- **Orchestrator delegates, never executes** - The orchestrator NEVER runs git commands directly. All git operations are delegated to subagents (setup, implementation, cleanup)
- **Subagents own their git operations** - Implementation subagents create branches and commit their own work using `gs branch create -m`
- **Skill-driven execution** - Uses using-git-spice, using-git-worktrees, and other superpowers skills
- **Automatic orchestration** - Reads plan strategies, executes accordingly
- **Git-spice stacking** - Sequential tasks stack linearly; parallel tasks branch from same base (per using-git-spice skill)
- **No feature branch** - The stack of task branches IS the feature; never create empty branch upfront
- **Worktree isolation** - Parallel tasks run in separate worktrees (per using-git-worktrees skill)
- **Critical: HEAD detachment** - Parallel task subagents MUST detach HEAD after creating branches to make them accessible in parent repo
- **Context management** - Each task runs in isolated subagent to avoid token bloat
- **Constitution adherence** - All agents follow project constitution (@docs/constitutions/current/)
- **Quality gates** - Tests and linting after every task, code review after every phase
- **Continuous commits** - Small, focused commits with [Task X.Y] markers throughout

Now execute the plan from: {plan-path}

Executing Sequential Phase

Overview

Sequential phases use natural git-spice stacking in the main worktree.

Each task creates a branch with gs branch create, which automatically stacks on the current HEAD. No manual stacking operations needed.

Critical distinction: Sequential tasks BUILD ON each other. They need integration, not isolation.

When to Use

Use this skill when execute command encounters a phase marked "Sequential" in plan.md:

  • ✅ Tasks must run in order (dependencies)
  • ✅ Execute in existing {runid}-main worktree
  • ✅ Trust natural stacking (no manual gs upstack onto)
  • ✅ Stay on task branches (don't switch to base between tasks)

Sequential phases never use worktrees. They share one workspace where tasks build cumulatively.

Multi-Repo Support

Receiving Multi-Repo Context

The orchestrator passes:

  • WORKSPACE_MODE: "multi-repo" or "single-repo"
  • WORKSPACE_ROOT: Absolute path to workspace
  • Per-task TASK_REPO from plan

Sequential Execution Across Repos

In multi-repo mode, sequential tasks may span repos:

Phase 1 (sequential):
- Task 1.1: repo=shared-lib  # Shared types first
- Task 1.2: repo=backend     # Backend uses shared types
- Task 1.3: repo=frontend    # Frontend uses shared types

For each task, switch to that task's repo context.

Per-Repo Worktrees

In multi-repo sequential phases:

  • Each repo has its own main worktree: {repo}/.worktrees/{runId}-main/
  • Tasks execute in their repo's worktree
  • Switching tasks = switching repos (if different)

Per-Repo Setup Commands

Read setup commands from each task's repo:

# Multi-repo: Read from task's repo CLAUDE.md
INSTALL_CMD=$(grep -A1 "**install**:" ${TASK_REPO}/CLAUDE.md | tail -1)

Per-Repo Constitution

Pass correct constitution to subagents:

# Multi-repo
CONSTITUTION="@${TASK_REPO}/docs/constitutions/current/"

Per-Repo Stacking

Sequential tasks across repos create per-repo stacks:

Execution order:
1. Task 1.1 (shared-lib) → creates branch in shared-lib
2. Task 1.2 (backend) → creates branch in backend
3. Task 1.3 (backend) → stacks on 1.2 in backend
4. Task 1.4 (frontend) → creates branch in frontend

Result:
- shared-lib stack: task-1-1
- backend stack: task-1-2 → task-1-3
- frontend stack: task-1-4

Each repo maintains its own linear stack. Cannot stack across repos.

Single-Repo Mode (Unchanged)

All existing behavior preserved:

  • Single main worktree at .worktrees/{runId}-main/
  • Single CLAUDE.md for setup commands
  • Single constitution at @docs/constitutions/current/
  • Single linear stack of branches

The Natural Stacking Principle

SEQUENTIAL PHASE = MAIN WORKTREE + NATURAL STACKING

What natural stacking means:

  1. Start on base branch (or previous task's branch)
  2. Create new branch with gs branch create → automatically stacks on current
  3. Stay on that branch when done
  4. Next task creates from there → automatically stacks on previous

No manual commands needed. The workflow IS the stacking.

The Process

Announce: "I'm using executing-sequential-phase to execute {N} tasks sequentially in Phase {phase-id}."

Step 0: Verify Orchestrator Location

MANDATORY: Verify orchestrator is in correct location before any operations:

Single-repo mode:

REPO_ROOT=$(git rev-parse --show-toplevel)
CURRENT=$(pwd)

if [ "$CURRENT" != "$REPO_ROOT" ]; then
  echo "❌ Error: Orchestrator must run from main repo root"
  echo "Current: $CURRENT"
  echo "Expected: $REPO_ROOT"
  echo ""
  echo "Return to main repo: cd $REPO_ROOT"
  exit 1
fi

echo "✅ Orchestrator location verified: Main repo root"

Multi-repo mode:

# Orchestrator runs from WORKSPACE_ROOT (parent of all repos)
CURRENT=$(pwd)

if [ "$CURRENT" != "$WORKSPACE_ROOT" ]; then
  echo "❌ Error: Orchestrator must run from workspace root"
  echo "Current: $CURRENT"
  echo "Expected: $WORKSPACE_ROOT"
  echo ""
  echo "Return to workspace: cd $WORKSPACE_ROOT"
  exit 1
fi

echo "✅ Orchestrator location verified: Workspace root ($WORKSPACE_MODE mode)"

Why critical:

  • Orchestrator delegates work but never changes directory
  • Single-repo: All operations use git -C .worktrees/path or bash -c "cd path && cmd"
  • Multi-repo: All operations use git -C {repo}/.worktrees/path or bash -c "cd {repo}/path && cmd"
  • This assertion catches upstream drift immediately

Step 1: Verify Setup and Base Branch

First, verify we're on the correct base branch for this phase:

Single-repo mode:

# Get current branch in main worktree
CURRENT_BRANCH=$(git -C .worktrees/{runid}-main branch --show-current)
EXPECTED_BASE="{expected-base-branch}"  # From plan: previous phase's last task, or {runid}-main for Phase 1

if [ "$CURRENT_BRANCH" != "$EXPECTED_BASE" ]; then
  echo "⚠️  WARNING: Phase {phase-id} starting from unexpected branch"
  echo "   Current: $CURRENT_BRANCH"
  echo "   Expected: $EXPECTED_BASE"
  echo ""
  echo "This means the previous phase ended on the wrong branch."
  echo "Possible causes:"
  echo "- Code review or quality checks switched branches"
  echo "- User manually checked out different branch"
  echo "- Resume from interrupted execution"
  echo ""
  echo "To fix:"
  echo "1. Verify previous phase completed: git log --oneline $EXPECTED_BASE"
  echo "2. Switch to correct base: cd .worktrees/{runid}-main && git checkout $EXPECTED_BASE"
  echo "3. Re-run /spectacular:execute"
  exit 1
fi

echo "✅ Phase {phase-id} starting from correct base: $CURRENT_BRANCH"

Multi-repo mode:

In multi-repo, base branch verification is per-repo. For each repo that has tasks in this phase:

# For each repo with tasks in this phase
for REPO in ${REPOS_IN_PHASE[@]}; do
  WORKTREE_PATH="${WORKSPACE_ROOT}/${REPO}/.worktrees/${RUN_ID}-main"

  # Check if this repo's worktree exists
  if [ ! -d "$WORKTREE_PATH" ]; then
    echo "Creating main worktree for repo: ${REPO}"
    bash <<EOF
    cd ${WORKSPACE_ROOT}/${REPO}
    git worktree add .worktrees/${RUN_ID}-main -b ${RUN_ID}-main
EOF
  fi

  # Verify branch (or create if first task in this repo)
  CURRENT_BRANCH=$(git -C "$WORKTREE_PATH" branch --show-current)
  echo "✅ Repo ${REPO} on branch: $CURRENT_BRANCH"
done

Then check and install dependencies (orchestrator never cd's):

Single-repo mode:

# Check if dependencies installed in main worktree
if [ ! -d .worktrees/{runid}-main/node_modules ]; then
  echo "Installing dependencies in main worktree..."
  bash <<'EOF'
  cd .worktrees/{runid}-main
  {install-command}
  {postinstall-command}
  EOF
fi

Multi-repo mode:

Setup commands are read from each task's repo CLAUDE.md. Install dependencies before executing each task:

# For each task, install dependencies in that repo's worktree
TASK_REPO="${task.repo}"
WORKTREE_PATH="${WORKSPACE_ROOT}/${TASK_REPO}/.worktrees/${RUN_ID}-main"

# Read setup commands from task's repo CLAUDE.md
if [ "$WORKSPACE_MODE" = "multi-repo" ]; then
  CLAUDE_MD_PATH="${WORKSPACE_ROOT}/${TASK_REPO}/CLAUDE.md"
else
  CLAUDE_MD_PATH="CLAUDE.md"
fi

INSTALL_CMD=$(grep -A1 "**install**:" ${CLAUDE_MD_PATH} | tail -1 | sed 's/`//g' | xargs)
POSTINSTALL_CMD=$(grep -A1 "**postinstall**:" ${CLAUDE_MD_PATH} | tail -1 | sed 's/`//g' | xargs)

# Check if dependencies installed in repo's worktree
if [ ! -d "${WORKTREE_PATH}/node_modules" ]; then
  echo "Installing dependencies in ${TASK_REPO} worktree..."
  bash <<EOF
  cd ${WORKTREE_PATH}
  ${INSTALL_CMD}
  ${POSTINSTALL_CMD}
EOF
fi

Why heredoc: Orchestrator stays in main repo/workspace root. Heredoc creates subshell that exits after commands.

Why main worktree: Sequential tasks share main worktree per repo. All sequential phases share this worktree within each repo.

Red flag: "Create phase-specific worktree" - NO. Sequential = shared worktree (per repo).

Step 1.5: Extract Phase Context (Before Dispatching)

Before spawning subagents, extract phase boundaries from plan:

The orchestrator already parsed the plan in execute.md Step 1. Extract:

  • Current phase number and name
  • Tasks in THIS phase (what TO implement)
  • Tasks in LATER phases (what NOT to implement)

Format for subagent context:

PHASE CONTEXT:
- Phase {current-phase-id}/{total-phases}: {phase-name}
- This phase includes: Task {task-ids-in-this-phase}

LATER PHASES (DO NOT IMPLEMENT):
- Phase {next-phase}: {phase-name} - {task-summary}
- Phase {next+1}: {phase-name} - {task-summary}
...

If implementing work beyond this phase's tasks, STOP and report scope violation.

Why critical: Spec describes WHAT to build (entire feature). Plan describes HOW/WHEN (phase breakdown). Subagents need both to avoid scope creep.

Step 2: Execute Tasks Sequentially

Multi-repo task execution:

For each task in sequential phase, handle repo switching:

PREVIOUS_REPO=""

for task in ${TASKS[@]}; do
  # Get task's repo
  TASK_REPO="${task.repo}"

  # If repo changed from previous task, switch context
  if [ "$TASK_REPO" != "$PREVIOUS_REPO" ]; then
    echo "Switching to repo: ${TASK_REPO}"

    # Ensure repo's main worktree exists
    if [ ! -d "${WORKSPACE_ROOT}/${TASK_REPO}/.worktrees/${RUN_ID}-main" ]; then
      # Create main worktree for this repo
      bash <<EOF
      cd ${WORKSPACE_ROOT}/${TASK_REPO}
      git worktree add .worktrees/${RUN_ID}-main -b ${RUN_ID}-main
EOF
    fi
  fi

  # Execute task in repo's worktree
  WORKTREE_PATH="${WORKSPACE_ROOT}/${TASK_REPO}/.worktrees/${RUN_ID}-main"

  # Track for next iteration
  PREVIOUS_REPO="$TASK_REPO"

  # Dispatch subagent (see below)
done

Single-repo mode: Execute all tasks in the single main worktree (unchanged).

For each task in order, spawn ONE subagent with embedded instructions:

Single-repo mode:

Task(Implement Task {task-id}: {task-name})

ROLE: Implement Task {task-id} in main worktree (sequential phase)

WORKTREE: .worktrees/{run-id}-main
CURRENT BRANCH: {current-branch}

TASK: {task-name}
FILES: {files-list}
ACCEPTANCE CRITERIA: {criteria}

PHASE BOUNDARIES:

Multi-repo mode:

Task(Implement Task {task-id}: {task-name})

ROLE: Implement Task {task-id} in repo worktree (sequential phase, multi-repo)

WORKSPACE_MODE: multi-repo
WORKSPACE_ROOT: {workspace-root}
TASK_REPO: {task-repo}
WORKTREE_PATH: {task-repo}/.worktrees/{run-id}-main
CONSTITUTION: @{task-repo}/docs/constitutions/current/
CURRENT BRANCH: {current-branch}

TASK: {task-name}
FILES: {files-list}
ACCEPTANCE CRITERIA: {criteria}

PHASE BOUNDARIES:
===== PHASE BOUNDARIES - CRITICAL =====

Phase {current-phase-id}/{total-phases}: {phase-name}
This phase includes ONLY: Task {task-ids-in-this-phase}

DO NOT CREATE ANY FILES from later phases.

Later phases (DO NOT CREATE):
- Phase {next-phase}: {phase-name} - {task-summary}
  ❌ NO implementation files
  ❌ NO stub functions (even with TODOs)
  ❌ NO type definitions or interfaces
  ❌ NO test scaffolding or temporary code

If tempted to create ANY file from later phases, STOP.
"Not fully implemented" = violation.
"Just types/stubs/tests" = violation.
"Temporary/for testing" = violation.

==========================================

CONTEXT REFERENCES (single-repo):
- Spec: specs/{run-id}-{feature-slug}/spec.md
- Constitution: docs/constitutions/current/
- Plan: specs/{run-id}-{feature-slug}/plan.md
- Worktree: .worktrees/{run-id}-main

CONTEXT REFERENCES (multi-repo):
- Spec: {workspace-root}/specs/{run-id}-{feature-slug}/spec.md
- Constitution: {task-repo}/docs/constitutions/current/
- Plan: {workspace-root}/specs/{run-id}-{feature-slug}/plan.md
- Worktree: {task-repo}/.worktrees/{run-id}-main

INSTRUCTIONS:

1. Navigate to correct worktree:
   Single-repo: cd .worktrees/{run-id}-main
   Multi-repo: cd {workspace-root}/{task-repo}/.worktrees/{run-id}-main

2. Read constitution (if exists):
   Single-repo: docs/constitutions/current/
   Multi-repo: {task-repo}/docs/constitutions/current/

3. Read feature specification: specs/{run-id}-{feature-slug}/spec.md

   This provides:
   - WHAT to build (requirements, user flows)
   - WHY decisions were made (architecture rationale)
   - HOW features integrate (system boundaries)

   The spec is your source of truth for architectural decisions.
   Constitution tells you HOW to code. Spec tells you WHAT to build.

4. VERIFY PHASE SCOPE before implementing:
   - Read the PHASE BOUNDARIES section above
   - Confirm this task belongs to Phase {current-phase-id}
   - If tempted to implement later phase work, STOP
   - The plan exists for a reason - respect phase boundaries

5. Implement task following spec + constitution + phase boundaries

6. Run quality checks with exit code validation:

   **CRITICAL**: Use heredoc to prevent bash parsing errors:

   bash <<'EOF'
   npm test
   if [ $? -ne 0 ]; then
     echo "❌ Tests failed"
     exit 1
   fi

   npm run lint
   if [ $? -ne 0 ]; then
     echo "❌ Lint failed"
     exit 1
   fi

   npm run build
   if [ $? -ne 0 ]; then
     echo "❌ Build failed"
     exit 1
   fi
   EOF

   **Why heredoc**: Prevents parsing errors when commands are wrapped by orchestrator.

7. Create stacked branch using verification skill:

   Skill: phase-task-verification

   Parameters:
   - RUN_ID: {run-id}
   - TASK_ID: {phase}-{task}
   - TASK_NAME: {short-name}
   - COMMIT_MESSAGE: "[Task {phase}.{task}] {task-name}"
   - MODE: sequential

   The verification skill will:
   a) Stage changes with git add .
   b) Create branch with gs branch create
   c) Verify HEAD points to new branch
   d) Stay on branch (next task builds on it)

8. Report completion

CRITICAL (single-repo):
- Work in .worktrees/{run-id}-main, NOT main repo
- Stay on your branch when done (next task builds on it)
- Do NOT create worktrees
- Do NOT use `gs upstack onto`
- Do NOT implement work from later phases (check PHASE BOUNDARIES above)

CRITICAL (multi-repo):
- Work in {task-repo}/.worktrees/{run-id}-main, NOT repo root
- Stay on your branch when done (next task in same repo builds on it)
- Do NOT create additional worktrees
- Do NOT use `gs upstack onto`
- Do NOT implement work from later phases (check PHASE BOUNDARIES above)
- Read constitution from THIS repo: {task-repo}/docs/constitutions/current/
- Each repo has its own stack - cross-repo stacking not possible

Sequential dispatch: Wait for each task to complete before starting next.

Red flags:

  • "Dispatch all tasks in parallel" - NO. Sequential = one at a time.
  • "Create task-specific worktrees" - NO. Sequential = shared worktree.
  • "Spec mentions feature X, I'll implement it now" - NO. Check phase boundaries first.
  • "I'll run git add myself" - NO. Let subagent use phase-task-verification skill.

Step 3: Verify Natural Stack Formation

After all tasks complete (verify from orchestrator location):

Single-repo mode:

# Display and verify stack using bash subshell (orchestrator stays in main repo)
bash <<'EOF'
cd .worktrees/{runid}-main

echo "📋 Stack after sequential phase:"
gs log short
echo ""

# Verify stack integrity (each task has unique commit)
echo "🔍 Verifying stack integrity..."
TASK_BRANCHES=( {array-of-branch-names} )
STACK_VALID=1
declare -A SEEN_COMMITS

for BRANCH in "${TASK_BRANCHES[@]}"; do
  if ! git rev-parse --verify "$BRANCH" >/dev/null 2>&1; then
    echo "❌ ERROR: Branch '$BRANCH' not found"
    STACK_VALID=0
    break
  fi

  BRANCH_SHA=$(git rev-parse "$BRANCH")

  # Check if this commit SHA was already seen
  if [ -n "${SEEN_COMMITS[$BRANCH_SHA]}" ]; then
    echo "❌ ERROR: Stack integrity violation"
    echo "   Branch '$BRANCH' points to commit $BRANCH_SHA"
    echo "   But '${SEEN_COMMITS[$BRANCH_SHA]}' already points to that commit"
    echo ""
    echo "This means one task created no new commits."
    echo "Possible causes:"
    echo "- Task implementation had no changes"
    echo "- Quality checks blocked commit"
    echo "- gs branch create failed silently"
    STACK_VALID=0
    break
  fi

  SEEN_COMMITS[$BRANCH_SHA]="$BRANCH"
  echo "  ✓ $BRANCH @ $BRANCH_SHA"
done

if [ $STACK_VALID -eq 0 ]; then
  echo ""
  echo "❌ Stack verification FAILED"
  echo ""
  echo "To investigate:"
  echo "1. Check task branch commits: git log --oneline \$BRANCH"
  echo "2. Review subagent output for failed task"
  echo "3. Check for quality check failures (test/lint/build)"
  echo "4. Fix and re-run /spectacular:execute"
  exit 1
fi

echo "✅ Stack integrity verified - all tasks have unique commits"
EOF

Multi-repo mode:

Verify stacks in each repo that had tasks in this phase:

# Group tasks by repo
declare -A REPO_TASKS
for task in ${TASKS[@]}; do
  REPO_TASKS[${task.repo}]+="${task.branch} "
done

# Verify each repo's stack
ALL_VALID=1
for REPO in "${!REPO_TASKS[@]}"; do
  echo "📋 Stack for repo: ${REPO}"
  WORKTREE_PATH="${WORKSPACE_ROOT}/${REPO}/.worktrees/${RUN_ID}-main"

  bash <<EOF
  cd ${WORKTREE_PATH}

  echo "Stack in ${REPO}:"
  gs log short
  echo ""

  # Verify stack integrity for this repo
  echo "🔍 Verifying ${REPO} stack integrity..."
  TASK_BRANCHES=( ${REPO_TASKS[$REPO]} )
  STACK_VALID=1
  declare -A SEEN_COMMITS

  for BRANCH in "\${TASK_BRANCHES[@]}"; do
    if ! git rev-parse --verify "\$BRANCH" >/dev/null 2>&1; then
      echo "❌ ERROR: Branch '\$BRANCH' not found in ${REPO}"
      STACK_VALID=0
      break
    fi

    BRANCH_SHA=\$(git rev-parse "\$BRANCH")

    if [ -n "\${SEEN_COMMITS[\$BRANCH_SHA]}" ]; then
      echo "❌ ERROR: Stack integrity violation in ${REPO}"
      echo "   Branch '\$BRANCH' points to commit \$BRANCH_SHA"
      echo "   But '\${SEEN_COMMITS[\$BRANCH_SHA]}' already points to that commit"
      STACK_VALID=0
      break
    fi

    SEEN_COMMITS[\$BRANCH_SHA]="\$BRANCH"
    echo "  ✓ \$BRANCH @ \$BRANCH_SHA"
  done

  if [ \$STACK_VALID -eq 0 ]; then
    exit 1
  fi
  echo "✅ ${REPO} stack integrity verified"
EOF

  if [ $? -ne 0 ]; then
    ALL_VALID=0
  fi
done

if [ $ALL_VALID -eq 0 ]; then
  echo ""
  echo "❌ Multi-repo stack verification FAILED"
  echo ""
  echo "To investigate:"
  echo "1. Check failing repo's task branch commits"
  echo "2. Review subagent output for failed task"
  echo "3. Check for quality check failures (test/lint/build)"
  echo "4. Fix and re-run /spectacular:execute"
  exit 1
fi

echo "✅ All repo stacks verified"

Per-repo stacking result:

Execution order:
1. Task 1.1 (shared-lib) → creates branch in shared-lib
2. Task 1.2 (backend) → creates branch in backend
3. Task 1.3 (backend) → stacks on 1.2 in backend
4. Task 1.4 (frontend) → creates branch in frontend

Result:
- shared-lib stack: task-1-1
- backend stack: task-1-2 → task-1-3
- frontend stack: task-1-4

Each gs branch create automatically stacked on the previous task's branch within that repo.

Verification ensures: Each task created a unique commit (no empty branches or duplicates).

Red flag: "Run gs upstack onto to ensure stacking" - NO. Already stacked naturally.

Red flag: "Stack across repos" - NO. Each repo has independent stack.

Step 4: Code Review (Binary Quality Gate)

Check review frequency setting (from execute.md Step 1.7):

REVIEW_FREQUENCY=${REVIEW_FREQUENCY:-per-phase}

If REVIEW_FREQUENCY is "end-only" or "skip":

Skipping per-phase code review (frequency: {REVIEW_FREQUENCY})
Phase {N} complete - proceeding to next phase

Mark phase complete and continue to next phase.

If REVIEW_FREQUENCY is "optimize":

Analyze the completed phase to decide if code review is needed:

High-risk indicators (REVIEW REQUIRED):

  • Schema or migration changes
  • Authentication/authorization logic
  • External API integrations or webhooks
  • Foundation phases (Phase 1-2 establishing patterns)
  • 3+ parallel tasks (coordination complexity)
  • New architectural patterns introduced
  • Security-sensitive code (payment, PII, access control)
  • Complex business logic with multiple edge cases
  • Changes affecting multiple layers (database → API → UI)

Low-risk indicators (SKIP REVIEW):

  • Pure UI component additions (no state/logic)
  • Documentation or comment updates
  • Test additions without implementation changes
  • Refactoring with existing test coverage
  • Isolated utility functions
  • Configuration file updates (non-security)

Analyze this phase:

  • Phase number: {N}
  • Tasks completed: {task-list}
  • Files modified: {file-list}
  • Types of changes: {describe changes}

Decision: If ANY high-risk indicator present → Proceed to code review below If ONLY low-risk indicators → Skip review:

✓ Phase {N} assessed as low-risk - skipping review (optimize mode)
  Reasoning: {brief explanation of why low-risk}
Phase {N} complete - proceeding to next phase

If REVIEW_FREQUENCY is "per-phase" OR optimize mode decided to review:

Use requesting-code-review skill, then parse results STRICTLY.

AUTONOMOUS EXECUTION: Code review rejections trigger automatic fix loops, NOT user prompts. Never ask user what to do.

  1. Dispatch code review:

    Single-repo mode:

    Skill: requesting-code-review
    
    Context provided to reviewer:
    - WORKTREE: .worktrees/{runid}-main
    - PHASE: {phase-number}
    - TASKS: {task-list}
    - BASE_BRANCH: {base-branch-name}
    - SPEC: specs/{run-id}-{feature-slug}/spec.md
    - PLAN: specs/{run-id}-{feature-slug}/plan.md (for phase boundary validation)
    

    Multi-repo mode:

    Review each repo that had tasks in this phase:

    Skill: requesting-code-review
    
    Context provided to reviewer:
    - WORKSPACE_MODE: multi-repo
    - WORKSPACE_ROOT: {workspace-root}
    - REPOS_IN_PHASE: {list-of-repos-with-tasks}
    
    For each repo:
    - REPO: {repo-name}
    - WORKTREE: {repo}/.worktrees/{runid}-main
    - TASKS: {tasks-in-this-repo}
    - BASE_BRANCH: {repo-base-branch}
    - CONSTITUTION: {repo}/docs/constitutions/current/
    
    Cross-repo context:
    - SPEC: {workspace-root}/specs/{run-id}-{feature-slug}/spec.md
    - PLAN: {workspace-root}/specs/{run-id}-{feature-slug}/plan.md
    
    **CRITICAL - EXHAUSTIVE FIRST-PASS REVIEW:**
    
    This is your ONLY opportunity to find issues. Re-review is for verifying fixes, NOT discovering new problems.
    
    Check EVERYTHING in this single review:
    □ Implementation correctness - logic bugs, edge cases, error handling, race conditions
    □ Test correctness - expectations match actual behavior, coverage is complete, no false positives
    □ Cross-file consistency - logic coherent across all files, no contradictions
    □ Architectural soundness - follows patterns, proper separation of concerns, no coupling issues
    □ Scope adherence - implements ONLY Phase {phase-number} work, no later-phase implementations
    □ Constitution compliance - follows all project standards and conventions
    
    Find ALL issues NOW. If you catch yourself thinking "I'll check that in re-review" - STOP. Check it NOW.
    
    Binary verdict required: "Ready to merge? Yes" (only if EVERYTHING passes) or "Ready to merge? No" (list ALL issues found)
    
  2. Parse "Ready to merge?" field:

    • "Yes" → APPROVED, continue to next phase
    • "No" or "With fixes" → REJECTED, dispatch fix subagent, go to step 3
    • No output / missing field → RETRY ONCE, if retry fails → STOP
    • Soft language → REJECTED, re-review required
  3. Re-review loop (if REJECTED):

    • Track rejections (REJECTION_COUNT)
    • If count > 3: Escalate to user (architectural issues beyond subagent scope)
    • Dispatch fix subagent with:
      • Issues list (severity + file locations)
      • Context: constitution, spec, plan
      • Scope enforcement: If scope creep, implement LESS (roll back to phase scope)
      • Quality checks required
    • Re-review after fixes (return to step 1)
    • On approval: Announce completion with iteration count

Critical: Only "Ready to merge? Yes" allows proceeding. Everything else stops execution.

Phase completion:

  • If REVIEW_FREQUENCY="per-phase": Phase complete ONLY when code review returns "Ready to merge? Yes"
  • If REVIEW_FREQUENCY="end-only" or "skip": Phase complete after all tasks finish (code review skipped)

Rationalization Table

ExcuseReality
"Need manual stacking commands"gs branch create stacks automatically on current HEAD
"Files don't overlap, could parallelize"Plan says sequential for semantic dependencies
"Create phase-specific worktree"Sequential phases share main worktree (per repo in multi-repo)
"Review rejected, ask user"Autonomous execution means automatic fixes
"Scope creep but quality passes"Plan violation = failure. Auto-fix to plan
"Use same worktree for all repos"Multi-repo: each repo has its own worktree
"Stack across repos"Cannot stack across repos - each repo has independent stack
"Use root CLAUDE.md for all repos"Multi-repo: read each repo's own CLAUDE.md for setup commands
"Use root constitution for all repos"Multi-repo: use each task's repo constitution

Phase Task Verification

When to Use

Invoked by sequential-phase-task and parallel-phase-task after task implementation to create and verify git-spice branch.

Parameters

  • RUN_ID: 6-char run ID (e.g., "8c8505")
  • TASK_ID: Phase-task (e.g., "1-1")
  • TASK_NAME: Short name (e.g., "create-verification-skill")
  • COMMIT_MESSAGE: Full commit message
  • MODE: "sequential" or "parallel"

The Process

Step 1: Stage and create branch

git add .
gs branch create {RUN_ID}-task-{TASK_ID}-{TASK_NAME} -m "{COMMIT_MESSAGE}"

Step 2: Verify based on MODE

MODE: sequential - Verify HEAD points to expected branch:

CURRENT=$(git rev-parse --abbrev-ref HEAD)
EXPECTED="{RUN_ID}-task-{TASK_ID}-{TASK_NAME}"
[ "$CURRENT" = "$EXPECTED" ] || { echo "ERROR: HEAD=$CURRENT, expected $EXPECTED"; exit 1; }

MODE: parallel - Detach HEAD (makes branch accessible in parent repo):

git switch --detach
CURRENT=$(git rev-parse --abbrev-ref HEAD)
[ "$CURRENT" = "HEAD" ] || { echo "ERROR: HEAD not detached ($CURRENT)"; exit 1; }

Rationalization Table

RationalizationWhy It's Wrong
"Verification is optional"Silent failures lose work
"Skip detach in parallel mode"Breaks worktree cleanup
"Branch create errors are obvious"Silent failures aren't detected until cleanup fails
"Detach can happen later"Cleanup runs in parent repo - branch must be accessible
"HEAD verification adds overhead"<100ms cost prevents hours of lost work debugging

Error Handling

git add fails:

  • No changes to stage: Error is expected - task implementation failed or incomplete
    • Check if task was actually implemented
    • Verify files were modified in expected locations
    • Do NOT continue with branch creation
  • Permission issues: Git repository permissions corrupted
    • Check file ownership: ls -la .git
    • Verify worktree is accessible
    • Escalate to orchestrator

gs branch create fails:

  • Duplicate branch name: Branch already exists
    • Check existing branches: git branch | grep {RUN_ID}-task-{TASK_ID}
    • Verify task wasn't already completed
    • May indicate resume scenario - escalate to orchestrator
  • Git-spice errors: Repository state issues
    • Run gs repo sync to fix state
    • Verify git-spice initialized: gs ls
    • Check for uncommitted changes blocking operation
  • Invalid branch name: Name contains invalid characters
    • Verify RUN_ID is 6-char alphanumeric
    • Verify TASK_NAME contains only alphanumeric + hyphens
    • Do NOT sanitize - escalate to orchestrator (indicates data corruption)

HEAD verification fails (sequential mode):

  • Expected: gs branch create should checkout new branch automatically
  • Actual: Still on previous branch or detached HEAD
    • Indicates git-spice behavior change or bug
    • Do NOT continue - task is not properly staged
    • Escalate to orchestrator with exact HEAD state

HEAD verification fails (parallel mode):

  • Expected: git switch --detach should detach HEAD
  • Actual: Still on branch after detach command
    • Indicates git version issue or repository corruption
    • Do NOT continue - cleanup will fail to access branch
    • Escalate to orchestrator with git version: git --version

Testing Workflows With Subagents

Overview

Testing workflows is TDD applied to orchestrator instructions and command documentation.

You find real execution failures (git logs, error reports), create test scenarios that reproduce them, watch subagents follow ambiguous instructions incorrectly (RED), fix the instructions (GREEN), and verify subagents now follow correctly (REFACTOR).

Core principle: If you didn't watch an agent misinterpret the instructions in a test, you don't know if your fix prevents the right failures.

REQUIRED BACKGROUND: You MUST understand superpowers:test-driven-development before using this skill. That skill defines the fundamental RED-GREEN-REFACTOR cycle. This skill applies TDD to workflow documentation.

When to Use

Use when:

  • Creating new commands (.claude/commands/*.md, /spectacular:*)
  • Editing orchestrator prompts for subagents
  • Updating workflow documentation in commands
  • You observed real execution failures (wrong branches, skipped steps, misinterpreted instructions)
  • Instructions involve multiple steps where order matters
  • Agents work under time pressure or cognitive load

Don't test:

  • Pure reference documentation (no workflow steps)
  • Single-step commands with no ambiguity
  • Documentation without actionable instructions

TDD Mapping for Workflow Testing

TDD PhaseWorkflow TestingWhat You Do
REDFind real failureCheck git logs, error reports for evidence of agents misinterpreting instructions
Verify REDCreate failing test scenarioReproduce the failure with test repo + pressure scenario
GREENFix instructionsRewrite ambiguous steps with explicit ordering, warnings, examples
Verify GREENTest with subagentSame scenario with fixed instructions - agent follows correctly
REFACTORIterate on clarityFind remaining ambiguities, improve wording, re-test
Stay GREENRe-verifyTest again to ensure fix holds

Same cycle as code TDD, different test format.

RED Phase: Find Real Execution Failures

Goal: Gather evidence of how instructions were misinterpreted in actual execution.

Where to look:

  • Git history: Commits on wrong branches, missing branches, incorrect stack structure
  • Run logs: Steps skipped, wrong order executed, missing quality checks
  • Error reports: Failed tasks, cleanup issues, integration problems
  • User reports: "Agents did X when I expected Y"

Document evidence:

## RED Phase Evidence

**Source**: bignight.party git log (Run ID: 082687)

**Failure**: Task 4.3 commit on branch `082687-task-4.2-auth-domain-migration`

**Expected**: Create branch `082687-task-4.3-server-actions`

**Actual**: Committed to Task 4.2's branch instead

**Root cause hypothesis**: Instructions ambiguous about creating branch before committing

Critical: Get actual git commits, branch names, error messages - not hypothetical scenarios.

Create RED Test Scenario

Goal: Reproduce the failure in a controlled test environment.

Test Repository Setup

Create minimal repo that simulates real execution state:

cd /path/to/test-area
mkdir workflow-test && cd workflow-test
git init
git config user.name "Test" && git config user.email "test@test.com"

# Set up state that led to failure
# (e.g., existing task branches for sequential phase testing)

Pressure Scenario Document

Create test file with:

  1. Role definition: "You are subagent implementing Task X"
  2. Current state: Branch, uncommitted work, what's done
  3. Actual instructions: Copy current ambiguous instructions
  4. Pressure context: Combine 2-3 pressure types from table below
  5. Options: Give explicit choices (forces decision, no deferring)

Pressure Types for Workflow Testing

PressureExampleEffect on Agent
Time"Orchestrator waiting", "4 more tasks to do", "Need to move fast"Skips reading skills, chooses fast option
Cognitive load"2 hours in, tired", "Third sequential task", "Complex state"Misreads instructions, makes assumptions
Urgency"Choose NOW", "Execute immediately", "No delays"Skips verification steps, commits to first interpretation
Task volume"4 more tasks after this", "Part of 10-task phase"Rushes through steps, skips optional guidance
Complexity"Multiple branches exist", "Shared worktree", "Parallel tasks running"Confused about current state, wrong branch

Best test scenarios combine 2-3 pressures to simulate realistic execution conditions.

Example:

# RED Test: Sequential Phase Task Execution

**Role**: Implementation subagent for Task 2.3

**Current state**: On branch `abc123-task-2-2-database`
Uncommitted changes in auth.js (your completed work)

**Instructions from execute.md (CURRENT VERSION)**:
  1. Use using-git-spice skill to:
    • Create branch: abc123-task-2-3-auth
    • Commit with message: "[Task 2.3] Add auth"

**Pressure**: 2 hours in, tired, 4 more tasks to do

**Options**:
A) Read skill (2 min delay)
B) Just commit now
C) Create branch with git, then commit
D) Guess git-spice command

Choose and execute NOW.

Run RED Test

# Dispatch subagent with test scenario
# Use haiku for speed and realistic "under pressure" behavior
# Document exact choice and reasoning verbatim

Expected RED result: Agent makes wrong choice, commits to wrong branch, or skips creating branch.

If agent succeeds, your test scenario isn't realistic enough - add more pressure or make options more tempting.

GREEN Phase: Fix Instructions

Goal: Rewrite instructions to prevent the specific failure observed in RED.

Analyze Root Cause

From RED test, identify:

  • Which step was ambiguous?
  • What order was unclear?
  • What assumptions did agent make?
  • What did pressure cause them to skip?

Example analysis:

**Ambiguous**: "Create branch" and "Commit" as separate bullets
**Unclear order**: Could mean "create then commit" OR "commit then create"
**Assumption**: "I'll just commit first, cleaner workflow"
**Pressure effect**: Skipped reading skill, chose fast option

Fix Patterns

Pattern 1: Explicit Sequential Steps

```markdown - Create branch: X - Commit with message: Y - Stay on branch ``` ```markdown a) FIRST: Stage changes - Command: `git add .`

b) THEN: Create branch (commits automatically)

  • Command: gs branch create X -m "Y"

c) Stay on new branch

</After>

**Pattern 2: Critical Warnings**

Add consequences upfront:
```markdown
CRITICAL: Stage changes FIRST, then create branch.

If you commit BEFORE creating branch, work goes to wrong branch.

Pattern 3: Show Commands

Reduce friction under pressure - show exact commands:

b) THEN: Create new stacked branch
   - Command: `gs branch create {name} -m "message"`
   - This creates branch and commits in one operation

Pattern 4: Skill-Based Reference

Balance showing commands with learning:

Use `using-git-spice` skill which teaches this two-step workflow:
[commands here]
Read the skill if uncertain about the workflow.

Apply Fix

Edit the actual command file with GREEN fix.

Verify GREEN: Test Fix

Goal: Confirm agents now follow instructions correctly under same pressure.

Reset Test Repository

cd /path/to/workflow-test
git reset --hard initial-state
# Recreate same starting conditions as RED test

Create GREEN Test Scenario

Same as RED test but:

  • Update to "Instructions from execute.md (NEW IMPROVED VERSION)"
  • Include the fixed instructions
  • Same pressure, same options available
  • Same "execute NOW" urgency

Run GREEN Test

# Dispatch subagent with GREEN scenario
# Use same model (haiku) for consistency
# Agent should now choose correct option and execute correctly

Expected GREEN result:

  • Agent follows fixed instructions
  • Creates branch before committing (or whatever correct behavior is)
  • Quotes reasoning showing they understood the explicit ordering
  • Work ends up in correct state

If agent still fails: Instructions still ambiguous. Return to GREEN phase, improve clarity, re-test.

Meta-Testing (When GREEN Fails)

If agent still misinterprets after your fix, ask them directly:

your human partner: You read the improved instructions and still chose the wrong option.

How could those instructions have been written differently to make
the correct workflow crystal clear?

Three possible responses:

  1. "The instructions WERE clear, I just rushed"

    • Not a clarity problem - need stronger warning/consequence
    • Add "CRITICAL:" or "MUST" language upfront
    • State failure consequence explicitly
  2. "The instructions should have said X"

    • Clarity problem - agent's suggestion usually good
    • Add their exact wording verbatim
    • Re-test to verify improvement
  3. "I didn't notice section Y"

    • Organization problem - important info buried
    • Move critical steps earlier
    • Use formatting (bold, CRITICAL) to highlight

Use meta-testing to diagnose WHY fix didn't work, not just add more content.

REFACTOR Phase: Iterate on Clarity

Goal: Find and fix remaining ambiguities.

Check for Remaining Issues

Run additional test scenarios:

  • Different pressure combinations
  • Different task positions (first task, middle, last)
  • Different states (clean vs dirty working tree)
  • Different agent models (haiku, sonnet)

Common Clarity Issues

IssueSymptomFix
Order ambiguousSteps done out of orderAdd "a) FIRST, b) THEN" labels
Missing consequencesAgent skips stepAdd "If you skip X, Y will fail"
Too abstractAgent guesses commandsShow exact commands inline
No warningsAgent makes wrong choiceAdd "CRITICAL:" upfront
Assumes knowledgeAgent doesn't know toolReference skill + show command

Document Test Results

Create summary document:

# Test Results: execute.md Sequential Phase Fix

**RED Phase**: Task 4.3 committed to Task 4.2 branch (real failure)
**GREEN Phase**: Agent created correct branch, no ambiguity
**REFACTOR**: Tested with different models, all passed

**Fix applied**: Lines 277-297 (sequential), 418-438 (parallel)
**Success criteria**: New stacked branch created BEFORE commit

Differences from Testing Skills

testing-skills-with-subagents (discipline skills):

  • Tests agent compliance under pressure (will they follow rules?)
  • Focuses on closing rationalization loopholes
  • Uses multiple combined pressures (time + sunk cost + exhaustion)
  • Goal: Bulletproof against shortcuts

testing-workflows-with-subagents (workflow documentation):

  • Tests instruction clarity (can they understand what to do?)
  • Focuses on removing ambiguity in ordering and steps
  • Uses realistic execution pressure (tired, more tasks, time limits)
  • Goal: Unambiguous instructions agents can follow correctly

Different problem: Skills test "will you comply?" vs Workflows test "can you understand?"

Quick Reference: RED-GREEN-REFACTOR Cycle

RED Phase:

  1. Find real execution failure (git log, error reports)
  2. Create test repo simulating pre-failure state
  3. Write pressure scenario with current instructions
  4. Launch subagent, document exact failure

GREEN Phase:

  1. Analyze root cause (what was ambiguous?)
  2. Fix instructions (explicit order, warnings, commands)
  3. Reset test repo to same state
  4. Write GREEN scenario with fixed instructions
  5. Launch subagent, verify correct execution

REFACTOR Phase:

  1. Test additional scenarios (different pressures, states)
  2. Find remaining ambiguities
  3. Improve clarity
  4. Re-verify all tests pass

Testing Checklist (TDD for Workflows)

IMPORTANT: Use TodoWrite to track these steps.

RED Phase:

  • Find real execution failure (git commits, logs, errors)
  • Document evidence (branch names, commit hashes, expected vs actual)
  • Create test repository simulating pre-failure state
  • Write pressure scenario with current instructions
  • Run subagent test, document exact failure and reasoning

GREEN Phase:

  • Analyze root cause of ambiguity
  • Fix instructions (explicit ordering, warnings, commands)
  • Apply fix to actual command file
  • Reset test repository to same starting state
  • Write GREEN scenario with fixed instructions
  • Run subagent test, verify correct execution

REFACTOR Phase:

  • Test with different pressure levels
  • Test with different execution states
  • Test with different agent models
  • Document all remaining ambiguities found
  • Improve clarity for each issue
  • Re-verify all scenarios pass

Documentation:

  • Create test results summary
  • Document before/after instructions
  • Save test scenarios for regression testing
  • Note which lines in command file were changed

Common Mistakes

❌ Testing without real failure evidence Start with hypothetical "this might be confusing" leads to fixes that don't address actual problems. ✅ Fix: Always start with git logs, error reports, real execution traces.

❌ Test scenario without pressure Agents follow instructions carefully when not rushed - doesn't match real execution. ✅ Fix: Add time pressure, cognitive load (tired, many tasks), urgency.

❌ Improving instructions without testing Guessing what's clear vs actually verifying leads to still-ambiguous docs. ✅ Fix: Always run GREEN verification with subagent before considering done.

❌ Testing once and done First test might not catch all ambiguities. ✅ Fix: REFACTOR phase with varied scenarios, different models.

❌ Vague test options Giving "what do you do?" instead of concrete choices lets agent defer. ✅ Fix: Force A/B/C/D choice with "Choose NOW" urgency.

Real-World Impact

From testing execute.md sequential phase instructions (this session):

RED Phase:

  • Found Task 4.3 committed to Task 4.2's branch in bignight.party
  • Created test scenario reproducing failure mode

GREEN Phase:

  • Fixed instructions with "a) FIRST, b) THEN" explicit ordering
  • Added CRITICAL warning about staging before branch creation
  • Showed exact atomic command: gs branch create -m

Result:

  • Agent followed corrected workflow perfectly
  • Quote: "The two-step process is clear and effective"
  • Prevents same failure class across all future executions

Time investment: 1 hour testing, prevents repeated failures across all spectacular runs.

The Bottom Line

Test workflow documentation the same way you test code.

RED (find real failure) → GREEN (fix and verify) → REFACTOR (iterate on clarity).

If you wouldn't deploy code without tests, don't deploy commands without verifying agents can follow them correctly.

Troubleshooting Execute Command

Overview

Reference guide for diagnosing and recovering from execute command failures.

This skill provides recovery strategies for common execute command errors. Use it when execution fails or produces unexpected results.

When to Use

Use this skill when:

  • Phase execution fails (sequential or parallel)
  • Parallel agent fails or doesn't complete
  • Merge conflicts occur during stacking
  • Worktree creation fails
  • Main worktree not found
  • Need to resume execution after fixing an issue

This is a reference skill - consult when errors occur, not part of normal execution flow.

Error Categories

1. Sequential Phase Execution Failure

Symptoms:

  • Task agent fails mid-execution
  • Quality checks fail (test, lint, build)
  • Branch not created after task completes

Error message format:

❌ Phase {id} Execution Failed

**Task**: {task-id}
**Error**: {error-message}

Resolution steps:

  1. Review the error output - Understand what failed (test? build? implementation?)

  2. Check current state:

    cd .worktrees/{runid}-main
    git status
    git log --oneline -5
    
  3. Fix manually if needed:

    # Current branch already has completed work from previous tasks
    # Fix the issue in the working directory
    
    # Run quality checks
    bash <<'EOF'
    npm test
    if [ $? -ne 0 ]; then
      echo "❌ Tests failed"
      exit 1
    fi
    
    npm run lint
    if [ $? -ne 0 ]; then
      echo "❌ Lint failed"
      exit 1
    fi
    
    npm run build
    if [ $? -ne 0 ]; then
      echo "❌ Build failed"
      exit 1
    fi
    EOF
    
    # Create branch if task completed but branch wasn't created
    gs branch create {runid}-task-{phase}-{task}-{name} -m "[Task {phase}.{task}] {description}"
    
  4. Resume execution:

    • If fixed manually: Continue to next task
    • If need fresh attempt: Reset branch and re-run task
    • If plan was wrong: Update plan and re-execute from this phase

2. Parallel Phase - Agent Failure

Symptoms:

  • One or more parallel agents fail
  • Some task branches created, others missing
  • Error during concurrent execution

Error message format:

❌ Parallel Phase {id} - Agent Failure

**Failed Task**: {task-id}
**Branch**: {task-branch}
**Error**: {error-message}

**Successful Tasks**: {list}

Resolution options:

Option A: Fix in Existing Branch

Use when fix is small and task mostly completed:

# Navigate to task's worktree
cd .worktrees/{runid}-task-{phase}-{task}

# Debug and fix issue
# Edit files, fix code

# Run quality checks
bash <<'EOF'
npm test
if [ $? -ne 0 ]; then
  echo "❌ Tests failed"
  exit 1
fi

npm run lint
if [ $? -ne 0 ]; then
  echo "❌ Lint failed"
  exit 1
fi

npm run build
if [ $? -ne 0 ]; then
  echo "❌ Build failed"
  exit 1
fi
EOF

# Commit fix on existing branch
git add --all
git commit -m "[Task {phase}.{task}] Fix: {description}"

# Return to main repo
cd "$REPO_ROOT"

# Proceed with stacking (failed branch now exists)
Option B: Create Stacked Fix Branch

Use when fix is significant or logically separate:

# Navigate to task's worktree
cd .worktrees/{runid}-task-{phase}-{task}

# Ensure original work is committed
git status  # Should be clean

# Create stacked fix branch
gs branch create {runid}-task-{phase}-{task}-fix-{issue} -m "[Task {phase}.{task}] Fix: {issue}"

# Implement fix
# Edit files

# Commit fix
git add --all
git commit -m "[Task {phase}.{task}] Fix: {description}"

# Return to main repo
cd "$REPO_ROOT"
Option C: Restart Failed Agent

Use when task implementation is fundamentally wrong:

# Navigate to main repo
cd "$REPO_ROOT"

# Remove task worktree
git worktree remove .worktrees/{runid}-task-{phase}-{task}

# Delete failed branch if it exists
git branch -D {runid}-task-{phase}-{task}-{name}

# Recreate worktree from base
BASE_BRANCH=$(git -C .worktrees/{runid}-main branch --show-current)
git worktree add .worktrees/{runid}-task-{phase}-{task} --detach "$BASE_BRANCH"

# Install dependencies
cd .worktrees/{runid}-task-{phase}-{task}
{install-command}
{postinstall-command}

# Spawn fresh agent for this task only
# [Use Task tool with task prompt]
Option D: Continue Without Failed Task

Use when task is non-critical or can be addressed later:

  1. Stack successful task branches
  2. Mark failed task as follow-up work
  3. Continue to next phase
  4. Address failed task in separate branch later

3. Merge Conflicts During Stacking

Symptoms:

  • Stacking parallel branches causes conflicts
  • gs upstack onto fails with merge conflict
  • Git reports conflicting changes in same files

Error message format:

❌ Merge Conflict - Tasks Modified Same Files

**Conflict**: {file-path}
**Branches**: {branch-1}, {branch-2}

This should not happen if task independence was verified correctly.

Root cause: Tasks were marked parallel but have file dependencies.

Resolution steps:

  1. Verify task independence:

    # Check which files each task modified
    git diff {base-branch}..{task-1-branch} --name-only
    git diff {base-branch}..{task-2-branch} --name-only
    # Should have no overlap for parallel tasks
    
  2. Resolve conflict manually:

    cd .worktrees/{runid}-main
    
    # Checkout first task branch
    git checkout {task-1-branch}
    
    # Attempt merge with second task
    git merge {task-2-branch}
    # Conflict will occur
    
    # Resolve in editor
    # Edit conflicted files
    
    # Complete merge
    git add {conflicted-files}
    git commit -m "Merge {task-2-branch} into {task-1-branch}"
    
    # Continue stacking remaining branches
    
  3. Update plan for future:

    • Mark tasks as sequential, not parallel
    • File dependencies mean tasks aren't independent
    • Prevents conflict in future executions

4. Worktree Not Found

Symptoms:

  • Execute command can't find {runid}-main worktree
  • Error: .worktrees/{runid}-main does not exist

Error message format:

❌ Worktree Not Found

**Error**: .worktrees/{run-id}-main does not exist

This means `/spectacular:spec` was not run, or the worktree was removed.

Root cause: Spec command not run, or worktree manually deleted.

Resolution:

Run the spec command first to create workspace:

/spectacular:spec {feature-name}

This will:

  1. Create .worktrees/{runid}-main/ directory
  2. Generate specs/{runid}-{feature-slug}/spec.md
  3. Create base branch {runid}-main

Then:

  1. Run /spectacular:plan to generate execution plan
  2. Run /spectacular:execute to execute the plan

Never skip spec - execute depends on worktree structure created by spec.

5. Parallel Task Worktree Creation Failure

Symptoms:

  • git worktree add fails for parallel tasks
  • Error: "path already exists"
  • Error: "working tree contains modified files"

Error message format:

❌ Parallel Task Worktree Creation Failed

**Error**: {error-message}

Common causes and fixes:

Cause 1: Path Already Exists
# Clean existing path
rm -rf .worktrees/{runid}-task-{phase}-{task}

# Prune stale worktree entries
git worktree prune

# Retry worktree creation
git worktree add .worktrees/{runid}-task-{phase}-{task} --detach {base-branch}
Cause 2: Uncommitted Changes on Current Branch
# Stash changes
git stash

# Or commit changes
git add --all
git commit -m "WIP: Save progress before parallel phase"

# Retry worktree creation
Cause 3: Working Directory Not Clean
# Check status
git status

# Either commit or stash changes
git add --all
git commit -m "[Task {X}.{Y}] Complete task"

# Or stash if work is incomplete
git stash

# Retry worktree creation
Cause 4: Running from Wrong Directory
# Verify not in worktree
REPO_ROOT=$(git rev-parse --show-toplevel)
if [[ "$REPO_ROOT" =~ \.worktrees ]]; then
  echo "Error: In worktree, navigate to main repo"
  cd "$(dirname "$(dirname "$REPO_ROOT")")"
fi

# Navigate to main repo root
MAIN_REPO=$(git rev-parse --show-toplevel | sed 's/\.worktrees.*//')
cd "$MAIN_REPO"

# Retry worktree creation

Diagnostic Commands

Check execution state:

# List all worktrees
git worktree list

# View current branches
git branch | grep "{runid}-"

# View stack structure
cd .worktrees/{runid}-main
gs log short

# Check main worktree state
cd .worktrees/{runid}-main
git status
git branch --show-current

Verify phase readiness:

# Before parallel phase
cd .worktrees/{runid}-main
BASE_BRANCH=$(git branch --show-current)
echo "Parallel phase will build from: $BASE_BRANCH"

# Before sequential phase
cd .worktrees/{runid}-main
CURRENT_BRANCH=$(git branch --show-current)
echo "Sequential phase starting from: $CURRENT_BRANCH"

Check task completion:

# Verify all task branches exist
TASK_BRANCHES=({runid}-task-{phase}-1-{name} {runid}-task-{phase}-2-{name})
for BRANCH in "${TASK_BRANCHES[@]}"; do
  if git rev-parse --verify "$BRANCH" >/dev/null 2>&1; then
    echo "✅ $BRANCH exists"
  else
    echo "❌ $BRANCH missing"
  fi
done

Recovery Strategies

Resume After Manual Fix

If you fixed an issue manually:

  1. Verify state is clean:

    cd .worktrees/{runid}-main
    git status  # Should be clean
    git log --oneline -3  # Verify commits exist
    
  2. Continue to next task/phase:

    • Sequential: Next task creates branch from current HEAD
    • Parallel: Remaining tasks execute in parallel

Reset Phase and Retry

If phase is fundamentally broken:

  1. Reset main worktree to pre-phase state:

    cd .worktrees/{runid}-main
    git reset --hard {base-branch}
    
  2. Remove failed task branches:

    git branch -D {failed-task-branches}
    
  3. Re-run phase:

    • Fix plan if needed
    • Re-execute phase from execute command

Abandon Feature and Clean Up

If feature implementation should be abandoned:

  1. Remove all worktrees:

    git worktree remove .worktrees/{runid}-main
    git worktree remove .worktrees/{runid}-task-*
    git worktree prune
    
  2. Delete all feature branches:

    git branch | grep "^  {runid}-" | xargs git branch -D
    
  3. Clean spec directory:

    rm -rf specs/{runid}-{feature-slug}
    

Prevention

Prevent failures before they occur:

  1. Validate plan before execution:

    • Check task independence for parallel phases
    • Verify file paths are explicit, not wildcards
    • Ensure no circular dependencies
  2. Run setup validation:

    • Use validating-setup-commands skill
    • Verify CLAUDE.md has install/postinstall commands
    • Test quality check commands exist
  3. Use skills correctly:

    • executing-parallel-phase for ALL parallel phases
    • executing-sequential-phase for ALL sequential phases
    • understanding-cross-phase-stacking for phase boundaries
  4. Verify before proceeding:

    • Check branches exist after each phase
    • Verify stack structure with gs log short
    • Run quality checks manually if agents skip them

Quick Reference

Common error patterns:

ErrorQuick Fix
Phase execution failedCheck error, fix manually, resume or retry
Parallel agent failedFix in branch, restart agent, or continue without
Merge conflictResolve manually, update plan to sequential
Worktree not foundRun /spectacular:spec first
Worktree creation failedClean path, stash changes, prune worktrees

Diagnostic sequence:

  1. Read error message carefully
  2. Check execution state (worktrees, branches, commits)
  3. Identify root cause (plan issue? implementation? environment?)
  4. Choose recovery strategy (fix, retry, or continue)
  5. Verify state is clean before proceeding

The Bottom Line

Most failures are recoverable. Understand the error, verify state, fix the issue, and resume execution.

The execute command is designed to be resilient - you can fix issues manually and continue from any phase.

Understanding Cross-Phase Stacking

Overview

Phases automatically build on each other's completed work. Understanding how phases chain together is essential for correct execution.

This is a reference skill - read it to understand cross-phase dependencies, not to execute a workflow.

When to Use

Use this skill when:

  • Starting a new phase (need to understand what base to build from)
  • Debugging stack relationships across phase boundaries
  • Verifying phases are chaining correctly
  • Understanding why parallel worktrees use specific base branches

Mental model check: If you're thinking "create worktrees from {runid}-main branch", you need this skill.

The Cross-Phase Inheritance Principle

MAIN WORKTREE CURRENT BRANCH = LATEST COMPLETED WORK

Key insight:

  • Sequential phases leave main worktree on their last task's branch
  • Parallel phases leave main worktree on their last stacked branch
  • Next phase (sequential or parallel) inherits from current branch, not original base

This creates automatic linear chaining across all phases.

Example: Sequential → Parallel → Sequential

Phase 1 (Sequential) - Database Setup

# Working in: .worktrees/{runid}-main
# Starting from: {runid}-main (base branch)

# Task 1: Database schema
gs branch create {runid}-task-1-1-database-schema
# Creates branch, commits work
# Main worktree now on: {runid}-task-1-1-database-schema ← KEY STATE

Phase 1 result:

  • Branch created: {runid}-task-1-1-database-schema
  • Main worktree current branch: {runid}-task-1-1-database-schema
  • This branch becomes Phase 2's base

Phase 2 (Parallel) - Three Feature Implementations

# Base detection (CRITICAL):
BASE_BRANCH=$(git -C .worktrees/{runid}-main branch --show-current)
# Returns: {runid}-task-1-1-database-schema ← Inherits from Phase 1

# Create parallel worktrees FROM Phase 1's completed branch
git worktree add .worktrees/{runid}-task-2-1 --detach "$BASE_BRANCH"
git worktree add .worktrees/{runid}-task-2-2 --detach "$BASE_BRANCH"
git worktree add .worktrees/{runid}-task-2-3 --detach "$BASE_BRANCH"

# All 3 parallel tasks build on Phase 1's database schema

After parallel tasks complete and stack:

# In main worktree (.worktrees/{runid}-main):
# Branch 1: {runid}-task-2-1-user-service → tracked
# Branch 2: {runid}-task-2-2-product-service → tracked, upstacked onto Branch 1
# Branch 3: {runid}-task-2-3-order-service → tracked, upstacked onto Branch 2

# Main worktree now on: {runid}-task-2-3-order-service ← KEY STATE

Phase 2 result:

  • Linear stack: database-schema → user-service → product-service → order-service
  • Main worktree current branch: {runid}-task-2-3-order-service
  • This branch becomes Phase 3's base

Phase 3 (Sequential) - Integration Tests

# Working in: .worktrees/{runid}-main (reused from Phase 1)
# Current branch: {runid}-task-2-3-order-service (from Phase 2)

# Task 1: Integration tests
gs branch create {runid}-task-3-1-integration-tests
# Automatically stacks on Phase 2's last task via natural stacking

Phase 3 result:

  • Linear chain: Phase 1 → Phase 2 tasks → Phase 3
  • Complete stack shows all work in order

Verification Between Phases

Before starting parallel phase (check inheritance):

# Verify base branch before creating worktrees
BASE_BRANCH=$(git -C .worktrees/{runid}-main branch --show-current)
echo "Starting parallel phase from: $BASE_BRANCH"
# Should show previous phase's completed branch, NOT {runid}-main

Before starting sequential phase (check current state):

# Verify starting point
CURRENT_BRANCH=$(git -C .worktrees/{runid}-main branch --show-current)
echo "Starting sequential phase from: $CURRENT_BRANCH"
# Should show previous phase's last stacked branch

After phase completes (verify stack):

cd .worktrees/{runid}-main
gs log short
# Should show linear chain including all previous phases

Key Principles

  1. Main worktree tracks progress

    • Current branch = latest completed work
    • Not static - changes as phases complete
  2. Parallel phases inherit from current

    • Use git -C .worktrees/{runid}-main branch --show-current as base
    • NOT {runid}-main (that's the original starting point)
  3. Parallel stacking preserves continuity

    • Last stacked branch becomes next phase's base
    • Checkout last branch after stacking completes
  4. Sequential phases extend naturally

    • gs branch create stacks on current HEAD
    • No manual base specification needed
  5. No manual intervention needed

    • Cross-phase chaining is automatic
    • Following per-phase patterns creates correct chain

Common Mistake: Creating From Wrong Base

❌ Wrong: Creating parallel worktrees from original base

# DON'T DO THIS:
git worktree add .worktrees/{runid}-task-2-1 --detach {runid}-main

Why wrong: Ignores Phase 1's completed work. Phase 2 won't have database schema from Phase 1.

Result: Broken dependency chain. Phase 2 builds on stale base instead of Phase 1's changes.

✅ Correct: Creating parallel worktrees from current branch

# DO THIS:
BASE_BRANCH=$(git -C .worktrees/{runid}-main branch --show-current)
git worktree add .worktrees/{runid}-task-2-1 --detach "$BASE_BRANCH"

Why correct: Inherits all previous work. Phase 2 builds on Phase 1's completed branch.

Result: Linear chain across all phases.

Mental Model Check

If you're thinking:

  • "Create worktrees from {runid}-main" → WRONG. Use current branch.
  • "Parallel tasks should start fresh" → WRONG. They inherit previous work.
  • "Phase boundaries break the stack" → WRONG. Stack is continuous across phases.

Correct mental model:

  • Main worktree is a moving cursor pointing to latest work
  • Each phase extends the cursor position, doesn't reset it
  • Stack is one continuous chain, not per-phase segments

Quick Reference

Starting parallel phase:

BASE_BRANCH=$(git -C .worktrees/{runid}-main branch --show-current)
# Use $BASE_BRANCH for all worktree creation

Starting sequential phase:

# Already on correct branch - just create next branch
gs branch create {runid}-task-{phase}-{task}-{name}
# Automatically stacks on current HEAD

Verifying cross-phase chain:

cd .worktrees/{runid}-main
gs log short
# Should show linear progression through all phases

The Bottom Line

Phases chain automatically through main worktree's current branch.

If you're manually specifying base branches or creating worktrees from {runid}-main, you're breaking the automatic inheritance system.

Trust the pattern: main worktree tracks progress, new phases build from current state.

Using git-spice

Overview

git-spice (gs) is a CLI tool for managing stacked Git branches and their Change Requests.

Core principle: git-spice tracks branch relationships (stacks) and automates rebasing/submitting dependent branches.

Key Concepts

Stack terminology:

  • Stack: All branches connected to current branch (both upstack and downstack)
  • Upstack: Branches built on top of current branch (children and descendants)
  • Downstack: Branches below current branch down to trunk (parents and ancestors)
  • Trunk: Main integration branch (typically main or master)

Example stack:

┌── feature-c     ← upstack from feature-b
├── feature-b     ← upstack from feature-a, downstack from feature-c
├── feature-a     ← downstack from feature-b
main (trunk)

When on feature-b:

  • Upstack: feature-c
  • Downstack: feature-a, main
  • Stack: feature-a, feature-b, feature-c

Quick Reference

TaskCommandNotes
Initialize repogs repo initRequired once per repo. Sets trunk branch.
Create stacked branchgs branch create <name>Creates branch on top of current. Use gs bc shorthand.
View stackgs log shortShows current stack. Use gs ls or gs log long (gs ll) for details.
Submit stack as PRsgs stack submitSubmits entire stack. Use gs ss shorthand.
Submit upstack onlygs upstack submitCurrent branch + children. Use gs us s shorthand.
Submit downstack onlygs downstack submitCurrent branch + parents to trunk. Use gs ds s shorthand.
Rebase entire stackgs repo restackRebases all tracked branches on their bases.
Rebase current stackgs stack restackRebases current branch's stack. Use gs sr shorthand.
Rebase upstackgs upstack restackCurrent branch + children. Use gs us r shorthand.
Move branch to new basegs upstack onto <base>Moves current + upstack to new base.
Sync with remotegs repo syncPulls latest, deletes merged branches.
Track existing branchgs branch track [branch]Adds branch to git-spice tracking.
Delete branchgs branch delete [branch]Deletes branch, restacks children. Use gs bd shorthand.

Command shortcuts: Most commands have short aliases. Use gs --help to see all aliases.

Common Workflows

These workflows apply to single-repository scenarios. For features spanning multiple repositories, see Multi-Repo Workflows below.

Workflow 1: Create and Submit Stack

# One-time setup
gs repo init
# Prompt asks for trunk branch (usually 'main')

# Create stacked branches
gs branch create feature-a
# Make changes, commit with git
git add . && git commit -m "Implement A"

gs branch create feature-b  # Stacks on feature-a
# Make changes, commit
git add . && git commit -m "Implement B"

gs branch create feature-c  # Stacks on feature-b
# Make changes, commit
git add . && git commit -m "Implement C"

# View the stack
gs log short

# Submit entire stack as PRs
gs stack submit
# Creates/updates PRs for all branches in stack

Workflow 2: Update Branch After Review

# You have feature-a → feature-b → feature-c
# Reviewer requested changes on feature-b

git checkout feature-b
# Make changes, commit
git add . && git commit -m "Address review feedback"

# Rebase upstack (feature-c) on updated feature-b
gs upstack restack

# Submit changes to update PRs
gs upstack submit
# Note: restack only rebases locally, submit pushes and updates PRs

CRITICAL: Don't manually rebase feature-c! Use gs upstack restack to maintain stack relationships.

Workflow 3: Sync After Upstream Merge

# feature-a was merged to main
# Need to update feature-b and feature-c

# Sync with remote (pulls main, deletes merged branches)
gs repo sync

# Restack everything on new main
gs repo restack

# Verify stack looks correct
gs log short

# Push updated branches
gs stack submit

CRITICAL: Don't rebase feature-c onto main! After feature-a merges:

  • feature-b rebases onto main (its new base)
  • feature-c rebases onto feature-b (maintains dependency)

When to Use Git vs git-spice

Use git-spice for:

  • Creating branches in a stack: gs branch create
  • Rebasing stacks: gs upstack restack, gs repo restack
  • Submitting PRs: gs stack submit, gs upstack submit
  • Viewing stack structure: gs log short
  • Deleting branches: gs branch delete (restacks children)

Use git for:

  • Making changes: git add, git commit
  • Checking status: git status, git diff
  • Viewing commit history: git log
  • Individual branch operations: git checkout, git switch

Never use git rebase directly on stacked branches - use git-spice restack commands to maintain relationships.

Common Mistakes

MistakeWhy It's WrongCorrect Approach
Rebasing child onto trunk after parent mergesBreaks stack relationships, creates conflictsUse gs repo sync && gs repo restack
Using git push --force after changesBypasses git-spice trackingUse gs upstack submit or gs stack submit
Manually rebasing with git rebasegit-spice doesn't track the rebaseUse gs upstack restack or gs stack restack
Running gs stack submit on wrong branchMight submit unintended branchesCheck gs log short first to see what's in stack
Forgetting gs repo initCommands fail with unclear errorsRun gs repo init once per repository
Using stack when you mean upstackSubmits downstack branches too (parents)Use upstack to submit only current + children
Assuming restack runs automaticallyAfter commits, stack can driftExplicitly run gs upstack restack after changes

Red Flags - Check Documentation

  • Confused about stack/upstack/downstack scope
  • About to run git rebase on a tracked branch
  • Unsure which submit command to use
  • Getting "not tracked" errors

When uncertain, run gs <command> --help for detailed usage.

Authentication and Setup

First time setup:

# Authenticate with GitHub/GitLab
gs auth login
# Follow prompts for OAuth or token auth

# Initialize repository
gs repo init
# Sets trunk branch and remote

# Verify setup
gs auth status

Handling Conflicts

If gs upstack restack or gs repo restack encounters conflicts:

  1. Resolve conflicts using standard git workflow (git status, edit files, git add)
  2. Continue with git rebase --continue
  3. git-spice will resume restacking remaining branches
  4. After resolution, run gs upstack submit to push changes

If you need to abort a restack, check gs --help for recovery options.

Multi-Repo Workflows

Per-Repo Stacking Limitation

Git-spice operates on ONE repository at a time. In multi-repo spectacular features:

  • Each repo has its own independent stack
  • Cannot create a cross-repo linear stack
  • Branches stay within their respective repos

Multi-Repo PR Submission

For features spanning multiple repos, submit PRs in phase order:

Phase-ordered submission:

# Phase 1 repos first (foundation)
cd shared-lib
gs stack submit
cd ..

# Phase 2 repos second
cd backend
gs stack submit
cd ..

# Phase 3 repos last (depends on earlier phases)
cd frontend
gs stack submit
cd ..

Why phase order matters:

  • Phase 1 changes (e.g., shared types) must merge before Phase 2 consumers
  • Prevents broken builds from missing dependencies
  • Mirrors the execution order during development

Multi-Repo Stack Visualization

View stacks across all repos:

# From workspace root
for repo in backend frontend shared-lib; do
  echo "=== $repo ==="
  cd $repo && gs log short && cd ..
done

Multi-Repo Sync

After PRs merge, sync all repos:

# From workspace root
for repo in backend frontend shared-lib; do
  echo "Syncing $repo..."
  cd $repo && gs repo sync && cd ..
done

Coordinating Cross-Repo Dependencies

If PR in repo A depends on PR in repo B:

  1. Merge repo B's PR first
  2. Update repo A to use the merged changes
  3. Then merge repo A's PR

Example:

shared-lib: PR for new types
  ↓ (merge first)
backend: PR using new types
  ↓ (merge second)
frontend: PR using backend API
  ↓ (merge third)

Additional Resources

<EXTREMELY_IMPORTANT> You have spectacular.

The content below is your introduction to using spectacular:


Using Spectacular

Spectacular extends superpowers with spec-anchored development workflows. Before responding to user requests for features or refactors, you MUST check if spectacular workflows apply.

MANDATORY FIRST RESPONSE PROTOCOL

Before responding to ANY user message about features, refactors, or implementations:

  1. ☐ Does request involve implementing/refactoring features?
  2. ☐ Is there a docs/constitutions/current/ directory in this project?
  3. ☐ If yes → Use spectacular workflow (spec → plan → execute)
  4. ☐ If no constitution → Ask if user wants to use spectacular

Responding to feature requests WITHOUT this check = automatic failure.

Core Spectacular Workflow

User request → /spectacular:spec → /spectacular:plan → /spectacular:execute

Each command has a specific purpose:

  1. /spectacular:spec - Generate feature specification

    • When: User describes a feature to implement or refactor
    • Output: specs/{runId}-{feature-slug}/spec.md
    • Includes: Requirements, architecture, acceptance criteria
    • References: Constitution rules (doesn't duplicate them)
  2. /spectacular:plan - Decompose spec into execution plan

    • When: After spec is reviewed and approved
    • Input: Path to spec.md
    • Output: specs/{runId}-{feature-slug}/plan.md
    • Analyzes: Task dependencies, file overlaps
    • Generates: Sequential/parallel phases with time estimates
  3. /spectacular:execute - Execute plan with parallel orchestration

    • When: After plan is reviewed and approved
    • Input: Path to plan.md
    • Creates: Worktrees, spawns subagents, stacks branches
    • Quality gates: Tests/lint after each task, code review after each phase

Constitutions: Architectural Truth

If docs/constitutions/current/ exists, it contains immutable architectural rules:

  • architecture.md - Layer boundaries, project structure
  • patterns.md - Mandatory patterns (e.g., "use Zod for validation")
  • tech-stack.md - Approved libraries and versions
  • testing.md - Testing requirements

Critical:

  • ✅ ALWAYS reference constitution in specs (don't duplicate)
  • ✅ ALWAYS validate implementation against constitution
  • ❌ NEVER violate constitutional patterns
  • ❌ NEVER copy-paste constitution rules into specs

Common Rationalizations That Mean You're Failing

If you catch yourself thinking ANY of these, STOP and use spectacular:

RationalizationWhy It's WrongWhat to Do Instead
"Request is clear, no spec needed"Clear request = easier to spec, not permission to skipUse /spectacular:spec
"Feature is small, just code it"Small features drift without specsUse /spectacular:spec
"User wants it fast"Workflow IS faster (parallel + fewer bugs)Use /spectacular:spec
"Constitution doesn't apply"Constitution always appliesReference in spec
"I can plan mentally"Mental = no review, no parallelizationUse /spectacular:plan
"Just a bugfix/refactor"Multi-file changes are featuresIf complex: use /spectacular:spec

Workflow Enforcement

User instructions describe WHAT to build, not permission to skip workflows.

  • "Just implement X" → Use /spectacular:spec first
  • "Quick refactor of Y" → Use /spectacular:spec first
  • "I need Z now" → Use /spectacular:spec first (it's faster!)

Why workflows matter:

  • Specs catch requirements drift before code
  • Plans enable parallelization (3-5x faster)
  • Constitution prevents architectural debt
  • Quality gates catch bugs early

Summary: Mandatory Workflow

For feature/refactor requests:

  1. ✅ Check if spectacular applies (constitution exists?)
  2. ✅ Use /spectacular:spec to create specification
  3. ✅ User reviews spec (STOP until approved)
  4. ✅ Use /spectacular:plan to decompose into tasks
  5. ✅ User reviews plan (STOP until approved)
  6. ✅ Use /spectacular:execute to implement with quality gates

Skipping steps = violating quality standards.

When in doubt: "Should I use spectacular for this?" → Almost always YES for multi-file changes.

</EXTREMELY_IMPORTANT>

Validating Environment

Overview

This skill validates that all required dependencies and configuration are in place for spectacular workflows. It checks for the superpowers plugin, git-spice installation, git repository status, and project structure. It also detects whether the workspace is single-repo or multi-repo.

When to Use

Use this skill when:

  • Starting a new spectacular session
  • Running /spectacular:init command
  • Before beginning any spectacular workflow to ensure prerequisites are met
  • Troubleshooting spectacular setup issues

Announce: "I'm using validating-environment to check the spectacular setup."

The Process

Step 1: Check Superpowers Plugin

Check if superpowers is installed (handles both direct and marketplace installs):

# Check both possible install locations:
# - Direct: ~/.claude/plugins/cache/superpowers
# - Marketplace: ~/.claude/plugins/cache/superpowers-marketplace/superpowers
SUPERPOWERS_PATH=""
if [ -d ~/.claude/plugins/cache/superpowers ]; then
  SUPERPOWERS_PATH=~/.claude/plugins/cache/superpowers
elif [ -d ~/.claude/plugins/cache/superpowers-marketplace/superpowers ]; then
  SUPERPOWERS_PATH=~/.claude/plugins/cache/superpowers-marketplace/superpowers
fi

if [ -n "$SUPERPOWERS_PATH" ]; then
  echo "Superpowers plugin is installed"
  SUPERPOWERS_VERSION=$(cd "$SUPERPOWERS_PATH" && git describe --tags 2>/dev/null || echo "unknown")
  echo "   Version: $SUPERPOWERS_VERSION"
  echo "   Path: $SUPERPOWERS_PATH"
else
  echo "Superpowers plugin NOT installed"
  echo ""
  echo "Spectacular requires the superpowers plugin for core skills:"
  echo "  - brainstorming"
  echo "  - subagent-driven-development"
  echo "  - requesting-code-review"
  echo "  - verification-before-completion"
  echo "  - finishing-a-development-branch"
  echo ""
  echo "Install with:"
  echo "  /plugin install superpowers@superpowers-marketplace"
  echo ""
  SUPERPOWERS_MISSING=true
fi

Step 2: Check Git-Spice

Verify git-spice is installed and accessible:

if command -v gs &> /dev/null; then
  echo "Git-spice is installed"
  GS_VERSION=$(gs --version 2>&1 | head -1)
  echo "   $GS_VERSION"

  # Check if we're in a git repo
  if git rev-parse --git-dir > /dev/null 2>&1; then
    # Check if git-spice is initialized
    if gs ls &> /dev/null; then
      echo "Git-spice is initialized for this repo"
    else
      echo "Git-spice not initialized for this repo"
      echo ""
      echo "Initialize with:"
      echo "  gs repo init"
      echo ""
      GS_NOT_INITIALIZED=true
    fi
  fi
else
  echo "Git-spice NOT installed"
  echo ""
  echo "Spectacular uses git-spice for stacked branch management."
  echo ""
  echo "Install instructions:"
  echo "  macOS: brew install git-spice"
  echo "  Linux: See https://github.com/abhinav/git-spice"
  echo ""
  GS_MISSING=true
fi

Step 3: Configure Gitignore

Ensure .gitignore has spectacular-specific entries:

if [ -f .gitignore ]; then
  echo ".gitignore exists"

  # Check for .worktrees/ entry
  if grep -q "^\.worktrees/" .gitignore 2>/dev/null; then
    echo "   .worktrees/ already in .gitignore"
  else
    echo "   Adding .worktrees/ to .gitignore"
    echo "" >> .gitignore
    echo "# Spectacular parallel execution worktrees" >> .gitignore
    echo ".worktrees/" >> .gitignore
    echo "   Added .worktrees/ to .gitignore"
  fi

  # Check for specs/ is NOT ignored (we want specs tracked)
  if grep -q "^specs/" .gitignore 2>/dev/null; then
    echo "   WARNING: specs/ is gitignored - you probably want to track specs"
    echo "   Remove 'specs/' from .gitignore to track your specifications"
  else
    echo "   specs/ will be tracked (not in .gitignore)"
  fi
else
  echo "No .gitignore found - creating one"
  cat > .gitignore << 'EOF'
# Spectacular parallel execution worktrees
.worktrees/

# Common patterns
node_modules/
.DS_Store
*.log
EOF
  echo "   Created .gitignore with spectacular patterns"
fi

Step 4: Check Git Repository

Validate git setup:

if git rev-parse --git-dir > /dev/null 2>&1; then
  echo "Git repository detected"

  # Check current branch
  CURRENT_BRANCH=$(git branch --show-current)
  echo "   Current branch: $CURRENT_BRANCH"

  # Check if there's a remote
  if git remote -v | grep -q .; then
    echo "   Remote configured"
    git remote -v | head -2 | sed 's/^/   /'
  else
    echo "   No remote configured"
    echo "   You may want to add a remote for PR submission"
  fi

  # Check working directory status
  if git diff --quiet && git diff --cached --quiet; then
    echo "   Working directory clean"
  else
    echo "   Uncommitted changes present"
  fi
else
  echo "NOT a git repository"
  echo ""
  echo "Initialize git with:"
  echo "  git init"
  echo "  git add ."
  echo "  git commit -m 'Initial commit'"
  echo ""
  NOT_GIT_REPO=true
fi

Step 5: Validate Project Structure

Check for expected directories:

echo ""
echo "Checking project structure..."

# Check/create specs directory
if [ -d specs ]; then
  echo "specs/ directory exists"
  SPEC_COUNT=$(find specs -name "spec.md" 2>/dev/null | wc -l | tr -d ' ')
  echo "   Found $SPEC_COUNT specification(s)"
else
  echo "Creating specs/ directory"
  mkdir -p specs
  echo "   Created specs/ directory"
fi

# Check for .worktrees (should NOT exist yet, just checking)
if [ -d .worktrees ]; then
  echo ".worktrees/ directory exists"
  WORKTREE_COUNT=$(ls -1 .worktrees 2>/dev/null | wc -l | tr -d ' ')
  if [ "$WORKTREE_COUNT" -gt 0 ]; then
    echo "   Contains $WORKTREE_COUNT worktree(s) - may be leftover from previous execution"
    echo "   Clean up with: git worktree list && git worktree remove <path>"
  fi
else
  echo "No .worktrees/ directory (will be created during parallel execution)"
fi

Step 6: Multi-Repo Detection and Validation

Detect whether the workspace is single-repo or multi-repo, and validate per-repo requirements:

echo ""
echo "Detecting workspace mode..."

# Detect workspace mode by looking for multiple .git directories
# In multi-repo setups, there are typically multiple repos in the parent directory
REPO_COUNT=$(find . -maxdepth 2 -name ".git" -type d 2>/dev/null | wc -l | tr -d ' ')
if [ "$REPO_COUNT" -gt 1 ]; then
  echo "Multi-repo workspace detected ($REPO_COUNT repos)"
  WORKSPACE_MODE="multi-repo"

  # List and validate each repo
  REPOS=$(find . -maxdepth 2 -name ".git" -type d | xargs -I{} dirname {} | sed 's|^\./||' | sort)

  for REPO in $REPOS; do
    echo ""
    echo "Checking repo: $REPO"

    # Check for CLAUDE.md with setup commands
    if [ -f "$REPO/CLAUDE.md" ]; then
      if grep -q "**install**:" "$REPO/CLAUDE.md"; then
        echo "  CLAUDE.md with setup commands found"
      else
        echo "  Warning: CLAUDE.md exists but missing setup commands"
        echo "    Add '**install**: \`your-install-command\`' to $REPO/CLAUDE.md"
      fi
    else
      echo "  Warning: No CLAUDE.md found in $REPO"
      echo "    Create $REPO/CLAUDE.md with setup commands for worktree support"
    fi

    # Check for constitution (optional)
    if [ -d "$REPO/docs/constitutions/current" ]; then
      echo "  Constitution found"
    else
      echo "  Note: No constitution at docs/constitutions/current/"
    fi
  done

else
  echo "Single-repo mode"
  WORKSPACE_MODE="single-repo"
fi

Create workspace-level specs directory (multi-repo only):

if [ "$WORKSPACE_MODE" = "multi-repo" ]; then
  echo ""
  if [ ! -d "specs" ]; then
    echo "Creating specs/ directory at workspace root"
    mkdir -p specs
    echo "   Created specs/ for cross-repo specifications"
  else
    echo "specs/ directory exists at workspace root"
    SPEC_COUNT=$(find specs -name "spec.md" 2>/dev/null | wc -l | tr -d ' ')
    echo "   Found $SPEC_COUNT specification(s)"
  fi
fi

Step 7: Report Summary

Generate final status report:

echo ""
echo "========================================="
echo "Spectacular Initialization Summary"
echo "========================================="
echo ""

# Report workspace mode
if [ "$WORKSPACE_MODE" = "multi-repo" ]; then
  echo "Workspace Mode: Multi-repo"
else
  echo "Workspace Mode: Single-repo"
fi
echo ""

# Check if all critical dependencies are met
if [ -z "$SUPERPOWERS_MISSING" ] && [ -z "$GS_MISSING" ] && [ -z "$NOT_GIT_REPO" ]; then
  echo "Environment ready for spectacular workflows!"
  echo ""
  echo "Next steps:"
  echo "  1. Generate a spec: /spectacular:spec \"your feature description\""
  echo "  2. Create a plan: /spectacular:plan @specs/{run-id}-{feature-slug}/spec.md"
  echo "  3. Execute: /spectacular:execute @specs/{run-id}-{feature-slug}/plan.md"
  echo ""

  if [ -n "$GS_NOT_INITIALIZED" ]; then
    echo "Optional: Initialize git-spice with 'gs repo init'"
    echo ""
  fi
else
  echo "Setup incomplete - resolve issues above before using spectacular"
  echo ""

  if [ -n "$SUPERPOWERS_MISSING" ]; then
    echo "REQUIRED: Install superpowers plugin"
    echo "  /plugin install superpowers@superpowers-marketplace"
    echo ""
  fi

  if [ -n "$GS_MISSING" ]; then
    echo "REQUIRED: Install git-spice"
    echo "  macOS: brew install git-spice"
    echo "  Linux: https://github.com/abhinav/git-spice"
    echo ""
  fi

  if [ -n "$NOT_GIT_REPO" ]; then
    echo "REQUIRED: Initialize git repository"
    echo "  git init"
    echo ""
  fi

  echo "Run /spectacular:init again after resolving issues"
fi

echo "========================================="

Multi-repo summary addition:

If WORKSPACE_MODE="multi-repo", append additional details:

if [ "$WORKSPACE_MODE" = "multi-repo" ]; then
  echo ""
  echo "========================================="
  echo "Multi-Repo Workspace Summary"
  echo "========================================="
  echo ""
  echo "Workspace root: $(pwd)"
  echo "Repos detected: $REPO_COUNT"
  echo ""
  echo "Per-repo status:"
  for REPO in $REPOS; do
    CLAUDE_STATUS="missing"
    CONST_STATUS="missing"
    [ -f "$REPO/CLAUDE.md" ] && CLAUDE_STATUS="present"
    [ -d "$REPO/docs/constitutions/current" ] && CONST_STATUS="present"
    echo "  $REPO: CLAUDE.md=$CLAUDE_STATUS, constitution=$CONST_STATUS"
  done
  echo ""
  echo "Specs location: ./specs/ (workspace root)"
  echo ""
  echo "Next steps for multi-repo:"
  echo "  1. Ensure each repo has CLAUDE.md with setup commands"
  echo "  2. Generate a spec: /spectacular:spec \"your feature\""
  echo "  3. Spec will be saved to ./specs/{runId}-{feature}/"
  echo "  4. Use @repo:path syntax to reference files across repos"
  echo ""
  echo "========================================="
fi

Quality Rules

  1. All checks must complete - Do not skip any validation step
  2. Clear status indicators - Use consistent status messages for pass/fail/warning
  3. Actionable guidance - Every failure must include instructions for resolution
  4. Non-destructive - Only create directories and modify .gitignore; never delete or overwrite existing content
  5. Idempotent - Running multiple times should produce the same result

Error Handling

Superpowers Plugin Missing

If superpowers is not installed:

  1. Report the missing dependency clearly
  2. Explain why it's required (list the dependent skills)
  3. Provide exact installation command
  4. Mark initialization as incomplete

Git-Spice Missing

If git-spice is not installed:

  1. Report the missing dependency
  2. Explain its purpose (stacked branch management)
  3. Provide installation instructions for multiple platforms
  4. Mark initialization as incomplete

Git-Spice Not Initialized

If git-spice is installed but not initialized for this repo:

  1. Report as a warning (not a blocker)
  2. Provide the initialization command
  3. Continue with remaining checks

Not a Git Repository

If the current directory is not a git repository:

  1. Report as a critical failure
  2. Provide git initialization commands
  3. Mark initialization as incomplete

Stale Worktrees

If .worktrees/ exists with content:

  1. Report as a warning
  2. Explain these may be from a previous incomplete execution
  3. Provide cleanup commands
  4. Continue with remaining checks

Multi-Repo Workspace

If multiple repositories are detected:

  1. Report the workspace mode and repo count
  2. Validate each repo for required configuration:
    • Check for CLAUDE.md file
    • Check if CLAUDE.md has setup commands (**install**:)
    • Check for constitution at docs/constitutions/current/
  3. Create workspace-level specs/ directory if missing
  4. Generate per-repo status summary showing:
    • CLAUDE.md presence (required for worktree support)
    • Constitution presence (optional, shows warning if missing)
  5. Provide clear next steps for multi-repo workflows

Missing CLAUDE.md in Repo

If a repo lacks CLAUDE.md:

  1. Report as a warning (not a blocker)
  2. Explain why it's needed (worktree setup requires install commands)
  3. Provide guidance on what to add
  4. Continue checking other repos

Missing Setup Commands

If CLAUDE.md exists but lacks setup commands:

  1. Report as a warning
  2. Explain the required format (**install**: \command``)
  3. Note that worktrees won't work properly without setup commands
  4. Continue validation

Validating Setup Commands

Overview

Worktrees require dependency installation before tasks can execute. Projects MUST define setup commands in CLAUDE.md.

This skill validates setup commands exist BEFORE creating worktrees, preventing cryptic failures later.

When to Use

Use this skill when:

  • Creating new worktrees (spec, execute commands)
  • Before executing tasks that need dependencies
  • Any time you need to verify project setup is documented

Use early: Validate during setup phase, not during task execution.

Why This Matters

Without validation:

  • Worktrees get created
  • Tasks start executing
  • Fail with "command not found" errors
  • User debugging nightmare: "Why is npm/pytest/cargo missing?"

With validation:

  • Missing commands detected immediately
  • Clear error with exact CLAUDE.md section to add
  • User fixes once, all worktrees work

The Validation Process

Announce: "Validating CLAUDE.md setup commands before creating worktrees."

Step 1: Check File Exists

# Get repo root
REPO_ROOT=$(git rev-parse --show-toplevel)

# Check if CLAUDE.md exists
if [ ! -f "$REPO_ROOT/CLAUDE.md" ]; then
  echo "❌ Error: CLAUDE.md not found in repository root"
  echo ""
  echo "Spectacular requires CLAUDE.md to define setup commands."
  echo "See: https://docs.claude.com/claude-code"
  exit 1
fi

Why fail fast: No CLAUDE.md = no command configuration. Stop before creating any worktrees.

Step 2: Parse Setup Section

# Parse CLAUDE.md for setup section
INSTALL_CMD=$(grep -A 10 "^### Setup" "$REPO_ROOT/CLAUDE.md" | grep "^- \*\*install\*\*:" | sed 's/.*: `\(.*\)`.*/\1/')

if [ -z "$INSTALL_CMD" ]; then
  echo "❌ Error: Setup commands not defined in CLAUDE.md"
  echo ""
  echo "Worktrees require dependency installation before tasks can execute."
  echo ""
  echo "Add this section to CLAUDE.md:"
  echo ""
  echo "## Development Commands"
  echo ""
  echo "### Setup"
  echo "- **install**: \`npm install\`  (or your package manager)"
  echo "- **postinstall**: \`npx prisma generate\`  (optional - any codegen)"
  echo ""
  echo "Example for different package managers:"
  echo "- Node.js: npm install, pnpm install, yarn, or bun install"
  echo "- Python: pip install -r requirements.txt"
  echo "- Rust: cargo build"
  echo "- Go: go mod download"
  echo ""
  echo "See: https://docs.claude.com/claude-code"
  echo ""
  echo "Execution stopped. Add setup commands to CLAUDE.md and retry."
  exit 1
fi

# Extract postinstall command (optional)
POSTINSTALL_CMD=$(grep -A 10 "^### Setup" "$REPO_ROOT/CLAUDE.md" | grep "^- \*\*postinstall\*\*:" | sed 's/.*: `\(.*\)`.*/\1/')

Parsing logic:

  • Look for ### Setup header
  • Extract **install**: command (required)
  • Extract **postinstall**: command (optional)
  • Use sed to extract command from backticks

Step 3: Report Success

# Report detected commands
echo "✅ Setup commands found in CLAUDE.md"
echo "   install: $INSTALL_CMD"
if [ -n "$POSTINSTALL_CMD" ]; then
  echo "   postinstall: $POSTINSTALL_CMD"
fi

Store for later use:

  • Return INSTALL_CMD to caller
  • Return POSTINSTALL_CMD (may be empty)
  • Caller uses these in worktree dependency installation

Expected CLAUDE.md Format

The skill expects this exact format:

## Development Commands

### Setup
- **install**: `npm install`
- **postinstall**: `npx prisma generate`  (optional)

Format requirements:

  • Section header: ### Setup (exactly)
  • Install line: - **install**: command`` (required)
  • Postinstall line: - **postinstall**: command`` (optional)
  • Commands must be in backticks

Multi-language examples:

### Setup
- **install**: `npm install`           # Node.js
- **install**: `pip install -r requirements.txt`  # Python
- **install**: `cargo build`           # Rust
- **install**: `go mod download`       # Go
- **install**: `bundle install`        # Ruby

Error Messages

Error 1: CLAUDE.md Not Found

❌ Error: CLAUDE.md not found in repository root

Spectacular requires CLAUDE.md to define setup commands.
See: https://docs.claude.com/claude-code

User action: Create CLAUDE.md in repository root.

Error 2: Setup Commands Missing

❌ Error: Setup commands not defined in CLAUDE.md

Worktrees require dependency installation before tasks can execute.

Add this section to CLAUDE.md:

## Development Commands

### Setup
- **install**: `npm install`  (or your package manager)
- **postinstall**: `npx prisma generate`  (optional - any codegen)

Example for different package managers:
- Node.js: npm install, pnpm install, yarn, or bun install
- Python: pip install -r requirements.txt
- Rust: cargo build
- Go: go mod download

See: https://docs.claude.com/claude-code

Execution stopped. Add setup commands to CLAUDE.md and retry.

User action: Add Setup section with at least install command.

Integration Pattern

How commands use this skill:

# In execute.md or spec.md:

# Step 1.5: Validate Setup Commands
# Use validating-setup-commands skill to extract and verify
INSTALL_CMD=$(validate_setup_commands_install)
POSTINSTALL_CMD=$(validate_setup_commands_postinstall)

# Step 3: Create worktrees
git worktree add .worktrees/{runid}-task-1

# Step 4: Install dependencies using validated commands
cd .worktrees/{runid}-task-1
$INSTALL_CMD
if [ -n "$POSTINSTALL_CMD" ]; then
  $POSTINSTALL_CMD
fi

Reusable across:

  • /spectacular:spec - Validates before creating main worktree
  • /spectacular:execute - Validates before creating task worktrees
  • Future commands that create worktrees

Common Mistakes

Mistake 1: Running Validation Too Late

Wrong: Create worktrees, then validate Right: Validate BEFORE creating ANY worktrees

Why: Failed validation after worktrees exist leaves orphaned directories.

Mistake 2: Not Providing Examples

Wrong: "Error: Add setup commands" Right: "Error: Add setup commands. Here's the exact format: [example]"

Why: Users need to know WHAT to add and WHERE.

Mistake 3: Requiring Postinstall

Wrong: Fail if postinstall missing Right: Postinstall is optional (codegen only needed in some projects)

Why: Not all projects have codegen (Prisma, GraphQL, etc.).

Quick Reference

Validation sequence:

  1. Check CLAUDE.md exists (exit if missing)
  2. Parse for ### Setup section
  3. Extract install command (exit if missing)
  4. Extract postinstall command (optional)
  5. Report success and return commands

Exit points:

  • Missing CLAUDE.md → Error with creation instructions
  • Missing setup section → Error with exact format example
  • Success → Return INSTALL_CMD and POSTINSTALL_CMD

Format validated:

  • ### Setup header
  • - **install**: command``
  • - **postinstall**: command`` (optional)

The Bottom Line

Validate setup commands BEFORE creating worktrees.

Early validation with clear error messages prevents confusing failures during task execution.

The skill provides users with exact examples of what to add, making fixes easy.

Versioning Constitutions

Core Principle

Constitution versions are immutable snapshots of architectural truth.

When foundational rules change (patterns, tech stack, architecture), create a new version rather than editing in place. This preserves history, enables rollback, and makes changes explicit.

When to Use This Skill

ALWAYS create a new version when:

  • Adding a new mandatory pattern (e.g., adopting effect-ts for error handling)
  • Removing OR relaxing a mandatory pattern (e.g., making next-safe-action optional)
  • Changing tech stack (e.g., migrating from Prisma to Drizzle)
  • Updating architectural boundaries (e.g., adding new layer)
  • Deprecating rules that are no longer valid
  • Major library version changes with breaking patterns (e.g., Next.js 15 → 16)

CRITICAL: Removing or relaxing a mandatory pattern ALWAYS requires a new version, even if existing code would still work. "Non-breaking" is not sufficient - any change to mandatory patterns needs versioning for audit trail.

Do NOT use for:

  • Fixing typos or clarifying existing rules (edit current version directly)
  • Adding examples to existing patterns (edit current version directly)
  • Project-specific implementation details (those go in specs/)

Test for Constitutionality:

Before adding content to constitution, ask: "If we violate this rule, does the architecture break?"

  • ✅ Constitutional: "Must use next-safe-action" → violating breaks type safety & validation
  • ❌ Not constitutional: "Forms should have wrapper, fields, button" → violating just looks different

Constitution = Architectural rules. Specs = Implementation patterns.

Process

Step 1: Determine Version Number

Read docs/constitutions/current/meta.md to get current version.

Version increment rules:

  • Increment by 1 (v1 → v2, v2 → v3)
  • No semantic versioning (major.minor.patch)
  • Sequential only

Step 2: Create New Version Directory

# Create new version directory
mkdir -p docs/constitutions/v{N}

# Copy structure from current
cp docs/constitutions/current/*.md docs/constitutions/v{N}/

Step 3: Update Content

Edit files in new version directory with changes:

  • meta.md - Update version number, date, changelog
  • architecture.md - Update if architectural boundaries changed
  • patterns.md - Update if mandatory patterns changed
  • tech-stack.md - Update if libraries added/removed
  • schema-rules.md - Update if database philosophy changed
  • testing.md - Update if testing requirements changed

Critical - Minimal Changes Only:

  • Only change what NEEDS changing for this version
  • NO reorganizing sections ("while I'm here")
  • NO reformatting code examples
  • NO alphabetizing lists
  • NO renaming headings for style
  • NO creating new categories unless absolutely required

The diff should show ONLY the substantive change, not stylistic improvements.

Step 4: Update Symlink

# Remove old symlink
rm docs/constitutions/current

# Create new symlink pointing to new version
ln -s v{N} docs/constitutions/current

Step 5: Verify References

Check that all references still work:

# Find all references to constitutions
grep -r "@docs/constitutions/current" .claude/
grep -r "docs/constitutions/current" .claude/

All references should use current/ symlink, never hardcoded versions.

Step 6: Document in meta.md

MANDATORY: Update meta.md with complete documentation:

  • New version number (e.g., "Version: 2")
  • Creation date (e.g., "Created: 2025-01-17")
  • Previous version reference (e.g., "Previous: v1")
  • Summary of WHAT changed (e.g., "Removed Redux prohibition")
  • Rationale for WHY (e.g., "React Server Components handle all state needs, Redux adds complexity without benefit")

The WHY is critical. In 6 months, the context will be lost. Document:

  • What problem does this change solve?
  • What decision or discussion led to this?
  • Why now vs earlier/later?

DO NOT rely on git commit messages or external docs. meta.md must be self-contained.

Quality Checklist

Before updating symlink:

  • New version directory exists at docs/constitutions/v{N}/
  • All 6 files present (meta, architecture, patterns, tech-stack, schema-rules, testing)
  • meta.md has correct version number and changelog
  • Changes documented with rationale (why, not just what)
  • Old version remains untouched (immutable)
  • References in commands use current/ not v{N}/

Common Mistakes

Mistake 1: Editing Current Version for Breaking Changes

Wrong: Edit docs/constitutions/current/patterns.md directly when removing next-safe-action requirement

Right: Create v2, update patterns.md in v2, update symlink

Why: Breaking changes need versioning. Commands/specs may reference old patterns.

Mistake 2: Hardcoding Version in References

Wrong: @docs/constitutions/v2/architecture.md

Right: @docs/constitutions/current/architecture.md

Why: When v3 is created, all references break. Symlink abstracts version.

Mistake 3: Reorganizing for Style

Wrong: "Let me alphabetize sections and rename files while versioning"

Right: Only change content that needs substantive updates

Why: Gratuitous changes obscure what actually changed. Diff should show real changes.

Mistake 4: Forgetting to Update meta.md

Wrong: Copy files, update content, update symlink, done

Right: Update meta.md with version, date, and changelog

Why: Future you won't remember why version changed. Document the why.

Mistake 5: Versioning Implementation Details

Wrong: Create v2 because we changed button component structure

Right: Constitution = foundational rules only. Implementation goes in specs/

Why: Constitution is for patterns/architecture/stack, not implementation choices.

Mistake 6: Rationalizing In-Place Edits

Wrong: "This change is non-breaking, so I can edit v1 in-place per the meta.md guidance"

Right: Removing/relaxing ANY mandatory pattern requires versioning, even if "non-breaking"

Why: Audit trail matters more than technical breaking changes. Future readers need to know WHEN rules changed, not just that they did. Git history is not sufficient - constitution versions create explicit snapshots.

Quick Reference

# Check current version
cat docs/constitutions/current/meta.md

# Create new version
mkdir -p docs/constitutions/v{N}
cp docs/constitutions/current/*.md docs/constitutions/v{N}/

# Edit content
# Update meta.md, then other files as needed

# Update symlink
rm docs/constitutions/current
ln -s v{N} docs/constitutions/current

# Verify
ls -la docs/constitutions/current
grep -r "constitutions/v[0-9]" .claude/  # Should return nothing

Example: Adding New Pattern

Scenario: We're adopting effect-ts for error handling and deprecating throw/catch.

Step 1: Current version is v1 (read meta.md)

Step 2: Create v2

mkdir -p docs/constitutions/v2
cp docs/constitutions/current/*.md docs/constitutions/v2/

Step 3: Update content

  • meta.md: Version 2, date, "Added effect-ts error handling pattern"
  • patterns.md: Add new section on Effect error handling
  • tech-stack.md: Add effect-ts to approved libraries
  • Leave other files unchanged

Step 4: Update symlink

rm docs/constitutions/current
ln -s v2 docs/constitutions/current

Step 5: Verify references (should all use current/)

Step 6: meta.md documents why (type-safe error handling, eliminate throw)

Testing This Skill

See test-scenarios.md for pressure scenarios and RED-GREEN-REFACTOR tests.

Writing Specifications

Overview

A specification defines WHAT to build and WHY. It is NOT an implementation plan.

Core principle: Reference constitutions, link to docs, keep it lean. The /plan command handles task decomposition.

Spec = Requirements + Architecture Plan = Tasks + Dependencies

When to Use

Use this skill when:

  • Invoked from /spectacular:spec slash command
  • Creating a new feature specification from scratch
  • Need the complete spec workflow (Run ID, worktree, brainstorm, spec, validation)

Do NOT use for:

  • Implementation plans with task breakdown - Use /spectacular:plan instead
  • API documentation - Goes in code comments or separate docs
  • Runbooks or operational guides - Different document type

Announce: "I'm using the writing-specs skill to create a feature specification."

Workspace Detection

Before starting the spec workflow, detect the workspace mode:

# Detect workspace mode
REPO_COUNT=$(find . -maxdepth 2 -name ".git" -type d 2>/dev/null | wc -l | tr -d ' ')
if [ "$REPO_COUNT" -gt 1 ]; then
  echo "Multi-repo workspace detected ($REPO_COUNT repos)"
  WORKSPACE_MODE="multi-repo"
  WORKSPACE_ROOT=$(pwd)
  # List detected repos
  find . -maxdepth 2 -name ".git" -type d | xargs -I{} dirname {} | sed 's|^\./||'
else
  echo "Single-repo mode"
  WORKSPACE_MODE="single-repo"
fi

Single-repo mode (current behavior):

  • Specs stored in specs/{runId}-{feature}/spec.md at repo root
  • Worktree created at .worktrees/{runId}-main/
  • Constitution referenced from @docs/constitutions/current/

Multi-repo mode (new behavior):

  • Specs stored in ./specs/{runId}-{feature}/spec.md at WORKSPACE root
  • NO worktree created (specs live at workspace level, not inside any repo)
  • Each repo's constitution referenced separately

Constitution Adherence

All specifications MUST follow: @docs/constitutions/current/

  • architecture.md - Layer boundaries, project structure
  • patterns.md - Mandatory patterns (next-safe-action, ts-pattern, etc.)
  • schema-rules.md - Database design philosophy
  • tech-stack.md - Approved libraries and versions
  • testing.md - Testing requirements

The Process

Step 0: Generate Run ID

First action: Generate a unique run identifier for this spec.

# Generate 6-char hash from feature name + timestamp
TIMESTAMP=$(date +%s)
RUN_ID=$(echo "{feature-description}-$TIMESTAMP" | shasum -a 256 | head -c 6)
echo "RUN_ID: $RUN_ID"

CRITICAL: Execute this entire block as a single multi-line Bash tool call. The comment on the first line is REQUIRED - without it, command substitution $(...) causes parse errors.

Store for use in:

  • Spec directory name: specs/{run-id}-{feature-slug}/
  • Spec frontmatter metadata
  • Plan generation
  • Branch naming during execution

Announce: "Generated RUN_ID: {run-id} for tracking this spec run"

Step 0.5: Create Isolated Worktree

Announce: "Creating isolated worktree for this spec run..."

Multi-repo mode: Skip worktree creation. Specs live at workspace root, not inside any repo.

if [ "$WORKSPACE_MODE" = "multi-repo" ]; then
  echo "Multi-repo mode: Specs stored at workspace root, no worktree needed"
  mkdir -p specs/${RUN_ID}-${FEATURE_SLUG}
  # Skip to Step 1 (brainstorming)
fi

Single-repo mode: Continue with worktree creation as normal.

Create worktree for isolated development:

  1. Create branch using git-spice:

    • Use using-git-spice skill to create branch {runId}-main from current branch
    • Branch name format: {runId}-main (e.g., abc123-main)
  2. Create worktree:

    # Create worktree at .worktrees/{runId}-main/
    git worktree add .worktrees/${RUN_ID}-main ${RUN_ID}-main
    
  3. Error handling:

    • If worktree already exists: "Worktree {runId}-main already exists. Remove it first with git worktree remove .worktrees/{runId}-main or use a different feature name."
    • If worktree creation fails: Report the git error details and exit

Working directory context:

  • All subsequent file operations happen in .worktrees/{runId}-main/
  • Brainstorming and spec generation occur in the worktree context
  • Main repository working directory remains unchanged

Announce: "Worktree created at .worktrees/{runId}-main/ - all work will happen in isolation"

Step 0.6: Install Dependencies in Worktree

REQUIRED: Each worktree needs dependencies installed before work begins.

  1. Check CLAUDE.md for setup commands:

    Look for this pattern in the project's CLAUDE.md:

    ## Development Commands
    
    ### Setup
    
    - **install**: `bun install`
    - **postinstall**: `npx prisma generate`
    
  2. If setup commands found, run installation:

    # Navigate to worktree
    cd .worktrees/${RUN_ID}-main
    
    # Check if dependencies already installed (handles resume)
    if [ ! -d node_modules ]; then
      echo "Installing dependencies..."
      {install-command}  # From CLAUDE.md (e.g., bun install)
    
      # Run postinstall if defined
      if [ -n "{postinstall-command}" ]; then
        echo "Running postinstall (codegen)..."
        {postinstall-command}  # From CLAUDE.md (e.g., npx prisma generate)
      fi
    else
      echo "Dependencies already installed"
    fi
    
  3. If setup commands NOT found in CLAUDE.md:

    Error and instruct user:

    Setup Commands Required
    
    Worktrees need dependencies installed to run quality checks and codegen.
    
    Please add to your project's CLAUDE.md:
    
    ## Development Commands
    
    ### Setup
    
    - **install**: `bun install` (or npm install, pnpm install, etc.)
    - **postinstall**: `npx prisma generate` (optional - for codegen)
    
    Then re-run: /spectacular:spec {feature-description}
    

Announce: "Dependencies installed in worktree - ready for spec generation"

Step 1: Brainstorm Requirements

Context: All brainstorming happens in the context of the worktree (.worktrees/{runId}-main/)

Announce: "I'm brainstorming the design using Phases 1-3 (Understanding, Exploration, Design Presentation)."

Create TodoWrite checklist:

Brainstorming for Spec:
- [ ] Phase 1: Understanding (purpose, constraints, criteria)
- [ ] Phase 2: Exploration (2-3 approaches proposed)
- [ ] Phase 3: Design Presentation (design validated)
- [ ] Proceed to Step 2: Generate Specification
Phase 1: Understanding

Goal: Clarify scope, constraints, and success criteria.

  1. Check current project state in working directory (note: we're in the worktree)
  2. Read @docs/constitutions/current/ to understand constraints:
    • architecture.md - Layer boundaries
    • patterns.md - Mandatory patterns
    • tech-stack.md - Approved libraries
    • schema-rules.md - Database rules
  3. Ask ONE question at a time to refine the idea
  4. Use AskUserQuestion tool for multiple choice options
  5. Gather: Purpose, constraints, success criteria

Constitution compliance:

  • All architectural decisions must follow @docs/constitutions/current/architecture.md
  • All pattern choices must follow @docs/constitutions/current/patterns.md
  • All library selections must follow @docs/constitutions/current/tech-stack.md
Phase 2: Exploration

Goal: Propose and evaluate 2-3 architectural approaches.

  1. Propose 2-3 different approaches that follow constitutional constraints
  2. For each approach explain:
    • Core architecture (layers, patterns)
    • Trade-offs (complexity vs features)
    • Constitution compliance (which patterns used)
  3. Use AskUserQuestion tool to present approaches as structured choices
  4. Ask partner which approach resonates
Phase 3: Design Presentation

Goal: Present detailed design incrementally and validate.

  1. Present design in 200-300 word sections
  2. Cover: Architecture, components, data flow, error handling, testing
  3. After each section ask: "Does this look right so far?" (open-ended)
  4. Use open-ended questions for freeform feedback
  5. Adjust design based on feedback

After Phase 3: Mark TodoWrite complete and proceed immediately to Step 2.

Step 2: Generate Specification

Announce: "Generating the specification document..."

Task:

  • Feature: {feature-description}
  • Design context: {summary from brainstorming}
  • RUN_ID: {run-id from Step 0}
  • Output location: .worktrees/{run-id}-main/specs/{run-id}-{feature-slug}/spec.md
  • Constitution: All design decisions must follow @docs/constitutions/current/
  • Analyze codebase for task-specific context:
    • Existing files to modify
    • New files to create (with exact paths per @docs/constitutions/current/architecture.md)
    • Dependencies needed (must be in @docs/constitutions/current/tech-stack.md)
    • Schema changes required (following @docs/constitutions/current/schema-rules.md)
  • Follow all Iron Laws (see below):
    • Reference constitutions, don't duplicate
    • Link to SDK docs, don't embed examples
    • No implementation plans (that's /spectacular:plan's job)
    • Keep it lean (<300 lines)

Spec frontmatter must include:

---
runId: {run-id}
feature: {feature-slug}
created: {date}
status: draft
---

Use the Spec Structure template below to generate the document.

Step 2.5: Commit Spec to Worktree

After spec generation completes, commit the spec to the worktree branch:

cd .worktrees/${RUN_ID}-main
git add specs/
git commit -m "spec: add ${feature-slug} specification [${RUN_ID}]"

Announce: "Spec committed to {runId}-main branch in worktree"

Step 3: Architecture Quality Validation

CRITICAL: Before reporting completion, validate the spec against architecture quality standards.

Announce: "Validating spec against architecture quality standards..."

Read the generated spec and check against these dimensions:

3.1 Constitution Compliance
  • Architecture: All components follow layer boundaries (@docs/constitutions/current/architecture.md)
    • Models - Services - Actions - UI (no layer violations)
    • Server/Client component boundaries respected
  • Patterns: All mandatory patterns referenced (@docs/constitutions/current/patterns.md)
    • next-safe-action for server actions
    • ts-pattern for discriminated unions
    • Zod schemas for validation
    • routes.ts for navigation
  • Schema: Database design follows rules (@docs/constitutions/current/schema-rules.md)
    • Proper indexing strategy
    • Naming conventions
    • Relationship patterns
  • Tech Stack: All dependencies approved (@docs/constitutions/current/tech-stack.md)
    • No unapproved libraries
    • Correct versions specified
  • Testing: Testing strategy defined (@docs/constitutions/current/testing.md)
3.2 Specification Quality (Iron Laws)
  • No Duplication: Constitution rules referenced, not recreated
  • No Code Examples: External docs linked, not embedded
  • No Implementation Plans: Focus on WHAT/WHY, not HOW/WHEN
  • Lean: Spec < 300 lines (if longer, likely duplicating constitutions)
3.3 Requirements Quality
  • Completeness: All FRs and NFRs defined, no missing scenarios
  • Clarity: All requirements unambiguous and specific (no "fast", "good", "better")
  • Measurability: All requirements have testable acceptance criteria
  • Consistency: No conflicts between sections
  • Edge Cases: Boundary conditions and error handling addressed
  • Dependencies: External dependencies and assumptions documented
3.4 Architecture Traceability
  • File Paths: All new/modified files have exact paths per architecture.md
  • Integration Points: How feature integrates with existing system clear
  • Migration Impact: Schema changes and data migrations identified
  • Security: Auth/authz requirements explicit
3.5 Surface Issues

If ANY checks fail, create .worktrees/{run-id}-main/specs/{run-id}-{feature-slug}/clarifications.md with:

# Clarifications Needed

## [Category: Constitution/Quality/Requirements/Architecture]

**Issue**: {What's wrong}
**Location**: {Spec section reference}
**Severity**: [BLOCKER/CRITICAL/MINOR]
**Question**: {What needs to be resolved}

Options:
- A: {Option with trade-offs}
- B: {Option with trade-offs}
- Custom: {User provides alternative}

Iteration limit: Maximum 3 validation cycles. If issues remain after 3 iterations, escalate to user with clarifications.md.

Step 4: Report Completion

IMPORTANT: After reporting completion, STOP HERE. Do not proceed to plan generation automatically. The user must review the spec and explicitly run /spectacular:plan when ready.

After validation passes OR clarifications documented, report to user:

If validation passed (single-repo mode):

Feature Specification Complete & Validated

RUN_ID: {run-id}
Worktree: .worktrees/{run-id}-main/
Branch: {run-id}-main
Location: .worktrees/{run-id}-main/specs/{run-id}-{feature-slug}/spec.md

Constitution Compliance: PASS
Architecture Quality: PASS
Requirements Quality: PASS

Note: Spec is in isolated worktree, main repo unchanged.

Next Steps (User Actions - DO NOT AUTO-EXECUTE):
1. Review the spec: .worktrees/{run-id}-main/specs/{run-id}-{feature-slug}/spec.md
2. When ready, create implementation plan: /spectacular:plan @.worktrees/{run-id}-main/specs/{run-id}-{feature-slug}/spec.md

If validation passed (multi-repo mode):

Feature Specification Complete & Validated

RUN_ID: {run-id}
Workspace: {workspace-root}
Location: specs/{run-id}-{feature-slug}/spec.md

Repos affected:
- backend: @backend/docs/constitutions/current/
- frontend: @frontend/docs/constitutions/current/

Constitution Compliance: PASS
Architecture Quality: PASS
Requirements Quality: PASS

Note: Spec is at workspace root, affecting multiple repos.

Next Steps (User Actions - DO NOT AUTO-EXECUTE):
1. Review the spec: specs/{run-id}-{feature-slug}/spec.md
2. When ready, create plan: /spectacular:plan @specs/{run-id}-{feature-slug}/spec.md

If clarifications needed (single-repo mode):

Feature Specification Complete - Clarifications Needed

RUN_ID: {run-id}
Worktree: .worktrees/{run-id}-main/
Branch: {run-id}-main
Location: .worktrees/{run-id}-main/specs/{run-id}-{feature-slug}/spec.md
Clarifications: .worktrees/{run-id}-main/specs/{run-id}-{feature-slug}/clarifications.md

Note: Spec is in isolated worktree, main repo unchanged.

Next Steps:
1. Review spec: .worktrees/{run-id}-main/specs/{run-id}-{feature-slug}/spec.md
2. Answer clarifications: .worktrees/{run-id}-main/specs/{run-id}-{feature-slug}/clarifications.md
3. Once resolved, re-run: /spectacular:spec {feature-description}

If clarifications needed (multi-repo mode):

Feature Specification Complete - Clarifications Needed

RUN_ID: {run-id}
Workspace: {workspace-root}
Location: specs/{run-id}-{feature-slug}/spec.md
Clarifications: specs/{run-id}-{feature-slug}/clarifications.md

Repos affected:
- backend: @backend/docs/constitutions/current/
- frontend: @frontend/docs/constitutions/current/

Note: Spec is at workspace root, affecting multiple repos.

Next Steps:
1. Review spec: specs/{run-id}-{feature-slug}/spec.md
2. Answer clarifications: specs/{run-id}-{feature-slug}/clarifications.md
3. Once resolved, re-run: /spectacular:spec {feature-description}

Spec Structure

# Feature: {Feature Name}

**Status**: Draft
**Created**: {date}

## Problem Statement

**Current State:**
{What exists today and what's missing/broken}

**Desired State:**
{What we want to achieve}

**Gap:**
{Specific problem this feature solves}

## Requirements

> **Note**: All features must follow @docs/constitutions/current/

### Functional Requirements
- FR1: {specific requirement}
- FR2: {specific requirement}

### Non-Functional Requirements
- NFR1: {performance/security/DX requirement}
- NFR2: {performance/security/DX requirement}

## Architecture

> **Layer boundaries**: @docs/constitutions/current/architecture.md
> **Required patterns**: @docs/constitutions/current/patterns.md

### Components

**New Files:**
- `src/lib/models/{name}.ts` - {purpose}
- `src/lib/services/{name}-service.ts` - {purpose}
- `src/lib/actions/{name}-actions.ts` - {purpose}

**Modified Files:**
- `{path}` - {what changes}

### Dependencies

**New packages:**
- `{package}` - {purpose}
- See: {link to official docs}

**Schema changes:**
- {migration name} - {purpose}
- Rules: @docs/constitutions/current/schema-rules.md

### Integration Points

- Auth: Uses existing Auth.js setup
- Database: Prisma client per @docs/constitutions/current/tech-stack.md
- Validation: Zod schemas per @docs/constitutions/current/patterns.md

## Acceptance Criteria

**Constitution compliance:**
- [ ] All patterns followed (@docs/constitutions/current/patterns.md)
- [ ] Architecture boundaries respected (@docs/constitutions/current/architecture.md)
- [ ] Testing requirements met (@docs/constitutions/current/testing.md)

**Feature-specific:**
- [ ] {criterion for this feature}
- [ ] {criterion for this feature}
- [ ] {criterion for this feature}

**Verification:**
- [ ] All tests pass
- [ ] Linting passes
- [ ] Feature works end-to-end

## Open Questions

{List any unresolved questions or decisions needed}

## References

- Architecture: @docs/constitutions/current/architecture.md
- Patterns: @docs/constitutions/current/patterns.md
- Schema Rules: @docs/constitutions/current/schema-rules.md
- Tech Stack: @docs/constitutions/current/tech-stack.md
- Testing: @docs/constitutions/current/testing.md
- {External SDK}: {link to official docs}

Multi-Repo Spec Template Addition

For multi-repo features, add this section to the spec:

## Constitutions

This feature must comply with constitutions from each affected repo:

**backend**: @backend/docs/constitutions/current/
- architecture.md - Backend layer boundaries
- patterns.md - Backend patterns (next-safe-action, etc.)
- schema-rules.md - Database design rules

**frontend**: @frontend/docs/constitutions/current/
- architecture.md - Frontend component structure
- patterns.md - Frontend patterns (React Query, etc.)

**shared-lib**: @shared-lib/docs/constitutions/current/
- (if applicable)

When brainstorming in multi-repo mode:

  • Read constitutions from ALL relevant repos
  • Note which repo each architectural decision applies to
  • Ensure cross-repo consistency (e.g., API contracts)

Iron Laws

1. Reference, Don't Duplicate

NEVER recreate constitution rules in the spec

```markdown ## Layered Architecture

The architecture has three layers:

  • Models: Data access with Prisma
  • Services: Business logic
  • Actions: Input validation with Zod
</Bad>

<Good>
```markdown
## Architecture

> **Layer boundaries**: @docs/constitutions/current/architecture.md

Components follow the established 3-layer pattern.

2. Link to Docs, Don't Embed Examples

NEVER include code examples from external libraries

```markdown ### Zod Validation
import { z } from 'zod';

export const schema = z.object({
  name: z.string().min(3),
  email: z.string().email()
});
</Bad>

<Good>
```markdown
### Validation

Use Zod schemas per @docs/constitutions/current/patterns.md

See: https://zod.dev for object schema syntax

3. No Implementation Plans

NEVER include task breakdown or migration phases

```markdown ## Migration Plan

Phase 1: Database Schema

  1. Create Prisma migration
  2. Run migration
  3. Verify indexes

Phase 2: Backend Implementation

...

</Bad>

<Good>
```markdown
## Dependencies

**Schema changes:**
- Migration: `init_rooms` - Add Room, RoomParticipant, WaitingListEntry models

Implementation order determined by `/plan` command.

4. No Success Metrics

NEVER include adoption metrics, performance targets, or measurement strategies

```markdown ## Success Metrics
  1. Adoption: 80% of users use feature within first month
  2. Performance: Page loads in <500ms
  3. Engagement: <5% churn rate
</Bad>

<Good>
```markdown
## Non-Functional Requirements

- NFR1: Page load performance <500ms (measured per @docs/constitutions/current/testing.md)
- NFR2: Support 1000 concurrent users

Common Mistakes

MistakeWhy It's WrongFix
Including full Prisma schemasDuplicates what goes in codeList model names + purposes, reference schema-rules.md
Writing test code examplesShows HOW not WHATList what to test, reference testing.md for how
Explaining ts-pattern syntaxAlready in patterns.mdReference patterns.md, list where pattern applies
Creating /notes subdirectoryViolates single-file principleKeep spec lean, remove supporting docs
Adding timeline estimatesThat's project managementFocus on requirements and architecture

Rationalization Table

ExcuseReality
"Thorough means showing complete code"Thorough = complete requirements. Code = implementation.
"Spec needs examples so people understand"Link to docs. Don't copy-paste library examples.
"Migration plan shows full picture"/plan command handles decomposition. Spec = WHAT not HOW.
"Include constitutions for context"Constitutions exist to avoid duplication. Reference, don't recreate.
"Testing code shows approach"testing.md shows approach. Spec lists WHAT to test.
"Metrics demonstrate value"NFRs show requirements. Metrics = measurement strategy (different doc).
"More detail = more helpful"More detail = harder to maintain. Lean + links = durable.

Red Flags - STOP and Fix

Seeing any of these? Delete and reference instead:

  • Full code examples from libraries (Zod, Prisma, Socket.io, etc.)
  • Migration phases or implementation steps
  • Success metrics or adoption targets
  • Recreated architecture explanations
  • Test implementation code
  • Files in specs/{run-id}-{feature-slug}/notes/ directory
  • Spec > 300 lines (probably duplicating constitutions)

All of these mean: Too much implementation detail. Focus on WHAT not HOW.

Quality Checklist

Before finalizing spec:

  • Problem statement shows current - desired state gap
  • All FRs and NFRs are testable/verifiable
  • Architecture section lists files (not code examples)
  • All constitution rules referenced (not recreated)
  • All external libraries linked to docs (not copied)
  • No implementation plan (saved for /spectacular:plan)
  • No success metrics or timelines
  • Single file at specs/{run-id}-{feature-slug}/spec.md
  • Spec < 300 lines (if longer, check for duplication)

Error Handling

Worktree Creation Fails

  • Check .worktrees/ is in .gitignore
  • Run git worktree prune to clean stale entries
  • Verify working directory is clean

Git-Spice Errors

  • Run gs repo init to initialize repository
  • Check gs ls to view current stack
  • See using-git-spice skill for troubleshooting

Setup Commands Missing

  • Project MUST define setup commands in CLAUDE.md
  • See error message for required format
  • Re-run spec command after adding commands

Validation Failures

  • Maximum 3 iteration cycles
  • If issues persist, escalate via clarifications.md
  • Do not skip validation - it catches real problems

The Bottom Line

Specs define WHAT and WHY. Plans define HOW and WHEN.

Reference heavily. Link to docs. Keep it lean.

If you're copy-pasting code or recreating rules, you're writing the wrong document.

Commands 5

Spectacular Commands

Spec-anchored development workflow with automatic sequential/parallel orchestration using superpowers skills and git-spice.

Workflow

Initialize → Specify → Plan → Execute

# 0. First time? Initialize your environment
/spectacular:init

# 1. Generate comprehensive spec from requirements (generates runId: a1b2c3)
/spectacular:spec "magic link authentication with Auth.js"

# 2. Decompose into execution plan with automatic phase analysis
/spectacular:plan @specs/a1b2c3-magic-link-auth/spec.md

# 3. Execute with automatic sequential/parallel orchestration
/spectacular:execute @specs/a1b2c3-magic-link-auth/plan.md

Key Innovation: Automatic parallelization based on file dependency analysis. You don't choose - Claude analyzes and orchestrates.


Commands

/spectacular:init

Purpose: Initialize spectacular environment and validate dependencies.

Checks:

  • Superpowers plugin installed
  • Git-spice installed and configured
  • Gitignore configured for .worktrees/
  • Git repository initialized
  • Project structure (specs/ directory)

Actions:

  • Installs missing .gitignore entries
  • Creates specs/ directory if needed
  • Reports missing dependencies with install instructions

Example:

/spectacular:init

First-time setup:

✅ Environment ready for spectacular workflows!

Next steps:
  1. Generate a spec: /spectacular:spec "your feature description"
  2. Create a plan: /spectacular:plan @specs/{run-id}-{feature-slug}/spec.md
  3. Execute: /spectacular:execute @specs/{run-id}-{feature-slug}/plan.md

/spectacular:spec {description}

Purpose: Generate a complete feature specification from a brief description.

Uses:

  • brainstorming skill to refine requirements
  • Task tool to analyze codebase context
  • Outputs comprehensive spec with task breakdown

Output: specs/{run-id}-{feature-slug}/spec.md

Example:

/spectacular:spec "user picks wizard with category navigation"
# Generates: specs/d4e5f6-user-picks-wizard/spec.md

What it generates:

  • Requirements (functional + non-functional)
  • Architecture (models, services, actions, UI)
  • Implementation tasks with file paths
  • Acceptance criteria per task
  • Mandatory pattern reminders (next-safe-action, ts-pattern)

/spectacular:plan {spec-path}

Purpose: Decompose spec into executable plan with automatic phase analysis.

Uses:

  • decomposing-tasks skill (custom spectacular skill)
  • Analyzes file dependencies between tasks
  • Groups into sequential/parallel phases
  • Validates task quality (no XL, explicit files, criteria)

Output: {spec-directory}/plan.md

Example:

/spectacular:plan @specs/a1b2c3-magic-link-auth/spec.md

What it generates:

  • Phase grouping with strategies (sequential/parallel)
  • Task dependencies based on file analysis
  • Execution time estimates with parallelization savings
  • Complete implementation details per task

Automatic decisions:

  • Sequential phase: Tasks share files or have dependencies
  • Parallel phase: Tasks are independent, can run simultaneously

Quality validation:

  • ❌ XL tasks (>8h) → Must split
  • ❌ Missing files → Must specify
  • ❌ Missing criteria → Must add 3-5
  • ❌ Wildcard patterns → Must be explicit

/spectacular:execute {plan-path}

Purpose: Execute plan with automatic sequential/parallel orchestration.

Uses:

  • executing-sequential-phase skill for sequential phase orchestration
  • executing-parallel-phase skill for parallel phase orchestration
  • phase-task-verification skill for shared branch creation/verification
  • Fresh subagent per task with code review gates
  • Git worktrees for parallel execution
  • finishing-a-development-branch skill for completion
  • Git-spice for branch management

Flow:

  1. Extract run ID from plan path
  2. For each phase:
    • Sequential: executing-sequential-phase orchestrates tasks in shared worktree
    • Parallel: executing-parallel-phase creates worktrees, spawns agents concurrently
  3. Complete with finishing-a-development-branch skill

Example:

/spectacular:execute @specs/a1b2c3-magic-link-auth/plan.md

Sequential phase execution:

Phase 1 (sequential):
  Task 1 → fresh subagent → code review → commit
  Task 2 → fresh subagent → code review → commit
  Task 3 → fresh subagent → code review → commit

Parallel phase execution:

Phase 2 (parallel):
  Worktree A: Task 4 → fresh subagent → code review → commit
  Worktree B: Task 5 → fresh subagent → code review → commit
  Worktree C: Task 6 → fresh subagent → code review → commit
  ↓
  Merge all → feature branch → cleanup worktrees

Quality Gates (every task):

  • Code review after each task
  • Biome linting
  • Tests pass
  • Frequent commits

Mandatory Patterns

All commands enforce these patterns from the constitution (see @docs/constitutions/current/patterns.md):

1. next-safe-action for ALL server actions

// ✅ REQUIRED
export const submitPickAction = authenticatedAction
  .schema(pickSchema)
  .action(async ({ parsedInput, ctx }) => {
    return pickService.submitPick(ctx.userId, parsedInput);
  });

// ❌ FORBIDDEN
export async function submitPick(data: unknown) {
  // Raw server action
}

2. ts-pattern for ALL discriminated unions

// ✅ REQUIRED
return match(event.status)
  .with("SETUP", () => false)
  .with("OPEN", () => true)
  .with("LIVE", () => false)
  .with("COMPLETED", () => false)
  .exhaustive(); // Compiler enforces completeness!

// ❌ FORBIDDEN
switch (event.status) {
  case "SETUP":
    return false;
  case "OPEN":
    return true;
  // Missing cases - no error!
}

3. Layer Boundaries

UI Components (src/components/)
    ↓ calls
Server Actions (src/lib/actions/) - next-safe-action only
    ↓ calls
Services (src/lib/services/) - business logic, no Prisma
    ↓ calls
Models (src/lib/models/) - Prisma only, no business logic

Rules:

  • ✅ Actions call services
  • ✅ Services call models
  • ✅ Models use Prisma
  • ❌ Services cannot import Prisma
  • ❌ Actions cannot call models directly

Tech Stack Reference

  • Framework: Next.js 15 (App Router + Turbopack)
  • Language: TypeScript (strict mode)
  • Database: Prisma + PostgreSQL
  • Auth: Auth.js v5 (magic links)
  • Real-time: Socket.io
  • Validation: Zod + next-safe-action
  • Pattern Matching: ts-pattern
  • Linting: Biome
  • VCS: Git + git-spice

Skills Used

Spectacular Skills

  • executing-sequential-phase - Orchestrates sequential phase execution with natural stacking
  • executing-parallel-phase - Orchestrates parallel phase execution with worktree isolation
  • phase-task-verification - Shared branch creation and verification logic
  • decomposing-tasks - Analyzes dependencies and groups into phases
  • writing-specs - Generates lean feature specifications
  • validating-setup-commands - Validates CLAUDE.md setup commands
  • understanding-cross-phase-stacking - Explains base branch inheritance
  • using-git-spice - Git-spice command reference and patterns
  • troubleshooting-execute - Error recovery for execution failures

Superpowers Skills

  • brainstorming - Refines requirements before spec generation
  • requesting-code-review - Dispatches code review after each phase
  • verification-before-completion - Evidence-based completion verification
  • finishing-a-development-branch - Completes work and chooses next action

Architecture: Orchestrator skills manage workflow lifecycle and dispatch Task tool with embedded execution instructions. Subagents receive focused ~150-line instructions (80% cognitive load reduction vs original 750-line monolithic skills).


Examples

Example 1: Single Feature (Sequential)

# Initialize (first time only)
/spectacular:init

# Generate spec
/spectacular:spec "leaderboard with real-time updates via Socket.io"

# Review: specs/a1b2c3-leaderboard/spec.md

# Generate plan with phase analysis
/spectacular:plan @specs/a1b2c3-leaderboard/spec.md

# Review: specs/a1b2c3-leaderboard/plan.md
# Plan shows: 3 phases, all sequential (tasks share files)

# Execute
/spectacular:execute @specs/a1b2c3-leaderboard/plan.md

# Result: Sequential execution, no parallelization

Example 2: Feature with Parallel Opportunities

# Generate spec
/spectacular:spec "user authentication with magic links"

# Generate plan
/spectacular:plan @specs/a1b2c3-auth/spec.md

# Review plan:
# - Phase 1 (sequential): Database + Models (share files)
# - Phase 2 (parallel): Magic link service + Email service (independent)
# - Phase 3 (sequential): Actions + UI (depend on Phase 2)

# Execute
/spectacular:execute @specs/a1b2c3-auth/plan.md

# Result:
# - Phase 1: Sequential execution
# - Phase 2: Parallel execution (significant time savings)
# - Phase 3: Sequential execution
# Overall: Faster than fully sequential execution

Example 3: Large Feature Auto-Decomposed

# Generate spec for complex feature
/spectacular:spec "admin category management with drag-reorder and live preview"

# Generate plan
/spectacular:plan @specs/a1b2c3-admin-categories/spec.md

# Plan auto-detects:
# - Phase 1 (sequential): 3 tasks - Database schema + models
# - Phase 2 (parallel): 4 tasks - Services (independent domains)
# - Phase 3 (sequential): 2 tasks - Admin actions
# - Phase 4 (parallel): 3 tasks - UI components (independent pages)
# - Phase 5 (sequential): 1 task - Integration + E2E tests
# Multiple parallel phases provide significant time savings

# Execute automatically orchestrates all phases
/spectacular:execute @specs/a1b2c3-admin-categories/plan.md

Troubleshooting

"Superpowers plugin not installed"

Cause: The superpowers plugin is required but not installed.

Fix:

/plugin install superpowers@superpowers-marketplace

Then restart Claude Code and run /spectacular:init again.

"Git-spice not installed"

Cause: Git-spice is required for stacked branch management.

Fix:

# macOS
brew install git-spice

# Linux
# See https://github.com/abhinav/git-spice for install instructions

Then run /spectacular:init again.

"Plan validation failed"

Cause: Spec has quality issues (XL tasks, missing files, missing criteria).

Fix:

  1. Review validation errors
  2. Update spec at the indicated locations
  3. Re-run /spectacular:plan @spec-path

"Parallel phase failed - one agent blocked"

Cause: One task in parallel phase hit an issue.

Fix:

  1. Other tasks already completed and merged
  2. Fix failing task in its worktree: cd {worktree-path}
  3. Debug and commit fix
  4. Merge manually: git merge {task-branch}
  5. Cleanup worktree: git worktree remove {path}

"Merge conflict in parallel phase"

Cause: Tasks marked as independent actually modified same files.

Fix:

  1. This indicates incorrect dependency analysis
  2. Resolve conflict manually
  3. Update plan to mark tasks as sequential
  4. Report issue so task-decomposition skill can be improved

"Tests failing after execution"

Cause: Implementation has bugs.

Fix: Code review runs after each phase, but bugs can slip through.

  1. Review test failures
  2. Use systematic-debugging skill to investigate
  3. Fix issues
  4. Commit fixes

Design Philosophy

Spec-Anchored Development:

  1. Comprehensive specs eliminate questions during implementation
  2. Mandatory patterns ensure consistency
  3. Layer boundaries prevent architectural drift
  4. Quality gates catch issues early

Automatic Orchestration:

  1. Dependency analysis determines sequential vs parallel
  2. No manual decision needed - Claude optimizes
  3. Worktrees provide true isolation for parallel work
  4. Git-spice manages branch stacking

Task-Level Autonomy:

  1. Fresh subagent per task (no context pollution)
  2. Code review after each task (catch issues early)
  3. Continuous commits (small, focused changes)
  4. Quality gates every step

Time Optimization:

  1. Automatic parallelization where safe
  2. Time savings scale with feature size and parallelization opportunities
  3. No coordination overhead (worktrees isolate)
  4. Transparent - see exactly what's parallel vs sequential

Performance Benefits

Without this workflow:

  • Manual dependency tracking
  • Conservative sequential execution
  • No automatic parallelization

With this workflow:

  • Automatic dependency analysis
  • Optimal parallel/sequential orchestration
  • Worktree isolation (no conflicts)
  • Time savings scale with feature complexity and number of independent tasks

Invoke the spectacular:executing-plan skill and follow it exactly as presented to you.

Invoke the spectacular:validating-environment skill and follow it exactly as presented to you.

Invoke the spectacular:decomposing-tasks skill and follow it exactly as presented to you.

Invoke the spectacular:writing-specs skill and follow it exactly as presented to you.

Sponsors

Details

Marketplace
arittr/spectacular
Author
Drew Ritter
Category
Community