Version Note: The version number (16.0.0) tracks the skill's evolution including documentation, templates, scripts, and MCP server. All package.json files are aligned to this version.
Spec Kit - Mandatory Conversation Documentation
Orchestrates mandatory spec folder creation for all conversations involving file modifications. Ensures proper documentation level selection (1-3), template usage, and context preservation through AGENTS.md-enforced workflows.
1. 🎯 WHEN TO USE
What is a Spec Folder?
A spec folder is a numbered directory (e.g., specs/007-auth-feature/) that contains all documentation for a single feature or task:
- Purpose: Track specifications, plans, tasks, and decisions for one unit of work
- Location: Always under
specs/ directory with format ###-short-name/
- Contents: Markdown files (spec.md, plan.md, tasks.md) plus optional memory/ and scratch/ subdirectories
Think of it as a "project folder" for AI-assisted development - it keeps context organized and enables session continuity.
Activation Triggers
MANDATORY for ALL file modifications:
- Code files: JS, TS, Python, CSS, HTML
- Documentation: Markdown, README, guides
- Configuration: JSON, YAML, TOML, env templates
- Templates, knowledge base, build/tooling files
Request patterns that trigger activation:
- "Add/implement/create [feature]"
- "Fix/update/refactor [code]"
- "Modify/change [configuration]"
- Any keyword: add, implement, fix, update, create, modify, rename, delete, configure, analyze
Example triggers:
- "Add email validation to the signup form" → Level 1-2
- "Refactor the authentication module" → Level 2-3
- "Fix the button alignment bug" → Level 1
- "Implement user dashboard with analytics" → Level 3
When NOT to Use
- Pure exploration/reading (no file modifications)
- Single typo fixes (<5 characters in one file)
- Whitespace-only changes
- Auto-generated file updates (package-lock.json)
- User explicitly selects Option D (skip documentation)
Rule of thumb: If modifying ANY file content → Activate this skill.
Utility Template Triggers
| Template |
Trigger Keywords |
Action |
handover.md |
"handover", "next session", "continue later", "pass context", "ending session", "save state", "multi-session", "for next AI" |
Suggest creating handover |
debug-delegation.md |
"stuck", "can't fix", "tried everything", "same error", "fresh eyes", "hours on this", "still failing", "need help debugging" |
Suggest /spec_kit:debug |
Rule: When detected, proactively suggest the appropriate action.
2. 🧭 SMART ROUTING
Activation Detection
User Request
│
├─► Contains "spec", "plan", "document", "checklist"?
│ └─► YES → Activate SpecKit (spec folder workflow)
│
├─► File modification requested?
│ └─► Gate 3 triggered → Ask spec folder question
│
├─► Contains "debug", "stuck", "help"?
│ └─► Route to /spec_kit:debug
│
├─► Contains "continue", "resume", "pick up"?
│ └─► Route to /spec_kit:resume
│
├─► Contains "save context", "save memory", "/memory:save"?
│ └─► Execute generate-context.js → Index to Spec Kit Memory
│
├─► Contains "search memory", "find context", "what did we"?
│ └─► Use memory_search({ query: "..." }) MCP tool (query OR concepts required)
│
├─► Contains "checkpoint", "save state", "restore"?
│ └─► Use checkpoint_create/restore MCP tools
│
└─► Gate enforcement triggered (file modification)?
└─► Constitutional memories auto-surface via memory_match_triggers()
Memory System Triggers
Note: Tool names use the full spec_kit_memory_* prefix as required by OpenCode MCP integration.
| Trigger Pattern |
Action |
MCP Tool |
"save context", "save memory", /memory:save |
Generate + index memory file |
spec_kit_memory_memory_save() |
| "search memory", "find prior", "what did we decide" |
Semantic search across sessions |
spec_kit_memory_memory_search({ query: "..." }) (query OR concepts required) |
| "list memories", "show context" |
Browse stored memories |
spec_kit_memory_memory_list() |
| "checkpoint", "save state" |
Create named checkpoint |
spec_kit_memory_checkpoint_create() |
| "restore checkpoint", "rollback" |
Restore from checkpoint |
spec_kit_memory_checkpoint_restore() |
| Gate enforcement (any file modification) |
Auto-surface constitutional rules |
spec_kit_memory_memory_match_triggers() |
Resource Router
Phase-Based Loading:
| Phase |
Trigger |
Load Resources |
Execute |
| Planning |
New feature, "plan", "design" |
level_specifications.md, template_guide.md |
/spec_kit:plan |
| Research |
"investigate", "explore", "analyze" |
quick_reference.md, worked_examples.md |
/spec_kit:research |
| Implementation |
"implement", "build", "code" |
validation_rules.md, template_guide.md |
/spec_kit:implement |
| Debugging |
"stuck", "error", "not working" |
quick_reference.md, troubleshooting.md |
/spec_kit:debug |
| Completion |
"done", "finished", "complete" |
validation_rules.md, phase_checklists.md |
/spec_kit:complete |
| Handover |
"stopping", "break", "continue later" |
quick_reference.md |
/spec_kit:handover |
| Resume |
"continue", "pick up", "resume" |
quick_reference.md |
/spec_kit:resume |
Reference Sub-folders
| Sub-folder |
Purpose |
Files |
memory/ |
Context preservation, MCP tools |
memory_system.md, save_workflow.md, trigger_config.md |
templates/ |
Template system, level specs |
level_specifications.md, template_guide.md, template_style_guide.md |
validation/ |
Validation rules, checklists |
validation_rules.md, phase_checklists.md, path_scoped_rules.md |
structure/ |
Folder organization, routing |
folder_structure.md, folder_routing.md, sub_folder_versioning.md |
workflows/ |
Usage workflows, examples |
quick_reference.md, execution_methods.md, worked_examples.md |
debugging/ |
Troubleshooting, debugging |
troubleshooting.md, universal_debugging_methodology.md |
config/ |
Configuration |
environment_variables.md |
Keyword-Based Routing
| Keywords |
Route To |
| "memory", "save context", "MCP", "trigger" |
references/memory/ |
| "embeddings", "vector", "semantic", "decay" |
references/memory/ |
| "anchor", "snapshot" |
references/memory/ |
| "template", "level 1/2/3", "spec.md format" |
references/templates/ |
| "validate", "rules", "checklist", "P0/P1/P2" |
references/validation/ |
| "folder", "naming", "structure", "versioning" |
references/structure/ |
| "workflow", "example", "commands", "quick" |
references/workflows/ |
| "debug", "error", "stuck", "troubleshoot" |
references/debugging/ |
| "env", "environment", "configuration" |
references/config/ |
| "scripts", "generate-context", "check-completion" |
scripts/ |
Resource Inventory
Templates by Level (templates/):
| Level |
Required Files |
Optional |
| 1 |
spec.md, plan.md, tasks.md, implementation-summary.md |
— |
| 2 |
Level 1 + checklist.md |
— |
| 3 |
Level 2 + decision-record.md |
research.md |
| Any |
— |
handover.md, debug-delegation.md |
Internal Templates:
context_template.md - Internal template for memory file generation (Mustache format)
Auto-Generated Folders:
memory/ - Session context (via generate-context.js)
scratch/ - Temporary workspace (manual creation)
Key Scripts:
| Script |
Purpose |
generate-context.js |
Generate memory files from conversation (modular: 44 modules in 10 dirs) |
validate-spec.sh |
Validate spec folder structure |
create-spec-folder.sh |
Create new spec folders with templates |
check-completion.sh |
Verify checklist completion status |
recommend-level.sh |
Suggest documentation level based on LOC |
archive-spec.sh |
Archive completed spec folders |
cleanup-orphaned-vectors.js |
Removes orphaned vector entries |
check-prerequisites.sh |
Checks prerequisites before implementation |
common.sh |
Shared shell utilities |
setup.sh |
Initial setup script |
calculate-completeness.sh |
Calculates spec completeness percentage |
package.json |
Node.js dependencies |
README.md |
Scripts documentation |
tests/test-validation.sh |
Validation test runner |
tests/test-embeddings-factory.js |
Test embedding provider configuration |
tests/test-bug-fixes.js |
Bug fix regression tests |
References (references/):
| Sub-folder |
File |
Purpose |
When to Load |
memory/ |
memory_system.md |
MCP tool behavior and config |
Memory operations |
memory/ |
save_workflow.md |
Memory save workflow docs |
Context preservation |
memory/ |
trigger_config.md |
Trigger phrase configuration |
Setup |
templates/ |
level_specifications.md |
Complete Level 1-3 requirements |
Planning |
templates/ |
template_guide.md |
Template selection and usage |
Planning, Implementation |
templates/ |
template_style_guide.md |
Template formatting conventions |
Documentation |
validation/ |
validation_rules.md |
All validation rules and fixes |
Implementation, Completion |
validation/ |
phase_checklists.md |
Per-phase validation |
Completion |
validation/ |
path_scoped_rules.md |
Path-scoped validation |
Advanced |
structure/ |
folder_structure.md |
Folder naming conventions |
Planning |
structure/ |
folder_routing.md |
Folder routing logic |
Planning |
structure/ |
sub_folder_versioning.md |
Sub-folder workflow |
Reusing spec folders |
workflows/ |
quick_reference.md |
Commands and checklists |
Any phase |
workflows/ |
execution_methods.md |
Script execution patterns |
Operations |
workflows/ |
worked_examples.md |
Real-world examples |
Learning |
debugging/ |
troubleshooting.md |
Common issues and solutions |
Debugging |
debugging/ |
universal_debugging_methodology.md |
Stack-agnostic 4-phase debugging |
Debugging |
config/ |
environment_variables.md |
Env var configuration |
Setup |
Assets (assets/):
| File |
Purpose |
level_decision_matrix.md |
LOC thresholds and complexity factors |
template_mapping.md |
Template-to-level mapping rules |
parallel_dispatch_config.md |
Agent dispatch configuration |
generate-context.js Input Modes:
| Mode |
Usage |
Description |
| Direct |
node generate-context.js specs/007-feature/ |
Auto-captures context from OpenCode session |
| JSON |
node generate-context.js /tmp/context-data.json |
Manual context injection via JSON file |
Architecture: The script uses a modular architecture (142-line CLI entry point + 44 modules across 10 directories: core/, extractors/, lib/, loaders/, renderers/, rules/, spec-folder/, test-fixtures/, tests/, utils/). See scripts/README.md for module details and extension points.
JSON mode documentation: See save_workflow.md for full schema and examples.
3. 🛠️ HOW IT WORKS
Gate 3 Integration
See AGENTS.md Section 2 for the complete Gate 3 flow. This skill implements that gate.
When file modification detected, AI MUST ask:
**Spec Folder** (required): A) Existing | B) New | C) Update related | D) Skip
| Option |
Description |
Best For |
| A) Existing |
Continue in related spec folder |
Iterative work, related changes |
| B) New |
Create specs/###-name/ |
New features, unrelated work |
| C) Update |
Add to existing documentation |
Extending existing docs |
| D) Skip |
No spec folder (creates tech debt) |
Trivial changes only |
Enforcement: Constitutional-tier memory surfaces automatically via memory_match_triggers().
3-Level Progressive Enhancement
Level 1 (Baseline): spec.md + plan.md + tasks.md + implementation-summary.md
↓
Level 2 (Verification): Level 1 + checklist.md
↓
Level 3 (Full): Level 2 + decision-record.md + optional research.md
| Level |
LOC Guidance |
Required Files |
Use When |
| 1 |
<100 |
spec.md, plan.md, tasks.md, implementation-summary.md |
All features (minimum) |
| 2 |
100-499 |
Level 1 + checklist.md |
QA validation needed |
| 3 |
≥500 |
Level 2 + decision-record.md |
Complex/architecture changes |
Level Selection Examples:
| Task |
LOC Est. |
Level |
Rationale |
| Fix CSS alignment |
10 |
1 |
Simple, low risk |
| Add form validation |
80 |
1-2 |
Borderline, low complexity |
| Modal component |
200 |
2 |
Multiple files, needs QA |
| Auth system refactor |
600 |
3 |
Architecture change, high risk |
| Database migration |
150 |
3 |
High risk overrides LOC |
Override Factors (can push to higher level):
- High complexity or architectural changes
- Risk (security, config cascades, authentication)
- Multiple systems affected (>5 files)
- Integration vs unit test requirements
Decision rule: When in doubt → choose higher level. Better to over-document than under-document.
Checklist as Verification Tool (Level 2+)
The checklist.md is an ACTIVE VERIFICATION TOOL, not passive documentation:
| Priority |
Meaning |
Deferral Rules |
| P0 |
HARD BLOCKER |
MUST complete, cannot defer |
| P1 |
Required |
MUST complete OR user-approved deferral |
| P2 |
Optional |
Can defer without approval |
AI Workflow:
- Load checklist.md at completion phase
- Verify items in order: P0 → P1 → P2
- Mark
[x] with evidence for each verified item
- Cannot claim "done" until all P0/P1 items verified
Evidence formats:
[Test: npm test - all passing]
[File: src/auth.ts:45-67]
[Commit: abc1234]
[Screenshot: evidence/login-works.png]
(verified by manual testing)
(confirmed in browser console)
Example checklist entry:
## P0 - Blockers
- [x] Auth flow working [Test: npm run test:auth - 12/12 passing]
- [x] No console errors [Screenshot: evidence/console-clean.png]
## P1 - Required
- [x] Unit tests added [File: tests/auth.test.ts - 8 new tests]
- [ ] Documentation updated [DEFERRED: Will complete in follow-up PR]
Folder Naming Convention
Format: specs/###-short-name/
Rules:
- 2-3 words (shorter is better)
- Lowercase, hyphen-separated
- Action-noun structure
- 3-digit padding:
001, 042, 099 (no padding past 999)
Good examples: fix-typo, add-auth, mcp-code-mode, cli-codex
Bad examples: new-feature-implementation, UpdateUserAuthSystem, fix_bug
Find next number:
ls -d specs/[0-9]*/ | sed 's/.*\/\([0-9]*\)-.*/\1/' | sort -n | tail -1
Sub-Folder Versioning
When reusing spec folders with existing content:
- Trigger: Option A selected + root-level content exists
- Pattern:
001-original/, 002-new-work/, 003-another/
- Memory: Each sub-folder has independent
memory/ directory
- Tracking: Spec folder path passed via CLI argument (stateless)
Example structure:
specs/007-auth-system/
├── 001-initial-implementation/
│ ├── spec.md
│ ├── plan.md
│ └── memory/
├── 002-oauth-addition/
│ ├── spec.md
│ ├── plan.md
│ └── memory/
└── 003-security-audit/
├── spec.md
└── memory/
Full documentation: See sub_folder_versioning.md
Context Preservation
Manual context save (MANDATORY workflow):
- Trigger:
/memory:save, "save context", or "save memory"
- MUST use:
node .opencode/skill/system-spec-kit/scripts/generate-context.js [spec-folder-path]
- NEVER: Create memory files manually via Write/Edit (AGENTS.md Memory Save Rule)
- Location:
specs/###-folder/memory/
- Filename:
DD-MM-YY_HH-MM__topic.md (auto-generated by script)
- Content includes: PROJECT STATE SNAPSHOT with Phase, Last Action, Next Action, Blockers
Memory File Structure:
<!-- ANCHOR:context -->
## Project Context
[Auto-generated summary of conversation and decisions]
<!-- /ANCHOR:context -->
<!-- ANCHOR:state -->
## Project State Snapshot
- Phase: Implementation
- Last Action: Completed auth middleware
- Next Action: Add unit tests for login flow
- Blockers: None
<!-- /ANCHOR:state -->
<!-- ANCHOR:artifacts -->
## Key Artifacts
- Modified: src/middleware/auth.ts
- Created: src/utils/jwt.ts
<!-- /ANCHOR:artifacts -->
Spec Kit Memory System (Integrated)
Context preservation across sessions via vector-based semantic search.
MCP Tools:
| Tool |
Purpose |
memory_search() |
Semantic search with vector similarity |
memory_match_triggers() |
Fast keyword matching (<50ms) |
memory_save() |
Index a memory file |
memory_list() |
Browse stored memories with pagination |
memory_delete() |
Delete memories by ID or spec folder |
memory_update() |
Update memory metadata and importance tier |
memory_stats() |
Get system statistics and counts |
memory_validate() |
Record validation feedback for confidence |
memory_index_scan() |
Bulk scan and index workspace |
memory_health() |
Check system health status |
checkpoint_create() |
Create named checkpoint |
checkpoint_list() |
List all available checkpoints |
checkpoint_restore() |
Restore from checkpoint |
checkpoint_delete() |
Delete a checkpoint |
Note: Full tool names use spec_kit_memory_ prefix (e.g., spec_kit_memory_memory_search()).
memory_search() Parameter Requirements:
IMPORTANT: query (string) OR concepts (array of 2-5 strings) is REQUIRED. specFolder alone is NOT sufficient and will cause E040 error.
// Correct usage
memory_search({ query: "session context", specFolder: "007-auth" })
memory_search({ concepts: ["auth", "session"], specFolder: "007-auth" })
// WRONG: Will cause E040 error
// memory_search({ specFolder: "007-auth" })
Key Concepts:
- Constitutional tier - Critical rules that ALWAYS surface at top of search results
- Decay scoring - Recent memories rank higher (~62-day half-life)
- Real-time sync - Use
memory_save or memory_index_scan after creating files
Indexing Persistence Note:
When generate-context.js creates a memory file, it performs internal indexing and reports "Indexed as memory #X". However, the running MCP server maintains its own database connection and may not immediately see the new index entry.
For immediate MCP visibility, call one of:
memory_index_scan({ specFolder: "your-folder" }) - Re-scan and index
memory_save({ filePath: "path/to/memory.md" }) - Index specific file
This is typically only needed if you want to search the memory immediately after creation in the same session.
Full documentation: See memory_system.md for tool behavior, importance tiers, and configuration.
Two-Stage Question Flow
When returning to an active spec folder:
STAGE 1: SPEC FOLDER
"Continue in '006-commands' or start fresh?"
A) Continue in 006-commands
B) Create new spec folder
D) Skip documentation
[If A chosen AND memory files exist]
STAGE 2: MEMORY LOADING
"Found 3 previous session files. Load context?"
A) Load most recent
B) Load all recent (1-3)
C) List and select specific
D) Skip (start fresh)
Key Insight: "D" means different things:
- Stage 1 "D" = Skip documentation entirely
- Stage 2 "D" = Skip memory loading (stay in spec folder)
AI Actions by Stage 2 Choice:
- A: Read most recent memory file
- B: Read 3 most recent files (parallel)
- C: List up to 10 files, wait for selection
- D: Proceed without loading context
Debug Delegation Workflow
When to Trigger:
- Manual:
/spec_kit:debug or "delegate this to a debug agent"
- Auto-suggest when detecting:
- Same error 3+ times after fix attempts
- Frustration keywords: "stuck", "can't fix", "tried everything"
- Extended debugging: >15 minutes with 2+ fix attempts
⚠️ MANDATORY: After 3 failed attempts on the same error, you MUST suggest /spec_kit:debug. Do not continue attempting fixes without offering debug delegation first.
Model Selection (MANDATORY - never skip):
| Model |
Best For |
Characteristics |
| Claude |
General debugging, code analysis |
Anthropic models (Sonnet/Opus) |
| Gemini |
Multi-modal, large context |
Google models (Pro/Ultra) |
| Codex |
Code generation, reasoning |
OpenAI models (GPT-4/o1) |
| Other |
User-specified model |
Custom selection |
Workflow:
- Ask which model to use
- Generate
debug-delegation.md with: error category, message, files, attempts, hypothesis
- Dispatch sub-agent via Task tool
- Present findings: Apply fix / Iterate / Manual review
- Update debug-delegation.md with resolution
Auto-suggestion display:
💡 Debug Delegation Suggested - You've been working on this issue for a while.
Run: /spec_kit:debug
Command Pattern Protocol
Commands in .opencode/command/**/*.yaml are Reference Patterns:
- Scan available commands for relevance to task
- Extract logic (decision trees), sequencing (order of ops), structure (outputs)
- Adapt if <80% match; apply directly if >80%
- Report contributions in
implementation-summary.md
Exception: Explicitly invoked commands (e.g., /spec_kit:complete) are ENFORCED LAW, not just reference.
Parallel Dispatch Configuration
SpecKit supports smart parallel sub-agent dispatch based on 5-dimension complexity scoring:
- <20% complexity: Proceed directly
- ≥20% + 2 domains: Ask user for dispatch preference
- Step 6 Planning: Auto-dispatches 4 parallel exploration agents
Full configuration: See parallel_dispatch_config.md
4. 📋 RULES
✅ ALWAYS
- Determine level (1/2/3) before ANY file changes - Count LOC, assess complexity/risk
- Copy templates from
templates/ - NEVER create from scratch
- Fill ALL placeholders - Remove
[PLACEHOLDER] and sample content
- Ask A/B/C/D when file modification detected - Present options, wait for selection
- Check for related specs before creating new folders - Search keywords, review status
- Get explicit user approval before changes - Show level, path, templates, approach
- Use consistent folder naming -
specs/###-short-name/ format
- Use checklist.md to verify (Level 2+) - Load before claiming done
- Mark items
[x] with evidence - Include links, test outputs, screenshots
- Complete P0/P1 before claiming done - No exceptions
- Suggest handover.md on session-end keywords - "continue later", "next session"
- Run validate-spec.sh before completion - Completion Verification requirement
- Create implementation-summary.md at end of implementation phase (Level 1+) - Document what was built
- Suggest /spec_kit:handover when session-end keywords detected OR after extended work (15+ tool calls) - Proactive context preservation
- Suggest /spec_kit:debug after 3+ failed fix attempts on same error - Do not continue without offering debug delegation
❌ NEVER
- Create documentation from scratch - Use templates only
- Skip spec folder creation - Unless user explicitly selects D
- Make changes before spec + approval - Spec folder is prerequisite
- Leave placeholders in final docs - All must be replaced
- Decide autonomously update vs create - Always ask user
- Claim done without checklist verification - Level 2+ requirement
- Proceed without spec folder confirmation - Wait for A/B/C/D
- Skip validation before completion - Completion Verification hard block
⚠️ ESCALATE IF
- Scope grows during implementation - Add higher-level templates, document change in changelog
- Uncertainty about level <80% - Present level options to user, default to higher
- Template doesn't fit requirements - Adapt closest template, document modifications
- User requests skip (Option D) - Warn about tech debt, explain debugging challenges, confirm consent
- Validation fails with errors - Report specific failures, provide fix guidance, re-run after fixes
5. ✅ VALIDATION
Automated validation of spec folder contents via validate-spec.sh.
Usage: .opencode/skill/system-spec-kit/scripts/validate-spec.sh <spec-folder>
Exit Codes
| Code |
Meaning |
Action |
| 0 |
Passed (no errors, no warnings) |
Proceed with completion |
| 1 |
Passed with warnings |
Address or document warnings |
| 2 |
Failed (errors found) |
MUST fix before completion |
Completion Verification
Before claiming "done":
- Run validation:
./scripts/validate-spec.sh <spec-folder>
- Exit 2 → FIX errors
- Exit 1 → ADDRESS warnings or document reason
- Exit 0 → Proceed with completion claim
Full documentation: See validation_rules.md for all rules, configuration, and troubleshooting.
6. 🏆 SUCCESS CRITERIA
Documentation Created
User Approval
Context Preservation
Checklist Verification (Level 2+)
Validation Passed
7. 🔌 INTEGRATION POINTS
Priority System
| Priority |
Level |
Deferral |
| P0 |
Blocker |
Cannot proceed without resolution |
| P1 |
Warning |
Must address or defer with user approval |
| P2 |
Optional |
Can defer without approval |
Validation Triggers
- AGENTS.md Gate 3 → Validates spec folder existence and template completeness
- AGENTS.md Completion Verification → Runs validate-spec.sh before completion claims
- Manual
/memory:save → Context preservation on demand
- Template validation → Checks placeholder removal and required field completion
Cross-Skill Workflows
Spec Folder → Implementation:
system-spec-kit (creates spec folder)
→ workflows-code (implements from spec + plan)
→ workflows-git (commits with spec reference)
→ Spec Kit Memory (preserves conversation to spec/memory/ via MCP)
Documentation Quality:
system-spec-kit (creates spec documentation)
→ workflows-documentation (validates structure, scores quality)
→ Feedback loop: Iterate if scores <90
Validation Workflow:
Implementation complete
→ validate-spec.sh (automated checks)
→ Fix ERROR-level issues
→ Address WARNING-level issues
→ Claim completion with confidence
Common Failure Patterns
| Pattern |
Trigger |
Prevention |
| Skip Gate 3 on exciting tasks |
"comprehensive", "fix all", "15 agents" |
STOP → Ask spec folder → Wait for A/B/C/D |
| Rush to code |
"straightforward", "simple fix" |
Analyze → Verify → Simplest solution |
| Create docs from scratch |
Time pressure |
Always copy from templates/ |
| Skip checklist verification |
"trivial edit" |
Load checklist.md, verify ALL items |
| Manual memory file creation |
"quick save" |
MUST use generate-context.js script |
| Autonomous update vs create |
"obvious choice" |
Always ask user for A/B/C/D |
Quick Reference Commands
Create new spec folder:
./scripts/create-spec-folder.sh "Add feature description" --short-name feature-name --level 2
Validate spec folder:
.opencode/skill/system-spec-kit/scripts/validate-spec.sh specs/007-feature/
Save context:
node .opencode/skill/system-spec-kit/scripts/generate-context.js specs/007-feature/
Find next spec number:
ls -d specs/[0-9]*/ | sed 's/.*\/\([0-9]*\)-.*/\1/' | sort -n | tail -1
Calculate documentation completeness:
.opencode/skill/system-spec-kit/scripts/calculate-completeness.sh specs/007-feature/
8. 🔗 RELATED RESOURCES
Related Skills
| Direction |
Skill |
Integration |
| Upstream |
None |
This is the foundational workflow |
| Downstream |
workflows-code |
Uses spec folders for implementation tracking |
| Downstream |
workflows-git |
References spec folders in commit messages and PRs |
| Downstream |
workflows-documentation |
Validates spec folder documentation quality |
| Integrated |
Spec Kit Memory |
Context preservation via MCP (merged into this skill) |
External Dependencies
| Resource |
Location |
Purpose |
| Templates (10) |
templates/ |
All spec folder templates |
| Validation |
scripts/validate-spec.sh |
Automated validation |
| Gates |
AGENTS.md Section 2 |
Gate definitions |
| Memory gen |
.opencode/skill/system-spec-kit/scripts/generate-context.js |
Memory file creation |
| MCP Server |
.opencode/skill/system-spec-kit/mcp_server/context-server.js |
Spec Kit Memory MCP |
| Database |
.opencode/skill/system-spec-kit/database/context-index.sqlite |
Vector search index |
| Constitutional |
.opencode/skill/system-spec-kit/constitutional/ |
Always-surface rules |
Remember: This skill is the foundational documentation orchestrator. It enforces structure, template usage, context preservation, and validation for all file modifications. Every conversation that modifies files MUST have a spec folder.
1---2name: system-spec-kit-23description: Unified documentation and context preservation: spec folder workflow (levels 1-3), template enforcement, validation, Spec Kit Memory with vector search, six-tier importance system, constitutional rules, checkpoint save/restore. Mandatory for all file modifications.4---56> **Version Note:** The version number (16.0.0) tracks the skill's evolution including documentation, templates, scripts, and MCP server. All package.json files are aligned to this version.78<!-- Keywords: spec-kit, speckit, documentation-workflow, spec-folder, template-enforcement, context-preservation, progressive-documentation, validation, spec-kit-memory, vector-search, constitutional-tier, checkpoint, importance-tiers -->910# Spec Kit - Mandatory Conversation Documentation1112Orchestrates mandatory spec folder creation for all conversations involving file modifications. Ensures proper documentation level selection (1-3), template usage, and context preservation through AGENTS.md-enforced workflows.1314---1516## 1. 🎯 WHEN TO USE1718### What is a Spec Folder?1920A **spec folder** is a numbered directory (e.g., `specs/007-auth-feature/`) that contains all documentation for a single feature or task:2122- **Purpose**: Track specifications, plans, tasks, and decisions for one unit of work23- **Location**: Always under `specs/` directory with format `###-short-name/`24- **Contents**: Markdown files (spec.md, plan.md, tasks.md) plus optional memory/ and scratch/ subdirectories2526Think of it as a "project folder" for AI-assisted development - it keeps context organized and enables session continuity.2728### Activation Triggers2930**MANDATORY for ALL file modifications:**31- Code files: JS, TS, Python, CSS, HTML32- Documentation: Markdown, README, guides33- Configuration: JSON, YAML, TOML, env templates34- Templates, knowledge base, build/tooling files3536**Request patterns that trigger activation:**37- "Add/implement/create [feature]"38- "Fix/update/refactor [code]"39- "Modify/change [configuration]"40- Any keyword: add, implement, fix, update, create, modify, rename, delete, configure, analyze4142**Example triggers:**43- "Add email validation to the signup form" → Level 1-244- "Refactor the authentication module" → Level 2-345- "Fix the button alignment bug" → Level 146- "Implement user dashboard with analytics" → Level 34748### When NOT to Use4950- Pure exploration/reading (no file modifications)51- Single typo fixes (<5 characters in one file)52- Whitespace-only changes53- Auto-generated file updates (package-lock.json)54- User explicitly selects Option D (skip documentation)5556**Rule of thumb:** If modifying ANY file content → Activate this skill.5758### Utility Template Triggers5960| Template | Trigger Keywords | Action |61| --------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------- |62| `handover.md` | "handover", "next session", "continue later", "pass context", "ending session", "save state", "multi-session", "for next AI" | Suggest creating handover |63| `debug-delegation.md` | "stuck", "can't fix", "tried everything", "same error", "fresh eyes", "hours on this", "still failing", "need help debugging" | Suggest `/spec_kit:debug` |6465**Rule:** When detected, proactively suggest the appropriate action.6667---6869## 2. 🧭 SMART ROUTING7071### Activation Detection7273```74User Request75 │76 ├─► Contains "spec", "plan", "document", "checklist"?77 │ └─► YES → Activate SpecKit (spec folder workflow)78 │79 ├─► File modification requested?80 │ └─► Gate 3 triggered → Ask spec folder question81 │82 ├─► Contains "debug", "stuck", "help"?83 │ └─► Route to /spec_kit:debug84 │85 ├─► Contains "continue", "resume", "pick up"?86 │ └─► Route to /spec_kit:resume87 │88 ├─► Contains "save context", "save memory", "/memory:save"?89 │ └─► Execute generate-context.js → Index to Spec Kit Memory90 │91 ├─► Contains "search memory", "find context", "what did we"?92 │ └─► Use memory_search({ query: "..." }) MCP tool (query OR concepts required)93 │94 ├─► Contains "checkpoint", "save state", "restore"?95 │ └─► Use checkpoint_create/restore MCP tools96 │97 └─► Gate enforcement triggered (file modification)?98 └─► Constitutional memories auto-surface via memory_match_triggers()99```100101### Memory System Triggers102103> **Note:** Tool names use the full `spec_kit_memory_*` prefix as required by OpenCode MCP integration.104105| Trigger Pattern | Action | MCP Tool |106|-----------------|--------|----------|107| "save context", "save memory", `/memory:save` | Generate + index memory file | `spec_kit_memory_memory_save()` |108| "search memory", "find prior", "what did we decide" | Semantic search across sessions | `spec_kit_memory_memory_search({ query: "..." })` (query OR concepts required) |109| "list memories", "show context" | Browse stored memories | `spec_kit_memory_memory_list()` |110| "checkpoint", "save state" | Create named checkpoint | `spec_kit_memory_checkpoint_create()` |111| "restore checkpoint", "rollback" | Restore from checkpoint | `spec_kit_memory_checkpoint_restore()` |112| Gate enforcement (any file modification) | Auto-surface constitutional rules | `spec_kit_memory_memory_match_triggers()` |113114### Resource Router115116**Phase-Based Loading:**117118| Phase | Trigger | Load Resources | Execute |119| ------------------ | ------------------------------------- | ------------------------------------------ | ------------------- |120| **Planning** | New feature, "plan", "design" | level_specifications.md, template_guide.md | /spec_kit:plan |121| **Research** | "investigate", "explore", "analyze" | quick_reference.md, worked_examples.md | /spec_kit:research |122| **Implementation** | "implement", "build", "code" | validation_rules.md, template_guide.md | /spec_kit:implement |123| **Debugging** | "stuck", "error", "not working" | quick_reference.md, troubleshooting.md | /spec_kit:debug |124| **Completion** | "done", "finished", "complete" | validation_rules.md, phase_checklists.md | /spec_kit:complete |125| **Handover** | "stopping", "break", "continue later" | quick_reference.md | /spec_kit:handover |126| **Resume** | "continue", "pick up", "resume" | quick_reference.md | /spec_kit:resume |127128### Reference Sub-folders129130| Sub-folder | Purpose | Files |131|------------|---------|-------|132| `memory/` | Context preservation, MCP tools | memory_system.md, save_workflow.md, trigger_config.md |133| `templates/` | Template system, level specs | level_specifications.md, template_guide.md, template_style_guide.md |134| `validation/` | Validation rules, checklists | validation_rules.md, phase_checklists.md, path_scoped_rules.md |135| `structure/` | Folder organization, routing | folder_structure.md, folder_routing.md, sub_folder_versioning.md |136| `workflows/` | Usage workflows, examples | quick_reference.md, execution_methods.md, worked_examples.md |137| `debugging/` | Troubleshooting, debugging | troubleshooting.md, universal_debugging_methodology.md |138| `config/` | Configuration | environment_variables.md |139140### Keyword-Based Routing141142| Keywords | Route To |143|----------|----------|144| "memory", "save context", "MCP", "trigger" | `references/memory/` |145| "embeddings", "vector", "semantic", "decay" | `references/memory/` |146| "anchor", "snapshot" | `references/memory/` |147| "template", "level 1/2/3", "spec.md format" | `references/templates/` |148| "validate", "rules", "checklist", "P0/P1/P2" | `references/validation/` |149| "folder", "naming", "structure", "versioning" | `references/structure/` |150| "workflow", "example", "commands", "quick" | `references/workflows/` |151| "debug", "error", "stuck", "troubleshoot" | `references/debugging/` |152| "env", "environment", "configuration" | `references/config/` |153| "scripts", "generate-context", "check-completion" | `scripts/` |154155### Resource Inventory156157**Templates by Level (`templates/`):**158159| Level | Required Files | Optional |160| ----- | -------------- | -------- |161| 1 | spec.md, plan.md, tasks.md, implementation-summary.md | — |162| 2 | Level 1 + checklist.md | — |163| 3 | Level 2 + decision-record.md | research.md |164| Any | — | handover.md, debug-delegation.md |165166**Internal Templates:**167- `context_template.md` - Internal template for memory file generation (Mustache format)168169**Auto-Generated Folders:**170- `memory/` - Session context (via `generate-context.js`)171- `scratch/` - Temporary workspace (manual creation)172173**Key Scripts:**174175| Script | Purpose |176|--------|---------|177| `generate-context.js` | Generate memory files from conversation (modular: 44 modules in 10 dirs) |178| `validate-spec.sh` | Validate spec folder structure |179| `create-spec-folder.sh` | Create new spec folders with templates |180| `check-completion.sh` | Verify checklist completion status |181| `recommend-level.sh` | Suggest documentation level based on LOC |182| `archive-spec.sh` | Archive completed spec folders |183| `cleanup-orphaned-vectors.js` | Removes orphaned vector entries |184| `check-prerequisites.sh` | Checks prerequisites before implementation |185| `common.sh` | Shared shell utilities |186| `setup.sh` | Initial setup script |187| `calculate-completeness.sh` | Calculates spec completeness percentage |188| `package.json` | Node.js dependencies |189| `README.md` | Scripts documentation |190| `tests/test-validation.sh` | Validation test runner |191| `tests/test-embeddings-factory.js` | Test embedding provider configuration |192| `tests/test-bug-fixes.js` | Bug fix regression tests |193194**References (`references/`):**195196| Sub-folder | File | Purpose | When to Load |197|------------|------|---------|--------------|198| `memory/` | `memory_system.md` | MCP tool behavior and config | Memory operations |199| `memory/` | `save_workflow.md` | Memory save workflow docs | Context preservation |200| `memory/` | `trigger_config.md` | Trigger phrase configuration | Setup |201| `templates/` | `level_specifications.md` | Complete Level 1-3 requirements | Planning |202| `templates/` | `template_guide.md` | Template selection and usage | Planning, Implementation |203| `templates/` | `template_style_guide.md` | Template formatting conventions | Documentation |204| `validation/` | `validation_rules.md` | All validation rules and fixes | Implementation, Completion |205| `validation/` | `phase_checklists.md` | Per-phase validation | Completion |206| `validation/` | `path_scoped_rules.md` | Path-scoped validation | Advanced |207| `structure/` | `folder_structure.md` | Folder naming conventions | Planning |208| `structure/` | `folder_routing.md` | Folder routing logic | Planning |209| `structure/` | `sub_folder_versioning.md` | Sub-folder workflow | Reusing spec folders |210| `workflows/` | `quick_reference.md` | Commands and checklists | Any phase |211| `workflows/` | `execution_methods.md` | Script execution patterns | Operations |212| `workflows/` | `worked_examples.md` | Real-world examples | Learning |213| `debugging/` | `troubleshooting.md` | Common issues and solutions | Debugging |214| `debugging/` | `universal_debugging_methodology.md` | Stack-agnostic 4-phase debugging | Debugging |215| `config/` | `environment_variables.md` | Env var configuration | Setup |216217**Assets (`assets/`):**218219| File | Purpose |220|------|---------|221| `level_decision_matrix.md` | LOC thresholds and complexity factors |222| `template_mapping.md` | Template-to-level mapping rules |223| `parallel_dispatch_config.md` | Agent dispatch configuration |224225**generate-context.js Input Modes:**226227| Mode | Usage | Description |228|------|-------|-------------|229| **Direct** | `node generate-context.js specs/007-feature/` | Auto-captures context from OpenCode session |230| **JSON** | `node generate-context.js /tmp/context-data.json` | Manual context injection via JSON file |231232**Architecture:** The script uses a modular architecture (142-line CLI entry point + 44 modules across 10 directories: `core/`, `extractors/`, `lib/`, `loaders/`, `renderers/`, `rules/`, `spec-folder/`, `test-fixtures/`, `tests/`, `utils/`). See [scripts/README.md](./scripts/README.md) for module details and extension points.233234**JSON mode documentation:** See [save_workflow.md](./references/memory/save_workflow.md) for full schema and examples.235236---237238## 3. 🛠️ HOW IT WORKS239240### Gate 3 Integration241242> **See AGENTS.md Section 2** for the complete Gate 3 flow. This skill implements that gate.243244When file modification detected, AI MUST ask:245246```247**Spec Folder** (required): A) Existing | B) New | C) Update related | D) Skip248```249250| Option | Description | Best For |251| --------------- | ---------------------------------- | ------------------------------- |252| **A) Existing** | Continue in related spec folder | Iterative work, related changes |253| **B) New** | Create `specs/###-name/` | New features, unrelated work |254| **C) Update** | Add to existing documentation | Extending existing docs |255| **D) Skip** | No spec folder (creates tech debt) | Trivial changes only |256257**Enforcement:** Constitutional-tier memory surfaces automatically via `memory_match_triggers()`.258259### 3-Level Progressive Enhancement260261```262Level 1 (Baseline): spec.md + plan.md + tasks.md + implementation-summary.md263 ↓264Level 2 (Verification): Level 1 + checklist.md265 ↓266Level 3 (Full): Level 2 + decision-record.md + optional research.md267```268269| Level | LOC Guidance | Required Files | Use When |270| ----- | ------------ | ------------------------------------------------------------------------ | ---------------------------- |271| **1** | <100 | spec.md, plan.md, tasks.md, implementation-summary.md | All features (minimum) |272| **2** | 100-499 | Level 1 + checklist.md | QA validation needed |273| **3** | ≥500 | Level 2 + decision-record.md | Complex/architecture changes |274275**Level Selection Examples:**276277| Task | LOC Est. | Level | Rationale |278| -------------------- | -------- | ----- | ------------------------------ |279| Fix CSS alignment | 10 | 1 | Simple, low risk |280| Add form validation | 80 | 1-2 | Borderline, low complexity |281| Modal component | 200 | 2 | Multiple files, needs QA |282| Auth system refactor | 600 | 3 | Architecture change, high risk |283| Database migration | 150 | 3 | High risk overrides LOC |284285**Override Factors (can push to higher level):**286- High complexity or architectural changes287- Risk (security, config cascades, authentication)288- Multiple systems affected (>5 files)289- Integration vs unit test requirements290291**Decision rule:** When in doubt → choose higher level. Better to over-document than under-document.292293### Checklist as Verification Tool (Level 2+)294295The `checklist.md` is an **ACTIVE VERIFICATION TOOL**, not passive documentation:296297| Priority | Meaning | Deferral Rules |298| -------- | ------------ | --------------------------------------- |299| **P0** | HARD BLOCKER | MUST complete, cannot defer |300| **P1** | Required | MUST complete OR user-approved deferral |301| **P2** | Optional | Can defer without approval |302303**AI Workflow:**3041. Load checklist.md at completion phase3052. Verify items in order: P0 → P1 → P23063. Mark `[x]` with evidence for each verified item3074. Cannot claim "done" until all P0/P1 items verified308309**Evidence formats:**310- `[Test: npm test - all passing]`311- `[File: src/auth.ts:45-67]`312- `[Commit: abc1234]`313- `[Screenshot: evidence/login-works.png]`314- `(verified by manual testing)`315- `(confirmed in browser console)`316317**Example checklist entry:**318```markdown319## P0 - Blockers320- [x] Auth flow working [Test: npm run test:auth - 12/12 passing]321- [x] No console errors [Screenshot: evidence/console-clean.png]322323## P1 - Required 324- [x] Unit tests added [File: tests/auth.test.ts - 8 new tests]325- [ ] Documentation updated [DEFERRED: Will complete in follow-up PR]326```327328### Folder Naming Convention329330**Format:** `specs/###-short-name/`331332**Rules:**333- 2-3 words (shorter is better)334- Lowercase, hyphen-separated335- Action-noun structure336- 3-digit padding: `001`, `042`, `099` (no padding past 999)337338**Good examples:** `fix-typo`, `add-auth`, `mcp-code-mode`, `cli-codex`339**Bad examples:** `new-feature-implementation`, `UpdateUserAuthSystem`, `fix_bug`340341**Find next number:**342```bash343ls -d specs/[0-9]*/ | sed 's/.*\/\([0-9]*\)-.*/\1/' | sort -n | tail -1344```345346### Sub-Folder Versioning347348When reusing spec folders with existing content:349- Trigger: Option A selected + root-level content exists350- Pattern: `001-original/`, `002-new-work/`, `003-another/`351- Memory: Each sub-folder has independent `memory/` directory352- Tracking: Spec folder path passed via CLI argument (stateless)353354**Example structure:**355```356specs/007-auth-system/357├── 001-initial-implementation/358│ ├── spec.md359│ ├── plan.md360│ └── memory/361├── 002-oauth-addition/362│ ├── spec.md363│ ├── plan.md364│ └── memory/365└── 003-security-audit/366 ├── spec.md367 └── memory/368```369370**Full documentation:** See [sub_folder_versioning.md](./references/structure/sub_folder_versioning.md)371372### Context Preservation373374**Manual context save (MANDATORY workflow):**375- Trigger: `/memory:save`, "save context", or "save memory"376- **MUST use:** `node .opencode/skill/system-spec-kit/scripts/generate-context.js [spec-folder-path]`377- **NEVER:** Create memory files manually via Write/Edit (AGENTS.md Memory Save Rule)378- Location: `specs/###-folder/memory/`379- Filename: `DD-MM-YY_HH-MM__topic.md` (auto-generated by script)380- Content includes: PROJECT STATE SNAPSHOT with Phase, Last Action, Next Action, Blockers381382**Memory File Structure:**383```markdown384<!-- ANCHOR:context -->385## Project Context386[Auto-generated summary of conversation and decisions]387<!-- /ANCHOR:context -->388389<!-- ANCHOR:state -->390## Project State Snapshot391- Phase: Implementation392- Last Action: Completed auth middleware393- Next Action: Add unit tests for login flow394- Blockers: None395<!-- /ANCHOR:state -->396397<!-- ANCHOR:artifacts -->398## Key Artifacts399- Modified: src/middleware/auth.ts400- Created: src/utils/jwt.ts401<!-- /ANCHOR:artifacts -->402```403404### Spec Kit Memory System (Integrated)405406Context preservation across sessions via vector-based semantic search.407408**MCP Tools:**409410| Tool | Purpose |411|------|---------|412| `memory_search()` | Semantic search with vector similarity |413| `memory_match_triggers()` | Fast keyword matching (<50ms) |414| `memory_save()` | Index a memory file |415| `memory_list()` | Browse stored memories with pagination |416| `memory_delete()` | Delete memories by ID or spec folder |417| `memory_update()` | Update memory metadata and importance tier |418| `memory_stats()` | Get system statistics and counts |419| `memory_validate()` | Record validation feedback for confidence |420| `memory_index_scan()` | Bulk scan and index workspace |421| `memory_health()` | Check system health status |422| `checkpoint_create()` | Create named checkpoint |423| `checkpoint_list()` | List all available checkpoints |424| `checkpoint_restore()` | Restore from checkpoint |425| `checkpoint_delete()` | Delete a checkpoint |426427> **Note:** Full tool names use `spec_kit_memory_` prefix (e.g., `spec_kit_memory_memory_search()`).428429**memory_search() Parameter Requirements:**430431> **IMPORTANT:** `query` (string) OR `concepts` (array of 2-5 strings) is REQUIRED. `specFolder` alone is NOT sufficient and will cause E040 error.432433```javascript434// Correct usage435memory_search({ query: "session context", specFolder: "007-auth" })436memory_search({ concepts: ["auth", "session"], specFolder: "007-auth" })437438// WRONG: Will cause E040 error439// memory_search({ specFolder: "007-auth" })440```441442**Key Concepts:**443- **Constitutional tier** - Critical rules that ALWAYS surface at top of search results444- **Decay scoring** - Recent memories rank higher (~62-day half-life)445- **Real-time sync** - Use `memory_save` or `memory_index_scan` after creating files446447**Indexing Persistence Note:**448When `generate-context.js` creates a memory file, it performs internal indexing and reports "Indexed as memory #X". However, the running MCP server maintains its own database connection and may not immediately see the new index entry.449450For immediate MCP visibility, call one of:451- `memory_index_scan({ specFolder: "your-folder" })` - Re-scan and index452- `memory_save({ filePath: "path/to/memory.md" })` - Index specific file453454This is typically only needed if you want to search the memory immediately after creation in the same session.455456**Full documentation:** See [memory_system.md](./references/memory/memory_system.md) for tool behavior, importance tiers, and configuration.457458### Two-Stage Question Flow459460When returning to an active spec folder:461462```463STAGE 1: SPEC FOLDER464"Continue in '006-commands' or start fresh?"465 A) Continue in 006-commands466 B) Create new spec folder467 D) Skip documentation468469[If A chosen AND memory files exist]470471STAGE 2: MEMORY LOADING472"Found 3 previous session files. Load context?"473 A) Load most recent474 B) Load all recent (1-3)475 C) List and select specific476 D) Skip (start fresh)477```478479**Key Insight:** "D" means different things:480- Stage 1 "D" = Skip documentation entirely481- Stage 2 "D" = Skip memory loading (stay in spec folder)482483**AI Actions by Stage 2 Choice:**484- **A:** Read most recent memory file485- **B:** Read 3 most recent files (parallel)486- **C:** List up to 10 files, wait for selection487- **D:** Proceed without loading context488489### Debug Delegation Workflow490491**When to Trigger:**492- Manual: `/spec_kit:debug` or "delegate this to a debug agent"493- Auto-suggest when detecting:494 - Same error 3+ times after fix attempts495 - Frustration keywords: "stuck", "can't fix", "tried everything"496 - Extended debugging: >15 minutes with 2+ fix attempts497498**⚠️ MANDATORY: After 3 failed attempts on the same error, you MUST suggest `/spec_kit:debug`. Do not continue attempting fixes without offering debug delegation first.**499500**Model Selection (MANDATORY - never skip):**501502| Model | Best For | Characteristics |503| ---------- | -------------------------------- | ------------------------------ |504| **Claude** | General debugging, code analysis | Anthropic models (Sonnet/Opus) |505| **Gemini** | Multi-modal, large context | Google models (Pro/Ultra) |506| **Codex** | Code generation, reasoning | OpenAI models (GPT-4/o1) |507| **Other** | User-specified model | Custom selection |508509**Workflow:**5101. Ask which model to use5112. Generate `debug-delegation.md` with: error category, message, files, attempts, hypothesis5123. Dispatch sub-agent via Task tool5134. Present findings: Apply fix / Iterate / Manual review5145. Update debug-delegation.md with resolution515516**Auto-suggestion display:**517```518💡 Debug Delegation Suggested - You've been working on this issue for a while.519Run: /spec_kit:debug520```521522### Command Pattern Protocol523524Commands in `.opencode/command/**/*.yaml` are **Reference Patterns**:5255261. **Scan** available commands for relevance to task5272. **Extract** logic (decision trees), sequencing (order of ops), structure (outputs)5283. **Adapt** if <80% match; apply directly if >80%5294. **Report** contributions in `implementation-summary.md`530531> **Exception:** Explicitly invoked commands (e.g., `/spec_kit:complete`) are **ENFORCED LAW**, not just reference.532533### Parallel Dispatch Configuration534535SpecKit supports smart parallel sub-agent dispatch based on 5-dimension complexity scoring:536- **<20% complexity:** Proceed directly537- **≥20% + 2 domains:** Ask user for dispatch preference538- **Step 6 Planning:** Auto-dispatches 4 parallel exploration agents539540**Full configuration:** See [parallel_dispatch_config.md](./assets/parallel_dispatch_config.md)541542---543544## 4. 📋 RULES545546### ✅ ALWAYS5475481. **Determine level (1/2/3) before ANY file changes** - Count LOC, assess complexity/risk5492. **Copy templates from `templates/`** - NEVER create from scratch5503. **Fill ALL placeholders** - Remove `[PLACEHOLDER]` and sample content5514. **Ask A/B/C/D when file modification detected** - Present options, wait for selection5525. **Check for related specs before creating new folders** - Search keywords, review status5536. **Get explicit user approval before changes** - Show level, path, templates, approach5547. **Use consistent folder naming** - `specs/###-short-name/` format5558. **Use checklist.md to verify (Level 2+)** - Load before claiming done5569. **Mark items `[x]` with evidence** - Include links, test outputs, screenshots55710. **Complete P0/P1 before claiming done** - No exceptions55811. **Suggest handover.md on session-end keywords** - "continue later", "next session"55912. **Run validate-spec.sh before completion** - Completion Verification requirement56013. **Create implementation-summary.md at end of implementation phase (Level 1+)** - Document what was built56114. **Suggest /spec_kit:handover when session-end keywords detected OR after extended work (15+ tool calls)** - Proactive context preservation56215. **Suggest /spec_kit:debug after 3+ failed fix attempts on same error** - Do not continue without offering debug delegation563564### ❌ NEVER5655661. **Create documentation from scratch** - Use templates only5672. **Skip spec folder creation** - Unless user explicitly selects D5683. **Make changes before spec + approval** - Spec folder is prerequisite5694. **Leave placeholders in final docs** - All must be replaced5705. **Decide autonomously update vs create** - Always ask user5716. **Claim done without checklist verification** - Level 2+ requirement5727. **Proceed without spec folder confirmation** - Wait for A/B/C/D5738. **Skip validation before completion** - Completion Verification hard block574575### ⚠️ ESCALATE IF5765771. **Scope grows during implementation** - Add higher-level templates, document change in changelog5782. **Uncertainty about level <80%** - Present level options to user, default to higher5793. **Template doesn't fit requirements** - Adapt closest template, document modifications5804. **User requests skip (Option D)** - Warn about tech debt, explain debugging challenges, confirm consent5815. **Validation fails with errors** - Report specific failures, provide fix guidance, re-run after fixes582583---584585## 5. ✅ VALIDATION586587Automated validation of spec folder contents via `validate-spec.sh`.588589**Usage:** `.opencode/skill/system-spec-kit/scripts/validate-spec.sh <spec-folder>`590591### Exit Codes592593| Code | Meaning | Action |594| ---- | ------------------------------- | ---------------------------- |595| 0 | Passed (no errors, no warnings) | Proceed with completion |596| 1 | Passed with warnings | Address or document warnings |597| 2 | Failed (errors found) | MUST fix before completion |598599### Completion Verification600601Before claiming "done":6021. Run validation: `./scripts/validate-spec.sh <spec-folder>`6032. Exit 2 → FIX errors6043. Exit 1 → ADDRESS warnings or document reason6054. Exit 0 → Proceed with completion claim606607**Full documentation:** See [validation_rules.md](./references/validation/validation_rules.md) for all rules, configuration, and troubleshooting.608609---610611## 6. 🏆 SUCCESS CRITERIA612613### Documentation Created614615- [ ] Spec folder exists at `specs/###-short-name/`616- [ ] Folder name follows convention (2-3 words, lowercase, hyphen-separated)617- [ ] Number is sequential (no gaps or duplicates)618- [ ] Correct level templates copied (not created from scratch)619- [ ] All placeholders replaced with actual content620- [ ] Sample content and instructional comments removed621- [ ] Cross-references to sibling documents work (spec.md ↔ plan.md ↔ tasks.md)622623### User Approval624625- [ ] Asked user for A/B/C/D choice when file modification detected626- [ ] Documentation level presented with rationale627- [ ] Spec folder path shown before creation628- [ ] Templates to be used listed629- [ ] Explicit approval ("yes", "go ahead", "proceed") received before file changes630631### Context Preservation632633- [ ] Context saved via `generate-context.js` script (NEVER manual Write/Edit)634- [ ] Memory files contain PROJECT STATE SNAPSHOT section635- [ ] Manual saves triggered via `/memory:save` or keywords636- [ ] Anchor pairs properly formatted and closed637638### Checklist Verification (Level 2+)639640- [ ] Loaded checklist.md before claiming completion641- [ ] Verified items in priority order (P0 → P1 → P2)642- [ ] All P0 items marked `[x]` with evidence643- [ ] All P1 items marked `[x]` with evidence644- [ ] P2 items either verified or deferred with documented reason645- [ ] No unchecked P0/P1 items remain646647### Validation Passed648649- [ ] Ran `validate-spec.sh` on spec folder650- [ ] Exit code is 0 (pass) or 1 (warnings only)651- [ ] All ERROR-level issues resolved652- [ ] WARNING-level issues addressed or documented653654---655656## 7. 🔌 INTEGRATION POINTS657658### Priority System659660| Priority | Level | Deferral |661| -------- | -------- | ---------------------------------------- |662| **P0** | Blocker | Cannot proceed without resolution |663| **P1** | Warning | Must address or defer with user approval |664| **P2** | Optional | Can defer without approval |665666### Validation Triggers667668- **AGENTS.md Gate 3** → Validates spec folder existence and template completeness669- **AGENTS.md Completion Verification** → Runs validate-spec.sh before completion claims670- **Manual `/memory:save`** → Context preservation on demand671- **Template validation** → Checks placeholder removal and required field completion672673### Cross-Skill Workflows674675**Spec Folder → Implementation:**676```677system-spec-kit (creates spec folder)678 → workflows-code (implements from spec + plan)679 → workflows-git (commits with spec reference)680 → Spec Kit Memory (preserves conversation to spec/memory/ via MCP)681```682683**Documentation Quality:**684```685system-spec-kit (creates spec documentation)686 → workflows-documentation (validates structure, scores quality)687 → Feedback loop: Iterate if scores <90688```689690**Validation Workflow:**691```692Implementation complete693 → validate-spec.sh (automated checks)694 → Fix ERROR-level issues695 → Address WARNING-level issues696 → Claim completion with confidence697```698699### Common Failure Patterns700701| Pattern | Trigger | Prevention |702| ----------------------------- | --------------------------------------- | ----------------------------------------- |703| Skip Gate 3 on exciting tasks | "comprehensive", "fix all", "15 agents" | STOP → Ask spec folder → Wait for A/B/C/D |704| Rush to code | "straightforward", "simple fix" | Analyze → Verify → Simplest solution |705| Create docs from scratch | Time pressure | Always copy from templates/ |706| Skip checklist verification | "trivial edit" | Load checklist.md, verify ALL items |707| Manual memory file creation | "quick save" | MUST use generate-context.js script |708| Autonomous update vs create | "obvious choice" | Always ask user for A/B/C/D |709710### Quick Reference Commands711712**Create new spec folder:**713```bash714./scripts/create-spec-folder.sh "Add feature description" --short-name feature-name --level 2715```716717**Validate spec folder:**718```bash719.opencode/skill/system-spec-kit/scripts/validate-spec.sh specs/007-feature/720```721722**Save context:**723```bash724node .opencode/skill/system-spec-kit/scripts/generate-context.js specs/007-feature/725```726727**Find next spec number:**728```bash729ls -d specs/[0-9]*/ | sed 's/.*\/\([0-9]*\)-.*/\1/' | sort -n | tail -1730```731732**Calculate documentation completeness:**733```bash734.opencode/skill/system-spec-kit/scripts/calculate-completeness.sh specs/007-feature/735```736737---738739## 8. 🔗 RELATED RESOURCES740741### Related Skills742743| Direction | Skill | Integration |744| -------------- | ----------------------- | -------------------------------------------------- |745| **Upstream** | None | This is the foundational workflow |746| **Downstream** | workflows-code | Uses spec folders for implementation tracking |747| **Downstream** | workflows-git | References spec folders in commit messages and PRs |748| **Downstream** | workflows-documentation | Validates spec folder documentation quality |749| **Integrated** | Spec Kit Memory | Context preservation via MCP (merged into this skill) |750751### External Dependencies752753| Resource | Location | Purpose |754| -------------- | ------------------------------------------------------------- | ---------------------------- |755| Templates (10) | `templates/` | All spec folder templates |756| Validation | `scripts/validate-spec.sh` | Automated validation |757| Gates | `AGENTS.md` Section 2 | Gate definitions |758| Memory gen | `.opencode/skill/system-spec-kit/scripts/generate-context.js` | Memory file creation |759| MCP Server | `.opencode/skill/system-spec-kit/mcp_server/context-server.js`| Spec Kit Memory MCP |760| Database | `.opencode/skill/system-spec-kit/database/context-index.sqlite`| Vector search index |761| Constitutional | `.opencode/skill/system-spec-kit/constitutional/` | Always-surface rules |762763---764765**Remember**: This skill is the foundational documentation orchestrator. It enforces structure, template usage, context preservation, and validation for all file modifications. Every conversation that modifies files MUST have a spec folder.