Compare commits

...
Author SHA1 Message Date
Tabish Bidiwale 82ba1f504e merge: resolve conflicts with main branch 2025-09-09 14:12:05 +10:00
Tabish Bidiwale d54fcc97f2 docs: mark completed tasks for diff command removal 2025-09-09 14:07:52 +10:00
Tabish Bidiwale ebff738860 feat: remove diff command in favor of show command
The diff command added unnecessary complexity and duplicated functionality
already available through the show command. Users can now use:
- `openspec show <change>` for structured change viewing
- `openspec show <change> --json --deltas-only` for delta-only views
- Standard git diff or other tools for file comparisons

This change:
- Removes ~227 lines of code and the jest-diff dependency
- Simplifies the CLI interface
- Reduces maintenance burden
- Aligns with verb-first command structure
2025-09-09 14:05:41 +10:00
Tabish Bidiwale 1bdaeef4da Update README.md 2025-09-07 09:16:53 +10:00
Tabish Bidiwale 2921676e93 docs(readme): make alignment the central value proposition 2025-09-07 05:16:40 +10:00
Tabish Bidiwale 792129bfe3 docs(readme): highlight supported AI tools and emphasize universal interoperability 2025-09-07 05:10:46 +10:00
Tabish Bidiwale 715ff513e3 docs(readme): restructure for clarity - focus on AI alignment benefits and quick wins 2025-09-07 05:07:21 +10:00
Tabish Bidiwale f6913b7661 docs(readme): streamline content, focus on change management vs Kiro 2025-09-07 04:53:19 +10:00
Tabish Bidiwale 730bbc00af docs(readme): remove JSON for automation section 2025-09-07 04:46:18 +10:00
Tabish Bidiwale adfcc65b9f docs(readme): simplify getting started with clearer AI workflow steps 2025-09-07 04:41:56 +10:00
Tabish Bidiwale 590541277d docs(readme): fix getting started to show AI-native workflow, not manual file creation 2025-09-07 04:36:03 +10:00
Tabish Bidiwale 14e2cc628a docs(readme): enhance for public release with why, workflow diagram, AI integration, comparisons 2025-09-07 04:26:44 +10:00
Tabish Bidiwale 299171c5cb docs(readme): add CI, npm, Node, license, conventional commits badges 2025-09-07 03:57:33 +10:00
Tabish Bidiwale bb6aae0205 docs(license): add MIT license file 2025-09-07 03:32:27 +10:00
Tabish Bidiwale 23c0ab6358 docs(readme): improve onboarding, verb-first commands, examples, JSON usage, troubleshooting 2025-09-07 03:20:34 +10:00
Tabish Bidiwale 02fe5b3547 Merge pull request #56 from Fission-AI/fix-tests
fix(test): resolve CI test failures with proper build setup
2025-09-07 02:34:13 +10:00
Tabish Bidiwale 57216a7824 refactor(test): use vitest globalSetup for build instead of per-test builds 2025-09-07 02:16:17 +10:00
Tabish Bidiwale 6e210cf084 fix(test): ensure dist exists before spawning CLI subprocesses 2025-09-07 02:13:21 +10:00
Tabish Bidiwale 5c6ae8e407 Merge pull request #55 from Fission-AI/fix-tests
fix(ci): ensure build runs before tests in workflows
2025-09-07 02:04:04 +10:00
Tabish Bidiwale 5376030421 fix(ci): simplify to single Node version for faster CI 2025-09-07 01:56:00 +10:00
Tabish Bidiwale 7d735eb2d8 fix(ci): ensure build runs before tests in workflows 2025-09-07 01:45:11 +10:00
Tabish Bidiwale 4d55e9ac6d chore(ci): use NODE_AUTH_TOKEN auth, add debug, build before tests 2025-09-07 01:23:32 +10:00
Tabish Bidiwale 9d674b22a3 Fix provenance 2025-09-07 01:13:23 +10:00
Tabish Bidiwale 96458ced1f Update actions workflow 2025-09-07 01:01:55 +10:00
Tabish Bidiwale 3d8f2a5974 update workflow 2025-09-07 00:31:37 +10:00
Tabish Bidiwale 006676c973 chore(test): clarify vitest worker note and newline 2025-09-06 23:27:49 +10:00
Tabish Bidiwale 63f45c0fcf test(commands): isolate change command tests via temp fixtures 2025-09-06 23:27:42 +10:00
Tabish Bidiwale 522126a6ee fix(utils): harden item discovery for determinism 2025-09-06 23:27:33 +10:00
Tabish Bidiwale 23b8030494 fix(change): only list active changes with proposal.md 2025-09-06 23:26:51 +10:00
Tabish Bidiwale f70df96656 docs(changes): add tasks.md for improve-deterministic-tests 2025-09-06 23:20:03 +10:00
Tabish Bidiwale df12368f11 chore(changes): remove obsolete cli-list spec 2025-09-06 21:01:19 +10:00
Tabish Bidiwale acd1ca28f3 docs(changes): add deterministic tests proposal 2025-09-06 21:01:19 +10:00
Tabish Bidiwale aedf4a34af docs(release): add 0.1.0 notes 2025-09-06 21:01:19 +10:00
Tabish Bidiwale f0c52ac7e8 Merge pull request #54 from Fission-AI/changeset-release/main
chore(release): version packages
2025-09-06 14:56:28 +10:00
github-actions[bot] f933e9b144 Version Packages 2025-09-06 04:43:55 +00:00
Tabish Bidiwale 24b4866426 chore(changeset): seed release notes 2025-09-06 14:35:50 +10:00
Tabish Bidiwale b7899602b4 chore(ci): add release workflows 2025-09-06 14:32:32 +10:00
Tabish Bidiwale b66d914198 chore(changesets): add config and script 2025-09-06 02:52:02 +10:00
Tabish Bidiwale 9926103505 chore(pkg): scope to @fission-ai and set public 2025-09-06 02:34:11 +10:00
Tabish Bidiwale 873e45a996 Merge pull request #53 from Fission-AI/prepare-publish
build: prepare for package publish
2025-09-06 02:28:48 +10:00
Tabish Bidiwale 573afa0c65 prepare for package publish 2025-09-06 02:22:38 +10:00
Tabish Bidiwale 665d740adb Remove retrospective doc 2025-09-01 11:34:23 +10:00
Tabish Bidiwale c35dd38567 Test cursor rules 2025-08-27 21:20:37 +10:00
Tabish Bidiwale aa9e49612b Merge pull request #51 from Fission-AI/updating-agent-instructions
feat: streamline OpenSpec agent instructions by 48%
2025-08-27 20:59:31 +10:00
Tabish Bidiwale 36eb0bbbf5 feat: streamline OpenSpec agent instructions by 48%
- Restructured README.md with three-stage workflow front-loaded
- Reduced from 575 to 298 lines while adding comprehensive content
- Added clear decision trees and removed ambiguous conditions
- Documented all CLI commands with examples and debugging tips
- Added critical scenario formatting guidance (most common error)
- Created troubleshooting section with error solutions
- Updated CLAUDE.md template with streamlined, focused content
- Added "Before Any Task" checklist for context gathering
- Added spec discovery workflow to prevent duplicates
- Included tool selection matrix and best practices
2025-08-27 18:22:29 +10:00
Tabish Bidiwale d549cec121 Merge pull request #50 from Fission-AI/update-openspec-agent-instructions
Update OpenSpec agent instructions for clarity and completeness
2025-08-27 18:01:29 +10:00
Tabish Bidiwale 1a3bfae784 feat: add comprehensive retrospective-based improvements
Based on OPENSPEC_COMPREHENSIVE_RETROSPECTIVE.md analysis:

Added critical missing documentation:
- Scenario formatting requirements (#### Scenario: headers) - #1 pain point
- Complete spec file structure examples with ADDED/MODIFIED sections
- Delta file location and extraction explanation
- Debugging commands (show --json --deltas-only)
- Troubleshooting section with common errors and solutions

Expanded implementation:
- Added 2 new task sections (Spec File Documentation, Troubleshooting)
- Increased from 41 to 52 total implementation tasks
- Added critical items to CLAUDE.md template tasks

This directly addresses the retrospective's top issues:
1. Scenario format documentation (marked "COMPLETELY MISSING")
2. Complete spec file examples
3. Delta detection debugging
4. Silent parsing failure explanations
2025-08-25 15:31:35 +10:00
Tabish Bidiwale fae08072a9 feat: add explicit implementation workflow for Stage 2
- Add detailed implementation steps: read docs → implement → mark complete
- Emphasize reading proposal.md, design.md, and tasks.md first
- Require immediate task completion marking (no batching)
- Add rationale: prevents jumping straight to code without context
- Update tasks to include implementation workflow documentation

This ensures agents understand and follow the complete change properly
2025-08-25 15:25:49 +10:00
Tabish Bidiwale 07df6c97c9 feat: add comprehensive CLI documentation and spec discovery workflow
- Document all 9 primary OpenSpec commands with examples
- Add openspec list and list --specs prominently
- Add "Before Creating Specs" rule to check existing specs first
- Document all CLI flags (--json, --type, --skip-specs, etc.)
- Update tasks to include 9 CLI documentation items
- Add spec discovery workflow to prevent duplicate capabilities

This ensures AI agents have complete CLI knowledge and avoid spec fragmentation
2025-08-25 15:21:09 +10:00
Tabish Bidiwale 7b13a2de03 feat: enhance proposal with agent instruction best practices
- Add decision clarity improvements (decision trees, remove ambiguity)
- Include agent-specific sections (tool selection, error recovery, context management)
- Restructure with clear information hierarchy
- Add comprehensive implementation tasks (6 sections, 26 tasks)
- Update design with industry best practices rationale

Based on analysis of Claude Code, Cursor, and other coding agent patterns
2025-08-24 13:36:12 +10:00
Tabish Bidiwale 41fc14d360 fix: remove spec deltas - this is a tooling change not a capability
- Documentation updates are tooling/infrastructure changes
- No specs needed for OpenSpec's own instructions
- Will use --skip-specs flag when archiving
2025-08-24 13:28:22 +10:00
Tabish Bidiwale 7c0face31b feat: add change proposal to update OpenSpec agent instructions
- Create proposal for streamlining agent instructions
- Document three-stage workflow clearly
- Update CLI command documentation
- Add best practices for AI agents
- Include spec deltas for documentation requirements
2025-08-24 13:25:23 +10:00
Tabish Bidiwale 332816cc35 Merge pull request #48 from Fission-AI/archive-changes
archive: apply delta-based spec updates and archive changes\n\n- adop…
2025-08-20 03:12:58 +10:00
Tabish Bidiwale 7ced2a8791 archive: apply delta-based spec updates and archive changes\n\n- adopt-delta-based-changes: fix MODIFIED/ADDED headers; update specs; archive\n- add-zod-validation: mark cli-diff validation as ADDED; archive\n- adopt-verb-noun-cli-structure: move Flags to MODIFIED; archive\n\nAlso adjust openspec-conventions deltas to reflect existing headers. 2025-08-20 03:11:00 +10:00
Tabish Bidiwale a79b8b5c03 Merge pull request #47 from Fission-AI/fix-invalid-spec-files
fix: fix invalid files
2025-08-20 01:42:09 +10:00
Tabish Bidiwale 52d620e40e fix invalid files 2025-08-20 01:41:36 +10:00
Tabish Bidiwale 22082338fd Merge pull request #46 from Fission-AI/feat/adopt-verb-noun-cli-structure
Adopt verb-noun CLI structure
2025-08-20 01:06:28 +10:00
Tabish Bidiwale 01a2f5d600 Merge pull request #45 from Fission-AI/feat/improve-validation-error-messages
feat(validate): improve error messages with actionable guidance
2025-08-20 01:00:14 +10:00
Tabish Bidiwale 95d855d641 feat(validate): improve error messages with actionable guidance 2025-08-20 00:54:34 +10:00
100 changed files with 3950 additions and 1609 deletions
+6
View File
@@ -0,0 +1,6 @@
This directory is managed by Changesets.
- Add a changeset locally with `pnpm changeset`.
- The CI "Release (prepare)" workflow opens/updates a Version Packages PR.
- Publishing happens from a GitHub Release via the "Publish to npm" workflow.
+12
View File
@@ -0,0 +1,12 @@
{
"$schema": "https://unpkg.com/@changesets/config/schema.json",
"changelog": "@changesets/cli/changelog",
"commit": false,
"fixed": [],
"linked": [],
"access": "public",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": []
}
+302
View File
@@ -0,0 +1,302 @@
---
description: OpenSpec conventions and workflow for Cursor agents working in this repo
alwaysApply: false
---
# OpenSpec Rules for Cursor Agents
Instructions for AI coding assistants using OpenSpec for spec-driven development.
## Three-Stage Workflow
### Stage 1: Creating Changes
Create proposal when you need to:
- Add features or functionality
- Make breaking changes (API, schema)
- Change architecture or patterns
- Optimize performance (changes behavior)
- Update security patterns
Skip proposal for:
- Bug fixes (restore intended behavior)
- Typos, formatting, comments
- Dependency updates (non-breaking)
- Configuration changes
- Tests for existing behavior
### Stage 2: Implementing Changes
1. **Read proposal.md** - Understand what's being built
2. **Read design.md** (if exists) - Review technical decisions
3. **Read tasks.md** - Get implementation checklist
4. **Implement tasks sequentially** - Complete in order
5. **Mark complete immediately** - Update `- [x]` after each task
### Stage 3: Archiving Changes
After deployment, create separate PR to:
- Move `changes/[name]/` → `changes/archive/YYYY-MM-DD-[name]/`
- Update `specs/` if capabilities changed
- Use `openspec archive [change] --skip-specs` for tooling-only changes
## Before Any Task
**Context Checklist:**
- [ ] Read relevant specs in `specs/[capability]/spec.md`
- [ ] Check pending changes in `changes/` for conflicts
- [ ] Read `openspec/project.md` for conventions
- [ ] Run `openspec list` to see active changes
- [ ] Run `openspec list --specs` to see existing capabilities
**Before Creating Specs:**
- Always check if capability already exists
- Prefer modifying existing specs over creating duplicates
- Use `openspec show [spec]` to review current state
## Quick Start
### CLI Commands
```bash
# Essential commands
openspec list # List active changes
openspec list --specs # List specifications
openspec show [item] # Display change or spec
openspec diff [change] # Show spec differences
openspec validate [item] # Validate changes or specs
openspec archive [change] # Archive after deployment
# Project management
openspec init [path] # Initialize OpenSpec
openspec update [path] # Update instruction files
# Interactive mode
openspec show # Prompts for selection
openspec validate # Bulk validation mode
# Debugging
openspec show [change] --json --deltas-only
openspec validate [change] --strict
```
### Command Flags
- `--json` - Machine-readable output
- `--type change|spec` - Disambiguate items
- `--strict` - Comprehensive validation
- `--no-interactive` - Disable prompts
- `--skip-specs` - Archive without spec updates
## Directory Structure
```
openspec/
├── project.md # Project conventions
├── specs/ # Current truth - what IS built
│ └── [capability]/ # Single focused capability
│ ├── spec.md # Requirements and scenarios
│ └── design.md # Technical patterns
├── changes/ # Proposals - what SHOULD change
│ ├── [change-name]/
│ │ ├── proposal.md # Why, what, impact
│ │ ├── tasks.md # Implementation checklist
│ │ ├── design.md # Technical decisions (optional)
│ │ └── specs/ # Delta changes
│ │ └── [capability]/
│ │ └── spec.md # ADDED/MODIFIED/REMOVED
│ └── archive/ # Completed changes
```
## Creating Change Proposals
### Decision Tree
```
New request?
├─ Bug fix restoring spec behavior? → Fix directly
├─ Typo/format/comment? → Fix directly
├─ New feature/capability? → Create proposal
├─ Breaking change? → Create proposal
├─ Architecture change? → Create proposal
└─ Unclear? → Create proposal (safer)
```
### Proposal Structure
1. **Create directory:** `changes/[descriptive-name]/`
2. **Write proposal.md:**
```markdown
## Why
[1-2 sentences on problem/opportunity]
## What Changes
- [Bullet list of changes]
- [Mark breaking changes with **BREAKING**]
## Impact
- Affected specs: [list capabilities]
- Affected code: [key files/systems]
```
3. **Create spec deltas:** `specs/[capability]/spec.md`
```markdown
## ADDED Requirements
### Requirement: New Feature
The system SHALL provide...
#### Scenario: Success case
- **WHEN** user performs action
- **THEN** expected result
## MODIFIED Requirements
### Requirement: Existing Feature
[Complete modified requirement]
## REMOVED Requirements
### Requirement: Old Feature
**Reason**: [Why removing]
**Migration**: [How to handle]
```
4. **Create tasks.md:**
```markdown
## 1. Implementation
- [ ] 1.1 Create database schema
- [ ] 1.2 Implement API endpoint
- [ ] 1.3 Add frontend component
- [ ] 1.4 Write tests
```
## Spec File Format
### Critical: Scenario Formatting
**CORRECT** (use #### headers):
```markdown
#### Scenario: User login success
- **WHEN** valid credentials provided
- **THEN** return JWT token
```
**WRONG** (don't use bullets or bold):
```markdown
- **Scenario: User login** ❌
**Scenario**: User login ❌
### Scenario: User login ❌
```
Every requirement MUST have at least one scenario.
### Delta Operations
- `## ADDED Requirements` - New capabilities
- `## MODIFIED Requirements` - Changed behavior
- `## REMOVED Requirements` - Deprecated features
- `## RENAMED Requirements` - Name changes
Headers matched with `trim(header)` - whitespace ignored.
## Troubleshooting
### Common Errors
**"Change must have at least one delta"**
- Check `changes/[name]/specs/` exists with .md files
- Verify files have operation prefixes (## ADDED Requirements)
**"Requirement must have at least one scenario"**
- Check scenarios use `#### Scenario:` format (4 hashtags)
- Don't use bullet points or bold for scenario headers
**Silent scenario parsing failures**
- Exact format required: `#### Scenario: Name`
- Debug with: `openspec show [change] --json --deltas-only`
### Validation Tips
```bash
# Always use strict mode for comprehensive checks
openspec validate [change] --strict
# Debug delta parsing
openspec show [change] --json | jq '.deltas'
# Check specific requirement
openspec show [spec] --json -r 1
```
## Best Practices
### Simplicity First
- Default to <100 lines of new code
- Single-file implementations until proven insufficient
- Avoid frameworks without clear justification
- Choose boring, proven patterns
### Complexity Triggers
Only add complexity with:
- Performance data showing current solution too slow
- Concrete scale requirements (>1000 users, >100MB data)
- Multiple proven use cases requiring abstraction
### Clear References
- Use `file.ts:42` format for code locations
- Reference specs as `specs/auth/spec.md`
- Link related changes and PRs
### Capability Naming
- Use verb-noun: `user-auth`, `payment-capture`
- Single purpose per capability
- 10-minute understandability rule
- Split if description needs "AND"
## Tool Selection Guide
| Task | Tool | Why |
|------|------|-----|
| Find files by pattern | Glob | Fast pattern matching |
| Search code content | Grep | Optimized regex search |
| Read specific files | Read | Direct file access |
| Explore unknown scope | Task | Multi-step investigation |
## Error Recovery
### Change Conflicts
1. Run `openspec list` to see active changes
2. Check for overlapping specs
3. Coordinate with change owners
4. Consider combining proposals
### Validation Failures
1. Run with `--strict` flag
2. Check JSON output for details
3. Verify spec file format
4. Ensure scenarios properly formatted
### Missing Context
1. Read project.md first
2. Check related specs
3. Review recent archives
4. Ask for clarification
## Quick Reference
### Stage Indicators
- `changes/` - Proposed, not yet built
- `specs/` - Built and deployed
- `archive/` - Completed changes
### File Purposes
- `proposal.md` - Why and what
- `tasks.md` - Implementation steps
- `design.md` - Technical decisions
- `spec.md` - Requirements and behavior
### CLI Essentials
```bash
openspec list # What's in progress?
openspec show [item] # View details
openspec diff [change] # What's changing?
openspec validate --strict # Is it correct?
openspec archive [change] # Mark complete
```
Remember: Specs are truth. Changes are proposals. Keep them in sync.
+141
View File
@@ -0,0 +1,141 @@
name: CI
on:
pull_request:
branches: [main]
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
test:
name: Test
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'pnpm'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Build project
run: pnpm run build
- name: Run tests
run: pnpm test
- name: Upload test coverage
uses: actions/upload-artifact@v4
with:
name: coverage-report
path: coverage/
retention-days: 7
lint:
name: Lint & Type Check
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'pnpm'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Build project
run: pnpm run build
- name: Type check
run: pnpm exec tsc --noEmit
- name: Check for build artifacts
run: |
if [ ! -d "dist" ]; then
echo "Error: dist directory not found after build"
exit 1
fi
if [ ! -f "dist/cli/index.js" ]; then
echo "Error: CLI entry point not found"
exit 1
fi
validate-changesets:
name: Validate Changesets
runs-on: ubuntu-latest
if: github.event_name == 'pull_request'
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'pnpm'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Validate changesets
run: |
if command -v changeset &> /dev/null; then
pnpm exec changeset status --since=origin/main
else
echo "Changesets not configured, skipping validation"
fi
required-checks:
name: All checks passed
runs-on: ubuntu-latest
needs: [test, lint]
if: always()
steps:
- name: Verify all checks passed
run: |
if [[ "${{ needs.test.result }}" != "success" ]]; then
echo "Test job failed"
exit 1
fi
if [[ "${{ needs.lint.result }}" != "success" ]]; then
echo "Lint job failed"
exit 1
fi
echo "All required checks passed!"
+37
View File
@@ -0,0 +1,37 @@
name: Release (prepare)
on:
push:
branches: [main]
permissions:
contents: write
pull-requests: write
jobs:
prepare:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: pnpm/action-setup@v4
with:
version: 9
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'pnpm'
- run: pnpm install --frozen-lockfile
# Opens/updates the Version Packages PR; no publishing here
- name: Create/Update Version PR
uses: changesets/action@v1
with:
title: 'chore(release): version packages'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+72
View File
@@ -0,0 +1,72 @@
name: Publish to npm
on:
release:
types: [published]
workflow_dispatch: {}
permissions:
contents: read
id-token: write
concurrency:
group: publish-${{ github.ref }}
cancel-in-progress: false
jobs:
publish:
runs-on: ubuntu-latest
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: pnpm/action-setup@v4
with:
version: 9
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
scope: '@fission-ai'
always-auth: true
- run: pnpm install --frozen-lockfile
- name: Build project
run: pnpm run build
- name: Ensure running from a tag
run: |
if [[ "$GITHUB_REF" != refs/tags/* ]]; then
echo "This workflow must run from a tag (got: $GITHUB_REF)";
exit 1;
fi
- name: Verify release tag matches package.json
run: |
TAG="${GITHUB_REF_NAME#v}"
PKG_VERSION=$(node -p "require('./package.json').version")
if [ "$TAG" != "$PKG_VERSION" ]; then
echo "Tag v$TAG does not match package.json $PKG_VERSION"; exit 1
fi
- name: Debug npm auth and context
run: |
test -n "$NODE_AUTH_TOKEN" || (echo "NODE_AUTH_TOKEN is missing" && exit 1)
echo "NODE_AUTH_TOKEN present"
npm --version
pnpm --version
node --version
npm config get registry
npm whoami
npm ping
- run: pnpm test
- name: Publish
run: pnpm publish --access public --provenance --no-git-checks --tag next
View File
+4
View File
@@ -0,0 +1,4 @@
### Minor Changes
- 24b4866: Initial release
+40
View File
@@ -0,0 +1,40 @@
<!-- OPENSPEC:START -->
# OpenSpec Project
This document provides instructions for AI coding assistants on how to use OpenSpec conventions for spec-driven development. Follow these rules precisely when working on OpenSpec-enabled projects.
This project uses OpenSpec for spec-driven development. Specifications are the source of truth.
See @openspec/AGENTS.md for detailed conventions and guidelines.
<!-- OPENSPEC:END -->
## Complexity Management
**Default to minimal solutions:**
- Propose <100 lines of new code for features
- Prefer single-file implementations until proven insufficient
- Avoid frameworks, abstractions, and optimizations without clear justification
- Choose boring, well-understood patterns over novel approaches
**Question requests for complexity:**
- Caching? → Ask for performance data and targets
- New framework? → Suggest plain code first
- Extra layers? → Start with the thinnest viable design
**Justify complexity with data:**
- Performance metrics showing current solution is too slow
- Concrete scale requirements (e.g., >1000 users, >100MB data)
- Multiple proven use cases requiring an abstraction
## Package Manager
Always use pnpm (NOT npm or yarn) for all Node.js package management:
- Install dependencies: `pnpm install`
- Add packages: `pnpm add [package]`
- Run scripts: `pnpm run [script]`
## Git Commits
Use conventional commits with these rules:
- Format: `type(scope): subject` (e.g., `fix: resolve auth error`, `feat(api): add user endpoint`)
- Keep commit messages to ONE line only - no body or footer
- Common types: feat, fix, docs, style, refactor, test, chore
- Never add co-authorship lines or attribution
+7
View File
@@ -0,0 +1,7 @@
# @fission-ai/openspec
## 0.1.0
### Minor Changes
- 24b4866: Initial release
+22
View File
@@ -0,0 +1,22 @@
MIT License
Copyright (c) 2024 OpenSpec Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-343
View File
@@ -1,343 +0,0 @@
# Comprehensive Retrospective: Creating an OpenSpec Change Proposal
## Executive Summary
This document consolidates learnings from creating the `bulk-validation-interactive-selection` change proposal for OpenSpec. The process revealed critical gaps in documentation, unhelpful error messages, and areas where the system could be more user-friendly. While OpenSpec's core functionality works correctly, the user experience for creating changes needs significant improvement.
## Table of Contents
1. [Errors Encountered](#errors-encountered)
2. [System Issues vs User Errors](#system-issues-vs-user-errors)
3. [Documentation Gaps Analysis](#documentation-gaps-analysis)
4. [Key Learnings](#key-learnings)
5. [Recommendations](#recommendations)
6. [Conclusion](#conclusion)
---
## Errors Encountered
### Error 1: Misunderstanding Delta Structure
**Error Message:** `✗ [ERROR] deltas: Change must have at least one delta`
**What Happened:**
Initially attempted to define deltas directly in the `proposal.md` file using markdown sections like:
```markdown
### Delta: Add validate-all command
**Type**: Feature addition
**Effort**: Small (< 100 lines)
```
**Root Cause:**
Fundamental misunderstanding of how OpenSpec processes deltas. Deltas are derived from spec files in the change's `specs/` directory, not from the proposal itself.
**Discovery Process:**
- Examined `ChangeParser` class in `/src/core/parsers/change-parser.ts`
- Found that `parseDeltaSpecs()` method looks for spec files in `specs/` subdirectory
- Learned that deltas are extracted by comparing spec files against existing specs
### Error 2: Missing Operation Prefix in Section Headers
**Error Message:** `✗ [ERROR] deltas: Change must have at least one delta`
**What Happened:**
Created new spec files with standard `## Requirements` headers instead of operation-prefixed headers.
**Root Cause:**
Failed to understand that ALL spec files in a change need operation prefixes (`ADDED`, `MODIFIED`, etc.) in their section headers, regardless of whether they're new specs or modifications.
**Discovery Process:**
- Created new specs with `## Requirements` → No deltas detected
- Changed to `## ADDED Requirements` → Deltas detected successfully!
- Realized creating new specs works perfectly fine once properly formatted
**Important Clarification:**
OpenSpec fully supports creating new specs. They appear as ADDED operations in the deltas. My initial analysis incorrectly suggested this was a limitation, but it was actually just a formatting issue.
### Error 3: Improper Scenario Formatting
**Error Message:**
```
✗ [ERROR] deltas.0.requirements.0.scenarios: Requirement must have at least one scenario
✗ [ERROR] deltas.1.requirements.0.scenarios: Requirement must have at least one scenario
```
**What Happened:**
Formatted scenarios as bullet lists under a bold "Scenarios:" label:
```markdown
**Scenarios:**
- **WHEN** executing command
- **THEN** expected behavior
```
**Root Cause:**
OpenSpec's parser expects scenarios to be defined as level 4 headers (`####`) with specific formatting:
```markdown
#### Scenario: Descriptive scenario name
- **WHEN** executing command
- **THEN** expected behavior
```
**Discovery Process:**
- Checked parsed JSON output: `npx openspec change show bulk-validation-interactive-selection --json`
- Saw `"scenarios": []` empty array despite having scenario content
- Examined working spec files and found the `#### Scenario:` header pattern
### Error 4: File Path Confusion
**Initial Confusion:**
Wasn't clear whether to create specs that would become part of the main `openspec/specs/` or just define them in the change.
**Resolution:**
Learned that changes can:
1. Create new specs (they start in `changes/{change-name}/specs/` and move to `openspec/specs/` when archived)
2. Modify existing specs (by creating a spec file with the same name as one in `openspec/specs/`)
3. The validation system detects both patterns and creates appropriate deltas
---
## System Issues vs User Errors
### System Issues / Bugs
#### 1. Unhelpful Error Messages ⚠️
**Issue:** `✗ [ERROR] deltas: Change must have at least one delta`
**Why This Is a System Problem:**
- Error message provides no guidance on HOW to create deltas
- Doesn't mention that deltas come from `specs/` subdirectory
- Doesn't explain the required section headers
- A better error would be: "No deltas found. Ensure your change has a specs/ directory with .md files containing sections like '## ADDED Requirements'"
#### 2. Silent Scenario Parsing Failures ⚠️
**Issue:** When scenarios were formatted incorrectly, they were silently ignored
**Why This Is a System Problem:**
- Parser silently returns empty scenarios array instead of warning
- No validation error explaining the format issue
- User gets "Requirement must have at least one scenario" without knowing their scenarios exist but aren't parsed
**Evidence:**
```json
{
"text": "The CLI SHALL provide a top-level `show` command with interactive selection.",
"scenarios": [] // Silent failure - scenarios existed but weren't parsed
}
```
#### 3. No Validation for Proposal Structure During Creation
**Issue:** System allows creating invalid proposals without early feedback
**Why This Is a System Problem:**
- No scaffolding or template commands
- No incremental validation as you build
- Must fully create the change before discovering structural issues
### User Errors (My Mistakes)
#### 1. Trying to Define Deltas in Proposal.md
- Incorrectly assumed deltas could be inline in the proposal
- System correctly expects deltas in separate spec files
#### 2. Using Wrong Section Headers
- Used `## Requirements` instead of `## ADDED Requirements`
- Convention is documented in existing changes, but I didn't examine carefully
#### 3. Wrong Scenario Format
- Used bullet lists instead of `#### Scenario:` headers
- Made assumptions instead of checking existing patterns
### Gray Areas
1. **Documentation gaps** - While examples exist, there's no comprehensive "How to Create a Change" guide
2. **Lack of tooling** - No scaffolding commands to create properly structured changes
---
## Documentation Gaps Analysis
### Critical Gaps in openspec/README.md
#### 1. Scenario Format - COMPLETELY MISSING ⚠️
**What README Shows:** No scenario examples at all
**What's Actually Required:**
```markdown
#### Scenario: Descriptive name
- **WHEN** condition
- **THEN** expected outcome
- **AND** additional outcomes
```
**Impact:** This was the biggest struggle. The README mentions requirements but never shows how to write scenarios. Without this, requirements fail validation.
#### 2. Complete Spec File Example - MISSING
**What README Shows:** Only fragments
**What's Actually Needed:** A complete working example showing:
- Full spec file structure
- Proper requirement format
- Scenario formatting
- All required elements
#### 3. Validation Commands - NOT MENTIONED
**Missing from README:**
- `npx openspec change validate <change-name>`
- `npx openspec change show <change-name> --json`
- The `--strict` flag for catching warnings
#### 4. Delta Detection Explanation - INCOMPLETE
**What's Missing:**
- WHERE the system looks for specs (specs/ subdirectory)
- THAT deltas are automatically extracted
- HOW to debug when deltas aren't detected
- WHAT error messages mean
### Misleading Documentation
#### "Store only the changes" - MISLEADING
**Line 145:** `# - Store only the changes (not complete future state)`
**Problem:** This suggests storing diffs or partial content. In reality, you need:
- Complete requirements in their final form
- Full scenario definitions
- The entire requirement text
### Documentation That Was Helpful
1. Delta section headers (`## ADDED Requirements`) - clearly documented
2. Directory structure - excellent visualization
3. When to create proposals - well defined
---
## Key Learnings
### 1. OpenSpec's Delta Detection Algorithm
The system follows this process:
1. Scans `openspec/changes/{change-name}/specs/` directory
2. For each spec file found, parses for delta sections (`ADDED`, `MODIFIED`, `REMOVED`, `RENAMED`)
3. Creates delta objects with operation type, affected spec, and requirements
4. Validates that at least one delta exists for the change to be valid
**Important:** Creating entirely new specs is fully supported! New specs use `## ADDED Requirements` and appear as ADDED operations in the deltas.
### 2. Spec File Structure Requirements
Valid spec files must follow this structure:
```markdown
# Spec Title
## [ADDED|MODIFIED|REMOVED|RENAMED] Requirements
### Requirement: Clear requirement statement
The requirement description using SHALL/SHOULD/MAY.
#### Scenario: Scenario name
- **WHEN** condition
- **THEN** expected outcome
- **AND** additional outcomes
```
### 3. Change Proposal Structure
A valid change must have:
- `## Why` section - explaining the motivation
- `## What Changes` section - summarizing the changes
- `specs/` directory with properly formatted spec files containing deltas
- Each delta must have at least one requirement with at least one scenario
### 4. Validation Commands Are Essential
```bash
# Basic validation
npx openspec change validate {change-name}
# Strict validation (recommended)
npx openspec change validate {change-name} --strict
# Debug delta detection
npx openspec change show {change-name} --json | jq '.deltas'
```
---
## Recommendations
### High Priority (System Bugs to Fix)
1. **Improve Error Messages**
- Add actionable guidance to error messages
- Example: "No deltas found. Check: 1) specs/ directory exists, 2) Files use ## ADDED Requirements headers, 3) Each requirement has #### Scenario: sections"
2. **Add Warnings for Malformed Content**
- Warn when scenarios exist but aren't properly formatted
- Show which line/file has the issue
3. **Add Delta Detection Debugging**
- Command like `openspec change debug-deltas {change-name}`
- Show which files were scanned, what was found, what was rejected
### Medium Priority (Documentation Improvements)
1. **Add Complete Working Example to README**
- Full change proposal with all files
- Properly formatted specs with scenarios
- Show the validation output
2. **Add Troubleshooting Section**
- Common errors and their solutions
- How to debug delta detection
- Scenario formatting requirements
3. **Add Validation Best Practices**
- When to use `--strict`
- How to use JSON output for debugging
- Common validation patterns
### Low Priority (Developer Experience)
1. **Add Scaffolding Command**
```bash
openspec change scaffold {change-name}
```
- Creates proper directory structure
- Includes template files with correct formatting
- Adds example scenarios
2. **Add Interactive Creation Wizard**
- Guide users through change creation
- Validate as they go
- Suggest fixes for common issues
3. **Add Auto-fix Capability**
- `--fix` flag to correct common formatting issues
- Convert bullet list scenarios to proper headers
- Add missing operation prefixes
---
## Conclusion
The OpenSpec system works correctly for its intended design, but the user experience for creating changes needs significant improvement. The core issues stem from:
### System Issues
- **Unhelpful error messages** that don't guide users to solutions
- **Silent parsing failures** that provide no feedback about malformed content
- **Lack of debugging tools** to understand what went wrong
### Documentation Issues
- **Critical formatting requirements missing** (especially scenario format)
- **No complete working examples** showing all required elements
- **Validation commands not documented** despite being essential
### User Issues
- **Incorrect assumptions** about how the system works
- **Not examining existing patterns** carefully enough
- **Trying to shortcut** instead of following established conventions
### The Path Forward
With better error messages, complete documentation, and basic tooling support, most of the errors encountered could be prevented. The system's delta-centric approach is powerful and ensures changes are atomic and trackable, but it needs to be more discoverable and user-friendly.
The most impactful improvements would be:
1. Adding scenario format documentation to the README
2. Improving error messages with actionable guidance
3. Creating a scaffolding command for new changes
These changes would transform OpenSpec from a system that works correctly but is hard to use, into one that actively helps developers succeed.
+230 -79
View File
@@ -1,119 +1,270 @@
# OpenSpec
A specification-driven development system for maintaining living documentation alongside your code.
[![CI](https://github.com/Fission-AI/OpenSpec/actions/workflows/ci.yml/badge.svg)](https://github.com/Fission-AI/OpenSpec/actions/workflows/ci.yml)
[![npm version](https://img.shields.io/npm/v/@fission-ai/openspec)](https://www.npmjs.com/package/@fission-ai/openspec)
[![node](https://img.shields.io/node/v/@fission-ai/openspec)](https://nodejs.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](./LICENSE)
[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org)
**Supported AI Tools:** ✅ Claude Code | 🔜 Cursor (coming soon) | 🔜 AGENTS.md support (coming soon)
Create **alignment** between humans and AI coding assistants through spec-driven development. **No API keys required.**
OpenSpec ensures you and your AI assistant agree on what to build before any code is written. By discussing and refining specifications first, you bring determinism to AI code generation, getting exactly what you want, not what the AI thinks you might want.
## Why OpenSpec?
**The Problem:** AI coding assistants are powerful but unpredictable. Without clear specifications, they generate code based on assumptions, often missing requirements or adding unwanted features. Teams waste time in review cycles because humans and AI aren't aligned on what to build.
**The Solution:** OpenSpec creates alignment BEFORE code is written:
- **Human-AI Alignment** - You and your AI agree on specifications before implementation
- **Deterministic Output** - Clear specs lead to predictable code generation
- **Team Alignment** - Everyone reviews specs, not code surprises
- **Focus on What, Not How** - Define requirements while AI handles implementation
- **Living Documentation** - Specs evolve with your code as a natural byproduct
## What You Get
- **Alignment First** - Ensure humans and AI agree on what to build before writing code
- **Predictable AI Output** - Turn non-deterministic AI into a reliable development partner
- **Universal Tool Support** - Works with any AI assistant - Claude Code, Cursor, or future tools
- **No API Keys Required** - Integrates through context rules, not external services
- **Spec-Level Reviews** - Teams review intentions, not implementation details
- **Clear Feature Scope** - Know exactly what you're building and what you're not
- **Progress Tracking** - See what's proposed, in progress, or completed at a glance
## How It Works
```
┌─────────────┐ ┌─────────────┐ ┌──────────────┐
│ SPECS │ │ CHANGES │ │ ARCHIVE │
│ (Truth) │◀──────│ (Proposals) │──────▶│ (Completed) │
└─────────────┘ └─────────────┘ └──────────────┘
▲ │ │
│ ▼ │
│ ┌─────────────┐ │
└───────────────│ CODE │◀──────────────┘
└─────────────┘
1. SPECS define current capabilities (what IS built)
2. CHANGES propose modifications using deltas (what SHOULD change)
3. CODE implements the changes following tasks
4. ARCHIVE preserves completed changes after deployment
```
## Installation
### Prerequisites
- Node.js >= 20.19.0
### Install OpenSpec
Install globally:
```bash
npm install -g openspec
npm install -g @fission-ai/openspec
```
## Quick Start
## Getting Started
### 1. Initialize OpenSpec in Your Project
```bash
# Initialize OpenSpec in your project
# Navigate to your project
cd my-project
# Initialize OpenSpec
openspec init
# Update existing OpenSpec instructions (team-friendly)
openspec update
# Select your AI tool (more coming soon!):
# "Which AI tool do you use?"
# > Claude Code
# Cursor (coming soon)
# List specs or changes
openspec spec list # specs (IDs by default; use --long for details)
openspec change list # changes (IDs by default; use --long for details)
# Show differences between specs and proposed changes
openspec diff [change-name]
# Archive completed changes
openspec archive [change-name]
# This creates:
# openspec/
# ├── specs/ # Current specifications (truth)
# ├── changes/ # Proposed changes
# └── README.md # AI instructions for your tool
```
## Commands
### 2. Create Your First Change
### `openspec init`
Jump straight into creating a change proposal with your AI assistant (works with Claude Code, Cursor, or any AI tool):
Initializes OpenSpec in your project by creating:
- `openspec/` directory structure
- `openspec/README.md` with OpenSpec instructions
- AI tool configuration files (based on your selection)
```markdown
// Quick win - Add a simple new feature:
You: "I want to add a user profile API endpoint.
Please create an OpenSpec change proposal for this."
### `openspec update`
AI: "I'll create an OpenSpec change proposal for the user profile API..."
*Creates openspec/changes/add-user-profile-api/ with:*
- proposal.md (why this feature is needed)
- tasks.md (implementation checklist)
- design.md (API design decisions)
- specs/user-profile/spec.md (new requirements)
Updates OpenSpec instructions to the latest version. This command is **team-friendly** and only updates files that already exist:
You: "The proposal looks good. Let's implement it."
- Always updates `openspec/README.md` with the latest OpenSpec instructions
- **Only updates existing AI tool configuration files** (e.g., CLAUDE.md, CURSOR.md)
- **Never creates new AI tool configuration files**
- Preserves content outside of OpenSpec markers in AI tool files
AI: "Following the tasks in openspec/changes/add-user-profile-api/tasks.md:
Task 1.1: Create user profile model..."
*Implements each task systematically*
```
This allows team members to use different AI tools without conflicts. Each developer can maintain their preferred AI tool configuration file, and `openspec update` will respect their choice.
### 3. Track Your Work
### `openspec spec`
```bash
# View active changes (what's being worked on)
openspec list
Manage and view specifications.
# Validate your changes are properly formatted
openspec validate add-2fa --strict
Examples:
- `openspec spec show <spec-id>`
- Text mode: prints raw `spec.md` content
- JSON mode (`--json`): returns minimal, stable shape
- Filters are JSON-only: `--requirements`, `--no-scenarios`, `-r/--requirement <1-based>`
- `openspec spec list`
- Prints IDs only by default
- Use `--long` to include `title` and `[requirements N]`
- `openspec spec validate <spec-id>`
- Text: human-readable summary to stdout/stderr
- `--json` for structured report
# After deployment, archive the completed change
openspec archive add-2fa
# This moves the change to archive/ and updates specs/
```
### `openspec change`
## Common Commands
Manage and view change proposals.
```bash
# Most used:
openspec list # See what changes you're working on
openspec archive <change> # Mark a change as complete after deployment
Examples:
- `openspec change show <change-id>`
- Text mode: prints raw `proposal.md` content
- JSON mode (`--json`): `{ id, title, deltaCount, deltas }`
- Filtering is JSON-only: `--deltas-only` (alias: `--requirements-only`, deprecated)
- `openspec change list`
- Prints IDs only by default
- Use `--long` to include `title` and counts `[deltas N] [tasks x/y]`
- `openspec change validate <change-id>`
- Text: human-readable result
- `--json` for structured report
# Also useful:
openspec validate <change> # Check formatting before committing
openspec show <change> # View change details
```
### `openspec diff [change-name]`
## Example: How AI Creates OpenSpec Files
Shows the differences between current specs and proposed changes:
- Displays a unified diff format
- Helps review what will change before implementation
- Useful for pull request reviews
When you ask your AI assistant to "add two-factor authentication", it creates:
### `openspec archive [change-name]`
```
openspec/
├── specs/
│ └── auth/
│ └── spec.md # Current auth spec (if exists)
└── changes/
└── add-2fa/ # AI creates this entire structure
├── proposal.md # Why and what changes
├── tasks.md # Implementation checklist
├── design.md # Technical decisions (optional)
└── specs/
└── auth/
└── spec.md # Delta showing additions
```
Archives a completed change:
- Moves change from `openspec/changes/` to `openspec/changes/archive/`
- Adds a date prefix to the archived change
- Updates specs to reflect the new state
- Use `--skip-specs` to archive without updating specs (for abandoned changes)
### AI-Generated Spec (created in `openspec/specs/auth/spec.md`):
## Team Collaboration
```markdown
# Auth Specification
OpenSpec is designed for team collaboration:
## Purpose
Authentication and session management.
## Requirements
### Requirement: User Authentication
The system SHALL issue a JWT on successful login.
#### Scenario: Valid credentials
- WHEN a user submits valid credentials
- THEN a JWT is returned
```
### AI-Generated Change Delta (created in `openspec/changes/add-2fa/specs/auth/spec.md`):
```markdown
# Delta for Auth
## ADDED Requirements
### Requirement: Two-Factor Authentication
The system MUST require a second factor during login.
#### Scenario: OTP required
- WHEN a user submits valid credentials
- THEN an OTP challenge is required
```
### AI-Generated Tasks (created in `openspec/changes/add-2fa/tasks.md`):
```markdown
## 1. Database Setup
- [ ] 1.1 Add OTP secret column to users table
- [ ] 1.2 Create OTP verification logs table
## 2. Backend Implementation
- [ ] 2.1 Add OTP generation endpoint
- [ ] 2.2 Modify login flow to require OTP
- [ ] 2.3 Add OTP verification endpoint
## 3. Frontend Updates
- [ ] 3.1 Create OTP input component
- [ ] 3.2 Update login flow UI
```
**Important:** You don't create these files manually. Your AI assistant generates them based on your requirements and the existing codebase.
## Understanding OpenSpec Files
### Delta Format
Deltas are "patches" that show how specs change:
- **`## ADDED Requirements`** - New capabilities
- **`## MODIFIED Requirements`** - Changed behavior (include complete updated text)
- **`## REMOVED Requirements`** - Deprecated features
**Format requirements:**
- Use `### Requirement: <name>` for headers
- Every requirement needs at least one `#### Scenario:` block
- Use SHALL/MUST in requirement text
## Why OpenSpec Works
OpenSpec creates **alignment** between you and your AI coding assistant:
1. **You describe** what you want to build
2. **AI creates specs** before writing any code
3. **You review and adjust** the specifications
4. **AI implements** exactly what was specified
5. **Everyone understands** what's being built through clear specs
**True Interoperability:** OpenSpec is designed to be universal. No API keys, no vendor lock-in. It works by adding context rules to ANY AI coding tool - whether you use Claude Code today, switch to Cursor tomorrow, or adopt the next breakthrough AI assistant. Your specs remain portable and your workflow stays consistent.
## How OpenSpec Compares
### vs. Kiro.dev
OpenSpec groups all changes for a feature in one place (`openspec/changes/feature-name/`), making it easy to track what needs to be done. Kiro spreads changes across multiple spec folders, making feature tracking harder.
### vs. No Specs
Without specs, AI coding assistants generate code based on vague prompts, often missing requirements or adding unwanted features. OpenSpec ensures alignment before any code is written.
## Team Adoption
### Getting Started with Your Team
1. **Initialize OpenSpec** - Run `openspec init` in your project
2. **Start with new features** - Use OpenSpec for your next change proposal
3. **Build incrementally** - Each new feature adds to your spec library
4. **Future capability** - We're working on tools to generate specs from existing code
**Tool Freedom:** Your team can use different AI assistants. One developer might use Claude Code while another uses Cursor - OpenSpec keeps everyone aligned through shared specifications. Run `openspec update` to configure for any supported tool without affecting others.
1. **AI Tool Flexibility**: Each team member can use their preferred AI assistant (Claude, Cursor, etc.)
2. **Non-Invasive Updates**: The `update` command only modifies existing files, never forcing tools on team members
3. **Specification Sharing**: The `openspec/` directory contains shared specifications that all team members work from
4. **Change Tracking**: Proposed changes are visible to all team members for review before implementation
## Contributing
See `openspec/specs/` for the current system specifications and `openspec/changes/` for pending improvements.
## Notes
- The legacy `openspec list` command is deprecated. Use `openspec spec list` and `openspec change list`.
- Text output is raw-first (no formatting or filtering). Prefer `--json` for tooling-friendly output.
- Global `--no-color` disables ANSI colors and respects `NO_COLOR`.
- Install dependencies: `npm install`
- Build: `npm run build`
- Test: `npm test`
- Develop CLI locally: `npm run dev` or `npm run dev:cli`
- Conventional commits (one-line): `type(scope): subject`
## License
MIT
MIT
+236 -515
View File
@@ -1,575 +1,296 @@
# OpenSpec Instructions
This document provides instructions for AI coding assistants on how to use OpenSpec conventions for spec-driven development. Follow these rules precisely when working on OpenSpec-enabled projects.
Instructions for AI coding assistants using OpenSpec for spec-driven development.
## Core Principle
## Three-Stage Workflow
OpenSpec is an AI-native system for change-driven development where:
- **Specs** (`specs/`) reflect what IS currently built and deployed
- **Changes** (`changes/`) contain proposals for what SHOULD be changed
- **AI drives the process** - You generate proposals, humans review and approve
- **Specs are living documentation** - Always kept in sync with deployed code
### Stage 1: Creating Changes
Create proposal when you need to:
- Add features or functionality
- Make breaking changes (API, schema)
- Change architecture or patterns
- Optimize performance (changes behavior)
- Update security patterns
## Start Simple
Skip proposal for:
- Bug fixes (restore intended behavior)
- Typos, formatting, comments
- Dependency updates (non-breaking)
- Configuration changes
- Tests for existing behavior
**Default to minimal implementations:**
- New features should be <100 lines of code initially
- Use the simplest solution that works
- Avoid premature optimization (no caching, parallelization, or complex patterns without proven need)
- Choose boring technology over cutting-edge solutions
### Stage 2: Implementing Changes
1. **Read proposal.md** - Understand what's being built
2. **Read design.md** (if exists) - Review technical decisions
3. **Read tasks.md** - Get implementation checklist
4. **Implement tasks sequentially** - Complete in order
5. **Mark complete immediately** - Update `- [x]` after each task
**Complexity triggers** - Only add complexity when you have:
- **Performance data** showing current solution is too slow
- **Scale requirements** with specific numbers (>1000 users, >100MB data)
- **Multiple use cases** requiring the same abstraction
- **Regulatory compliance** mandating specific patterns
- **Security threats** that simple solutions cannot address
### Stage 3: Archiving Changes
After deployment, create separate PR to:
- Move `changes/[name]/` → `changes/archive/YYYY-MM-DD-[name]/`
- Update `specs/` if capabilities changed
- Use `openspec archive [change] --skip-specs` for tooling-only changes
When triggered, document the specific justification in your change proposal.
## Before Any Task
**Context Checklist:**
- [ ] Read relevant specs in `specs/[capability]/spec.md`
- [ ] Check pending changes in `changes/` for conflicts
- [ ] Read `openspec/project.md` for conventions
- [ ] Run `openspec list` to see active changes
- [ ] Run `openspec list --specs` to see existing capabilities
**Before Creating Specs:**
- Always check if capability already exists
- Prefer modifying existing specs over creating duplicates
- Use `openspec show [spec]` to review current state
## Quick Start
### CLI Commands
```bash
# Essential commands
openspec list # List active changes
openspec list --specs # List specifications
openspec show [item] # Display change or spec
openspec validate [item] # Validate changes or specs
openspec archive [change] # Archive after deployment
# Project management
openspec init [path] # Initialize OpenSpec
openspec update [path] # Update instruction files
# Interactive mode
openspec show # Prompts for selection
openspec validate # Bulk validation mode
# Debugging
openspec show [change] --json --deltas-only
openspec validate [change] --strict
```
### Command Flags
- `--json` - Machine-readable output
- `--type change|spec` - Disambiguate items
- `--strict` - Comprehensive validation
- `--no-interactive` - Disable prompts
- `--skip-specs` - Archive without spec updates
## Directory Structure
```
openspec/
├── project.md # Project-specific context (tech stack, conventions)
├── README.md # This file - OpenSpec instructions
├── project.md # Project conventions
├── specs/ # Current truth - what IS built
│ ├── [capability]/ # Single, focused capability
│ │ ├── spec.md # WHAT the capability does and WHY
│ │ └── design.md # HOW it's built (established patterns)
│ └── ...
├── changes/ # Proposed changes - what we're CHANGING
│ └── [capability]/ # Single focused capability
│ ├── spec.md # Requirements and scenarios
│ └── design.md # Technical patterns
├── changes/ # Proposals - what SHOULD change
│ ├── [change-name]/
│ │ ├── proposal.md # Why, what, impact (consolidated)
│ │ ├── proposal.md # Why, what, impact
│ │ ├── tasks.md # Implementation checklist
│ │ ├── design.md # Technical decisions (optional, for complex changes)
│ │ └── specs/ # Delta changes to specs
│ │ ├── design.md # Technical decisions (optional)
│ │ └── specs/ # Delta changes
│ │ └── [capability]/
│ │ └── spec.md # Delta format (ADDED/MODIFIED/REMOVED/RENAMED)
│ └── archive/ # Completed changes (dated)
│ │ └── spec.md # ADDED/MODIFIED/REMOVED
│ └── archive/ # Completed changes
```
## CLI Usage: show command
## Creating Change Proposals
Use the `show` command to display change proposals or specs with automatic detection and interactive selection.
### Decision Tree
- Interactive (no args, in a TTY):
```bash
openspec show
# → prompts to pick change/spec, then item
```
New request?
├─ Bug fix restoring spec behavior? → Fix directly
├─ Typo/format/comment? → Fix directly
├─ New feature/capability? → Create proposal
├─ Breaking change? → Create proposal
├─ Architecture change? → Create proposal
└─ Unclear? → Create proposal (safer)
```
- Direct item (auto-detect type):
### Proposal Structure
```bash
openspec show demo # shows change 'demo'
openspec show auth # shows spec 'auth'
1. **Create directory:** `changes/[descriptive-name]/`
2. **Write proposal.md:**
```markdown
## Why
[1-2 sentences on problem/opportunity]
## What Changes
- [Bullet list of changes]
- [Mark breaking changes with **BREAKING**]
## Impact
- Affected specs: [list capabilities]
- Affected code: [key files/systems]
```
- Disambiguation when names collide:
```bash
openspec show foo # if both change/spec exist → error suggests --type
openspec show foo --type spec # forces spec
openspec show foo --type change
```
- Common flags:
```bash
# JSON output (both types)
openspec show <item> --json
# Change-only flags
openspec show <change-id> --json --deltas-only
openspec show <change-id> --json --requirements-only # deprecated alias of --deltas-only
# Spec-only flags
openspec show <spec-id> --json --requirements
openspec show <spec-id> --json --no-scenarios
openspec show <spec-id> --json -r 1 # show requirement 1 only (1-based)
```
- Interactivity controls:
```bash
openspec show --no-interactive # never prompt
# or via env
OPEN_SPEC_INTERACTIVE=0 openspec show
```
- Backwards compatibility (subcommands also support interactive selection when no arg):
```bash
openspec change show [change-id] [--json] [--deltas-only]
openspec spec show [spec-id] [--json] [--requirements] [--no-scenarios] [-r N]
```
### Capability Organization
**Use capabilities, not features** - Each directory under `specs/` represents a single, focused responsibility:
- **Verb-noun naming**: `user-auth`, `payment-capture`, `order-checkout`
- **10-minute rule**: Each capability should be understandable in <10 minutes
- **Single purpose**: If it needs "AND" to describe it, split it
Examples:
```
✅ GOOD: user-auth, user-sessions, payment-capture, payment-refunds
❌ BAD: users, payments, core, misc
```
## Key Behavioral Rules
### 1. Always Start by Reading
Before any task:
1. **Read relevant specs** in `specs/[capability]/spec.md` to understand current state
2. **Check pending changes** in `changes/` directory for potential conflicts
3. **Read project.md** for project-specific conventions
### 2. When to Create Change Proposals
**ALWAYS create a change proposal for:**
- New features or functionality
- Breaking changes (API changes, schema updates)
- Architecture changes or new patterns
- Performance optimizations that change behavior
- Security updates affecting auth/access patterns
- Any change requiring multiple steps or affecting multiple systems
**SKIP proposals for:**
- Bug fixes that restore intended behavior
- Typos, formatting, or comment updates
- Dependency updates (unless breaking)
- Configuration or environment variable changes
- Adding tests for existing behavior
- Documentation fixes
**Complexity assessment:**
- If your solution requires >100 lines of new code, justify the complexity
- If adding dependencies, frameworks, or architectural patterns, document why simpler alternatives won't work
- Default to single-file implementations until proven insufficient
### 3. Delta-Based Change Format
Changes use a delta format with clear sections:
3. **Create spec deltas:** `specs/[capability]/spec.md`
```markdown
## ADDED Requirements
### Requirement: New Feature
[Complete requirement content in structured format]
The system SHALL provide...
## MODIFIED Requirements
#### Scenario: Success case
- **WHEN** user performs action
- **THEN** expected result
## MODIFIED Requirements
### Requirement: Existing Feature
[Complete modified requirement (header must match current spec)]
[Complete modified requirement]
## REMOVED Requirements
### Requirement: Old Feature
**Reason for removal**: [Why removing]
**Migration path**: [How to handle existing usage]
## RENAMED Requirements
- FROM: `### Requirement: Old Name`
- TO: `### Requirement: New Name`
**Reason**: [Why removing]
**Migration**: [How to handle]
```
Key rules:
- Headers are matched using `normalize(header) = trim(header)`
- Include complete requirements (not diffs)
- Use standard symbols in CLI output: + (added), ~ (modified), - (removed), → (renamed)
4. **Create tasks.md:**
```markdown
## 1. Implementation
- [ ] 1.1 Create database schema
- [ ] 1.2 Implement API endpoint
- [ ] 1.3 Add frontend component
- [ ] 1.4 Write tests
```
### 4. Creating a Change Proposal
## Spec File Format
When a user requests a significant change:
### Critical: Scenario Formatting
**CORRECT** (use #### headers):
```markdown
#### Scenario: User login success
- **WHEN** valid credentials provided
- **THEN** return JWT token
```
**WRONG** (don't use bullets or bold):
```markdown
- **Scenario: User login** ❌
**Scenario**: User login ❌
### Scenario: User login ❌
```
Every requirement MUST have at least one scenario.
### Delta Operations
- `## ADDED Requirements` - New capabilities
- `## MODIFIED Requirements` - Changed behavior
- `## REMOVED Requirements` - Deprecated features
- `## RENAMED Requirements` - Name changes
Headers matched with `trim(header)` - whitespace ignored.
## Troubleshooting
### Common Errors
**"Change must have at least one delta"**
- Check `changes/[name]/specs/` exists with .md files
- Verify files have operation prefixes (## ADDED Requirements)
**"Requirement must have at least one scenario"**
- Check scenarios use `#### Scenario:` format (4 hashtags)
- Don't use bullet points or bold for scenario headers
**Silent scenario parsing failures**
- Exact format required: `#### Scenario: Name`
- Debug with: `openspec show [change] --json --deltas-only`
### Validation Tips
```bash
# 1. Create the change directory
openspec/changes/[descriptive-name]/
# Always use strict mode for comprehensive checks
openspec validate [change] --strict
# 2. Generate proposal.md with all context
## Why
[1-2 sentences on the problem/opportunity]
# Debug delta parsing
openspec show [change] --json | jq '.deltas'
## What Changes
[Bullet list of changes, including breaking changes]
## Impact
- Affected specs: [list capabilities that will change]
- Affected code: [list key files/systems]
# 3. Create delta specs for ALL affected capabilities
# - Store only the changes (not complete future state)
# - Use sections: ## ADDED, ## MODIFIED, ## REMOVED, ## RENAMED
# - Include complete requirements in their final form
# Example spec.md content:
# ## ADDED Requirements
# ### Requirement: Password Reset
# Users SHALL be able to reset passwords via email...
#
# ## MODIFIED Requirements
# ### Requirement: User Authentication
# [Complete modified requirement with new password reset hook]
specs/
└── [capability]/
└── spec.md # Contains delta sections
# 4. Create tasks.md with implementation steps
## 1. [Task Group]
- [ ] 1.1 [Specific task]
- [ ] 1.2 [Specific task]
# 5. For complex changes, add design.md
[Technical decisions and trade-offs]
# Check specific requirement
openspec show [spec] --json -r 1
```
### 5. The Change Lifecycle
## Best Practices
1. **Propose** → Create change directory with delta-based documentation
2. **Review** → User reviews and approves the proposal
3. **Implement** → Follow the approved tasks.md (can be multiple PRs)
4. **Deploy** → User confirms deployment
5. **Update Specs** → Apply deltas to sync specs/ with new reality (IF the change affects system capabilities)
6. **Archive** → Move to `changes/archive/YYYY-MM-DD-[name]/`
### Simplicity First
- Default to <100 lines of new code
- Single-file implementations until proven insufficient
- Avoid frameworks without clear justification
- Choose boring, proven patterns
### 6. Implementing Changes
### Complexity Triggers
Only add complexity with:
- Performance data showing current solution too slow
- Concrete scale requirements (>1000 users, >100MB data)
- Multiple proven use cases requiring abstraction
When implementing an approved change:
1. Follow the tasks.md checklist exactly
2. **Mark completed tasks** in tasks.md as you finish them (e.g., `- [x] 1.1 Task completed`)
3. Ensure code matches the proposed behavior
4. Update any affected tests
5. **Keep change in `changes/` directory** - do NOT archive in implementation PR
### Clear References
- Use `file.ts:42` format for code locations
- Reference specs as `specs/auth/spec.md`
- Link related changes and PRs
**Multiple Implementation PRs:**
- Changes can be implemented across multiple PRs
- Each PR should update tasks.md to mark what was completed
- Different developers can work on different task groups
- Example: PR #1 completes tasks 1.1-1.3, PR #2 completes tasks 2.1-2.4
### Capability Naming
- Use verb-noun: `user-auth`, `payment-capture`
- Single purpose per capability
- 10-minute understandability rule
- Split if description needs "AND"
### 7. Updating Specs and Archiving After Deployment
## Tool Selection Guide
**Create a separate PR after deployment** that:
1. Moves change to `changes/archive/YYYY-MM-DD-[name]/`
2. Updates relevant files in `specs/` to reflect new reality (if needed)
3. If design.md exists, incorporates proven patterns into `specs/[capability]/design.md`
| Task | Tool | Why |
|------|------|-----|
| Find files by pattern | Glob | Fast pattern matching |
| Search code content | Grep | Optimized regex search |
| Read specific files | Read | Direct file access |
| Explore unknown scope | Task | Multi-step investigation |
This ensures changes are only archived when truly complete and deployed.
## Error Recovery
### 8. Types of Changes That Don't Require Specs
### Change Conflicts
1. Run `openspec list` to see active changes
2. Check for overlapping specs
3. Coordinate with change owners
4. Consider combining proposals
Some changes only affect development infrastructure and don't need specs:
- Initial project setup (package.json, tsconfig.json, etc.)
- Development tooling changes (linters, formatters, build tools)
- CI/CD configuration
- Development dependencies
### Validation Failures
1. Run with `--strict` flag
2. Check JSON output for details
3. Verify spec file format
4. Ensure scenarios properly formatted
For these changes:
1. Implement → Deploy → Mark tasks complete → Archive
2. Skip the "Update Specs" step entirely
### Missing Context
1. Read project.md first
2. Check related specs
3. Review recent archives
4. Ask for clarification
### What Deserves a Spec?
## Quick Reference
Ask yourself:
- Is this a system capability that users or other systems interact with?
- Does it have ongoing behavior that needs documentation?
- Would a new developer need to understand this to work with the system?
### Stage Indicators
- `changes/` - Proposed, not yet built
- `specs/` - Built and deployed
- `archive/` - Completed changes
If NO to all → No spec needed (likely just tooling/infrastructure)
### File Purposes
- `proposal.md` - Why and what
- `tasks.md` - Implementation steps
- `design.md` - Technical decisions
- `spec.md` - Requirements and behavior
## Understanding Specs vs Code
### Specs Document WHAT and WHY
```markdown
# Authentication Spec
Users SHALL authenticate with email and password.
WHEN credentials are valid THEN issue JWT token.
WHEN credentials are invalid THEN return generic error.
WHY: Prevent user enumeration attacks.
### CLI Essentials
```bash
openspec list # What's in progress?
openspec show [item] # View details
openspec validate --strict # Is it correct?
openspec archive [change] # Mark complete
```
### Code Documents HOW
```javascript
// Implementation details
const user = await db.users.findOne({ email });
const valid = await bcrypt.compare(password, user.hashedPassword);
```
**Key Distinction**: Specs capture intent, constraints, and decisions that aren't obvious from code.
## Common Scenarios
### New Feature Request
```
User: "Add password reset functionality"
You should:
1. Read specs/user-auth/spec.md
2. Check changes/ for pending auth changes
3. Create changes/add-password-reset/ with:
- proposal.md describing the change
- specs/user-auth/spec.md with:
## ADDED Requirements
### Requirement: Password Reset
[Complete requirement for password reset]
## MODIFIED Requirements
### Requirement: User Authentication
[Updated to integrate with password reset]
4. Wait for approval before implementing
```
### Bug Fix
```
User: "Getting null pointer error when bio is empty"
You should:
1. Check if spec says bios are optional
2. If yes → Fix directly (it's a bug)
3. If no → Create change proposal (it's a behavior change)
```
### Infrastructure Setup
```
User: "Initialize TypeScript project"
You should:
1. Create change proposal for TypeScript setup
2. Implement configuration files (PR #1)
3. Mark tasks complete in tasks.md
4. After deployment, create separate PR to archive
(no specs update needed - this is tooling, not a capability)
```
## Summary Workflow
1. **Receive request** → Determine if it needs a change proposal
2. **Read current state** → Check specs and pending changes
3. **Create proposal** → Generate complete change documentation
4. **Get approval** → User reviews the proposal
5. **Implement** → Follow approved tasks, mark completed items in tasks.md
6. **Deploy** → User deploys the implementation
7. **Archive PR** → Create separate PR to:
- Move change to archive
- Update specs if needed
- Mark change as complete
## PR Workflow Examples
### Single Developer, Simple Change
```
PR #1: Implementation
- Implement all tasks
- Update tasks.md marking items complete
- Get merged and deployed
PR #2: Archive (after deployment)
- Move changes/feature-x/ → changes/archive/2025-01-15-feature-x/
- Update specs if needed
```
### Multiple Developers, Complex Change
```
PR #1: Alice implements auth components
- Complete tasks 1.1, 1.2, 1.3
- Update tasks.md marking these complete
PR #2: Bob implements UI components
- Complete tasks 2.1, 2.2
- Update tasks.md marking these complete
PR #3: Alice fixes integration issues
- Complete remaining task 1.4
- Update tasks.md
[Deploy all changes]
PR #4: Archive
- Move to archive with deployment date
- Update specs to reflect new auth flow
```
### Key Rules
- **Never archive in implementation PRs** - changes aren't done until deployed
- **Always update tasks.md** - shows accurate progress
- **One archive PR per change** - clear completion boundary
- **Archive PR includes spec updates** - keeps specs current
## Capability Organization Best Practices
### Naming Capabilities
- Use **verb-noun** patterns: `user-auth`, `payment-capture`, `order-checkout`
- Be specific: `payment-capture` not just `payments`
- Keep flat: Avoid nesting capabilities within capabilities
- Singular focus: If you need "AND" to describe it, split it
### When to Split Capabilities
Split when you have:
- Multiple unrelated API endpoints
- Different user personas or actors
- Separate deployment considerations
- Independent evolution paths
#### Capability Boundary Guidelines
- Would you import these separately? → Separate capabilities
- Different deployment cadence? → Separate capabilities
- Different teams own them? → Separate capabilities
- Shared data models are OK, shared business logic means combine
Examples:
- user-auth (login/logout) vs user-sessions (token management) → SEPARATE
- payment-capture vs payment-refunds → SEPARATE (different workflows)
- user-profile vs user-settings → COMBINE (same data model, same owner)
### Cross-Cutting Concerns
For system-wide policies (rate limiting, error handling, security), document them in:
- `project.md` for project-wide conventions
- Within relevant capability specs where they apply
- Or create a dedicated capability if complex enough (e.g., `api-rate-limiting/`)
### Examples of Well-Organized Capabilities
```
specs/
├── user-auth/ # Login, logout, password reset
├── user-sessions/ # Token management, refresh
├── user-profile/ # Profile CRUD operations
├── payment-capture/ # Processing payments
├── payment-refunds/ # Handling refunds
└── order-checkout/ # Checkout workflow
```
For detailed guidance, see the [Capability Organization Guide](../docs/capability-organization.md).
## Common Scenarios and Clarifications
### Decision Ambiguity: Bug vs Behavior Change
When specs are missing or ambiguous:
- If NO spec exists → Treat current code behavior as implicit spec, require proposal
- If spec is VAGUE → Require proposal to clarify spec alongside fix
- If code and spec DISAGREE → Spec is truth, code is buggy (fix without proposal)
- If unsure → Default to creating a proposal (safer option)
Example:
```
User: "The API returns 404 for missing users but should return 400"
AI: Is this a bug (spec says 400) or behavior change (spec says 404)?
```
### When You Don't Know the Scope
It's OK to explore first! Tell the user you need to investigate, then create an informed proposal.
### Exploration Phase (When Needed)
BEFORE creating proposal, you may need exploration when:
- User request is vague or high-level
- Multiple implementation approaches exist
- Scope is unclear without seeing code
Exploration checklist:
1. Tell user you need to explore first
2. Use Grep/Read to understand current state
3. Create initial proposal based on findings
4. Refine with user feedback
Example:
```
User: "Add caching to improve performance"
AI: "Let me explore the codebase to understand the current architecture and identify caching opportunities."
[After exploration]
AI: "Based on my analysis, I've identified three areas where caching would help. Here's my proposal..."
```
### When No Specs Exist
Treat current code as implicit spec. Your proposal should document current state AND proposed changes.
### When in Doubt
Default to creating a proposal. It's easier to skip an unnecessary proposal than fix an undocumented change.
### AI Workflow Adaptations
Task tracking with OpenSpec:
- Track exploration tasks separately from implementation
- Document proposal creation steps as you go
- Keep implementation tasks separate until proposal approved
Parallel operations encouraged:
- Read multiple specs simultaneously
- Check multiple pending changes at once
- Batch related searches for efficiency
Progress communication:
- "Exploring codebase to understand scope..."
- "Creating proposal based on findings..."
- "Implementing approved changes..."
### For AI Assistants
- **Bias toward simplicity** - Propose the minimal solution that works
- Use your exploration tools liberally before proposing
- Batch operations for efficiency
- Communicate your progress
- It's OK to revise proposals based on discoveries
- **Question complexity** - If your solution feels complex, simplify first
## Edge Case Handling
### Multi-Capability Changes
Create ONE proposal that:
- Lists all affected capabilities
- Shows changes per capability
- Has unified task list
- Gets approved as a whole
### Outdated Specs
If specs clearly outdated:
1. Create proposal to update specs to match reality
2. Implement new feature in separate proposal
3. OR combine both in one proposal with clear sections
### Emergency Hotfixes
For critical production issues:
1. Announce: "This is an emergency fix"
2. Implement fix immediately
3. Create retroactive proposal
4. Update specs after deployment
5. Tag with [EMERGENCY] in archive
### Pure Refactoring
No proposal needed for:
- Code formatting/style
- Internal refactoring (same API)
- Performance optimization (same behavior)
- Adding types to untyped code
Proposal REQUIRED for:
- API changes (even if compatible)
- Database schema changes
- Architecture changes
- New dependencies
### Observability Additions
No proposal needed for:
- Adding log statements
- New metrics/traces
- Debugging additions
- Error tracking
Proposal REQUIRED if:
- Changes log format/structure
- Adds new monitoring service
- Changes what's logged (privacy)
## Remember
- You are the process driver - automate documentation burden
- Specs must always reflect deployed reality
- Changes are proposed, not imposed
- Impact analysis prevents surprises
- Simplicity is the power - just markdown files, minimal solutions
- Start simple, add complexity only when justified
By following these conventions, you enable true spec-driven development where documentation stays current, changes are traceable, and evolution is intentional.
Remember: Specs are truth. Changes are proposals. Keep them in sync.
@@ -1,6 +1,6 @@
## MODIFIED Requirements
### Requirement: List Command Behavior
### Requirement: Command Execution
The current `list` command behavior SHALL be preserved but marked as deprecated.
@@ -1,4 +1,4 @@
## MODIFIED Requirements
## ADDED Requirements
### Requirement: Diff Command Enhancement
@@ -24,6 +24,8 @@ Before moving the change to archive, the command SHALL apply delta changes to ma
- **THEN** abort with error message showing the conflict
- **AND** suggest manual resolution
## ADDED Requirements
### Requirement: Display Output
The command SHALL provide clear feedback about delta operations.
@@ -31,6 +31,8 @@ The command SHALL show a requirement-level comparison displaying only changed re
- Indicates removed requirements (not in future)
- Aligns modified requirements for easy comparison
## ADDED Requirements
### Requirement: Validation
The command SHALL validate that changes can be applied successfully.
@@ -1,6 +1,6 @@
# OpenSpec Conventions - Changes
## ADDED Requirements
## MODIFIED Requirements
### Requirement: Header-Based Requirement Identification
@@ -31,8 +31,6 @@ Requirement headers SHALL serve as unique identifiers for programmatic matching
- **THEN** ensure no duplicate headers exist within a spec
- **AND** validation tools SHALL flag duplicate headers as errors
## MODIFIED Requirements
### Requirement: Change Storage Convention
Change proposals SHALL store only the additions, modifications, and removals to specifications, not complete future states.
@@ -100,18 +98,4 @@ The archive process SHALL programmatically apply delta changes to current specif
- **AND** require manual resolution before proceeding
- **AND** provide clear guidance on resolving conflicts
## REMOVED Requirements
### Requirement: Future State Storage
The system SHALL no longer store complete future-state specifications in change proposals.
**Reason for removal**: Replaced by delta-based change storage which provides better review experience and clearer change tracking.
**Migration path**: All new changes must use delta format.
#### Scenario: Deprecate future state storage
- **WHEN** creating a new change proposal
- **THEN** do not include full future-state specs
- **AND** include only ADDED/MODIFIED/REMOVED/RENAMED requirements under the change's `specs/` directory
@@ -43,8 +43,6 @@ The command SHALL provide clear feedback when no items are present for the selec
- **WHEN** no specs directory exists or contains no capabilities
- **THEN** display: "No specs found."
## ADDED Requirements
### Requirement: Flags
The command SHALL accept flags to select the noun being listed.
@@ -106,6 +106,8 @@ Where `Issue` follows the existing per-item validation report shape `{ level: "E
### Requirement: Item type detection and ambiguity handling
The validate command SHALL handle ambiguous names and explicit type overrides to ensure clear, deterministic behavior.
#### Scenario: Direct item validation with automatic type detection
- **WHEN** executing `openspec validate <item-name>`
@@ -138,4 +140,10 @@ Where `Issue` follows the existing per-item validation report shape `{ level: "E
- The CLI SHALL respect `--no-interactive` to disable prompts.
- The CLI SHALL respect `OPEN_SPEC_INTERACTIVE=0` to disable prompts globally.
- Interactive prompts SHALL only be shown when stdin is a TTY and interactivity is not disabled.
- Interactive prompts SHALL only be shown when stdin is a TTY and interactivity is not disabled.
#### Scenario: Disabling prompts via flags or environment
- **WHEN** `openspec validate` is executed with `--no-interactive` or with environment `OPEN_SPEC_INTERACTIVE=0`
- **THEN** the CLI SHALL not display interactive prompts
- **AND** SHALL print non-interactive hints or chosen outputs as appropriate
@@ -0,0 +1,25 @@
# improve-validate-error-messages
## Why
Developers struggle to resolve validation failures because current errors lack actionable guidance. Common issues include: missing deltas, missing required sections, and misformatted scenarios that are silently ignored. Without clear remediation steps, users cannot quickly correct structure or formatting, leading to frustration and rework. Improving error messages with concrete fixes, file/section hints, and suggested commands will significantly reduce time-to-green and make OpenSpec more approachable.
## What Changes
- Validation errors SHALL include specific remediation steps (what to change and where).
- "No deltas found" error SHALL guide users to create `specs/` with proper delta headers and suggest debug commands.
- Missing required sections (Spec: Purpose/Requirements; Change: Why/What Changes) SHALL include expected header names and a minimal skeleton example.
- Likely misformatted scenarios (bulleted WHEN/THEN/AND) SHALL emit a targeted warning explaining the `#### Scenario:` format and show a conversion template.
- All reported issues SHALL include the source file path and structured location (e.g., `deltas[0].requirements[0]`).
- Non-JSON output SHOULD end with a short "Next steps" footer when invalid.
## Impact
- Affected CLI: validate
- Affected code:
- `src/commands/validate.ts`
- `src/core/validation/validator.ts`
- `src/core/validation/constants.ts`
- `src/core/parsers/*` (wrapping thrown errors with richer context)
@@ -0,0 +1,55 @@
# Validate Command
## ADDED Requirements
### Requirement: Validation SHALL provide actionable remediation steps
Validation output SHALL include specific guidance to fix each error, including expected structure, example headers, and suggested commands to verify fixes.
#### Scenario: No deltas found in change
- **WHEN** validating a change with zero parsed deltas
- **THEN** show error "No deltas found" with guidance:
- Ensure `openspec/changes/{id}/specs/` exists with `.md` files
- Use delta headers: `## ADDED Requirements`, `## MODIFIED Requirements`, `## REMOVED Requirements`, `## RENAMED Requirements`
- Each requirement must include at least one `#### Scenario:` block
- Try: `openspec change show {id} --json --deltas-only` to inspect what was parsed
#### Scenario: Missing required sections
- **WHEN** a required section is missing
- **THEN** the validator SHALL include expected header names and a minimal skeleton:
- For Spec: `## Purpose`, `## Requirements`
- For Change: `## Why`, `## What Changes`
- Show an example snippet of the missing section
### Requirement: Validator SHALL detect likely misformatted scenarios and warn with a fix
The validator SHALL recognize bulleted lines that look like scenarios (e.g., lines beginning with WHEN/THEN/AND) and emit a targeted warning with a conversion example to `#### Scenario:`.
#### Scenario: Bulleted WHEN/THEN under a Requirement
- **WHEN** bullets that start with WHEN/THEN/AND are found under a requirement without any `#### Scenario:` headers
- **THEN** emit warning: "Scenarios must use '#### Scenario:' headers", and show a conversion template:
```
#### Scenario: Short name
- **WHEN** ...
- **THEN** ...
- **AND** ...
```
### Requirement: All issues SHALL include file paths and structured locations
Error, warning, and info messages SHALL include:
- Source file path (`openspec/changes/{id}/proposal.md`, `.../specs/{cap}/spec.md`)
- Structured path (e.g., `deltas[0].requirements[0].scenarios`)
#### Scenario: Zod validation error
- **WHEN** a schema validation fails
- **THEN** the message SHALL include `file`, `path`, and a remediation hint if applicable
### Requirement: Invalid results SHALL include a Next steps footer in human-readable output
The CLI SHALL append a Next steps footer when the item is invalid and not using `--json`, including:
- Summary line with counts
- Top-3 guidance bullets (contextual to the most frequent or blocking errors)
- A suggestion to re-run with `--json` and/or the debug command
#### Scenario: Change invalid summary
- **WHEN** a change validation fails
- **THEN** print "Next steps" with 2-3 targeted bullets and suggest `openspec change show <id> --json --deltas-only`
@@ -0,0 +1,21 @@
## 1. Enhance validation messages
- [x] 1.1 Add remediation guidance for "No deltas found"
- [x] 1.2 Include file path and structured path in all issues
- [x] 1.3 Improve messages for missing required sections (Spec, Change)
- [x] 1.4 Detect likely misformatted scenarios and warn with conversion example
- [x] 1.5 Add "Next steps" footer for non-JSON invalid output
## 2. Update constants and helpers
- [x] 2.1 Centralize guidance snippets in `VALIDATION_MESSAGES`
- [x] 2.2 Provide minimal skeleton examples for missing sections
## 3. Parser integration
- [x] 3.1 Capture parser-thrown errors and wrap with richer context
- [x] 3.2 Add file/section references to surfaced parser errors
## 4. Tests
- [x] 4.1 Unit tests for validator message composition
- [x] 4.2 CLI integration tests for human-readable output (with footer)
- [x] 4.3 JSON mode tests (structure unchanged, content enriched)
@@ -0,0 +1,78 @@
# Change: Improve Deterministic Tests (Isolate From Repo State)
## Problem
Some unit tests (e.g., ChangeCommand.show/validate) read the live repository
state via `process.cwd()` and `openspec/changes`. This makes outcomes depend on
whatever directories happen to exist and the order returned by `fs.readdir`,
causing flaky success/failure across environments.
Symptoms observed:
- Tests sometimes select a partial or unrelated change folder.
- Failures like missing `proposal.md` when a stray change directory is picked.
- Environment/sandbox differences alter `readdir` ordering and worker behavior.
## Goals
- Make tests deterministic and hermetic.
- Remove dependence on real repo contents and directory ordering.
- Keep runtime behavior unchanged for end users.
## Non‑Goals
- Introduce heavy frameworks or test harness complexity.
- Redesign CLI behavior or change default paths for users.
## Approach
1) Test-local fixture root
- Each suite that touches filesystem discovery creates a temporary directory:
- `openspec/changes/sample-change/proposal.md`
- `openspec/changes/sample-change/specs/sample/spec.md`
- `beforeAll`: `process.chdir(tmpRoot)`; `afterAll`: restore original cwd.
- Use a constant `changeName = 'sample-change'`; remove reliance on
`readdir` order.
2) Optional thin DI for commands (minimal, if needed)
- Allow `ChangeCommand` (and similar) to accept an optional `root` path
(default `process.cwd()`), used for path resolution.
- Tests pass the temp root explicitly; production code remains unchanged.
3) Harden discovery helpers (safe enhancement)
- Update `getActiveChangeIds()`/`getActiveChanges()` to include only
directories containing `proposal.md` (and optionally at least one
`specs/*/spec.md`).
- Prevents incomplete/stray change folders from being treated as active.
## Rationale
- Small, focused changes eliminate flakiness without altering user workflows.
- Temporary fixtures are a well-understood testing pattern and keep tests fast.
- Optional constructor root param is a minimal DI surface that avoids global
stubbing and keeps code simple.
## Risks & Mitigations
- Risk: Tests forget to restore `process.cwd()`.
- Mitigation: Add `afterAll` guard restoring cwd; reset `process.exitCode` in
`afterEach` where modified.
- Risk: Behavior divergence if DI root is misused.
- Mitigation: Default to `process.cwd()`; only tests pass custom roots.
## Acceptance Criteria
- Tests that previously depended on repo state now:
- Create and use a temp fixture root.
- Do not read real `openspec/changes` during execution.
- Pass consistently regardless of directory order or stray folders.
- No change to CLI behavior for end users (paths still default to cwd).
## Rollout
- Phase 1: Convert the suites that hit `ChangeCommand.show/validate` to
isolated fixtures; verify stability locally and in CI.
- Phase 2: Apply the same pattern to any remaining suites that touch file
discovery (`list`, `show`, `validate`, `diff`).
- Phase 3 (optional): Introduce the constructor `root` param and discovery
hardening, if Phase 1 alone isn’t sufficient.
@@ -0,0 +1,25 @@
# Implementation Tasks
## 1. Test Isolation
- [x] 1.1 Create temp fixture roots per suite (openspec/changes, openspec/specs)
- [x] 1.2 Use process.chdir to temp root within tests
- [x] 1.3 Restore original cwd and clean temp dirs after each
## 2. Deterministic Discovery
- [x] 2.1 Implement getActiveChangeIds(root?) to only include dirs with proposal.md
- [x] 2.2 Implement getSpecIds(root?) to only include dirs with spec.md
- [x] 2.3 Return sorted results to avoid fs.readdir ordering variance
## 3. Command Integration
- [x] 3.1 Ensure change/show/validate rely on cwd and discovery helpers
- [x] 3.2 Keep runtime behavior unchanged for end users
## 4. Validation
- [x] 4.1 Convert affected command tests (show, spec, validate, change) to isolated fixtures
- [x] 4.2 Verify tests pass consistently across environments
- [x] 4.3 Confirm no reads from real repo state during tests
## 5. Optional (Not Needed Now)
- [x] 5.1 Add optional root param to discovery helpers (default process.cwd())
- [ ] 5.2 Consider threading root through command constructors if ever required
@@ -0,0 +1,81 @@
# Remove Diff Command
## Problem
The `openspec diff` command adds unnecessary complexity to the OpenSpec CLI for several reasons:
1. **Redundant functionality**: The `openspec show` command already provides comprehensive visualization of changes through structured JSON output and markdown rendering
2. **Maintenance burden**: The diff command requires a separate dependency (jest-diff) and additional code complexity (~227 lines)
3. **Limited value**: Developers can achieve better diff visualization using existing tools:
- Git diff for actual file changes
- The `show` command for structured change viewing
- Standard diff utilities for comparing spec files directly
4. **Inconsistent with verb-noun pattern**: The command doesn't follow the preferred verb-first command structure that other commands are migrating to
## Solution
Remove the `openspec diff` command entirely and guide users to more appropriate alternatives:
1. **For viewing change content**: Use `openspec show <change-name>` which provides:
- Structured JSON output with `--json` flag
- Markdown rendering for human-readable format
- Delta-only views with `--deltas-only` flag
- Full spec content visualization
2. **For comparing files**: Use standard tools:
- `git diff` for version control comparisons
- System diff utilities for file-by-file comparisons
- IDE diff viewers for visual comparisons
## Benefits
- **Reduced complexity**: Removes ~227 lines of code and the jest-diff dependency
- **Clearer user journey**: Directs users to the canonical `show` command for viewing changes
- **Lower maintenance**: Fewer commands to maintain and test
- **Better alignment**: Focuses on the core OpenSpec workflow without redundant features
## Implementation
### Files to Remove
- `/src/core/diff.ts` - The entire diff command implementation
- `/openspec/specs/cli-diff/spec.md` - The diff command specification
### Files to Update
- `/src/cli/index.ts` - Remove diff command registration (lines 8, 84-96)
- `/package.json` - Remove jest-diff dependency
- `/README.md` - Remove diff command documentation
- `/openspec/README.md` - Remove diff command references
- Various documentation files mentioning `openspec diff`
### Migration Guide for Users
Users currently using `openspec diff` should transition to:
```bash
# Before
openspec diff add-feature
# After - view the change proposal
openspec show add-feature
# After - view only the deltas
openspec show add-feature --json --deltas-only
# After - use git for file comparisons
git diff openspec/specs openspec/changes/add-feature/specs
```
## Risks
- **User disruption**: Existing users may have workflows depending on the diff command
- Mitigation: Provide clear migration guide and deprecation period
- **Loss of visual diff**: The colored, unified diff format will no longer be available
- Mitigation: Users can use git diff or other tools for visual comparisons
## Success Metrics
- Successful removal with no broken dependencies
- Documentation updated to reflect the change
- Tests passing without the diff command
- Reduced package size from removing jest-diff dependency
@@ -0,0 +1,41 @@
# Remove Diff Command - Tasks
## 1. Remove Core Implementation
- [x] Delete `/src/core/diff.ts`
- [x] Remove DiffCommand import from `/src/cli/index.ts`
- [x] Remove diff command registration from CLI
## 2. Remove Specifications
- [x] Delete `/openspec/specs/cli-diff/spec.md`
- [x] Archive the spec for historical reference if needed
## 3. Update Dependencies
- [x] Remove jest-diff from package.json dependencies
- [x] Run pnpm install to update lock file
## 4. Update Documentation
- [x] Update main README.md to remove diff command references
- [x] Update openspec/README.md to remove diff command from command list
- [x] Update CLAUDE.md template if it mentions diff command
- [x] Update any example workflows that use diff command
## 5. Update Related Files
- [x] Search and update any remaining references to "openspec diff" in:
- Template files
- Test files (if any exist for diff command)
- Archive documentation
- Change proposals
## 6. Add Deprecation Notice (Optional Phase)
- [ ] Consider adding a deprecation warning before full removal
- [ ] Provide helpful message directing users to `openspec show` command
## 7. Testing
- [x] Ensure all tests pass after removal
- [x] Verify CLI help text no longer shows diff command
- [x] Test that show command provides adequate replacement functionality
## 8. Documentation of Alternative Workflows
- [x] Document how to use `openspec show` for viewing changes
- [x] Document how to use git diff for file comparisons
- [x] Add migration guide to help text or documentation
@@ -0,0 +1,130 @@
# Design: Agent Instructions Update
## Approach
### Information Architecture
- **Front-load critical information** - Three-stage workflow comes first
- **Clear hierarchy** - Core Workflow → Quick Start → Commands → Details → Edge Cases
- **50% length reduction** - Target ~285 lines from current ~575 lines
- **Imperative mood** - "Create proposal" vs "You should create a proposal"
- **Bullet points over paragraphs** - Scannable, concise information
### Three-Stage Workflow Documentation
The workflow is now prominently featured as a core concept:
1. **Creating** - Proposal generation phase
2. **Implementing** - Code development phase with explicit steps:
- Read proposal.md for understanding
- Read design.md for technical context
- Read tasks.md for checklist
- Implement tasks sequentially
- Mark complete immediately after each task
3. **Archiving** - Post-deployment finalization phase
This structure helps agents understand the lifecycle and their role at each stage. The implementation phase is particularly detailed to prevent common mistakes like skipping documentation or batching task completion.
### CLI Documentation Updates
- **Comprehensive command coverage** - All 9 primary commands documented
- **`openspec list` prominence** - Essential for discovering changes and specs
- **Interactive mode documentation** - How agents can use prompts effectively
- **Complete flag documentation** - All options like --json, --type, --skip-specs
- **Deprecation cleanup** - Remove noun-first patterns (openspec change show)
### Agent-Specific Enhancements
Based on industry best practices for coding agents (Claude Code, Cursor, etc.):
**Implementation Workflow**
- Explicit steps prevent skipping critical context
- Reading proposal/design first ensures understanding before coding
- Sequential task completion maintains focus
- Immediate marking prevents losing track of progress
- Addresses common failure mode: jumping straight to code
**Spec Discovery Workflow**
- Always check existing specs before creating new ones
- Use `openspec list --specs` to discover current capabilities
- Prefer modifying existing specs over creating duplicates
- Prevents fragmentation and maintains coherent architecture
**Decision Clarity**
- Clear decision trees eliminating ambiguous conditions
- Concrete examples for each decision branch
- Simplified bug vs feature determination
**Tool Usage Guidance**
- Tool selection matrix (when to use Grep vs Glob vs Read)
- Error recovery patterns for common failures
- Verification workflows to confirm correctness
**Context Management**
- "Before Any Task" checklist for gathering context
- What to read before starting any work
- How to maintain state across interactions
**Spec File Structure Documentation**
- Complete examples with ADDED/MODIFIED/REMOVED sections
- Critical scenario formatting (#### Scenario: headers)
- Delta file location clarity (changes/{name}/specs/)
- Addresses most common creation errors from retrospective
**Troubleshooting and Debugging**
- Common error messages with solutions
- Delta detection debugging steps
- Validation best practices
- JSON output for inspection
- Prevents hours of frustration from silent failures
**Best Practices**
- Be concise (one-line answers when appropriate)
- Be specific (file.ts:42 line references)
- Start simple (<100 lines, single-file defaults)
- Justify complexity (require metrics/data)
## Design Rationale
### Why These Changes Matter
**Cognitive Load Reduction**
- Agents process instructions better with clear structure
- Front-loading critical info reduces scanning time
- Decision trees eliminate analysis paralysis
**Industry Alignment**
- Follows patterns proven effective in Claude Code, Cursor, GitHub Copilot
- Addresses common failure modes (ambiguous decisions, missing context)
- Optimizes for LLM strengths (pattern matching) vs weaknesses (calculations)
**Addressing Critical Pain Points (from Retrospective)**
- **Scenario formatting** - Biggest struggle, now explicitly documented with examples
- **Complete spec structure** - Full examples prevent structural errors
- **Delta detection issues** - Debugging commands help diagnose problems
- **Silent parsing failures** - Troubleshooting section explains common issues
**Practical Impact**
- Faster agent comprehension of tasks
- Fewer misinterpretations of requirements
- More consistent implementation quality
- Better error recovery when things go wrong
- Prevents the most common errors identified in user experience
## Trade-offs
### What We're Removing
- Lengthy explanations of concepts that can be inferred
- Redundant examples that don't add clarity
- Verbose edge case documentation (moved to reference section)
- Deprecated command documentation
### What We're Keeping
- All critical workflow steps
- Complete CLI command reference
- Complexity management principles
- Directory structure visualization
- Quick reference summary
## Implementation Notes
The CLAUDE.md template is intentionally more concise than README.md since:
- It appears in every project root
- Agents can reference the full README.md for details
- It needs to load quickly in AI context windows
- Focus is on immediate actionable guidance
@@ -0,0 +1,117 @@
# Update OpenSpec Agent Instructions
## Why
The current OpenSpec agent instructions need updates to follow best practices for AI assistant instructions (brevity, clarity, removing ambiguity), ensure CLI commands are current with the actual implementation, and properly document the three-stage workflow pattern that agents should follow.
## What Changes
### Core Structure Improvements
- **Front-load the 3-stage workflow** as the primary mental model:
1. Creating a change proposal (proposal.md, spec deltas, design.md, tasks.md)
2. Implementing a change proposal:
- First read proposal.md to understand the change
- Read design.md if it exists for technical context
- Read tasks.md for the implementation checklist
- Complete tasks one by one
- Mark each task complete immediately after finishing
3. Archiving the change proposal (using archive command after deployment)
- **Reduce instruction length by 50%** while maintaining all critical information
- **Restructure with clear hierarchy**: Core Workflow → Quick Start → Commands → Details → Edge Cases
### Decision Clarity Enhancements
- **Add clear decision trees** for common scenarios (bug vs feature, proposal needed vs not)
- **Remove ambiguous conditions** that confuse agent decision-making
- **Add "Before Any Task" checklist** for context gathering
- **Add "Before Creating Specs" rule** - Always check existing specs first to avoid duplicates
### CLI Documentation Updates
- **Complete command documentation** with all current functionality:
- `openspec init [path]` - Initialize OpenSpec in a project
- `openspec list` - List all active changes (default)
- `openspec list --specs` - List all specifications
- `openspec show [item]` - Display change or spec with auto-detection
- `openspec show` - Interactive mode for selection
- `openspec diff [change]` - Show spec differences for a change
- `openspec validate [item]` - Validate changes or specs
- `openspec archive [change]` - Archive completed change after deployment
- `openspec update [path]` - Update OpenSpec instruction files
- **Document all flags and options**:
- `--json` output format for programmatic use
- `--type change|spec` for disambiguation
- `--skip-specs` for tooling-only archives
- `--strict` for strict validation mode
- `--no-interactive` to disable prompts
- **Remove deprecated command references** (noun-first patterns like `openspec change show`)
- **Add concrete examples** for each command variation
- **Document debugging commands**:
- `openspec show [change] --json --deltas-only` for inspecting deltas
- `openspec validate [change] --strict` for comprehensive validation
### Spec File Structure Documentation
- **Complete spec file examples** showing proper structure:
```markdown
## ADDED Requirements
### Requirement: Clear requirement statement
The system SHALL provide the functionality...
#### Scenario: Descriptive scenario name
- **WHEN** condition occurs
- **THEN** expected outcome
- **AND** additional outcomes
```
- **Scenario formatting requirements** (critical - most common error):
- MUST use `#### Scenario:` headers (4 hashtags)
- NOT bullet lists or bold text
- Each requirement MUST have at least one scenario
- **Delta file location** - Clear explanation:
- Spec files go in `changes/{name}/specs/` directory
- Deltas are automatically extracted from these files
- Use operation prefixes: ADDED, MODIFIED, REMOVED, RENAMED
### Troubleshooting Section
- **Common errors and solutions**:
- "Change must have at least one delta" → Check specs/ directory exists with .md files
- "Requirement must have at least one scenario" → Check scenario uses `#### Scenario:` format
- Silent scenario parsing failures → Verify exact header format
- **Delta detection debugging**:
- Use `openspec show [change] --json --deltas-only` to inspect parsed deltas
- Check that spec files have operation prefixes (## ADDED Requirements)
- Verify specs/ subdirectory structure
- **Validation best practices**:
- Always use `--strict` flag for comprehensive checks
- Use JSON output for debugging: `--json | jq '.deltas'`
### Agent-Specific Improvements
- **Implementation workflow** - Clear step-by-step process:
1. Read proposal.md to understand what's being built
2. Read design.md (if exists) for technical decisions
3. Read tasks.md for the implementation checklist
4. Implement tasks one by one in order
5. Mark each task complete immediately: `- [x] Task completed`
6. Never skip ahead or batch task completion
- **Spec discovery workflow** - Always check existing specs before creating new ones:
- Use `openspec list --specs` to see all current specs
- Check if capability already exists before creating
- Prefer modifying existing specs over creating duplicates
- **Tool selection matrix** - When to use Grep vs Glob vs Read
- **Error recovery patterns** - How to handle common failures
- **Context management guide** - What to read before starting tasks
- **Verification workflows** - How to confirm changes are correct
### Best Practices Section
- **Be concise** - One-line answers when appropriate
- **Be specific** - Use exact file paths and line numbers (file.ts:42)
- **Start simple** - Default to <100 lines, single-file implementations
- **Justify complexity** - Require data/metrics for any optimization
## Impact
- Affected specs: None (this is a tooling/documentation change)
- Affected code:
- `src/core/templates/claude-template.ts` - Update CLAUDE.md template
- Affected documentation:
- `openspec/README.md` - Main OpenSpec instructions
- CLAUDE.md files generated by `openspec init` command
Note: This is a tooling/infrastructure change that doesn't require spec updates. When archiving, use `openspec archive update-agent-instructions --skip-specs`.
@@ -0,0 +1,69 @@
# Implementation Tasks
## 1. Restructure OpenSpec README.md
- [x] 1.1 Front-load the three-stage workflow as primary content
- [x] 1.2 Restructure with hierarchy: Core Workflow → Quick Start → Commands → Details → Edge Cases
- [x] 1.3 Reduce total length by 50% (target: ~285 lines from current ~575)
- [x] 1.4 Add "Before Any Task" context-gathering checklist
- [x] 1.5 Add "Before Creating Specs" rule to check existing specs first
## 2. Add Decision Clarity
- [x] 2.1 Create clear decision trees for "Create Proposal?" scenarios
- [x] 2.2 Remove ambiguous conditions that confuse agents
- [x] 2.3 Add concrete examples for each decision branch
- [x] 2.4 Simplify bug vs feature determination logic
- [x] 2.5 Add explicit Stage 2 implementation steps (read → implement → mark complete)
## 3. Update CLI Documentation
- [x] 3.1 Document `openspec list` and `openspec list --specs` commands
- [x] 3.2 Document `openspec show` with all flags and interactive mode
- [x] 3.3 Document `openspec diff [change]` for viewing spec differences
- [x] 3.4 Document `openspec archive` with --skip-specs option
- [x] 3.5 Document `openspec validate` with --strict and batch modes
- [x] 3.6 Document `openspec init` and `openspec update` commands
- [x] 3.7 Remove all deprecated noun-first command references
- [x] 3.8 Add concrete usage examples for each command variation
- [x] 3.9 Document all flags: --json, --type, --no-interactive, etc.
- [x] 3.10 Document debugging commands: `show --json --deltas-only`
## 4. Add Spec File Documentation
- [x] 4.1 Add complete spec file structure example with ADDED/MODIFIED sections
- [x] 4.2 Document scenario formatting requirements (#### Scenario: headers)
- [x] 4.3 Explain delta file location (changes/{name}/specs/ directory)
- [x] 4.4 Show how deltas are automatically extracted
- [x] 4.5 Include warning about most common error (scenario formatting)
## 5. Add Troubleshooting Section
- [x] 5.1 Document common errors and their solutions
- [x] 5.2 Add delta detection debugging steps
- [x] 5.3 Include validation best practices (--strict flag)
- [x] 5.4 Show how to use JSON output for debugging
- [x] 5.5 Add examples of silent parsing failures
## 6. Add Agent-Specific Sections
- [x] 6.1 Add implementation workflow (read docs → implement tasks → mark complete)
- [x] 6.2 Add spec discovery workflow (check existing before creating)
- [x] 6.3 Create tool selection matrix (Grep vs Glob vs Read)
- [x] 6.4 Add error recovery patterns section
- [x] 6.5 Add context management guide
- [x] 6.6 Add verification workflows section
- [x] 6.7 Add best practices section (concise, specific, simple)
## 7. Update CLAUDE.md Template
- [x] 7.1 Update `src/core/templates/claude-template.ts` with streamlined content
- [x] 7.2 Include three-stage workflow prominently
- [x] 7.3 Add comprehensive CLI quick reference (list, show, diff, archive, etc.)
- [x] 7.4 Add "Before Any Task" checklist
- [x] 7.5 Add "Before Creating Specs" rule
- [x] 7.6 Keep complexity management principles
- [x] 7.7 Add critical scenario formatting note (#### Scenario: headers)
- [x] 7.8 Include debugging command reference
## 8. Testing and Validation
- [x] 8.1 Test all documented CLI commands for accuracy
- [x] 8.2 Run `openspec init` to verify CLAUDE.md generation
- [x] 8.3 Validate instruction clarity with example scenarios
- [x] 8.4 Ensure no critical information was lost in streamlining
- [x] 8.5 Verify decision trees eliminate ambiguity
- [x] 8.6 Test scenario formatting examples work correctly
- [x] 8.7 Verify troubleshooting steps resolve common errors
+75 -20
View File
@@ -10,9 +10,7 @@ openspec archive [change-name] [--yes|-y]
Options:
- `--yes`, `-y`: Skip confirmation prompts (for automation)
## Requirements
### Requirement: Change Selection
The command SHALL support both interactive and direct change selection methods.
@@ -72,26 +70,25 @@ The archive operation SHALL follow a structured process to safely move changes t
### Requirement: Spec Update Process
Before moving the change to archive, the command SHALL update main specs to reflect the deployed reality.
Before moving the change to archive, the command SHALL apply delta changes to main specs to reflect the deployed reality.
#### Scenario: Updating specs from change
#### Scenario: Applying delta changes
- **WHEN** the change contains specs in `changes/[name]/specs/`
- **THEN** execute these steps:
1. Analyze which specs will be affected by comparing with existing specs
2. Display a summary of spec updates to the user (see Confirmation Behavior below)
3. Prompt for confirmation unless `--yes` flag is provided
4. If confirmed, for each capability spec in the change directory:
- Copy the spec from `changes/[name]/specs/[capability]/spec.md` to `openspec/specs/[capability]/spec.md`
- Create the target directory structure if it doesn't exist
- Overwrite existing spec files (specs represent current reality, change specs are the new reality)
- Track which specs were updated for the success message
- **WHEN** archiving a change with delta-based specs
- **THEN** parse and apply delta changes as defined in openspec-conventions
- **AND** validate all operations before applying
#### Scenario: No specs in change
#### Scenario: Validating delta changes
- **WHEN** no specs exist in the change
- **THEN** skip the spec update step
- **AND** proceed with archiving
- **WHEN** processing delta changes
- **THEN** perform validations as specified in openspec-conventions
- **AND** if validation fails, show specific errors and abort
#### Scenario: Conflict detection
- **WHEN** applying deltas would create duplicate requirement headers
- **THEN** abort with error message showing the conflict
- **AND** suggest manual resolution
### Requirement: Confirmation Behavior
@@ -129,8 +126,6 @@ The spec update confirmation SHALL provide clear visibility into changes before
- **AND** display message: "Archive cancelled. No changes were made."
- **AND** exit with non-zero status code
## Error Handling
### Requirement: Error Conditions
The command SHALL handle various error conditions gracefully.
@@ -144,6 +139,66 @@ The command SHALL handle various error conditions gracefully.
- Archive target already exists
- File system permissions issues
### Requirement: Skip Specs Option
The archive command SHALL support a `--skip-specs` flag that skips all spec update operations and proceeds directly to archiving.
#### Scenario: Skipping spec updates with flag
- **WHEN** executing `openspec archive <change> --skip-specs`
- **THEN** skip spec discovery and update confirmation
- **AND** proceed directly to moving the change to archive
- **AND** display a message indicating specs were skipped
### Requirement: Non-blocking confirmation
The archive operation SHALL proceed when the user declines spec updates instead of cancelling the entire operation.
#### Scenario: User declines spec update confirmation
- **WHEN** the user declines spec update confirmation
- **THEN** skip spec updates
- **AND** continue with the archive operation
- **AND** display a success message indicating specs were not updated
### Requirement: Display Output
The command SHALL provide clear feedback about delta operations.
#### Scenario: Showing delta application
- **WHEN** applying delta changes
- **THEN** display for each spec:
- Number of requirements added
- Number of requirements modified
- Number of requirements removed
- Number of requirements renamed
- **AND** use standard output symbols (+ ~ - →) as defined in openspec-conventions:
```
Applying changes to specs/user-auth/spec.md:
+ 2 added
~ 3 modified
- 1 removed
→ 1 renamed
```
### Requirement: Archive Validation
The archive command SHALL validate changes before applying them to ensure data integrity.
#### Scenario: Pre-archive validation
- **WHEN** executing `openspec archive change-name`
- **THEN** validate the change structure first
- **AND** only proceed if validation passes
- **AND** show validation errors if it fails
#### Scenario: Force archive without validation
- **WHEN** executing `openspec archive change-name --no-validate`
- **THEN** skip validation (unsafe mode)
- **AND** show warning about skipping validation
## Why These Decisions
**Interactive selection**: Reduces typing and helps users see available changes
+91
View File
@@ -0,0 +1,91 @@
# cli-change Specification
## Purpose
TBD - created by archiving change add-change-commands. Update Purpose after archive.
## Requirements
### Requirement: Change Command
The system SHALL provide a `change` command with subcommands for displaying, listing, and validating change proposals.
#### Scenario: Show change as JSON
- **WHEN** executing `openspec change show update-error --json`
- **THEN** parse the markdown change file
- **AND** extract change structure and deltas
- **AND** output valid JSON to stdout
#### Scenario: List all changes
- **WHEN** executing `openspec change list`
- **THEN** scan the openspec/changes directory
- **AND** return list of all pending changes
- **AND** support JSON output with `--json` flag
#### Scenario: Show only requirement changes
- **WHEN** executing `openspec change show update-error --requirements-only`
- **THEN** display only the requirement changes (ADDED/MODIFIED/REMOVED/RENAMED)
- **AND** exclude why and what changes sections
#### Scenario: Validate change structure
- **WHEN** executing `openspec change validate update-error`
- **THEN** parse the change file
- **AND** validate against Zod schema
- **AND** ensure deltas are well-formed
### Requirement: Legacy Compatibility
The system SHALL maintain backward compatibility with the existing `list` command while showing deprecation notices.
#### Scenario: Legacy list command
- **WHEN** executing `openspec list`
- **THEN** display current list of changes (existing behavior)
- **AND** show deprecation notice: "Note: 'openspec list' is deprecated. Use 'openspec change list' instead."
#### Scenario: Legacy list with --all flag
- **WHEN** executing `openspec list --all`
- **THEN** display all changes (existing behavior)
- **AND** show same deprecation notice
### Requirement: Interactive show selection
The change show command SHALL support interactive selection when no change name is provided.
#### Scenario: Interactive change selection for show
- **WHEN** executing `openspec change show` without arguments
- **THEN** display an interactive list of available changes
- **AND** allow the user to select a change to show
- **AND** display the selected change content
- **AND** maintain all existing show options (--json, --deltas-only)
#### Scenario: Non-interactive fallback keeps current behavior
- **GIVEN** stdin is not a TTY or `--no-interactive` is provided or environment variable `OPEN_SPEC_INTERACTIVE=0`
- **WHEN** executing `openspec change show` without a change name
- **THEN** do not prompt interactively
- **AND** print the existing hint including available change IDs
- **AND** set `process.exitCode = 1`
### Requirement: Interactive validation selection
The change validate command SHALL support interactive selection when no change name is provided.
#### Scenario: Interactive change selection for validation
- **WHEN** executing `openspec change validate` without arguments
- **THEN** display an interactive list of available changes
- **AND** allow the user to select a change to validate
- **AND** validate the selected change
#### Scenario: Non-interactive fallback keeps current behavior
- **GIVEN** stdin is not a TTY or `--no-interactive` is provided or environment variable `OPEN_SPEC_INTERACTIVE=0`
- **WHEN** executing `openspec change validate` without a change name
- **THEN** do not prompt interactively
- **AND** print the existing hint including available change IDs
- **AND** set `process.exitCode = 1`
-120
View File
@@ -1,120 +0,0 @@
# CLI Diff Command Specification
## Purpose
The `openspec diff` command provides developers with a visual comparison between proposed spec changes and the current deployed specs.
## Command Syntax
```bash
openspec diff [change-name]
```
## Requirements
### Requirement: Without Arguments
The command SHALL provide an interactive selection when no change is specified.
#### Scenario: Running without arguments
- **WHEN** running `openspec diff` without arguments
- **THEN** list all available changes in the `changes/` directory (excluding archive)
- **AND** prompt user to select a change
### Requirement: With Change Name
The command SHALL compare specs when a specific change is provided.
#### Scenario: Running with change name
- **WHEN** running `openspec diff <change-name>`
- **THEN** compare all spec files in `changes/<change-name>/specs/` with corresponding files in `specs/`
### Requirement: Diff Output
The command SHALL generate appropriate diff output for all spec changes.
#### Scenario: Comparing existing files
- **WHEN** file exists in both locations
- **THEN** show unified diff
#### Scenario: New files
- **WHEN** file only exists in change
- **THEN** show as new file (all lines with +)
#### Scenario: Deleted files
- **WHEN** file only exists in current specs
- **THEN** show as deleted (all lines with -)
### Requirement: Display Format
The command SHALL use standard unified diff format for consistency with existing tools.
#### Scenario: Formatting diff output
- **WHEN** displaying diff output
- **THEN** use standard unified diff format:
- Lines prefixed with `-` for removed content
- Lines prefixed with `+` for added content
- Lines without prefix for unchanged context
- File headers showing the paths being compared
### Requirement: Color Support
The command SHALL enhance readability with colors when supported.
#### Scenario: Terminal with color support
- **WHEN** terminal supports colors
- **THEN** display:
- Removed lines in red
- Added lines in green
- File headers in bold
- Context lines in default color
### Requirement: Error Handling
The command SHALL provide clear error messages for various failure conditions.
#### Scenario: Change not found
- **WHEN** specified change doesn't exist
- **THEN** display error "Change '<name>' not found"
#### Scenario: No specs in change
- **WHEN** no specs directory in change
- **THEN** display "No spec changes found for '<name>'"
#### Scenario: Missing changes directory
- **WHEN** changes directory doesn't exist
- **THEN** display "No OpenSpec changes directory found"
## Examples
```bash
# View diff for specific change
$ openspec diff add-auth-feature
--- specs/user-auth/spec.md
+++ changes/add-auth-feature/specs/user-auth/spec.md
@@ -10,6 +10,8 @@
Users SHALL authenticate with email and password.
+Users MAY authenticate with OAuth providers.
+
WHEN credentials are valid THEN issue JWT token.
# List all changes and select
$ openspec diff
Available changes:
1. add-auth-feature
2. update-payment-flow
3. add-status-command
Select a change (1-3):
```
+11 -37
View File
@@ -3,26 +3,21 @@
## Purpose
The `openspec list` command SHALL provide developers with a quick overview of all active changes in the project, showing their names and task completion status.
## Requirements
### Requirement: Command Execution
The command SHALL scan and analyze either active changes or specs based on the selected mode.
The command SHALL scan and analyze items based on the selected mode to provide a comprehensive overview.
#### Scenario: Scanning for changes
- **WHEN** `openspec list` is executed (default)
#### Scenario: Scanning for changes (default)
- **WHEN** `openspec list` is executed without flags
- **THEN** scan the `openspec/changes/` directory for change directories
- **AND** exclude the `archive/` subdirectory from results
- **AND** parse each change's `tasks.md` file to count task completion
#### Scenario: Scanning for specs
- **WHEN** `openspec list --specs` is executed
- **THEN** scan the `openspec/specs/` directory for capability directories
- **THEN** scan the `openspec/specs/` directory for capabilities
- **AND** read each capability's `spec.md`
- **AND** parse the requirements to compute requirement counts
- **AND** parse requirements to compute requirement counts
### Requirement: Task Counting
@@ -37,61 +32,40 @@ The command SHALL accurately count task completion status using standard markdow
- **AND** calculate total tasks as the sum of completed and incomplete
### Requirement: Output Format
The command SHALL display items in a clear, readable table format with mode-appropriate progress or counts.
The command SHALL display items in a clear, readable table format with mode-appropriate indicators.
#### Scenario: Displaying change list
- **WHEN** displaying the list
#### Scenario: Displaying change list (default)
- **WHEN** displaying the list of changes
- **THEN** show a table with columns:
- Change name (directory name)
- Task progress (e.g., "3/5 tasks" or "✓ Complete")
#### Scenario: Displaying spec list
- **WHEN** displaying the list for specs mode
- **WHEN** displaying the list of specs
- **THEN** show a table with columns:
- Spec id (directory name)
- Requirement count (e.g., "requirements 12")
- **AND** use status indicators:
- `✓` for fully completed changes (all tasks done)
- Progress fraction for partial completion
Example output:
```
Changes:
add-auth-feature 3/5 tasks
update-api-docs ✓ Complete
fix-validation 0/2 tasks
add-list-command 1/4 tasks
```
### Requirement: Flags
The command SHALL accept flags to choose the noun being listed.
The command SHALL accept flags to select the noun being listed.
#### Scenario: Selecting specs
- **WHEN** `--specs` is provided
- **THEN** list specs instead of changes
#### Scenario: Selecting changes
- **WHEN** `--changes` is provided
- **THEN** list changes explicitly (same as default behavior)
### Requirement: Empty State
The command SHALL provide clear feedback when no items are present for the selected mode.
#### Scenario: Handling empty state (changes)
- **WHEN** no active changes exist (only archive/ or empty changes/)
- **THEN** display: "No active changes found."
#### Scenario: Handling empty state (specs)
- **WHEN** no specs exist or the `openspec/specs/` directory is missing
- **WHEN** no specs directory exists or contains no capabilities
- **THEN** display: "No specs found."
### Requirement: Error Handling
+85
View File
@@ -0,0 +1,85 @@
# cli-show Specification
## Purpose
TBD - created by archiving change add-interactive-show-command. Update Purpose after archive.
## Requirements
### Requirement: Top-level show command
The CLI SHALL provide a top-level `show` command for displaying changes and specs with intelligent selection.
#### Scenario: Interactive show selection
- **WHEN** executing `openspec show` without arguments
- **THEN** prompt user to select type (change or spec)
- **AND** display list of available items for selected type
- **AND** show the selected item's content
#### Scenario: Non-interactive environments do not prompt
- **GIVEN** stdin is not a TTY or `--no-interactive` is provided or environment variable `OPEN_SPEC_INTERACTIVE=0`
- **WHEN** executing `openspec show` without arguments
- **THEN** do not prompt
- **AND** print a helpful hint with examples for `openspec show <item>` or `openspec change/spec show`
- **AND** exit with code 1
#### Scenario: Direct item display
- **WHEN** executing `openspec show <item-name>`
- **THEN** automatically detect if item is a change or spec
- **AND** display the item's content
- **AND** use appropriate formatting based on item type
#### Scenario: Type detection and ambiguity handling
- **WHEN** executing `openspec show <item-name>`
- **THEN** if `<item-name>` uniquely matches a change or a spec, show that item
- **AND** if it matches both, print an ambiguity error and suggest `--type change|spec` or using `openspec change show`/`openspec spec show`
- **AND** if it matches neither, print not-found with nearest-match suggestions
#### Scenario: Explicit type override
- **WHEN** executing `openspec show --type change <item>`
- **THEN** treat `<item>` as a change ID and show it (skipping auto-detection)
- **WHEN** executing `openspec show --type spec <item>`
- **THEN** treat `<item>` as a spec ID and show it (skipping auto-detection)
### Requirement: Output format options
The show command SHALL support various output formats consistent with existing commands.
#### Scenario: JSON output
- **WHEN** executing `openspec show <item> --json`
- **THEN** output the item in JSON format
- **AND** include parsed metadata and structure
- **AND** maintain format consistency with existing change/spec show commands
#### Scenario: Flag scoping and delegation
- **WHEN** showing a change or a spec via the top-level command
- **THEN** accept common flags such as `--json`
- **AND** pass through type-specific flags to the corresponding implementation
- Change-only flags: `--deltas-only` (alias `--requirements-only` deprecated)
- Spec-only flags: `--requirements`, `--no-scenarios`, `-r/--requirement`
- **AND** ignore irrelevant flags for the detected type with a warning
### Requirement: Interactivity controls
- The CLI SHALL respect `--no-interactive` to disable prompts.
- The CLI SHALL respect `OPEN_SPEC_INTERACTIVE=0` to disable prompts globally.
- Interactive prompts SHALL only be shown when stdin is a TTY and interactivity is not disabled.
#### Scenario: Change-specific options
- **WHEN** showing a change with `openspec show <change-name> --deltas-only`
- **THEN** display only the deltas in JSON format
- **AND** maintain compatibility with existing change show options
#### Scenario: Spec-specific options
- **WHEN** showing a spec with `openspec show <spec-id> --requirements`
- **THEN** display only requirements in JSON format
- **AND** support other spec options (--no-scenarios, -r)
- **AND** maintain compatibility with existing spec show options
+87
View File
@@ -0,0 +1,87 @@
# cli-spec Specification
## Purpose
TBD - created by archiving change add-interactive-show-command. Update Purpose after archive.
## Requirements
### Requirement: Interactive spec show
The spec show command SHALL support interactive selection when no spec-id is provided.
#### Scenario: Interactive spec selection for show
- **WHEN** executing `openspec spec show` without arguments
- **THEN** display an interactive list of available specs
- **AND** allow the user to select a spec to show
- **AND** display the selected spec content
- **AND** maintain all existing show options (--json, --requirements, --no-scenarios, -r)
#### Scenario: Non-interactive fallback keeps current behavior
- **GIVEN** stdin is not a TTY or `--no-interactive` is provided or environment variable `OPEN_SPEC_INTERACTIVE=0`
- **WHEN** executing `openspec spec show` without a spec-id
- **THEN** do not prompt interactively
- **AND** print the existing error message for missing spec-id
- **AND** set non-zero exit code
### Requirement: Spec Command
The system SHALL provide a `spec` command with subcommands for displaying, listing, and validating specifications.
#### Scenario: Show spec as JSON
- **WHEN** executing `openspec spec show init --json`
- **THEN** parse the markdown spec file
- **AND** extract headings and content hierarchically
- **AND** output valid JSON to stdout
#### Scenario: List all specs
- **WHEN** executing `openspec spec list`
- **THEN** scan the openspec/specs directory
- **AND** return list of all available capabilities
- **AND** support JSON output with `--json` flag
#### Scenario: Filter spec content
- **WHEN** executing `openspec spec show init --requirements`
- **THEN** display only requirement names and SHALL statements
- **AND** exclude scenario content
#### Scenario: Validate spec structure
- **WHEN** executing `openspec spec validate init`
- **THEN** parse the spec file
- **AND** validate against Zod schema
- **AND** report any structural issues
### Requirement: JSON Schema Definition
The system SHALL define Zod schemas that accurately represent the spec structure for runtime validation.
#### Scenario: Schema validation
- **WHEN** parsing a spec into JSON
- **THEN** validate the structure using Zod schemas
- **AND** ensure all required fields are present
- **AND** provide clear error messages for validation failures
### Requirement: Interactive spec validation
The spec validate command SHALL support interactive selection when no spec-id is provided.
#### Scenario: Interactive spec selection for validation
- **WHEN** executing `openspec spec validate` without arguments
- **THEN** display an interactive list of available specs
- **AND** allow the user to select a spec to validate
- **AND** validate the selected spec
- **AND** maintain all existing validation options (--strict, --json)
#### Scenario: Non-interactive fallback keeps current behavior
- **GIVEN** stdin is not a TTY or `--no-interactive` is provided or environment variable `OPEN_SPEC_INTERACTIVE=0`
- **WHEN** executing `openspec spec validate` without a spec-id
- **THEN** do not prompt interactively
- **AND** print the existing error message for missing spec-id
- **AND** set non-zero exit code
+23 -3
View File
@@ -3,9 +3,7 @@
## Purpose
As a developer using OpenSpec, I want to update the OpenSpec instructions in my project when new versions are released, so that I can benefit from improvements to AI agent instructions.
## Core Requirements
## Requirements
### Requirement: Update Behavior
The update command SHALL update OpenSpec instruction files to the latest templates in a team-friendly manner.
@@ -48,6 +46,28 @@ The update command SHALL handle file updates in a predictable and safe manner.
- **AND** be idempotent (repeated runs have no additional effect)
- **AND** respect team members' AI tool choices by not creating unwanted files
### Requirement: Tool-Agnostic Updates
The update command SHALL update only existing AI tool configuration files and SHALL NOT create new ones.
#### Scenario: Updating existing tool files
- **WHEN** a user runs `openspec update`
- **THEN** update each AI tool configuration file that exists (e.g., CLAUDE.md, COPILOT.md)
- **AND** do not create missing tool configuration files
- **AND** preserve user content outside OpenSpec markers
### Requirement: Core Files Always Updated
The update command SHALL always update the core OpenSpec files and display an ASCII-safe success message.
#### Scenario: Successful update
- **WHEN** the update completes successfully
- **THEN** replace `openspec/README.md` with the latest template
- **AND** update existing AI tool configuration files within markers
- **AND** display the message: "Updated OpenSpec instructions"
## Edge Cases
### Requirement: Error Handling
+201
View File
@@ -0,0 +1,201 @@
# cli-validate Specification
## Purpose
TBD - created by archiving change improve-validate-error-messages. Update Purpose after archive.
## Requirements
### Requirement: Validation SHALL provide actionable remediation steps
Validation output SHALL include specific guidance to fix each error, including expected structure, example headers, and suggested commands to verify fixes.
#### Scenario: No deltas found in change
- **WHEN** validating a change with zero parsed deltas
- **THEN** show error "No deltas found" with guidance:
- Ensure `openspec/changes/{id}/specs/` exists with `.md` files
- Use delta headers: `## ADDED Requirements`, `## MODIFIED Requirements`, `## REMOVED Requirements`, `## RENAMED Requirements`
- Each requirement must include at least one `#### Scenario:` block
- Try: `openspec change show {id} --json --deltas-only` to inspect what was parsed
#### Scenario: Missing required sections
- **WHEN** a required section is missing
- **THEN** the validator SHALL include expected header names and a minimal skeleton:
- For Spec: `## Purpose`, `## Requirements`
- For Change: `## Why`, `## What Changes`
- Show an example snippet of the missing section
### Requirement: Validator SHALL detect likely misformatted scenarios and warn with a fix
The validator SHALL recognize bulleted lines that look like scenarios (e.g., lines beginning with WHEN/THEN/AND) and emit a targeted warning with a conversion example to `#### Scenario:`.
#### Scenario: Bulleted WHEN/THEN under a Requirement
- **WHEN** bullets that start with WHEN/THEN/AND are found under a requirement without any `#### Scenario:` headers
- **THEN** emit warning: "Scenarios must use '#### Scenario:' headers", and show a conversion template:
```
#### Scenario: Short name
- **WHEN** ...
- **THEN** ...
- **AND** ...
```
### Requirement: All issues SHALL include file paths and structured locations
Error, warning, and info messages SHALL include:
- Source file path (`openspec/changes/{id}/proposal.md`, `.../specs/{cap}/spec.md`)
- Structured path (e.g., `deltas[0].requirements[0].scenarios`)
#### Scenario: Zod validation error
- **WHEN** a schema validation fails
- **THEN** the message SHALL include `file`, `path`, and a remediation hint if applicable
### Requirement: Invalid results SHALL include a Next steps footer in human-readable output
The CLI SHALL append a Next steps footer when the item is invalid and not using `--json`, including:
- Summary line with counts
- Top-3 guidance bullets (contextual to the most frequent or blocking errors)
- A suggestion to re-run with `--json` and/or the debug command
#### Scenario: Change invalid summary
- **WHEN** a change validation fails
- **THEN** print "Next steps" with 2-3 targeted bullets and suggest `openspec change show <id> --json --deltas-only`
### Requirement: Top-level validate command
The CLI SHALL provide a top-level `validate` command for validating changes and specs with flexible selection options.
#### Scenario: Interactive validation selection
- **WHEN** executing `openspec validate` without arguments
- **THEN** prompt user to select what to validate (all, changes, specs, or specific item)
- **AND** perform validation based on selection
- **AND** display results with appropriate formatting
#### Scenario: Non-interactive environments do not prompt
- **GIVEN** stdin is not a TTY or `--no-interactive` is provided or environment variable `OPEN_SPEC_INTERACTIVE=0`
- **WHEN** executing `openspec validate` without arguments
- **THEN** do not prompt interactively
- **AND** print a helpful hint listing available commands/flags and exit with code 1
#### Scenario: Direct item validation
- **WHEN** executing `openspec validate <item-name>`
- **THEN** automatically detect if item is a change or spec
- **AND** validate the specified item
- **AND** display validation results
### Requirement: Bulk and filtered validation
The validate command SHALL support flags for bulk validation (--all) and filtered validation by type (--changes, --specs).
#### Scenario: Validate everything
- **WHEN** executing `openspec validate --all`
- **THEN** validate all changes in openspec/changes/ (excluding archive)
- **AND** validate all specs in openspec/specs/
- **AND** display a summary showing passed/failed items
- **AND** exit with code 1 if any validation fails
#### Scenario: Scope of bulk validation
- **WHEN** validating with `--all` or `--changes`
- **THEN** include all change proposals under `openspec/changes/`
- **AND** exclude the `openspec/changes/archive/` directory
- **WHEN** validating with `--specs`
- **THEN** include all specs that have a `spec.md` under `openspec/specs/<id>/spec.md`
#### Scenario: Validate all changes
- **WHEN** executing `openspec validate --changes`
- **THEN** validate all changes in openspec/changes/ (excluding archive)
- **AND** display results for each change
- **AND** show summary statistics
#### Scenario: Validate all specs
- **WHEN** executing `openspec validate --specs`
- **THEN** validate all specs in openspec/specs/
- **AND** display results for each spec
- **AND** show summary statistics
### Requirement: Validation options and progress indication
The validate command SHALL support standard validation options (--strict, --json) and display progress during bulk operations.
#### Scenario: Strict validation
- **WHEN** executing `openspec validate --all --strict`
- **THEN** apply strict validation to all items
- **AND** treat warnings as errors
- **AND** fail if any item has warnings or errors
#### Scenario: JSON output
- **WHEN** executing `openspec validate --all --json`
- **THEN** output validation results as JSON
- **AND** include detailed issues for each item
- **AND** include summary statistics
#### Scenario: JSON output schema for bulk validation
- **WHEN** executing `openspec validate --all --json` (or `--changes` / `--specs`)
- **THEN** output a JSON object with the following shape:
- `items`: Array of objects with fields `{ id: string, type: "change"|"spec", valid: boolean, issues: Issue[], durationMs: number }`
- `summary`: Object `{ totals: { items: number, passed: number, failed: number }, byType: { change?: { items: number, passed: number, failed: number }, spec?: { items: number, passed: number, failed: number } } }`
- `version`: String identifier for the schema (e.g., `"1.0"`)
- **AND** exit with code 1 if any `items[].valid === false`
Where `Issue` follows the existing per-item validation report shape `{ level: "ERROR"|"WARNING"|"INFO", path: string, message: string }`.
#### Scenario: Show validation progress
- **WHEN** validating multiple items (--all, --changes, or --specs)
- **THEN** show progress indicator or status updates
- **AND** indicate which item is currently being validated
- **AND** display running count of passed/failed items
#### Scenario: Concurrency limits for performance
- **WHEN** validating multiple items
- **THEN** run validations with a bounded concurrency (e.g., 4–8 in parallel)
- **AND** ensure progress indicators remain responsive
### Requirement: Item type detection and ambiguity handling
The validate command SHALL handle ambiguous names and explicit type overrides to ensure clear, deterministic behavior.
#### Scenario: Direct item validation with automatic type detection
- **WHEN** executing `openspec validate <item-name>`
- **THEN** if `<item-name>` uniquely matches a change or a spec, validate that item
#### Scenario: Ambiguity between change and spec names
- **GIVEN** `<item-name>` exists both as a change and as a spec
- **WHEN** executing `openspec validate <item-name>`
- **THEN** print an ambiguity error explaining both matches
- **AND** suggest passing `--type change` or `--type spec`, or using `openspec change validate` / `openspec spec validate`
- **AND** exit with code 1 without performing validation
#### Scenario: Unknown item name
- **WHEN** the `<item-name>` matches neither a change nor a spec
- **THEN** print a not-found error
- **AND** show nearest-match suggestions when available
- **AND** exit with code 1
#### Scenario: Explicit type override
- **WHEN** executing `openspec validate --type change <item>`
- **THEN** treat `<item>` as a change ID and validate it (skipping auto-detection)
- **WHEN** executing `openspec validate --type spec <item>`
- **THEN** treat `<item>` as a spec ID and validate it (skipping auto-detection)
### Requirement: Interactivity controls
- The CLI SHALL respect `--no-interactive` to disable prompts.
- The CLI SHALL respect `OPEN_SPEC_INTERACTIVE=0` to disable prompts globally.
- Interactive prompts SHALL only be shown when stdin is a TTY and interactivity is not disabled.
#### Scenario: Disabling prompts via flags or environment
- **WHEN** `openspec validate` is executed with `--no-interactive` or with environment `OPEN_SPEC_INTERACTIVE=0`
- **THEN** the CLI SHALL not display interactive prompts
- **AND** SHALL print non-interactive hints or chosen outputs as appropriate
+220 -2
View File
@@ -3,6 +3,226 @@
## Purpose
OpenSpec conventions SHALL define how system capabilities are documented, how changes are proposed and tracked, and how specifications evolve over time. This meta-specification serves as the source of truth for OpenSpec's own conventions.
## Requirements
### Requirement: Structured conventions for specs and changes
OpenSpec conventions SHALL mandate a structured spec format with clear requirement and scenario sections so tooling can parse consistently.
#### Scenario: Following the structured spec format
- **WHEN** writing or updating OpenSpec specifications
- **THEN** authors SHALL use `### Requirement: ...` followed by at least one `#### Scenario: ...` section
### Requirement: Project Structure
An OpenSpec project SHALL maintain a consistent directory structure for specifications and changes.
#### Scenario: Initializing project structure
- **WHEN** an OpenSpec project is initialized
- **THEN** it SHALL have this structure:
```
openspec/
├── project.md # Project-specific context
├── README.md # AI assistant instructions
├── specs/ # Current deployed capabilities
│ └── [capability]/ # Single, focused capability
│ ├── spec.md # WHAT and WHY
│ └── design.md # HOW (optional, for established patterns)
└── changes/ # Proposed changes
├── [change-name]/ # Descriptive change identifier
│ ├── proposal.md # Why, what, and impact
│ ├── tasks.md # Implementation checklist
│ ├── design.md # Technical decisions (optional)
│ └── specs/ # Complete future state
│ └── [capability]/
│ └── spec.md # Clean markdown (no diff syntax)
└── archive/ # Completed changes
└── YYYY-MM-DD-[name]/
```
### Requirement: Structured Format for Behavioral Specs
Behavioral specifications SHALL use a structured format with consistent section headers and keywords to ensure visual consistency and parseability.
#### Scenario: Writing requirement sections
- **WHEN** documenting a requirement in a behavioral specification
- **THEN** use a level-3 heading with format `### Requirement: [Name]`
- **AND** immediately follow with a SHALL statement describing core behavior
- **AND** keep requirement names descriptive and under 50 characters
#### Scenario: Documenting scenarios
- **WHEN** documenting specific behaviors or use cases
- **THEN** use level-4 headings with format `#### Scenario: [Description]`
- **AND** use bullet points with bold keywords for steps:
- **GIVEN** for initial state (optional)
- **WHEN** for conditions or triggers
- **THEN** for expected outcomes
- **AND** for additional outcomes or conditions
#### Scenario: Adding implementation details
- **WHEN** a step requires additional detail
- **THEN** use sub-bullets under the main step
- **AND** maintain consistent indentation
- Sub-bullets provide examples or specifics
- Keep sub-bullets concise
### Requirement: Header-Based Requirement Identification
Requirement headers SHALL serve as unique identifiers for programmatic matching between current specs and proposed changes.
#### Scenario: Matching requirements programmatically
- **WHEN** processing delta changes
- **THEN** use the `### Requirement: [Name]` header as the unique identifier
- **AND** match using normalized headers: `normalize(header) = trim(header)`
- **AND** compare headers with case-sensitive equality after normalization
#### Scenario: Handling requirement renames
- **WHEN** renaming a requirement
- **THEN** use a special `## RENAMED Requirements` section
- **AND** specify both old and new names explicitly:
```markdown
## RENAMED Requirements
- FROM: `### Requirement: Old Name`
- TO: `### Requirement: New Name`
```
- **AND** if content also changes, include under MODIFIED using the NEW header
#### Scenario: Validating header uniqueness
- **WHEN** creating or modifying requirements
- **THEN** ensure no duplicate headers exist within a spec
- **AND** validation tools SHALL flag duplicate headers as errors
### Requirement: Change Storage Convention
Change proposals SHALL store only the additions, modifications, and removals to specifications, not complete future states.
#### Scenario: Creating change proposals with additions
- **WHEN** creating a change proposal that adds new requirements
- **THEN** include only the new requirements under `## ADDED Requirements`
- **AND** each requirement SHALL include its complete content
- **AND** use the standard structured format for requirements and scenarios
#### Scenario: Creating change proposals with modifications
- **WHEN** creating a change proposal that modifies existing requirements
- **THEN** include the modified requirements under `## MODIFIED Requirements`
- **AND** use the same header text as in the current spec (normalized)
- **AND** include the complete modified requirement (not a diff)
- **AND** optionally annotate what changed with inline comments like `← (was X)`
#### Scenario: Creating change proposals with removals
- **WHEN** creating a change proposal that removes requirements
- **THEN** list them under `## REMOVED Requirements`
- **AND** use the normalized header text for identification
- **AND** include reason for removal
- **AND** document any migration path if applicable
The `changes/[name]/specs/` directory SHALL contain:
- Delta files showing only what changes
- Sections for ADDED, MODIFIED, REMOVED, and RENAMED requirements
- Normalized header matching for requirement identification
- Complete requirements using the structured format
- Clear indication of change type for each requirement
#### Scenario: Using standard output symbols
- **WHEN** displaying delta operations in CLI output
- **THEN** use these standard symbols:
- `+` for ADDED (green)
- `~` for MODIFIED (yellow)
- `-` for REMOVED (red)
- `→` for RENAMED (cyan)
### Requirement: Archive Process Enhancement
The archive process SHALL programmatically apply delta changes to current specifications using header-based matching.
#### Scenario: Archiving changes with deltas
- **WHEN** archiving a completed change
- **THEN** the archive command SHALL:
1. Parse RENAMED sections first and apply renames
2. Parse REMOVED sections and remove by normalized header match
3. Parse MODIFIED sections and replace by normalized header match (using new names if renamed)
4. Parse ADDED sections and append new requirements
- **AND** validate that all MODIFIED/REMOVED headers exist in current spec
- **AND** validate that ADDED headers don't already exist
- **AND** generate the updated spec in the main specs/ directory
#### Scenario: Handling conflicts during archive
- **WHEN** delta changes conflict with current spec state
- **THEN** the archive command SHALL report specific conflicts
- **AND** require manual resolution before proceeding
- **AND** provide clear guidance on resolving conflicts
### Requirement: Proposal Format
Proposals SHALL explicitly document all changes with clear from/to comparisons.
#### Scenario: Documenting changes
- **WHEN** documenting what changes
- **THEN** the proposal SHALL explicitly describe each change:
```markdown
**[Section or Behavior Name]**
- From: [current state/requirement]
- To: [future state/requirement]
- Reason: [why this change is needed]
- Impact: [breaking/non-breaking, who's affected]
```
This explicit format compensates for not having inline diffs and ensures reviewers understand exactly what will change.
### Requirement: Change Review
The system SHALL support multiple methods for reviewing proposed changes.
#### Scenario: Reviewing changes
- **WHEN** reviewing proposed changes
- **THEN** reviewers can compare using:
- GitHub PR diff view when changes are committed
- Command line: `diff -u specs/[capability]/spec.md changes/[name]/specs/[capability]/spec.md`
- Any visual diff tool comparing current vs future state
### Requirement: Structured Format Adoption
Behavioral specifications SHALL adopt the structured format with `### Requirement:` and `#### Scenario:` headers as the default.
#### Scenario: Use structured headings for behavior
- **WHEN** documenting behavioral requirements
- **THEN** use `### Requirement:` for requirements
- **AND** use `#### Scenario:` for scenarios with bold WHEN/THEN/AND keywords
### Requirement: Verb–Noun CLI Command Structure
OpenSpec CLI design SHALL use verbs as top-level commands with nouns provided as arguments or flags for scoping.
#### Scenario: Verb-first command discovery
- **WHEN** a user runs a command like `openspec list`
- **THEN** the verb communicates the action clearly
- **AND** nouns refine scope via flags or arguments (e.g., `--changes`, `--specs`)
#### Scenario: Backward compatibility for noun commands
- **WHEN** users run noun-prefixed commands such as `openspec spec ...` or `openspec change ...`
- **THEN** the CLI SHALL continue to support them for at least one release
- **AND** display a deprecation warning that points to verb-first alternatives
#### Scenario: Disambiguation guidance
- **WHEN** item names are ambiguous between changes and specs
- **THEN** `openspec show` and `openspec validate` SHALL accept `--type spec|change`
- **AND** the help text SHALL document this clearly
## Core Principles
@@ -73,7 +293,6 @@ Behavioral specifications SHALL use a structured format with consistent section
- Sub-bullets provide examples or specifics
- Keep sub-bullets concise
## Change Storage Convention
### Requirement: Header-Based Requirement Identification
@@ -132,7 +351,6 @@ Change proposals SHALL store only the additions, modifications, and removals to
- **AND** include reason for removal
- **AND** document any migration path if applicable
The `changes/[name]/specs/` directory SHALL contain:
- Delta files showing only what changes
- Sections for ADDED, MODIFIED, REMOVED, and RENAMED requirements
+13 -7
View File
@@ -1,6 +1,6 @@
{
"name": "openspec",
"version": "0.0.1",
"name": "@fission-ai/openspec",
"version": "0.1.0",
"description": "AI-native system for spec-driven development",
"keywords": [
"openspec",
@@ -9,14 +9,18 @@
"ai",
"development"
],
"homepage": "https://github.com/tabdilsaidixit/openspec",
"homepage": "https://github.com/Fission-AI/OpenSpec",
"repository": {
"type": "git",
"url": "git+https://github.com/tabdilsaidixit/openspec.git"
"url": "https://github.com/Fission-AI/OpenSpec"
},
"license": "MIT",
"author": "OpenSpec Contributors",
"type": "module",
"publishConfig": {
"access": "public",
"tag": "next"
},
"exports": {
".": {
"types": "./dist/index.d.ts",
@@ -41,12 +45,15 @@
"test:watch": "vitest",
"test:ui": "vitest --ui",
"test:coverage": "vitest --coverage",
"prepare": "npm run build"
"prepare": "pnpm run build",
"prepublishOnly": "pnpm run build",
"changeset": "changeset"
},
"engines": {
"node": ">=20.19.0"
},
"devDependencies": {
"@changesets/cli": "^2.27.7",
"@types/node": "^24.2.0",
"@vitest/ui": "^3.2.4",
"typescript": "^5.9.2",
@@ -56,8 +63,7 @@
"@inquirer/prompts": "^7.8.0",
"chalk": "^5.5.0",
"commander": "^14.0.0",
"jest-diff": "^30.0.5",
"ora": "^8.2.0",
"zod": "^4.0.17"
}
}
}
+744 -70
View File
File diff suppressed because it is too large Load Diff
+8 -17
View File
@@ -1,10 +1,10 @@
import { Command } from 'commander';
import { createRequire } from 'module';
import ora from 'ora';
import path from 'path';
import { promises as fs } from 'fs';
import { InitCommand } from '../core/init.js';
import { UpdateCommand } from '../core/update.js';
import { DiffCommand } from '../core/diff.js';
import { ListCommand } from '../core/list.js';
import { ArchiveCommand } from '../core/archive.js';
import { registerSpecCommand } from '../commands/spec.js';
@@ -13,11 +13,13 @@ import { ValidateCommand } from '../commands/validate.js';
import { ShowCommand } from '../commands/show.js';
const program = new Command();
const require = createRequire(import.meta.url);
const { version } = require('../../package.json');
program
.name('openspec')
.description('AI-native system for spec-driven development')
.version('0.0.1');
.version(version);
// Global options
program.option('--no-color', 'Disable color output');
@@ -78,20 +80,6 @@ program
}
});
program
.command('diff [change-name]')
.description('Show differences between proposed spec changes and current specs (includes validation warnings)')
.action(async (changeName?: string) => {
try {
const diffCommand = new DiffCommand();
await diffCommand.execute(changeName);
} catch (error) {
console.log(); // Empty line for spacing
ora().fail(`Error: ${(error as Error).message}`);
process.exit(1);
}
});
program
.command('list')
.description('List items (changes by default). Use --specs to list specs.')
@@ -162,6 +150,9 @@ changeCmd
try {
const changeCommand = new ChangeCommand();
await changeCommand.validate(changeName, options);
if (typeof process.exitCode === 'number' && process.exitCode !== 0) {
process.exit(process.exitCode);
}
} catch (error) {
console.error(`Error: ${(error as Error).message}`);
process.exitCode = 1;
@@ -237,4 +228,4 @@ program
}
});
program.parse();
program.parse();
+32 -10
View File
@@ -206,16 +206,16 @@ export class ChangeCommand {
}
}
const proposalPath = path.join(changesPath, changeName, 'proposal.md');
const changeDir = path.join(changesPath, changeName);
try {
await fs.access(proposalPath);
await fs.access(changeDir);
} catch {
throw new Error(`Change "${changeName}" not found at ${proposalPath}`);
throw new Error(`Change "${changeName}" not found at ${changeDir}`);
}
const validator = new Validator(options?.strict || false);
const report = await validator.validateChange(proposalPath);
const report = await validator.validateChangeDeltaSpecs(changeDir);
if (options?.json) {
console.log(JSON.stringify(report, null, 2));
@@ -223,12 +223,17 @@ export class ChangeCommand {
if (report.valid) {
console.log(`Change "${changeName}" is valid`);
} else {
console.error(`Change "${changeName}" has validation issues`);
console.error(`Change "${changeName}" has issues`);
report.issues.forEach(issue => {
const label = issue.level === 'ERROR' ? 'ERROR' : 'WARNING';
const prefix = issue.level === 'ERROR' ? '✗' : '⚠';
console.error(`${prefix} [${label}] ${issue.path}: ${issue.message}`);
});
// Next steps footer to guide fixing issues
this.printNextSteps();
if (!options?.json) {
process.exitCode = 1;
}
}
}
}
@@ -236,10 +241,18 @@ export class ChangeCommand {
private async getActiveChanges(changesPath: string): Promise<string[]> {
try {
const entries = await fs.readdir(changesPath, { withFileTypes: true });
return entries
.filter(entry => entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== ARCHIVE_DIR)
.map(entry => entry.name)
.sort();
const result: string[] = [];
for (const entry of entries) {
if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name === ARCHIVE_DIR) continue;
const proposalPath = path.join(changesPath, entry.name, 'proposal.md');
try {
await fs.access(proposalPath);
result.push(entry.name);
} catch {
// skip directories without proposal.md
}
}
return result.sort();
} catch {
return [];
}
@@ -266,4 +279,13 @@ export class ChangeCommand {
return { total, completed };
}
}
private printNextSteps(): void {
const bullets: string[] = [];
bullets.push('- Ensure change has deltas in specs/: use headers ## ADDED/MODIFIED/REMOVED/RENAMED Requirements');
bullets.push('- Each requirement MUST include at least one #### Scenario: block');
bullets.push('- Debug parsed deltas: openspec change show <id> --json --deltas-only');
console.error('Next steps:');
bullets.forEach(b => console.error(` ${b}`));
}
}
+21 -4
View File
@@ -129,11 +129,12 @@ export class ValidateCommand {
private async validateByType(type: ItemType, id: string, opts: { strict: boolean; json: boolean }): Promise<void> {
const validator = new Validator(opts.strict);
if (type === 'change') {
const file = path.join(process.cwd(), 'openspec', 'changes', id, 'proposal.md');
const changeDir = path.join(process.cwd(), 'openspec', 'changes', id);
const start = Date.now();
const report = await validator.validateChange(file);
const report = await validator.validateChangeDeltaSpecs(changeDir);
const durationMs = Date.now() - start;
this.printReport('change', id, report, durationMs, opts.json);
// Non-zero exit if invalid (keeps enriched output test semantics)
process.exitCode = report.valid ? 0 : 1;
return;
}
@@ -160,9 +161,25 @@ export class ValidateCommand {
const prefix = issue.level === 'ERROR' ? '✗' : issue.level === 'WARNING' ? '⚠' : 'ℹ';
console.error(`${prefix} [${label}] ${issue.path}: ${issue.message}`);
}
this.printNextSteps(type);
}
}
private printNextSteps(type: ItemType): void {
const bullets: string[] = [];
if (type === 'change') {
bullets.push('- Ensure change has deltas in specs/: use headers ## ADDED/MODIFIED/REMOVED/RENAMED Requirements');
bullets.push('- Each requirement MUST include at least one #### Scenario: block');
bullets.push('- Debug parsed deltas: openspec change show <id> --json --deltas-only');
} else {
bullets.push('- Ensure spec includes ## Purpose and ## Requirements sections');
bullets.push('- Each requirement MUST include at least one #### Scenario: block');
bullets.push('- Re-run with --json to see structured report');
}
console.error('Next steps:');
bullets.forEach(b => console.error(` ${b}`));
}
private async runBulkValidation(scope: { changes: boolean; specs: boolean }, opts: { strict: boolean; json: boolean; concurrency?: string }): Promise<void> {
const spinner = !opts.json ? ora('Validating...').start() : undefined;
const [changeIds, specIds] = await Promise.all([
@@ -179,8 +196,8 @@ export class ValidateCommand {
for (const id of changeIds) {
queue.push(async () => {
const start = Date.now();
const file = path.join(process.cwd(), 'openspec', 'changes', id, 'proposal.md');
const report = await validator.validateChange(file);
const changeDir = path.join(process.cwd(), 'openspec', 'changes', id);
const report = await validator.validateChangeDeltaSpecs(changeDir);
const durationMs = Date.now() - start;
return { id, type: 'change' as const, valid: report.valid, issues: report.issues, durationMs };
});
+51 -41
View File
@@ -59,16 +59,48 @@ export class ArchiveCommand {
const validator = new Validator();
let hasValidationErrors = false;
// Validate change.md file
const changeFile = path.join(changeDir, 'change.md');
// Validate proposal.md (non-blocking unless strict mode desired in future)
const changeFile = path.join(changeDir, 'proposal.md');
try {
await fs.access(changeFile);
const changeReport = await validator.validateChange(changeFile);
// Proposal validation is informative only (do not block archive)
if (!changeReport.valid) {
hasValidationErrors = true;
console.log(chalk.red(`\nValidation errors in change.md:`));
console.log(chalk.yellow(`\nProposal warnings in proposal.md (non-blocking):`));
for (const issue of changeReport.issues) {
const symbol = issue.level === 'ERROR' ? '⚠' : (issue.level === 'WARNING' ? '⚠' : 'ℹ');
console.log(chalk.yellow(` ${symbol} ${issue.message}`));
}
}
} catch {
// Change file doesn't exist, skip validation
}
// Validate delta-formatted spec files under the change directory if present
const changeSpecsDir = path.join(changeDir, 'specs');
let hasDeltaSpecs = false;
try {
const candidates = await fs.readdir(changeSpecsDir, { withFileTypes: true });
for (const c of candidates) {
if (c.isDirectory()) {
try {
const candidatePath = path.join(changeSpecsDir, c.name, 'spec.md');
await fs.access(candidatePath);
const content = await fs.readFile(candidatePath, 'utf-8');
if (/^##\s+(ADDED|MODIFIED|REMOVED|RENAMED)\s+Requirements/m.test(content)) {
hasDeltaSpecs = true;
break;
}
} catch {}
}
}
} catch {}
if (hasDeltaSpecs) {
const deltaReport = await validator.validateChangeDeltaSpecs(changeDir);
if (!deltaReport.valid) {
hasValidationErrors = true;
console.log(chalk.red(`\nValidation errors in change delta specs:`));
for (const issue of deltaReport.issues) {
if (issue.level === 'ERROR') {
console.log(chalk.red(` ✗ ${issue.message}`));
} else if (issue.level === 'WARNING') {
@@ -76,41 +108,6 @@ export class ArchiveCommand {
}
}
}
} catch {
// Change file doesn't exist, skip validation
}
// Validate spec files
const changeSpecsDir = path.join(changeDir, 'specs');
try {
const entries = await fs.readdir(changeSpecsDir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
const specFile = path.join(changeSpecsDir, entry.name, 'spec.md');
try {
await fs.access(specFile);
const report = await validator.validateSpec(specFile);
if (!report.valid) {
hasValidationErrors = true;
console.log(chalk.red(`\nValidation errors in ${entry.name}/spec.md:`));
for (const issue of report.issues) {
if (issue.level === 'ERROR') {
console.log(chalk.red(` ✗ ${issue.message}`));
} else if (issue.level === 'WARNING') {
console.log(chalk.yellow(` ⚠ ${issue.message}`));
}
}
}
} catch {
// Spec file doesn't exist, skip validation
}
}
}
} catch {
// No specs directory, skip validation
}
if (hasValidationErrors) {
@@ -200,9 +197,22 @@ export class ArchiveCommand {
return;
}
// All validations passed; write files and display counts
// All validations passed; pre-validate rebuilt full spec and then write files and display counts
let totals = { added: 0, modified: 0, removed: 0, renamed: 0 };
for (const p of prepared) {
const specName = path.basename(path.dirname(p.update.target));
if (!options.noValidate) {
const report = await new Validator().validateSpecContent(specName, p.rebuilt);
if (!report.valid) {
console.log(chalk.red(`\nValidation errors in rebuilt spec for ${specName} (will not write changes):`));
for (const issue of report.issues) {
if (issue.level === 'ERROR') console.log(chalk.red(` ✗ ${issue.message}`));
else if (issue.level === 'WARNING') console.log(chalk.yellow(` ⚠ ${issue.message}`));
}
console.log('Aborted. No files were changed.');
return;
}
}
await this.writeUpdatedSpec(p.update, p.rebuilt, p.counts);
totals.added += p.counts.added;
totals.modified += p.counts.modified;
-227
View File
@@ -1,227 +0,0 @@
import { promises as fs } from 'fs';
import path from 'path';
import chalk from 'chalk';
import { diffStringsUnified } from 'jest-diff';
import { select } from '@inquirer/prompts';
import { Validator } from './validation/validator.js';
// Constants
const ARCHIVE_DIR = 'archive';
const MARKDOWN_EXT = '.md';
const OPENSPEC_DIR = 'openspec';
const CHANGES_DIR = 'changes';
const SPECS_DIR = 'specs';
export class DiffCommand {
private filesChanged: number = 0;
private linesAdded: number = 0;
private linesRemoved: number = 0;
async execute(changeName?: string): Promise<void> {
const changesDir = path.join(process.cwd(), OPENSPEC_DIR, CHANGES_DIR);
try {
await fs.access(changesDir);
} catch {
throw new Error('No OpenSpec changes directory found');
}
if (!changeName) {
changeName = await this.selectChange(changesDir);
if (!changeName) return;
}
const changeDir = path.join(changesDir, changeName);
try {
await fs.access(changeDir);
} catch {
throw new Error(`Change '${changeName}' not found`);
}
const changeSpecsDir = path.join(changeDir, SPECS_DIR);
try {
await fs.access(changeSpecsDir);
} catch {
console.log(`No spec changes found for '${changeName}'`);
return;
}
// Validate specs and show warnings (non-blocking)
const validator = new Validator();
let hasWarnings = false;
try {
const entries = await fs.readdir(changeSpecsDir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
const specFile = path.join(changeSpecsDir, entry.name, 'spec.md');
try {
await fs.access(specFile);
const report = await validator.validateSpec(specFile);
if (report.issues.length > 0) {
const warnings = report.issues.filter(i => i.level === 'WARNING');
const errors = report.issues.filter(i => i.level === 'ERROR');
if (errors.length > 0 || warnings.length > 0) {
if (!hasWarnings) {
console.log(chalk.yellow('\n⚠️ Validation warnings found:'));
hasWarnings = true;
}
console.log(chalk.yellow(`\n ${entry.name}/spec.md:`));
for (const issue of errors) {
console.log(chalk.red(` ✗ ${issue.message}`));
}
for (const issue of warnings) {
console.log(chalk.yellow(` ⚠ ${issue.message}`));
}
}
}
} catch {
// Spec file doesn't exist, skip validation
}
}
}
if (hasWarnings) {
console.log(chalk.yellow('\nConsider fixing these issues before archiving.\n'));
}
} catch {
// No specs directory, skip validation
}
// Reset counters
this.filesChanged = 0;
this.linesAdded = 0;
this.linesRemoved = 0;
await this.showDiffs(changeSpecsDir);
// Show summary
if (this.filesChanged > 0) {
console.log(chalk.bold(`\n📊 Summary: ${this.filesChanged} file(s) changed, ${chalk.green(`+${this.linesAdded}`)} ${chalk.red(`-${this.linesRemoved}`)}`));
}
}
private async selectChange(changesDir: string): Promise<string | undefined> {
const entries = await fs.readdir(changesDir, { withFileTypes: true });
const changes = entries
.filter(entry => entry.isDirectory() && entry.name !== ARCHIVE_DIR)
.map(entry => entry.name);
if (changes.length === 0) {
console.log('No changes found');
return undefined;
}
console.log('Available changes:');
const choices = changes.map((name) => ({
name: name,
value: name
}));
const answer = await select({
message: 'Select a change',
choices
});
return answer as string;
}
private async showDiffs(changeSpecsDir: string): Promise<void> {
const currentSpecsDir = path.join(process.cwd(), OPENSPEC_DIR, SPECS_DIR);
await this.walkAndDiff(changeSpecsDir, currentSpecsDir, '');
}
private async walkAndDiff(changeDir: string, currentDir: string, relativePath: string): Promise<void> {
const entries = await fs.readdir(path.join(changeDir, relativePath), { withFileTypes: true });
for (const entry of entries) {
const entryPath = path.join(relativePath, entry.name);
if (entry.isDirectory()) {
await this.walkAndDiff(changeDir, currentDir, entryPath);
} else if (entry.isFile() && entry.name.endsWith(MARKDOWN_EXT)) {
await this.diffFile(
path.join(changeDir, entryPath),
path.join(currentDir, entryPath),
entryPath
);
}
}
}
private async diffFile(changePath: string, currentPath: string, displayPath: string): Promise<void> {
let changeContent = '';
let currentContent = '';
let isNewFile = false;
let isDeleted = false;
try {
changeContent = await fs.readFile(changePath, 'utf-8');
} catch {
changeContent = '';
}
try {
currentContent = await fs.readFile(currentPath, 'utf-8');
} catch {
currentContent = '';
isNewFile = true;
}
if (changeContent === currentContent) {
return;
}
if (changeContent === '' && currentContent !== '') {
isDeleted = true;
}
// Enhanced header with file status
console.log(chalk.bold.cyan(`\n${'═'.repeat(60)}`));
console.log(chalk.bold.cyan(`📄 ${displayPath}`));
if (isNewFile) {
console.log(chalk.green(` Status: NEW FILE`));
} else if (isDeleted) {
console.log(chalk.red(` Status: DELETED`));
} else {
console.log(chalk.yellow(` Status: MODIFIED`));
}
// Use jest-diff for the actual diff with custom options
const diffOptions = {
aAnnotation: 'Current',
bAnnotation: 'Proposed',
aColor: chalk.red,
bColor: chalk.green,
commonColor: chalk.gray,
contextLines: 3,
expand: false,
includeChangeCounts: true,
};
const diff = diffStringsUnified(currentContent, changeContent, diffOptions);
// Count lines for statistics (approximate)
const addedLines = (diff.match(/^\+[^+]/gm) || []).length;
const removedLines = (diff.match(/^-[^-]/gm) || []).length;
console.log(chalk.gray(` Lines: ${chalk.green(`+${addedLines}`)} ${chalk.red(`-${removedLines}`)}`));
console.log(chalk.bold.cyan(`${'─'.repeat(60)}\n`));
// Display the diff
console.log(diff);
// Update counters
this.filesChanged++;
this.linesAdded += addedLines;
this.linesRemoved += removedLines;
}
}
+83 -15
View File
@@ -1,26 +1,94 @@
export const claudeTemplate = `# OpenSpec Project
This document provides instructions for AI coding assistants on how to use OpenSpec conventions for spec-driven development. Follow these rules precisely when working on OpenSpec-enabled projects.
This project uses OpenSpec for spec-driven development. Specifications are the source of truth.
See @openspec/README.md for detailed conventions and guidelines.
## Three-Stage Workflow
### Stage 1: Creating Changes
Create proposal for: features, breaking changes, architecture changes
Skip proposal for: bug fixes, typos, non-breaking updates
### Stage 2: Implementing Changes
1. Read proposal.md to understand the change
2. Read design.md if it exists for technical context
3. Read tasks.md for implementation checklist
4. Complete tasks one by one
5. Mark each task complete immediately: \`- [x]\`
### Stage 3: Archiving
After deployment, use \`openspec archive [change]\` (add \`--skip-specs\` for tooling-only changes)
## Before Any Task
**Always:**
- Check existing specs: \`openspec list --specs\`
- Check active changes: \`openspec list\`
- Read relevant specs before creating new ones
- Prefer modifying existing specs over creating duplicates
## CLI Quick Reference
\`\`\`bash
# Essential
openspec list # Active changes
openspec list --specs # Existing specifications
openspec show [item] # View details
openspec validate --strict # Validate thoroughly
openspec archive [change] # Archive after deployment
# Interactive
openspec show # Prompts for selection
openspec validate # Bulk validation
# Debugging
openspec show [change] --json --deltas-only
\`\`\`
## Creating Changes
1. **Directory:** \`changes/[descriptive-name]/\`
2. **Files:**
- \`proposal.md\` - Why, what, impact
- \`tasks.md\` - Implementation checklist
- \`specs/[capability]/spec.md\` - Delta changes (ADDED/MODIFIED/REMOVED)
## Critical: Scenario Format
**CORRECT:**
\`\`\`markdown
#### Scenario: User login
- **WHEN** valid credentials
- **THEN** return token
\`\`\`
**WRONG:** Using bullets (- **Scenario**), bold (**Scenario:**), or ### headers
Every requirement MUST have scenarios using \`#### Scenario:\` format.
## Complexity Management
**Default to minimal solutions:**
- Propose <100 lines of new code for features
- Prefer single-file implementations until proven insufficient
- Avoid frameworks, abstractions, and optimizations without clear justification
- Choose boring, well-understood patterns over novel approaches
**Default to minimal:**
- <100 lines of new code
- Single-file implementations
- No frameworks without justification
- Boring, proven patterns
**Question requests for complexity:**
- Caching? → Ask for performance data and targets
- New framework? → Suggest plain code first
- Extra layers? → Start with the thinnest viable design
**Only add complexity with:**
- Performance data showing need
- Concrete scale requirements (>1000 users)
- Multiple proven use cases
**Justify complexity with data:**
- Performance metrics showing current solution is too slow
- Concrete scale requirements (e.g., >1000 users, >100MB data)
- Multiple proven use cases requiring an abstraction
## Troubleshooting
**"Change must have at least one delta"**
- Check \`changes/[name]/specs/\` exists
- Verify operation prefixes (## ADDED Requirements)
**"Requirement must have at least one scenario"**
- Use \`#### Scenario:\` format (4 hashtags)
- Don't use bullets or bold
**Debug:** \`openspec show [change] --json --deltas-only\`
`;
+10
View File
@@ -35,4 +35,14 @@ export const VALIDATION_MESSAGES = {
REQUIREMENT_TOO_LONG: `Requirement text is very long (>${MAX_REQUIREMENT_TEXT_LENGTH} characters). Consider breaking it down.`,
DELTA_DESCRIPTION_TOO_BRIEF: 'Delta description is too brief',
DELTA_MISSING_REQUIREMENTS: 'Delta should include requirements',
// Guidance snippets (appended to primary messages for remediation)
GUIDE_NO_DELTAS:
'No deltas found. Ensure your change has a specs/ directory with .md files using delta headers (## ADDED/MODIFIED/REMOVED/RENAMED Requirements) and that each requirement includes at least one "#### Scenario:" block. Tip: run "openspec change show <change-id> --json --deltas-only" to inspect parsed deltas.',
GUIDE_MISSING_SPEC_SECTIONS:
'Missing required sections. Expected headers: "## Purpose" and "## Requirements". Example:\n## Purpose\n[brief purpose]\n\n## Requirements\n### Requirement: Clear requirement statement\nUsers SHALL ...\n\n#### Scenario: Descriptive name\n- **WHEN** ...\n- **THEN** ...',
GUIDE_MISSING_CHANGE_SECTIONS:
'Missing required sections. Expected headers: "## Why" and "## What Changes". Ensure deltas are documented in specs/ using delta headers.',
GUIDE_SCENARIO_FORMAT:
'Scenarios must use level-4 headers. Convert bullet lists into:\n#### Scenario: Short name\n- **WHEN** ...\n- **THEN** ...\n- **AND** ...',
} as const;
+222 -13
View File
@@ -1,5 +1,5 @@
import { z, ZodError } from 'zod';
import { readFileSync } from 'fs';
import { readFileSync, promises as fs } from 'fs';
import path from 'path';
import { SpecSchema, ChangeSchema, Spec, Change } from '../schemas/index.js';
import { MarkdownParser } from '../parsers/markdown-parser.js';
@@ -10,6 +10,7 @@ import {
MAX_REQUIREMENT_TEXT_LENGTH,
VALIDATION_MESSAGES
} from './constants.js';
import { parseDeltaSpec, normalizeRequirementName } from '../parsers/requirement-blocks.js';
export class Validator {
private strictMode: boolean;
@@ -20,11 +21,10 @@ export class Validator {
async validateSpec(filePath: string): Promise<ValidationReport> {
const issues: ValidationIssue[] = [];
const specName = this.extractNameFromPath(filePath);
try {
const content = readFileSync(filePath, 'utf-8');
const parser = new MarkdownParser(content);
const specName = this.extractNameFromPath(filePath);
const spec = parser.parseSpec(specName);
@@ -37,22 +37,44 @@ export class Validator {
issues.push(...this.applySpecRules(spec, content));
} catch (error) {
const baseMessage = error instanceof Error ? error.message : 'Unknown error';
const enriched = this.enrichTopLevelError(specName, baseMessage);
issues.push({
level: 'ERROR',
path: 'file',
message: error instanceof Error ? error.message : 'Unknown error',
message: enriched,
});
}
return this.createReport(issues);
}
/**
* Validate spec content from a string (used for pre-write validation of rebuilt specs)
*/
async validateSpecContent(specName: string, content: string): Promise<ValidationReport> {
const issues: ValidationIssue[] = [];
try {
const parser = new MarkdownParser(content);
const spec = parser.parseSpec(specName);
const result = SpecSchema.safeParse(spec);
if (!result.success) {
issues.push(...this.convertZodErrors(result.error));
}
issues.push(...this.applySpecRules(spec, content));
} catch (error) {
const baseMessage = error instanceof Error ? error.message : 'Unknown error';
const enriched = this.enrichTopLevelError(specName, baseMessage);
issues.push({ level: 'ERROR', path: 'file', message: enriched });
}
return this.createReport(issues);
}
async validateChange(filePath: string): Promise<ValidationReport> {
const issues: ValidationIssue[] = [];
const changeName = this.extractNameFromPath(filePath);
try {
const content = readFileSync(filePath, 'utf-8');
const changeName = this.extractNameFromPath(filePath);
const changeDir = path.dirname(filePath);
const parser = new ChangeParser(content, changeDir);
@@ -67,22 +89,172 @@ export class Validator {
issues.push(...this.applyChangeRules(change, content));
} catch (error) {
const baseMessage = error instanceof Error ? error.message : 'Unknown error';
const enriched = this.enrichTopLevelError(changeName, baseMessage);
issues.push({
level: 'ERROR',
path: 'file',
message: error instanceof Error ? error.message : 'Unknown error',
message: enriched,
});
}
return this.createReport(issues);
}
/**
* Validate delta-formatted spec files under a change directory.
* Enforces:
* - At least one delta across all files
* - ADDED/MODIFIED: each requirement has SHALL/MUST and at least one scenario
* - REMOVED: names only; no scenario/description required
* - RENAMED: pairs well-formed
* - No duplicates within sections; no cross-section conflicts per spec
*/
async validateChangeDeltaSpecs(changeDir: string): Promise<ValidationReport> {
const issues: ValidationIssue[] = [];
const specsDir = path.join(changeDir, 'specs');
let totalDeltas = 0;
try {
const entries = await fs.readdir(specsDir, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const specName = entry.name;
const specFile = path.join(specsDir, specName, 'spec.md');
let content: string | undefined;
try {
content = await fs.readFile(specFile, 'utf-8');
} catch {
continue;
}
const plan = parseDeltaSpec(content);
const entryPath = `${specName}/spec.md`;
const addedNames = new Set<string>();
const modifiedNames = new Set<string>();
const removedNames = new Set<string>();
const renamedFrom = new Set<string>();
const renamedTo = new Set<string>();
// Validate ADDED
for (const block of plan.added) {
const key = normalizeRequirementName(block.name);
totalDeltas++;
if (addedNames.has(key)) {
issues.push({ level: 'ERROR', path: entryPath, message: `Duplicate requirement in ADDED: "${block.name}"` });
} else {
addedNames.add(key);
}
const requirementText = this.extractRequirementText(block.raw);
if (!requirementText) {
issues.push({ level: 'ERROR', path: entryPath, message: `ADDED "${block.name}" is missing requirement text` });
} else if (!this.containsShallOrMust(requirementText)) {
issues.push({ level: 'ERROR', path: entryPath, message: `ADDED "${block.name}" must contain SHALL or MUST` });
}
const scenarioCount = this.countScenarios(block.raw);
if (scenarioCount < 1) {
issues.push({ level: 'ERROR', path: entryPath, message: `ADDED "${block.name}" must include at least one scenario` });
}
}
// Validate MODIFIED
for (const block of plan.modified) {
const key = normalizeRequirementName(block.name);
totalDeltas++;
if (modifiedNames.has(key)) {
issues.push({ level: 'ERROR', path: entryPath, message: `Duplicate requirement in MODIFIED: "${block.name}"` });
} else {
modifiedNames.add(key);
}
const requirementText = this.extractRequirementText(block.raw);
if (!requirementText) {
issues.push({ level: 'ERROR', path: entryPath, message: `MODIFIED "${block.name}" is missing requirement text` });
} else if (!this.containsShallOrMust(requirementText)) {
issues.push({ level: 'ERROR', path: entryPath, message: `MODIFIED "${block.name}" must contain SHALL or MUST` });
}
const scenarioCount = this.countScenarios(block.raw);
if (scenarioCount < 1) {
issues.push({ level: 'ERROR', path: entryPath, message: `MODIFIED "${block.name}" must include at least one scenario` });
}
}
// Validate REMOVED (names only)
for (const name of plan.removed) {
const key = normalizeRequirementName(name);
totalDeltas++;
if (removedNames.has(key)) {
issues.push({ level: 'ERROR', path: entryPath, message: `Duplicate requirement in REMOVED: "${name}"` });
} else {
removedNames.add(key);
}
}
// Validate RENAMED pairs
for (const { from, to } of plan.renamed) {
const fromKey = normalizeRequirementName(from);
const toKey = normalizeRequirementName(to);
totalDeltas++;
if (renamedFrom.has(fromKey)) {
issues.push({ level: 'ERROR', path: entryPath, message: `Duplicate FROM in RENAMED: "${from}"` });
} else {
renamedFrom.add(fromKey);
}
if (renamedTo.has(toKey)) {
issues.push({ level: 'ERROR', path: entryPath, message: `Duplicate TO in RENAMED: "${to}"` });
} else {
renamedTo.add(toKey);
}
}
// Cross-section conflicts (within the same spec file)
for (const n of modifiedNames) {
if (removedNames.has(n)) {
issues.push({ level: 'ERROR', path: entryPath, message: `Requirement present in both MODIFIED and REMOVED: "${n}"` });
}
if (addedNames.has(n)) {
issues.push({ level: 'ERROR', path: entryPath, message: `Requirement present in both MODIFIED and ADDED: "${n}"` });
}
}
for (const n of addedNames) {
if (removedNames.has(n)) {
issues.push({ level: 'ERROR', path: entryPath, message: `Requirement present in both ADDED and REMOVED: "${n}"` });
}
}
for (const { from, to } of plan.renamed) {
const fromKey = normalizeRequirementName(from);
const toKey = normalizeRequirementName(to);
if (modifiedNames.has(fromKey)) {
issues.push({ level: 'ERROR', path: entryPath, message: `MODIFIED references old name from RENAMED. Use new header for "${to}"` });
}
if (addedNames.has(toKey)) {
issues.push({ level: 'ERROR', path: entryPath, message: `RENAMED TO collides with ADDED for "${to}"` });
}
}
}
} catch {
// If no specs dir, treat as no deltas
}
if (totalDeltas === 0) {
issues.push({ level: 'ERROR', path: 'file', message: this.enrichTopLevelError('change', VALIDATION_MESSAGES.CHANGE_NO_DELTAS) });
}
return this.createReport(issues);
}
private convertZodErrors(error: ZodError): ValidationIssue[] {
return error.issues.map(err => ({
level: 'ERROR' as ValidationLevel,
path: err.path.join('.'),
message: err.message,
}));
return error.issues.map(err => {
let message = err.message;
if (message === VALIDATION_MESSAGES.CHANGE_NO_DELTAS) {
message = `${message}. ${VALIDATION_MESSAGES.GUIDE_NO_DELTAS}`;
}
return {
level: 'ERROR' as ValidationLevel,
path: err.path.join('.'),
message,
};
});
}
private applySpecRules(spec: Spec, content: string): ValidationIssue[] {
@@ -109,7 +281,7 @@ export class Validator {
issues.push({
level: 'WARNING',
path: `requirements[${index}].scenarios`,
message: 'Requirement has no scenarios',
message: `${VALIDATION_MESSAGES.REQUIREMENT_NO_SCENARIOS}. ${VALIDATION_MESSAGES.GUIDE_SCENARIO_FORMAT}`,
});
}
});
@@ -144,6 +316,20 @@ export class Validator {
return issues;
}
private enrichTopLevelError(itemId: string, baseMessage: string): string {
const msg = baseMessage.trim();
if (msg === VALIDATION_MESSAGES.CHANGE_NO_DELTAS) {
return `${msg}. ${VALIDATION_MESSAGES.GUIDE_NO_DELTAS}`;
}
if (msg.includes('Spec must have a Purpose section') || msg.includes('Spec must have a Requirements section')) {
return `${msg}. ${VALIDATION_MESSAGES.GUIDE_MISSING_SPEC_SECTIONS}`;
}
if (msg.includes('Change must have a Why section') || msg.includes('Change must have a What Changes section')) {
return `${msg}. ${VALIDATION_MESSAGES.GUIDE_MISSING_CHANGE_SECTIONS}`;
}
return msg;
}
private extractNameFromPath(filePath: string): string {
const parts = filePath.split('/');
@@ -184,4 +370,27 @@ export class Validator {
isValid(report: ValidationReport): boolean {
return report.valid;
}
private extractRequirementText(blockRaw: string): string | undefined {
const lines = blockRaw.split('\n');
// Skip header
let i = 1;
const bodyLines: string[] = [];
for (; i < lines.length; i++) {
const line = lines[i];
if (/^####\s+/.test(line)) break; // scenarios start
bodyLines.push(line);
}
const text = bodyLines.join('\n').split('\n').map(l => l.trim()).find(l => l.length > 0);
return text;
}
private containsShallOrMust(text: string): boolean {
return /\b(SHALL|MUST)\b/.test(text);
}
private countScenarios(blockRaw: string): number {
const matches = blockRaw.match(/^####\s+/gm);
return matches ? matches.length : 0;
}
}
+12 -5
View File
@@ -5,10 +5,18 @@ export async function getActiveChangeIds(root: string = process.cwd()): Promise<
const changesPath = path.join(root, 'openspec', 'changes');
try {
const entries = await fs.readdir(changesPath, { withFileTypes: true });
return entries
.filter(entry => entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'archive')
.map(entry => entry.name)
.sort();
const result: string[] = [];
for (const entry of entries) {
if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name === 'archive') continue;
const proposalPath = path.join(changesPath, entry.name, 'proposal.md');
try {
await fs.access(proposalPath);
result.push(entry.name);
} catch {
// skip directories without proposal.md
}
}
return result.sort();
} catch {
return [];
}
@@ -35,4 +43,3 @@ export async function getSpecIds(root: string = process.cwd()): Promise<string[]
return result.sort();
}
@@ -1,4 +1,4 @@
import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { promises as fs } from 'fs';
import path from 'path';
import { execSync } from 'child_process';
@@ -9,9 +9,6 @@ describe('change show (interactive behavior)', () => {
const changesDir = path.join(testDir, 'openspec', 'changes');
const bin = path.join(projectRoot, 'bin', 'openspec.js');
beforeAll(() => {
execSync('pnpm -s build', { stdio: 'pipe' });
});
beforeEach(async () => {
await fs.mkdir(changesDir, { recursive: true });
@@ -1,4 +1,4 @@
import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { promises as fs } from 'fs';
import path from 'path';
import { execSync } from 'child_process';
@@ -12,9 +12,6 @@ describe('change validate (interactive behavior)', () => {
const changesDir = path.join(testDir, 'openspec', 'changes');
const bin = path.join(projectRoot, 'bin', 'openspec.js');
beforeAll(() => {
execSync('pnpm -s build', { stdio: 'pipe' });
});
beforeEach(async () => {
await fs.mkdir(changesDir, { recursive: true });
+1 -4
View File
@@ -1,4 +1,4 @@
import { describe, it, expect, beforeEach, afterEach, beforeAll } from 'vitest';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { promises as fs } from 'fs';
import path from 'path';
import { execSync } from 'child_process';
@@ -10,9 +10,6 @@ describe('top-level show command', () => {
const specsDir = path.join(testDir, 'openspec', 'specs');
const openspecBin = path.join(projectRoot, 'bin', 'openspec.js');
beforeAll(() => {
execSync('pnpm -s build', { stdio: 'pipe' });
});
beforeEach(async () => {
await fs.mkdir(changesDir, { recursive: true });
+1 -4
View File
@@ -1,4 +1,4 @@
import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { promises as fs } from 'fs';
import path from 'path';
import { execSync } from 'child_process';
@@ -9,9 +9,6 @@ describe('spec show (interactive behavior)', () => {
const specsDir = path.join(testDir, 'openspec', 'specs');
const bin = path.join(projectRoot, 'bin', 'openspec.js');
beforeAll(() => {
execSync('pnpm -s build', { stdio: 'pipe' });
});
beforeEach(async () => {
await fs.mkdir(specsDir, { recursive: true });
@@ -1,4 +1,4 @@
import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { promises as fs } from 'fs';
import path from 'path';
import { execSync } from 'child_process';
@@ -9,9 +9,6 @@ describe('spec validate (interactive behavior)', () => {
const specsDir = path.join(testDir, 'openspec', 'specs');
const bin = path.join(projectRoot, 'bin', 'openspec.js');
beforeAll(() => {
execSync('pnpm -s build', { stdio: 'pipe' });
});
beforeEach(async () => {
await fs.mkdir(specsDir, { recursive: true });
+1 -5
View File
@@ -1,4 +1,4 @@
import { describe, it, expect, beforeEach, afterEach, beforeAll } from 'vitest';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { promises as fs } from 'fs';
import path from 'path';
import { execSync } from 'child_process';
@@ -9,10 +9,6 @@ describe('spec command', () => {
const specsDir = path.join(testDir, 'openspec', 'specs');
const openspecBin = path.join(projectRoot, 'bin', 'openspec.js');
beforeAll(() => {
// Ensure CLI is built so bin/openspec.js loads latest logic from dist/
execSync('pnpm -s build', { stdio: 'pipe' });
});
beforeEach(async () => {
await fs.mkdir(specsDir, { recursive: true });
@@ -0,0 +1,49 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { promises as fs } from 'fs';
import path from 'path';
import { execSync } from 'child_process';
describe('validate command enriched human output', () => {
const projectRoot = process.cwd();
const testDir = path.join(projectRoot, 'test-validate-enriched-tmp');
const changesDir = path.join(testDir, 'openspec', 'changes');
const bin = path.join(projectRoot, 'bin', 'openspec.js');
beforeEach(async () => {
await fs.mkdir(changesDir, { recursive: true });
});
afterEach(async () => {
await fs.rm(testDir, { recursive: true, force: true });
});
it('prints Next steps footer and guidance on invalid change', () => {
const changeContent = `# Test Change\n\n## Why\nThis is a sufficiently long explanation to pass the why length requirement for validation purposes.\n\n## What Changes\nThere are changes proposed, but no delta specs provided yet.`;
const changeId = 'c-next-steps';
const changePath = path.join(changesDir, changeId);
execSync(`mkdir -p ${changePath}`);
execSync(`bash -lc "cat > ${path.join(changePath, 'proposal.md')} <<'EOF'\n${changeContent}\nEOF"`);
const originalCwd = process.cwd();
try {
process.chdir(testDir);
let code = 0;
let stderr = '';
try {
execSync(`node ${bin} change validate ${changeId}`, { encoding: 'utf-8', stdio: 'pipe' });
} catch (e: any) {
code = e?.status ?? 1;
stderr = e?.stderr?.toString?.() ?? '';
}
expect(code).not.toBe(0);
expect(stderr).toContain('has issues');
expect(stderr).toContain('Next steps:');
expect(stderr).toContain('openspec change show');
} finally {
process.chdir(originalCwd);
}
});
});
+1 -4
View File
@@ -1,4 +1,4 @@
import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { promises as fs } from 'fs';
import path from 'path';
import { execSync } from 'child_process';
@@ -10,9 +10,6 @@ describe('top-level validate command', () => {
const specsDir = path.join(testDir, 'openspec', 'specs');
const bin = path.join(projectRoot, 'bin', 'openspec.js');
beforeAll(() => {
execSync('pnpm -s build', { stdio: 'pipe' });
});
beforeEach(async () => {
await fs.mkdir(changesDir, { recursive: true });
+20 -5
View File
@@ -1,14 +1,29 @@
import { describe, it, expect, beforeAll } from 'vitest';
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { ChangeCommand } from '../../../src/commands/change.js';
// These tests assume the repository's own openspec/changes directory exists
// and contains at least one active change (e.g., add-change-commands)
import path from 'path';
import { promises as fs } from 'fs';
import os from 'os';
describe('ChangeCommand.list', () => {
let cmd: ChangeCommand;
let tempRoot: string;
let originalCwd: string;
beforeAll(() => {
beforeAll(async () => {
cmd = new ChangeCommand();
originalCwd = process.cwd();
tempRoot = path.join(os.tmpdir(), `openspec-change-command-list-${Date.now()}`);
const changeDir = path.join(tempRoot, 'openspec', 'changes', 'demo');
await fs.mkdir(changeDir, { recursive: true });
const proposal = `# Change: Demo\n\n## Why\nTest list.\n\n## What Changes\n- **auth:** Add requirement`;
await fs.writeFile(path.join(changeDir, 'proposal.md'), proposal, 'utf-8');
await fs.writeFile(path.join(changeDir, 'tasks.md'), '- [x] Task 1\n- [ ] Task 2\n', 'utf-8');
process.chdir(tempRoot);
});
afterAll(async () => {
process.chdir(originalCwd);
await fs.rm(tempRoot, { recursive: true, force: true });
});
it('returns JSON with expected shape', async () => {
@@ -1,34 +1,33 @@
import { describe, it, expect, beforeAll } from 'vitest';
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { ChangeCommand } from '../../../src/commands/change.js';
import path from 'path';
import { promises as fs } from 'fs';
async function findSingleActiveChange(root: string): Promise<string | undefined> {
const changesDir = path.join(root, 'openspec', 'changes');
try {
const entries = await fs.readdir(changesDir, { withFileTypes: true });
const names = entries
.filter((e) => e.isDirectory() && e.name !== 'archive')
.map((e) => e.name);
if (names.length === 1) return names[0];
return names.includes('add-change-commands') ? 'add-change-commands' : names[0];
} catch {
return undefined;
}
}
import os from 'os';
describe('ChangeCommand.show/validate', () => {
let cmd: ChangeCommand;
let changeName: string | undefined;
let changeName: string;
let tempRoot: string;
let originalCwd: string;
beforeAll(async () => {
cmd = new ChangeCommand();
changeName = await findSingleActiveChange(process.cwd());
originalCwd = process.cwd();
tempRoot = path.join(os.tmpdir(), `openspec-change-command-${Date.now()}`);
const changesDir = path.join(tempRoot, 'openspec', 'changes', 'sample-change');
await fs.mkdir(changesDir, { recursive: true });
const proposal = `# Change: Sample Change\n\n## Why\nConsistency in tests.\n\n## What Changes\n- **auth:** Add requirement`;
await fs.writeFile(path.join(changesDir, 'proposal.md'), proposal, 'utf-8');
process.chdir(tempRoot);
changeName = 'sample-change';
});
afterAll(async () => {
process.chdir(originalCwd);
await fs.rm(tempRoot, { recursive: true, force: true });
});
it('show --json prints JSON including deltas', async () => {
if (!changeName) return; // skip if no changes present
const logs: string[] = [];
const origLog = console.log;
try {
@@ -67,8 +66,6 @@ describe('ChangeCommand.show/validate', () => {
});
it('show --json --requirements-only returns minimal object with deltas (deprecated alias)', async () => {
if (!changeName) return; // skip if no changes present
const logs: string[] = [];
const origLog = console.log;
try {
@@ -93,8 +90,6 @@ describe('ChangeCommand.show/validate', () => {
});
it('validate --strict --json returns a report with valid boolean', async () => {
if (!changeName) return; // skip if no changes present
const logs: string[] = [];
const origLog = console.log;
try {
@@ -0,0 +1,74 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { promises as fs } from 'fs';
import path from 'path';
import { Validator } from '../../src/core/validation/validator.js';
describe('Validator enriched messages', () => {
const testDir = path.join(process.cwd(), 'test-validation-enriched-tmp');
beforeEach(async () => {
await fs.mkdir(testDir, { recursive: true });
});
afterEach(async () => {
await fs.rm(testDir, { recursive: true, force: true });
});
it('adds guidance for no deltas in change', async () => {
const changeContent = `# Test Change
## Why
This is a sufficiently long explanation to pass the why length requirement for validation purposes.
## What Changes
There are changes proposed, but no delta specs provided yet.`;
const changePath = path.join(testDir, 'proposal.md');
await fs.writeFile(changePath, changeContent);
const validator = new Validator();
const report = await validator.validateChange(changePath);
expect(report.valid).toBe(false);
const msg = report.issues.map(i => i.message).join('\n');
expect(msg).toContain('Change must have at least one delta');
expect(msg).toContain('Ensure your change has a specs/ directory');
expect(msg).toContain('## ADDED/MODIFIED/REMOVED/RENAMED Requirements');
});
it('adds guidance when spec missing Purpose/Requirements', async () => {
const specContent = `# Test Spec\n\n## Requirements\n\n### Requirement: Foo\nFoo SHALL ...\n\n#### Scenario: Bar\nWhen...`;
const specPath = path.join(testDir, 'spec.md');
await fs.writeFile(specPath, specContent);
const validator = new Validator();
const report = await validator.validateSpec(specPath);
expect(report.valid).toBe(false);
const msg = report.issues.map(i => i.message).join('\n');
expect(msg).toContain('Spec must have a Purpose section');
expect(msg).toContain('Expected headers: "## Purpose" and "## Requirements"');
});
it('warns with scenario conversion template when missing scenarios', async () => {
const specContent = `# Test Spec
## Purpose
This is a sufficiently long purpose section to avoid warnings about brevity.
## Requirements
### Requirement: Foo SHALL be described
Text of requirement
`;
const specPath = path.join(testDir, 'spec.md');
await fs.writeFile(specPath, specContent);
const validator = new Validator();
const report = await validator.validateSpec(specPath);
expect(report.valid).toBe(false);
const warn = report.issues.find(i => i.path.includes('requirements[0].scenarios'));
expect(warn?.message).toContain('Requirement must have at least one scenario');
expect(warn?.message).toContain('Scenarios must use level-4 headers');
expect(warn?.message).toContain('#### Scenario:');
});
});
+4 -1
View File
@@ -4,6 +4,9 @@ export default defineConfig({
test: {
globals: true,
environment: 'node',
globalSetup: './vitest.setup.ts',
// Keep default pool settings; some tests rely on process.chdir,
// which is not supported in worker threads
include: ['test/**/*.test.ts'],
coverage: {
reporter: ['text', 'json', 'html'],
@@ -19,4 +22,4 @@ export default defineConfig({
testTimeout: 10000,
hookTimeout: 10000
}
});
});
+21
View File
@@ -0,0 +1,21 @@
import { execSync } from 'child_process';
import { existsSync } from 'fs';
import path from 'path';
// Run once before all tests
export async function setup() {
const distPath = path.join(process.cwd(), 'dist', 'cli', 'index.js');
if (!existsSync(distPath)) {
console.log('Building project before tests...');
try {
execSync('pnpm run build', {
stdio: 'inherit',
cwd: process.cwd()
});
} catch (error) {
console.error('Failed to build project:', error);
process.exit(1);
}
}
}