Compare commits

...
Author SHA1 Message Date
Tabish Bidiwale 5b2049aedf feat(view): sort active changes by progress 2025-09-16 11:59:40 +10:00
Tabish Bidiwale 332020ac6b fix: clarify active change sorting tasks 2025-09-16 11:49:57 +10:00
Tabish Bidiwale 17e6f7166b docs(readme): merge 'What You Get' into 'Why OpenSpec?' 2025-09-16 10:33:29 +10:00
Tabish Bidiwale 931d10477e Merge pull request #59 from Fission-AI/codex/rename-agent-instruction-file-to-agents.md
chore(changes): propose agent file rename
2025-09-16 10:26:37 +10:00
Tabish Bidiwale e4548bcc58 Merge pull request #60 from Fission-AI/codex/add-custom-slash-command-support-for-openspec
docs: add slash command support proposal
2025-09-16 08:41:10 +10:00
Tabish Bidiwale 68fc049955 docs(changes): use proposal/apply/archive names and per-tool slash naming; add format examples and test guidance 2025-09-16 08:39:39 +10:00
Tabish Bidiwale 4874a16495 feat(validate): propose scope-aware change validation (validate only existing artifacts) 2025-09-16 08:15:39 +10:00
Tabish Bidiwale 3caabf86cf docs(readme): regenerate from template via openspec update 2025-09-16 07:42:52 +10:00
Tabish Bidiwale d4593e4a54 docs(readme): clarify ADDED vs MODIFIED and update README template 2025-09-16 07:40:35 +10:00
Tabish Bidiwale 0144ec2b1b fix(changes): use ADDED for slash command requirements in cli-init and cli-update 2025-09-16 07:40:21 +10:00
Tabish Bidiwale 98d90cc00d Merge pull request #61 from Fission-AI/view-command-proposal
feat: add openspec view dashboard command
2025-09-12 21:33:45 +10:00
Tabish Bidiwale ccaa5ad0b0 feat: add openspec view dashboard command 2025-09-12 21:11:42 +10:00
Tabish Bidiwale 8eb7ebd7cd docs: detail slash command instructions 2025-09-12 18:25:40 +10:00
Tabish Bidiwale be395d9d74 docs(readme): shrink header logo to 64px 2025-09-12 16:34:17 +10:00
Tabish Bidiwale a09b87e391 docs(readme): add adaptive logo and center badges 2025-09-12 16:32:33 +10:00
Tabish Bidiwale 9d7b44b722 chore(changes): propose agent file rename 2025-09-10 10:56:08 +10:00
Tabish Bidiwale 44c06cc40e Merge pull request #58 from Fission-AI/docs/align-agent-instructions
docs(openspec): align agent instructions and templates
2025-09-10 10:38:29 +10:00
Tabish Bidiwale b33f435812 docs(template): sync readme-template to exactly match openspec/README.md 2025-09-09 22:15:39 +10:00
Tabish Bidiwale b62b57caf3 fix(templates): escape backticks and move examples inside template literals 2025-09-09 22:02:34 +10:00
Tabish Bidiwale 758d91613d docs(openspec): prefer CLI examples for listing/showing; keep rg for full-text search 2025-09-09 21:50:05 +10:00
Tabish Bidiwale 47180e5120 docs(openspec): add TL;DR, search guidance, design skeleton, renamed example, approval gate, and examples 2025-09-09 21:36:17 +10:00
Tabish Bidiwale 8dde1d55fc docs(openspec): align agent instructions and templates 2025-09-09 21:26:56 +10:00
Tabish Bidiwale 3cef6f0925 Merge pull request #57 from Fission-AI/remove-diff-command
Remove diff command in favor of show command
2025-09-09 14:15:34 +10:00
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 6458b6ed39 feat: adopt verb-noun CLI structure 2025-08-20 01:01:17 +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
Tabish Bidiwale 562530dfa8 Merge pull request #44 from Fission-AI/feat/add-interactive-show-command
feat: add unified show command with interactive selection
2025-08-20 00:17:26 +10:00
Tabish Bidiwale 1e17cfdd0b Address review 2025-08-20 00:14:34 +10:00
Tabish Bidiwale 5d185ba3a8 feat: add unified show command with interactive selection 2025-08-20 00:06:19 +10:00
Tabish Bidiwale 08b41c7bea Merge pull request #43 from Fission-AI/feat/validate-command-interactive-selection
feat: add unified validate command with interactive selection and bulk operations
2025-08-19 23:23:11 +10:00
Tabish Bidiwale 8ac50289f0 Add tests 2025-08-19 23:22:18 +10:00
Tabish Bidiwale 1f295cec52 feat: add unified validate command with interactive selection and bulk operations 2025-08-19 22:58:17 +10:00
Tabish Bidiwale ad8e213cf9 Merge pull request #42 from Fission-AI/feat/bulk-validation-and-interactive-selection
feat: add bulk validation and interactive selection for OpenSpec commands
2025-08-19 22:35:25 +10:00
Tabish Bidiwale a6c1a90165 docs: consolidate retrospective documents into comprehensive analysis 2025-08-19 22:30:13 +10:00
Tabish Bidiwale 21b5a3e680 refactor: split validation and show commands into separate change proposals 2025-08-19 22:06:09 +10:00
Tabish Bidiwale 1bda5be96c refactor: use single validate command with flags for better UX 2025-08-19 21:40:27 +10:00
Tabish Bidiwale 0faf44807e refactor: simplify change to modify existing command specs instead of creating new ones 2025-08-19 21:29:38 +10:00
Tabish Bidiwale f9c1d07edb feat: add change proposal for bulk validation and interactive selection 2025-08-19 21:10:56 +10:00
Tabish Bidiwale 2bd1a4417c Merge pull request #41 from Fission-AI/chore/fix-change-validations
feat: Chore/fix change validations
2025-08-19 20:51:22 +10:00
Tabish Bidiwale 1db19ac3d8 remove delta from proposal 2025-08-19 20:49:02 +10:00
Tabish Bidiwale 25018786e4 chore(conventions): remove delta sections from proposals; keep deltas only in change specs; all changes pass --strict validation 2025-08-19 20:46:13 +10:00
Tabish Bidiwale 5fd9173ad9 remove md files 2025-08-19 20:40:14 +10:00
Tabish Bidiwale 0a611747bc fix(change-validate): ensure delta specs emit requirements arrays; add missing Why/What sections and delta content for changes; refine removed requirement text and scenarios; all changes pass --strict validation 2025-08-19 20:31:41 +10:00
Tabish Bidiwale 49e422724f update test commands 2025-08-19 19:51:43 +10:00
Tabish Bidiwale c22d6bce1c show completion for tasks when archiving 2025-08-19 19:48:54 +10:00
Tabish Bidiwale 1c0dc09dc9 Merge pull request #40 from Fission-AI/update-archive-command
feat: Update archive command
2025-08-19 18:57:51 +10:00
Tabish Bidiwale f0b1e00c65 Address review 2025-08-19 18:44:37 +10:00
Tabish Bidiwale 5fe72ddc5d remove archive file 2025-08-19 18:26:34 +10:00
Tabish Bidiwale c18f3b2b2e feat(archive): apply delta-based updates with header matching, skeleton creation, atomic writes, and per-spec counts; add requirement-block parser; add tests covering normalization, order, validation, rename+modify, and multi-spec; update proposal and tasks with product decisions 2025-08-19 18:24:27 +10:00
Tabish Bidiwale 33344727a8 Merge pull request #39 from Fission-AI/make-commands-consistent
Make change and spec commands consistent (raw-first)
2025-08-18 23:26:47 +10:00
Tabish Bidiwale 828e5ba316 chore: remove unused imports; improve no-change messaging; update README for raw-first, JSON-only filters, --long, and --no-color 2025-08-18 23:20:47 +10:00
Tabish Bidiwale 31c57f5c0f Follow-up: add debug logging and tests for raw-first behavior\n\n- change list: add conditional debug logging when reading tasks.md fails\n- spec tests: align with raw-first (JSON-only filters), add --no-color test, raw text passthrough, missing ID error\n- fix change show JSON mapping to stable keys (id/title) and types; ensure build passes 2025-08-18 22:47:03 +10:00
Tabish Bidiwale 767a0053e8 Make change and spec commands consistent (raw-first)\n\n- Require explicit IDs for show; no auto-pick\n- Text mode: raw markdown passthrough; no filters\n- JSON contracts: minimal objects (no top-level arrays)\n- change show: add --deltas-only (JSON); deprecate --requirements-only\n- change list: ids by default; --long for minimal details; unified JSON { id, title, deltaCount, taskStatus }\n- spec show: raw text; JSON { id, title, overview, requirementCount, requirements, metadata }\n- spec list: ids by default; --long for minimal details; unified JSON { id, title, requirementCount }\n- Errors: console.error + process.exitCode\n- Add global --no-color\n- Update tests to new contracts 2025-08-18 22:31:17 +10:00
Tabish Bidiwale fd65b99c91 Merge pull request #38 from Fission-AI/add-change-commands
feat: add change command with show, list, and validate subcommands
2025-08-16 17:19:35 +10:00
Tabish Bidiwale e170df9f41 test(change): add minimal tests for change parser and command; fix async converter usage 2025-08-16 17:18:32 +10:00
Tabish Bidiwale b91040e8c2 chore(cli): tighten change show help text and remove unused imports 2025-08-16 17:18:32 +10:00
Tabish Bidiwale 8824bd2a42 feat: implement change-specific parser for delta format 2025-08-16 17:18:32 +10:00
Tabish Bidiwale 1d3c292d94 fix: address code review feedback for change commands
- Replace any types with proper Change and Delta types from schemas
- Add error logging in catch blocks when DEBUG env var is set
- Include file paths in error messages for better debugging
- Extract regex patterns and magic strings as constants
- Improve code maintainability and type safety
2025-08-16 17:18:32 +10:00
Tabish Bidiwale cfe6da96ac feat: add change command with show, list, and validate subcommands
- Add new `openspec change` command with three subcommands
- Implement JSON output capability for change proposals
- Add deprecation warning to legacy `openspec list` command
- Enable --requirements-only filtering for change show
- Support --strict mode and --json flags for validation

This provides programmatic access to change proposals through JSON output
and establishes a consistent resource-based command structure.
2025-08-16 17:18:32 +10:00
Tabish Bidiwale c3c78551d0 Merge pull request #37 from Fission-AI/add-spec-commands
Add spec command for programmatic access to specifications
2025-08-16 11:40:25 +10:00
Tabish Bidiwale f1fabc5f18 refactor: standardize spec format to use Purpose and Requirements sections only 2025-08-16 11:34:09 +10:00
Tabish Bidiwale 166b960428 chore(deps): upgrade zod to v4 and verify compatibility 2025-08-16 00:39:47 +10:00
Tabish Bidiwale ef1a6c0f0b docs: mark all spec command tasks as complete 2025-08-16 00:39:42 +10:00
Tabish Bidiwale 9b3944bd09 refactor(cli): simplify spec command parsing and filtering; improve option validation and exits 2025-08-16 00:32:55 +10:00
Tabish Bidiwale 7917d08a50 feat(cli): add spec command for programmatic access to specifications
Implements new `openspec spec` command with three subcommands:
- `spec show`: Display specs with JSON output and filtering options
- `spec list`: List all available specifications
- `spec validate`: Validate spec structure with detailed reporting

Key features:
- JSON output for CI/CD integration (--json flag)
- Content filtering (--requirements, --no-scenarios, -r)
- Strict validation mode (--strict)
- Support for both Overview/Purpose and Requirements/Behavior sections

This enables programmatic access to OpenSpec specifications for external
tools and automated pipelines as specified in the add-spec-commands change.
2025-08-15 23:54:26 +10:00
Tabish Bidiwale 4a8e5986f0 Merge pull request #35 from Fission-AI/add-zod-validation
feat: Add Zod runtime validation for specs and changes
2025-08-15 23:34:48 +10:00
Tabish Bidiwale 103838f371 fix: address PR review comments for validation improvements
- Use word boundaries in delta operation detection to avoid false matches
- Standardize name extraction to use directory name after specs/changes
- Combine archive validation warning into single prompt for better UX
- Add change.md validation to archive command before archiving
2025-08-15 23:32:51 +10:00
Tabish Bidiwale 0a26c686f9 refactor: simplify scenario parsing to store raw text
- Replace structured {given, when, then} with {rawText} field
- Remove complex Given/When/Then parsing logic
- Preserve original formatting and whitespace
- Update all tests to use rawText field
- Remove unnecessary validation checks

This change reduces complexity while preserving all content exactly
as written, making the system more maintainable and flexible.
2025-08-15 23:25:24 +10:00
Tabish Bidiwale efcf766193 docs: add validation and migration documentation to openspec
- Add VALIDATION.md with comprehensive schema and rules documentation
- Add MIGRATION.md with guide for future command integration
- Update task references to correct documentation locations
2025-08-15 23:07:00 +10:00
Tabish Bidiwale 151eddb759 fix: address minor code review issues
- Extract magic numbers to named constants in validation/constants.ts
- Update task 3.2 to reflect actual implementation (constants.ts)
- Add comprehensive documentation for validation system
- Add migration guide for future command integration
- Update CLI help text for diff command
2025-08-15 23:05:47 +10:00
Tabish Bidiwale cb0d6f3189 feat: add zod runtime validation for specs and changes
- Add Zod schemas for specs, changes, requirements, and scenarios
- Implement markdown parser for extracting structured data
- Create validation infrastructure with error/warning/info levels
- Enhance archive command with pre-archive validation
- Add --no-validate flag with confirmation prompt for emergencies
- Enhance diff command with non-blocking validation warnings
- Add JSON converters for spec and change formats
- Add comprehensive test coverage for all validation components
2025-08-15 22:50:05 +10:00
Tabish Bidiwale a897c697a5 Merge pull request #34 from Fission-AI/json-zod-implementation-plan
Add JSON output and Zod validation change proposals
2025-08-15 22:01:58 +10:00
Tabish Bidiwale 3bedf6b23e fix: move cli-change and cli-spec specs to their respective changes 2025-08-15 21:28:57 +10:00
Tabish Bidiwale 9ff0e85693 refactor: reorder implementation phases to zod -> change -> spec 2025-08-15 21:09:46 +10:00
Tabish Bidiwale 1ca407fa2f fix: rename --deltas to --requirements-only for clarity
The --deltas flag was ambiguous. Since it shows only the requirement
changes (ADDED/MODIFIED/REMOVED/RENAMED sections), rename it to
--requirements-only to be explicit about what it displays.
2025-08-15 19:14:29 +10:00
Tabish Bidiwale 46c927af06 fix: use explicit --json flag instead of ambiguous -j
Following the principle that explicit is better than implicit,
replace all occurrences of `-j` with `--json` for clarity.
2025-08-15 19:12:12 +10:00
Tabish Bidiwale 87cb206e88 feat: add JSON output and Zod validation change proposals
Add three OpenSpec change proposals for enhancing the CLI:
- add-spec-commands: Resource-based spec commands with JSON output
- add-change-commands: Resource-based change commands with JSON output
- add-zod-validation: Runtime validation with detailed error reporting

These proposals enable programmatic access to specs and changes,
improving integration with CI/CD pipelines and external tooling.
2025-08-15 17:40:06 +10:00
Tabish Bidiwale 6806a2fc5a Merge pull request #32 from Fission-AI/update-delta-conventions
feat: update conventions to support delta-based changes
2025-08-14 18:06:43 +10:00
Tabish Bidiwale 4ab65d75dd feat: update conventions to support delta-based changes
- Update openspec-conventions spec with delta-based approach
- Add Header-Based Requirement Identification for programmatic matching
- Define ADDED/MODIFIED/REMOVED/RENAMED sections format
- Document standard output symbols (+ ~ - →)
- Update openspec/README.md with delta conventions and examples
- Update init command template to use delta format
- Mark completed tasks in adopt-delta-based-changes/tasks.md

This implements the first part of the delta-based changes proposal,
updating all documentation and conventions to support the new format.
2025-08-14 18:01:09 +10:00
Tabish Bidiwale 2a3294dbfb Delete abandoned changes 2025-08-14 17:44:21 +10:00
Tabish Bidiwale 8334006f2b Merge pull request #31 from Fission-AI/adopt-delta-based-changes
feat: adopt delta-based change storage for better reviews
2025-08-14 17:33:50 +10:00
Tabish Bidiwale 8a559e0d00 fix: clarify openspec/README.md in tasks (AI instructions file) 2025-08-14 17:31:37 +10:00
Tabish Bidiwale a3924f17b2 fix: remove specific rendering examples from diff spec 2025-08-14 17:25:12 +10:00
Tabish Bidiwale b11e862b0f chore: reorganize tasks into clearer command-based groups 2025-08-14 17:20:18 +10:00
Tabish Bidiwale 099585afcb fix: remove unnecessary backward compatibility for full-state format 2025-08-14 17:16:18 +10:00
Tabish Bidiwale f023fc317e fix: simplify diff command to show only changes by default 2025-08-14 16:59:47 +10:00
Tabish Bidiwale 38a1463af0 fix: redesign diff command for requirement-level comparison
The diff command now applies deltas and shows side-by-side
requirement comparison rather than just displaying delta instructions.
2025-08-14 16:49:39 +10:00
Tabish Bidiwale f2399d3280 fix: restore implementation tasks that update actual specs
- Added back tasks to update the actual specs (not just proposals)
- Included validation implementation tasks
- Kept implementation-focused structure
- Clarified that specs in changes folder are proposals, not current truth
2025-08-14 12:51:01 +10:00
Tabish Bidiwale f699e10778 fix: remove duplication and simplify spec organization
- CLI specs now reference openspec-conventions for shared concepts
- Added standard output symbols definition to conventions
- Simplified tasks.md to focus on implementation only
- Fixed terminology to consistently use 'normalized header'
2025-08-14 12:38:27 +10:00
Tabish Bidiwale c824d8927f fix: address review feedback for consistency and clarity
- Unify header matching: normalize(header) = trim(header), case-sensitive
- Clarify RENAMED+MODIFIED: MODIFIED must use new header after rename
- Add RENAMED display to cli-diff with → symbol
- Define delta format detection via level-2 heading presence
- Remove RESTRUCTURED marker completely (unnecessary complexity)
- Standardize output symbols: + (added), ~ (modified), - (removed), → (renamed)
2025-08-14 12:14:26 +10:00
Tabish Bidiwale 5821b24ab3 fix: simplify proposal to reduce complexity
- Condense 'What Changes' section to core concepts only
- Simplify Impact section to essentials
- Make Conflict Resolution one concise paragraph
- Remove inline comment from example
- Focus on the key benefit: readable GitHub diffs
2025-08-14 00:02:30 +10:00
Tabish Bidiwale e812eb9e78 fix: remove migration timeline and deprecation notices
- Remove phased migration timeline (project not in use yet)
- Remove deprecation notices from CLI commands
- Keep simple backward compatibility for both formats
2025-08-13 23:59:52 +10:00
Tabish Bidiwale abfe13c5a7 fix: address review feedback on delta-based storage proposal
- Add whitespace normalization for header matching
- Add migration timeline with 3-phase approach over 6 months
- Clarify conflict resolution (handled by Git naturally)
- Replace 'self-contained' with 'complete content' for clarity
2025-08-13 23:57:24 +10:00
Tabish Bidiwale 0d5a75d3a0 feat: add cli-archive and cli-diff spec changes for delta-based storage 2025-08-13 23:49:36 +10:00
Tabish Bidiwale b30c0ad27e chore: remove overly detailed header-matching example 2025-08-13 23:43:14 +10:00
Tabish Bidiwale 1cada18186 feat: propose delta-based change storage for better reviews
- Replace full future state storage with delta-based approach
- Store only ADDED, MODIFIED, RENAMED, and REMOVED requirements
- Use headers as unique identifiers for programmatic matching
- Enable cleaner GitHub reviews showing only actual changes
- Add comprehensive examples and implementation tasks
2025-08-13 23:40:01 +10:00
Tabish Bidiwale fa50b07938 Merge pull request #29 from Fission-AI/fix-update-respects-tool-selection
fix: update command respects existing AI tool files
2025-08-13 23:36:50 +10:00
Tabish Bidiwale b6cad1631c feat: improve error handling and console output clarity
- Added try-catch error handling for configurator failures
- Improved console output to be more specific about what was updated
- Added TODO comment for future multi-configurator test enhancement
- Added test for error handling when configurator fails
- Console now shows 'Updated OpenSpec instructions (README.md)' for clarity
2025-08-13 23:33:23 +10:00
Tabish Bidiwale 2497e81e4d Merge pull request #28 from Fission-AI/add-skip-specs-archive-option
feat: add --skip-specs flag to archive command
2025-08-13 23:31:15 +10:00
Tabish Bidiwale d8cba03840 docs: enhance --skip-specs help text and add implementation notes 2025-08-13 23:27:41 +10:00
Tabish Bidiwale 0b1be19302 fix: update command respects existing AI tool files
The update command now only updates existing AI tool configuration
files instead of forcing CLAUDE.md creation. This allows team members
to use different AI tools without conflicts.

- Modified update.ts to check for existing files before updating
- Added comprehensive tests for the new behavior
- Updated spec and documentation to reflect team-friendly approach
- Created project README documenting the behavior
2025-08-13 23:25:53 +10:00
Tabish Bidiwale d7ebee4555 feat: add --skip-specs flag to archive command and fix confirmation behavior
- Add --skip-specs flag to archive command to skip spec update operations
- Fix confirmation behavior: declining spec updates now continues with archiving instead of cancelling
- Add comprehensive tests for new functionality
- Update task documentation to reflect completed implementation
2025-08-13 23:21:57 +10:00
Tabish Bidiwale 8f45a6f6ee Merge pull request #27 from Fission-AI/fix/update-respects-tool-selection
Fix: Update command respects AI tool selection
2025-08-13 23:11:36 +10:00
Tabish Bidiwale 6da77f01ce Merge pull request #26 from Fission-AI/feat/skip-spec-update-archive-proposal
feat: add skip-specs option for archive command
2025-08-13 23:10:45 +10:00
Tabish Bidiwale d90eccf959 fix: update command respects AI tool selection
The update command now only updates existing AI tool configuration
files instead of forcing CLAUDE.md creation. This allows team members
to use different AI tools without conflicts.
2025-08-13 23:06:05 +10:00
Tabish Bidiwale f192a97aeb feat: add proposal for skip-specs option in archive command
Add change proposal to enable skipping spec updates during archive operation.
This allows archiving changes that don't modify specs (tooling, docs, etc.)
and fixes the confirmation behavior to continue archiving even when users
decline spec updates.
2025-08-13 23:00:16 +10:00
Tabish Bidiwale 7781bbadd3 Merge pull request #25 from Fission-AI/feat/apply-structured-spec-format
feat: apply structured spec format to all specifications
2025-08-13 22:31:43 +10:00
Tabish Bidiwale aeaa1d50cc fix: remove Format Flexibility requirement from conventions
Remove the Format Flexibility section as it's not needed for the structured spec format. Keep focus on behavioral specifications only.
2025-08-13 22:29:10 +10:00
Tabish Bidiwale fa5df9a329 feat: apply structured spec format to all specifications
- Add Specification Format section to openspec-conventions with:
  - Requirement headers for consistent structure
  - Scenario headers with bold WHEN/THEN/AND keywords
  - Format flexibility for different content types

- Update all CLI command specs to use structured format:
  - cli-init: Convert all behavioral sections
  - cli-list: Apply structured format throughout
  - cli-update: Restructure requirements and edge cases
  - cli-diff: Update all behavior sections
  - cli-archive: Convert complex behaviors to scenarios

- Update openspec-conventions spec itself to follow its own format
- Mark all tasks as completed
2025-08-13 22:26:03 +10:00
Tabish Bidiwale f94f396c99 Merge pull request #24 from Fission-AI/cleanup/remove-add-requirement-markers
chore: remove abandoned add-requirement-markers change
2025-08-13 22:10:24 +10:00
Tabish Bidiwale 1f670f71d4 chore: remove abandoned add-requirement-markers change 2025-08-13 22:02:51 +10:00
Tabish Bidiwale 32b2901d13 Merge pull request #23 from Fission-AI/feat/structured-spec-format
feat(openspec): add structured format specification
2025-08-13 21:52:05 +10:00
Tabish Bidiwale 2ad0b1d306 feat: add tasks to update existing specs to new format
Add section 3 with tasks to update all existing CLI command specs to use the new structured format in their Behavior sections
2025-08-13 21:49:26 +10:00
Tabish Bidiwale 279d327899 fix: remove Format Flexibility task for non-behavioral specs
Non-behavioral specs not planned for now, keeping focus on behavioral specifications only
2025-08-13 21:48:36 +10:00
Tabish Bidiwale 5d848cf005 fix: remove unnecessary migration documentation
- Remove migration.md as project has no existing users to migrate
- Remove Migration Support section from tasks.md
- Structured format only applies to behavioral specs, not convention definitions
2025-08-13 21:36:52 +10:00
Tabish Bidiwale 5607fd3ccb fix: remove migration section from spec, keep only in change proposal 2025-08-13 21:21:28 +10:00
Tabish Bidiwale 6a0d862258 refactor: enhance openspec-conventions with structured format
- Merge format rules into openspec-conventions instead of separate spec
- Add Format Flexibility requirement for non-behavioral content
- Address review feedback on gradual migration and alternative formats
2025-08-13 21:17:46 +10:00
Tabish Bidiwale 1fe5f84fbc feat(openspec): add structured format specification for consistency 2025-08-13 21:05:36 +10:00
Tabish Bidiwale 80e78ecd1e chore: archive add-archive-command change after deployment 2025-08-13 18:49:17 +10:00
Tabish Bidiwale 564135a530 archive diff command 2025-08-13 18:47:31 +10:00
Tabish Bidiwale b9e80641a0 Merge pull request #21 from Fission-AI/feat/implement-archive-command
feat: implement archive command for OpenSpec changes
2025-08-13 18:41:54 +10:00
Tabish Bidiwale 0755994eaa refactor: use @inquirer/prompts for consistent UX in archive command
- Replace readline with @inquirer/prompts for all user interactions
- Add arrow key navigation for change selection (consistent with diff command)
- Use confirm() for yes/no prompts with better UX
- Remove manual readline interface management (no longer needed)
- Update tests to mock @inquirer/prompts instead of readline
- Add new test cases for interactive mode behavior

This change provides a consistent user experience across all OpenSpec commands,
where users can navigate options with arrow keys rather than typing numbers.
2025-08-13 18:37:18 +10:00
Tabish Bidiwale dcabd6de31 fix: address PR review feedback for archive command
- Add try-finally block to ensure readline interface always closes
- Extract date formatting to dedicated getArchiveDate() method
- Add comprehensive unit tests for ArchiveCommand covering:
  - Successful archiving flow
  - Incomplete tasks warning
  - Spec updates during archiving
  - Edge cases (missing tasks.md, no specs)
  - Error scenarios (missing change, duplicate archive)
  - No OpenSpec directory error
2025-08-13 18:27:24 +10:00
Tabish Bidiwale aef6ce01ff feat: implement archive command for OpenSpec changes
Adds a new `openspec archive` command that moves completed changes to an archive
directory with date-based naming. The command includes:
- Interactive change selection when no name provided
- Incomplete task warnings before archiving
- Automatic spec updates to main specs directory
- Confirmation prompts (skippable with --yes flag)
- Duplicate archive prevention

Also fixes TypeScript compilation errors in diff.ts and init.ts.
2025-08-13 18:19:26 +10:00
Tabish Bidiwale 441f9f444b Merge pull request #20 from Fission-AI/fix-archive-spec-updates
Fix: Add spec update functionality to archive command
2025-08-13 18:03:09 +10:00
Tabish Bidiwale b322829091 fix: add spec update functionality to archive command
The archive command was missing critical functionality to update main specs
from the change's future state specs when archiving. This fix adds:
- Spec update process that copies future state specs to main specs directory
- Confirmation prompt showing which specs will be created vs updated
- --yes flag for automation scenarios to skip confirmations
- Safety by default with clear visibility into spec changes
2025-08-13 18:00:00 +10:00
Tabish Bidiwale 5167e65a5c chore: archive add-list-command change after deployment 2025-08-13 17:36:12 +10:00
Tabish Bidiwale 5c6b4113a7 Merge pull request #19 from Fission-AI/feat/add-archive-command
feat: add archive command for completed changes
2025-08-13 17:25:34 +10:00
Tabish Bidiwale a8b76c3e69 Merge pull request #18 from Fission-AI/feat/implement-list-command
feat: add list command to show active changes with task status
2025-08-13 17:23:21 +10:00
Tabish Bidiwale d3237cac7b feat: add OpenSpec change proposal for archive command 2025-08-13 17:23:17 +10:00
166 changed files with 14048 additions and 1518 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.
+275
View File
@@ -0,0 +1,275 @@
<p align="center">
<a href="https://github.com/Fission-AI/OpenSpec">
<picture>
<source srcset="assets/openspec_pixel_dark.svg" media="(prefers-color-scheme: dark)">
<source srcset="assets/openspec_pixel_light.svg" media="(prefers-color-scheme: light)">
<img src="assets/openspec_pixel_light.svg" alt="OpenSpec logo" height="64">
</picture>
</a>
</p>
<p align="center">Spec-driven development for AI coding assistants.</p>
<p align="center">
<a href="https://github.com/Fission-AI/OpenSpec/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/Fission-AI/OpenSpec/actions/workflows/ci.yml/badge.svg" /></a>
<a href="https://www.npmjs.com/package/@fission-ai/openspec"><img alt="npm version" src="https://img.shields.io/npm/v/@fission-ai/openspec?style=flat-square" /></a>
<a href="https://nodejs.org/"><img alt="node version" src="https://img.shields.io/node/v/@fission-ai/openspec?style=flat-square" /></a>
<a href="./LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square" /></a>
<a href="https://conventionalcommits.org"><img alt="Conventional Commits" src="https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg?style=flat-square" /></a>
</p>
# OpenSpec
**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, Predictable Output** - Clear specs lead to reliable, repeatable code generation
- **Team Alignment via Spec Reviews** - Everyone reviews intentions, not code surprises
- **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
- **Living Documentation** - Specs evolve with your code as a natural byproduct
- **Universal Tool Support** - Works with any AI assistant (Claude Code, Cursor, and more)
- **No API Keys Required** - Integrates through context rules, not external services
## 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 @fission-ai/openspec
```
## Getting Started
### 1. Initialize OpenSpec in Your Project
```bash
# Navigate to your project
cd my-project
# Initialize OpenSpec
openspec init
# Select your AI tool (more coming soon!):
# "Which AI tool do you use?"
# > Claude Code
# Cursor (coming soon)
# This creates:
# openspec/
# ├── specs/ # Current specifications (truth)
# ├── changes/ # Proposed changes
# └── README.md # AI instructions for your tool
```
### 2. Create Your First Change
Jump straight into creating a change proposal with your AI assistant (works with Claude Code, Cursor, or any AI tool):
```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."
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)
You: "The proposal looks good. Let's implement it."
AI: "Following the tasks in openspec/changes/add-user-profile-api/tasks.md:
Task 1.1: Create user profile model..."
*Implements each task systematically*
```
### 3. Track Your Work
```bash
# View active changes (what's being worked on)
openspec list
# Validate your changes are properly formatted
openspec validate add-2fa --strict
# After deployment, archive the completed change
openspec archive add-2fa
# This moves the change to archive/ and updates specs/
```
## Common Commands
```bash
# Most used:
openspec list # See what changes you're working on
openspec archive <change> # Mark a change as complete after deployment
# Also useful:
openspec validate <change> # Check formatting before committing
openspec show <change> # View change details
```
## Example: How AI Creates OpenSpec Files
When you ask your AI assistant to "add two-factor authentication", it creates:
```
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
```
### AI-Generated Spec (created in `openspec/specs/auth/spec.md`):
```markdown
# Auth Specification
## 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.
## Contributing
- 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
+89
View File
@@ -0,0 +1,89 @@
<svg width="640" height="80" viewBox="0 0 640 80" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M32 0H16V16H32V0Z" fill="white"/>
<path d="M48 0H32V16H48V0Z" fill="white"/>
<path d="M16 16H0V32H16V16Z" fill="white"/>
<path d="M64 16H48V32H64V16Z" fill="white"/>
<path d="M16 32H0V48H16V32Z" fill="white"/>
<path d="M64 32H48V48H64V32Z" fill="white"/>
<path d="M16 48H0V64H16V48Z" fill="white"/>
<path d="M64 48H48V64H64V48Z" fill="white"/>
<path d="M32 64H16V80H32V64Z" fill="white"/>
<path d="M48 64H32V80H48V64Z" fill="white"/>
<path d="M96 0H80V16H96V0Z" fill="white"/>
<path d="M112 0H96V16H112V0Z" fill="white"/>
<path d="M128 0H112V16H128V0Z" fill="white"/>
<path d="M96 16H80V32H96V16Z" fill="white"/>
<path d="M144 16H128V32H144V16Z" fill="white"/>
<path d="M96 32H80V48H96V32Z" fill="white"/>
<path d="M112 32H96V48H112V32Z" fill="white"/>
<path d="M128 32H112V48H128V32Z" fill="white"/>
<path d="M144 32H128V48H144V32Z" fill="white"/>
<path d="M96 48H80V64H96V48Z" fill="white"/>
<path d="M96 64H80V80H96V64Z" fill="white"/>
<path d="M176 0H160V16H176V0Z" fill="white"/>
<path d="M192 0H176V16H192V0Z" fill="white"/>
<path d="M208 0H192V16H208V0Z" fill="white"/>
<path d="M224 0H208V16H224V0Z" fill="white"/>
<path d="M176 16H160V32H176V16Z" fill="white"/>
<path d="M176 32H160V48H176V32Z" fill="white"/>
<path d="M192 32H176V48H192V32Z" fill="white"/>
<path d="M208 32H192V48H208V32Z" fill="white"/>
<path d="M176 48H160V64H176V48Z" fill="white"/>
<path d="M176 64H160V80H176V64Z" fill="white"/>
<path d="M192 64H176V80H192V64Z" fill="white"/>
<path d="M208 64H192V80H208V64Z" fill="white"/>
<path d="M224 64H208V80H224V64Z" fill="white"/>
<path d="M256 0H240V16H256V0Z" fill="white"/>
<path d="M304 0H288V16H304V0Z" fill="white"/>
<path d="M256 16H240V32H256V16Z" fill="white"/>
<path d="M272 16H256V32H272V16Z" fill="white"/>
<path d="M304 16H288V32H304V16Z" fill="white"/>
<path d="M256 32H240V48H256V32Z" fill="white"/>
<path d="M288 32H272V48H288V32Z" fill="white"/>
<path d="M304 32H288V48H304V32Z" fill="white"/>
<path d="M256 48H240V64H256V48Z" fill="white"/>
<path d="M304 48H288V64H304V48Z" fill="white"/>
<path d="M256 64H240V80H256V64Z" fill="white"/>
<path d="M304 64H288V80H304V64Z" fill="white"/>
<path d="M352 0H336V16H352V0Z" fill="white"/>
<path d="M368 0H352V16H368V0Z" fill="white"/>
<path d="M384 0H368V16H384V0Z" fill="white"/>
<path d="M336 16H320V32H336V16Z" fill="white"/>
<path d="M352 32H336V48H352V32Z" fill="white"/>
<path d="M368 32H352V48H368V32Z" fill="white"/>
<path d="M384 48H368V64H384V48Z" fill="white"/>
<path d="M336 64H320V80H336V64Z" fill="white"/>
<path d="M352 64H336V80H352V64Z" fill="white"/>
<path d="M368 64H352V80H368V64Z" fill="white"/>
<path d="M416 0H400V16H416V0Z" fill="white"/>
<path d="M432 0H416V16H432V0Z" fill="white"/>
<path d="M448 0H432V16H448V0Z" fill="white"/>
<path d="M416 16H400V32H416V16Z" fill="white"/>
<path d="M464 16H448V32H464V16Z" fill="white"/>
<path d="M416 32H400V48H416V32Z" fill="white"/>
<path d="M432 32H416V48H432V32Z" fill="white"/>
<path d="M448 32H432V48H448V32Z" fill="white"/>
<path d="M464 32H448V48H464V32Z" fill="white"/>
<path d="M416 48H400V64H416V48Z" fill="white"/>
<path d="M416 64H400V80H416V64Z" fill="white"/>
<path d="M496 0H480V16H496V0Z" fill="white"/>
<path d="M512 0H496V16H512V0Z" fill="white"/>
<path d="M528 0H512V16H528V0Z" fill="white"/>
<path d="M544 0H528V16H544V0Z" fill="white"/>
<path d="M496 16H480V32H496V16Z" fill="white"/>
<path d="M496 32H480V48H496V32Z" fill="white"/>
<path d="M512 32H496V48H512V32Z" fill="white"/>
<path d="M528 32H512V48H528V32Z" fill="white"/>
<path d="M496 48H480V64H496V48Z" fill="white"/>
<path d="M496 64H480V80H496V64Z" fill="white"/>
<path d="M512 64H496V80H512V64Z" fill="white"/>
<path d="M528 64H512V80H528V64Z" fill="white"/>
<path d="M544 64H528V80H544V64Z" fill="white"/>
<path d="M592 0H576V16H592V0Z" fill="white"/>
<path d="M608 0H592V16H608V0Z" fill="white"/>
<path d="M576 16H560V32H576V16Z" fill="white"/>
<path d="M576 32H560V48H576V32Z" fill="white"/>
<path d="M576 48H560V64H576V48Z" fill="white"/>
<path d="M592 64H576V80H592V64Z" fill="white"/>
<path d="M608 64H592V80H608V64Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 4.1 KiB

+89
View File
@@ -0,0 +1,89 @@
<svg xmlns="http://www.w3.org/2000/svg" width="640" height="80" viewBox="0 0 640 80">
<rect x="16" y="0" width="16" height="16" fill="black" />
<rect x="32" y="0" width="16" height="16" fill="black" />
<rect x="0" y="16" width="16" height="16" fill="black" />
<rect x="48" y="16" width="16" height="16" fill="black" />
<rect x="0" y="32" width="16" height="16" fill="black" />
<rect x="48" y="32" width="16" height="16" fill="black" />
<rect x="0" y="48" width="16" height="16" fill="black" />
<rect x="48" y="48" width="16" height="16" fill="black" />
<rect x="16" y="64" width="16" height="16" fill="black" />
<rect x="32" y="64" width="16" height="16" fill="black" />
<rect x="80" y="0" width="16" height="16" fill="black" />
<rect x="96" y="0" width="16" height="16" fill="black" />
<rect x="112" y="0" width="16" height="16" fill="black" />
<rect x="80" y="16" width="16" height="16" fill="black" />
<rect x="128" y="16" width="16" height="16" fill="black" />
<rect x="80" y="32" width="16" height="16" fill="black" />
<rect x="96" y="32" width="16" height="16" fill="black" />
<rect x="112" y="32" width="16" height="16" fill="black" />
<rect x="128" y="32" width="16" height="16" fill="black" />
<rect x="80" y="48" width="16" height="16" fill="black" />
<rect x="80" y="64" width="16" height="16" fill="black" />
<rect x="160" y="0" width="16" height="16" fill="black" />
<rect x="176" y="0" width="16" height="16" fill="black" />
<rect x="192" y="0" width="16" height="16" fill="black" />
<rect x="208" y="0" width="16" height="16" fill="black" />
<rect x="160" y="16" width="16" height="16" fill="black" />
<rect x="160" y="32" width="16" height="16" fill="black" />
<rect x="176" y="32" width="16" height="16" fill="black" />
<rect x="192" y="32" width="16" height="16" fill="black" />
<rect x="160" y="48" width="16" height="16" fill="black" />
<rect x="160" y="64" width="16" height="16" fill="black" />
<rect x="176" y="64" width="16" height="16" fill="black" />
<rect x="192" y="64" width="16" height="16" fill="black" />
<rect x="208" y="64" width="16" height="16" fill="black" />
<rect x="240" y="0" width="16" height="16" fill="black" />
<rect x="288" y="0" width="16" height="16" fill="black" />
<rect x="240" y="16" width="16" height="16" fill="black" />
<rect x="256" y="16" width="16" height="16" fill="black" />
<rect x="288" y="16" width="16" height="16" fill="black" />
<rect x="240" y="32" width="16" height="16" fill="black" />
<rect x="272" y="32" width="16" height="16" fill="black" />
<rect x="288" y="32" width="16" height="16" fill="black" />
<rect x="240" y="48" width="16" height="16" fill="black" />
<rect x="288" y="48" width="16" height="16" fill="black" />
<rect x="240" y="64" width="16" height="16" fill="black" />
<rect x="288" y="64" width="16" height="16" fill="black" />
<rect x="336" y="0" width="16" height="16" fill="black" />
<rect x="352" y="0" width="16" height="16" fill="black" />
<rect x="368" y="0" width="16" height="16" fill="black" />
<rect x="320" y="16" width="16" height="16" fill="black" />
<rect x="336" y="32" width="16" height="16" fill="black" />
<rect x="352" y="32" width="16" height="16" fill="black" />
<rect x="368" y="48" width="16" height="16" fill="black" />
<rect x="320" y="64" width="16" height="16" fill="black" />
<rect x="336" y="64" width="16" height="16" fill="black" />
<rect x="352" y="64" width="16" height="16" fill="black" />
<rect x="400" y="0" width="16" height="16" fill="black" />
<rect x="416" y="0" width="16" height="16" fill="black" />
<rect x="432" y="0" width="16" height="16" fill="black" />
<rect x="400" y="16" width="16" height="16" fill="black" />
<rect x="448" y="16" width="16" height="16" fill="black" />
<rect x="400" y="32" width="16" height="16" fill="black" />
<rect x="416" y="32" width="16" height="16" fill="black" />
<rect x="432" y="32" width="16" height="16" fill="black" />
<rect x="448" y="32" width="16" height="16" fill="black" />
<rect x="400" y="48" width="16" height="16" fill="black" />
<rect x="400" y="64" width="16" height="16" fill="black" />
<rect x="480" y="0" width="16" height="16" fill="black" />
<rect x="496" y="0" width="16" height="16" fill="black" />
<rect x="512" y="0" width="16" height="16" fill="black" />
<rect x="528" y="0" width="16" height="16" fill="black" />
<rect x="480" y="16" width="16" height="16" fill="black" />
<rect x="480" y="32" width="16" height="16" fill="black" />
<rect x="496" y="32" width="16" height="16" fill="black" />
<rect x="512" y="32" width="16" height="16" fill="black" />
<rect x="480" y="48" width="16" height="16" fill="black" />
<rect x="480" y="64" width="16" height="16" fill="black" />
<rect x="496" y="64" width="16" height="16" fill="black" />
<rect x="512" y="64" width="16" height="16" fill="black" />
<rect x="528" y="64" width="16" height="16" fill="black" />
<rect x="576" y="0" width="16" height="16" fill="black" />
<rect x="592" y="0" width="16" height="16" fill="black" />
<rect x="560" y="16" width="16" height="16" fill="black" />
<rect x="560" y="32" width="16" height="16" fill="black" />
<rect x="560" y="48" width="16" height="16" fill="black" />
<rect x="576" y="64" width="16" height="16" fill="black" />
<rect x="592" y="64" width="16" height="16" fill="black" />
</svg>

After

Width:  |  Height:  |  Size: 5.1 KiB

+3 -2
View File
@@ -11,10 +11,11 @@ if (existsSync('dist')) {
rmSync('dist', { recursive: true, force: true });
}
// Run TypeScript compiler
// Run TypeScript compiler (use local version explicitly)
console.log('Compiling TypeScript...');
try {
execSync('tsc', { stdio: 'inherit' });
execSync('./node_modules/.bin/tsc -v', { stdio: 'inherit' });
execSync('./node_modules/.bin/tsc', { stdio: 'inherit' });
console.log('\n✅ Build completed successfully!');
} catch (error) {
console.error('\n❌ Build failed!');
@@ -1,19 +0,0 @@
# Add Status Command to OpenSpec CLI
## Why
Developers need to know which changes have all tasks completed and are ready to archive.
## What Changes
- Add `openspec status` command that scans the changes/ directory
- Parse each tasks.md file to count `[x]` (complete) and `[ ]` (incomplete) tasks
- Display each change with its completion status (e.g., "auth-feature: 5/5" or "auth-feature: ✓")
- Skip the archive/ subdirectory
## Impact
- Affected specs: New capability `cli-status` will be added
- Affected code:
- `src/cli/index.ts` - Add status command
- `src/core/status.ts` - New file with simple scanning and parsing logic (~50 lines)
@@ -1,58 +0,0 @@
# CLI Status Command Specification
## Purpose
The status command shows which OpenSpec changes are ready to archive by displaying task completion status for each change.
## Command Interface
```bash
# Show status of all changes
openspec status
```
## Behavior
WHEN the status command runs:
1. Scan the `openspec/changes/` directory
2. Skip the `archive/` subdirectory
3. For each change directory with a `tasks.md` file:
- Count tasks marked with `[x]` (case-insensitive)
- Count tasks marked with `[ ]`
- Display the change name and completion status
## Output Format
```
add-auth-feature: 15/15
fix-payment-bug: 8/8
refactor-api: 3/10
update-docs: 0/5
```
Or with checkmark for fully complete:
```
add-auth-feature: ✓
fix-payment-bug: ✓
refactor-api: 3/10
update-docs: 0/5
```
## Task Detection
The command recognizes these patterns as tasks:
- `- [ ]` Incomplete task
- `- [x]` Complete task (lowercase)
- `- [X]` Complete task (uppercase)
## Error Handling
- If no `tasks.md` exists, skip that change
- If `tasks.md` is empty or has no tasks, skip that change
- Continue scanning even if individual files have errors
## Exit Codes
- `0`: Success - status displayed
- `1`: Error - unable to scan changes directory
@@ -1,8 +0,0 @@
# Implementation Tasks for Status Command
## Core Implementation
- [ ] Add status command to `src/cli/index.ts`
- [ ] Create `src/core/status.ts` with directory scanning logic
- [ ] Parse tasks.md files to count `[x]` and `[ ]` patterns
- [ ] Display each change with completion status (name: complete/total)
- [ ] Skip the archive/ subdirectory when scanning
+362 -387
View File
@@ -1,472 +1,447 @@
# 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
## TL;DR Quick Checklist
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
- Search existing work: `openspec spec list --long`, `openspec list` (use `rg` only for full-text search)
- Decide scope: new capability vs modify existing capability
- Pick a unique `change-id`: kebab-case, verb-led (`add-`, `update-`, `remove-`, `refactor-`)
- Scaffold: `proposal.md`, `tasks.md`, `design.md` (only if needed), and delta specs per affected capability
- Write deltas: use `## ADDED|MODIFIED|REMOVED|RENAMED Requirements`; include at least one `#### Scenario:` per requirement
- Validate: `openspec validate [change-id] --strict` and fix issues
- Request approval: Do not start implementation until proposal is approved
## Start Simple
## Three-Stage Workflow
**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 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
**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
Triggers (examples):
- "Help me create a change proposal"
- "Help me plan a change"
- "Help me create a proposal"
- "I want to create a spec proposal"
- "I want to create a spec"
When triggered, document the specific justification in your change proposal.
Loose matching guidance:
- Contains one of: `proposal`, `change`, `spec`
- With one of: `create`, `plan`, `make`, `start`, `help`
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
6. **Validate strictly** - Run `openspec validate [change] --strict` and address issues
7. **Approval gate** - Do not start implementation until the proposal is reviewed and approved
### 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
- If request is ambiguous, ask 1–2 clarifying questions before scaffolding
### Search Guidance
- Enumerate specs: `openspec spec list --long` (or `--json` for scripts)
- Enumerate changes: `openspec list` (or `openspec change list --json` - deprecated but available)
- Show details:
- Spec: `openspec show <spec-id> --type spec` (use `--json` for filters)
- Change: `openspec show <change-id> --json --deltas-only`
- Full-text search (use ripgrep): `rg -n "Requirement:|Scenario:" openspec/specs`
## 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-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/ # Future state of affected specs
│ │ ├── design.md # Technical decisions (optional; see criteria)
│ │ └── specs/ # Delta changes
│ │ └── [capability]/
│ │ └── spec.md # Clean markdown (no diff syntax)
│ └── archive/ # Completed changes (dated)
│ │ └── spec.md # ADDED/MODIFIED/REMOVED
│ └── archive/ # Completed changes
```
### Capability Organization
## Creating Change Proposals
**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
### Decision Tree
Examples:
```
✅ GOOD: user-auth, user-sessions, payment-capture, payment-refunds
❌ BAD: users, payments, core, misc
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)
```
## Key Behavioral Rules
### Proposal Structure
### 1. Always Start by Reading
1. **Create directory:** `changes/[change-id]/` (kebab-case, verb-led, unique)
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. Creating a Change Proposal
When a user requests a significant change:
```bash
# 1. Create the change directory
openspec/changes/[descriptive-name]/
# 2. Generate proposal.md with all context
2. **Write proposal.md:**
```markdown
## Why
[1-2 sentences on the problem/opportunity]
[1-2 sentences on problem/opportunity]
## What Changes
[Bullet list of changes, including breaking changes]
## What Changes
- [Bullet list of changes]
- [Mark breaking changes with **BREAKING**]
## Impact
- Affected specs: [list capabilities that will change]
- Affected code: [list key files/systems]
# 3. Create future state specs for ALL affected capabilities
# - Store complete spec files as they will exist after the change
# - Use clean markdown without diff syntax (+/- prefixes)
# - Include all formatting and structure of the final intended state
specs/
└── [capability]/
└── spec.md
# 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]
- Affected specs: [list capabilities]
- Affected code: [key files/systems]
```
### 4. The Change Lifecycle
1. **Propose** → Create change directory with all 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** → Sync specs/ with new reality (IF the change affects system capabilities)
6. **Archive** → Move to `changes/archive/YYYY-MM-DD-[name]/`
### 5. Implementing Changes
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
**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
### 6. Updating Specs and Archiving After Deployment
**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`
This ensures changes are only archived when truly complete and deployed.
### 7. Types of Changes That Don't Require Specs
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
For these changes:
1. Implement → Deploy → Mark tasks complete → Archive
2. Skip the "Update Specs" step entirely
### What Deserves a Spec?
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?
If NO to all → No spec needed (likely just tooling/infrastructure)
## Understanding Specs vs Code
### Specs Document WHAT and WHY
3. **Create spec deltas:** `specs/[capability]/spec.md`
```markdown
# Authentication Spec
## ADDED Requirements
### Requirement: New Feature
The system SHALL provide...
Users SHALL authenticate with email and password.
#### Scenario: Success case
- **WHEN** user performs action
- **THEN** expected result
WHEN credentials are valid THEN issue JWT token.
WHEN credentials are invalid THEN return generic error.
## MODIFIED Requirements
### Requirement: Existing Feature
[Complete modified requirement]
WHY: Prevent user enumeration attacks.
## REMOVED Requirements
### Requirement: Old Feature
**Reason**: [Why removing]
**Migration**: [How to handle]
```
If multiple capabilities are affected, create multiple delta files under `changes/[change-id]/specs/<capability>/spec.md`—one per capability.
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
```
### Code Documents HOW
```javascript
// Implementation details
const user = await db.users.findOne({ email });
const valid = await bcrypt.compare(password, user.hashedPassword);
5. **Create design.md when needed:**
Create `design.md` if any of the following apply; otherwise omit it:
- Cross-cutting change (multiple services/modules) or a new architectural pattern
- New external dependency or significant data model changes
- Security, performance, or migration complexity
- Ambiguity that benefits from technical decisions before coding
Minimal `design.md` skeleton:
```markdown
## Context
[Background, constraints, stakeholders]
## Goals / Non-Goals
- Goals: [...]
- Non-Goals: [...]
## Decisions
- Decision: [What and why]
- Alternatives considered: [Options + rationale]
## Risks / Trade-offs
- [Risk] → Mitigation
## Migration Plan
[Steps, rollback]
## Open Questions
- [...]
```
**Key Distinction**: Specs capture intent, constraints, and decisions that aren't obvious from code.
## Spec File Format
## Common Scenarios
### Critical: Scenario Formatting
### 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
4. Wait for approval before implementing
**CORRECT** (use #### headers):
```markdown
#### Scenario: User login success
- **WHEN** valid credentials provided
- **THEN** return JWT token
```
### 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)
**WRONG** (don't use bullets or bold):
```markdown
- **Scenario: User login** ❌
**Scenario**: User login ❌
### Scenario: User login ❌
```
### Infrastructure Setup
```
User: "Initialize TypeScript project"
Every requirement MUST have at least one scenario.
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)
### Requirement Wording
- Use SHALL/MUST for normative requirements (avoid should/may unless intentionally non-normative)
### 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.
#### When to use ADDED vs MODIFIED
- ADDED: Introduces a new capability or sub-capability that can stand alone as a requirement. Prefer ADDED when the change is orthogonal (e.g., adding "Slash Command Configuration") rather than altering the semantics of an existing requirement.
- MODIFIED: Changes the behavior, scope, or acceptance criteria of an existing requirement. Always paste the full, updated requirement content (header + all scenarios). The archiver will replace the entire requirement with what you provide here; partial deltas will drop previous details.
- RENAMED: Use when only the name changes. If you also change behavior, use RENAMED (name) plus MODIFIED (content) referencing the new name.
Common pitfall: Using MODIFIED to add a new concern without including the previous text. This causes loss of detail at archive time. If you aren’t explicitly changing the existing requirement, add a new requirement under ADDED instead.
Authoring a MODIFIED requirement correctly:
1) Locate the existing requirement in `openspec/specs/<capability>/spec.md`.
2) Copy the entire requirement block (from `### Requirement: ...` through its scenarios).
3) Paste it under `## MODIFIED Requirements` and edit to reflect the new behavior.
4) Ensure the header text matches exactly (whitespace-insensitive) and keep at least one `#### Scenario:`.
Example for RENAMED:
```markdown
## RENAMED Requirements
- FROM: `### Requirement: Login`
- TO: `### Requirement: User Authentication`
```
## Summary Workflow
## Troubleshooting
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
### Common Errors
## PR Workflow Examples
**"Change must have at least one delta"**
- Check `changes/[name]/specs/` exists with .md files
- Verify files have operation prefixes (## ADDED Requirements)
### Single Developer, Simple Change
```
PR #1: Implementation
- Implement all tasks
- Update tasks.md marking items complete
- Get merged and deployed
**"Requirement must have at least one scenario"**
- Check scenarios use `#### Scenario:` format (4 hashtags)
- Don't use bullet points or bold for scenario headers
PR #2: Archive (after deployment)
- Move changes/feature-x/ → changes/archive/2025-01-15-feature-x/
- Update specs if needed
**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
```
### Multiple Developers, Complex Change
```
PR #1: Alice implements auth components
- Complete tasks 1.1, 1.2, 1.3
- Update tasks.md marking these complete
## Happy Path Script
PR #2: Bob implements UI components
- Complete tasks 2.1, 2.2
- Update tasks.md marking these complete
```bash
# 1) Explore current state
openspec spec list --long
openspec list
# Optional full-text search:
# rg -n "Requirement:|Scenario:" openspec/specs
# rg -n "^#|Requirement:" openspec/changes
PR #3: Alice fixes integration issues
- Complete remaining task 1.4
- Update tasks.md
# 2) Choose change id and scaffold
CHANGE=add-two-factor-auth
mkdir -p openspec/changes/$CHANGE/{specs/auth}
printf "## Why\n...\n\n## What Changes\n- ...\n\n## Impact\n- ...\n" > openspec/changes/$CHANGE/proposal.md
printf "## 1. Implementation\n- [ ] 1.1 ...\n" > openspec/changes/$CHANGE/tasks.md
[Deploy all changes]
# 3) Add deltas (example)
cat > openspec/changes/$CHANGE/specs/auth/spec.md << 'EOF'
## ADDED Requirements
### Requirement: Two-Factor Authentication
Users MUST provide a second factor during login.
PR #4: Archive
- Move to archive with deployment date
- Update specs to reflect new auth flow
#### Scenario: OTP required
- **WHEN** valid credentials are provided
- **THEN** an OTP challenge is required
EOF
# 4) Validate
openspec validate $CHANGE --strict
```
### 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
## Multi-Capability Example
## 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
openspec/changes/add-2fa-notify/
├── proposal.md
├── tasks.md
└── specs/
├── auth/
│ └── spec.md # ADDED: Two-Factor Authentication
└── notifications/
└── spec.md # ADDED: OTP email notification
```
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)?
auth/spec.md
```markdown
## ADDED Requirements
### Requirement: Two-Factor Authentication
...
```
### 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..."
notifications/spec.md
```markdown
## ADDED Requirements
### Requirement: OTP Email Notification
...
```
### When No Specs Exist
Treat current code as implicit spec. Your proposal should document current state AND proposed changes.
## Best Practices
### When in Doubt
Default to creating a proposal. It's easier to skip an unnecessary proposal than fix an undocumented change.
### Simplicity First
- Default to <100 lines of new code
- Single-file implementations until proven insufficient
- Avoid frameworks without clear justification
- Choose boring, proven patterns
### AI Workflow Adaptations
### 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
Task tracking with OpenSpec:
- Track exploration tasks separately from implementation
- Document proposal creation steps as you go
- Keep implementation tasks separate until proposal approved
### Clear References
- Use `file.ts:42` format for code locations
- Reference specs as `specs/auth/spec.md`
- Link related changes and PRs
Parallel operations encouraged:
- Read multiple specs simultaneously
- Check multiple pending changes at once
- Batch related searches for efficiency
### Capability Naming
- Use verb-noun: `user-auth`, `payment-capture`
- Single purpose per capability
- 10-minute understandability rule
- Split if description needs "AND"
Progress communication:
- "Exploring codebase to understand scope..."
- "Creating proposal based on findings..."
- "Implementing approved changes..."
### Change ID Naming
- Use kebab-case, short and descriptive: `add-two-factor-auth`
- Prefer verb-led prefixes: `add-`, `update-`, `remove-`, `refactor-`
- Ensure uniqueness; if taken, append `-2`, `-3`, etc.
### 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
## Tool Selection Guide
## Edge Case Handling
| 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 |
### Multi-Capability Changes
Create ONE proposal that:
- Lists all affected capabilities
- Shows changes per capability
- Has unified task list
- Gets approved as a whole
## Error Recovery
### 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
### Change Conflicts
1. Run `openspec list` to see active changes
2. Check for overlapping specs
3. Coordinate with change owners
4. Consider combining proposals
### 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
### Validation Failures
1. Run with `--strict` flag
2. Check JSON output for details
3. Verify spec file format
4. Ensure scenarios properly formatted
### Pure Refactoring
No proposal needed for:
- Code formatting/style
- Internal refactoring (same API)
- Performance optimization (same behavior)
- Adding types to untyped code
### Missing Context
1. Read project.md first
2. Check related specs
3. Review recent archives
4. Ask for clarification
Proposal REQUIRED for:
- API changes (even if compatible)
- Database schema changes
- Architecture changes
- New dependencies
## Quick Reference
### Observability Additions
No proposal needed for:
- Adding log statements
- New metrics/traces
- Debugging additions
- Error tracking
### Stage Indicators
- `changes/` - Proposed, not yet built
- `specs/` - Built and deployed
- `archive/` - Completed changes
Proposal REQUIRED if:
- Changes log format/structure
- Adds new monitoring service
- Changes what's logged (privacy)
### File Purposes
- `proposal.md` - Why and what
- `tasks.md` - Implementation steps
- `design.md` - Technical decisions
- `spec.md` - Requirements and behavior
## Remember
### 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
```
- 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.
+68
View File
@@ -0,0 +1,68 @@
# Implementation Order and Dependencies
## Required Implementation Sequence
The following changes must be implemented in this specific order due to dependencies:
### Phase 1: Foundation
**1. add-zod-validation** (No dependencies)
- Creates all core schemas (RequirementSchema, ScenarioSchema, SpecSchema, ChangeSchema, DeltaSchema)
- Implements markdown parser utilities
- Implements validation infrastructure and rules
- Establishes validation patterns used by all commands
- Must be completed first
### Phase 2: Change Commands
**2. add-change-commands** (Depends on: add-zod-validation)
- Imports ChangeSchema and DeltaSchema from zod validation
- Reuses markdown parsing utilities
- Implements change command with built-in validation
- Uses validation infrastructure for change validate subcommand
- Cannot start until schemas and validation exist
### Phase 3: Spec Commands
**3. add-spec-commands** (Depends on: add-zod-validation, add-change-commands)
- Imports RequirementSchema, ScenarioSchema, SpecSchema from zod validation
- Reuses markdown parsing utilities
- Implements spec command with built-in validation
- Uses validation infrastructure for spec validate subcommand
- Builds on patterns established by change commands
## Dependency Graph
```
add-zod-validation
↓
add-change-commands
↓
add-spec-commands
```
## Key Dependencies
### Shared Code Dependencies
1. **Schemas**: All schemas created in add-zod-validation, used by both command implementations
2. **Validation**: Infrastructure created in add-zod-validation, integrated into both commands
3. **Parsers**: Markdown parsing utilities created in add-zod-validation, used by both commands
### File Dependencies
- `src/core/schemas/*.schema.ts` (created by add-zod-validation) → imported by both commands
- `src/core/validation/validator.ts` (created by add-zod-validation) → used by both commands
- `src/core/parsers/markdown-parser.ts` (created by add-zod-validation) → used by both commands
## Implementation Notes
### For Developers
1. Complete each phase fully before moving to the next
2. Run tests after each phase to ensure stability
3. The legacy `list` command remains functional throughout
### For CI/CD
1. Each change can be validated independently
2. Integration tests should run after each phase
3. Full system tests required after Phase 3
### Parallel Work Opportunities
Within each phase, the following can be done in parallel:
- **Phase 1**: Schema design, validation rules, and parser implementation
- **Phase 2**: Change command features and legacy compatibility work
- **Phase 3**: Spec command features and final integration
@@ -1,26 +0,0 @@
# Implementation Tasks
## 1. Core Implementation
- [ ] 1.1 Create `src/core/list.ts` with list logic
- [ ] 1.1.1 Implement directory scanning (exclude archive/)
- [ ] 1.1.2 Implement task counting from tasks.md files
- [ ] 1.1.3 Format output as simple table
- [ ] 1.2 Add list command to CLI in `src/cli/index.ts`
- [ ] 1.2.1 Register `openspec list` command
- [ ] 1.2.2 Connect to list.ts implementation
## 2. Error Handling
- [ ] 2.1 Handle missing openspec/changes/ directory
- [ ] 2.2 Handle changes without tasks.md files
- [ ] 2.3 Handle empty changes directory
## 3. Testing
- [ ] 3.1 Add tests for list functionality
- [ ] 3.1.1 Test with multiple changes
- [ ] 3.1.2 Test with completed changes
- [ ] 3.1.3 Test with no changes
- [ ] 3.1.4 Test error conditions
## 4. Documentation
- [ ] 4.1 Update CLI help text with list command
- [ ] 4.2 Add list command to README if applicable
@@ -1,15 +0,0 @@
# Add @requirement Markers for Requirement Identification
## Why
Specs contain WHEN/THEN patterns that define system requirements, but extracting these programmatically requires brittle regex parsing that may miss edge cases or break with formatting changes.
## What Changes
- Define @requirement marker convention for identifying key requirements in specs
- Each marker includes a brief identifier (e.g., @requirement user-register)
- Markers appear directly before their WHEN/THEN blocks
- Document convention in openspec-conventions spec
## Impact
- Affected specs: openspec-conventions (new)
- Affected code: None initially - enables future tooling
- Breaking changes: None - additive convention only
@@ -1,24 +0,0 @@
# Implementation Tasks
## 1. Define Convention
- [ ] 1.1 Document @requirement marker syntax
- [ ] 1.2 Define identifier naming guidelines
- [ ] 1.3 Specify marker placement rules
- [ ] 1.4 Add examples of proper usage
## 2. Create Specification
- [ ] 2.1 Write openspec-conventions spec
- [ ] 2.2 Include requirement marker section
- [ ] 2.3 Add good and bad examples
- [ ] 2.4 Document edge cases
## 3. Update Existing Specs
- [ ] 3.1 Add @requirement markers to cli-init spec
- [ ] 3.2 Add @requirement markers to cli-update spec
- [ ] 3.3 Add @requirement markers to cli-view spec
- [ ] 3.4 Review and update any other existing specs
## 4. Documentation
- [ ] 4.1 Update README with marker convention
- [ ] 4.2 Add marker usage to CLAUDE.md
- [ ] 4.3 Create examples for AI assistants
@@ -0,0 +1,119 @@
# Add Slash Command Support for Coding Agents
## Summary
- Enable OpenSpec to generate and update custom slash commands for supported coding agents (Claude Code and Cursor).
- Provide three slash commands aligned with OpenSpec's workflow: proposal (start a change proposal), apply (implement), and archive.
- Share slash command templating between agents to make future extensions simple.
## Motivation
Developers use different coding agents and editors. Having consistent slash commands across tools for the OpenSpec workflow reduces friction and ensures a standard way to trigger the workflow. Supporting both Claude Code and Cursor now lays a foundation for future agents that introduce slash command features.
## Proposal
1. During `openspec init`, when a user selects a supported tool, generate slash command configuration for three OpenSpec workflow stages:
- Claude (namespaced): `/openspec/proposal`, `/openspec/apply`, `/openspec/archive`.
- Cursor (flat, prefixed): `/openspec-proposal`, `/openspec-apply`, `/openspec-archive`.
- Semantics:
- Create – scaffold a change (ID, `proposal.md`, `tasks.md`, delta specs); validate strictly.
- Apply – implement an approved change; complete tasks; validate strictly.
- Archive – archive after deployment; update specs if needed.
- Each command file MUST embed concise, step-by-step instructions sourced from `openspec/README.md` (see Template Content section).
2. Store slash command files per tool:
- Claude Code: `.claude/commands/openspec/{proposal,apply,archive}.md`
- Cursor: `.cursor/commands/{openspec-proposal,openspec-apply,openspec-archive}.md`
- Ensure nested directories are created.
3. Command file format and metadata:
- Use Markdown with optional YAML frontmatter for tool metadata (name/title, description, category/tags) when supported by the tool.
- Place OpenSpec markers around the body only, never inside frontmatter.
- Keep the visible slash name, file name, and any frontmatter `name`/`id` consistently aligned (e.g., `proposal`, `openspec-proposal`).
- Namespacing: categorize these under “OpenSpec” and prefer unique IDs (e.g., `openspec-proposal`) to avoid collisions.
4. Centralize templates: define command bodies once and reuse across tools; apply minimal per-tool wrappers (frontmatter, categories, filenames).
5. During `openspec update`, refresh only existing slash command files (per-file basis) within markers; do not create missing files or new tools.
## Design Ideas
- Introduce `SlashCommandConfigurator` to manage multiple files per tool.
- Expose targets rather than a single `configFileName` (e.g., `getTargets(): Array<{ path: string; kind: 'slash'; id: string }>`).
- Provide `generateAll(projectPath, openspecDir)` for init and `updateExisting(projectPath, openspecDir)` for update.
- Per-tool adapters add only frontmatter and pathing; bodies come from shared templates.
- Templates live in `TemplateManager` with helpers that extract concise, authoritative snippets from `openspec/README.md`.
- Update flow logs per-file results so users see exactly which slash files were refreshed.
### Marker Placement
- Markers MUST wrap only the Markdown body contents:
- Frontmatter (if present) goes first.
- Then `<!-- OPENSPEC:START -->` … body … `<!-- OPENSPEC:END -->`.
- Avoid inserting markers into the YAML block to prevent parse errors.
### Idempotency and Creation Rules
- `init`: create all three files for the chosen tool(s) once; subsequent `init` runs are no-ops for existing files.
- `update`: refresh only files that exist; skip missing ones without creating new files.
- Directory creation for `.claude/commands/openspec/` and `.cursor/commands/` is the configurator’s responsibility.
### Command Naming & UX
- Claude Code: use namespacing in the slash itself for readability and grouping: `/openspec/proposal`, `/openspec/apply`, `/openspec/archive`.
- Cursor: use flat names with an `openspec-` prefix: `/openspec-proposal`, `/openspec-apply`, `/openspec-archive`. Group via `category: OpenSpec` when supported.
- Consistency: align file names, visible slash names, and any frontmatter `id` (e.g., `id: openspec-apply`).
- Migration: do not rename existing commands during `update`; apply new naming only on `init` (or via an explicit migrate step).
## Open Questions
- Validate exact metadata/frontmatter supported by each tool version; if unsupported, omit frontmatter and ship Markdown body only.
- Confirm the final Cursor command file location for the targeted versions; fall back to Markdown-only if Cursor does not parse frontmatter.
- Evaluate additional commands beyond the initial three (e.g., `/show-change`, `/validate-all`) based on user demand.
## Alternatives
- Hard-code slash command text per tool (rejected: duplicates content; increases maintenance).
- Delay Cursor support until its config stabilizes (partial accept): gate Cursor behind a feature flag until verified in real environments.
## Risks
- Tool configuration formats may change, requiring updates to wrappers/frontmatter.
- Incorrect paths or categories can hide commands; add path existence checks and clear logging.
- Marker misuse (inside frontmatter) can break parsing; enforce placement rules in tests.
## Future Work
- Support additional editors/agents that expose slash command APIs.
- Allow users to customize command names and categories during `openspec init`.
- Provide a dedicated command to regenerate slash commands without running full `update`.
## File Format Examples
The following examples illustrate expected structure. If a tool does not support frontmatter, omit the YAML block and keep only the markers + body.
### Claude Code: `.claude/commands/openspec/proposal.md`
```markdown
---
name: OpenSpec: Proposal
description: Scaffold a new OpenSpec change and validate strictly.
category: OpenSpec
tags: [openspec, change]
---
<!-- OPENSPEC:START -->
...command body from shared template...
<!-- OPENSPEC:END -->
```
Slash invocation: `/openspec/proposal` (namespaced)
### Cursor: `.cursor/commands/openspec-proposal.md`
```markdown
---
name: /openspec-proposal
id: openspec-proposal
category: OpenSpec
description: Scaffold a new OpenSpec change and validate strictly.
---
<!-- OPENSPEC:START -->
...command body from shared template...
<!-- OPENSPEC:END -->
```
Slash invocation: `/openspec-proposal` (flat, prefixed)
## Template Content
Templates should be brief, actionable, and sourced from `openspec/README.md` to avoid duplication. Each command body includes:
- Guardrails: ask 1–2 clarifying questions if needed; follow minimal-complexity rules; use `pnpm` for Node projects.
- Step list tailored to the workflow stage (proposal, apply, archive), including strict validation commands.
- Pointers to `openspec show`, `openspec list`, and troubleshooting tips when validation fails.
## Testing Strategy
- Golden snapshots for generated files per tool (frontmatter + markers + body).
- Partial presence tests: if 1–2 files exist, `update` only refreshes those and does not create missing ones.
- Marker placement tests: ensure markers never appear inside frontmatter; cover missing/duplicated marker recovery behavior.
- Logging tests: `update` reports per-file updates for slash commands.
@@ -0,0 +1,15 @@
## ADDED Requirements
### Requirement: Slash Command Configuration
The init command SHALL generate slash command files for supported editors using shared templates.
#### Scenario: Generating slash commands for Claude Code
- **WHEN** the user selects Claude Code during initialization
- **THEN** create `.claude/commands/openspec/proposal.md`, `.claude/commands/openspec/apply.md`, and `.claude/commands/openspec/archive.md`
- **AND** populate each file from shared templates so command text matches other tools
- **AND** each template includes instructions for the relevant OpenSpec workflow stage
#### Scenario: Generating slash commands for Cursor
- **WHEN** the user selects Cursor during initialization
- **THEN** create `.cursor/commands/openspec-proposal.md`, `.cursor/commands/openspec-apply.md`, and `.cursor/commands/openspec-archive.md`
- **AND** populate each file from shared templates so command text matches other tools
- **AND** each template includes instructions for the relevant OpenSpec workflow stage
@@ -0,0 +1,17 @@
## ADDED Requirements
### Requirement: Slash Command Updates
The update command SHALL refresh existing slash command files for configured tools without creating new ones.
#### Scenario: Updating slash commands for Claude Code
- **WHEN** `.claude/commands/openspec/` contains `proposal.md`, `apply.md`, and `archive.md`
- **THEN** refresh each file using shared templates
- **AND** ensure templates include instructions for the relevant workflow stage
#### Scenario: Updating slash commands for Cursor
- **WHEN** `.cursor/commands/` contains `openspec-proposal.md`, `openspec-apply.md`, and `openspec-archive.md`
- **THEN** refresh each file using shared templates
- **AND** ensure templates include instructions for the relevant workflow stage
#### Scenario: Missing slash command file
- **WHEN** a tool lacks a slash command file
- **THEN** do not create a new file during update
@@ -0,0 +1,16 @@
# Implementation Tasks
## 1. Templates and Configurators
- [ ] 1.1 Create shared templates for the Proposal, Apply, and Archive commands with instructions for each workflow stage from `openspec/README.md`.
- [ ] 1.2 Implement a `SlashCommandConfigurator` base and tool-specific configurators for Claude Code and Cursor.
## 2. Claude Code Integration
- [ ] 2.1 Generate `.claude/commands/openspec/{proposal,apply,archive}.md` during `openspec init` using shared templates.
- [ ] 2.2 Update existing `.claude/commands/openspec/*` files during `openspec update`.
## 3. Cursor Integration
- [ ] 3.1 Generate `.cursor/commands/{openspec-proposal,openspec-apply,openspec-archive}.md` during `openspec init` using shared templates.
- [ ] 3.2 Update existing `.cursor/commands/*` files during `openspec update`.
## 4. Verification
- [ ] 4.1 Add tests verifying slash command files are created and updated correctly.
@@ -0,0 +1,26 @@
# Implementation Tasks
## 1. Core Implementation
- [x] 1.1 Create `src/core/list.ts` with list logic
- [x] 1.1.1 Implement directory scanning (exclude archive/)
- [x] 1.1.2 Implement task counting from tasks.md files
- [x] 1.1.3 Format output as simple table
- [x] 1.2 Add list command to CLI in `src/cli/index.ts`
- [x] 1.2.1 Register `openspec list` command
- [x] 1.2.2 Connect to list.ts implementation
## 2. Error Handling
- [x] 2.1 Handle missing openspec/changes/ directory
- [x] 2.2 Handle changes without tasks.md files
- [x] 2.3 Handle empty changes directory
## 3. Testing
- [x] 3.1 Add tests for list functionality
- [x] 3.1.1 Test with multiple changes
- [x] 3.1.2 Test with completed changes
- [x] 3.1.3 Test with no changes
- [x] 3.1.4 Test error conditions
## 4. Documentation
- [x] 4.1 Update CLI help text with list command
- [x] 4.2 Add list command to README if applicable
@@ -0,0 +1,15 @@
## Why
Need a command to archive completed changes to the archive folder with proper date prefixing, following OpenSpec conventions. Currently changes must be manually moved and renamed.
## What Changes
- Add new `archive` command to CLI that moves changes to `changes/archive/YYYY-MM-DD-[change-name]/`
- Check for incomplete tasks before archiving and warn user
- Allow interactive selection of change to archive
- Prevent archiving if target directory already exists
- Update main specs from the change's future state specs (copy from `changes/[name]/specs/` to `openspec/specs/`)
- Show confirmation prompt before updating specs, displaying which specs will be created/updated
- Support `--yes` flag to skip confirmations for automation
## Impact
- Affected specs: cli-archive (new)
- Affected code: src/cli/index.ts, src/core/archive.ts (new)
@@ -0,0 +1,111 @@
# CLI Archive Command Specification
## Purpose
The archive command moves completed changes from the active changes directory to the archive folder with date-based naming, following OpenSpec conventions.
## Command Syntax
```bash
openspec archive [change-name] [--yes|-y]
```
Options:
- `--yes`, `-y`: Skip confirmation prompts (for automation)
## Behavior
### Change Selection
WHEN no change-name is provided
THEN display interactive list of available changes (excluding archive/)
AND allow user to select one
WHEN change-name is provided
THEN use that change directly
AND validate it exists
### Task Completion Check
The command SHALL scan the change's tasks.md file for incomplete tasks (marked with `- [ ]`)
WHEN incomplete tasks are found
THEN display all incomplete tasks to the user
AND prompt for confirmation to continue
AND default to "No" for safety
WHEN all tasks are complete OR no tasks.md exists
THEN proceed with archiving without prompting
### Archive Process
The archive operation SHALL:
1. Create archive/ directory if it doesn't exist
2. Generate target name as `YYYY-MM-DD-[change-name]` using current date
3. Check if target directory already exists
4. Update main specs from the change's future state specs (see Spec Update Process below)
5. Move the entire change directory to the archive location
WHEN target archive already exists
THEN fail with error message
AND do not overwrite existing archive
WHEN move succeeds
THEN display success message with archived name and list of updated specs
### Spec Update Process
Before moving the change to archive, the command SHALL update main specs to reflect the deployed reality:
WHEN the change contains specs in `changes/[name]/specs/`
THEN:
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 no specs exist in the change
THEN skip the spec update step
AND proceed with archiving
### Confirmation Behavior
The spec update confirmation SHALL:
- Display a clear summary showing:
- Which specs will be created (new capabilities)
- Which specs will be updated (existing capabilities)
- The source path for each spec
- Format the confirmation prompt as:
```
The following specs will be updated:
NEW specs to be created:
- cli-archive (from changes/add-archive-command/specs/cli-archive/spec.md)
EXISTING specs to be updated:
- cli-init (from changes/update-init-command/specs/cli-init/spec.md)
Update 2 specs and archive 'add-archive-command'? [y/N]:
```
- Default to "No" for safety (require explicit "y" or "yes")
- Skip confirmation when `--yes` or `-y` flag is provided
WHEN user declines the confirmation
THEN abort the entire archive operation
AND display message: "Archive cancelled. No changes were made."
AND exit with non-zero status code
## Error Handling
SHALL handle the following error conditions:
- Missing openspec/changes/ directory
- Change not found
- Archive target already exists
- File system permissions issues
## Why These Decisions
**Interactive selection**: Reduces typing and helps users see available changes
**Task checking**: Prevents accidental archiving of incomplete work
**Date prefixing**: Maintains chronological order and prevents naming conflicts
**No overwrite**: Preserves historical archives and prevents data loss
**Spec updates before archiving**: Specs in the main directory represent current reality; when a change is deployed and archived, its future state specs become the new reality and must replace the main specs
**Confirmation for spec updates**: Provides visibility into what will change, prevents accidental overwrites, and ensures users understand the impact before specs are modified
**--yes flag for automation**: Allows CI/CD pipelines to archive without interactive prompts while maintaining safety by default for manual use
@@ -0,0 +1,44 @@
# Implementation Tasks
## 1. Core Implementation
- [ ] 1.1 Create `src/core/archive.ts` with ArchiveCommand class
- [ ] 1.1.1 Implement change selection (interactive if not provided)
- [ ] 1.1.2 Implement incomplete task checking from tasks.md
- [ ] 1.1.3 Implement confirmation prompt for incomplete tasks
- [ ] 1.1.4 Implement spec update functionality
- [ ] 1.1.4.1 Detect specs in change directory
- [ ] 1.1.4.2 Compare with existing main specs
- [ ] 1.1.4.3 Display summary of new vs updated specs
- [ ] 1.1.4.4 Show confirmation prompt for spec updates
- [ ] 1.1.4.5 Copy specs to main spec directory
- [ ] 1.1.5 Implement archive move with date prefixing
- [ ] 1.1.6 Support --yes flag to skip confirmations
## 2. CLI Integration
- [ ] 2.1 Add archive command to `src/cli/index.ts`
- [ ] 2.1.1 Import ArchiveCommand
- [ ] 2.1.2 Register command with commander
- [ ] 2.1.3 Add --yes/-y flag option
- [ ] 2.1.4 Add proper error handling
## 3. Error Handling
- [ ] 3.1 Handle missing openspec/changes/ directory
- [ ] 3.2 Handle change not found
- [ ] 3.3 Handle archive target already exists
- [ ] 3.4 Handle user cancellation
## 4. Testing
- [ ] 4.1 Test with fully completed change
- [ ] 4.2 Test with incomplete tasks (warning shown)
- [ ] 4.3 Test interactive selection mode
- [ ] 4.4 Test duplicate archive prevention
- [ ] 4.5 Test spec update functionality
- [ ] 4.5.1 Test creating new specs
- [ ] 4.5.2 Test updating existing specs
- [ ] 4.5.3 Test confirmation prompt display
- [ ] 4.5.4 Test declining confirmation (no changes made)
- [ ] 4.5.5 Test --yes flag skips confirmation
## 5. Build and Validation
- [ ] 5.1 Ensure TypeScript compilation succeeds
- [ ] 5.2 Test command execution
@@ -0,0 +1,56 @@
# Design: Change Commands
## Architecture Decisions
### Command Structure
Similar to spec commands, we use subcommands (`change show`, `change list`, `change validate`) for:
- Consistency with spec command pattern
- Clear separation of concerns
- Future extensibility for change management features
### JSON Schema for Changes
```typescript
{
version: string, // Schema version
format: "change", // Identifies as change document
sourcePath: string, // Original markdown file path
id: string, // Change identifier
title: string, // Change title
why: string, // Motivation section
whatChanges: Array<{
type: "ADDED" | "MODIFIED" | "REMOVED" | "RENAMED",
deltas: Array<{
specId: string,
description: string,
requirements?: Array<Requirement> // Only for ADDED/MODIFIED
}>
}>
}
```
**Rationale:**
- Group deltas by operation type for clearer organization
- Optional requirements field (only relevant for ADDED/MODIFIED)
- Reuse RequirementSchema from spec commands for consistency
### Delta Operations
**Four operation types:**
1. **ADDED**: New requirements added to specs
2. **MODIFIED**: Changes to existing requirements
3. **REMOVED**: Requirements being deleted
4. **RENAMED**: Spec identifier changes
**Design choice:** Explicit operation types rather than diff-based approach for:
- Human readability in markdown
- Clear intent communication
- Easier validation and tooling
### Dependency on Spec Commands
- **Shared schemas**: RequirementSchema and ScenarioSchema reused
- **Implementation order**: spec commands must be implemented first
- **Common parser utilities**: Share markdown parsing logic
### Legacy Compatibility
- Keep existing `list` command functional with deprecation warning
- Migration path: `list` → `change list` with same functionality
- Gradual transition to avoid breaking existing workflows
@@ -0,0 +1,17 @@
# Change: Add Change Commands with JSON Output
## Why
OpenSpec change proposals currently can only be viewed as markdown files, creating the same programmatic access limitations as specs. Additionally, the current `openspec list` command only lists changes, which is inconsistent with the new resource-based command structure.
## What Changes
- **cli-change:** Add new command for managing change proposals with show, list, and validate subcommands
- **cli-list:** Add deprecation notice for legacy list command to guide users to the new change list command
## Impact
- **Affected specs**: cli-list (modify to add deprecation notice)
- **Affected code**:
- src/cli/index.ts (register new command)
- src/core/list.ts (add deprecation notice)
@@ -0,0 +1,48 @@
## ADDED 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
@@ -0,0 +1,12 @@
## MODIFIED Requirements
### Requirement: Command Execution
The current `list` command behavior SHALL be preserved but marked as deprecated.
#### Scenario: Deprecation notice
- **WHEN** using the legacy `list` command
- **THEN** continue to work as before
- **AND** display deprecation notice
- **AND** suggest using `openspec change list` instead
@@ -0,0 +1,34 @@
# Implementation Tasks (Phase 2: Builds on add-zod-validation)
## 1. Command Implementation
- [x] 1.1 Create src/commands/change.ts
- [x] 1.2 Import ChangeSchema and DeltaSchema from src/core/schemas/change.schema.ts
- [x] 1.3 Import markdown parser from src/core/parsers/markdown-parser.ts
- [x] 1.4 Import ChangeValidator from src/core/validation/validator.ts
- [x] 1.5 Import JSON converter from src/core/converters/json-converter.ts
- [x] 1.6 Implement show subcommand with JSON output using existing converter
- [x] 1.7 Implement list subcommand
- [x] 1.8 Implement validate subcommand using existing ChangeValidator
- [x] 1.9 Add --requirements-only filtering option
- [x] 1.10 Add --strict mode support (leveraging existing validation infrastructure)
- [x] 1.11 Add --json flag for validation reports
## 2. Change-Specific Parser Extensions
- [x] 2.1 Create src/core/parsers/change-parser.ts (extends base markdown parser)
- [x] 2.2 Parse proposal structure (Why, What Changes sections)
- [x] 2.3 Extract ADDED/MODIFIED/REMOVED/RENAMED sections
- [x] 2.4 Parse delta operations within each section
- [x] 2.5 Add tests for change parser
## 3. Legacy Compatibility
- [x] 3.1 Update src/core/list.ts to add deprecation notice
- [x] 3.2 Ensure existing list command continues to work
- [x] 3.3 Add console warning for deprecated command usage
## 4. Integration
- [x] 4.1 Register change command in src/cli/index.ts
- [ ] 4.2 Add integration tests for all subcommands
- [x] 4.3 Test JSON output for changes
- [x] 4.4 Test legacy compatibility
- [x] 4.5 Test validation with strict mode
- [x] 4.6 Update CLI help documentation (add 'change' command to main help, document subcommands: show, list, validate)
@@ -0,0 +1,20 @@
## Why
Users frequently need to view changes and specs but must know in advance whether they're looking at a change or spec. The current subcommand structure (`change show`, `spec show`) creates friction when:
- Users want to quickly view an item without remembering its type
- Exploring the codebase requires switching between different show commands
- Show commands without arguments return errors instead of helpful guidance
## What Changes
- Add new top-level `show` command for displaying changes or specs with intelligent selection
- Support direct item display: `openspec show <item>` with automatic type detection
- Interactive selection when no arguments provided
- Enhance existing `change show` and `spec show` to support interactive selection (backwards compatibility)
- Maintain all existing format options (--json, --deltas-only, --requirements, etc.)
## Impact
- New specs to create: cli-show
- Specs to enhance: cli-change, cli-spec (for backwards compatibility)
- Affected code: src/cli/index.ts, src/commands/show.ts (new), src/commands/spec.ts, src/commands/change.ts
@@ -0,0 +1,23 @@
# CLI Change Command Spec
## ADDED Requirements
### 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`
@@ -0,0 +1,83 @@
# CLI Show Command Spec
## ADDED 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
@@ -0,0 +1,23 @@
# CLI Spec Command Spec
## ADDED 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
@@ -0,0 +1,142 @@
# Implementation Tasks — Add Interactive Show Command
## Goals
- Add a top-level `show` command with intelligent selection and type detection.
- Add interactive selection to `change show` and `spec show` when no ID is provided.
- Preserve raw-first output behavior and existing JSON formats/filters.
- Respect `--no-interactive` and `OPEN_SPEC_INTERACTIVE=0` consistently.
---
## 1) CLI wiring
- [x] In `src/cli/index.ts` add a top-level command: `program.command('show [item-name]')`
- Options:
- `--json`
- `--type <type>` where `<type>` is `change|spec`
- `--no-interactive`
- Allow passing-through type-specific flags using `.allowUnknownOption(true)` so the top-level can forward flags to the underlying type handler.
- Action: instantiate `new ShowCommand().execute(itemName, options)`.
- [x] Update `change show` subcommand to accept `--no-interactive` and pass it to `ChangeCommand.show(...)`.
- [x] Change `spec show` subcommand to accept optional ID (`show [spec-id]`), add `--no-interactive`, and pass to spec show implementation.
Acceptance:
- `openspec show` exists and prints a helpful hint in non-interactive contexts when no args.
- Unknown flags for other types do not crash parsing; they are warned/ignored appropriately.
---
## 2) New module: `src/commands/show.ts`
- [x] Create `ShowCommand` with:
- `execute(itemName?: string, options?: { json?: boolean; type?: string; noInteractive?: boolean; [k: string]: any })`
- Interactive path when `!itemName` and interactive is enabled:
- Prompt: "What would you like to show?" → `change` or `spec`.
- Load available IDs for the chosen type and prompt selection.
- Delegate to type-specific show implementation.
- Non-interactive path when `!itemName`:
- Print hint with examples:
- `openspec show <item>`
- `openspec change show`
- `openspec spec show`
- Exit with code 1.
- Direct item path when `itemName` is provided:
- Type override via `--type` takes precedence.
- Otherwise detect using `getActiveChangeIds()` and `getSpecIds()`.
- If ambiguous and no override: print error + suggestion to pass `--type` or use subcommands; exit code 1.
- If unknown: print not-found with nearest-match suggestions; exit code 1.
- On success: delegate to type-specific show.
- [x] Flag scoping and pass-through:
- Common: `--json` → forwarded to both types.
- Change-only: `--deltas-only`, `--requirements-only` (deprecated alias).
- Spec-only: `--requirements`, `--no-scenarios`, `-r/--requirement`.
- Warn and ignore irrelevant flags for the resolved type.
Acceptance:
- `openspec show <change-id> --json --deltas-only` matches `openspec change show <id> --json --deltas-only` output.
- `openspec show <spec-id> --json --requirements` matches `openspec spec show <id> --json --requirements` output.
- Ambiguity and not-found behaviors match the `cli-show` spec.
---
## 3) Refactor spec show into reusable API
- [x] In `src/commands/spec.ts`, extract show logic into an exported `SpecCommand` with `show(specId?: string, options?: { json?: boolean; requirements?: boolean; scenarios?: boolean; requirement?: string; noInteractive?: boolean })`.
- Reuse current helpers (`parseSpecFromFile`, `filterSpec`, raw-first printing).
- Keep `registerSpecCommand` but delegate to `new SpecCommand().show(...)`.
- [x] Update CLI spec show subcommand to optional arg and interactive behavior (see section 4).
Acceptance:
- Existing `spec show` tests continue to pass.
- New `SpecCommand.show` can be called from `ShowCommand`.
---
## 4) Backwards-compatible interactive in subcommands
- [x] `src/commands/change.ts` → extend `show(changeName?: string, options?: { json?: boolean; requirementsOnly?: boolean; deltasOnly?: boolean; noInteractive?: boolean })`:
- When `!changeName` and interactive enabled: prompt from `getActiveChangeIds()` and show the selected change.
- Non-interactive fallback: keep current behavior (print available IDs + `openspec change list` hint, set `process.exitCode = 1`).
- [x] `src/commands/spec.ts` → `SpecCommand.show` as above:
- When `!specId` and interactive enabled: prompt from `getSpecIds()` and show the selected spec.
- Non-interactive fallback: print the same error as existing behavior for missing `<spec-id>` and set non-zero exit code.
Acceptance:
- `openspec change show` in non-interactive prints list hint and exits non-zero.
- `openspec spec show` in non-interactive prints missing-arg error and exits non-zero.
---
## 5) Shared utilities
- [x] Extract `nearestMatches` and `levenshtein` from `src/commands/validate.ts` into `src/utils/match.ts` (exported helpers).
- [x] Update `ValidateCommand` and new `ShowCommand` to import from `utils/match`.
Acceptance:
- Build succeeds with shared helpers and no duplication.
---
## 6) Hints, warnings, and messages
- [x] Top-level `show` hint (non-interactive no-arg):
- Lines include: `openspec show <item>`, `openspec change show`, `openspec spec show`, and "Or run in an interactive terminal.".
- [x] Ambiguity message suggests `--type change|spec` and the subcommands.
- [x] Not-found suggests nearest matches (up to 5).
- [x] Irrelevant flag warnings for the resolved type (printed to stderr, no crash).
Acceptance:
- Messages match the `cli-show` spec wording intent and style used elsewhere.
---
## 7) Tests
Add tests mirroring existing patterns (non-TTY simulation via `OPEN_SPEC_INTERACTIVE=0`).
- [x] `test/commands/show.test.ts`
- Non-interactive, no arg → prints hint and exits non-zero.
- Direct item detection for change and for spec.
- Ambiguity case when both exist → error and suggestion for `--type`.
- Not-found case → nearest-match suggestions.
- Pass-through flags: change `--json --deltas-only`, spec `--json --requirements`.
- [x] `test/commands/change.interactive-show.test.ts` (non-interactive fallback)
- Ensure `openspec change show` without args prints available IDs + list hint and non-zero exit.
- [x] `test/commands/spec.interactive-show.test.ts` (non-interactive fallback)
- Ensure `openspec spec show` without args prints missing-arg error and non-zero exit.
Acceptance:
- All new tests pass after build; no regressions in existing tests.
---
## 8) Documentation (optional but recommended)
- [x] Update `openspec/README.md` usage examples to include the new `show` command with type detection and flags.
---
## 9) Non-functional checks
- [x] Run `pnpm build` and all tests (`pnpm test`).
- [x] Ensure no linter/type errors and messages are consistent with existing style.
---
## Notes on consistency
- Follow raw-first behavior for text output: passthrough file content with no formatting, mirroring current `change show` and `spec show`.
- Reuse `isInteractive` and `item-discovery` helpers for consistent prompting behavior.
- Keep JSON output shapes identical to current `ChangeCommand.show` and `spec show` outputs.
@@ -0,0 +1,13 @@
## Why
The archive command currently forces users to either accept spec updates or cancel the entire archive operation. Users need flexibility to archive changes without updating specs, either through explicit flags or by declining the confirmation prompt. This is especially important for changes that don't modify specs (like tooling, documentation, or infrastructure updates).
## What Changes
- Add new `--skip-specs` flag to the archive command that bypasses all spec update operations
- Fix confirmation behavior: when users decline spec updates interactively, proceed with archiving instead of cancelling the entire operation
- When `--skip-specs` flag is used, skip both the spec discovery and update confirmation steps entirely
- Display clear message when specs are skipped (either via flag or user choice)
- Flag can be combined with existing `--yes` flag for fully automated archiving without spec updates
## Impact
- Affected specs: cli-archive
- Affected code: src/core/archive.ts, src/cli/index.ts
@@ -0,0 +1,191 @@
# CLI Archive Command Specification
## Purpose
The archive command moves completed changes from the active changes directory to the archive folder with date-based naming, following OpenSpec conventions.
## Command Syntax
```bash
openspec archive [change-name] [--yes|-y] [--skip-specs]
```
Options:
- `--yes`, `-y`: Skip confirmation prompts (for automation)
- `--skip-specs`: Skip spec update operations entirely (for changes without spec modifications)
## Behavior
### Requirement: Change Selection
The command SHALL support both interactive and direct change selection methods.
#### Scenario: Interactive selection
- **WHEN** no change-name is provided
- **THEN** display interactive list of available changes (excluding archive/)
- **AND** allow user to select one
#### Scenario: Direct selection
- **WHEN** change-name is provided
- **THEN** use that change directly
- **AND** validate it exists
### Requirement: Task Completion Check
The command SHALL verify task completion status before archiving to prevent premature archival.
#### Scenario: Incomplete tasks found
- **WHEN** incomplete tasks are found (marked with `- [ ]`)
- **THEN** display all incomplete tasks to the user
- **AND** prompt for confirmation to continue
- **AND** default to "No" for safety
#### Scenario: All tasks complete
- **WHEN** all tasks are complete OR no tasks.md exists
- **THEN** proceed with archiving without prompting
### Requirement: Archive Process
The archive operation SHALL follow a structured process to safely move changes to the archive.
#### Scenario: Performing archive
- **WHEN** archiving a change
- **THEN** execute these steps:
1. Create archive/ directory if it doesn't exist
2. Generate target name as `YYYY-MM-DD-[change-name]` using current date
3. Check if target directory already exists
4. Update main specs from the change's future state specs unless `--skip-specs` is provided (see Spec Update Process below)
5. Move the entire change directory to the archive location
#### Scenario: Archive already exists
- **WHEN** target archive already exists
- **THEN** fail with error message
- **AND** do not overwrite existing archive
#### Scenario: Successful archive
- **WHEN** move succeeds
- **THEN** display success message with archived name and list of updated specs (if any)
### Requirement: Spec Update Process
Before moving the change to archive, the command SHALL update main specs to reflect the deployed reality unless the `--skip-specs` flag is provided.
#### Scenario: Skipping spec updates
- **WHEN** the `--skip-specs` flag is provided
- **THEN** skip all spec discovery and update operations
- **AND** proceed directly to moving the change to archive
- **AND** display message indicating specs were skipped
#### Scenario: Updating specs from change
- **WHEN** the change contains specs in `changes/[name]/specs/` AND `--skip-specs` is NOT provided
- **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
#### Scenario: No specs in change
- **WHEN** no specs exist in the change AND `--skip-specs` is NOT provided
- **THEN** skip the spec update step
- **AND** proceed with archiving
### Requirement: Confirmation Behavior
The spec update confirmation SHALL provide clear visibility into changes before they are applied.
#### Scenario: Displaying confirmation
- **WHEN** prompting for confirmation AND `--skip-specs` is NOT provided
- **THEN** display a clear summary showing:
- Which specs will be created (new capabilities)
- Which specs will be updated (existing capabilities)
- The source path for each spec
- **AND** format the confirmation prompt as:
```
The following specs will be updated:
NEW specs to be created:
- cli-archive (from changes/add-archive-command/specs/cli-archive/spec.md)
EXISTING specs to be updated:
- cli-init (from changes/update-init-command/specs/cli-init/spec.md)
Update 2 specs and archive 'add-archive-command'? [y/N]:
```
#### Scenario: Handling confirmation response
- **WHEN** waiting for user confirmation
- **THEN** default to "No" for safety (require explicit "y" or "yes")
- **AND** skip confirmation when `--yes` or `-y` flag is provided
- **AND** skip entire spec confirmation when `--skip-specs` flag is provided
#### Scenario: User declines spec update confirmation
- **WHEN** user declines the spec update confirmation
- **THEN** skip the spec update operations
- **AND** display message: "Skipping spec updates. Proceeding with archive."
- **AND** continue with the archive operation
- **AND** display success message indicating specs were not updated
## Error Handling
### Requirement: Error Conditions
The command SHALL handle various error conditions gracefully.
#### Scenario: Handling errors
- **WHEN** errors occur
- **THEN** handle the following conditions:
- Missing openspec/changes/ directory
- Change not found
- Archive target already exists
- File system permissions issues
## Why These Decisions
**Interactive selection**: Reduces typing and helps users see available changes
**Task checking**: Prevents accidental archiving of incomplete work
**Date prefixing**: Maintains chronological order and prevents naming conflicts
**No overwrite**: Preserves historical archives and prevents data loss
**Spec updates before archiving**: Specs in the main directory represent current reality; when a change is deployed and archived, its future state specs become the new reality and must replace the main specs
**Confirmation for spec updates**: Provides visibility into what will change, prevents accidental overwrites, and ensures users understand the impact before specs are modified
**Non-blocking confirmation**: Declining spec updates doesn't cancel archiving - users can review specs and choose to update them separately if needed
**--yes flag for automation**: Allows CI/CD pipelines to archive without interactive prompts while maintaining safety by default for manual use
**--skip-specs flag**: Enables archiving of changes that don't modify specs (like infrastructure, tooling, or documentation changes) without unnecessary spec update prompts or operations
## ADDED Requirements
### 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
@@ -0,0 +1,57 @@
## 1. Update Archive Command Implementation
- [x] 1.1 Add `skipSpecs` option to the archive command options interface
- [x] 1.2 Modify the execute method to skip spec operations when flag is set
- [x] 1.3 Fix confirmation behavior: when user declines spec updates, proceed with archiving instead of cancelling
- [x] 1.4 Update console output to indicate when specs are being skipped (via flag or user choice)
- [x] 1.5 Ensure archive continues after declining spec updates
## 2. Update CLI Interface
- [x] 2.1 Add `--skip-specs` flag to the archive command definition
- [x] 2.2 Pass the flag value to the archive command execute method
## 3. Update Tests
- [x] 3.1 Add test case for archiving with --skip-specs flag
- [x] 3.2 Add test case for declining spec updates but continuing with archive
- [x] 3.3 Verify that spec updates are skipped when flag is used
- [x] 3.4 Verify that archive proceeds when user declines spec updates
- [x] 3.5 Ensure existing behavior remains unchanged when flag is not used
## 4. Update Documentation
- [x] 4.1 Update the cli-archive spec to document the new --skip-specs flag
- [x] 4.2 Document the new behavior when declining spec updates interactively
## Implementation Notes
### Key Design Decisions
1. **Non-blocking Confirmation Behavior**: When users decline spec updates interactively, the archive operation continues rather than cancelling entirely. This was a critical UX improvement because:
- Users may want to review specs separately before updating them
- Archiving work shouldn't be blocked by spec review decisions
- Maintains flexibility in the deployment workflow
2. **Flag Naming Convention**: Chose `--skip-specs` for clarity and consistency:
- Clearly indicates the action (skipping) and target (specs)
- Follows kebab-case convention for CLI flags
- Converts naturally to `skipSpecs` camelCase in code
3. **Console Messaging Strategy**: Added explicit messages for all spec-skipping scenarios:
- When flag is used: "Skipping spec updates (--skip-specs flag provided)."
- When user declines: "Skipping spec updates. Proceeding with archive."
- Ensures users always understand what's happening with their specs
4. **Test Coverage Approach**: Created separate test cases for:
- Flag-based skipping (explicit user choice via CLI)
- Interactive declining (runtime user decision)
- Both verify the same outcome but test different code paths
### Use Cases Addressed
- **Infrastructure Changes**: Changes to build tools, CI/CD, dependencies
- **Documentation Updates**: README updates, comment improvements
- **Tooling Modifications**: Developer tools, scripts, configuration files
- **Refactoring**: Code improvements that don't change functionality/specs
### Future Considerations
- Could potentially auto-detect when changes don't include specs and suggest using the flag
- May want to track which archives skipped spec updates for audit purposes
@@ -0,0 +1,45 @@
# Design: Spec Commands
## Architecture Decisions
### Command Hierarchy
We chose a subcommand pattern (`spec show`, `spec list`, `spec validate`) to:
- Group related functionality under a common namespace
- Enable future extensibility without polluting the top-level CLI
- Maintain consistency with the planned `change` command structure
### JSON Schema Structure
The spec JSON schema follows this structure:
```typescript
{
version: string, // Schema version for compatibility
format: "spec", // Identifies this as a spec document
sourcePath: string, // Original markdown file path
id: string, // Spec identifier from filename
title: string, // Human-readable title
overview?: string, // Optional overview section
requirements: Array<{
id: string,
text: string,
scenarios: Array<{
id: string,
text: string
}>
}>
}
```
**Rationale:**
- Flat structure for requirements array (vs nested objects) for easier iteration
- Scenarios nested within requirements to maintain relationship
- Metadata fields (version, format, sourcePath) for tooling integration
### Parser Architecture
- **Markdown-first approach**: Parse markdown headings rather than custom syntax
- **Streaming parser**: Process line-by-line to handle large files efficiently
- **Strict heading hierarchy**: Enforce ##/###/#### structure for consistency
### Validation Strategy
- **Parse-time validation**: Catch structural issues during parsing
- **Schema validation**: Use Zod for runtime type checking of parsed data
- **Separate validation command**: Allow validation without full parsing/conversion
@@ -0,0 +1,19 @@
# Change: Add Spec Commands with JSON Output
## Why
Currently, OpenSpec specs can only be viewed as markdown files. This makes programmatic access difficult and prevents integration with CI/CD pipelines, external tools, and automated processing.
## What Changes
- Add new `openspec spec` command with three subcommands: `show`, `list`, and `validate`
- Implement JSON output capability for specs using heading-based parsing
- Add Zod schemas for spec structure validation
- Enable content filtering options (requirements only, no scenarios, specific requirement)
## Impact
- **Affected specs**: None (new capability)
- **Affected code**:
- src/cli/index.ts (register new command)
- package.json (add zod dependency)
@@ -0,0 +1,43 @@
## ADDED Requirements
### 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
@@ -0,0 +1,22 @@
# Implementation Tasks (Phase 3: Builds on add-zod-validation and add-change-commands)
## 1. Command Implementation
- [x] 1.1 Create src/commands/spec.ts
- [x] 1.2 Import RequirementSchema, ScenarioSchema, SpecSchema from src/core/schemas/
- [x] 1.3 Import markdown parser from src/core/parsers/markdown-parser.ts
- [x] 1.4 Import SpecValidator from src/core/validation/validator.ts
- [x] 1.5 Import JSON converter from src/core/converters/json-converter.ts
- [x] 1.6 Implement show subcommand with JSON output using existing converter
- [x] 1.7 Implement list subcommand
- [x] 1.8 Implement validate subcommand using existing SpecValidator
- [x] 1.9 Add filtering options (--requirements, --no-scenarios, -r)
- [x] 1.10 Add --strict mode support (leveraging existing validation infrastructure)
- [x] 1.11 Add --json flag for validation reports
## 2. Integration
- [x] 2.1 Register spec command in src/cli/index.ts
- [x] 2.2 Add integration tests for all subcommands
- [x] 2.3 Test JSON output validation
- [x] 2.4 Test filtering options
- [x] 2.5 Test validation with strict mode
- [x] 2.6 Update CLI help documentation (add 'spec' command to main help, document subcommands: show, list, validate)
@@ -0,0 +1,104 @@
# Design: Zod Validation Framework
## Architecture Decisions
### Validation Levels
Three-tier validation system:
1. **ERROR**: Structural issues that prevent parsing (must fix)
2. **WARNING**: Quality issues that should be addressed (recommended fix)
3. **INFO**: Suggestions for improvement (optional)
**Rationale:**
- Gradual enforcement allows teams to adopt validation incrementally
- CI/CD can fail on errors but allow warnings initially
- Info level provides guidance without blocking
### Validation Rules Hierarchy
#### Spec Validation Rules
```
ERROR level:
- Missing ## Overview or ## Requirements sections
- Invalid heading hierarchy
- Malformed requirement/scenario structure
WARNING level:
- Requirements without scenarios
- Requirements missing SHALL keyword
- Empty overview section
INFO level:
- Very long requirement text (>500 chars)
- Scenarios without Given/When/Then structure
```
#### Change Validation Rules
```
ERROR level:
- Missing ## Why or ## What Changes sections
- Invalid delta operation types
- Malformed delta structure
WARNING level:
- Why section too brief (<50 chars)
- Deltas without clear descriptions
- Missing requirements in ADDED/MODIFIED
INFO level:
- Very long why section (>1000 chars)
- Too many deltas in single change (>10)
```
### Strict Mode
- **Default**: Show all levels, fail on ERROR only
- **--strict flag**: Fail on both ERROR and WARNING
- **Use case**: Gradual quality improvement in CI/CD pipelines
### Archive Command Safety
**Problem:** Invalid specs could be archived, polluting the archive.
**Solution:**
1. Pre-archive validation (default behavior)
2. --no-validate flag with safeguards:
- Interactive confirmation prompt
- Prominent warning message
- Console logging with timestamp
- Not recommended for CI/CD usage
**Rationale:**
- Protect archive integrity by default
- Allow emergency overrides with accountability
- Clear audit trail for validation bypasses
### Validation Report Format
```json
{
"valid": boolean,
"issues": [
{
"level": "ERROR" | "WARNING" | "INFO",
"path": "requirements[0].scenarios",
"message": "Requirement must have at least one scenario",
"line": 15,
"column": 0
}
],
"summary": {
"errors": 2,
"warnings": 5,
"info": 3
}
}
```
**Benefits:**
- Machine-readable for tooling integration
- Human-friendly messages
- Line/column info for IDE integration
- Summary for quick assessment
### Implementation Strategy
1. **Zod schemas with refinements**: Built-in validation in type definitions
2. **Custom validators**: Additional business logic validation
3. **Composable rules**: Mix and match for different contexts
4. **Extensible framework**: Easy to add new rules without refactoring
@@ -0,0 +1,22 @@
# Change: Add Zod Runtime Validation
## Why
While the spec and change commands can output JSON, they currently don't perform strict runtime validation beyond basic structure checking. This can lead to invalid specs or changes being processed, silent failures when required fields are missing, and poor error messages.
## What Changes
- Enhance existing `spec validate` and `change validate` commands with strict Zod validation
- Add validation to the archive command to ensure changes are valid before applying
- Add validation to the diff command to ensure changes are well-formed
- Provide detailed validation reports in JSON format
- Add `--strict` mode that fails on warnings
## Impact
- **Affected specs**: cli-spec, cli-change, cli-archive, cli-diff
- **Affected code**:
- src/commands/spec.ts (enhance validate subcommand)
- src/commands/change.ts (enhance validate subcommand)
- src/core/archive.ts (add pre-archive validation)
- src/core/diff.ts (add validation check)
@@ -0,0 +1,18 @@
## ADDED Requirements
### 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
@@ -0,0 +1,12 @@
## ADDED Requirements
### Requirement: Diff Command Enhancement
The diff command SHALL validate change structure before displaying differences.
#### Scenario: Validate before diff
- **WHEN** executing `openspec diff change-name`
- **THEN** validate change structure
- **AND** show validation warnings if present
- **AND** continue with diff display
@@ -0,0 +1,59 @@
# Implementation Tasks (Foundation Phase)
## 1. Core Schemas
- [x] 1.1 Add zod dependency to package.json
- [x] 1.2 Create src/core/schemas/base.schema.ts with ScenarioSchema and RequirementSchema
- [x] 1.3 Create src/core/schemas/spec.schema.ts with SpecSchema
- [x] 1.4 Create src/core/schemas/change.schema.ts with DeltaSchema and ChangeSchema
- [x] 1.5 Create src/core/schemas/index.ts to export all schemas
## 2. Parser Implementation
- [x] 2.1 Create src/core/parsers/markdown-parser.ts
- [x] 2.2 Implement heading extraction (##, ###, ####)
- [x] 2.3 Implement content capture between headings
- [x] 2.4 Add tests for parser edge cases
## 3. Validation Infrastructure
- [x] 3.1 Create src/core/validation/types.ts with ValidationLevel, ValidationIssue, ValidationReport types
- [x] 3.2 Create src/core/validation/constants.ts with validation rules and thresholds
- [x] 3.3 Create src/core/validation/validator.ts with SpecValidator and ChangeValidator classes
## 4. Enhanced Validation Rules
- [x] 4.1 Add RequirementValidation refinements (must have scenarios, must contain SHALL)
- [x] 4.2 Add SpecValidation refinements (must have requirements)
- [x] 4.3 Add ChangeValidation refinements (must have deltas, why section length)
- [x] 4.4 Implement custom error messages for each rule
## 5. JSON Converter
- [x] 5.1 Create src/core/converters/json-converter.ts
- [x] 5.2 Implement spec-to-JSON conversion
- [x] 5.3 Implement change-to-JSON conversion
- [x] 5.4 Add metadata fields (version, format, sourcePath)
## 6. Archive Command Enhancement
- [x] 6.1 Add pre-archive validation check using new validators
- [x] 6.2 Add --no-validate flag with required confirmation prompt and warning message: "⚠️ WARNING: Skipping validation may archive invalid specs. Continue? (y/N)"
- [x] 6.3 Display validation errors before aborting
- [x] 6.4 Log all --no-validate usages to console with timestamp and affected files
- [x] 6.5 Add tests for validation scenarios including --no-validate confirmation flow
## 7. Diff Command Enhancement
- [x] 7.1 Add validation check before diff using new validators
- [x] 7.2 Show validation warnings (non-blocking)
- [x] 7.3 Continue with diff even if warnings present
## 8. Testing
- [x] 8.1 Unit tests for all schemas
- [x] 8.2 Unit tests for parser
- [x] 8.3 Unit tests for validation rules
- [x] 8.4 Integration tests for validation reports
- [x] 8.5 Test various invalid spec/change formats
- [x] 8.6 Test strict mode behavior
- [x] 8.7 Test pre-archive validation
- [x] 8.8 Test validation report JSON output
## 9. Documentation
- [x] 9.1 Document schema structure and validation rules (openspec/VALIDATION.md)
- [x] 9.2 Update CLI help for archive (document --no-validate flag and its warnings)
- [x] 9.3 Update CLI help for diff (document validation warnings behavior)
- [x] 9.4 Create migration guide for future command integration (openspec/MIGRATION.md)
@@ -0,0 +1,93 @@
# Adopt Delta-Based Changes for Specifications
## Why
The current approach of storing complete future states in change proposals creates a poor review experience. When reviewing changes on GitHub, reviewers see entire spec files (often 100+ lines) as "added" in green, making it impossible to identify what actually changed. With the recent structured format adoption, we now have clear section boundaries that enable a better approach: storing only additions and modifications.
## What Changes
Store only the requirements that actually change, not complete future states:
- **ADDED Requirements**: New capabilities being introduced
- **MODIFIED Requirements**: Existing requirements being changed (must match current header)
- **REMOVED Requirements**: Deprecated capabilities
- **RENAMED Requirements**: Explicit header changes (e.g., `FROM: Old Name` → `TO: New Name`)
The archive command will programmatically apply these deltas using normalized header matching (trim leading/trailing whitespace) instead of manually copying entire files.
## Impact
**Affected specs**: openspec-conventions, cli-archive, cli-diff
**Benefits**:
- GitHub diffs show only actual changes (25 lines instead of 150+)
- Reviewers immediately see what's being added, modified, or removed
- Conflicts are more apparent when two changes modify the same requirement
- Archive command can programmatically apply changes
**Format**: Delta format only - all changes must use ADDED/MODIFIED/REMOVED sections.
## Example
Instead of storing a 150-line complete future spec, store only:
```markdown
# User Authentication - Changes
## ADDED Requirements
### Requirement: OAuth Support
Users SHALL authenticate via OAuth providers including Google and GitHub.
#### Scenario: OAuth login flow
- **WHEN** user selects OAuth provider
- **THEN** redirect to provider authorization
- **AND** exchange authorization code for tokens
## MODIFIED Requirements
### Requirement: Session Management
Sessions SHALL expire after 30 minutes of inactivity.
#### Scenario: Inactive session timeout
- **WHEN** no activity for 30 minutes ← (was 60 minutes)
- **THEN** invalidate session token
- **AND** require re-authentication
## RENAMED Requirements
- FROM: `### Requirement: Basic Authentication`
- TO: `### Requirement: Email Authentication`
```
This makes reviews focused and changes explicit.
## Conflict Resolution
Git naturally detects conflicts when two changes modify the same requirement header. This is actually better than full-state storage where Git might silently merge incompatible changes.
## Decisions and Product Guidelines
To keep the archive flow lean and predictable, the following decisions apply:
- New spec creation: When a target spec does not exist, auto-generate a minimal skeleton and insert ADDED requirements only. Skeleton format:
- `# [Spec Name] Specification`
- `## Purpose` with placeholder: "TBD — created by archiving change [change-name]. Update Purpose after archive."
- `## Requirements`
- If a non-existent spec includes MODIFIED/REMOVED/RENAMED, abort with guidance to create via ADDED-only first.
- Requirement identification: Match requirements by exact header `### Requirement: [Name]` with trim-only normalization and case-sensitive comparison. Use a requirement-block extractor that preserves the exact header and captures full content (including scenarios) for both main specs and delta files.
- Application order and atomicity: Apply deltas in order RENAMED → REMOVED → MODIFIED → ADDED. Validate all operations first, apply in-memory, and write each spec once. On any validation failure, abort without writing partial results. An aggregated totals line is displayed across all specs: `Totals: + A, ~ M, - R, → N`.
- Validation matrix: Enforce that MODIFIED/REMOVED exist; ADDED do not exist; RENAMED FROM exists and TO does not; no duplicates after all operations; and no cross-section conflicts (e.g., same item in MODIFIED and REMOVED). When a rename and modify apply to the same item, MODIFIED must reference the NEW header.
- Idempotency: Keep v1 simple. Abort on precondition failures (e.g., ADDED already exists) with clear errors. Do not implement no-op detection in v1.
- Output and UX: For each spec, display operation counts using standard symbols `+ ~ - →`. Optionally include a short aggregated totals line at the end. Keep messages concise and actionable.
- Error messaging: Standardize messages as `[spec] [operation] failed for header "### Requirement: X" — reason`. On abort, explicitly state: `Aborted. No files were changed.`
- Subsections: Any subsections under a requirement (e.g., `#### Scenario: ...`) are preserved verbatim during parsing and application.
- Backward compatibility: Reject full future-state spec copies for existing specs with guidance to convert to deltas. Allow brand-new specs to be created via ADDED-only deltas using the skeleton above.
- Dry-run: Deferred for v1 to keep scope minimal.
@@ -0,0 +1,48 @@
# CLI Archive Command - Changes
## MODIFIED Requirements
### Requirement: Spec Update Process
Before moving the change to archive, the command SHALL apply delta changes to main specs to reflect the deployed reality.
#### Scenario: Applying delta changes
- **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: Validating delta changes
- **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
## ADDED Requirements
### 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
```
@@ -0,0 +1,45 @@
# CLI Diff Command - Changes
## REMOVED Requirements
### Requirement: Display Format
The diff command SHALL display unified diff output in text format.
**Reason for removal**: The standard unified diff format is replaced by requirement-level side-by-side comparison that better shows semantic changes rather than line-by-line text differences.
#### Scenario: Unified diff output (deprecated)
- **WHEN** running `openspec diff <change>`
- **THEN** show a unified text diff of files
- **AND** include `+`/`-` prefixed lines representing additions and removals
## MODIFIED Requirements
### Requirement: Diff Output
The command SHALL show a requirement-level comparison displaying only changed requirements.
#### Scenario: Side-by-side comparison of changes
- **WHEN** running `openspec diff <change>`
- **THEN** display only requirements that have changed
- **AND** show them in a side-by-side format that:
- Clearly shows the current version on the left
- Shows the future version on the right
- Indicates new requirements (not in current)
- 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.
#### Scenario: Invalid delta references
- **WHEN** delta references non-existent requirement
- **THEN** show error message with specific requirement
- **AND** continue showing other valid changes
- **AND** clearly mark failed changes in the output
@@ -0,0 +1,101 @@
# OpenSpec Conventions - Changes
## MODIFIED Requirements
### 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
@@ -0,0 +1,55 @@
# Implementation Tasks
## 1. Update Conventions
- [x] 1.1 Update openspec-conventions spec with delta-based approach
- [x] 1.2 Add Header-Based Requirement Identification
- [x] 1.3 Define ADDED/MODIFIED/REMOVED/RENAMED sections
- [x] 1.4 Document standard output symbols (+ ~ - →)
- [x] 1.5 Update openspec/README.md with delta-based conventions
- [x] 1.6 Update examples to use delta format
## 2. Update Diff Command
- [ ] 2.1 Update cli-diff spec with requirement-level comparison
- [ ] 2.2 Parse specs into requirement-level structures
- [ ] 2.3 Apply deltas to generate future state
- [ ] 2.4 Implement side-by-side comparison view (changes only)
- [ ] 2.5 Add tests for requirement-level comparison
- [ ] 2.6 Add tests for side-by-side view formatting
## 3. Update Archive Command
- [x] 3.1 Update cli-archive spec with delta processing behavior
- [x] 3.2 Implement requirement-block extractor that preserves exact headers (`### Requirement: [Name]`) and captures full content (including scenarios)
- [x] 3.3 Implement normalized header matching (trim-only, case-sensitive)
- [x] 3.4 Parse delta sections (ADDED/MODIFIED/REMOVED/RENAMED)
- [x] 3.5 New spec creation when target spec does not exist
- [x] 3.5.1 Auto-generate minimal skeleton: `# [Spec Name] Specification`, `## Purpose` placeholder, `## Requirements`
- [x] 3.5.2 Allow only ADDED operations for non-existent specs; abort if MODIFIED/REMOVED/RENAMED present
- [x] 3.6 Apply changes in order: RENAMED → REMOVED → MODIFIED → ADDED
- [x] 3.7 Validation and conflict checks
- [x] 3.7.1 MODIFIED/REMOVED requirements exist (after applying rename mappings)
- [x] 3.7.2 ADDED requirements don't already exist (consider post-rename state)
- [x] 3.7.3 RENAMED FROM headers exist; TO headers don't (including collisions with ADDED)
- [x] 3.7.4 No duplicate headers within specs after all operations
- [x] 3.7.5 Detect cross-section conflicts (e.g., same requirement in MODIFIED and REMOVED)
- [x] 3.7.6 When a rename exists, require MODIFIED to reference the NEW header
- [x] 3.8 Atomic updates
- [x] 3.8.1 Validate all deltas first; stage updates in-memory per spec
- [x] 3.8.2 Single write per spec; abort entire archive on any validation failure (no partial writes)
- [x] 3.9 Output and error messaging
- [x] 3.9.1 Display per-spec operation counts with symbols: `+` added, `~` modified, `-` removed, `→` renamed
- [x] 3.9.2 Optionally display an aggregated totals line across all specs
- [x] 3.9.3 Standardize error message format: `[spec] [operation] failed for header "### Requirement: X" — reason`; end with `Aborted. No files were changed.` on failure
- [x] 3.10 Idempotency behavior (v1): abort on precondition failures (e.g., ADDED already exists); do not implement no-op detection
- [x] 3.11 Tests
- [x] 3.11.1 Header normalization (trim-only) matching
- [x] 3.11.2 Apply in correct order (RENAMED → REMOVED → MODIFIED → ADDED)
- [x] 3.11.3 Validation edge cases (missing headers, duplicates, rename collisions, conflicting sections)
- [x] 3.11.4 Rename + modify interplay (MODIFIED uses new header)
- [x] 3.11.5 New spec creation via skeleton
- [x] 3.11.6 Multi-spec mixed operations with independent validation and write
## Notes
- Archive command is critical path - must work reliably
- All new changes must use delta format
- Header normalization: normalize(header) = trim(header)
- Diff command shows only changed requirements in side-by-side comparison
@@ -0,0 +1,19 @@
# Design: Verb–Noun CLI Structure Adoption
## Overview
We will make verb commands (`list`, `show`, `validate`, `diff`, `archive`) the primary interface and keep noun commands (`spec`, `change`) as deprecated aliases for one release.
## Decisions
1. Keep routing centralized in `src/cli/index.ts`.
2. Add `--specs`/`--changes` to `openspec list`, with `--changes` as default.
3. Show deprecation warnings for `openspec change list` and, more generally, for any `openspec change ...` and `openspec spec ...` subcommands.
4. Do not change `show`/`validate` behavior beyond help text; they already support `--type` for disambiguation.
## Backward Compatibility
All noun-based commands continue to work with clear deprecation warnings directing users to verb-first equivalents.
## Out of Scope
JSON output parity for `openspec list` across modes and `show --specs/--changes` discovery are follow-ups.
@@ -0,0 +1,67 @@
# Change: Adopt Verb–Noun CLI Structure (Deprecate Noun-Based Commands)
## Why
Most widely used CLIs (git, docker, kubectl) start with an action (verb) followed by the object (noun). This matches how users think: “do X to Y”. Using verbs as top-level commands improves clarity, discoverability, and extensibility.
## What Changes
- Promote top-level verb commands as primary entry points: `list`, `show`, `validate`, `diff`, `archive`.
- Deprecate noun-based top-level commands: `openspec spec ...` and `openspec change ...`.
- Introduce consistent noun scoping via flags where applicable (e.g., `--changes`, `--specs`) and keep smart defaults.
- Clarify disambiguation for `show` and `validate` when names collide.
### Mappings (From → To)
- **List**
- From: `openspec change list`
- To: `openspec list --changes` (default), or `openspec list --specs`
- **Show**
- From: `openspec spec show <spec-id>` / `openspec change show <change-id>`
- To: `openspec show <item-id>` with auto-detect, use `--type spec|change` if ambiguous
- **Validate**
- From: `openspec spec validate <spec-id>` / `openspec change validate <change-id>`
- To: `openspec validate <item-id> --type spec|change`, or bulk: `openspec validate --specs` / `--changes` / `--all`
### Backward Compatibility
- Keep `openspec spec` and `openspec change` available with deprecation warnings for one release cycle.
- Update help text to point users to the verb–noun alternatives.
## Impact
- **Affected specs**:
- `cli-list`: Add support for `--specs` and explicit `--changes` (default remains changes)
- `openspec-conventions`: Add explicit requirement establishing verb–noun CLI design and deprecation guidance
- **Affected code**:
- `src/cli/index.ts`: Un-deprecate top-level `list`; mark `change list` as deprecated; ensure help text and warnings align
- `src/core/list.ts`: Support listing specs via `--specs` and default to changes; shared output shape
- Optional follow-ups: tighten `show`/`validate` help and ambiguity handling
## Explicit Changes
**CLI Design**
- From: Mixed model with nouns (`spec`, `change`) and some top-level verbs; `openspec list` currently deprecated
- To: Verbs as primary: `openspec list|show|validate|diff|archive`; nouns scoped via flags or item ids; noun commands deprecated
- Reason: Align with common CLIs; improve UX; simpler mental model
- Impact: Non-breaking with deprecation period; users migrate incrementally
**Listing Behavior**
- From: `openspec change list` (primary), `openspec list` (deprecated)
- To: `openspec list` as primary, defaulting to `--changes`; add `--specs` to list specs
- Reason: Consistent verb–noun style; better discoverability
- Impact: New option; preserves existing behavior via default
## Rollout and Deprecation Policy
- Show deprecation warnings on noun-based commands for one release.
- Document new usage in `openspec/README.md` and CLI help.
- After one release, consider removing noun-based commands, or keep as thin aliases without warnings.
## Open Questions
- Should `show` also accept `--changes`/`--specs` for discovery without an id? (Out of scope here; current auto-detect and `--type` remain.)
@@ -0,0 +1,57 @@
# Delta: CLI List Command
## MODIFIED Requirements
### Requirement: Command Execution
The command SHALL scan and analyze either active changes or specs based on the selected mode.
#### 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 capabilities
- **AND** read each capability's `spec.md`
- **AND** parse requirements to compute requirement counts
### Requirement: Output Format
The command SHALL display items in a clear, readable table format with mode-appropriate progress or counts.
#### 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 of specs
- **THEN** show a table with columns:
- Spec id (directory name)
- Requirement count (e.g., "requirements 12")
### 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 directory exists or contains no capabilities
- **THEN** display: "No specs found."
### Requirement: Flags
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)
@@ -0,0 +1,23 @@
# Delta: OpenSpec Conventions — Verb–Noun CLI Design
## ADDED Requirements
### 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
@@ -0,0 +1,27 @@
# Implementation Tasks
## 1. CLI Behavior and Help
- [x] 1.1 Un-deprecate top-level `openspec list`; mark `change list` as deprecated with warning that points to `openspec list`
- [x] 1.2 Add support to list specs via `openspec list --specs` and keep `--changes` as default
- [x] 1.3 Update command descriptions and `--help` output to emphasize verb–noun pattern
- [x] 1.4 Keep `openspec spec ...` and `openspec change ...` commands working but print deprecation notices
## 2. Core List Logic
- [x] 2.1 Extend `src/core/list.ts` to accept a mode: `changes` (default) or `specs`
- [x] 2.2 Implement `specs` listing: scan `openspec/specs/*/spec.md`, compute requirement count via parser, format output consistently
- [x] 2.3 Share output structure for both modes; preserve current text table; ensure JSON parity in future change
## 3. Specs and Conventions
- [x] 3.1 Update `openspec/specs/cli-list/spec.md` to document `--specs` (and default to changes)
- [x] 3.2 Update `openspec/specs/openspec-conventions/spec.md` with a requirement for verb–noun CLI design and deprecation guidance
## 4. Tests and Docs
- [x] 4.1 Update tests: ensure `openspec list` works for changes and specs; keep `change list` tests but assert warning
- [ ] 4.2 Update README and any usage docs to show new primary commands
- [ ] 4.3 Add migration notes in repo CHANGELOG or README
## 5. Follow-ups (Optional, not in this change)
- [ ] 5.1 Consider `openspec show --specs/--changes` for discovery without ids
- [ ] 5.2 Consider JSON output for `openspec list` with `--json` for both modes
@@ -0,0 +1,20 @@
## Why
Currently, users must validate changes and specs individually by specifying each ID. This creates friction when:
- Teams want to validate all changes/specs before a release
- Developers need to ensure consistency across multiple related changes
- Users run validation commands without arguments and receive errors instead of helpful guidance
- The subcommand structure requires users to know in advance whether they're validating a change or spec
## What Changes
- Add new top-level `validate` command with intuitive flags (--all, --changes, --specs)
- Enhance existing `change validate` and `spec validate` to support interactive selection (backwards compatibility)
- Interactive selection by default when no arguments provided
- Support direct item validation: `openspec validate <item>` with automatic type detection
## Impact
- New specs to create: cli-validate
- Specs to enhance: cli-change, cli-spec (for backwards compatibility)
- Affected code: src/cli/index.ts, src/commands/validate.ts (new), src/commands/spec.ts, src/commands/change.ts
@@ -0,0 +1,22 @@
# CLI Change Command Spec
## ADDED Requirements
### 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`
@@ -0,0 +1,23 @@
# CLI Spec Command Spec
## ADDED Requirements
### 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
@@ -0,0 +1,149 @@
# CLI Validate Command Spec
## ADDED Requirements
### 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
@@ -0,0 +1,81 @@
# Implementation Tasks
## 1. Change Command: Interactive Validation Selection
- [x] 1.1 Add `--no-interactive` flag to `change validate` in `src/cli/index.ts`
- [x] 1.2 Implement interactivity gate respecting TTY and `OPEN_SPEC_INTERACTIVE=0` in `src/commands/change.ts`
- [x] 1.3 When no `[change-name]` is provided and interactivity is allowed, prompt with a list of active changes (exclude `archive/`) and validate the selected one
- [x] 1.4 Preserve current non-interactive fallback: print available change IDs and hint, set `process.exitCode = 1`
- [x] 1.5 Tests: add coverage for interactive and non-interactive flows
- Added `test/commands/change.interactive-validate.test.ts`
## 2. Spec Command: Interactive Validation Selection
- [x] 2.1 Make `spec validate` accept optional `[spec-id]` in `src/commands/spec.ts` registration
- [x] 2.2 Add `--no-interactive` flag to `spec validate`
- [x] 2.3 Implement interactivity gate respecting TTY and `OPEN_SPEC_INTERACTIVE=0`
- [x] 2.4 When no `[spec-id]` provided and interactivity allowed, prompt to select from `openspec/specs/*/spec.md` and validate the selected spec
- [x] 2.5 Preserve current non-interactive fallback when no spec-id and no interactivity: print existing error and exit code non-zero
- [x] 2.6 Tests: add coverage for interactive and non-interactive flows
- Added `test/commands/spec.interactive-validate.test.ts`
## 3. New Top-level `validate` Command
- [x] 3.1 Add `validate` command in `src/cli/index.ts`
- Options: `--all`, `--changes`, `--specs`, `--type <change|spec>`, `--strict`, `--json`, `--no-interactive`
- Usage: `openspec validate [item-name]`
- [x] 3.2 Create `src/commands/validate.ts` implementing:
- [x] 3.2.1 Interactive selector when no args (choices: All, Changes, Specs, Specific item)
- [x] 3.2.2 Non-interactive fallback with helpful hint and exit code 1
- [x] 3.2.3 Direct item validation with automatic type detection
- [x] 3.2.4 Ambiguity error when name exists as both change and spec; suggest `--type` or subcommands
- [x] 3.2.5 Unknown item handling with nearest-match suggestions
- [x] 3.2.6 Bulk validation for `--all`, `--changes`, `--specs` (exclude `openspec/changes/archive/`)
- [x] 3.2.7 Respect `--strict` and `--json` options; JSON shape per spec
- [x] 3.2.8 Exit with code 1 if any validation fails
- [x] 3.2.9 Bounded concurrency (default 4–8) for bulk validation
- [x] 3.2.10 Progress indication during bulk runs (current item, running counts)
## 4. Utilities and Shared Helpers
- [x] 4.1 Add `src/utils/interactive.ts` with `isInteractive(stdin: NodeJS.ReadStream, noInteractiveFlag?: boolean): boolean`
- Considers: `process.stdin.isTTY`, `--no-interactive`, `OPEN_SPEC_INTERACTIVE=0`
- [x] 4.2 Add `src/utils/item-discovery.ts` with:
- `getActiveChangeIds(root = process.cwd()): Promise<string[]>` (exclude `archive/`)
- `getSpecIds(root = process.cwd()): Promise<string[]>` (folders with `spec.md`)
- [ ] 4.3 Optional: `src/utils/concurrency.ts` helper for bounded parallelism
- [x] 4.4 Reuse `src/core/validation/validator.ts` for item validation
## 5. JSON Output (Bulk Validation)
- [x] 5.1 Implement JSON schema:
- `items: Array<{ id: string, type: "change"|"spec", valid: boolean, issues: Issue[], durationMs: number }>`
- `summary: { totals: { items: number, passed: number, failed: number }, byType: { change?: { items: number, passed: number, failed: number }, spec?: { items: number, passed: number, failed: number } } }`
- `version: "1.0"`
- [x] 5.2 Ensure process exit code is 1 if any `items[].valid === false`
- [x] 5.3 Tests for JSON shape (keys, types, counts) and exit code behavior
- Added `test/commands/validate.test.ts`
## 6. Progress and UX
- [x] 6.1 Use `ora` or minimal console progress to show current item and running counts
- [x] 6.2 Keep output stable in `--json` mode (no extra logs to stdout; use stderr for progress if needed)
- [x] 6.3 Ensure responsiveness with concurrency limits
## 7. Tests
- [x] 7.1 Add top-level validate tests: `test/commands/validate.test.ts`
- Includes non-interactive hint, --all JSON, --specs with concurrency, ambiguity error
- [ ] 7.2 Add unit tests for `isInteractive` and item discovery helpers
- [x] 7.3 Extend existing change/spec command tests to cover interactive `validate`
- Added `test/commands/change.interactive-validate.test.ts`, `test/commands/spec.interactive-validate.test.ts`
## 8. CLI Help and Docs
- [x] 8.1 Update command descriptions/options in `src/cli/index.ts`
- [x] 8.2 Verify help output includes `validate` command and flags
- [x] 8.3 Ensure existing specs under `openspec/changes/bulk-validation-interactive-selection/specs/*` remain satisfied
## 9. Non-functional
- [x] 9.1 Code style and types: explicit types for exported APIs; avoid `any`
- [x] 9.2 No linter errors; stable formatting; avoid unrelated refactors
- [x] 9.3 Maintain existing behavior for unaffected commands
## 10. Acceptance Criteria Mapping
- [x] AC-1: `openspec change validate` interactive selection when no arg (TTY only; respects `--no-interactive`/env) — matches cli-change spec
- [x] AC-2: `openspec spec validate` interactive selection when no arg (TTY only; respects `--no-interactive`/env) — matches cli-spec spec
- [x] AC-3: New `openspec validate` supports interactive selection, bulk/filtered validation, JSON schema, progress, concurrency, exit codes — matches cli-validate spec
@@ -0,0 +1,40 @@
# Fix Update Command Tool Selection
## Problem
The `openspec update` command currently forces the creation/update of CLAUDE.md regardless of which AI tool was selected during initialization. This violates the tool-agnostic design principle and creates confusion for users who selected different AI assistants.
Additionally, different team members may use different AI tools, so we cannot rely on a shared configuration file.
## Solution
Modify the update command to:
1. Only update AI tool configuration files that already exist
2. Never create new AI tool configuration files
3. Always update the core OpenSpec files (README.md, etc.)
## Implementation
- Remove hardcoded CLAUDE.md update from update command
- Implement file existence check before updating any AI tool config
- Update each existing AI tool config file with its appropriate markers
- No configuration file needed (avoids team conflicts)
## Success Criteria
- Update command only modifies existing AI tool configuration files
- No new AI tool files created during update
- Team members can use different AI tools without conflicts
- Existing projects continue to work (backward compatibility)
## Why
Users need predictable, tool-agnostic behavior from `openspec update`. Creating or forcing updates for AI tool files that a project does not use causes confusion and merge conflicts. Restricting updates to existing files and always updating core OpenSpec files keeps the workflow consistent for mixed-tool teams.
## What Changes
- **cli-update:** Modify update behavior to update only existing AI tool configuration files and never create new ones; always update core OpenSpec files and display an ASCII-safe success message.
## ADDED Requirements
Removed from proposal to follow conventions. See `specs/cli-update/spec.md` for the delta requirements content.
@@ -0,0 +1,23 @@
## ADDED Requirements
### 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"
@@ -0,0 +1,21 @@
# Implementation Tasks
## 1. Update Update Command
- [x] Remove hardcoded CLAUDE.md update from `src/core/update.ts`
- [x] Add logic to check for existing AI tool configuration files
- [x] Update only existing files using their appropriate configurators
- [x] Iterate through all registered configurators to check for existing files
## 2. Update Configurator Registry
- [x] Add method to get all configurators for update command
- [x] Ensure each configurator can check if its file exists
## 3. Add Tests
- [x] Test update command with only CLAUDE.md present
- [x] Test update command with no AI tool files present
- [x] Test update command with multiple AI tool files present
- [x] Test that update never creates new AI tool files
## 4. Update Documentation
- [x] Update README to clarify team-friendly behavior
- [x] Document that update only modifies existing files
@@ -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,36 @@
## Why
OpenSpec specifications lack a consistent structure that makes sections visually identifiable and programmatically parseable across different specs. This makes it harder to maintain consistency and build tooling.
## What Changes
**Specification Format Section**
- From: No formal structure requirements for specifications
- To: Structured format with `### Requirement:` and `#### Scenario:` headers
- Reason: Visual consistency and parseability across all specs
- Impact: Non-breaking - existing specs can migrate gradually
**Keyword Formatting**
- From: Inconsistent use of WHEN/THEN/AND keywords
- To: Bold keywords (**WHEN**, **THEN**, **AND**) in scenario bullets
- Reason: Improved readability and consistent visual hierarchy
- Impact: Non-breaking - formatting enhancement only
**Format Flexibility**
- From: Implicit understanding that different content needs different formats
- To: Explicit allowance for alternative formats (OpenAPI, JSON Schema, etc.)
- Reason: Address concern that not all specs fit requirement/scenario pattern
- Impact: Non-breaking - clarifies existing practice
**Migration Guidelines**
- From: No migration guidance
- To: Documented gradual migration approach
- Reason: Allows incremental adoption without disrupting existing specs
- Impact: Non-breaking - opt-in migration as specs are modified
## Impact
- Affected specs: openspec-conventions (enhancement to existing capability)
- Affected code: None initially - this is a documentation standard enhancement
- Migration: Gradual - existing specs migrate as they're modified
- Tooling: Enables future parsing tools but doesn't require them
@@ -1,5 +1,17 @@
# OpenSpec Conventions Specification
## ADDED Requirements
### 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
## 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.
@@ -36,6 +48,60 @@ openspec/
└── YYYY-MM-DD-[name]/
```
## Specification Format
### 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: Format Flexibility
The structured format SHALL be the default for behavioral specifications, but alternative formats MAY be used when more appropriate for the content type.
#### Scenario: Documenting API specifications
- **WHEN** documenting REST API endpoints or GraphQL schemas
- **THEN** OpenAPI, GraphQL SDL, or similar formats MAY be used
- **AND** the spec SHALL clearly indicate the format being used
- **AND** behavioral aspects SHALL still follow the structured format
#### Scenario: Documenting data schemas
- **WHEN** documenting data structures, database schemas, or configurations
- **THEN** JSON Schema, SQL DDL, or similar formats MAY be used
- **AND** include the structured format for behavioral rules and constraints
#### Scenario: Using simplified format
- **WHEN** documenting simple capabilities without complex scenarios
- **THEN** a simplified WHEN/THEN format without full structure MAY be used
- **AND** this should be consistent within the capability
## Change Storage Convention
### Future State Storage
@@ -110,105 +176,6 @@ A proposal is NOT required for:
- Adding tests for existing behavior
- Documentation clarifications
## Requirement Markers
### Marker Syntax
@requirement marker-syntax
WHEN writing a requirement in a spec
THEN prefix it with @requirement followed by a brief kebab-case identifier
AND place the marker on the line immediately before the WHEN statement
@requirement marker-identifier
WHEN choosing an identifier for @requirement
THEN use kebab-case (lowercase with hyphens)
AND keep it brief but descriptive (2-4 words)
AND ensure it's unique within the spec
@requirement marker-placement
WHEN adding @requirement markers to a spec
THEN place them in the ## Behavior or ## Behaviors section
AND ensure each WHEN/THEN block has exactly one marker
AND maintain a blank line after each THEN block for readability
### Examples
@requirement valid-marker-example
WHEN a spec includes properly formatted markers
THEN tools can extract and identify requirements programmatically
AND the spec remains human-readable
Example of correct usage:
```markdown
## Behavior
@requirement user-register
WHEN user registers with valid email
THEN create account and send confirmation
@requirement user-login
WHEN user logs in with correct credentials
THEN return JWT token with user data
@requirement invalid-credentials
WHEN user provides invalid credentials
THEN return 401 unauthorized error
```
@requirement invalid-marker-detection
WHEN a requirement lacks an @requirement marker
THEN tools should gracefully skip it
AND optionally warn about unmarked requirements
### Edge Cases
@requirement multiline-when-then
WHEN a WHEN or THEN clause spans multiple lines
THEN the @requirement marker still goes on the line before WHEN
AND the entire block is considered part of that requirement
@requirement multiple-then-clauses
WHEN a requirement has multiple THEN clauses using AND
THEN treat them as part of the same requirement
AND use a single @requirement marker for the entire block
@requirement nested-conditions
WHEN requirements have nested conditions or complex logic
THEN keep the @requirement marker simple
AND let the WHEN/THEN content contain the complexity
## Spec Structure
@requirement spec-file-location
WHEN creating a spec file
THEN place it in openspec/specs/[capability-name]/spec.md
AND use kebab-case for the capability name
@requirement spec-sections
WHEN structuring a spec
THEN include these sections in order:
- # [Capability Name] Specification
- ## Purpose (brief description)
- ## Behavior or ## Behaviors (with @requirement markers)
- ## Examples (optional, for complex requirements)
## Benefits of Requirement Markers
@requirement tooling-extraction
WHEN tools need to extract requirements from specs
THEN they can parse @requirement markers reliably
AND avoid complex regex patterns for WHEN/THEN extraction
@requirement requirement-counting
WHEN displaying change summaries
THEN tools can count requirements by counting @requirement markers
AND show accurate requirement counts per spec
@requirement requirement-referencing
WHEN documenting or discussing specific requirements
THEN use the @requirement identifier for clear reference
AND maintain consistency across documentation
## Why This Approach
Clean future state storage provides:
@@ -216,4 +183,10 @@ Clean future state storage provides:
- **AI-compatibility**: Standard markdown that AI tools understand
- **Simplicity**: No special parsing or processing needed
- **Tool-agnostic**: Any diff tool can show changes
- **Clear intent**: Explicit proposals document reasoning
- **Clear intent**: Explicit proposals document reasoning
The structured format adds:
- **Visual Consistency**: Requirement and Scenario prefixes make sections instantly recognizable
- **Parseability**: Consistent structure enables tooling and automation
- **Flexibility**: Alternative formats supported where appropriate
- **Gradual Adoption**: Existing specs can migrate incrementally
@@ -0,0 +1,19 @@
## 1. Update OpenSpec Conventions Spec
- [x] 1.1 Add "Specification Format" section to openspec-conventions
- [x] 1.2 Document structured format with Requirement/Scenario headers
- [x] 1.3 Define bold keyword usage (WHEN/THEN/AND) for scenarios
- [x] 1.4 Include examples demonstrating the format within the spec itself
## 2. Update Documentation
- [x] 2.1 Update the "Why This Approach" section with structured format benefits
- [x] 2.2 Ensure spec follows its own format as a demonstration
## 3. Update Existing Specs
- [x] 3.1 Update cli-init spec to use structured format in Behavior section
- [x] 3.2 Update cli-list spec to use structured format in Behavior section
- [x] 3.3 Update cli-update spec to use structured format in Behavior section
- [x] 3.4 Update cli-diff spec to use structured format in Behavior section
- [x] 3.5 Update cli-archive spec to use structured format in Behavior section
@@ -0,0 +1,38 @@
# Change: Add View Dashboard Command
## Why
Users need a quick, at-a-glance overview of their OpenSpec project status without running multiple commands. Currently, users must run `openspec list --changes` and `openspec list --specs` separately to understand the project state. A unified dashboard view would improve developer experience and provide immediate insight into project progress.
## What Changes
### Added `openspec view` Command
The new command provides an interactive dashboard displaying:
- Summary metrics (total specs, requirements, changes, task progress)
- Active changes with visual progress bars
- Completed changes
- Specifications with requirement counts
### Specifications Affected
- **cli-view** (NEW): Complete specification for the view dashboard command
## Implementation Details
### File Structure
- Created `/src/core/view.ts` implementing the `ViewCommand` class
- Registered command in `/src/cli/index.ts`
- Reuses existing utilities from `task-progress.ts` and `MarkdownParser`
### Visual Design
- Uses Unicode box drawing characters for borders
- Color coding: cyan for specs, yellow for active, green for completed
- Progress bars using filled (█) and empty (░) blocks
- Clean alignment with proper padding
### Technical Approach
- Async data fetching from changes and specs directories
- Parallel processing of specs and changes
- Error handling for missing or invalid data
- Maintains consistency with existing list command output
@@ -0,0 +1,109 @@
# CLI View Command - Changes
## ADDED Requirements
### Requirement: Dashboard Display
The system SHALL provide a `view` command that displays a dashboard overview of specs and changes.
#### Scenario: Basic dashboard display
- **WHEN** user runs `openspec view`
- **THEN** system displays a formatted dashboard with sections for summary, active changes, completed changes, and specifications
#### Scenario: No OpenSpec directory
- **WHEN** user runs `openspec view` in a directory without OpenSpec
- **THEN** system displays error message "✗ No openspec directory found"
### Requirement: Summary Section
The dashboard SHALL display a summary section with key project metrics.
#### Scenario: Complete summary display
- **WHEN** dashboard is rendered with specs and changes
- **THEN** system shows total number of specifications and requirements
- **AND** shows number of active changes in progress
- **AND** shows number of completed changes
- **AND** shows overall task progress percentage
#### Scenario: Empty project summary
- **WHEN** no specs or changes exist
- **THEN** summary shows zero counts for all metrics
### Requirement: Active Changes Display
The dashboard SHALL show active changes with visual progress indicators.
#### Scenario: Active changes with progress bars
- **WHEN** there are in-progress changes with tasks
- **THEN** system displays each change with change name left-aligned
- **AND** visual progress bar using Unicode characters
- **AND** percentage completion on the right
#### Scenario: No active changes
- **WHEN** all changes are completed or no changes exist
- **THEN** active changes section is omitted from display
### Requirement: Completed Changes Display
The dashboard SHALL list completed changes in a separate section.
#### Scenario: Completed changes listing
- **WHEN** there are completed changes (all tasks done)
- **THEN** system shows them with checkmark indicators in a dedicated section
#### Scenario: Mixed completion states
- **WHEN** some changes are complete and others active
- **THEN** system separates them into appropriate sections
### Requirement: Specifications Display
The dashboard SHALL display specifications sorted by requirement count.
#### Scenario: Specs listing with counts
- **WHEN** specifications exist in the project
- **THEN** system shows specs sorted by requirement count (descending) with count labels
#### Scenario: Specs with parsing errors
- **WHEN** a spec file cannot be parsed
- **THEN** system includes it with 0 requirement count
### Requirement: Visual Formatting
The dashboard SHALL use consistent visual formatting with colors and symbols.
#### Scenario: Color coding
- **WHEN** dashboard elements are displayed
- **THEN** system uses cyan for specification items
- **AND** yellow for active changes
- **AND** green for completed items
- **AND** dim gray for supplementary text
#### Scenario: Progress bar rendering
- **WHEN** displaying progress bars
- **THEN** system uses filled blocks (█) for completed portions and light blocks (░) for remaining
### Requirement: Error Handling
The view command SHALL handle errors gracefully.
#### Scenario: File system errors
- **WHEN** file system operations fail
- **THEN** system continues with available data and omits inaccessible items
#### Scenario: Invalid data structures
- **WHEN** specs or changes have invalid format
- **THEN** system skips invalid items and continues rendering
@@ -0,0 +1,47 @@
# Implementation Tasks
## Design Phase
- [x] Research existing list command implementation
- [x] Design dashboard layout and information architecture
- [x] Choose appropriate command verb (`view`)
- [x] Define visual elements (progress bars, colors, layout)
## Core Implementation
- [x] Create ViewCommand class in `/src/core/view.ts`
- [x] Implement getChangesData method for fetching change information
- [x] Implement getSpecsData method for fetching spec information
- [x] Implement displaySummary method for summary metrics
- [x] Add progress bar visualization with Unicode characters
- [x] Implement color coding using chalk
## Integration
- [x] Import ViewCommand in CLI index
- [x] Register `openspec view` command with commander
- [x] Add proper error handling and ora spinner integration
- [x] Ensure command appears in help documentation
## Data Processing
- [x] Reuse TaskProgress utilities for change progress
- [x] Integrate MarkdownParser for spec requirement counting
- [x] Handle async operations for file system access
- [x] Sort specifications by requirement count
## Testing and Validation
- [x] Build project successfully with new command
- [x] Test command with sample data
- [x] Verify correct requirement counts match list --specs
- [x] Test progress bar display for various completion states
- [x] Run existing test suite to ensure no regressions
- [x] Verify TypeScript compilation with no errors
## Documentation
- [x] Add command description in CLI help
- [x] Create change proposal documentation
- [x] Update README with view command example (if needed)
- [x] Add view command to user documentation (if exists)
## Polish
- [x] Ensure consistent formatting and alignment
- [x] Add helpful footer text referencing list commands
- [x] Optimize for terminal width considerations
- [x] Review and refine color choices for accessibility
@@ -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,12 @@
## Why
Validation currently errors on changes without spec deltas, even when the change is intentionally proposal-only or tooling-only. This creates false negatives and noisy CI.
## What Changes
- Make change validation scope-aware: validate only artifacts that exist.
- Only error on "No deltas found" if spec delta files exist but parse to zero deltas.
- Keep archive stricter: if specs exist but parse to zero deltas, fail; allow `--skip-specs` for tooling-only changes.
## Impact
- Affected specs: cli-validate
- Affected code: `src/commands/validate.ts`, `src/core/validation/validator.ts`
@@ -0,0 +1,25 @@
## ADDED Requirements
### Requirement: Scope-Aware Change Validation
The validator SHALL validate only artifacts that exist for a change, avoiding errors for proposal-only or tooling-only changes.
#### Scenario: Proposal-only change
- **WHEN** a change contains `proposal.md` but has no `specs/` directory or contains no `*/spec.md` files
- **THEN** validate the proposal (Why/What sections)
- **AND** do not require or validate spec deltas
#### Scenario: Delta validation when specs exist
- **WHEN** a change contains one or more `specs/<capability>/spec.md` files
- **THEN** validate delta-formatted specs with existing rules (SHALL/MUST, scenarios, duplicates, conflicts)
## MODIFIED 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 that contains `specs/` with one or more `*/spec.md` files but the parser finds zero deltas
- **THEN** show error "No deltas found" with guidance:
- Ensure `openspec/changes/{id}/specs/` has `.md` files that include delta headers
- 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 parsed deltas
@@ -0,0 +1,16 @@
## 1. Validator changes
- [ ] 1.1 Change `validateChangeDeltaSpecs` to only emit "Change must have at least one delta" when `specs/` exists and contains at least one `*/spec.md` but parsed total deltas is 0
- [ ] 1.2 Return valid (no error) when `specs/` directory is missing or has no `spec.md` files
## 2. CLI changes
- [ ] 2.1 In bulk validation, keep current behavior (call delta validator). Behavior remains correct after 1.1
- [ ] 2.2 Add a short INFO log in human-readable mode when a change has no `specs/` (optional)
## 3. Documentation
- [ ] 3.1 Update README and template: "Validation checks only existing artifacts. Proposal-only changes are valid without spec deltas."
## 4. Tests
- [ ] 4.1 Add test: proposal-only change passes validation without deltas
- [ ] 4.2 Add test: specs present but zero parsed deltas → ERROR
- [ ] 4.3 Add test: specs present with proper deltas → valid
@@ -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,25 @@
# Change: Sort Active Changes by Progress
## Problem
- The dashboard currently lists active changes in filesystem discovery order.
- Users cannot quickly spot proposals that have not started or are nearly complete.
- Inconsistent ordering between runs makes it harder to track progress when many changes exist.
## Proposal
1. Update the Active Changes list in the dashboard to sort by percentage of completion in ascending order so 0% items show first.
2. When two changes share the same completion percentage, break ties deterministically by change identifier (alphabetical).
## Benefits
- Highlights work that has not started yet, enabling quicker prioritization.
- Provides consistent ordering across machines and repeated runs.
- Keeps the dashboard compact while communicating the most important status signal.
## Risks & Mitigations
- **Risk:** Sorting logic could regress rendering when progress data is missing.
- **Mitigation:** Treat missing progress as 0% so items still surface and document behavior in tests.
- **Risk:** Additional sorting could impact performance for large change sets.
- **Mitigation:** The number of active changes is typically small; sorting a few entries is negligible.
## Success Criteria
- Dashboard output shows active changes ordered by ascending completion percentage with deterministic tie-breaking.
- Unit coverage verifying the sort when percentages vary and when ties occur.
@@ -0,0 +1,9 @@
## MODIFIED Requirements
### Requirement: Active Changes Display
The dashboard SHALL show active changes with visual progress indicators.
#### Scenario: Active changes ordered by completion percentage
- **WHEN** multiple active changes are displayed with progress information
- **THEN** list them sorted by completion percentage ascending so 0% items appear first
- **AND** treat missing progress values as 0% for ordering
- **AND** break ties by change identifier in ascending alphabetical order to keep output deterministic
@@ -0,0 +1,8 @@
# Implementation Tasks
## 1. Dashboard Sorting Logic
- [x] 1.1 Update the Active Changes rendering to sort by completion percentage ascending.
- [x] 1.2 Treat missing progress as 0% and break ties alphabetically by change identifier.
## 2. Verification
- [x] 2.1 Add tests that cover different completion percentages and tie cases to confirm deterministic ordering.
@@ -0,0 +1,29 @@
# Update Agent Instruction File Name
## Problem
The agent instructions live in `openspec/README.md`, which clashes with conventional project README usage and creates confusion for tooling and contributors.
## Solution
Rename the agent instruction file to `openspec/AGENTS.md` and update OpenSpec tooling to use the new filename:
- `openspec init` generates `AGENTS.md` instead of `README.md`
- Templates and code reference `AGENTS.md`
- Specifications and documentation are updated accordingly
## Benefits
- Clear separation from project documentation
- Consistent naming with other agent instruction files
- Simplifies tooling and project onboarding
## Implementation
- Rename instruction file and template
- Update CLI commands (`init`, `update`) to read/write `AGENTS.md`
- Adjust specs and documentation to reference the new path
## Risks
- Existing projects may still rely on `README.md`
- Tooling may miss lingering references to the old filename
## Success Metrics
- `openspec init` creates `openspec/AGENTS.md`
- `openspec update` refreshes `AGENTS.md`
- All specs reference `openspec/AGENTS.md`
@@ -0,0 +1,36 @@
## MODIFIED Requirements
### Requirement: Directory Creation
The command SHALL create the complete OpenSpec directory structure with all required directories and files.
#### Scenario: Creating OpenSpec structure
- **WHEN** `openspec init` is executed
- **THEN** create the following directory structure:
```
openspec/
├── project.md
├── AGENTS.md
├── specs/
└── changes/
└── archive/
```
### Requirement: File Generation
The command SHALL generate required template files with appropriate content for immediate use.
#### Scenario: Generating template files
- **WHEN** initializing OpenSpec
- **THEN** generate `AGENTS.md` containing complete OpenSpec instructions for AI assistants
- **AND** generate `project.md` with project context template
### Requirement: AI Tool Configuration Details
#### Scenario: Creating new CLAUDE.md
- **WHEN** CLAUDE.md does not exist
- **THEN** create new file with OpenSpec content wrapped in markers including reference to `@openspec/AGENTS.md`
### Requirement: Success Output
#### Scenario: Displaying success message
- **WHEN** initialization completes successfully
- **THEN** include prompt: "Please explain the OpenSpec workflow from openspec/AGENTS.md and how I should work with you on this project"
@@ -0,0 +1,22 @@
## MODIFIED Requirements
### Requirement: Update Behavior
The update command SHALL update OpenSpec instruction files to the latest templates in a team-friendly manner.
#### Scenario: Running update command
- **WHEN** a user runs `openspec update`
- **THEN** replace `openspec/AGENTS.md` with the latest template
### Requirement: File Handling
The update command SHALL handle file updates in a predictable and safe manner.
#### Scenario: Updating files
- **WHEN** updating files
- **THEN** completely replace `openspec/AGENTS.md` with the latest template
### 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/AGENTS.md` with the latest template
@@ -0,0 +1,27 @@
## MODIFIED Requirements
### 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
├── AGENTS.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]/
```
@@ -0,0 +1,22 @@
# Update Agent Instruction File Name - Tasks
## 1. Rename Instruction File
- [ ] Rename `openspec/README.md` to `openspec/AGENTS.md`
- [ ] Update root references to new path
## 2. Update Templates
- [ ] Rename `src/core/templates/readme-template.ts` to `agents-template.ts`
- [ ] Update exported constant from `readmeTemplate` to `agentsTemplate`
## 3. Adjust CLI Commands
- [ ] Modify `openspec init` to generate `AGENTS.md`
- [ ] Update `openspec update` to refresh `AGENTS.md`
- [ ] Ensure CLAUDE.md markers link to `@openspec/AGENTS.md`
## 4. Update Specifications
- [ ] Modify `cli-init` spec to reference `AGENTS.md`
- [ ] Modify `cli-update` spec to reference `AGENTS.md`
- [ ] Modify `openspec-conventions` spec to include `AGENTS.md` in project structure
## 5. Validation
- [ ] `pnpm test`

Some files were not shown because too many files have changed in this diff Show More