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., 007-auth-feature/) that contains documentation for a single feature/task or a coordinated packet of related phase work:
Spec folders may also be nested as coordination-root packets with direct-child phase folders (e.g., specs/02--track/022-feature/011-phase/002-child/).
- Purpose: Track specifications, plans, tasks, and decisions for one unit of work
- Location: Under
specs/ using either ###-short-name/ at the root or nested packet paths for phased coordination
- 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, phase
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.
Status: ✅ This requirement applies immediately once file edits are requested.
Agent Exclusivity
⛔ CRITICAL: @speckit is the ONLY agent permitted to create or substantively write spec folder documentation (*.md files).
- Requires @speckit: spec.md, plan.md, tasks.md, checklist.md, decision-record.md, implementation-summary.md, and any other *.md in spec folders
- Exceptions:
memory/ → uses generate-context.js script
scratch/ → temporary workspace, any agent
handover.md → @handover agent only
research/research.md → @deep-research agent only
debug-delegation.md → @debug agent only
Routing to @general, @write, or other agents for spec documentation is a hard violation. See constitutional memory: speckit-exclusivity.md
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
Resource Domains
The router discovers markdown resources recursively from references/ and assets/ and then applies intent scoring from RESOURCE_MAP. Keep this section domain-focused rather than static file inventories.
references/memory/ for context retrieval, save workflows, trigger behavior, and indexing.
references/templates/ for level selection, template composition, and structure guides.
references/validation/ for checklist policy, verification rules, decision formats, and template compliance contracts.
references/structure/ for folder organization and sub-folder versioning.
references/workflows/ for command workflows and worked examples.
references/debugging/ for troubleshooting and root-cause methodology.
references/config/ for runtime environment configuration.
Template and Script Sources of Truth
- Level definitions and template size guidance: level_specifications.md
- Template usage and composition rules: template_guide.md
- Use
templates/level_N/ for operational templates; core/ and addendum/ remain composition inputs.
- Use
templates/changelog/ for packet-local nested changelog generation at completion time.
- Script architecture, build outputs, and runtime entrypoints: scripts/README.md
- Memory save JSON schema and workflow contracts: save_workflow.md
- Nested packet changelog workflow: nested_changelog.md
Primary operational scripts:
spec/validate.sh
spec/create.sh
spec/archive.sh
spec/check-completion.sh
spec/recommend-level.sh
templates/compose.sh
Resource Loading Levels
| Level |
When to Load |
Resources |
| ALWAYS |
Every skill invocation |
Shared patterns + SKILL.md |
| CONDITIONAL |
If intent signals match |
Intent-mapped references |
| ON_DEMAND |
Only on explicit request |
Deep-dive quality standards |
references/workflows/quick_reference.md is the primary first-touch command surface. Keep the compact spec_kit and memory command map there, and use this file only to point readers to it rather than duplicating the full matrix.
Smart Router Pseudocode
The authoritative routing logic for scoped loading, weighted intent scoring, and ambiguity handling.
from pathlib import Path
SKILL_ROOT = Path(__file__).resolve().parent
RESOURCE_BASES = (SKILL_ROOT / "references", SKILL_ROOT / "assets")
DEFAULT_RESOURCE = "references/workflows/quick_reference.md"
INTENT_SIGNALS = {
"PLAN": {"weight": 3, "keywords": ["plan", "design", "new spec", "level selection", "option b"]},
"RESEARCH": {"weight": 3, "keywords": ["investigate", "explore", "analyze", "prior work", "evidence"]},
"IMPLEMENT": {"weight": 3, "keywords": ["implement", "build", "execute", "workflow"]},
"DEBUG": {"weight": 4, "keywords": ["stuck", "error", "not working", "failed", "debug"]},
"COMPLETE": {"weight": 4, "keywords": ["done", "complete", "finish", "verify", "checklist"]},
"MEMORY": {"weight": 4, "keywords": ["memory", "save context", "resume", "checkpoint", "context"]},
"HANDOVER": {"weight": 4, "keywords": ["handover", "continue later", "next session", "pause"]},
"PHASE": {"weight": 4, "keywords": ["phase", "decompose", "split", "workstream", "multi-phase", "phased approach", "phased", "multi-session"]},
"RETRIEVAL_TUNING": {"weight": 3, "keywords": ["retrieval", "search tuning", "fusion", "scoring", "pipeline"]},
"EVALUATION": {"weight": 3, "keywords": ["evaluate", "ablation", "benchmark", "baseline", "metrics"]},
"SCORING_CALIBRATION": {"weight": 3, "keywords": ["calibration", "scoring", "normalization", "decay", "interference"]},
"ROLLOUT_FLAGS": {"weight": 3, "keywords": ["feature flag", "rollout", "toggle", "enable", "disable"]},
"GOVERNANCE": {"weight": 3, "keywords": ["governance", "shared memory", "tenant", "retention", "audit"]},
}
RESOURCE_MAP = {
"PLAN": [
"references/templates/level_specifications.md",
"references/templates/template_guide.md",
"references/validation/template_compliance_contract.md",
],
"RESEARCH": [
"references/workflows/quick_reference.md",
"references/workflows/worked_examples.md",
"references/memory/epistemic_vectors.md",
],
"IMPLEMENT": [
"references/validation/validation_rules.md",
"references/validation/template_compliance_contract.md",
"references/templates/template_guide.md",
],
"DEBUG": [
"references/debugging/troubleshooting.md",
"references/workflows/quick_reference.md",
"manual_testing_playbook/MANUAL_TESTING_PLAYBOOK.md",
],
"COMPLETE": [
"references/validation/validation_rules.md",
"references/workflows/nested_changelog.md",
],
"MEMORY": [
"references/memory/memory_system.md",
"references/memory/save_workflow.md",
"references/memory/trigger_config.md",
],
"HANDOVER": [
"references/workflows/quick_reference.md",
],
"PHASE": [
"references/structure/phase_definitions.md",
"references/structure/sub_folder_versioning.md",
"references/validation/phase_checklists.md",
],
"RETRIEVAL_TUNING": [
"references/memory/embedding_resilience.md",
"references/memory/trigger_config.md",
],
"EVALUATION": [
"references/memory/epistemic_vectors.md",
"references/config/environment_variables.md",
"manual_testing_playbook/MANUAL_TESTING_PLAYBOOK.md",
],
"SCORING_CALIBRATION": [
"references/config/environment_variables.md",
],
"ROLLOUT_FLAGS": [
"references/config/environment_variables.md",
"feature_catalog/19--feature-flag-reference/",
],
"GOVERNANCE": [
"references/config/environment_variables.md",
],
}
COMMAND_BOOSTS = {
"/spec_kit:plan": "PLAN",
"/spec_kit:implement": "IMPLEMENT",
"/spec_kit:debug": "DEBUG",
"/spec_kit:complete": "COMPLETE",
"/spec_kit:handover": "HANDOVER",
"/spec_kit:plan :with-phases": "PHASE",
"/memory:search": "MEMORY",
"/memory:save": "MEMORY",
"/memory:manage": "MEMORY",
"/memory:learn": "MEMORY",
"/spec_kit:resume": "MEMORY",
"/memory:manage shared": "GOVERNANCE",
}
LOADING_LEVELS = {
"ALWAYS": [DEFAULT_RESOURCE],
"ON_DEMAND_KEYWORDS": ["deep dive", "full validation", "full checklist", "full template"],
"ON_DEMAND": [
"references/validation/phase_checklists.md",
"references/templates/template_guide.md",
],
}
def _task_text(task) -> str:
parts = [
str(getattr(task, "query", "")),
str(getattr(task, "text", "")),
" ".join(getattr(task, "keywords", []) or []),
str(getattr(task, "command", "")),
]
return " ".join(parts).lower()
def _guard_in_skill(relative_path: str) -> str:
"""Allow markdown loads only within this skill folder."""
resolved = (SKILL_ROOT / relative_path).resolve()
resolved.relative_to(SKILL_ROOT)
if resolved.suffix.lower() != ".md":
raise ValueError(f"Only markdown resources are routable: {relative_path}")
return resolved.relative_to(SKILL_ROOT).as_posix()
def discover_markdown_resources() -> set[str]:
"""Recursively discover routable markdown docs for this skill only."""
docs = []
for base in RESOURCE_BASES:
if base.exists():
docs.extend(p for p in base.rglob("*.md") if p.is_file())
return {doc.relative_to(SKILL_ROOT).as_posix() for doc in docs}
def score_intents(task) -> dict[str, float]:
"""Weighted scoring from request text, keywords, and explicit command boosts."""
text = _task_text(task)
scores = {intent: 0.0 for intent in INTENT_SIGNALS}
for intent, cfg in INTENT_SIGNALS.items():
for keyword in cfg["keywords"]:
if keyword in text:
scores[intent] += cfg["weight"]
command = str(getattr(task, "command", "")).lower()
for prefix, intent in COMMAND_BOOSTS.items():
if command.startswith(prefix):
scores[intent] += 6
return scores
def select_intents(scores: dict[str, float], ambiguity_delta: float = 1.0, max_intents: int = 2) -> list[str]:
"""Return primary intent and secondary intent when scores are close."""
ranked = sorted(scores.items(), key=lambda item: item[1], reverse=True)
if not ranked or ranked[0][1] <= 0:
return ["IMPLEMENT"]
selected = [ranked[0][0]]
if len(ranked) > 1:
primary_score = ranked[0][1]
secondary_intent, secondary_score = ranked[1]
if secondary_score > 0 and (primary_score - secondary_score) <= ambiguity_delta:
selected.append(secondary_intent)
return selected[:max_intents]
def route_speckit_resources(task):
"""Scoped, recursive, weighted, ambiguity-aware routing."""
inventory = discover_markdown_resources()
intents = select_intents(score_intents(task), ambiguity_delta=1.0)
loaded = []
seen = set()
def load_if_available(relative_path: str) -> None:
guarded = _guard_in_skill(relative_path)
if guarded in inventory and guarded not in seen:
load(guarded)
loaded.append(guarded)
seen.add(guarded)
# ALWAYS: base references for every invocation
for relative_path in LOADING_LEVELS["ALWAYS"]:
load_if_available(relative_path)
# CONDITIONAL: intent-scored resources
for intent in intents:
for relative_path in RESOURCE_MAP.get(intent, []):
load_if_available(relative_path)
# ON_DEMAND: explicit deep-dive requests
text = _task_text(task)
if any(keyword in text for keyword in LOADING_LEVELS["ON_DEMAND_KEYWORDS"]):
for relative_path in LOADING_LEVELS["ON_DEMAND"]:
load_if_available(relative_path)
if not loaded:
load_if_available(DEFAULT_RESOURCE)
return {"intents": intents, "resources": loaded}
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 | E) Phase folder (e.g., specs/NNN-name/001-phase/)
| 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().
Coordination Roots: For large multi-phase efforts, the root spec.md serves as a coordination document with point-in-time snapshots of directory counts and phase status.
Current tree truth takes precedence over historical synthesis (ref: ADR-001 pattern).
Complexity Detection (Option B Flow)
When user selects B) New, AI estimates complexity and recommends a level:
- Estimate LOC, files affected, risk factors
- Recommend level (1, 2, 3, or 3+) with rationale
- User accepts or overrides
- Run
./scripts/spec/create.sh --level N
Level Guidelines:
| LOC |
Level |
Template Folder |
| <100 |
1 |
templates/level_1/ |
| 100-499 |
2 |
templates/level_2/ |
| ≥500 |
3 |
templates/level_3/ |
| Complex |
3+ |
templates/level_3+/ |
See: quick_reference.md for detailed examples.
CLI Tool:
# Create spec folder with level 2 templates
./scripts/spec/create.sh "Add OAuth2 with MFA" --level 2
# Create spec folder with level 3+ (extended) templates
./scripts/spec/create.sh "Major platform migration" --level 3+
3-Level Progressive Enhancement (CORE + ADDENDUM v2.2)
Higher levels ADD VALUE, not just length. Each level builds on the previous:
Level 1 (Core): Essential what/why/how (~455 LOC)
↓ +Verify
Level 2 (Verification): +Quality gates, NFRs, edge cases (~875 LOC)
↓ +Arch
Level 3 (Full): +Architecture decisions, ADRs, risk matrix (~1090 LOC)
↓ +Govern
Level 3+ (Extended): +Enterprise governance, AI protocols (~1075 LOC)
| Level |
LOC Guidance |
Required Files |
What It ADDS |
| 1 |
<100 |
spec.md, plan.md, tasks.md, implementation-summary.md |
Essential what/why/how |
| 2 |
100-499 |
Level 1 + checklist.md |
Quality gates, verification, NFRs |
| 3 |
≥500 |
Level 2 + decision-record.md |
Architecture decisions, ADRs |
| 3+ |
Complex |
Level 3 + extended content |
Governance, approval workflow, AI protocols |
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: Saves pass the target spec folder alongside structured JSON via the generate-context script
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/dist/memory/generate-context.js
- NEVER: Create memory files manually via Write/Edit (AGENTS.md Memory Save Rule)
- JSON mode (PREFERRED): AI composes structured JSON → pass via
--json, --stdin, or temp file. The AI has strictly better information about its own session than any DB query.
- Structured JSON fields: The JSON payload supports optional structured summary fields that improve memory quality:
toolCalls[] — AI-composed tool call records (tool, inputSummary, outputSummary, status)
exchanges[] — Key conversation turns (userInput, assistantResponse, timestamp)
preflight / postflight — Epistemic baseline snapshots (knowledgeScore, uncertaintyScore, contextScore, gaps[], confidence)
sessionSummary — Free-text session narrative (used for conversation synthesis when conversation prompts are sparse)
- The AI has strictly better information about its own session than any DB extraction; these fields provide richer context at source.
- 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
Subfolder Support:
The generate-context script supports nested spec folder paths (parent/child format):
# Full nested path (parent/child)
node .opencode/skill/system-spec-kit/scripts/dist/memory/generate-context.js --json '{"specFolder":"system-spec-kit/121-script-audit","sessionSummary":"..."}' system-spec-kit/121-script-audit
# Bare child name (auto-searches all parents for unique match)
node .opencode/skill/system-spec-kit/scripts/dist/memory/generate-context.js --json '{"specFolder":"121-script-audit","sessionSummary":"..."}' 121-script-audit
# With specs/ prefix
node .opencode/skill/system-spec-kit/scripts/dist/memory/generate-context.js --json '{"specFolder":"specs/system-spec-kit/121-script-audit","sessionSummary":"..."}' specs/system-spec-kit/121-script-audit
# Flat folder
node .opencode/skill/system-spec-kit/scripts/dist/memory/generate-context.js --json '{"specFolder":"system-spec-kit","sessionSummary":"..."}' system-spec-kit
Memory files are always saved to the child folder's memory/ directory (e.g., specs/system-spec-kit/121-script-audit/memory/). If a bare child name matches multiple parents, the script reports an error and requires the full parent/child path.
Memory File Structure:
## Project Context
[Auto-generated summary of conversation and decisions]
## Project State Snapshot
- Phase: Implementation
- Last Action: Completed auth middleware
- Next Action: Add unit tests for login flow
- Blockers: None
## Key Artifacts
- Modified: src/middleware/auth.ts
- Created: src/utils/jwt.ts
Spec Kit Memory System (Integrated)
Context preservation across sessions via 5-channel hybrid retrieval (vector, FTS5, BM25, graph, and degree) with Reciprocal Rank Fusion, intent-aware routing, and post-fusion reranking/filtering.
Server: @spec-kit/mcp-server v1.7.2 — context-server.ts with 43 MCP tools across 7 layers. The tool surface is defined in mcp_server/tool-schemas.ts.
Memory Commands: 4 memory slash commands (/memory:save, /memory:manage, /memory:learn, /memory:search) cover the memory command surface, with shared-memory operations available under /memory:manage shared, while /spec_kit:resume owns session recovery through the broader memory/session recovery stack. The /memory:search command covers all analysis and retrieval workflows. See .opencode/command/memory/ and .opencode/command/spec_kit/resume.md for command documentation.
MCP Tools (18 most-used of 43 total — see memory_system.md for full reference):
| Tool |
Layer |
Purpose |
memory_context() |
L1 |
Unified entry point — modes: auto, quick, deep, focused, resume |
memory_search() |
L2 |
5-channel hybrid retrieval with intent-aware routing, channel normalization, graph/degree signals, reranking, and filtered output |
memory_quick_search() |
L2 |
Simplified search (query + optional spec folder) |
memory_match_triggers() |
L2 |
Trigger matching + cognitive (decay, tiers, co-activation) |
memory_save() |
L2 |
Index a memory file with pre-flight validation |
memory_list() |
L3 |
Browse stored memories with pagination (parent rows by default) |
memory_delete() |
L4 |
Delete memories by ID or spec folder |
checkpoint_create() |
L5 |
Create gzip-compressed checkpoint snapshot |
checkpoint_restore() |
L5 |
Transaction-wrapped restore with rollback |
memory_stats() |
L3 |
System statistics and memory counts |
memory_health() |
L3 |
Diagnostics: orphan detection, index consistency |
shared_memory_status() |
L5 |
Shared-memory subsystem status check |
memory_index_scan() |
L7 |
Workspace scanning and re-indexing |
checkpoint_list() |
L5 |
List available checkpoint snapshots |
checkpoint_delete() |
L5 |
Delete checkpoint by name (with confirmName safety) |
shared_memory_enable() |
L5 |
Enable shared-memory collaboration subsystem |
shared_space_upsert() |
L5 |
Create or update shared collaboration space |
shared_space_membership_set() |
L5 |
Set membership for shared collaboration space |
Search architecture: The search pipeline uses a 4-stage architecture (candidate generation → fusion → reranking → filtering). Current retrieval uses five channels, normalizes fallback thresholds correctly, keeps disabled channels disabled through fallback, defers irreversible confidence truncation until after reranking, and enforces token budgets using actual post-truncation counts. See search/README.md for pipeline details, scoring algorithms, and graph signal features.
memory_context() — Mode Routing:
| Mode |
Token Budget |
When mode=auto: Intent Routing |
quick |
800 |
— |
deep |
3500 |
add_feature, refactor, security_audit |
focused |
3000 |
fix_bug, understand |
resume |
1200 |
— |
memory_search() — Key Rules:
- REQUIRED:
query (string) OR concepts (2-5 strings). specFolder alone causes E040 error.
- Use
anchors with includeContent: true for token-efficient section retrieval (~90% savings).
- Intent weights auto-adjust scoring:
fix_bug boosts recency, security_audit boosts importance, refactor/understand boost similarity.
- Full parameter reference: See memory_system.md
memory_save() — Save-Time Processing:
- Runs a pre-storage quality gate (threshold 0.4 signal density). Low-quality saves receive warnings or rejection when strict. See
SPECKIT_SAVE_QUALITY_GATE flag.
- An exception path allows short decision-type memories to bypass the length gate when SPECKIT_SAVE_QUALITY_GATE_EXCEPTIONS=true and at least two structural signals are present.
- Similar existing memories are auto-merged via reconsolidation (≥0.88 similarity). The save may update an existing memory instead of creating a new one. See
SPECKIT_RECONSOLIDATION flag.
- A verify-fix-verify loop auto-corrects trigger phrases, anchors, and token budget (up to 2 retries).
- Preflight parses are revalidated inside the write lock when file contents change, and duplicate short-circuits verify stored content before trusting a stale hash hit.
- Delete and replacement paths now treat vector cleanup and projection replacement as integrity-critical instead of best-effort, so stale vector/projection rows do not silently survive successful writes.
- Entities are extracted and linked cross-document at save time. See
SPECKIT_AUTO_ENTITIES and SPECKIT_ENTITY_LINKING flags.
- Governed save and retrieval flows can carry
tenantId, userId, agentId, and sharedSpaceId so private, agent-scoped, and shared-space memory boundaries stay aligned end to end.
- Shared-memory collaboration is opt-in: use
/memory:manage shared to enable rollout, create spaces, and manage deny-by-default memberships before relying on shared-space save or retrieval flows.
Epistemic Learning: Use task_preflight() before and task_postflight() after implementation to measure knowledge gains. Learning Index: LI = (KnowledgeDelta × 0.4) + (UncertaintyReduction × 0.35) + (ContextImprovement × 0.25). Review trends via memory_get_learning_history(). See epistemic_vectors.md.
Key Concepts:
- Constitutional tier — 3.0x search boost + 2.0x importance multiplier; merged into normal scoring pipeline
- Document-type scoring — 10 indexed document types with multipliers: spec (1.4x), plan (1.3x), constitutional (2.0x), decision_record (1.4x), tasks (1.1x), implementation_summary (1.1x), scratch (0.6x), checklist (1.0x), handover (1.0x), memory (1.0x). README files and skill-doc trees (
sk-*, including references/ and assets/) are excluded from memory indexing.
- Decay scoring — FSRS v4 power-law model; recent memories rank higher
- Import-path hardening — MCP import paths are validated for memory runtime modules (context server and attention decay wiring)
- Metadata preservation —
memory_save update/reinforce paths preserve document_type and spec_level with synchronized vector-index metadata
- Descriptive memory titles —
MEMORY_TITLE is derived from the content slug via generateContentSlug() and slugToTitle(), producing unique and deterministic H1 headings. The parser falls back to feature/overview content when the top heading is generic
- Causal edge stability — conflict-update semantics maintain stable causal edge IDs during re-link and graph maintenance
- Real-time sync — Use
memory_save or memory_index_scan after creating files
- Checkpoints — Gzip-compressed JSON snapshots of memory_index + working_memory; max 10 stored; transaction-wrapped restore
- Indexing persistence — After
generate-context.js, call memory_index_scan() or memory_save() for immediate MCP visibility
- Artifact routing — 9 artifact classes (spec, plan, tasks, checklist, decision-record, implementation-summary, memory, research, unknown) with per-type retrieval strategies applied at query time
- Adaptive fusion — Intent-aware weighted RRF with 7 task-type profiles (fix_bug, add_feature, understand, refactor, security_audit, find_spec, find_decision), plus corrected channel fallback and normalization behavior in the live hybrid pipeline
- Adaptive ranking — Feedback-driven shadow ranking that accumulates access/outcome/correction signals and applies bounded score deltas (±0.08 max) per memory. Each signal event carries an optional
query field for per-query attribution. Runs silently in shadow mode by default; promote to active ranking via SPECKIT_MEMORY_ADAPTIVE_MODE=promoted. Thresholds persist to SQLite with last_tune_watermark idempotency. Enable with SPECKIT_MEMORY_ADAPTIVE_RANKING=true.
- Causal graph diagnostics —
memory_drift_why() now wraps traversal reads in a read transaction and returns truncation metadata when per-node edge caps make lineage incomplete
- Eval guardrails — Ablation reporting preserves per-channel dashboard breakdowns, treats missing query IDs explicitly, and avoids persisting synthetic zeroed token-usage snapshots as if they were measured results
- Runtime-resolved flags — Long-lived MCP processes re-read rollout and scoring flags at runtime for graph-walk rollout, co-activation, relation handling, and related search toggles instead of freezing values at import time
- Retrieval trace — Typed ContextEnvelope wraps every retrieval response with pipeline stages and a DegradedModeContract describing fallback behavior
- Mutation ledger — Append-only audit trail for all memory mutations (create, update, delete, reinforce); implemented via SQLite triggers; queryable for compliance and rollback
- Retrieval telemetry — 4-dimension metrics (latency, retrieval mode, fallback activation, quality score) plus Hydra architecture metadata. Enabled only when
SPECKIT_EXTENDED_TELEMETRY=true (default: off)
- Hydra roadmap metadata —
SPECKIT_MEMORY_ROADMAP_PHASE / SPECKIT_HYDRA_PHASE plus canonical SPECKIT_MEMORY_* and legacy SPECKIT_HYDRA_* capability flags annotate telemetry, eval baselines, and migration checkpoint sidecars. Note: SPECKIT_MEMORY_ADAPTIVE_RANKING=true does affect live retrieval (shadow or promoted ranking stage); the remaining roadmap flags are metadata-only.
- Feature catalog — 291 documented features across 22 categories (
feature_catalog/01--retrieval/ through 22--context-preservation-and-code-graph/) document every MCP server feature with current-reality status, source files, and catalog references. Use for audit, alignment checks, and understanding what exists. See feature_catalog/
- Manual testing playbook — Operator-facing validation matrix covering existing (
EX-*) and new (NEW-*) features with deterministic prompts, execution sequences, and pass/fail triage. Includes review protocol and subagent utilization ledger. See manual_testing_playbook/
- Validation scoring —
wasUseful=false applies a demotion penalty to memory scores; 5+ positive validations may promote a memory's importance tier
- Tree-thinning threshold — 150 tokens with merge group cap of 3 for improved file visibility in memory context
- JSON-mode conversation synthesis — When conversation prompts are sparse (e.g., JSON-mode captures with minimal exchange data), conversation content is synthesized from
sessionSummary field
- Decision deduplication — String-form decisions produce deduplicated CONTEXT/RATIONALE/CHOSEN values in memory output
- Structural blocker detection — Structural pattern detection identifies blockers (avoiding false positives from broad keyword matching)
Feature Flags:
Flags below describe live runtime behavior. Several retrieval and scoring controls are resolved at call time rather than captured once at module import, so changing process.env affects long-running MCP processes without a code reload.
| Flag |
Default |
Effect |
SPECKIT_ADAPTIVE_FUSION |
on |
Enables intent-aware weighted RRF with 7 task-type profiles in memory_search() (set false to disable) |
SPECKIT_EXTENDED_TELEMETRY |
off |
Emits 4-dimension retrieval metrics (latency, mode, fallback, quality) plus architecture metadata when explicitly set to true |
SPECKIT_INDEX_SPEC_DOCS |
on |
Gates spec document indexing in memory_index_scan(). When enabled, discovers and indexes spec folder documents (specs, plans, tasks, etc.) with document-type scoring multipliers. Set SPECKIT_INDEX_SPEC_DOCS=false to disable. |
SPECKIT_SAVE_QUALITY_GATE |
on |
Pre-storage quality gate rejects content below 0.4 signal density (14-day warn-only period after activation) |
SPECKIT_RECONSOLIDATION |
off |
Auto-merges similar memories on save when similarity ≥0.88; supersedes at 0.75-0.88 when explicitly enabled |
SPECKIT_NEGATIVE_FEEDBACK |
on |
wasUseful=false applies score demotion with 30-day recovery window |
SPECKIT_LEARN_FROM_SELECTION |
on |
Tracks which search results are used and boosts them in future searches |
SPECKIT_EMBEDDING_EXPANSION |
on |
Expands queries with semantic neighbors before vector search |
SPECKIT_AUTO_ENTITIES |
on |
Extracts entities at save time for cross-document linking |
SPECKIT_ENTITY_LINKING |
on |
Links memories sharing extracted entities during search |
SPECKIT_QUALITY_LOOP |
off |
Enables verify-fix-verify quality loop on save with up to 2 autofix retries |
SPECKIT_RELATIONS |
on |
Correction tracking with undo semantics (superseded/deprecated/refined/merged). Graduated to default ON |
SPECKIT_STRICT_SCHEMAS |
on |
Strict Zod validation for all 43 MCP tools; rejects hallucinated parameters |
SPECKIT_DEGREE_BOOST |
on |
Typed weighted-degree channel in graph signal scoring |
SPECKIT_GRAPH_SIGNALS |
on |
Graph momentum and causal depth scoring signals |
SPECKIT_COMMUNITY_DETECTION |
on |
Community detection clustering for graph-aware retrieval |
SPECKIT_CAUSAL_BOOST |
on |
Causal neighbor boost and injection in scoring |
SPECKIT_GRAPH_UNIFIED |
on |
Unified graph retrieval with deterministic ranking and explainability |
SPECKIT_SCORE_NORMALIZATION |
on |
Min-max score normalization across channels |
SPECKIT_CLASSIFICATION_DECAY |
on |
Classification-based decay rates by memory type |
SPECKIT_INTERFERENCE_SCORE |
on |
Interference detection scoring between similar memories |
SPECKIT_FOLDER_SCORING |
on |
Folder-level relevance scoring boost |
SPECKIT_SHADOW_SCORING |
off |
Shadow attribution logging (comparison path disabled; attribution tracking only) |
SPECKIT_DASHBOARD_LIMIT |
100 |
Row cap for reporting dashboard queries |
SPECKIT_CALIBRATED_OVERLAP_BONUS |
on |
Calibrated overlap bonus with query-aware scaling |
SPECKIT_RRF_K_EXPERIMENTAL |
on |
Per-intent NDCG@10-maximizing K selection over sweep grid |
SPECKIT_TYPED_TRAVERSAL |
on |
Sparse-first policy + intent-aware edge traversal in graph scoring |
SPECKIT_EMPTY_RESULT_RECOVERY_V1 |
on |
Structured recovery payloads for empty/weak search results |
SPECKIT_RESULT_CONFIDENCE_V1 |
on |
Per-result calibrated confidence from 4 weighted |
…(truncated)
1---2name: michelkerkmeester-opencode-spec-kit-framework-system-spec-ki3description: <!-- Keywords: spec-kit, speckit, documentation-workflow, spec-folder, template-enforcement, context-preservation, progressive-documentation, validation, spec-kit-memory, vector-search, hybrid-search, bm25, rrf-fusion, fsrs-decay, constitutional-tier, checkpoint, importance-tiers, cognitive-memory, co-activation, tiered-injection -->4---56<!-- Keywords: spec-kit, speckit, documentation-workflow, spec-folder, template-enforcement, context-preservation, progressive-documentation, validation, spec-kit-memory, vector-search, hybrid-search, bm25, rrf-fusion, fsrs-decay, constitutional-tier, checkpoint, importance-tiers, cognitive-memory, co-activation, tiered-injection -->78# Spec Kit - Mandatory Conversation Documentation910Orchestrates 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.111213<!-- ANCHOR:when-to-use -->14## 1. WHEN TO USE1516### What is a Spec Folder?1718A **spec folder** is a numbered directory (e.g., `007-auth-feature/`) that contains documentation for a single feature/task or a coordinated packet of related phase work:1920Spec folders may also be nested as coordination-root packets with direct-child phase folders (e.g., `specs/02--track/022-feature/011-phase/002-child/`).2122- **Purpose**: Track specifications, plans, tasks, and decisions for one unit of work23- **Location**: Under `specs/` using either `###-short-name/` at the root or nested packet paths for phased coordination24- **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, analyze, phase4142**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.57Status: ✅ This requirement applies immediately once file edits are requested.5859### Agent Exclusivity6061**⛔ CRITICAL:** `@speckit` is the ONLY agent permitted to create or substantively write spec folder documentation (*.md files).6263- **Requires @speckit:** spec.md, plan.md, tasks.md, checklist.md, decision-record.md, implementation-summary.md, and any other *.md in spec folders64- **Exceptions:**65 - `memory/` → uses generate-context.js script66 - `scratch/` → temporary workspace, any agent67 - `handover.md` → @handover agent only68 - `research/research.md` → @deep-research agent only69 - `debug-delegation.md` → @debug agent only7071Routing to `@general`, `@write`, or other agents for spec documentation is a **hard violation**. See constitutional memory: `speckit-exclusivity.md`7273### Utility Template Triggers7475| Template | Trigger Keywords | Action |76| --------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------- |77| `handover.md` | "handover", "next session", "continue later", "pass context", "ending session", "save state", "multi-session", "for next AI" | Suggest creating handover |78| `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` |7980**Rule:** When detected, proactively suggest the appropriate action.8182---8384<!-- /ANCHOR:when-to-use -->85<!-- ANCHOR:smart-routing -->86## 2. SMART ROUTING8788### Resource Domains8990The router discovers markdown resources recursively from `references/` and `assets/` and then applies intent scoring from `RESOURCE_MAP`. Keep this section domain-focused rather than static file inventories.9192- `references/memory/` for context retrieval, save workflows, trigger behavior, and indexing.93- `references/templates/` for level selection, template composition, and structure guides.94- `references/validation/` for checklist policy, verification rules, decision formats, and template compliance contracts.95- `references/structure/` for folder organization and sub-folder versioning.96- `references/workflows/` for command workflows and worked examples.97- `references/debugging/` for troubleshooting and root-cause methodology.98- `references/config/` for runtime environment configuration.99100### Template and Script Sources of Truth101102- Level definitions and template size guidance: [level_specifications.md](./references/templates/level_specifications.md)103- Template usage and composition rules: [template_guide.md](./references/templates/template_guide.md)104- Use `templates/level_N/` for operational templates; `core/` and `addendum/` remain composition inputs.105- Use `templates/changelog/` for packet-local nested changelog generation at completion time.106- Script architecture, build outputs, and runtime entrypoints: [scripts/README.md](./scripts/README.md)107- Memory save JSON schema and workflow contracts: [save_workflow.md](./references/memory/save_workflow.md)108- Nested packet changelog workflow: [nested_changelog.md](./references/workflows/nested_changelog.md)109110Primary operational scripts:111- `spec/validate.sh`112- `spec/create.sh`113- `spec/archive.sh`114- `spec/check-completion.sh`115- `spec/recommend-level.sh`116- `templates/compose.sh`117118### Resource Loading Levels119120| Level | When to Load | Resources |121| ----------- | -------------------------- | ---------------------------- |122| ALWAYS | Every skill invocation | Shared patterns + SKILL.md |123| CONDITIONAL | If intent signals match | Intent-mapped references |124| ON_DEMAND | Only on explicit request | Deep-dive quality standards |125126`references/workflows/quick_reference.md` is the primary first-touch command surface. Keep the compact `spec_kit` and `memory` command map there, and use this file only to point readers to it rather than duplicating the full matrix.127128### Smart Router Pseudocode129130The authoritative routing logic for scoped loading, weighted intent scoring, and ambiguity handling.131132```python133from pathlib import Path134135SKILL_ROOT = Path(__file__).resolve().parent136RESOURCE_BASES = (SKILL_ROOT / "references", SKILL_ROOT / "assets")137DEFAULT_RESOURCE = "references/workflows/quick_reference.md"138139INTENT_SIGNALS = {140 "PLAN": {"weight": 3, "keywords": ["plan", "design", "new spec", "level selection", "option b"]},141 "RESEARCH": {"weight": 3, "keywords": ["investigate", "explore", "analyze", "prior work", "evidence"]},142 "IMPLEMENT": {"weight": 3, "keywords": ["implement", "build", "execute", "workflow"]},143 "DEBUG": {"weight": 4, "keywords": ["stuck", "error", "not working", "failed", "debug"]},144 "COMPLETE": {"weight": 4, "keywords": ["done", "complete", "finish", "verify", "checklist"]},145 "MEMORY": {"weight": 4, "keywords": ["memory", "save context", "resume", "checkpoint", "context"]},146 "HANDOVER": {"weight": 4, "keywords": ["handover", "continue later", "next session", "pause"]},147 "PHASE": {"weight": 4, "keywords": ["phase", "decompose", "split", "workstream", "multi-phase", "phased approach", "phased", "multi-session"]},148 "RETRIEVAL_TUNING": {"weight": 3, "keywords": ["retrieval", "search tuning", "fusion", "scoring", "pipeline"]},149 "EVALUATION": {"weight": 3, "keywords": ["evaluate", "ablation", "benchmark", "baseline", "metrics"]},150 "SCORING_CALIBRATION": {"weight": 3, "keywords": ["calibration", "scoring", "normalization", "decay", "interference"]},151 "ROLLOUT_FLAGS": {"weight": 3, "keywords": ["feature flag", "rollout", "toggle", "enable", "disable"]},152 "GOVERNANCE": {"weight": 3, "keywords": ["governance", "shared memory", "tenant", "retention", "audit"]},153}154155RESOURCE_MAP = {156 "PLAN": [157 "references/templates/level_specifications.md",158 "references/templates/template_guide.md",159 "references/validation/template_compliance_contract.md",160 ],161 "RESEARCH": [162 "references/workflows/quick_reference.md",163 "references/workflows/worked_examples.md",164 "references/memory/epistemic_vectors.md",165 ],166 "IMPLEMENT": [167 "references/validation/validation_rules.md",168 "references/validation/template_compliance_contract.md",169 "references/templates/template_guide.md",170 ],171 "DEBUG": [172 "references/debugging/troubleshooting.md",173 "references/workflows/quick_reference.md",174 "manual_testing_playbook/MANUAL_TESTING_PLAYBOOK.md",175 ],176 "COMPLETE": [177 "references/validation/validation_rules.md",178 "references/workflows/nested_changelog.md",179 ],180 "MEMORY": [181 "references/memory/memory_system.md",182 "references/memory/save_workflow.md",183 "references/memory/trigger_config.md",184 ],185 "HANDOVER": [186 "references/workflows/quick_reference.md",187 ],188 "PHASE": [189 "references/structure/phase_definitions.md",190 "references/structure/sub_folder_versioning.md",191 "references/validation/phase_checklists.md",192 ],193 "RETRIEVAL_TUNING": [194 "references/memory/embedding_resilience.md",195 "references/memory/trigger_config.md",196 ],197 "EVALUATION": [198 "references/memory/epistemic_vectors.md",199 "references/config/environment_variables.md",200 "manual_testing_playbook/MANUAL_TESTING_PLAYBOOK.md",201 ],202 "SCORING_CALIBRATION": [203 "references/config/environment_variables.md",204 ],205 "ROLLOUT_FLAGS": [206 "references/config/environment_variables.md",207 "feature_catalog/19--feature-flag-reference/",208 ],209 "GOVERNANCE": [210 "references/config/environment_variables.md",211 ],212}213214COMMAND_BOOSTS = {215 "/spec_kit:plan": "PLAN",216 "/spec_kit:implement": "IMPLEMENT",217 "/spec_kit:debug": "DEBUG",218 "/spec_kit:complete": "COMPLETE",219 "/spec_kit:handover": "HANDOVER",220 "/spec_kit:plan :with-phases": "PHASE",221 "/memory:search": "MEMORY",222 "/memory:save": "MEMORY",223 "/memory:manage": "MEMORY",224 "/memory:learn": "MEMORY",225 "/spec_kit:resume": "MEMORY",226 "/memory:manage shared": "GOVERNANCE",227}228229LOADING_LEVELS = {230 "ALWAYS": [DEFAULT_RESOURCE],231 "ON_DEMAND_KEYWORDS": ["deep dive", "full validation", "full checklist", "full template"],232 "ON_DEMAND": [233 "references/validation/phase_checklists.md",234 "references/templates/template_guide.md",235 ],236}237238def _task_text(task) -> str:239 parts = [240 str(getattr(task, "query", "")),241 str(getattr(task, "text", "")),242 " ".join(getattr(task, "keywords", []) or []),243 str(getattr(task, "command", "")),244 ]245 return " ".join(parts).lower()246247def _guard_in_skill(relative_path: str) -> str:248 """Allow markdown loads only within this skill folder."""249 resolved = (SKILL_ROOT / relative_path).resolve()250 resolved.relative_to(SKILL_ROOT)251 if resolved.suffix.lower() != ".md":252 raise ValueError(f"Only markdown resources are routable: {relative_path}")253 return resolved.relative_to(SKILL_ROOT).as_posix()254255def discover_markdown_resources() -> set[str]:256 """Recursively discover routable markdown docs for this skill only."""257 docs = []258 for base in RESOURCE_BASES:259 if base.exists():260 docs.extend(p for p in base.rglob("*.md") if p.is_file())261 return {doc.relative_to(SKILL_ROOT).as_posix() for doc in docs}262263def score_intents(task) -> dict[str, float]:264 """Weighted scoring from request text, keywords, and explicit command boosts."""265 text = _task_text(task)266 scores = {intent: 0.0 for intent in INTENT_SIGNALS}267268 for intent, cfg in INTENT_SIGNALS.items():269 for keyword in cfg["keywords"]:270 if keyword in text:271 scores[intent] += cfg["weight"]272273 command = str(getattr(task, "command", "")).lower()274 for prefix, intent in COMMAND_BOOSTS.items():275 if command.startswith(prefix):276 scores[intent] += 6277278 return scores279280def select_intents(scores: dict[str, float], ambiguity_delta: float = 1.0, max_intents: int = 2) -> list[str]:281 """Return primary intent and secondary intent when scores are close."""282 ranked = sorted(scores.items(), key=lambda item: item[1], reverse=True)283 if not ranked or ranked[0][1] <= 0:284 return ["IMPLEMENT"]285286 selected = [ranked[0][0]]287 if len(ranked) > 1:288 primary_score = ranked[0][1]289 secondary_intent, secondary_score = ranked[1]290 if secondary_score > 0 and (primary_score - secondary_score) <= ambiguity_delta:291 selected.append(secondary_intent)292293 return selected[:max_intents]294295def route_speckit_resources(task):296 """Scoped, recursive, weighted, ambiguity-aware routing."""297 inventory = discover_markdown_resources()298 intents = select_intents(score_intents(task), ambiguity_delta=1.0)299 loaded = []300 seen = set()301302 def load_if_available(relative_path: str) -> None:303 guarded = _guard_in_skill(relative_path)304 if guarded in inventory and guarded not in seen:305 load(guarded)306 loaded.append(guarded)307 seen.add(guarded)308309 # ALWAYS: base references for every invocation310 for relative_path in LOADING_LEVELS["ALWAYS"]:311 load_if_available(relative_path)312313 # CONDITIONAL: intent-scored resources314 for intent in intents:315 for relative_path in RESOURCE_MAP.get(intent, []):316 load_if_available(relative_path)317318 # ON_DEMAND: explicit deep-dive requests319 text = _task_text(task)320 if any(keyword in text for keyword in LOADING_LEVELS["ON_DEMAND_KEYWORDS"]):321 for relative_path in LOADING_LEVELS["ON_DEMAND"]:322 load_if_available(relative_path)323324 if not loaded:325 load_if_available(DEFAULT_RESOURCE)326327 return {"intents": intents, "resources": loaded}328```329330---331332<!-- /ANCHOR:smart-routing -->333<!-- ANCHOR:how-it-works -->334## 3. HOW IT WORKS335336### Gate 3 Integration337338> **See AGENTS.md Section 2** for the complete Gate 3 flow. This skill implements that gate.339340When file modification detected, AI MUST ask:341342```343**Spec Folder** (required): A) Existing | B) New | C) Update related | D) Skip | E) Phase folder (e.g., specs/NNN-name/001-phase/)344```345346| Option | Description | Best For |347| --------------- | ---------------------------------- | ------------------------------- |348| **A) Existing** | Continue in related spec folder | Iterative work, related changes |349| **B) New** | Create `specs/###-name/` | New features, unrelated work |350| **C) Update** | Add to existing documentation | Extending existing docs |351| **D) Skip** | No spec folder (creates tech debt) | Trivial changes only |352353**Enforcement:** Constitutional-tier memory surfaces automatically via `memory_match_triggers()`.354355**Coordination Roots**: For large multi-phase efforts, the root `spec.md` serves as a coordination document with point-in-time snapshots of directory counts and phase status.356Current tree truth takes precedence over historical synthesis (ref: ADR-001 pattern).357358### Complexity Detection (Option B Flow)359360When user selects **B) New**, AI estimates complexity and recommends a level:3613621. Estimate LOC, files affected, risk factors3632. Recommend level (1, 2, 3, or 3+) with rationale3643. User accepts or overrides3654. Run `./scripts/spec/create.sh --level N`366367**Level Guidelines:**368369| LOC | Level | Template Folder |370| ------- | ----- | --------------------- |371| <100 | 1 | `templates/level_1/` |372| 100-499 | 2 | `templates/level_2/` |373| ≥500 | 3 | `templates/level_3/` |374| Complex | 3+ | `templates/level_3+/` |375376**See:** [quick_reference.md](./references/workflows/quick_reference.md) for detailed examples.377378**CLI Tool:**379```bash380# Create spec folder with level 2 templates381./scripts/spec/create.sh "Add OAuth2 with MFA" --level 2382383# Create spec folder with level 3+ (extended) templates384./scripts/spec/create.sh "Major platform migration" --level 3+385```386387### 3-Level Progressive Enhancement (CORE + ADDENDUM v2.2)388389Higher levels ADD VALUE, not just length. Each level builds on the previous:390391```392Level 1 (Core): Essential what/why/how (~455 LOC)393 ↓ +Verify394Level 2 (Verification): +Quality gates, NFRs, edge cases (~875 LOC)395 ↓ +Arch396Level 3 (Full): +Architecture decisions, ADRs, risk matrix (~1090 LOC)397 ↓ +Govern398Level 3+ (Extended): +Enterprise governance, AI protocols (~1075 LOC)399```400401| Level | LOC Guidance | Required Files | What It ADDS |402| ------ | ------------ | ----------------------------------------------------- | ------------------------------------------- |403| **1** | <100 | spec.md, plan.md, tasks.md, implementation-summary.md | Essential what/why/how |404| **2** | 100-499 | Level 1 + checklist.md | Quality gates, verification, NFRs |405| **3** | ≥500 | Level 2 + decision-record.md | Architecture decisions, ADRs |406| **3+** | Complex | Level 3 + extended content | Governance, approval workflow, AI protocols |407408**Level Selection Examples:**409410| Task | LOC Est. | Level | Rationale |411| -------------------- | -------- | ----- | ------------------------------ |412| Fix CSS alignment | 10 | 1 | Simple, low risk |413| Add form validation | 80 | 1-2 | Borderline, low complexity |414| Modal component | 200 | 2 | Multiple files, needs QA |415| Auth system refactor | 600 | 3 | Architecture change, high risk |416| Database migration | 150 | 3 | High risk overrides LOC |417418**Override Factors (can push to higher level):**419- High complexity or architectural changes420- Risk (security, config cascades, authentication)421- Multiple systems affected (>5 files)422- Integration vs unit test requirements423424**Decision rule:** When in doubt → choose higher level. Better to over-document than under-document.425426### Checklist as Verification Tool (Level 2+)427428The `checklist.md` is an **ACTIVE VERIFICATION TOOL**, not passive documentation:429430| Priority | Meaning | Deferral Rules |431| -------- | ------------ | --------------------------------------- |432| **P0** | HARD BLOCKER | MUST complete, cannot defer |433| **P1** | Required | MUST complete OR user-approved deferral |434| **P2** | Optional | Can defer without approval |435436**AI Workflow:**4371. Load checklist.md at completion phase4382. Verify items in order: P0 → P1 → P24393. Mark `[x]` with evidence for each verified item4404. Cannot claim "done" until all P0/P1 items verified441442**Evidence formats:**443- `[Test: npm test - all passing]`444- `[File: src/auth.ts:45-67]`445- `[Commit: abc1234]`446- `[Screenshot: evidence/login-works.png]`447- `(verified by manual testing)`448- `(confirmed in browser console)`449450**Example checklist entry:**451```markdown452## P0 - Blockers453- [x] Auth flow working [Test: npm run test:auth - 12/12 passing]454- [x] No console errors [Screenshot: evidence/console-clean.png]455456## P1 - Required 457- [x] Unit tests added [File: tests/auth.test.ts - 8 new tests]458- [ ] Documentation updated [DEFERRED: Will complete in follow-up PR]459```460461### Folder Naming Convention462463**Format:** `specs/###-short-name/`464465**Rules:**466- 2-3 words (shorter is better)467- Lowercase, hyphen-separated468- Action-noun structure469- 3-digit padding: `001`, `042`, `099` (no padding past 999)470471**Good examples:** `fix-typo`, `add-auth`, `mcp-code-mode`, `cli-codex`472**Bad examples:** `new-feature-implementation`, `UpdateUserAuthSystem`, `fix_bug`473474**Find next number:**475```bash476ls -d specs/[0-9]*/ | sed 's/.*\/\([0-9]*\)-.*/\1/' | sort -n | tail -1477```478479### Sub-Folder Versioning480481When reusing spec folders with existing content:482- Trigger: Option A selected + root-level content exists483- Pattern: `001-original/`, `002-new-work/`, `003-another/`484- Memory: Each sub-folder has independent `memory/` directory485- Tracking: Saves pass the target spec folder alongside structured JSON via the generate-context script486487**Example structure:**488```489specs/007-auth-system/490├── 001-initial-implementation/491│ ├── spec.md492│ ├── plan.md493│ └── memory/494├── 002-oauth-addition/495│ ├── spec.md496│ ├── plan.md497│ └── memory/498└── 003-security-audit/499 ├── spec.md500 └── memory/501```502503**Full documentation:** See [sub_folder_versioning.md](./references/structure/sub_folder_versioning.md)504505### Context Preservation506507**Manual context save (MANDATORY workflow):**508- Trigger: `/memory:save`, "save context", or "save memory"509- **MUST use:** `node .opencode/skill/system-spec-kit/scripts/dist/memory/generate-context.js`510- **NEVER:** Create memory files manually via Write/Edit (AGENTS.md Memory Save Rule)511- **JSON mode (PREFERRED):** AI composes structured JSON → pass via `--json`, `--stdin`, or temp file. The AI has strictly better information about its own session than any DB query.512- **Structured JSON fields:** The JSON payload supports optional structured summary fields that improve memory quality:513 - `toolCalls[]` — AI-composed tool call records (`tool`, `inputSummary`, `outputSummary`, `status`)514 - `exchanges[]` — Key conversation turns (`userInput`, `assistantResponse`, `timestamp`)515 - `preflight` / `postflight` — Epistemic baseline snapshots (`knowledgeScore`, `uncertaintyScore`, `contextScore`, `gaps[]`, `confidence`)516 - `sessionSummary` — Free-text session narrative (used for conversation synthesis when conversation prompts are sparse)517 - The AI has strictly better information about its own session than any DB extraction; these fields provide richer context at source.518- Location: `specs/###-folder/memory/`519- Filename: `DD-MM-YY_HH-MM__topic.md` (auto-generated by script)520- Content includes: PROJECT STATE SNAPSHOT with Phase, Last Action, Next Action, Blockers521522**Subfolder Support:**523524The generate-context script supports nested spec folder paths (parent/child format):525526```bash527# Full nested path (parent/child)528node .opencode/skill/system-spec-kit/scripts/dist/memory/generate-context.js --json '{"specFolder":"system-spec-kit/121-script-audit","sessionSummary":"..."}' system-spec-kit/121-script-audit529530# Bare child name (auto-searches all parents for unique match)531node .opencode/skill/system-spec-kit/scripts/dist/memory/generate-context.js --json '{"specFolder":"121-script-audit","sessionSummary":"..."}' 121-script-audit532533# With specs/ prefix534node .opencode/skill/system-spec-kit/scripts/dist/memory/generate-context.js --json '{"specFolder":"specs/system-spec-kit/121-script-audit","sessionSummary":"..."}' specs/system-spec-kit/121-script-audit535536# Flat folder537node .opencode/skill/system-spec-kit/scripts/dist/memory/generate-context.js --json '{"specFolder":"system-spec-kit","sessionSummary":"..."}' system-spec-kit538```539540Memory files are always saved to the child folder's `memory/` directory (e.g., `specs/system-spec-kit/121-script-audit/memory/`). If a bare child name matches multiple parents, the script reports an error and requires the full `parent/child` path.541542**Memory File Structure:**543```markdown544## Project Context545[Auto-generated summary of conversation and decisions]546547## Project State Snapshot548- Phase: Implementation549- Last Action: Completed auth middleware550- Next Action: Add unit tests for login flow551- Blockers: None552553## Key Artifacts554- Modified: src/middleware/auth.ts555- Created: src/utils/jwt.ts556```557558### Spec Kit Memory System (Integrated)559560Context preservation across sessions via 5-channel hybrid retrieval (vector, FTS5, BM25, graph, and degree) with Reciprocal Rank Fusion, intent-aware routing, and post-fusion reranking/filtering.561562**Server:** `@spec-kit/mcp-server` v1.7.2 — `context-server.ts` with 43 MCP tools across 7 layers. The tool surface is defined in `mcp_server/tool-schemas.ts`.563564**Memory Commands:** 4 memory slash commands (`/memory:save`, `/memory:manage`, `/memory:learn`, `/memory:search`) cover the memory command surface, with shared-memory operations available under `/memory:manage shared`, while `/spec_kit:resume` owns session recovery through the broader memory/session recovery stack. The `/memory:search` command covers all analysis and retrieval workflows. See `.opencode/command/memory/` and `.opencode/command/spec_kit/resume.md` for command documentation.565566**MCP Tools (18 most-used of 43 total — see [memory_system.md](./references/memory/memory_system.md) for full reference):**567568| Tool | Layer | Purpose |569| ------------------------------- | ----- | ------------------------------------------------- |570| `memory_context()` | L1 | Unified entry point — modes: auto, quick, deep, focused, resume |571| `memory_search()` | L2 | 5-channel hybrid retrieval with intent-aware routing, channel normalization, graph/degree signals, reranking, and filtered output |572| `memory_quick_search()` | L2 | Simplified search (query + optional spec folder) |573| `memory_match_triggers()` | L2 | Trigger matching + cognitive (decay, tiers, co-activation) |574| `memory_save()` | L2 | Index a memory file with pre-flight validation |575| `memory_list()` | L3 | Browse stored memories with pagination (parent rows by default) |576| `memory_delete()` | L4 | Delete memories by ID or spec folder |577| `checkpoint_create()` | L5 | Create gzip-compressed checkpoint snapshot |578| `checkpoint_restore()` | L5 | Transaction-wrapped restore with rollback |579| `memory_stats()` | L3 | System statistics and memory counts |580| `memory_health()` | L3 | Diagnostics: orphan detection, index consistency |581| `shared_memory_status()` | L5 | Shared-memory subsystem status check |582| `memory_index_scan()` | L7 | Workspace scanning and re-indexing |583| `checkpoint_list()` | L5 | List available checkpoint snapshots |584| `checkpoint_delete()` | L5 | Delete checkpoint by name (with confirmName safety)|585| `shared_memory_enable()` | L5 | Enable shared-memory collaboration subsystem |586| `shared_space_upsert()` | L5 | Create or update shared collaboration space |587| `shared_space_membership_set()` | L5 | Set membership for shared collaboration space |588589> **Search architecture:** The search pipeline uses a 4-stage architecture (candidate generation → fusion → reranking → filtering). Current retrieval uses five channels, normalizes fallback thresholds correctly, keeps disabled channels disabled through fallback, defers irreversible confidence truncation until after reranking, and enforces token budgets using actual post-truncation counts. See [search/README.md](./mcp_server/lib/search/README.md) for pipeline details, scoring algorithms, and graph signal features.590591**memory_context() — Mode Routing:**592593| Mode | Token Budget | When `mode=auto`: Intent Routing |594| --- | --- | --- |595| `quick` | 800 | — |596| `deep` | 3500 | `add_feature`, `refactor`, `security_audit` |597| `focused` | 3000 | `fix_bug`, `understand` |598| `resume` | 1200 | — |599600**memory_search() — Key Rules:**601- **REQUIRED:** `query` (string) OR `concepts` (2-5 strings). `specFolder` alone causes E040 error.602- Use `anchors` with `includeContent: true` for token-efficient section retrieval (~90% savings).603- Intent weights auto-adjust scoring: `fix_bug` boosts recency, `security_audit` boosts importance, `refactor`/`understand` boost similarity.604- **Full parameter reference:** See [memory_system.md](./references/memory/memory_system.md)605606**memory_save() — Save-Time Processing:**607- Runs a pre-storage quality gate (threshold 0.4 signal density). Low-quality saves receive warnings or rejection when strict. See `SPECKIT_SAVE_QUALITY_GATE` flag.608- An exception path allows short decision-type memories to bypass the length gate when SPECKIT_SAVE_QUALITY_GATE_EXCEPTIONS=true and at least two structural signals are present.609- Similar existing memories are auto-merged via reconsolidation (≥0.88 similarity). The save may update an existing memory instead of creating a new one. See `SPECKIT_RECONSOLIDATION` flag.610- A verify-fix-verify loop auto-corrects trigger phrases, anchors, and token budget (up to 2 retries).611- Preflight parses are revalidated inside the write lock when file contents change, and duplicate short-circuits verify stored content before trusting a stale hash hit.612- Delete and replacement paths now treat vector cleanup and projection replacement as integrity-critical instead of best-effort, so stale vector/projection rows do not silently survive successful writes.613- Entities are extracted and linked cross-document at save time. See `SPECKIT_AUTO_ENTITIES` and `SPECKIT_ENTITY_LINKING` flags.614- Governed save and retrieval flows can carry `tenantId`, `userId`, `agentId`, and `sharedSpaceId` so private, agent-scoped, and shared-space memory boundaries stay aligned end to end.615- Shared-memory collaboration is opt-in: use `/memory:manage shared` to enable rollout, create spaces, and manage deny-by-default memberships before relying on shared-space save or retrieval flows.616617**Epistemic Learning:** Use `task_preflight()` before and `task_postflight()` after implementation to measure knowledge gains. Learning Index: `LI = (KnowledgeDelta × 0.4) + (UncertaintyReduction × 0.35) + (ContextImprovement × 0.25)`. Review trends via `memory_get_learning_history()`. See [epistemic_vectors.md](./references/memory/epistemic_vectors.md).618619**Key Concepts:**620- **Constitutional tier** — 3.0x search boost + 2.0x importance multiplier; merged into normal scoring pipeline621- **Document-type scoring** — 10 indexed document types with multipliers: spec (1.4x), plan (1.3x), constitutional (2.0x), decision_record (1.4x), tasks (1.1x), implementation_summary (1.1x), scratch (0.6x), checklist (1.0x), handover (1.0x), memory (1.0x). README files and skill-doc trees (`sk-*`, including `references/` and `assets/`) are excluded from memory indexing.622- **Decay scoring** — FSRS v4 power-law model; recent memories rank higher623- **Import-path hardening** — MCP import paths are validated for memory runtime modules (context server and attention decay wiring)624- **Metadata preservation** — `memory_save` update/reinforce paths preserve `document_type` and `spec_level` with synchronized vector-index metadata625- **Descriptive memory titles** — `MEMORY_TITLE` is derived from the content slug via `generateContentSlug()` and `slugToTitle()`, producing unique and deterministic H1 headings. The parser falls back to feature/overview content when the top heading is generic626- **Causal edge stability** — conflict-update semantics maintain stable causal edge IDs during re-link and graph maintenance627- **Real-time sync** — Use `memory_save` or `memory_index_scan` after creating files628- **Checkpoints** — Gzip-compressed JSON snapshots of memory_index + working_memory; max 10 stored; transaction-wrapped restore629- **Indexing persistence** — After `generate-context.js`, call `memory_index_scan()` or `memory_save()` for immediate MCP visibility630- **Artifact routing** — 9 artifact classes (spec, plan, tasks, checklist, decision-record, implementation-summary, memory, research, unknown) with per-type retrieval strategies applied at query time631- **Adaptive fusion** — Intent-aware weighted RRF with 7 task-type profiles (fix_bug, add_feature, understand, refactor, security_audit, find_spec, find_decision), plus corrected channel fallback and normalization behavior in the live hybrid pipeline632- **Adaptive ranking** — Feedback-driven shadow ranking that accumulates access/outcome/correction signals and applies bounded score deltas (±0.08 max) per memory. Each signal event carries an optional `query` field for per-query attribution. Runs silently in shadow mode by default; promote to active ranking via `SPECKIT_MEMORY_ADAPTIVE_MODE=promoted`. Thresholds persist to SQLite with `last_tune_watermark` idempotency. Enable with `SPECKIT_MEMORY_ADAPTIVE_RANKING=true`.633- **Causal graph diagnostics** — `memory_drift_why()` now wraps traversal reads in a read transaction and returns truncation metadata when per-node edge caps make lineage incomplete634- **Eval guardrails** — Ablation reporting preserves per-channel dashboard breakdowns, treats missing query IDs explicitly, and avoids persisting synthetic zeroed token-usage snapshots as if they were measured results635- **Runtime-resolved flags** — Long-lived MCP processes re-read rollout and scoring flags at runtime for graph-walk rollout, co-activation, relation handling, and related search toggles instead of freezing values at import time636- **Retrieval trace** — Typed ContextEnvelope wraps every retrieval response with pipeline stages and a DegradedModeContract describing fallback behavior637- **Mutation ledger** — Append-only audit trail for all memory mutations (create, update, delete, reinforce); implemented via SQLite triggers; queryable for compliance and rollback638- **Retrieval telemetry** — 4-dimension metrics (latency, retrieval mode, fallback activation, quality score) plus Hydra architecture metadata. Enabled only when `SPECKIT_EXTENDED_TELEMETRY=true` (default: off)639- **Hydra roadmap metadata** — `SPECKIT_MEMORY_ROADMAP_PHASE` / `SPECKIT_HYDRA_PHASE` plus canonical `SPECKIT_MEMORY_*` and legacy `SPECKIT_HYDRA_*` capability flags annotate telemetry, eval baselines, and migration checkpoint sidecars. Note: `SPECKIT_MEMORY_ADAPTIVE_RANKING=true` does affect live retrieval (shadow or promoted ranking stage); the remaining roadmap flags are metadata-only.640- **Feature catalog** — 291 documented features across 22 categories (`feature_catalog/01--retrieval/` through `22--context-preservation-and-code-graph/`) document every MCP server feature with current-reality status, source files, and catalog references. Use for audit, alignment checks, and understanding what exists. See [feature_catalog/](./feature_catalog/)641- **Manual testing playbook** — Operator-facing validation matrix covering existing (`EX-*`) and new (`NEW-*`) features with deterministic prompts, execution sequences, and pass/fail triage. Includes review protocol and subagent utilization ledger. See [manual_testing_playbook/](./manual_testing_playbook/)642- **Validation scoring** — `wasUseful=false` applies a demotion penalty to memory scores; 5+ positive validations may promote a memory's importance tier643- **Tree-thinning threshold** — 150 tokens with merge group cap of 3 for improved file visibility in memory context644- **JSON-mode conversation synthesis** — When conversation prompts are sparse (e.g., JSON-mode captures with minimal exchange data), conversation content is synthesized from `sessionSummary` field645- **Decision deduplication** — String-form decisions produce deduplicated CONTEXT/RATIONALE/CHOSEN values in memory output646- **Structural blocker detection** — Structural pattern detection identifies blockers (avoiding false positives from broad keyword matching)647648**Feature Flags:**649650Flags below describe live runtime behavior. Several retrieval and scoring controls are resolved at call time rather than captured once at module import, so changing `process.env` affects long-running MCP processes without a code reload.651652| Flag | Default | Effect |653| ----------------------------- | ------- | ------------------------------------------------------------------------------------------- |654| `SPECKIT_ADAPTIVE_FUSION` | on | Enables intent-aware weighted RRF with 7 task-type profiles in `memory_search()` (set `false` to disable) |655| `SPECKIT_EXTENDED_TELEMETRY` | off | Emits 4-dimension retrieval metrics (latency, mode, fallback, quality) plus architecture metadata when explicitly set to `true` |656| `SPECKIT_INDEX_SPEC_DOCS` | on | Gates spec document indexing in `memory_index_scan()`. When enabled, discovers and indexes spec folder documents (specs, plans, tasks, etc.) with document-type scoring multipliers. Set `SPECKIT_INDEX_SPEC_DOCS=false` to disable. |657| `SPECKIT_SAVE_QUALITY_GATE` | on | Pre-storage quality gate rejects content below 0.4 signal density (14-day warn-only period after activation) |658| `SPECKIT_RECONSOLIDATION` | off | Auto-merges similar memories on save when similarity ≥0.88; supersedes at 0.75-0.88 when explicitly enabled |659| `SPECKIT_NEGATIVE_FEEDBACK` | on | `wasUseful=false` applies score demotion with 30-day recovery window |660| `SPECKIT_LEARN_FROM_SELECTION` | on | Tracks which search results are used and boosts them in future searches |661| `SPECKIT_EMBEDDING_EXPANSION` | on | Expands queries with semantic neighbors before vector search |662| `SPECKIT_AUTO_ENTITIES` | on | Extracts entities at save time for cross-document linking |663| `SPECKIT_ENTITY_LINKING` | on | Links memories sharing extracted entities during search |664| `SPECKIT_QUALITY_LOOP` | off | Enables verify-fix-verify quality loop on save with up to 2 autofix retries |665| `SPECKIT_RELATIONS` | on | Correction tracking with undo semantics (superseded/deprecated/refined/merged). Graduated to default ON |666| `SPECKIT_STRICT_SCHEMAS` | on | Strict Zod validation for all 43 MCP tools; rejects hallucinated parameters |667| `SPECKIT_DEGREE_BOOST` | on | Typed weighted-degree channel in graph signal scoring |668| `SPECKIT_GRAPH_SIGNALS` | on | Graph momentum and causal depth scoring signals |669| `SPECKIT_COMMUNITY_DETECTION` | on | Community detection clustering for graph-aware retrieval |670| `SPECKIT_CAUSAL_BOOST` | on | Causal neighbor boost and injection in scoring |671| `SPECKIT_GRAPH_UNIFIED` | on | Unified graph retrieval with deterministic ranking and explainability |672| `SPECKIT_SCORE_NORMALIZATION` | on | Min-max score normalization across channels |673| `SPECKIT_CLASSIFICATION_DECAY` | on | Classification-based decay rates by memory type |674| `SPECKIT_INTERFERENCE_SCORE` | on | Interference detection scoring between similar memories |675| `SPECKIT_FOLDER_SCORING` | on | Folder-level relevance scoring boost |676| `SPECKIT_SHADOW_SCORING` | off | Shadow attribution logging (comparison path disabled; attribution tracking only) |677| `SPECKIT_DASHBOARD_LIMIT` | 100 | Row cap for reporting dashboard queries |678| `SPECKIT_CALIBRATED_OVERLAP_BONUS` | on | Calibrated overlap bonus with query-aware scaling |679| `SPECKIT_RRF_K_EXPERIMENTAL` | on | Per-intent NDCG@10-maximizing K selection over sweep grid |680| `SPECKIT_TYPED_TRAVERSAL` | on | Sparse-first policy + intent-aware edge traversal in graph scoring |681| `SPECKIT_EMPTY_RESULT_RECOVERY_V1` | on | Structured recovery payloads for empty/weak search results |682| `SPECKIT_RESULT_CONFIDENCE_V1` | on | Per-result calibrated confidence from 4 weighted683684…(truncated)