Compare commits

...
Author SHA1 Message Date
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 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
35 changed files with 1598 additions and 176 deletions
+87
View File
@@ -0,0 +1,87 @@
# OpenSpec
A specification-driven development system for maintaining living documentation alongside your code.
## Installation
```bash
npm install -g openspec
```
## Quick Start
```bash
# Initialize OpenSpec in your project
openspec init
# Update existing OpenSpec instructions (team-friendly)
openspec update
# List all specifications
openspec list
# Show differences between specs and proposed changes
openspec diff [change-name]
# Archive completed changes
openspec archive [change-name]
```
## Commands
### `openspec init`
Initializes OpenSpec in your project by creating:
- `openspec/` directory structure
- `openspec/README.md` with OpenSpec instructions
- AI tool configuration files (based on your selection)
### `openspec update`
Updates OpenSpec instructions to the latest version. This command is **team-friendly** and only updates files that already exist:
- Always updates `openspec/README.md` with the latest OpenSpec instructions
- **Only updates existing AI tool configuration files** (e.g., CLAUDE.md, CURSOR.md)
- **Never creates new AI tool configuration files**
- Preserves content outside of OpenSpec markers in AI tool files
This allows team members to use different AI tools without conflicts. Each developer can maintain their preferred AI tool configuration file, and `openspec update` will respect their choice.
### `openspec list`
Lists all specifications and pending changes in your project:
- Shows current specifications in `openspec/specs/`
- Shows pending changes in `openspec/changes/`
- Shows archived changes in `openspec/changes/archive/`
### `openspec diff [change-name]`
Shows the differences between current specs and proposed changes:
- Displays a unified diff format
- Helps review what will change before implementation
- Useful for pull request reviews
### `openspec archive [change-name]`
Archives a completed change:
- Moves change from `openspec/changes/` to `openspec/changes/archive/`
- Adds a date prefix to the archived change
- Updates specs to reflect the new state
- Use `--skip-specs` to archive without updating specs (for abandoned changes)
## Team Collaboration
OpenSpec is designed for team collaboration:
1. **AI Tool Flexibility**: Each team member can use their preferred AI assistant (Claude, Cursor, etc.)
2. **Non-Invasive Updates**: The `update` command only modifies existing files, never forcing tools on team members
3. **Specification Sharing**: The `openspec/` directory contains shared specifications that all team members work from
4. **Change Tracking**: Proposed changes are visible to all team members for review before implementation
## Contributing
See `openspec/specs/` for the current system specifications and `openspec/changes/` for pending improvements.
## License
MIT
@@ -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
+60 -15
View File
@@ -43,9 +43,9 @@ openspec/
│ │ ├── proposal.md # Why, what, impact (consolidated)
│ │ ├── tasks.md # Implementation checklist
│ │ ├── design.md # Technical decisions (optional, for complex changes)
│ │ └── specs/ # Future state of affected specs
│ │ └── specs/ # Delta changes to specs
│ │ └── [capability]/
│ │ └── spec.md # Clean markdown (no diff syntax)
│ │ └── spec.md # Delta format (ADDED/MODIFIED/REMOVED/RENAMED)
│ └── archive/ # Completed changes (dated)
```
@@ -94,7 +94,35 @@ Before any task:
- 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
### 3. Delta-Based Change Format
Changes use a delta format with clear sections:
```markdown
## ADDED Requirements
### Requirement: New Feature
[Complete requirement content in structured format]
## MODIFIED Requirements
### Requirement: Existing Feature
[Complete modified requirement (header must match current spec)]
## REMOVED Requirements
### Requirement: Old Feature
**Reason for removal**: [Why removing]
**Migration path**: [How to handle existing usage]
## RENAMED Requirements
- FROM: `### Requirement: Old Name`
- TO: `### Requirement: New Name`
```
Key rules:
- Headers are matched using `normalize(header) = trim(header)`
- Include complete requirements (not diffs)
- Use standard symbols in CLI output: + (added), ~ (modified), - (removed), → (renamed)
### 4. Creating a Change Proposal
When a user requests a significant change:
@@ -113,13 +141,21 @@ openspec/changes/[descriptive-name]/
- 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
# 3. Create delta specs for ALL affected capabilities
# - Store only the changes (not complete future state)
# - Use sections: ## ADDED, ## MODIFIED, ## REMOVED, ## RENAMED
# - Include complete requirements in their final form
# Example spec.md content:
# ## ADDED Requirements
# ### Requirement: Password Reset
# Users SHALL be able to reset passwords via email...
#
# ## MODIFIED Requirements
# ### Requirement: User Authentication
# [Complete modified requirement with new password reset hook]
specs/
└── [capability]/
└── spec.md
└── spec.md # Contains delta sections
# 4. Create tasks.md with implementation steps
## 1. [Task Group]
@@ -130,16 +166,16 @@ specs/
[Technical decisions and trade-offs]
```
### 4. The Change Lifecycle
### 5. The Change Lifecycle
1. **Propose** → Create change directory with all documentation
1. **Propose** → Create change directory with delta-based documentation
2. **Review** → User reviews and approves the proposal
3. **Implement** → Follow the approved tasks.md (can be multiple PRs)
4. **Deploy** → User confirms deployment
5. **Update Specs** → Sync specs/ with new reality (IF the change affects system capabilities)
5. **Update Specs** → Apply deltas to sync specs/ with new reality (IF the change affects system capabilities)
6. **Archive** → Move to `changes/archive/YYYY-MM-DD-[name]/`
### 5. Implementing Changes
### 6. Implementing Changes
When implementing an approved change:
1. Follow the tasks.md checklist exactly
@@ -154,7 +190,7 @@ When implementing an approved change:
- 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
### 7. Updating Specs and Archiving After Deployment
**Create a separate PR after deployment** that:
1. Moves change to `changes/archive/YYYY-MM-DD-[name]/`
@@ -163,7 +199,7 @@ When implementing an approved change:
This ensures changes are only archived when truly complete and deployed.
### 7. Types of Changes That Don't Require Specs
### 8. 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.)
@@ -216,7 +252,16 @@ 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
3. Create changes/add-password-reset/ with:
- proposal.md describing the change
- specs/user-auth/spec.md with:
## ADDED Requirements
### Requirement: Password Reset
[Complete requirement for password reset]
## MODIFIED Requirements
### Requirement: User Authentication
[Updated to integrate with password reset]
4. Wait for approval before implementing
```
+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
@@ -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,20 @@
# 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
- Add new `openspec change` command with three subcommands: `show`, `list`, and `validate`
- Implement JSON output capability for change proposals
- Add Zod schemas for change structure validation
- Maintain backward compatibility with existing `openspec list` command
- Enable filtering options specific to changes (requirements-only view)
## 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: List Command Behavior
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
- [ ] 1.1 Create src/commands/change.ts
- [ ] 1.2 Import ChangeSchema and DeltaSchema from src/core/schemas/change.schema.ts
- [ ] 1.3 Import markdown parser from src/core/parsers/markdown-parser.ts
- [ ] 1.4 Import ChangeValidator from src/core/validation/validator.ts
- [ ] 1.5 Import JSON converter from src/core/converters/json-converter.ts
- [ ] 1.6 Implement show subcommand with JSON output using existing converter
- [ ] 1.7 Implement list subcommand
- [ ] 1.8 Implement validate subcommand using existing ChangeValidator
- [ ] 1.9 Add --requirements-only filtering option
- [ ] 1.10 Add --strict mode support (leveraging existing validation infrastructure)
- [ ] 1.11 Add --json flag for validation reports
## 2. Change-Specific Parser Extensions
- [ ] 2.1 Create src/core/parsers/change-parser.ts (extends base markdown parser)
- [ ] 2.2 Parse proposal structure (Why, What Changes sections)
- [ ] 2.3 Extract ADDED/MODIFIED/REMOVED/RENAMED sections
- [ ] 2.4 Parse delta operations within each section
- [ ] 2.5 Add tests for change parser
## 3. Legacy Compatibility
- [ ] 3.1 Update src/core/list.ts to add deprecation notice
- [ ] 3.2 Ensure existing list command continues to work
- [ ] 3.3 Add console warning for deprecated command usage
## 4. Integration
- [ ] 4.1 Register change command in src/cli/index.ts
- [ ] 4.2 Add integration tests for all subcommands
- [ ] 4.3 Test JSON output for changes
- [ ] 4.4 Test legacy compatibility
- [ ] 4.5 Test validation with strict mode
- [ ] 4.6 Update CLI help documentation (add 'change' command to main help, document subcommands: show, list, validate)
@@ -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,167 @@
# 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
@@ -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
- [ ] 1.1 Create src/commands/spec.ts
- [ ] 1.2 Import RequirementSchema, ScenarioSchema, SpecSchema from src/core/schemas/
- [ ] 1.3 Import markdown parser from src/core/parsers/markdown-parser.ts
- [ ] 1.4 Import SpecValidator from src/core/validation/validator.ts
- [ ] 1.5 Import JSON converter from src/core/converters/json-converter.ts
- [ ] 1.6 Implement show subcommand with JSON output using existing converter
- [ ] 1.7 Implement list subcommand
- [ ] 1.8 Implement validate subcommand using existing SpecValidator
- [ ] 1.9 Add filtering options (--requirements, --no-scenarios, -r)
- [ ] 1.10 Add --strict mode support (leveraging existing validation infrastructure)
- [ ] 1.11 Add --json flag for validation reports
## 2. Integration
- [ ] 2.1 Register spec command in src/cli/index.ts
- [ ] 2.2 Add integration tests for all subcommands
- [ ] 2.3 Test JSON output validation
- [ ] 2.4 Test filtering options
- [ ] 2.5 Test validation with strict mode
- [ ] 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 @@
## MODIFIED 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
- [ ] 1.1 Add zod dependency to package.json
- [ ] 1.2 Create src/core/schemas/base.schema.ts with ScenarioSchema and RequirementSchema
- [ ] 1.3 Create src/core/schemas/spec.schema.ts with SpecSchema
- [ ] 1.4 Create src/core/schemas/change.schema.ts with DeltaSchema and ChangeSchema
- [ ] 1.5 Create src/core/schemas/index.ts to export all schemas
## 2. Parser Implementation
- [ ] 2.1 Create src/core/parsers/markdown-parser.ts
- [ ] 2.2 Implement heading extraction (##, ###, ####)
- [ ] 2.3 Implement content capture between headings
- [ ] 2.4 Add tests for parser edge cases
## 3. Validation Infrastructure
- [ ] 3.1 Create src/core/validation/types.ts with ValidationLevel, ValidationIssue, ValidationReport types
- [ ] 3.2 Create src/core/validation/rules.ts with enhanced validation rules
- [ ] 3.3 Create src/core/validation/validator.ts with SpecValidator and ChangeValidator classes
## 4. Enhanced Validation Rules
- [ ] 4.1 Add RequirementValidation refinements (must have scenarios, must contain SHALL)
- [ ] 4.2 Add SpecValidation refinements (must have requirements)
- [ ] 4.3 Add ChangeValidation refinements (must have deltas, why section length)
- [ ] 4.4 Implement custom error messages for each rule
## 5. JSON Converter
- [ ] 5.1 Create src/core/converters/json-converter.ts
- [ ] 5.2 Implement spec-to-JSON conversion
- [ ] 5.3 Implement change-to-JSON conversion
- [ ] 5.4 Add metadata fields (version, format, sourcePath)
## 6. Archive Command Enhancement
- [ ] 6.1 Add pre-archive validation check using new validators
- [ ] 6.2 Add --no-validate flag with required confirmation prompt and warning message: "⚠️ WARNING: Skipping validation may archive invalid specs. Continue? (y/N)"
- [ ] 6.3 Display validation errors before aborting
- [ ] 6.4 Log all --no-validate usages to console with timestamp and affected files
- [ ] 6.5 Add tests for validation scenarios including --no-validate confirmation flow
## 7. Diff Command Enhancement
- [ ] 7.1 Add validation check before diff using new validators
- [ ] 7.2 Show validation warnings (non-blocking)
- [ ] 7.3 Continue with diff even if warnings present
## 8. Testing
- [ ] 8.1 Unit tests for all schemas
- [ ] 8.2 Unit tests for parser
- [ ] 8.3 Unit tests for validation rules
- [ ] 8.4 Integration tests for validation reports
- [ ] 8.5 Test various invalid spec/change formats
- [ ] 8.6 Test strict mode behavior
- [ ] 8.7 Test pre-archive validation
- [ ] 8.8 Test validation report JSON output
## 9. Documentation
- [ ] 9.1 Document schema structure and validation rules
- [ ] 9.2 Update CLI help for archive (document --no-validate flag and its warnings)
- [ ] 9.3 Update CLI help for diff (document validation warnings behavior)
- [ ] 9.4 Create migration guide for future command integration
@@ -1,12 +1,12 @@
# Implementation Tasks
## 1. Update Conventions
- [ ] 1.1 Update openspec-conventions spec with delta-based approach
- [ ] 1.2 Add Header-Based Requirement Identification
- [ ] 1.3 Define ADDED/MODIFIED/REMOVED/RENAMED sections
- [ ] 1.4 Document standard output symbols (+ ~ - →)
- [ ] 1.5 Update openspec/README.md with delta-based conventions
- [ ] 1.6 Update examples to use delta format
- [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
@@ -0,0 +1,28 @@
# 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)
@@ -0,0 +1,113 @@
# Update Command Specification
## Purpose
As a developer using OpenSpec, I want to update the OpenSpec instructions in my project when new versions are released, so that I can benefit from improvements to AI agent instructions.
## Core Requirements
### Requirement: Update Behavior
The update command SHALL update OpenSpec instruction files to the latest templates.
#### Scenario: Running update command
- **WHEN** a user runs `openspec update`
- **THEN** the command SHALL:
- Check if the `openspec` directory exists
- Replace `openspec/README.md` with the latest template (complete replacement)
- For each supported AI tool configuration file:
- Check if the file exists (e.g., CLAUDE.md, COPILOT.md)
- If it exists, update it using appropriate markers
- If it doesn't exist, skip it (do NOT create)
- Preserve user content outside markers
- Display ASCII-safe success message: "Updated OpenSpec instructions"
### Requirement: Prerequisites
The command SHALL require an existing OpenSpec structure before allowing updates.
#### Scenario: Checking prerequisites
- **GIVEN** the command requires an existing `openspec` directory (created by `openspec init`)
- **WHEN** the `openspec` directory does not exist
- **THEN** display error: "No OpenSpec directory found. Run 'openspec init' first."
- **AND** exit with code 1
### 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/README.md` with the latest template
- **AND** update only the AI tool configuration files that already exist
- **AND** use the default directory name `openspec`
- **AND** be idempotent (repeated runs have no additional effect)
### Requirement: Tool-Agnostic Updates
The update command SHALL work for any team member regardless of their AI tool choice.
#### Scenario: Team member using Claude
- **GIVEN** a team member has CLAUDE.md in their project
- **WHEN** running `openspec update`
- **THEN** update the CLAUDE.md file with the latest template
- **AND** preserve user content outside OpenSpec markers
- **AND** NOT create files for other tools
#### Scenario: Team member using different tool
- **GIVEN** a team member has COPILOT.md but no CLAUDE.md
- **WHEN** running `openspec update`
- **THEN** update the COPILOT.md file if implementation exists
- **AND** NOT create CLAUDE.md
- **AND** preserve user content outside OpenSpec markers
#### Scenario: Mixed team environment
- **GIVEN** a repository with both CLAUDE.md and COPILOT.md (different team members)
- **WHEN** any team member runs `openspec update`
- **THEN** update all existing AI tool configuration files
- **AND** NOT create new AI tool configuration files
- **AND** each team member's preferred tool remains configured
## Edge Cases
### Requirement: Error Handling
The command SHALL handle edge cases gracefully.
#### Scenario: File permission errors
- **WHEN** file write fails
- **THEN** let the error bubble up naturally with file path
#### Scenario: No AI tool files exist
- **GIVEN** no AI tool configuration files exist
- **WHEN** running update
- **THEN** only update openspec/README.md
- **AND** display success message
#### Scenario: Custom directory names
- **WHEN** considering custom directory names
- **THEN** not supported in this change
- **AND** the default directory name `openspec` SHALL be used
## Success Criteria
Users SHALL be able to:
- Update OpenSpec instructions with a single command
- Get the latest AI agent instructions for their existing tools
- Work in teams where members use different AI tools
- NOT have unwanted AI tool configuration files created
The update process SHALL be:
- Simple and fast (no version checking)
- Predictable (same result every time)
- Self-contained (no network required)
- Team-friendly (respects individual tool choices)
@@ -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
+13 -8
View File
@@ -8,7 +8,7 @@ As a developer using OpenSpec, I want to update the OpenSpec instructions in my
### Requirement: Update Behavior
The update command SHALL update OpenSpec instruction files to the latest templates.
The update command SHALL update OpenSpec instruction files to the latest templates in a team-friendly manner.
#### Scenario: Running update command
@@ -16,10 +16,13 @@ The update command SHALL update OpenSpec instruction files to the latest templat
- **THEN** the command SHALL:
- Check if the `openspec` directory exists
- Replace `openspec/README.md` with the latest template (complete replacement)
- Update the OpenSpec-managed block in `CLAUDE.md` using markers
- Update **only existing** AI tool configuration files (e.g., CLAUDE.md)
- Check each registered AI tool configurator
- For each configurator, check if its file exists
- Update only files that already exist using their markers
- Preserve user content outside markers
- Create `CLAUDE.md` if missing
- Display ASCII-safe success message: "Updated OpenSpec instructions"
- **Never create new AI tool configuration files**
- Display success message listing updated files
### Requirement: Prerequisites
@@ -40,9 +43,10 @@ The update command SHALL handle file updates in a predictable and safe manner.
- **WHEN** updating files
- **THEN** completely replace `openspec/README.md` with the latest template
- **AND** update only the OpenSpec-managed block in `CLAUDE.md` using markers
- **AND** update only the OpenSpec-managed blocks in **existing** AI tool files using markers
- **AND** use the default directory name `openspec`
- **AND** be idempotent (repeated runs have no additional effect)
- **AND** respect team members' AI tool choices by not creating unwanted files
## Edge Cases
@@ -55,10 +59,11 @@ The command SHALL handle edge cases gracefully.
- **WHEN** file write fails
- **THEN** let the error bubble up naturally with file path
#### Scenario: Missing CLAUDE.md
#### Scenario: Missing AI tool files
- **WHEN** CLAUDE.md doesn't exist
- **THEN** create it with the template content
- **WHEN** an AI tool configuration file doesn't exist
- **THEN** skip updating that file
- **AND** do not create it
#### Scenario: Custom directory names
+90 -9
View File
@@ -76,20 +76,101 @@ Behavioral specifications SHALL use a structured format with consistent section
## Change Storage Convention
### Requirement: Future State Storage
### Requirement: Header-Based Requirement Identification
Change proposals SHALL store complete future state specifications without diff syntax.
Requirement headers SHALL serve as unique identifiers for programmatic matching between current specs and proposed changes.
#### Scenario: Creating change proposals
#### 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
- **WHEN** creating a change proposal
- **THEN** store the complete future state of affected specs
- **AND** use clean markdown without diff syntax
The `changes/[name]/specs/` directory SHALL contain:
- Complete spec files as they will exist after the change
- Clean markdown without `+` or `-` prefixes
- All formatting and structure of the final intended state
- Delta files showing only what changes
- Sections for ADDED, MODIFIED, REMOVED, and RENAMED requirements
- Normalized header matching for requirement identification
- Complete requirements using the structured format
- Clear indication of change type for each requirement
#### Scenario: Using standard output symbols
- **WHEN** displaying delta operations in CLI output
- **THEN** use these standard symbols:
- `+` for ADDED (green)
- `~` for MODIFIED (yellow)
- `-` for REMOVED (red)
- `→` for RENAMED (cyan)
### Requirement: Archive Process Enhancement
The archive process SHALL programmatically apply delta changes to current specifications using header-based matching.
#### Scenario: Archiving changes with deltas
- **WHEN** archiving a completed change
- **THEN** the archive command SHALL:
1. Parse RENAMED sections first and apply renames
2. Parse REMOVED sections and remove by normalized header match
3. Parse MODIFIED sections and replace by normalized header match (using new names if renamed)
4. Parse ADDED sections and append new requirements
- **AND** validate that all MODIFIED/REMOVED headers exist in current spec
- **AND** validate that ADDED headers don't already exist
- **AND** generate the updated spec in the main specs/ directory
#### Scenario: Handling conflicts during archive
- **WHEN** delta changes conflict with current spec state
- **THEN** the archive command SHALL report specific conflicts
- **AND** require manual resolution before proceeding
- **AND** provide clear guidance on resolving conflicts
### Requirement: Proposal Format
+2 -1
View File
@@ -95,7 +95,8 @@ program
.command('archive [change-name]')
.description('Archive a completed change and update main specs')
.option('-y, --yes', 'Skip confirmation prompts')
.action(async (changeName?: string, options?: { yes?: boolean }) => {
.option('--skip-specs', 'Skip spec update operations (useful for infrastructure, tooling, or doc-only changes)')
.action(async (changeName?: string, options?: { yes?: boolean; skipSpecs?: boolean }) => {
try {
const archiveCommand = new ArchiveCommand();
await archiveCommand.execute(changeName, options);
+32 -25
View File
@@ -10,7 +10,7 @@ interface SpecUpdate {
}
export class ArchiveCommand {
async execute(changeName?: string, options: { yes?: boolean } = {}): Promise<void> {
async execute(changeName?: string, options: { yes?: boolean; skipSpecs?: boolean } = {}): Promise<void> {
const targetPath = '.';
const changesDir = path.join(targetPath, 'openspec', 'changes');
const archiveDir = path.join(changesDir, 'archive');
@@ -64,33 +64,40 @@ export class ArchiveCommand {
}
}
// Find specs to update
const specUpdates = await this.findSpecUpdates(changeDir, mainSpecsDir);
if (specUpdates.length > 0) {
console.log('\nSpecs to update:');
for (const update of specUpdates) {
const status = update.exists ? 'update' : 'create';
const capability = path.basename(path.dirname(update.target));
console.log(` ${capability}: ${status}`);
}
// Handle spec updates unless skipSpecs flag is set
if (options.skipSpecs) {
console.log('Skipping spec updates (--skip-specs flag provided).');
} else {
// Find specs to update
const specUpdates = await this.findSpecUpdates(changeDir, mainSpecsDir);
if (specUpdates.length > 0) {
console.log('\nSpecs to update:');
for (const update of specUpdates) {
const status = update.exists ? 'update' : 'create';
const capability = path.basename(path.dirname(update.target));
console.log(` ${capability}: ${status}`);
}
if (!options.yes) {
const proceed = await confirm({
message: 'Proceed with spec updates?',
default: true
});
if (!proceed) {
console.log('Archive cancelled.');
return;
let shouldUpdateSpecs = true;
if (!options.yes) {
shouldUpdateSpecs = await confirm({
message: 'Proceed with spec updates?',
default: true
});
if (!shouldUpdateSpecs) {
console.log('Skipping spec updates. Proceeding with archive.');
}
}
if (shouldUpdateSpecs) {
// Update specs
for (const update of specUpdates) {
await this.updateSpec(update);
}
console.log('Specs updated successfully.');
}
}
// Update specs
for (const update of specUpdates) {
await this.updateSpec(update);
}
console.log('Specs updated successfully.');
}
// Create archive directory with date prefix
+60 -15
View File
@@ -43,9 +43,9 @@ openspec/
│ │ ├── proposal.md # Why, what, impact (consolidated)
│ │ ├── tasks.md # Implementation checklist
│ │ ├── design.md # Technical decisions (optional, for complex changes)
│ │ └── specs/ # Future state of affected specs
│ │ └── specs/ # Delta changes to specs
│ │ └── [capability]/
│ │ └── spec.md # Clean markdown (no diff syntax)
│ │ └── spec.md # Delta format (ADDED/MODIFIED/REMOVED/RENAMED)
│ └── archive/ # Completed changes (dated)
\`\`\`
@@ -94,7 +94,35 @@ Before any task:
- 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
### 3. Delta-Based Change Format
Changes use a delta format with clear sections:
\`\`\`markdown
## ADDED Requirements
### Requirement: New Feature
[Complete requirement content in structured format]
## MODIFIED Requirements
### Requirement: Existing Feature
[Complete modified requirement (header must match current spec)]
## REMOVED Requirements
### Requirement: Old Feature
**Reason for removal**: [Why removing]
**Migration path**: [How to handle existing usage]
## RENAMED Requirements
- FROM: \`### Requirement: Old Name\`
- TO: \`### Requirement: New Name\`
\`\`\`
Key rules:
- Headers are matched using \`normalize(header) = trim(header)\`
- Include complete requirements (not diffs)
- Use standard symbols in CLI output: + (added), ~ (modified), - (removed), → (renamed)
### 4. Creating a Change Proposal
When a user requests a significant change:
@@ -113,13 +141,21 @@ openspec/changes/[descriptive-name]/
- 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
# 3. Create delta specs for ALL affected capabilities
# - Store only the changes (not complete future state)
# - Use sections: ## ADDED, ## MODIFIED, ## REMOVED, ## RENAMED
# - Include complete requirements in their final form
# Example spec.md content:
# ## ADDED Requirements
# ### Requirement: Password Reset
# Users SHALL be able to reset passwords via email...
#
# ## MODIFIED Requirements
# ### Requirement: User Authentication
# [Complete modified requirement with new password reset hook]
specs/
└── [capability]/
└── spec.md
└── spec.md # Contains delta sections
# 4. Create tasks.md with implementation steps
## 1. [Task Group]
@@ -130,16 +166,16 @@ specs/
[Technical decisions and trade-offs]
\`\`\`
### 4. The Change Lifecycle
### 5. The Change Lifecycle
1. **Propose** → Create change directory with all documentation
1. **Propose** → Create change directory with delta-based documentation
2. **Review** → User reviews and approves the proposal
3. **Implement** → Follow the approved tasks.md (can be multiple PRs)
4. **Deploy** → User confirms deployment
5. **Update Specs** → Sync specs/ with new reality (IF the change affects system capabilities)
5. **Update Specs** → Apply deltas to sync specs/ with new reality (IF the change affects system capabilities)
6. **Archive** → Move to \`changes/archive/YYYY-MM-DD-[name]/\`
### 5. Implementing Changes
### 6. Implementing Changes
When implementing an approved change:
1. Follow the tasks.md checklist exactly
@@ -154,7 +190,7 @@ When implementing an approved change:
- 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
### 7. Updating Specs and Archiving After Deployment
**Create a separate PR after deployment** that:
1. Moves change to \`changes/archive/YYYY-MM-DD-[name]/\`
@@ -163,7 +199,7 @@ When implementing an approved change:
This ensures changes are only archived when truly complete and deployed.
### 7. Types of Changes That Don't Require Specs
### 8. 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.)
@@ -216,7 +252,16 @@ 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
3. Create changes/add-password-reset/ with:
- proposal.md describing the change
- specs/user-auth/spec.md with:
## ADDED Requirements
### Requirement: Password Reset
[Complete requirement for password reset]
## MODIFIED Requirements
### Requirement: User Authentication
[Updated to integrate with password reset]
4. Wait for approval before implementing
\`\`\`
+32 -12
View File
@@ -1,8 +1,8 @@
import path from 'path';
import { FileSystemUtils } from '../utils/file-system.js';
import { TemplateManager } from './templates/index.js';
import { OPENSPEC_DIR_NAME, OPENSPEC_MARKERS } from './config.js';
import { OPENSPEC_DIR_NAME } from './config.js';
import { readmeTemplate } from './templates/readme-template.js';
import { ToolRegistry } from './configurators/registry.js';
export class UpdateCommand {
async execute(projectPath: string): Promise<void> {
@@ -19,17 +19,37 @@ export class UpdateCommand {
const readmePath = path.join(openspecPath, 'README.md');
await FileSystemUtils.writeFile(readmePath, readmeTemplate);
// 3. Update CLAUDE.md (marker-based)
const claudePath = path.join(resolvedProjectPath, 'CLAUDE.md');
const claudeContent = TemplateManager.getClaudeTemplate();
await FileSystemUtils.updateFileWithMarkers(
claudePath,
claudeContent,
OPENSPEC_MARKERS.start,
OPENSPEC_MARKERS.end
);
// 3. Update existing AI tool configuration files only
const configurators = ToolRegistry.getAll();
let updatedFiles: string[] = [];
let failedFiles: string[] = [];
for (const configurator of configurators) {
const configFilePath = path.join(resolvedProjectPath, configurator.configFileName);
// Only update if the file already exists
if (await FileSystemUtils.fileExists(configFilePath)) {
try {
await configurator.configure(resolvedProjectPath, openspecPath);
updatedFiles.push(configurator.configFileName);
} catch (error) {
failedFiles.push(configurator.configFileName);
console.error(`Failed to update ${configurator.configFileName}: ${error instanceof Error ? error.message : String(error)}`);
}
}
}
// 4. Success message (ASCII-safe)
console.log('Updated OpenSpec instructions');
const messages: string[] = ['Updated OpenSpec instructions (README.md)'];
if (updatedFiles.length > 0) {
messages.push(`Updated AI tool files: ${updatedFiles.join(', ')}`);
}
if (failedFiles.length > 0) {
messages.push(`Failed to update: ${failedFiles.join(', ')}`);
}
console.log(messages.join('\n'));
}
}
+70
View File
@@ -171,6 +171,76 @@ describe('ArchiveCommand', () => {
const archives = await fs.readdir(archiveDir);
expect(archives.length).toBe(1);
});
it('should skip spec updates when --skip-specs flag is used', async () => {
const changeName = 'skip-specs-feature';
const changeDir = path.join(tempDir, 'openspec', 'changes', changeName);
const changeSpecDir = path.join(changeDir, 'specs', 'test-capability');
await fs.mkdir(changeSpecDir, { recursive: true });
// Create spec in change
const specContent = '# Test Capability Spec\n\nTest content';
await fs.writeFile(path.join(changeSpecDir, 'spec.md'), specContent);
// Execute archive with --skip-specs flag
await archiveCommand.execute(changeName, { yes: true, skipSpecs: true });
// Verify skip message was logged
expect(console.log).toHaveBeenCalledWith(
'Skipping spec updates (--skip-specs flag provided).'
);
// Verify spec was NOT copied to main specs
const mainSpecPath = path.join(tempDir, 'openspec', 'specs', 'test-capability', 'spec.md');
await expect(fs.access(mainSpecPath)).rejects.toThrow();
// Verify change was still archived
const archiveDir = path.join(tempDir, 'openspec', 'changes', 'archive');
const archives = await fs.readdir(archiveDir);
expect(archives.length).toBe(1);
expect(archives[0]).toMatch(new RegExp(`\\d{4}-\\d{2}-\\d{2}-${changeName}`));
});
it('should proceed with archive when user declines spec updates', async () => {
const { confirm } = await import('@inquirer/prompts');
const mockConfirm = confirm as unknown as ReturnType<typeof vi.fn>;
const changeName = 'decline-specs-feature';
const changeDir = path.join(tempDir, 'openspec', 'changes', changeName);
const changeSpecDir = path.join(changeDir, 'specs', 'test-capability');
await fs.mkdir(changeSpecDir, { recursive: true });
// Create spec in change
const specContent = '# Test Capability Spec\n\nTest content';
await fs.writeFile(path.join(changeSpecDir, 'spec.md'), specContent);
// Mock confirm to return false (decline spec updates)
mockConfirm.mockResolvedValueOnce(false);
// Execute archive without --yes flag
await archiveCommand.execute(changeName);
// Verify user was prompted about specs
expect(mockConfirm).toHaveBeenCalledWith({
message: 'Proceed with spec updates?',
default: true
});
// Verify skip message was logged
expect(console.log).toHaveBeenCalledWith(
'Skipping spec updates. Proceeding with archive.'
);
// Verify spec was NOT copied to main specs
const mainSpecPath = path.join(tempDir, 'openspec', 'specs', 'test-capability', 'spec.md');
await expect(fs.access(mainSpecPath)).rejects.toThrow();
// Verify change was still archived
const archiveDir = path.join(tempDir, 'openspec', 'changes', 'archive');
const archives = await fs.readdir(archiveDir);
expect(archives.length).toBe(1);
expect(archives[0]).toMatch(new RegExp(`\\d{4}-\\d{2}-\\d{2}-${changeName}`));
});
});
describe('error handling', () => {
+165
View File
@@ -0,0 +1,165 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { UpdateCommand } from '../../src/core/update.js';
import { FileSystemUtils } from '../../src/utils/file-system.js';
import { ToolRegistry } from '../../src/core/configurators/registry.js';
import path from 'path';
import fs from 'fs/promises';
import os from 'os';
describe('UpdateCommand', () => {
let testDir: string;
let updateCommand: UpdateCommand;
beforeEach(async () => {
// Create a temporary test directory
testDir = path.join(os.tmpdir(), `openspec-test-${Date.now()}`);
await fs.mkdir(testDir, { recursive: true });
// Create openspec directory
const openspecDir = path.join(testDir, 'openspec');
await fs.mkdir(openspecDir, { recursive: true });
updateCommand = new UpdateCommand();
});
afterEach(async () => {
// Clean up test directory
await fs.rm(testDir, { recursive: true, force: true });
});
it('should update only existing CLAUDE.md file', async () => {
// Create CLAUDE.md file with initial content
const claudePath = path.join(testDir, 'CLAUDE.md');
const initialContent = `# Project Instructions
Some existing content here.
<!-- OPENSPEC:START -->
Old OpenSpec content
<!-- OPENSPEC:END -->
More content after.`;
await fs.writeFile(claudePath, initialContent);
const consoleSpy = vi.spyOn(console, 'log');
// Execute update command
await updateCommand.execute(testDir);
// Check that CLAUDE.md was updated
const updatedContent = await fs.readFile(claudePath, 'utf-8');
expect(updatedContent).toContain('<!-- OPENSPEC:START -->');
expect(updatedContent).toContain('<!-- OPENSPEC:END -->');
expect(updatedContent).toContain('This project uses OpenSpec');
expect(updatedContent).toContain('Some existing content here');
expect(updatedContent).toContain('More content after');
// Check console output
expect(consoleSpy).toHaveBeenCalledWith(
'Updated OpenSpec instructions (README.md)\nUpdated AI tool files: CLAUDE.md'
);
consoleSpy.mockRestore();
});
it('should not create CLAUDE.md if it does not exist', async () => {
// Ensure CLAUDE.md does not exist
const claudePath = path.join(testDir, 'CLAUDE.md');
// Execute update command
await updateCommand.execute(testDir);
// Check that CLAUDE.md was not created
const fileExists = await FileSystemUtils.fileExists(claudePath);
expect(fileExists).toBe(false);
});
it('should handle no AI tool files present', async () => {
// Execute update command with no AI tool files
const consoleSpy = vi.spyOn(console, 'log');
await updateCommand.execute(testDir);
// Should only update OpenSpec instructions
expect(consoleSpy).toHaveBeenCalledWith('Updated OpenSpec instructions (README.md)');
consoleSpy.mockRestore();
});
it('should update multiple AI tool files if present', async () => {
// TODO: When additional configurators are added (Cursor, Aider, etc.),
// enhance this test to create multiple AI tool files and verify
// that all existing files are updated in a single operation.
// For now, we test with just CLAUDE.md.
const claudePath = path.join(testDir, 'CLAUDE.md');
await fs.writeFile(claudePath, '<!-- OPENSPEC:START -->\nOld\n<!-- OPENSPEC:END -->');
const consoleSpy = vi.spyOn(console, 'log');
await updateCommand.execute(testDir);
// Should report updating with new format
expect(consoleSpy).toHaveBeenCalledWith(
'Updated OpenSpec instructions (README.md)\nUpdated AI tool files: CLAUDE.md'
);
consoleSpy.mockRestore();
});
it('should never create new AI tool files', async () => {
// Get all configurators
const configurators = ToolRegistry.getAll();
// Execute update command
await updateCommand.execute(testDir);
// Check that no new AI tool files were created
for (const configurator of configurators) {
const configPath = path.join(testDir, configurator.configFileName);
const fileExists = await FileSystemUtils.fileExists(configPath);
expect(fileExists).toBe(false);
}
});
it('should update README.md in openspec directory', async () => {
// Execute update command
await updateCommand.execute(testDir);
// Check that README.md was created/updated
const readmePath = path.join(testDir, 'openspec', 'README.md');
const fileExists = await FileSystemUtils.fileExists(readmePath);
expect(fileExists).toBe(true);
const content = await fs.readFile(readmePath, 'utf-8');
expect(content).toContain('# OpenSpec Instructions');
});
it('should throw error if openspec directory does not exist', async () => {
// Remove openspec directory
await fs.rm(path.join(testDir, 'openspec'), { recursive: true, force: true });
// Execute update command and expect error
await expect(updateCommand.execute(testDir)).rejects.toThrow(
"No OpenSpec directory found. Run 'openspec init' first."
);
});
it('should handle configurator errors gracefully', async () => {
// Create CLAUDE.md file but make it read-only to cause an error
const claudePath = path.join(testDir, 'CLAUDE.md');
await fs.writeFile(claudePath, '<!-- OPENSPEC:START -->\nOld\n<!-- OPENSPEC:END -->');
await fs.chmod(claudePath, 0o444); // Read-only
const consoleSpy = vi.spyOn(console, 'log');
const errorSpy = vi.spyOn(console, 'error');
// Execute update command - should not throw
await updateCommand.execute(testDir);
// Should report the failure
expect(errorSpy).toHaveBeenCalled();
expect(consoleSpy).toHaveBeenCalledWith(
'Updated OpenSpec instructions (README.md)\nFailed to update: CLAUDE.md'
);
// Restore permissions for cleanup
await fs.chmod(claudePath, 0o644);
consoleSpy.mockRestore();
errorSpy.mockRestore();
});
});