Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 17:58:10 +08:00
commit 62e38f6386
28 changed files with 8679 additions and 0 deletions

481
commands/README.md Normal file
View File

@@ -0,0 +1,481 @@
# Spectacular Commands
Spec-anchored development workflow with automatic sequential/parallel orchestration using superpowers skills and git-spice.
## Workflow
### Initialize → Specify → Plan → Execute
```bash
# 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**:
```bash
/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**:
```bash
/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**:
```bash
/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**:
```bash
/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
```typescript
// ✅ 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
```typescript
// ✅ 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)
```bash
# 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
```bash
# 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
```bash
# 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**:
```bash
/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**:
```bash
# 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

504
commands/execute.md Normal file
View File

@@ -0,0 +1,504 @@
---
description: Execute implementation plan with automatic sequential/parallel orchestration using git-spice and worktrees
---
You are executing an implementation 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)
## 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.
## Workflow
### 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`
```bash
# 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
**After extracting RUN_ID, verify the worktree exists:**
```bash
# 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:**
```bash
# 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)
````
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:**
```bash
# 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:
**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):**
```bash
# 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:**
```
⚠️ 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
````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)
```bash
# 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)
```bash
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)
```bash
# 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}
```

338
commands/init.md Normal file
View File

@@ -0,0 +1,338 @@
---
description: Initialize spectacular environment - install dependencies, configure git, and validate setup
---
You are initializing the spectacular environment for spec-anchored development.
## Purpose
This command ensures all required dependencies and configuration are in place:
- Superpowers plugin installed
- Git-spice installed and configured
- Gitignore configured for spectacular workflows
- Project structure validated
## Workflow
### Step 1: Check Superpowers Plugin
Check if superpowers is installed:
```bash
if [ -d ~/.claude/plugins/cache/superpowers ]; then
echo "✅ Superpowers plugin is installed"
SUPERPOWERS_VERSION=$(cd ~/.claude/plugins/cache/superpowers && git describe --tags 2>/dev/null || echo "unknown")
echo " Version: $SUPERPOWERS_VERSION"
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:
```bash
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:
```bash
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:
```bash
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:
```bash
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: Report Summary
Generate final status report:
```bash
echo ""
echo "========================================="
echo "Spectacular Initialization Summary"
echo "========================================="
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 "========================================="
```
## What Gets Checked
### Required Dependencies
- ✅ Superpowers plugin (for core skills)
- ✅ Git-spice (for stacked branch management)
- ✅ Git repository (for version control)
### Configuration
- ✅ .gitignore configured (.worktrees/, specs/ handling)
- ✅ Git remote configured (optional but recommended)
- ✅ Git-spice initialized (optional but recommended)
### Project Structure
- ✅ specs/ directory created
- ✅ .worktrees/ directory status checked
- ✅ Working directory status
## Example Output
**Successful initialization:**
```
✅ Superpowers plugin is installed
Version: v3.2.1
✅ Git-spice is installed
git-spice version 0.5.0
✅ Git-spice is initialized for this repo
✅ .gitignore exists
✅ .worktrees/ already in .gitignore
✅ specs/ will be tracked (not in .gitignore)
✅ Git repository detected
Current branch: main
✅ Remote configured
origin git@github.com:user/repo.git (fetch)
origin git@github.com:user/repo.git (push)
✅ Working directory clean
✅ specs/ directory exists
Found 3 specification(s)
✅ No .worktrees/ directory (will be created during parallel execution)
=========================================
Spectacular Initialization Summary
=========================================
✅ 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
=========================================
```
**Missing dependencies:**
```
❌ Superpowers plugin NOT installed
Spectacular requires the superpowers plugin for core skills:
- brainstorming
- subagent-driven-development
- requesting-code-review
- verification-before-completion
- finishing-a-development-branch
Install with:
/plugin install superpowers@superpowers-marketplace
❌ Git-spice NOT installed
Spectacular uses git-spice for stacked branch management.
Install instructions:
macOS: brew install git-spice
Linux: See https://github.com/abhinav/git-spice
=========================================
Spectacular Initialization Summary
=========================================
❌ Setup incomplete - resolve issues above before using spectacular
REQUIRED: Install superpowers plugin
/plugin install superpowers@superpowers-marketplace
REQUIRED: Install git-spice
macOS: brew install git-spice
Linux: https://github.com/abhinav/git-spice
Run /spectacular:init again after resolving issues
=========================================
```
Now run the initialization check.

365
commands/plan.md Normal file
View File

@@ -0,0 +1,365 @@
---
description: Decompose feature spec into executable plan with automatic phase analysis and sequential/parallel strategy
---
You are creating an execution plan from a feature specification.
## 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.
## 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.
```bash
# 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):
```bash
# 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`.
```bash
# 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:
```markdown
❌ 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 using the Task Decomposition skill to create an execution plan."
Use the `decomposing-tasks` skill to analyze the spec and generate a plan.
**The skill 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:
```bash
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:
````markdown
✅ 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
```
````
## Error Handling
### Missing Worktree
If the worktree doesn't exist when trying to switch context:
```markdown
❌ 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:
```markdown
❌ 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:
````markdown
❌ Cannot Generate Plan - No Tasks Found
The spec at {spec-path} doesn't have an "Implementation Plan" section with tasks.
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
````
## 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/
Now generate the plan from: {spec-path}

347
commands/spec.md Normal file
View File

@@ -0,0 +1,347 @@
---
description: Generate a lean feature specification using brainstorming and the writing-specs skill
---
You are creating a feature specification.
## 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
## Input
User will provide: `/spectacular:spec {feature-description}`
Example: `/spectacular:spec magic link authentication with Auth.js`
## Workflow
### Step 0: Generate Run ID
**First action**: Generate a unique run identifier for this spec.
```bash
# 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..."
**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**:
```bash
# 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.5: 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:
```markdown
## Development Commands
### Setup
- **install**: `bun install`
- **postinstall**: `npx prisma generate`
```
2. **If setup commands found, run installation**:
```bash
# 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**:
```markdown
❌ 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:** "I'm using the Writing Specs skill to create the specification."
Use the `writing-specs` skill to generate the spec document.
**Task for writing-specs skill:**
- 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:
- 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:**
```yaml
---
runId: {run-id}
feature: {feature-slug}
created: {date}
status: draft
---
```
### Step 2.5: Commit Spec to Worktree
**After spec generation completes, commit the spec to the worktree branch:**
```bash
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:
```markdown
# 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:**
```
✅ 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: ✓
Architecture Quality: ✓
Requirements Quality: ✓
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 clarifications needed:**
```
⚠️ 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}
```
Now generate the specification for: {feature-description}