mirror of
https://github.com/Fission-AI/OpenSpec.git
synced 2026-10-04 06:18:24 +08:00
Compare commits
36
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d664e740d3 | ||
|
|
6469593495 | ||
|
|
157936cf68 | ||
|
|
fef33df753 | ||
|
|
78b61e8466 | ||
|
|
5fa0fa68a7 | ||
|
|
fe9eb44ec2 | ||
|
|
ee78f21b08 | ||
|
|
e3ae2ceaf0 | ||
|
|
20b2fee749 | ||
|
|
e7fff31df2 | ||
|
|
fdf9a30f0b | ||
|
|
161aa41cb3 | ||
|
|
9e092a185b | ||
|
|
38454bb2a6 | ||
|
|
b04f1cc923 | ||
|
|
ae86e9be9e | ||
|
|
f955e87fd9 | ||
|
|
55efd19953 | ||
|
|
dab5d93b85 | ||
|
|
7b0f494754 | ||
|
|
dd7ba71fe5 | ||
|
|
66ad5658f9 | ||
|
|
21a0e74b74 | ||
|
|
485ef07ec7 | ||
|
|
ce5ceadbe7 | ||
|
|
9a173b917c | ||
|
|
79baabbed1 | ||
|
|
818a5922ce | ||
|
|
d8d2930182 | ||
|
|
6af6e0ccb6 | ||
|
|
50e6660018 | ||
|
|
4bbb52dda4 | ||
|
|
4a0ae49b6e | ||
|
|
646c516b0d | ||
|
|
8c1b580f03 |
@@ -1,302 +0,0 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,2 @@
|
||||
# Default code ownership
|
||||
* @TabishB
|
||||
@@ -69,4 +69,4 @@ jobs:
|
||||
- run: pnpm test
|
||||
|
||||
- name: Publish
|
||||
run: pnpm publish --access public --provenance --no-git-checks --tag next
|
||||
run: pnpm publish --access public --provenance --no-git-checks
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 24b4866: Initial release
|
||||
@@ -1,5 +1,19 @@
|
||||
# @fission-ai/openspec
|
||||
|
||||
## 0.3.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- Enhance `openspec init` with extend mode, multi-tool selection, and an interactive `AGENTS.md` configurator.
|
||||
|
||||
## 0.2.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- ce5cead: - Add an `openspec view` dashboard that rolls up spec counts and change progress at a glance
|
||||
- Generate and update AI slash commands alongside the renamed `openspec/AGENTS.md` instructions file
|
||||
- Remove the deprecated `openspec diff` command and direct users to `openspec show`
|
||||
|
||||
## 0.1.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
@@ -17,131 +17,191 @@
|
||||
<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>
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/openspec_dashboard.png" alt="OpenSpec dashboard preview" width="90%">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
Follow <a href="https://x.com/0xTab">@0xTab on X</a> for updates.
|
||||
</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.
|
||||
OpenSpec aligns humans and AI coding assistants with spec-driven development so you agree on what to build before any code is written. **No API keys required.**
|
||||
|
||||
## 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.
|
||||
AI coding assistants are powerful but unpredictable when requirements live in chat history. OpenSpec adds a lightweight specification workflow that locks intent before implementation, giving you deterministic, reviewable outputs.
|
||||
|
||||
**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
|
||||
Key outcomes:
|
||||
- Human and AI stakeholders agree on specs before work begins.
|
||||
- Structured change folders (proposals, tasks, and spec updates) keep scope explicit and auditable.
|
||||
- Shared visibility into what's proposed, active, or archived.
|
||||
- Works with the AI tools you already use: custom slash commands where supported, context rules everywhere else.
|
||||
|
||||
## How It Works
|
||||
|
||||
```
|
||||
┌─────────────┐ ┌─────────────┐ ┌──────────────┐
|
||||
│ SPECS │ │ CHANGES │ │ ARCHIVE │
|
||||
│ (Truth) │◀──────│ (Proposals) │──────▶│ (Completed) │
|
||||
└─────────────┘ └─────────────┘ └──────────────┘
|
||||
▲ │ │
|
||||
│ ▼ │
|
||||
│ ┌─────────────┐ │
|
||||
└───────────────│ CODE │◀──────────────┘
|
||||
└─────────────┘
|
||||
┌────────────────────┐
|
||||
│ Draft Change │
|
||||
│ Proposal │
|
||||
└────────┬───────────┘
|
||||
│ share intent with your AI
|
||||
▼
|
||||
┌────────────────────┐
|
||||
│ Review & Align │
|
||||
│ (edit specs/tasks) │◀──── feedback loop ──────┐
|
||||
└────────┬───────────┘ │
|
||||
│ approved plan │
|
||||
▼ │
|
||||
┌────────────────────┐ │
|
||||
│ Implement Tasks │──────────────────────────┘
|
||||
│ (AI writes code) │
|
||||
└────────┬───────────┘
|
||||
│ ship the change
|
||||
▼
|
||||
┌────────────────────┐
|
||||
│ Archive & Update │
|
||||
│ Specs (source) │
|
||||
└────────────────────┘
|
||||
|
||||
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
|
||||
1. Draft a change proposal that captures the spec updates you want.
|
||||
2. Review the proposal with your AI assistant until everyone agrees.
|
||||
3. Implement tasks that reference the agreed specs.
|
||||
4. Archive the change to merge the approved updates back into the source-of-truth specs.
|
||||
```
|
||||
|
||||
## Getting Started
|
||||
|
||||
### 1. Initialize OpenSpec in Your Project
|
||||
### Supported AI Tools
|
||||
|
||||
#### Native Slash Commands
|
||||
These tools have built-in OpenSpec commands. Select the OpenSpec integration when prompted.
|
||||
|
||||
| Tool | Commands |
|
||||
|------|----------|
|
||||
| **Claude Code** | `/openspec:proposal`, `/openspec:apply`, `/openspec:archive` |
|
||||
| **Cursor** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` |
|
||||
|
||||
#### AGENTS.md Compatible
|
||||
These tools automatically read workflow instructions from `openspec/AGENTS.md`. Ask them to follow the OpenSpec workflow if they need a reminder. Learn more about the [AGENTS.md convention](https://agents.md/).
|
||||
|
||||
| Tools |
|
||||
|-------|
|
||||
| Codex • Amp • Jules • OpenCode • Gemini CLI • GitHub Copilot • Others |
|
||||
|
||||
### Install & Initialize
|
||||
|
||||
#### Prerequisites
|
||||
- **Node.js >= 20.19.0** - Check your version with `node --version`
|
||||
|
||||
#### Step 1: Install the CLI globally
|
||||
|
||||
```bash
|
||||
# Navigate to your project
|
||||
npm install -g @fission-ai/openspec@latest
|
||||
```
|
||||
|
||||
Verify installation:
|
||||
```bash
|
||||
openspec --version
|
||||
```
|
||||
|
||||
#### Step 2: Initialize OpenSpec in your project
|
||||
|
||||
Navigate to your project directory:
|
||||
```bash
|
||||
cd my-project
|
||||
```
|
||||
|
||||
# Initialize OpenSpec
|
||||
Run the initialization:
|
||||
```bash
|
||||
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
|
||||
**What happens during initialization:**
|
||||
- You'll be prompted to select your AI tool (Claude Code, Cursor, etc.)
|
||||
- OpenSpec automatically configures slash commands or `AGENTS.md` based on your selection
|
||||
- A new `openspec/` directory structure is created in your project
|
||||
|
||||
Jump straight into creating a change proposal with your AI assistant (works with Claude Code, Cursor, or any AI tool):
|
||||
**After setup:**
|
||||
- Primary AI tools can trigger `/openspec` workflows without additional configuration
|
||||
- Run `openspec list` to verify the setup and view any active changes
|
||||
|
||||
```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."
|
||||
### Create Your First Change
|
||||
|
||||
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)
|
||||
Here's a real example showing the complete OpenSpec workflow. This works with any AI tool. Those with native slash commands will recognize the shortcuts automatically.
|
||||
|
||||
You: "The proposal looks good. Let's implement it."
|
||||
#### 1. Draft the Proposal
|
||||
Start by asking your AI to create a change proposal:
|
||||
|
||||
AI: "Following the tasks in openspec/changes/add-user-profile-api/tasks.md:
|
||||
Task 1.1: Create user profile model..."
|
||||
*Implements each task systematically*
|
||||
```text
|
||||
You: Create an OpenSpec change proposal for adding profile search filters by role and team
|
||||
(Shortcut for tools with slash commands: /openspec:proposal Add profile search filters)
|
||||
|
||||
AI: I'll create an OpenSpec change proposal for profile filters.
|
||||
*Scaffolds openspec/changes/add-profile-filters/ with proposal.md, tasks.md, spec deltas.*
|
||||
```
|
||||
|
||||
### 3. Track Your Work
|
||||
#### 2. Verify & Review
|
||||
Check that the change was created correctly and review the proposal:
|
||||
|
||||
```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/
|
||||
$ openspec list # Confirm the change folder exists
|
||||
$ openspec validate add-profile-filters # Validate spec formatting
|
||||
$ openspec show add-profile-filters # Review proposal, tasks, and spec delta
|
||||
```
|
||||
|
||||
## Common Commands
|
||||
#### 3. Refine the Specs
|
||||
Iterate on the specifications until they match your needs:
|
||||
|
||||
```text
|
||||
You: Can you add acceptance criteria for the role and team filters?
|
||||
|
||||
AI: I'll update the spec delta with scenarios for role and team filters.
|
||||
*Edits openspec/changes/add-profile-filters/specs/profile/spec.md and tasks.md.*
|
||||
```
|
||||
|
||||
#### 4. Implement the Change
|
||||
Once specs look good, start implementation:
|
||||
|
||||
```text
|
||||
You: The specs look good. Let's implement this change.
|
||||
(Shortcut for tools with slash commands: /openspec:apply add-profile-filters)
|
||||
|
||||
AI: I'll work through the tasks in the add-profile-filters change.
|
||||
*Implements tasks from openspec/changes/add-profile-filters/tasks.md*
|
||||
*Marks tasks complete: Task 1.1 ✓, Task 1.2 ✓, Task 2.1 ✓...*
|
||||
```
|
||||
|
||||
#### 5. Archive the Completed Change
|
||||
After implementation is complete, archive the change:
|
||||
|
||||
```text
|
||||
AI: All tasks are complete. The implementation is ready.
|
||||
|
||||
You: Please archive the change
|
||||
(Shortcut for tools with slash commands: /openspec:archive add-profile-filters)
|
||||
|
||||
AI: I'll archive the add-profile-filters change.
|
||||
*Runs: openspec archive add-profile-filters*
|
||||
✓ Change archived successfully. Specs updated. Ready for the next feature!
|
||||
```
|
||||
|
||||
Or run the command yourself in terminal:
|
||||
```bash
|
||||
$ openspec archive add-profile-filters # Archive the completed change
|
||||
```
|
||||
|
||||
**Note:** Tools with native slash commands (Claude Code, Cursor) can use the shortcuts shown. All other tools work with natural language requests to "create an OpenSpec proposal", "apply the OpenSpec change", or "archive the change".
|
||||
|
||||
## Command Reference
|
||||
|
||||
```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
|
||||
openspec list # View active change folders
|
||||
openspec view # Interactive dashboard of specs and changes
|
||||
openspec show <change> # Display change details (proposal, tasks, spec updates)
|
||||
openspec validate <change> # Check spec formatting and structure
|
||||
openspec archive <change> # Move a completed change into archive/
|
||||
```
|
||||
|
||||
## Example: How AI Creates OpenSpec Files
|
||||
@@ -228,46 +288,38 @@ Deltas are "patches" that show how specs change:
|
||||
- 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.
|
||||
OpenSpec groups every change for a feature in one folder (`openspec/changes/feature-name/`), making it easy to track related specs, tasks, and designs together. Kiro spreads updates across multiple spec folders, which can make 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.
|
||||
Without specs, AI coding assistants generate code from vague prompts, often missing requirements or adding unwanted features. OpenSpec brings predictability by agreeing on the desired behavior before any code is written.
|
||||
|
||||
## Team Adoption
|
||||
|
||||
### Getting Started with Your Team
|
||||
1. **Initialize OpenSpec** – Run `openspec init` in your repo.
|
||||
2. **Start with new features** – Ask your AI to capture upcoming work as change proposals.
|
||||
3. **Grow incrementally** – Each change archives into living specs that document your system.
|
||||
4. **Stay flexible** – Different teammates can use Claude Code, Cursor, or any AGENTS.md-compatible tool while sharing the same specs.
|
||||
|
||||
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
|
||||
Run `openspec update` whenever someone switches tools so your agents pick up the latest instructions and slash-command bindings.
|
||||
|
||||
**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.
|
||||
## Updating OpenSpec
|
||||
|
||||
1. **Upgrade the package**
|
||||
```bash
|
||||
npm install -g @fission-ai/openspec@latest
|
||||
```
|
||||
2. **Refresh agent instructions**
|
||||
- Run `openspec update` inside each project to regenerate AI guidance and ensure the latest slash commands are active.
|
||||
|
||||
## Contributing
|
||||
|
||||
- Install dependencies: `npm install`
|
||||
- Build: `npm run build`
|
||||
- Test: `npm test`
|
||||
- Develop CLI locally: `npm run dev` or `npm run dev:cli`
|
||||
- Install dependencies: `pnpm install`
|
||||
- Build: `pnpm run build`
|
||||
- Test: `pnpm test`
|
||||
- Develop CLI locally: `pnpm run dev` or `pnpm run dev:cli`
|
||||
- Conventional commits (one-line): `type(scope): subject`
|
||||
|
||||
## License
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 450 KiB |
@@ -40,20 +40,26 @@ Skip proposal for:
|
||||
- Configuration changes
|
||||
- Tests for existing behavior
|
||||
|
||||
**Workflow**
|
||||
1. Review `openspec/project.md`, `openspec list`, and `openspec list --specs` to understand current context.
|
||||
2. Choose a unique verb-led `change-id` and scaffold `proposal.md`, `tasks.md`, optional `design.md`, and spec deltas under `openspec/changes/<id>/`.
|
||||
3. Draft spec deltas using `## ADDED|MODIFIED|REMOVED Requirements` with at least one `#### Scenario:` per requirement.
|
||||
4. Run `openspec validate <id> --strict` and resolve any issues before sharing the proposal.
|
||||
|
||||
### 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
|
||||
6. **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
|
||||
- Run `openspec validate --strict` to confirm the archived change passes checks
|
||||
|
||||
## Before Any Task
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# Add AGENTS.md Standard Support To Init/Update
|
||||
|
||||
## Summary
|
||||
- Teach `openspec init` to manage a root-level `AGENTS.md` file using the same marker system as `CLAUDE.md`.
|
||||
- Allow `openspec update` to refresh or scaffold that root `AGENTS.md` so AGENTS-compatible tools always receive current instructions.
|
||||
- Keep the existing `openspec/AGENTS.md` template as the canonical source while ensuring assistants that read `AGENTS.md` opt-in instructions get the latest guidance automatically.
|
||||
|
||||
## Motivation
|
||||
The README now points teams to AGENTS.md-compatible assistants, but the CLI only manages `CLAUDE.md`. Projects must hand-roll a root `AGENTS.md` file to benefit from the standard, and updates will drift unless maintainers remember to copy content manually. Extending `init` and `update` closes that gap so OpenSpec actually delivers on the promise of first-class AGENTS support.
|
||||
|
||||
## Proposal
|
||||
1. Extend the `openspec init` selection flow with an "AGENTS.md standard" option that creates or refreshes a root `AGENTS.md` file wrapped in OpenSpec markers, mirroring the existing CLAUDE integration.
|
||||
2. When generating the file, pull the managed content from the same template used in `openspec/AGENTS.md`, ensuring both locations stay in sync.
|
||||
3. Update `openspec update` so it always refreshes the root `AGENTS.md` (creating it if missing) alongside `openspec/AGENTS.md` and any other configured assistants.
|
||||
4. Document the new behavior in CLI specs and verify marker handling (no duplicates, preserve user content outside the block) with tests for both commands.
|
||||
|
||||
## Out of Scope
|
||||
- Adding additional AGENTS-specific prompts or workflows beyond the shared instructions block.
|
||||
- Non-interactive flags or bulk configuration for multiple standards in one run.
|
||||
- Broader restructuring of how templates are stored or loaded.
|
||||
|
||||
## Risks & Mitigations
|
||||
- **Risk:** Accidentally overwriting user-edited content surrounding the managed block.
|
||||
- **Mitigation:** Reuse the existing marker-update helper shared with `CLAUDE.md`, and add tests that cover files containing custom text before and after the block.
|
||||
- **Risk:** Divergence between `openspec/AGENTS.md` and the root file.
|
||||
- **Mitigation:** Source the root file content from the canonical template rather than duplicating strings inline.
|
||||
- **Risk:** Confusion about when the file is created.
|
||||
- **Mitigation:** Log creation vs update, and ensure help text references the AGENTS option during `init`.
|
||||
@@ -0,0 +1,71 @@
|
||||
## MODIFIED Requirements
|
||||
### Requirement: AI Tool Configuration
|
||||
The command SHALL configure AI coding assistants with OpenSpec instructions based on user selection.
|
||||
|
||||
#### Scenario: Prompting for AI tool selection
|
||||
|
||||
- **WHEN** run
|
||||
- **THEN** prompt user to select AI tools to configure:
|
||||
- Claude Code (✅ OpenSpec custom slash commands available)
|
||||
- Cursor (✅ OpenSpec custom slash commands available)
|
||||
- AGENTS.md (works with Codex, Amp, Copilot, …)
|
||||
|
||||
### Requirement: AI Tool Configuration Details
|
||||
The command SHALL properly configure selected AI tools with OpenSpec-specific instructions using a marker system.
|
||||
|
||||
#### Scenario: Configuring Claude Code
|
||||
|
||||
- **WHEN** Claude Code is selected
|
||||
- **THEN** create or update `CLAUDE.md` in the project root directory (not inside openspec/)
|
||||
|
||||
#### Scenario: Configuring AGENTS standard
|
||||
|
||||
- **WHEN** the AGENTS.md standard is selected
|
||||
- **THEN** create or update `AGENTS.md` in the project root directory (not inside openspec/)
|
||||
|
||||
#### Scenario: Creating new CLAUDE.md
|
||||
|
||||
- **WHEN** CLAUDE.md does not exist
|
||||
- **THEN** create new file with OpenSpec content wrapped in markers:
|
||||
```markdown
|
||||
<!-- 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 -->
|
||||
```
|
||||
|
||||
#### Scenario: Creating new AGENTS.md
|
||||
|
||||
- **WHEN** AGENTS.md does not exist in the project root
|
||||
- **THEN** create new file with OpenSpec content wrapped in markers using the same template as CLAUDE.md
|
||||
|
||||
#### Scenario: Updating existing CLAUDE.md
|
||||
|
||||
- **WHEN** CLAUDE.md already exists
|
||||
- **THEN** preserve all existing content
|
||||
- **AND** insert OpenSpec content at the beginning of the file using markers
|
||||
- **AND** ensure markers don't duplicate if they already exist
|
||||
|
||||
#### Scenario: Updating existing AGENTS.md
|
||||
|
||||
- **WHEN** AGENTS.md already exists in the project root
|
||||
- **THEN** preserve all existing content
|
||||
- **AND** ensure the OpenSpec-managed block at the beginning of the file is refreshed without duplicating markers
|
||||
|
||||
#### Scenario: Managing content with markers
|
||||
|
||||
- **WHEN** using the marker system
|
||||
- **THEN** use `<!-- OPENSPEC:START -->` to mark the beginning of managed content
|
||||
- **AND** use `<!-- OPENSPEC:END -->` to mark the end of managed content
|
||||
- **AND** allow OpenSpec to update its content without affecting user customizations
|
||||
- **AND** preserve all content outside the markers intact
|
||||
|
||||
WHY use markers:
|
||||
- Users may have existing CLAUDE.md or AGENTS.md instructions they want to keep
|
||||
- OpenSpec can update its instructions in future versions
|
||||
- Clear boundary between OpenSpec-managed and user-managed content
|
||||
@@ -0,0 +1,41 @@
|
||||
## 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** the command SHALL:
|
||||
- Check if the `openspec` directory exists
|
||||
- Replace `openspec/AGENTS.md` with the latest template (complete replacement)
|
||||
- Create or refresh a root-level `AGENTS.md` file using the managed marker block (create if missing)
|
||||
- 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
|
||||
- Display success message listing updated files
|
||||
|
||||
### Requirement: Tool-Agnostic Updates
|
||||
The update command SHALL handle file updates in a predictable and safe manner while respecting team tool choices.
|
||||
|
||||
#### Scenario: Updating files
|
||||
|
||||
- **WHEN** updating files
|
||||
- **THEN** completely replace `openspec/AGENTS.md` with the latest template
|
||||
- **AND** create or update the root-level `AGENTS.md` using the OpenSpec 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 additional tool files beyond the root `AGENTS.md`
|
||||
|
||||
### 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
|
||||
- **AND** ensure the root-level `AGENTS.md` matches the latest template via the marker block
|
||||
- **AND** update existing AI tool configuration files within markers
|
||||
- **AND** display the message: "Updated OpenSpec instructions"
|
||||
@@ -0,0 +1,17 @@
|
||||
# Implementation Tasks
|
||||
|
||||
## 1. Extend Init Workflow
|
||||
- [x] 1.1 Add an "AGENTS.md standard" option to the `openspec init` tool-selection prompt, respecting the existing UI conventions.
|
||||
- [x] 1.2 Generate or refresh a root-level `AGENTS.md` file using the OpenSpec markers when that option is selected, sourcing content from the canonical template.
|
||||
|
||||
## 2. Enhance Update Command
|
||||
- [x] 2.1 Ensure `openspec update` writes the root `AGENTS.md` from the latest template (creating it if missing) alongside `openspec/AGENTS.md`.
|
||||
- [x] 2.2 Update success messaging and logging to reflect creation vs refresh of the AGENTS standard file.
|
||||
|
||||
## 3. Shared Template Handling
|
||||
- [x] 3.1 Refactor template utilities if necessary so both commands reuse the same content without duplication.
|
||||
- [x] 3.2 Add automated tests covering init/update flows for projects with and without an existing `AGENTS.md`, ensuring markers behave correctly.
|
||||
|
||||
## 4. Documentation
|
||||
- [x] 4.1 Update CLI specs and user-facing docs to describe AGENTS standard support.
|
||||
- [x] 4.2 Run `openspec validate add-agents-md-config --strict` and document any notable behavior changes.
|
||||
@@ -0,0 +1,35 @@
|
||||
# Allow Additional AI Tool Initialization After Setup
|
||||
|
||||
## Summary
|
||||
- Let `openspec init` configure new AI coding tools for projects that already contain an OpenSpec structure.
|
||||
- Keep the initialization flow safe by skipping structure creation and only generating files for tools the user explicitly selects.
|
||||
- Provide clear feedback so users know which tool files were added versus already present.
|
||||
|
||||
## Motivation
|
||||
Today `openspec init` exits with an error once an `openspec/` directory exists. That protects the directory layout, but it blocks
|
||||
teams that start with one assistant (for example, Claude Code) and later want to add another such as Cursor. They have to create
|
||||
those files by hand or rerun `init` in a clean clone, which undermines the "easy onboarding" promise. Letting the command extend
|
||||
an existing installation keeps the workflow consistent and avoids manual file management.
|
||||
|
||||
## Proposal
|
||||
1. Detect an existing OpenSpec structure at the start of `openspec init` and branch into an "extend" mode instead of exiting.
|
||||
- Announce that the base structure already exists and that the command will only manage AI tool configuration files.
|
||||
- Keep the existing guard for directories or files we must not overwrite.
|
||||
2. Present the usual AI tool selection prompt even in extend mode, showing which tools are already configured.
|
||||
- Skip disabled options that remain "coming soon".
|
||||
- Mark already configured tools as such so users know whether selecting them will refresh or add files.
|
||||
3. When the user selects additional tools, generate the same initialization files that a fresh run would create (e.g., Cursor
|
||||
workspace files) while leaving untouched tools intact apart from marker-managed sections.
|
||||
- Do nothing when the user selects no new tools and keep the previous error messaging to avoid silently succeeding.
|
||||
4. Summarize the outcome (created, refreshed, skipped) before exiting with code 0 when work was performed.
|
||||
- Include friendly guidance that future updates to shared content still come from `openspec update`.
|
||||
|
||||
## Out of Scope
|
||||
- Changing how `openspec update` discovers or updates AI tool files.
|
||||
- Supporting brand-new AI tools beyond those already wired into the CLI.
|
||||
- Adding non-interactive flags for selecting multiple tools in one run (follow-up if needed).
|
||||
|
||||
## Risks & Mitigations
|
||||
- **User confusion about extend mode** → Explicitly log what will happen before prompting and summarise results afterward.
|
||||
- **Accidental overwrites** → Continue using marker-based updates and skip files unless the user chooses that tool.
|
||||
- **Inconsistent state if init fails mid-run** → Reuse existing rollback/transaction logic so partial writes clean up.
|
||||
@@ -0,0 +1,45 @@
|
||||
## MODIFIED Requirements
|
||||
### Requirement: Safety Checks
|
||||
The command SHALL perform safety checks to prevent overwriting existing structures and ensure proper permissions.
|
||||
|
||||
#### Scenario: Detecting existing initialization
|
||||
- **WHEN** the `openspec/` directory already exists
|
||||
- **THEN** inform the user that OpenSpec is already initialized, skip recreating the base structure, and enter an extend mode
|
||||
- **AND** continue to the AI tool selection step so additional tools can be configured
|
||||
- **AND** display the existing-initialization error message only when the user declines to add any AI tools
|
||||
|
||||
### Requirement: Interactive Mode
|
||||
The command SHALL provide an interactive menu for AI tool selection with clear navigation instructions.
|
||||
|
||||
#### Scenario: Displaying interactive menu
|
||||
- **WHEN** run in fresh or extend mode
|
||||
- **THEN** present a looping select menu that lets users toggle tools with Enter and finish via a "Done" option
|
||||
- **AND** label already configured tools with "(already configured)" while keeping disabled options marked "coming soon"
|
||||
- **AND** change the prompt copy in extend mode to "Which AI tools would you like to add or refresh?"
|
||||
- **AND** display inline instructions clarifying that Enter toggles a tool and selecting "Done" confirms the list
|
||||
|
||||
## ADDED Requirements
|
||||
### Requirement: Additional AI Tool Initialization
|
||||
`openspec init` SHALL allow users to add configuration files for new AI coding assistants after the initial setup.
|
||||
|
||||
#### Scenario: Configuring an extra tool after initial setup
|
||||
- **GIVEN** an `openspec/` directory already exists and at least one AI tool file is present
|
||||
- **WHEN** the user runs `openspec init` and selects a different supported AI tool
|
||||
- **THEN** generate that tool's configuration files with OpenSpec markers the same way as during first-time initialization
|
||||
- **AND** leave existing tool configuration files unchanged except for managed sections that need refreshing
|
||||
- **AND** exit with code 0 and display a success summary highlighting the newly added tool files
|
||||
|
||||
### Requirement: Success Output Enhancements
|
||||
`openspec init` SHALL summarize tool actions when initialization or extend mode completes.
|
||||
|
||||
#### Scenario: Showing tool summary
|
||||
- **WHEN** the command completes successfully
|
||||
- **THEN** display a categorized summary of tools that were created, refreshed, or skipped (including already-configured skips)
|
||||
- **AND** personalize the "Next steps" header using the names of the selected tools, defaulting to a generic label when none remain
|
||||
|
||||
### Requirement: Exit Code Adjustments
|
||||
`openspec init` SHALL treat extend mode with no selected tools as a guarded error.
|
||||
|
||||
#### Scenario: Preventing empty extend runs
|
||||
- **WHEN** OpenSpec is already initialized and the user selects no additional tools
|
||||
- **THEN** exit with code 1 after showing the existing-initialization guidance message
|
||||
@@ -0,0 +1,16 @@
|
||||
# Implementation Tasks
|
||||
|
||||
## 1. Extend Init Guard
|
||||
- [x] 1.1 Detect existing OpenSpec structures at the start of `openspec init` and enter an extend mode instead of failing.
|
||||
- [x] 1.2 Log that core scaffolding will be skipped while still protecting against missing write permissions.
|
||||
|
||||
## 2. Update AI Tool Selection
|
||||
- [x] 2.1 Present AI tool choices even in extend mode, indicating which tools are already configured.
|
||||
- [x] 2.2 Ensure disabled "coming soon" tools remain non-selectable.
|
||||
|
||||
## 3. Generate Additional Tool Files
|
||||
- [x] 3.1 Create configuration files for newly selected tools while leaving untouched tools unaffected apart from marker-managed sections.
|
||||
- [x] 3.2 Summarize created, refreshed, and skipped tools before exiting with the appropriate code.
|
||||
|
||||
## 4. Verification
|
||||
- [x] 4.1 Add tests covering rerunning `openspec init` to add another tool and the scenario where the user declines to add anything.
|
||||
@@ -1,16 +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.
|
||||
- [x] 1.1 Create shared templates for the Proposal, Apply, and Archive commands with instructions for each workflow stage from `openspec/README.md`.
|
||||
- [x] 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`.
|
||||
- [x] 2.1 Generate `.claude/commands/openspec/{proposal,apply,archive}.md` during `openspec init` using shared templates.
|
||||
- [x] 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`.
|
||||
- [x] 3.1 Generate `.cursor/commands/{openspec-proposal,openspec-apply,openspec-archive}.md` during `openspec init` using shared templates.
|
||||
- [x] 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.
|
||||
- [x] 4.1 Add tests verifying slash command files are created and updated correctly.
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
## Why
|
||||
The current `openspec init` flow assumes a single assistant selection and stops once an OpenSpec structure already exists. That makes onboarding feel rigid: teams cannot configure multiple tools in one pass, they do not learn which files were refreshed, and the success copy always references Claude even when other assistants are involved.
|
||||
|
||||
## What Changes
|
||||
- Allow selecting multiple assistants during `openspec init`, including refreshing existing configurations in a single run.
|
||||
- Provide richer onboarding copy that summarizes which tool files were created or refreshed and guides users on next steps for each assistant.
|
||||
- Align generated AI-instruction content and specs so CLAUDE.md and AGENTS.md share the same OpenSpec guidance.
|
||||
- Update specs and tests to cover the multi-select prompt, improved summaries, and extend-mode coordination.
|
||||
|
||||
## Impact
|
||||
- Specs: `cli-init`
|
||||
- Code: `src/core/init.ts`, `src/core/config.ts`, `src/core/templates/*`, `src/core/configurators/*`
|
||||
- Tests: `test/core/init.test.ts`, `test/core/update.test.ts`
|
||||
@@ -0,0 +1,92 @@
|
||||
## MODIFIED Requirements
|
||||
### Requirement: AI Tool Configuration
|
||||
|
||||
The command SHALL configure AI coding assistants with OpenSpec instructions based on user selection.
|
||||
|
||||
#### Scenario: Prompting for AI tool selection
|
||||
|
||||
- **WHEN** run interactively
|
||||
- **THEN** prompt the user with "Which AI tools do you use?" using a multi-select menu
|
||||
- **AND** list every available tool with a checkbox:
|
||||
- Claude Code (creates or refreshes CLAUDE.md and slash commands)
|
||||
- Cursor (creates or refreshes `.cursor/commands/*` slash commands)
|
||||
- AGENTS.md standard (creates or refreshes AGENTS.md with OpenSpec markers)
|
||||
- **AND** show "(already configured)" beside tools whose managed files exist so users understand selections will refresh content
|
||||
- **AND** treat disabled tools as "coming soon" and keep them unselectable
|
||||
- **AND** allow confirming with Enter after selecting one or more tools
|
||||
|
||||
### Requirement: AI Tool Configuration Details
|
||||
|
||||
The command SHALL properly configure selected AI tools with OpenSpec-specific instructions using a marker system.
|
||||
|
||||
#### Scenario: Configuring Claude Code
|
||||
|
||||
- **WHEN** Claude Code is selected
|
||||
- **THEN** create or update `CLAUDE.md` in the project root directory (not inside openspec/)
|
||||
|
||||
#### Scenario: Creating new CLAUDE.md
|
||||
|
||||
- **WHEN** CLAUDE.md does not exist
|
||||
- **THEN** create new file with OpenSpec content wrapped in markers:
|
||||
```markdown
|
||||
<!-- OPENSPEC:START -->
|
||||
# OpenSpec Instructions
|
||||
|
||||
Instructions for AI coding assistants using OpenSpec for spec-driven development.
|
||||
|
||||
## TL;DR Quick Checklist
|
||||
- Search existing work: `openspec spec list --long`, `openspec list`
|
||||
- Decide scope: new capability vs modify existing capability
|
||||
- Pick a unique `change-id`: verb-led kebab-case (`add-`, `update-`, `remove-`, `refactor-`)
|
||||
- Scaffold: `proposal.md`, `tasks.md`, optional `design.md`, and spec deltas
|
||||
- Validate with `openspec validate [change-id] --strict`
|
||||
- Request approval before implementation
|
||||
<!-- OPENSPEC:END -->
|
||||
```
|
||||
|
||||
#### Scenario: Updating existing CLAUDE.md
|
||||
|
||||
- **WHEN** CLAUDE.md already exists
|
||||
- **THEN** preserve all existing content
|
||||
- **AND** insert OpenSpec content at the beginning of the file using markers
|
||||
- **AND** ensure markers don't duplicate if they already exist
|
||||
|
||||
#### Scenario: Managing content with markers
|
||||
|
||||
- **WHEN** using the marker system
|
||||
- **THEN** use `<!-- OPENSPEC:START -->` to mark the beginning of managed content
|
||||
- **AND** use `<!-- OPENSPEC:END -->` to mark the end of managed content
|
||||
- **AND** allow OpenSpec to update its content without affecting user customizations
|
||||
- **AND** preserve all content outside the markers intact
|
||||
|
||||
### Requirement: Interactive Mode
|
||||
|
||||
The command SHALL provide an interactive menu for AI tool selection with clear navigation instructions.
|
||||
|
||||
#### Scenario: Displaying interactive menu
|
||||
|
||||
- **WHEN** run
|
||||
- **THEN** prompt the user with: "Which AI tools do you use?"
|
||||
- **AND** show a checkbox-based multi-select menu with available tools (Claude Code, Cursor, AGENTS.md standard)
|
||||
- **AND** show disabled options as "coming soon" (not selectable)
|
||||
- **AND** display inline help indicating Space toggles selections and Enter confirms
|
||||
|
||||
#### Scenario: Navigating the menu
|
||||
|
||||
- **WHEN** the user is in the menu
|
||||
- **THEN** allow arrow keys to move between options
|
||||
- **AND** allow Spacebar to toggle the highlighted option
|
||||
- **AND** allow Enter key to confirm all current selections
|
||||
|
||||
### Requirement: Success Output
|
||||
|
||||
The command SHALL provide clear, actionable next steps upon successful initialization.
|
||||
|
||||
#### Scenario: Displaying success message
|
||||
|
||||
- **WHEN** initialization completes successfully
|
||||
- **THEN** display a success banner followed by actionable prompts tailored to the selected tools
|
||||
- **AND** summarize which assistant files were created versus refreshed (e.g., `CLAUDE.md (created)`, `.cursor/commands/openspec-apply.md (refreshed)`)
|
||||
- **AND** include copy-pasteable onboarding prompts for each configured assistant, replacing placeholder text ([YOUR FEATURE HERE]) with real guidance to customize
|
||||
- **AND** reference AGENTS.md-compatible assistants when no tool-specific file exists (e.g., when only AGENTS.md standard is selected)
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
## 1. Planning & Spec Updates
|
||||
- [ ] 1.1 Confirm overlap with `add-multi-agent-init` and coordinate extend-mode flow
|
||||
- [ ] 1.2 Update `openspec/specs/cli-init/spec.md` to capture multi-select onboarding requirements
|
||||
|
||||
## 2. Implementation
|
||||
- [ ] 2.1 Add multi-select support to the `openspec init` prompt, including indicators for existing tool configs
|
||||
- [ ] 2.2 Enhance success messaging to summarize created/refreshed assets per tool
|
||||
- [ ] 2.3 Ensure shared instruction template is applied consistently (CLAUDE.md, AGENTS.md, slash commands)
|
||||
|
||||
## 3. Quality
|
||||
- [ ] 3.1 Expand unit tests for init/update flows covering multi-select and summaries
|
||||
- [ ] 3.2 Perform `openspec init` smoke test in a temp directory (document output)
|
||||
@@ -1,22 +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
|
||||
- [x] Rename `openspec/README.md` to `openspec/AGENTS.md`
|
||||
- [x] 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`
|
||||
- [x] Rename `src/core/templates/readme-template.ts` to `agents-template.ts`
|
||||
- [x] 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`
|
||||
- [x] Modify `openspec init` to generate `AGENTS.md`
|
||||
- [x] Update `openspec update` to refresh `AGENTS.md`
|
||||
- [x] 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
|
||||
- [x] Modify `cli-init` spec to reference `AGENTS.md`
|
||||
- [x] Modify `cli-update` spec to reference `AGENTS.md`
|
||||
- [x] Modify `openspec-conventions` spec to include `AGENTS.md` in project structure
|
||||
|
||||
## 5. Validation
|
||||
- [ ] `pnpm test`
|
||||
- [x] `pnpm test`
|
||||
|
||||
@@ -31,7 +31,7 @@ The command SHALL create the complete OpenSpec directory structure with all requ
|
||||
```
|
||||
openspec/
|
||||
├── project.md
|
||||
├── README.md
|
||||
├── AGENTS.md
|
||||
├── specs/
|
||||
└── changes/
|
||||
└── archive/
|
||||
@@ -44,7 +44,7 @@ The command SHALL generate required template files with appropriate content for
|
||||
#### Scenario: Generating template files
|
||||
|
||||
- **WHEN** initializing OpenSpec
|
||||
- **THEN** generate `README.md` containing complete OpenSpec instructions for AI assistants
|
||||
- **THEN** generate `AGENTS.md` containing complete OpenSpec instructions for AI assistants
|
||||
- **AND** generate `project.md` with project context template
|
||||
|
||||
### Requirement: AI Tool Configuration
|
||||
@@ -80,7 +80,7 @@ This document provides instructions for AI coding assistants on how to use OpenS
|
||||
|
||||
This project uses OpenSpec for spec-driven development. Specifications are the source of truth.
|
||||
|
||||
See @openspec/README.md for detailed conventions and guidelines.
|
||||
See @openspec/AGENTS.md for detailed conventions and guidelines.
|
||||
<!-- OPENSPEC:END -->
|
||||
```
|
||||
|
||||
@@ -164,7 +164,7 @@ Next steps - Copy these prompts to Claude:
|
||||
OpenSpec change proposal for this feature"
|
||||
|
||||
3. Learn the OpenSpec workflow:
|
||||
"Please explain the OpenSpec workflow from openspec/README.md
|
||||
"Please explain the OpenSpec workflow from openspec/AGENTS.md
|
||||
and how I should work with you on this project"
|
||||
────────────────────────────────────────────────────────────
|
||||
```
|
||||
|
||||
@@ -13,7 +13,7 @@ The update command SHALL update OpenSpec instruction files to the latest templat
|
||||
- **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)
|
||||
- Replace `openspec/AGENTS.md` with the latest template (complete replacement)
|
||||
- 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
|
||||
@@ -40,7 +40,7 @@ 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
|
||||
- **THEN** completely replace `openspec/AGENTS.md` with the latest template
|
||||
- **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)
|
||||
@@ -64,7 +64,7 @@ The update command SHALL always update the core OpenSpec files and display an AS
|
||||
#### Scenario: Successful update
|
||||
|
||||
- **WHEN** the update completes successfully
|
||||
- **THEN** replace `openspec/README.md` with the latest template
|
||||
- **THEN** replace `openspec/AGENTS.md` with the latest template
|
||||
- **AND** update existing AI tool configuration files within markers
|
||||
- **AND** display the message: "Updated OpenSpec instructions"
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ An OpenSpec project SHALL maintain a consistent directory structure for specific
|
||||
```
|
||||
openspec/
|
||||
├── project.md # Project-specific context
|
||||
├── README.md # AI assistant instructions
|
||||
├── AGENTS.md # AI assistant instructions
|
||||
├── specs/ # Current deployed capabilities
|
||||
│ └── [capability]/ # Single, focused capability
|
||||
│ ├── spec.md # WHAT and WHY
|
||||
@@ -245,7 +245,7 @@ An OpenSpec project SHALL maintain a consistent directory structure for specific
|
||||
```
|
||||
openspec/
|
||||
├── project.md # Project-specific context
|
||||
├── README.md # AI assistant instructions
|
||||
├── AGENTS.md # AI assistant instructions
|
||||
├── specs/ # Current deployed capabilities
|
||||
│ └── [capability]/ # Single, focused capability
|
||||
│ ├── spec.md # WHAT and WHY
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@fission-ai/openspec",
|
||||
"version": "0.1.0",
|
||||
"version": "0.3.0",
|
||||
"description": "AI-native system for spec-driven development",
|
||||
"keywords": [
|
||||
"openspec",
|
||||
@@ -18,8 +18,7 @@
|
||||
"author": "OpenSpec Contributors",
|
||||
"type": "module",
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"tag": "next"
|
||||
"access": "public"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
@@ -60,6 +59,7 @@
|
||||
"vitest": "^3.2.4"
|
||||
},
|
||||
"dependencies": {
|
||||
"@inquirer/core": "^10.2.2",
|
||||
"@inquirer/prompts": "^7.8.0",
|
||||
"chalk": "^5.5.0",
|
||||
"commander": "^14.0.0",
|
||||
|
||||
Generated
+23
-14
@@ -8,6 +8,9 @@ importers:
|
||||
|
||||
.:
|
||||
dependencies:
|
||||
'@inquirer/core':
|
||||
specifier: ^10.2.2
|
||||
version: 10.2.2(@types/node@24.2.0)
|
||||
'@inquirer/prompts':
|
||||
specifier: ^7.8.0
|
||||
version: 7.8.0(@types/node@24.2.0)
|
||||
@@ -257,6 +260,10 @@ packages:
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
'@inquirer/ansi@1.0.0':
|
||||
resolution: {integrity: sha512-JWaTfCxI1eTmJ1BIv86vUfjVatOdxwD0DAVKYevY8SazeUUZtW+tNbsdejVO1GYE0GXJW1N1ahmiC3TFd+7wZA==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
'@inquirer/checkbox@4.2.0':
|
||||
resolution: {integrity: sha512-fdSw07FLJEU5vbpOPzXo5c6xmMGDzbZE2+niuDHX5N6mc6V0Ebso/q3xiHra4D73+PMsC8MJmcaZKuAAoaQsSA==}
|
||||
engines: {node: '>=18'}
|
||||
@@ -275,8 +282,8 @@ packages:
|
||||
'@types/node':
|
||||
optional: true
|
||||
|
||||
'@inquirer/core@10.1.15':
|
||||
resolution: {integrity: sha512-8xrp836RZvKkpNbVvgWUlxjT4CraKk2q+I3Ksy+seI2zkcE+y6wNs1BVhgcv8VyImFecUhdQrYLdW32pAjwBdA==}
|
||||
'@inquirer/core@10.2.2':
|
||||
resolution: {integrity: sha512-yXq/4QUnk4sHMtmbd7irwiepjB8jXU0kkFRL4nr/aDBA2mDz13cMakEWdDwX3eSCTkk03kwcndD1zfRAIlELxA==}
|
||||
engines: {node: '>=18'}
|
||||
peerDependencies:
|
||||
'@types/node': '>=18'
|
||||
@@ -1440,9 +1447,11 @@ snapshots:
|
||||
'@esbuild/win32-x64@0.25.8':
|
||||
optional: true
|
||||
|
||||
'@inquirer/ansi@1.0.0': {}
|
||||
|
||||
'@inquirer/checkbox@4.2.0(@types/node@24.2.0)':
|
||||
dependencies:
|
||||
'@inquirer/core': 10.1.15(@types/node@24.2.0)
|
||||
'@inquirer/core': 10.2.2(@types/node@24.2.0)
|
||||
'@inquirer/figures': 1.0.13
|
||||
'@inquirer/type': 3.0.8(@types/node@24.2.0)
|
||||
ansi-escapes: 4.3.2
|
||||
@@ -1452,16 +1461,16 @@ snapshots:
|
||||
|
||||
'@inquirer/confirm@5.1.14(@types/node@24.2.0)':
|
||||
dependencies:
|
||||
'@inquirer/core': 10.1.15(@types/node@24.2.0)
|
||||
'@inquirer/core': 10.2.2(@types/node@24.2.0)
|
||||
'@inquirer/type': 3.0.8(@types/node@24.2.0)
|
||||
optionalDependencies:
|
||||
'@types/node': 24.2.0
|
||||
|
||||
'@inquirer/core@10.1.15(@types/node@24.2.0)':
|
||||
'@inquirer/core@10.2.2(@types/node@24.2.0)':
|
||||
dependencies:
|
||||
'@inquirer/ansi': 1.0.0
|
||||
'@inquirer/figures': 1.0.13
|
||||
'@inquirer/type': 3.0.8(@types/node@24.2.0)
|
||||
ansi-escapes: 4.3.2
|
||||
cli-width: 4.1.0
|
||||
mute-stream: 2.0.0
|
||||
signal-exit: 4.1.0
|
||||
@@ -1472,7 +1481,7 @@ snapshots:
|
||||
|
||||
'@inquirer/editor@4.2.15(@types/node@24.2.0)':
|
||||
dependencies:
|
||||
'@inquirer/core': 10.1.15(@types/node@24.2.0)
|
||||
'@inquirer/core': 10.2.2(@types/node@24.2.0)
|
||||
'@inquirer/type': 3.0.8(@types/node@24.2.0)
|
||||
external-editor: 3.1.0
|
||||
optionalDependencies:
|
||||
@@ -1480,7 +1489,7 @@ snapshots:
|
||||
|
||||
'@inquirer/expand@4.0.17(@types/node@24.2.0)':
|
||||
dependencies:
|
||||
'@inquirer/core': 10.1.15(@types/node@24.2.0)
|
||||
'@inquirer/core': 10.2.2(@types/node@24.2.0)
|
||||
'@inquirer/type': 3.0.8(@types/node@24.2.0)
|
||||
yoctocolors-cjs: 2.1.2
|
||||
optionalDependencies:
|
||||
@@ -1497,21 +1506,21 @@ snapshots:
|
||||
|
||||
'@inquirer/input@4.2.1(@types/node@24.2.0)':
|
||||
dependencies:
|
||||
'@inquirer/core': 10.1.15(@types/node@24.2.0)
|
||||
'@inquirer/core': 10.2.2(@types/node@24.2.0)
|
||||
'@inquirer/type': 3.0.8(@types/node@24.2.0)
|
||||
optionalDependencies:
|
||||
'@types/node': 24.2.0
|
||||
|
||||
'@inquirer/number@3.0.17(@types/node@24.2.0)':
|
||||
dependencies:
|
||||
'@inquirer/core': 10.1.15(@types/node@24.2.0)
|
||||
'@inquirer/core': 10.2.2(@types/node@24.2.0)
|
||||
'@inquirer/type': 3.0.8(@types/node@24.2.0)
|
||||
optionalDependencies:
|
||||
'@types/node': 24.2.0
|
||||
|
||||
'@inquirer/password@4.0.17(@types/node@24.2.0)':
|
||||
dependencies:
|
||||
'@inquirer/core': 10.1.15(@types/node@24.2.0)
|
||||
'@inquirer/core': 10.2.2(@types/node@24.2.0)
|
||||
'@inquirer/type': 3.0.8(@types/node@24.2.0)
|
||||
ansi-escapes: 4.3.2
|
||||
optionalDependencies:
|
||||
@@ -1534,7 +1543,7 @@ snapshots:
|
||||
|
||||
'@inquirer/rawlist@4.1.5(@types/node@24.2.0)':
|
||||
dependencies:
|
||||
'@inquirer/core': 10.1.15(@types/node@24.2.0)
|
||||
'@inquirer/core': 10.2.2(@types/node@24.2.0)
|
||||
'@inquirer/type': 3.0.8(@types/node@24.2.0)
|
||||
yoctocolors-cjs: 2.1.2
|
||||
optionalDependencies:
|
||||
@@ -1542,7 +1551,7 @@ snapshots:
|
||||
|
||||
'@inquirer/search@3.1.0(@types/node@24.2.0)':
|
||||
dependencies:
|
||||
'@inquirer/core': 10.1.15(@types/node@24.2.0)
|
||||
'@inquirer/core': 10.2.2(@types/node@24.2.0)
|
||||
'@inquirer/figures': 1.0.13
|
||||
'@inquirer/type': 3.0.8(@types/node@24.2.0)
|
||||
yoctocolors-cjs: 2.1.2
|
||||
@@ -1551,7 +1560,7 @@ snapshots:
|
||||
|
||||
'@inquirer/select@4.3.1(@types/node@24.2.0)':
|
||||
dependencies:
|
||||
'@inquirer/core': 10.1.15(@types/node@24.2.0)
|
||||
'@inquirer/core': 10.2.2(@types/node@24.2.0)
|
||||
'@inquirer/figures': 1.0.13
|
||||
'@inquirer/type': 3.0.8(@types/node@24.2.0)
|
||||
ansi-escapes: 4.3.2
|
||||
|
||||
+16
-10
@@ -1,17 +1,23 @@
|
||||
export const OPENSPEC_DIR_NAME = 'openspec';
|
||||
|
||||
export interface OpenSpecConfig {
|
||||
aiTools: string[];
|
||||
}
|
||||
|
||||
export const OPENSPEC_MARKERS = {
|
||||
start: '<!-- OPENSPEC:START -->',
|
||||
end: '<!-- OPENSPEC:END -->'
|
||||
};
|
||||
|
||||
export const AI_TOOLS = [
|
||||
{ name: 'Claude Code', value: 'claude', available: true },
|
||||
{ name: 'Cursor', value: 'cursor', available: false },
|
||||
{ name: 'Aider', value: 'aider', available: false },
|
||||
{ name: 'Continue', value: 'continue', available: false }
|
||||
];
|
||||
export interface OpenSpecConfig {
|
||||
aiTools: string[];
|
||||
}
|
||||
|
||||
export interface AIToolOption {
|
||||
name: string;
|
||||
value: string;
|
||||
available: boolean;
|
||||
successLabel?: string;
|
||||
}
|
||||
|
||||
export const AI_TOOLS: AIToolOption[] = [
|
||||
{ name: 'Claude Code (✅ OpenSpec custom slash commands available)', value: 'claude', available: true, successLabel: 'Claude Code' },
|
||||
{ name: 'Cursor (✅ OpenSpec custom slash commands available)', value: 'cursor', available: true, successLabel: 'Cursor' },
|
||||
{ name: 'AGENTS.md (works with Codex, Amp, Copilot, …)', value: 'agents', available: true, successLabel: 'your AGENTS.md-compatible assistant' }
|
||||
];
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import path from 'path';
|
||||
import { ToolConfigurator } from './base.js';
|
||||
import { FileSystemUtils } from '../../utils/file-system.js';
|
||||
import { TemplateManager } from '../templates/index.js';
|
||||
import { OPENSPEC_MARKERS } from '../config.js';
|
||||
|
||||
export class AgentsStandardConfigurator implements ToolConfigurator {
|
||||
name = 'AGENTS.md standard';
|
||||
configFileName = 'AGENTS.md';
|
||||
isAvailable = true;
|
||||
|
||||
async configure(projectPath: string, _openspecDir: string): Promise<void> {
|
||||
const filePath = path.join(projectPath, this.configFileName);
|
||||
const content = TemplateManager.getAgentsStandardTemplate();
|
||||
|
||||
await FileSystemUtils.updateFileWithMarkers(
|
||||
filePath,
|
||||
content,
|
||||
OPENSPEC_MARKERS.start,
|
||||
OPENSPEC_MARKERS.end
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,16 @@
|
||||
import { ToolConfigurator } from './base.js';
|
||||
import { ClaudeConfigurator } from './claude.js';
|
||||
import { AgentsStandardConfigurator } from './agents.js';
|
||||
|
||||
export class ToolRegistry {
|
||||
private static tools: Map<string, ToolConfigurator> = new Map();
|
||||
|
||||
static {
|
||||
const claudeConfigurator = new ClaudeConfigurator();
|
||||
const agentsConfigurator = new AgentsStandardConfigurator();
|
||||
// Register with the ID that matches the checkbox value
|
||||
this.tools.set('claude', claudeConfigurator);
|
||||
this.tools.set('agents', agentsConfigurator);
|
||||
}
|
||||
|
||||
static register(tool: ToolConfigurator): void {
|
||||
@@ -25,4 +28,4 @@ export class ToolRegistry {
|
||||
static getAvailable(): ToolConfigurator[] {
|
||||
return this.getAll().filter(tool => tool.isAvailable);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import path from 'path';
|
||||
import { FileSystemUtils } from '../../../utils/file-system.js';
|
||||
import { TemplateManager, SlashCommandId } from '../../templates/index.js';
|
||||
import { OPENSPEC_MARKERS } from '../../config.js';
|
||||
|
||||
export interface SlashCommandTarget {
|
||||
id: SlashCommandId;
|
||||
path: string;
|
||||
kind: 'slash';
|
||||
}
|
||||
|
||||
const ALL_COMMANDS: SlashCommandId[] = ['proposal', 'apply', 'archive'];
|
||||
|
||||
export abstract class SlashCommandConfigurator {
|
||||
abstract readonly toolId: string;
|
||||
abstract readonly isAvailable: boolean;
|
||||
|
||||
getTargets(): SlashCommandTarget[] {
|
||||
return ALL_COMMANDS.map((id) => ({
|
||||
id,
|
||||
path: this.getRelativePath(id),
|
||||
kind: 'slash'
|
||||
}));
|
||||
}
|
||||
|
||||
async generateAll(projectPath: string, _openspecDir: string): Promise<string[]> {
|
||||
const createdOrUpdated: string[] = [];
|
||||
|
||||
for (const target of this.getTargets()) {
|
||||
const body = TemplateManager.getSlashCommandBody(target.id).trim();
|
||||
const filePath = path.join(projectPath, target.path);
|
||||
|
||||
if (await FileSystemUtils.fileExists(filePath)) {
|
||||
await this.updateBody(filePath, body);
|
||||
} else {
|
||||
const frontmatter = this.getFrontmatter(target.id);
|
||||
const sections: string[] = [];
|
||||
if (frontmatter) {
|
||||
sections.push(frontmatter.trim());
|
||||
}
|
||||
sections.push(`${OPENSPEC_MARKERS.start}\n${body}\n${OPENSPEC_MARKERS.end}`);
|
||||
const content = sections.join('\n') + '\n';
|
||||
await FileSystemUtils.writeFile(filePath, content);
|
||||
}
|
||||
|
||||
createdOrUpdated.push(target.path);
|
||||
}
|
||||
|
||||
return createdOrUpdated;
|
||||
}
|
||||
|
||||
async updateExisting(projectPath: string, _openspecDir: string): Promise<string[]> {
|
||||
const updated: string[] = [];
|
||||
|
||||
for (const target of this.getTargets()) {
|
||||
const filePath = path.join(projectPath, target.path);
|
||||
if (await FileSystemUtils.fileExists(filePath)) {
|
||||
const body = TemplateManager.getSlashCommandBody(target.id).trim();
|
||||
await this.updateBody(filePath, body);
|
||||
updated.push(target.path);
|
||||
}
|
||||
}
|
||||
|
||||
return updated;
|
||||
}
|
||||
|
||||
protected abstract getRelativePath(id: SlashCommandId): string;
|
||||
protected abstract getFrontmatter(id: SlashCommandId): string | undefined;
|
||||
|
||||
private async updateBody(filePath: string, body: string): Promise<void> {
|
||||
const content = await FileSystemUtils.readFile(filePath);
|
||||
const startIndex = content.indexOf(OPENSPEC_MARKERS.start);
|
||||
const endIndex = content.indexOf(OPENSPEC_MARKERS.end);
|
||||
|
||||
if (startIndex === -1 || endIndex === -1 || endIndex <= startIndex) {
|
||||
throw new Error(`Missing OpenSpec markers in ${filePath}`);
|
||||
}
|
||||
|
||||
const before = content.slice(0, startIndex + OPENSPEC_MARKERS.start.length);
|
||||
const after = content.slice(endIndex);
|
||||
const updatedContent = `${before}\n${body}\n${after}`;
|
||||
|
||||
await FileSystemUtils.writeFile(filePath, updatedContent);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { SlashCommandConfigurator } from './base.js';
|
||||
import { SlashCommandId } from '../../templates/index.js';
|
||||
|
||||
const FILE_PATHS: Record<SlashCommandId, string> = {
|
||||
proposal: '.claude/commands/openspec/proposal.md',
|
||||
apply: '.claude/commands/openspec/apply.md',
|
||||
archive: '.claude/commands/openspec/archive.md'
|
||||
};
|
||||
|
||||
const FRONTMATTER: Record<SlashCommandId, string> = {
|
||||
proposal: `---
|
||||
name: OpenSpec: Proposal
|
||||
description: Scaffold a new OpenSpec change and validate strictly.
|
||||
category: OpenSpec
|
||||
tags: [openspec, change]
|
||||
---`,
|
||||
apply: `---
|
||||
name: OpenSpec: Apply
|
||||
description: Implement an approved OpenSpec change and keep tasks in sync.
|
||||
category: OpenSpec
|
||||
tags: [openspec, apply]
|
||||
---`,
|
||||
archive: `---
|
||||
name: OpenSpec: Archive
|
||||
description: Archive a deployed OpenSpec change and update specs.
|
||||
category: OpenSpec
|
||||
tags: [openspec, archive]
|
||||
---`
|
||||
};
|
||||
|
||||
export class ClaudeSlashCommandConfigurator extends SlashCommandConfigurator {
|
||||
readonly toolId = 'claude';
|
||||
readonly isAvailable = true;
|
||||
|
||||
protected getRelativePath(id: SlashCommandId): string {
|
||||
return FILE_PATHS[id];
|
||||
}
|
||||
|
||||
protected getFrontmatter(id: SlashCommandId): string {
|
||||
return FRONTMATTER[id];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { SlashCommandConfigurator } from './base.js';
|
||||
import { SlashCommandId } from '../../templates/index.js';
|
||||
|
||||
const FILE_PATHS: Record<SlashCommandId, string> = {
|
||||
proposal: '.cursor/commands/openspec-proposal.md',
|
||||
apply: '.cursor/commands/openspec-apply.md',
|
||||
archive: '.cursor/commands/openspec-archive.md'
|
||||
};
|
||||
|
||||
const FRONTMATTER: Record<SlashCommandId, string> = {
|
||||
proposal: `---
|
||||
name: /openspec-proposal
|
||||
id: openspec-proposal
|
||||
category: OpenSpec
|
||||
description: Scaffold a new OpenSpec change and validate strictly.
|
||||
---`,
|
||||
apply: `---
|
||||
name: /openspec-apply
|
||||
id: openspec-apply
|
||||
category: OpenSpec
|
||||
description: Implement an approved OpenSpec change and keep tasks in sync.
|
||||
---`,
|
||||
archive: `---
|
||||
name: /openspec-archive
|
||||
id: openspec-archive
|
||||
category: OpenSpec
|
||||
description: Archive a deployed OpenSpec change and update specs.
|
||||
---`
|
||||
};
|
||||
|
||||
export class CursorSlashCommandConfigurator extends SlashCommandConfigurator {
|
||||
readonly toolId = 'cursor';
|
||||
readonly isAvailable = true;
|
||||
|
||||
protected getRelativePath(id: SlashCommandId): string {
|
||||
return FILE_PATHS[id];
|
||||
}
|
||||
|
||||
protected getFrontmatter(id: SlashCommandId): string {
|
||||
return FRONTMATTER[id];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { SlashCommandConfigurator } from './base.js';
|
||||
import { ClaudeSlashCommandConfigurator } from './claude.js';
|
||||
import { CursorSlashCommandConfigurator } from './cursor.js';
|
||||
|
||||
export class SlashCommandRegistry {
|
||||
private static configurators: Map<string, SlashCommandConfigurator> = new Map();
|
||||
|
||||
static {
|
||||
const claude = new ClaudeSlashCommandConfigurator();
|
||||
const cursor = new CursorSlashCommandConfigurator();
|
||||
|
||||
this.configurators.set(claude.toolId, claude);
|
||||
this.configurators.set(cursor.toolId, cursor);
|
||||
}
|
||||
|
||||
static register(configurator: SlashCommandConfigurator): void {
|
||||
this.configurators.set(configurator.toolId, configurator);
|
||||
}
|
||||
|
||||
static get(toolId: string): SlashCommandConfigurator | undefined {
|
||||
return this.configurators.get(toolId);
|
||||
}
|
||||
|
||||
static getAll(): SlashCommandConfigurator[] {
|
||||
return Array.from(this.configurators.values());
|
||||
}
|
||||
}
|
||||
+472
-55
@@ -1,72 +1,411 @@
|
||||
import path from 'path';
|
||||
import { select } from '@inquirer/prompts';
|
||||
import {
|
||||
createPrompt,
|
||||
isBackspaceKey,
|
||||
isDownKey,
|
||||
isEnterKey,
|
||||
isSpaceKey,
|
||||
isUpKey,
|
||||
useKeypress,
|
||||
usePagination,
|
||||
useState
|
||||
} from '@inquirer/core';
|
||||
import chalk from 'chalk';
|
||||
import ora from 'ora';
|
||||
import { FileSystemUtils } from '../utils/file-system.js';
|
||||
import { TemplateManager, ProjectContext } from './templates/index.js';
|
||||
import { ToolRegistry } from './configurators/registry.js';
|
||||
import { OpenSpecConfig, AI_TOOLS, OPENSPEC_DIR_NAME } from './config.js';
|
||||
import { SlashCommandRegistry } from './configurators/slash/registry.js';
|
||||
import { OpenSpecConfig, AI_TOOLS, OPENSPEC_DIR_NAME, AIToolOption } from './config.js';
|
||||
|
||||
const PROGRESS_SPINNER = {
|
||||
interval: 80,
|
||||
frames: ['░░░', '▒░░', '▒▒░', '▒▒▒', '▓▒▒', '▓▓▒', '▓▓▓', '▒▓▓', '░▒▓']
|
||||
};
|
||||
|
||||
const PALETTE = {
|
||||
white: chalk.hex('#f4f4f4'),
|
||||
lightGray: chalk.hex('#c8c8c8'),
|
||||
midGray: chalk.hex('#8a8a8a'),
|
||||
darkGray: chalk.hex('#4a4a4a')
|
||||
};
|
||||
|
||||
const LETTER_MAP: Record<string, string[]> = {
|
||||
O: [
|
||||
' ████ ',
|
||||
'██ ██',
|
||||
'██ ██',
|
||||
'██ ██',
|
||||
' ████ '
|
||||
],
|
||||
P: [
|
||||
'█████ ',
|
||||
'██ ██',
|
||||
'█████ ',
|
||||
'██ ',
|
||||
'██ '
|
||||
],
|
||||
E: [
|
||||
'██████',
|
||||
'██ ',
|
||||
'█████ ',
|
||||
'██ ',
|
||||
'██████'
|
||||
],
|
||||
N: [
|
||||
'██ ██',
|
||||
'███ ██',
|
||||
'██ ███',
|
||||
'██ ██',
|
||||
'██ ██'
|
||||
],
|
||||
S: [
|
||||
' █████',
|
||||
'██ ',
|
||||
' ████ ',
|
||||
' ██',
|
||||
'█████ '
|
||||
],
|
||||
C: [
|
||||
' █████',
|
||||
'██ ',
|
||||
'██ ',
|
||||
'██ ',
|
||||
' █████'
|
||||
],
|
||||
' ': [
|
||||
' ',
|
||||
' ',
|
||||
' ',
|
||||
' ',
|
||||
' '
|
||||
]
|
||||
};
|
||||
|
||||
type ToolLabel = {
|
||||
primary: string;
|
||||
annotation?: string;
|
||||
};
|
||||
|
||||
const sanitizeToolLabel = (raw: string): string => raw.replace(/✅/gu, '✔').trim();
|
||||
|
||||
const parseToolLabel = (raw: string): ToolLabel => {
|
||||
const sanitized = sanitizeToolLabel(raw);
|
||||
const match = sanitized.match(/^(.*?)\s*\((.+)\)$/u);
|
||||
if (!match) {
|
||||
return { primary: sanitized };
|
||||
}
|
||||
return {
|
||||
primary: match[1].trim(),
|
||||
annotation: match[2].trim()
|
||||
};
|
||||
};
|
||||
|
||||
type ToolWizardChoice = {
|
||||
value: string;
|
||||
label: ToolLabel;
|
||||
configured: boolean;
|
||||
};
|
||||
|
||||
type ToolWizardConfig = {
|
||||
extendMode: boolean;
|
||||
baseMessage: string;
|
||||
choices: ToolWizardChoice[];
|
||||
initialSelected?: string[];
|
||||
};
|
||||
|
||||
type WizardStep = 'intro' | 'select' | 'review';
|
||||
|
||||
type ToolSelectionPrompt = (config: ToolWizardConfig) => Promise<string[]>;
|
||||
|
||||
const toolSelectionWizard = createPrompt<string[], ToolWizardConfig>((config, done) => {
|
||||
const totalSteps = 3;
|
||||
const [step, setStep] = useState<WizardStep>('intro');
|
||||
const [cursor, setCursor] = useState<number>(0);
|
||||
const [selected, setSelected] = useState<string[]>(() => config.initialSelected ?? []);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const selectedSet = new Set(selected);
|
||||
const pageSize = Math.max(Math.min(config.choices.length, 7), 1);
|
||||
|
||||
const updateSelected = (next: Set<string>) => {
|
||||
const ordered = config.choices
|
||||
.map((choice) => choice.value)
|
||||
.filter((value) => next.has(value));
|
||||
setSelected(ordered);
|
||||
};
|
||||
|
||||
const page = usePagination({
|
||||
items: config.choices,
|
||||
active: cursor,
|
||||
pageSize,
|
||||
loop: config.choices.length > 1,
|
||||
renderItem: ({ item, isActive }) => {
|
||||
const isSelected = selectedSet.has(item.value);
|
||||
const cursorSymbol = isActive ? PALETTE.white('›') : PALETTE.midGray(' ');
|
||||
const indicator = isSelected ? PALETTE.white('◉') : PALETTE.midGray('○');
|
||||
const nameColor = isActive ? PALETTE.white : PALETTE.midGray;
|
||||
const label = `${nameColor(item.label.primary)}${item.configured ? PALETTE.midGray(' (already configured)') : ''}`;
|
||||
return `${cursorSymbol} ${indicator} ${label}`;
|
||||
}
|
||||
});
|
||||
|
||||
useKeypress((key) => {
|
||||
if (step === 'intro') {
|
||||
if (isEnterKey(key)) {
|
||||
setStep('select');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (step === 'select') {
|
||||
if (isUpKey(key)) {
|
||||
const previousIndex = cursor <= 0 ? config.choices.length - 1 : cursor - 1;
|
||||
setCursor(previousIndex);
|
||||
setError(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isDownKey(key)) {
|
||||
const nextIndex = cursor >= config.choices.length - 1 ? 0 : cursor + 1;
|
||||
setCursor(nextIndex);
|
||||
setError(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isSpaceKey(key)) {
|
||||
const current = config.choices[cursor];
|
||||
if (!current) return;
|
||||
|
||||
const next = new Set(selected);
|
||||
if (next.has(current.value)) {
|
||||
next.delete(current.value);
|
||||
} else {
|
||||
next.add(current.value);
|
||||
}
|
||||
|
||||
updateSelected(next);
|
||||
setError(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isEnterKey(key)) {
|
||||
if (selected.length === 0) {
|
||||
setError('Select at least one AI tool to continue.');
|
||||
return;
|
||||
}
|
||||
setStep('review');
|
||||
setError(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (key.name === 'escape') {
|
||||
setSelected([]);
|
||||
setError(null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (step === 'review') {
|
||||
if (isEnterKey(key)) {
|
||||
const finalSelection = config.choices
|
||||
.map((choice) => choice.value)
|
||||
.filter((value) => selectedSet.has(value));
|
||||
done(finalSelection);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isBackspaceKey(key) || key.name === 'escape') {
|
||||
setStep('select');
|
||||
setError(null);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const selectedNames = config.choices
|
||||
.filter((choice) => selectedSet.has(choice.value))
|
||||
.map((choice) => choice.label.primary);
|
||||
|
||||
const stepIndex = step === 'intro' ? 1 : step === 'select' ? 2 : 3;
|
||||
const lines: string[] = [];
|
||||
lines.push(PALETTE.midGray(`Step ${stepIndex}/${totalSteps}`));
|
||||
lines.push('');
|
||||
|
||||
if (step === 'intro') {
|
||||
const introHeadline = config.extendMode
|
||||
? 'Extend your OpenSpec tooling'
|
||||
: 'Configure your OpenSpec tooling';
|
||||
const introBody = config.extendMode
|
||||
? 'We detected an existing setup. We will help you refresh or add integrations.'
|
||||
: "Let's get your AI assistants connected so they understand OpenSpec.";
|
||||
|
||||
lines.push(PALETTE.white(introHeadline));
|
||||
lines.push(PALETTE.midGray(introBody));
|
||||
lines.push('');
|
||||
lines.push(PALETTE.midGray('Press Enter to continue.'));
|
||||
} else if (step === 'select') {
|
||||
lines.push(PALETTE.white(config.baseMessage));
|
||||
lines.push(PALETTE.midGray('Use ↑/↓ to move · Space to toggle · Enter to review selections.'));
|
||||
lines.push('');
|
||||
lines.push(page);
|
||||
lines.push('');
|
||||
if (selectedNames.length === 0) {
|
||||
lines.push(`${PALETTE.midGray('Selected')}: ${PALETTE.midGray('None selected yet')}`);
|
||||
} else {
|
||||
lines.push(PALETTE.midGray('Selected:'));
|
||||
selectedNames.forEach((name) => {
|
||||
lines.push(` ${PALETTE.white('-')} ${PALETTE.white(name)}`);
|
||||
});
|
||||
}
|
||||
} else {
|
||||
lines.push(PALETTE.white('Review selections'));
|
||||
lines.push(PALETTE.midGray('Press Enter to confirm or Backspace to adjust.'));
|
||||
lines.push('');
|
||||
|
||||
if (selectedNames.length === 0) {
|
||||
lines.push(PALETTE.midGray('No tools selected. Press Backspace to return.'));
|
||||
} else {
|
||||
selectedNames.forEach((name) => {
|
||||
lines.push(`${PALETTE.white('▌')} ${PALETTE.white(name)}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return [lines.join('\n'), chalk.red(error)];
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
});
|
||||
|
||||
type InitCommandOptions = {
|
||||
prompt?: ToolSelectionPrompt;
|
||||
};
|
||||
|
||||
export class InitCommand {
|
||||
private readonly prompt: ToolSelectionPrompt;
|
||||
|
||||
constructor(options: InitCommandOptions = {}) {
|
||||
this.prompt = options.prompt ?? ((config) => toolSelectionWizard(config));
|
||||
}
|
||||
|
||||
async execute(targetPath: string): Promise<void> {
|
||||
const projectPath = path.resolve(targetPath);
|
||||
const openspecDir = OPENSPEC_DIR_NAME;
|
||||
const openspecPath = path.join(projectPath, openspecDir);
|
||||
|
||||
// Validation happens silently in the background
|
||||
await this.validate(projectPath, openspecPath);
|
||||
const extendMode = await this.validate(projectPath, openspecPath);
|
||||
const existingToolStates = await this.getExistingToolStates(projectPath);
|
||||
|
||||
this.renderBanner(extendMode);
|
||||
|
||||
// Get configuration (after validation to avoid prompts if validation fails)
|
||||
const config = await this.getConfiguration();
|
||||
const config = await this.getConfiguration(existingToolStates, extendMode);
|
||||
|
||||
if (config.aiTools.length === 0) {
|
||||
if (extendMode) {
|
||||
throw new Error(
|
||||
`OpenSpec seems to already be initialized at ${openspecPath}.\n` +
|
||||
`Use 'openspec update' to update the structure.`
|
||||
);
|
||||
}
|
||||
|
||||
throw new Error('You must select at least one AI tool to configure.');
|
||||
}
|
||||
|
||||
const availableTools = AI_TOOLS.filter(tool => tool.available);
|
||||
const selectedIds = new Set(config.aiTools);
|
||||
const selectedTools = availableTools.filter(tool => selectedIds.has(tool.value));
|
||||
const created = selectedTools.filter(tool => !existingToolStates[tool.value]);
|
||||
const refreshed = selectedTools.filter(tool => existingToolStates[tool.value]);
|
||||
const skippedExisting = availableTools.filter(tool => !selectedIds.has(tool.value) && existingToolStates[tool.value]);
|
||||
const skipped = availableTools.filter(tool => !selectedIds.has(tool.value) && !existingToolStates[tool.value]);
|
||||
|
||||
// Step 1: Create directory structure
|
||||
const structureSpinner = ora({ text: 'Creating OpenSpec structure...', stream: process.stdout }).start();
|
||||
await this.createDirectoryStructure(openspecPath);
|
||||
await this.generateFiles(openspecPath, config);
|
||||
structureSpinner.succeed('OpenSpec structure created');
|
||||
if (!extendMode) {
|
||||
const structureSpinner = this.startSpinner('Creating OpenSpec structure...');
|
||||
await this.createDirectoryStructure(openspecPath);
|
||||
await this.generateFiles(openspecPath, config);
|
||||
structureSpinner.stopAndPersist({
|
||||
symbol: PALETTE.white('▌'),
|
||||
text: PALETTE.white('OpenSpec structure created')
|
||||
});
|
||||
} else {
|
||||
ora({ stream: process.stdout }).info(PALETTE.midGray('ℹ OpenSpec already initialized. Skipping base scaffolding.'));
|
||||
}
|
||||
|
||||
// Step 2: Configure AI tools
|
||||
const toolSpinner = ora({ text: 'Configuring AI tools...', stream: process.stdout }).start();
|
||||
const toolSpinner = this.startSpinner('Configuring AI tools...');
|
||||
await this.configureAITools(projectPath, openspecDir, config.aiTools);
|
||||
toolSpinner.succeed('AI tools configured');
|
||||
toolSpinner.stopAndPersist({
|
||||
symbol: PALETTE.white('▌'),
|
||||
text: PALETTE.white('AI tools configured')
|
||||
});
|
||||
|
||||
// Success message
|
||||
this.displaySuccessMessage(openspecDir, config);
|
||||
this.displaySuccessMessage(selectedTools, created, refreshed, skippedExisting, skipped, extendMode);
|
||||
}
|
||||
|
||||
private async validate(projectPath: string, openspecPath: string): Promise<void> {
|
||||
// Check if OpenSpec already exists
|
||||
if (await FileSystemUtils.directoryExists(openspecPath)) {
|
||||
throw new Error(
|
||||
`OpenSpec seems to already be initialized at ${openspecPath}.\n` +
|
||||
`Use 'openspec update' to update the structure.`
|
||||
);
|
||||
}
|
||||
private async validate(projectPath: string, _openspecPath: string): Promise<boolean> {
|
||||
const extendMode = await FileSystemUtils.directoryExists(_openspecPath);
|
||||
|
||||
// Check write permissions
|
||||
if (!await FileSystemUtils.ensureWritePermissions(projectPath)) {
|
||||
throw new Error(`Insufficient permissions to write to ${projectPath}`);
|
||||
}
|
||||
|
||||
return extendMode;
|
||||
}
|
||||
|
||||
private async getConfiguration(): Promise<OpenSpecConfig> {
|
||||
const config: OpenSpecConfig = {
|
||||
aiTools: []
|
||||
};
|
||||
private async getConfiguration(existingTools: Record<string, boolean>, extendMode: boolean): Promise<OpenSpecConfig> {
|
||||
const selectedTools = await this.promptForAITools(existingTools, extendMode);
|
||||
return { aiTools: selectedTools };
|
||||
}
|
||||
|
||||
// Single-select for better UX
|
||||
const selectedTool = await select({
|
||||
message: 'Which AI tool do you use?',
|
||||
choices: AI_TOOLS.map(tool => ({
|
||||
name: tool.available ? tool.name : `${tool.name} (coming soon)`,
|
||||
private async promptForAITools(existingTools: Record<string, boolean>, extendMode: boolean): Promise<string[]> {
|
||||
const availableTools = AI_TOOLS.filter(tool => tool.available);
|
||||
|
||||
if (availableTools.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const baseMessage = extendMode
|
||||
? 'Which AI tools would you like to add or refresh?'
|
||||
: 'Which AI tools do you use?';
|
||||
const initialSelected = extendMode
|
||||
? availableTools.filter(tool => existingTools[tool.value]).map(tool => tool.value)
|
||||
: [];
|
||||
|
||||
return this.prompt({
|
||||
extendMode,
|
||||
baseMessage,
|
||||
choices: availableTools.map((tool) => ({
|
||||
value: tool.value,
|
||||
disabled: !tool.available
|
||||
}))
|
||||
label: parseToolLabel(tool.name),
|
||||
configured: Boolean(existingTools[tool.value])
|
||||
})),
|
||||
initialSelected
|
||||
});
|
||||
|
||||
config.aiTools = [selectedTool as string];
|
||||
}
|
||||
|
||||
return config;
|
||||
private async getExistingToolStates(projectPath: string): Promise<Record<string, boolean>> {
|
||||
const states: Record<string, boolean> = {};
|
||||
for (const tool of AI_TOOLS) {
|
||||
states[tool.value] = await this.isToolConfigured(projectPath, tool.value);
|
||||
}
|
||||
return states;
|
||||
}
|
||||
|
||||
private async isToolConfigured(projectPath: string, toolId: string): Promise<boolean> {
|
||||
const configFile = ToolRegistry.get(toolId)?.configFileName;
|
||||
if (configFile && await FileSystemUtils.fileExists(path.join(projectPath, configFile))) return true;
|
||||
|
||||
const slashConfigurator = SlashCommandRegistry.get(toolId);
|
||||
if (!slashConfigurator) return false;
|
||||
for (const target of slashConfigurator.getTargets()) {
|
||||
if (await FileSystemUtils.fileExists(path.join(projectPath, target.path))) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private async createDirectoryStructure(openspecPath: string): Promise<void> {
|
||||
@@ -105,29 +444,107 @@ export class InitCommand {
|
||||
if (configurator && configurator.isAvailable) {
|
||||
await configurator.configure(projectPath, openspecDir);
|
||||
}
|
||||
|
||||
const slashConfigurator = SlashCommandRegistry.get(toolId);
|
||||
if (slashConfigurator && slashConfigurator.isAvailable) {
|
||||
await slashConfigurator.generateAll(projectPath, openspecDir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private displaySuccessMessage(openspecDir: string, config: OpenSpecConfig): void {
|
||||
private displaySuccessMessage(
|
||||
selectedTools: AIToolOption[],
|
||||
created: AIToolOption[],
|
||||
refreshed: AIToolOption[],
|
||||
skippedExisting: AIToolOption[],
|
||||
skipped: AIToolOption[],
|
||||
extendMode: boolean
|
||||
): void {
|
||||
console.log(); // Empty line for spacing
|
||||
ora().succeed('OpenSpec initialized successfully!');
|
||||
|
||||
// Get the selected tool name for display
|
||||
const selectedToolId = config.aiTools[0];
|
||||
const selectedTool = AI_TOOLS.find(t => t.value === selectedToolId);
|
||||
const toolName = selectedTool ? selectedTool.name : 'your AI assistant';
|
||||
|
||||
console.log(`\nNext steps - Copy these prompts to ${toolName}:\n`);
|
||||
console.log('────────────────────────────────────────────────────────────');
|
||||
console.log('1. Populate your project context:');
|
||||
console.log(' "Please read openspec/project.md and help me fill it out');
|
||||
console.log(' with details about my project, tech stack, and conventions"\n');
|
||||
console.log('2. Create your first change proposal:');
|
||||
console.log(' "I want to add [YOUR FEATURE HERE]. Please create an');
|
||||
console.log(' OpenSpec change proposal for this feature"\n');
|
||||
console.log('3. Learn the OpenSpec workflow:');
|
||||
console.log(' "Please explain the OpenSpec workflow from openspec/README.md');
|
||||
console.log(' and how I should work with you on this project"');
|
||||
console.log('────────────────────────────────────────────────────────────\n');
|
||||
const successHeadline = extendMode
|
||||
? 'OpenSpec tool configuration updated!'
|
||||
: 'OpenSpec initialized successfully!';
|
||||
ora().succeed(PALETTE.white(successHeadline));
|
||||
|
||||
console.log();
|
||||
console.log(PALETTE.lightGray('Tool summary:'));
|
||||
const summaryLines = [
|
||||
created.length ? `${PALETTE.white('▌')} ${PALETTE.white('Created:')} ${this.formatToolNames(created)}` : null,
|
||||
refreshed.length ? `${PALETTE.lightGray('▌')} ${PALETTE.lightGray('Refreshed:')} ${this.formatToolNames(refreshed)}` : null,
|
||||
skippedExisting.length ? `${PALETTE.midGray('▌')} ${PALETTE.midGray('Skipped (already configured):')} ${this.formatToolNames(skippedExisting)}` : null,
|
||||
skipped.length ? `${PALETTE.darkGray('▌')} ${PALETTE.darkGray('Skipped:')} ${this.formatToolNames(skipped)}` : null
|
||||
].filter((line): line is string => Boolean(line));
|
||||
for (const line of summaryLines) {
|
||||
console.log(line);
|
||||
}
|
||||
|
||||
console.log();
|
||||
console.log(PALETTE.midGray('Use `openspec update` to refresh shared OpenSpec instructions in the future.'));
|
||||
|
||||
// Get the selected tool name(s) for display
|
||||
const toolName = this.formatToolNames(selectedTools);
|
||||
|
||||
console.log();
|
||||
console.log(`Next steps - Copy these prompts to ${toolName}:`);
|
||||
console.log(chalk.gray('────────────────────────────────────────────────────────────'));
|
||||
console.log(PALETTE.white('1. Populate your project context:'));
|
||||
console.log(PALETTE.lightGray(' "Please read openspec/project.md and help me fill it out'));
|
||||
console.log(PALETTE.lightGray(' with details about my project, tech stack, and conventions"\n'));
|
||||
console.log(PALETTE.white('2. Create your first change proposal:'));
|
||||
console.log(PALETTE.lightGray(' "I want to add [YOUR FEATURE HERE]. Please create an'));
|
||||
console.log(PALETTE.lightGray(' OpenSpec change proposal for this feature"\n'));
|
||||
console.log(PALETTE.white('3. Learn the OpenSpec workflow:'));
|
||||
console.log(PALETTE.lightGray(' "Please explain the OpenSpec workflow from openspec/AGENTS.md'));
|
||||
console.log(PALETTE.lightGray(' and how I should work with you on this project"'));
|
||||
console.log(PALETTE.darkGray('────────────────────────────────────────────────────────────\n'));
|
||||
}
|
||||
}
|
||||
|
||||
private formatToolNames(tools: AIToolOption[]): string {
|
||||
const names = tools
|
||||
.map((tool) => tool.successLabel ?? tool.name)
|
||||
.filter((name): name is string => Boolean(name));
|
||||
|
||||
if (names.length === 0) return PALETTE.lightGray('your AI assistant');
|
||||
if (names.length === 1) return PALETTE.white(names[0]);
|
||||
|
||||
const base = names.slice(0, -1).map((name) => PALETTE.white(name));
|
||||
const last = PALETTE.white(names[names.length - 1]);
|
||||
|
||||
return `${base.join(PALETTE.midGray(', '))}${base.length ? PALETTE.midGray(', and ') : ''}${last}`;
|
||||
}
|
||||
|
||||
private renderBanner(_extendMode: boolean): void {
|
||||
const rows = ['', '', '', '', ''];
|
||||
for (const char of 'OPENSPEC') {
|
||||
const glyph = LETTER_MAP[char] ?? LETTER_MAP[' '];
|
||||
for (let i = 0; i < rows.length; i += 1) {
|
||||
rows[i] += `${glyph[i]} `;
|
||||
}
|
||||
}
|
||||
|
||||
const rowStyles = [
|
||||
PALETTE.white,
|
||||
PALETTE.lightGray,
|
||||
PALETTE.midGray,
|
||||
PALETTE.lightGray,
|
||||
PALETTE.white
|
||||
];
|
||||
|
||||
console.log();
|
||||
rows.forEach((row, index) => {
|
||||
console.log(rowStyles[index](row.replace(/\s+$/u, '')));
|
||||
});
|
||||
console.log();
|
||||
console.log(PALETTE.white('Welcome to OpenSpec!'));
|
||||
console.log();
|
||||
}
|
||||
|
||||
private startSpinner(text: string) {
|
||||
return ora({
|
||||
text,
|
||||
stream: process.stdout,
|
||||
color: 'gray',
|
||||
spinner: PROGRESS_SPINNER
|
||||
}).start();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export const readmeTemplate = `# OpenSpec Instructions
|
||||
export const agentsTemplate = `# OpenSpec Instructions
|
||||
|
||||
Instructions for AI coding assistants using OpenSpec for spec-driven development.
|
||||
|
||||
@@ -40,20 +40,26 @@ Skip proposal for:
|
||||
- Configuration changes
|
||||
- Tests for existing behavior
|
||||
|
||||
**Workflow**
|
||||
1. Review \`openspec/project.md\`, \`openspec list\`, and \`openspec list --specs\` to understand current context.
|
||||
2. Choose a unique verb-led \`change-id\` and scaffold \`proposal.md\`, \`tasks.md\`, optional \`design.md\`, and spec deltas under \`openspec/changes/<id>/\`.
|
||||
3. Draft spec deltas using \`## ADDED|MODIFIED|REMOVED Requirements\` with at least one \`#### Scenario:\` per requirement.
|
||||
4. Run \`openspec validate <id> --strict\` and resolve any issues before sharing the proposal.
|
||||
|
||||
### 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
|
||||
6. **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
|
||||
- Run \`openspec validate --strict\` to confirm the archived change passes checks
|
||||
|
||||
## Before Any Task
|
||||
|
||||
@@ -1,105 +1 @@
|
||||
export const claudeTemplate = `# OpenSpec Project
|
||||
|
||||
This project uses OpenSpec for spec-driven development. Specifications are the source of truth.
|
||||
|
||||
See @openspec/README.md for detailed conventions and guidelines.
|
||||
|
||||
## Three-Stage Workflow
|
||||
|
||||
### Stage 1: Creating Changes
|
||||
Create proposal for: features, breaking changes, architecture changes
|
||||
Skip proposal for: bug fixes, typos, non-breaking updates
|
||||
|
||||
### Stage 2: Implementing Changes
|
||||
1. Read proposal.md to understand the change
|
||||
2. Read design.md if it exists for technical context
|
||||
3. Read tasks.md for implementation checklist
|
||||
4. Complete tasks one by one
|
||||
5. Mark each task complete immediately: \`- [x]\`
|
||||
6. Validate strictly: \`openspec validate [change] --strict\`
|
||||
7. Approval gate: Do not start implementation until the proposal is approved
|
||||
|
||||
### Stage 3: Archiving
|
||||
After deployment, use \`openspec archive [change]\` (add \`--skip-specs\` for tooling-only changes)
|
||||
|
||||
## Before Any Task
|
||||
|
||||
**Always:**
|
||||
- Check existing specs: \`openspec list --specs\`
|
||||
- Check active changes: \`openspec list\`
|
||||
- Read relevant specs before creating new ones
|
||||
- Prefer modifying existing specs over creating duplicates
|
||||
|
||||
## CLI Quick Reference
|
||||
|
||||
\`\`\`bash
|
||||
# Essential
|
||||
openspec list # Active changes
|
||||
openspec list --specs # Existing specifications
|
||||
openspec show [item] # View details
|
||||
openspec validate --strict # Validate thoroughly
|
||||
openspec archive [change] # Archive after deployment
|
||||
|
||||
# Interactive
|
||||
openspec show # Prompts for selection
|
||||
openspec validate # Bulk validation
|
||||
|
||||
# Debugging
|
||||
openspec show [change] --json --deltas-only
|
||||
\`\`\`
|
||||
|
||||
## Creating Changes
|
||||
|
||||
1. **Directory:** \`changes/[change-id]/\`
|
||||
- Change ID naming: kebab-case, verb-led (\`add-\`, \`update-\`, \`remove-\`, \`refactor-\`), unique (append \`-2\`, \`-3\` if needed)
|
||||
2. **Files:**
|
||||
- \`proposal.md\` - Why, what, impact
|
||||
- \`tasks.md\` - Implementation checklist
|
||||
- \`design.md\` - Only if needed (cross-cutting, new deps/data model, security/perf/migration complexity, or high ambiguity)
|
||||
- \`specs/[capability]/spec.md\` - Delta changes (ADDED/MODIFIED/REMOVED). For multiple capabilities, include multiple files.
|
||||
3. **If ambiguous:** ask 1–2 clarifying questions before scaffolding
|
||||
|
||||
## Search Guidance
|
||||
- Enumerate specs: \`openspec spec list --long\` (or \`--json\`)
|
||||
- Enumerate changes: \`openspec list\`
|
||||
- Show details: \`openspec show <spec-id> --type spec\`, \`openspec show <change-id> --json --deltas-only\`
|
||||
- Full-text search (use ripgrep): \`rg -n "Requirement:|Scenario:" openspec/specs\`
|
||||
|
||||
## Critical: Scenario Format
|
||||
|
||||
**CORRECT:**
|
||||
\`\`\`markdown
|
||||
#### Scenario: User login
|
||||
- **WHEN** valid credentials
|
||||
- **THEN** return token
|
||||
\`\`\`
|
||||
|
||||
**WRONG:** Using bullets (- **Scenario**), bold (**Scenario:**), or ### headers
|
||||
|
||||
Every requirement MUST have scenarios using \`#### Scenario:\` format.
|
||||
|
||||
## Complexity Management
|
||||
|
||||
**Default to minimal:**
|
||||
- <100 lines of new code
|
||||
- Single-file implementations
|
||||
- No frameworks without justification
|
||||
- Boring, proven patterns
|
||||
|
||||
**Only add complexity with:**
|
||||
- Performance data showing need
|
||||
- Concrete scale requirements (>1000 users)
|
||||
- Multiple proven use cases
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**"Change must have at least one delta"**
|
||||
- Check \`changes/[name]/specs/\` exists
|
||||
- Verify operation prefixes (## ADDED Requirements)
|
||||
|
||||
**"Requirement must have at least one scenario"**
|
||||
- Use \`#### Scenario:\` format (4 hashtags)
|
||||
- Don't use bullets or bold
|
||||
|
||||
**Debug:** \`openspec show [change] --json --deltas-only\`
|
||||
`;
|
||||
export { agentsTemplate as claudeTemplate } from './agents-template.js';
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { readmeTemplate } from './readme-template.js';
|
||||
import { agentsTemplate } from './agents-template.js';
|
||||
import { projectTemplate, ProjectContext } from './project-template.js';
|
||||
import { claudeTemplate } from './claude-template.js';
|
||||
import { getSlashCommandBody, SlashCommandId } from './slash-command-templates.js';
|
||||
|
||||
export interface Template {
|
||||
path: string;
|
||||
@@ -11,8 +12,8 @@ export class TemplateManager {
|
||||
static getTemplates(context: ProjectContext = {}): Template[] {
|
||||
return [
|
||||
{
|
||||
path: 'README.md',
|
||||
content: readmeTemplate
|
||||
path: 'AGENTS.md',
|
||||
content: agentsTemplate
|
||||
},
|
||||
{
|
||||
path: 'project.md',
|
||||
@@ -24,6 +25,15 @@ export class TemplateManager {
|
||||
static getClaudeTemplate(): string {
|
||||
return claudeTemplate;
|
||||
}
|
||||
|
||||
static getAgentsStandardTemplate(): string {
|
||||
return agentsTemplate;
|
||||
}
|
||||
|
||||
static getSlashCommandBody(id: SlashCommandId): string {
|
||||
return getSlashCommandBody(id);
|
||||
}
|
||||
}
|
||||
|
||||
export { ProjectContext } from './project-template.js';
|
||||
export { ProjectContext } from './project-template.js';
|
||||
export type { SlashCommandId } from './slash-command-templates.js';
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
export type SlashCommandId = 'proposal' | 'apply' | 'archive';
|
||||
|
||||
const baseGuardrails = `**Guardrails**
|
||||
- Favor straightforward, minimal implementations first and add complexity only when it is requested or clearly required.
|
||||
- Keep changes tightly scoped to the requested outcome.
|
||||
- Refer to \`openspec/AGENTS.md\` if you need additional OpenSpec conventions or clarifications.`;
|
||||
|
||||
const proposalGuardrails = `${baseGuardrails}\n- Identify any vague or ambiguous details and ask the necessary follow-up questions before editing files.`;
|
||||
|
||||
const proposalSteps = `**Steps**
|
||||
1. Review \`openspec/project.md\`, run \`openspec list\` and \`openspec list --specs\`, and inspect related code or docs (e.g., via \`rg\`/\`ls\`) to ground the proposal in current behaviour; note any gaps that require clarification.
|
||||
2. Choose a unique verb-led \`change-id\` and scaffold \`proposal.md\`, \`tasks.md\`, and \`design.md\` (when needed) under \`openspec/changes/<id>/\`.
|
||||
3. Map the change into concrete capabilities or requirements, breaking multi-scope efforts into distinct spec deltas with clear relationships and sequencing.
|
||||
4. Capture architectural reasoning in \`design.md\` when the solution spans multiple systems, introduces new patterns, or demands trade-off discussion before committing to specs.
|
||||
5. Draft spec deltas in \`changes/<id>/specs/\` using \`## ADDED|MODIFIED|REMOVED Requirements\` with at least one \`#### Scenario:\` per requirement and cross-reference related capabilities when relevant.
|
||||
6. Draft \`tasks.md\` as an ordered list of small, verifiable work items that deliver user-visible progress, include validation (tests, tooling), and highlight dependencies or parallelizable work.
|
||||
7. Validate with \`openspec validate <id> --strict\` and resolve every issue before sharing the proposal.`;
|
||||
|
||||
const proposalReferences = `**Reference**
|
||||
- Use \`openspec show <id> --json --deltas-only\` or \`openspec show <spec> --type spec\` to inspect details when validation fails.
|
||||
- Search existing requirements with \`rg -n "Requirement:|Scenario:" openspec/specs\` before writing new ones.
|
||||
- Explore the codebase with \`rg <keyword>\`, \`ls\`, or direct file reads so proposals align with current implementation realities.`;
|
||||
|
||||
const applySteps = `**Steps**
|
||||
1. Read \`changes/<id>/proposal.md\`, \`design.md\` (if present), and \`tasks.md\` to confirm scope and acceptance criteria.
|
||||
2. Work through tasks sequentially, keeping edits minimal and focused on the requested change.
|
||||
3. Mark each task \`- [x]\` immediately after completing it to keep the checklist in sync.
|
||||
4. Reference \`openspec list\` or \`openspec show <item>\` when additional context is required.`;
|
||||
|
||||
const applyReferences = `**Reference**
|
||||
- Use \`openspec show <id> --json --deltas-only\` if you need additional context from the proposal while implementing.`;
|
||||
|
||||
const archiveSteps = `**Steps**
|
||||
1. Identify the requested change ID (via the prompt or \`openspec list\`).
|
||||
2. Run \`openspec archive <id>\` to let the CLI move the change and apply spec updates (use \`--skip-specs\` only for tooling-only work).
|
||||
3. Review the command output to confirm the target specs were updated and the change landed in \`changes/archive/\`.
|
||||
4. Validate with \`openspec validate --strict\` and inspect with \`openspec show <id>\` if anything looks off.`;
|
||||
|
||||
const archiveReferences = `**Reference**
|
||||
- Inspect refreshed specs with \`openspec list --specs\` and address any validation issues before handing off.`;
|
||||
|
||||
export const slashCommandBodies: Record<SlashCommandId, string> = {
|
||||
proposal: [proposalGuardrails, proposalSteps, proposalReferences].join('\n\n'),
|
||||
apply: [baseGuardrails, applySteps, applyReferences].join('\n\n'),
|
||||
archive: [baseGuardrails, archiveSteps, archiveReferences].join('\n\n')
|
||||
};
|
||||
|
||||
export function getSlashCommandBody(id: SlashCommandId): string {
|
||||
return slashCommandBodies[id];
|
||||
}
|
||||
+51
-6
@@ -1,8 +1,10 @@
|
||||
import path from 'path';
|
||||
import { FileSystemUtils } from '../utils/file-system.js';
|
||||
import { OPENSPEC_DIR_NAME } from './config.js';
|
||||
import { readmeTemplate } from './templates/readme-template.js';
|
||||
import { OPENSPEC_DIR_NAME, OPENSPEC_MARKERS } from './config.js';
|
||||
import { agentsTemplate } from './templates/agents-template.js';
|
||||
import { TemplateManager } from './templates/index.js';
|
||||
import { ToolRegistry } from './configurators/registry.js';
|
||||
import { SlashCommandRegistry } from './configurators/slash/registry.js';
|
||||
|
||||
export class UpdateCommand {
|
||||
async execute(projectPath: string): Promise<void> {
|
||||
@@ -15,14 +17,27 @@ export class UpdateCommand {
|
||||
throw new Error(`No OpenSpec directory found. Run 'openspec init' first.`);
|
||||
}
|
||||
|
||||
// 2. Update README.md (full replacement)
|
||||
const readmePath = path.join(openspecPath, 'README.md');
|
||||
await FileSystemUtils.writeFile(readmePath, readmeTemplate);
|
||||
// 2. Update AGENTS.md (full replacement)
|
||||
const agentsPath = path.join(openspecPath, 'AGENTS.md');
|
||||
const rootAgentsPath = path.join(resolvedProjectPath, 'AGENTS.md');
|
||||
const rootAgentsExisted = await FileSystemUtils.fileExists(rootAgentsPath);
|
||||
|
||||
await FileSystemUtils.writeFile(agentsPath, agentsTemplate);
|
||||
const agentsStandardContent = TemplateManager.getAgentsStandardTemplate();
|
||||
await FileSystemUtils.updateFileWithMarkers(
|
||||
rootAgentsPath,
|
||||
agentsStandardContent,
|
||||
OPENSPEC_MARKERS.start,
|
||||
OPENSPEC_MARKERS.end
|
||||
);
|
||||
|
||||
// 3. Update existing AI tool configuration files only
|
||||
const configurators = ToolRegistry.getAll();
|
||||
const slashConfigurators = SlashCommandRegistry.getAll();
|
||||
let updatedFiles: string[] = [];
|
||||
let failedFiles: string[] = [];
|
||||
let updatedSlashFiles: string[] = [];
|
||||
let failedSlashTools: string[] = [];
|
||||
|
||||
for (const configurator of configurators) {
|
||||
const configFilePath = path.join(resolvedProjectPath, configurator.configFileName);
|
||||
@@ -30,6 +45,9 @@ export class UpdateCommand {
|
||||
// Only update if the file already exists
|
||||
if (await FileSystemUtils.fileExists(configFilePath)) {
|
||||
try {
|
||||
if (!await FileSystemUtils.canWriteFile(configFilePath)) {
|
||||
throw new Error(`Insufficient permissions to modify ${configurator.configFileName}`);
|
||||
}
|
||||
await configurator.configure(resolvedProjectPath, openspecPath);
|
||||
updatedFiles.push(configurator.configFileName);
|
||||
} catch (error) {
|
||||
@@ -39,16 +57,43 @@ export class UpdateCommand {
|
||||
}
|
||||
}
|
||||
|
||||
for (const slashConfigurator of slashConfigurators) {
|
||||
if (!slashConfigurator.isAvailable) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const updated = await slashConfigurator.updateExisting(resolvedProjectPath, openspecPath);
|
||||
updatedSlashFiles = updatedSlashFiles.concat(updated);
|
||||
} catch (error) {
|
||||
failedSlashTools.push(slashConfigurator.toolId);
|
||||
console.error(
|
||||
`Failed to update slash commands for ${slashConfigurator.toolId}: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Success message (ASCII-safe)
|
||||
const messages: string[] = ['Updated OpenSpec instructions (README.md)'];
|
||||
const instructionUpdates = ['openspec/AGENTS.md'];
|
||||
instructionUpdates.push(`AGENTS.md${rootAgentsExisted ? '' : ' (created)'}`);
|
||||
|
||||
const messages: string[] = [`Updated OpenSpec instructions (${instructionUpdates.join(', ')})`];
|
||||
|
||||
if (updatedFiles.length > 0) {
|
||||
messages.push(`Updated AI tool files: ${updatedFiles.join(', ')}`);
|
||||
}
|
||||
|
||||
if (updatedSlashFiles.length > 0) {
|
||||
messages.push(`Updated slash commands: ${updatedSlashFiles.join(', ')}`);
|
||||
}
|
||||
|
||||
if (failedFiles.length > 0) {
|
||||
messages.push(`Failed to update: ${failedFiles.join(', ')}`);
|
||||
}
|
||||
|
||||
if (failedSlashTools.length > 0) {
|
||||
messages.push(`Failed slash command updates: ${failedSlashTools.join(', ')}`);
|
||||
}
|
||||
|
||||
console.log(messages.join('\n'));
|
||||
}
|
||||
|
||||
@@ -18,6 +18,25 @@ export class FileSystemUtils {
|
||||
}
|
||||
}
|
||||
|
||||
static async canWriteFile(filePath: string): Promise<boolean> {
|
||||
try {
|
||||
const stats = await fs.stat(filePath);
|
||||
|
||||
if (!stats.isFile()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (stats.mode & 0o222) !== 0;
|
||||
} catch (error: any) {
|
||||
if (error.code === 'ENOENT') {
|
||||
return true;
|
||||
}
|
||||
|
||||
console.debug(`Unable to determine write permissions for ${filePath}: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static async directoryExists(dirPath: string): Promise<boolean> {
|
||||
try {
|
||||
const stats = await fs.stat(dirPath);
|
||||
|
||||
+159
-36
@@ -3,11 +3,35 @@ import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import { InitCommand } from '../../src/core/init.js';
|
||||
import * as prompts from '@inquirer/prompts';
|
||||
|
||||
vi.mock('@inquirer/prompts', () => ({
|
||||
select: vi.fn()
|
||||
}));
|
||||
const DONE = '__done__';
|
||||
|
||||
type SelectionQueue = string[][];
|
||||
|
||||
let selectionQueue: SelectionQueue = [];
|
||||
|
||||
const mockPrompt = vi.fn(async () => {
|
||||
if (selectionQueue.length === 0) {
|
||||
throw new Error('No queued selections provided to init prompt.');
|
||||
}
|
||||
return selectionQueue.shift() ?? [];
|
||||
});
|
||||
|
||||
function queueSelections(...values: string[]) {
|
||||
let current: string[] = [];
|
||||
values.forEach((value) => {
|
||||
if (value === DONE) {
|
||||
selectionQueue.push(current);
|
||||
current = [];
|
||||
} else {
|
||||
current.push(value);
|
||||
}
|
||||
});
|
||||
|
||||
if (current.length > 0) {
|
||||
selectionQueue.push(current);
|
||||
}
|
||||
}
|
||||
|
||||
describe('InitCommand', () => {
|
||||
let testDir: string;
|
||||
@@ -16,7 +40,9 @@ describe('InitCommand', () => {
|
||||
beforeEach(async () => {
|
||||
testDir = path.join(os.tmpdir(), `openspec-init-test-${Date.now()}`);
|
||||
await fs.mkdir(testDir, { recursive: true });
|
||||
initCommand = new InitCommand();
|
||||
selectionQueue = [];
|
||||
mockPrompt.mockReset();
|
||||
initCommand = new InitCommand({ prompt: mockPrompt });
|
||||
|
||||
// Mock console.log to suppress output during tests
|
||||
vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
@@ -29,7 +55,7 @@ describe('InitCommand', () => {
|
||||
|
||||
describe('execute', () => {
|
||||
it('should create OpenSpec directory structure', async () => {
|
||||
vi.mocked(prompts.select).mockResolvedValue('claude');
|
||||
queueSelections('claude', DONE);
|
||||
|
||||
await initCommand.execute(testDir);
|
||||
|
||||
@@ -40,24 +66,24 @@ describe('InitCommand', () => {
|
||||
expect(await directoryExists(path.join(openspecPath, 'changes', 'archive'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should create README.md and project.md', async () => {
|
||||
vi.mocked(prompts.select).mockResolvedValue('claude');
|
||||
|
||||
it('should create AGENTS.md and project.md', async () => {
|
||||
queueSelections('claude', DONE);
|
||||
|
||||
await initCommand.execute(testDir);
|
||||
|
||||
|
||||
const openspecPath = path.join(testDir, 'openspec');
|
||||
expect(await fileExists(path.join(openspecPath, 'README.md'))).toBe(true);
|
||||
expect(await fileExists(path.join(openspecPath, 'AGENTS.md'))).toBe(true);
|
||||
expect(await fileExists(path.join(openspecPath, 'project.md'))).toBe(true);
|
||||
|
||||
const readmeContent = await fs.readFile(path.join(openspecPath, 'README.md'), 'utf-8');
|
||||
expect(readmeContent).toContain('OpenSpec Instructions');
|
||||
|
||||
const agentsContent = await fs.readFile(path.join(openspecPath, 'AGENTS.md'), 'utf-8');
|
||||
expect(agentsContent).toContain('OpenSpec Instructions');
|
||||
|
||||
const projectContent = await fs.readFile(path.join(openspecPath, 'project.md'), 'utf-8');
|
||||
expect(projectContent).toContain('Project Context');
|
||||
});
|
||||
|
||||
it('should create CLAUDE.md when Claude Code is selected', async () => {
|
||||
vi.mocked(prompts.select).mockResolvedValue('claude');
|
||||
queueSelections('claude', DONE);
|
||||
|
||||
await initCommand.execute(testDir);
|
||||
|
||||
@@ -66,12 +92,12 @@ describe('InitCommand', () => {
|
||||
|
||||
const content = await fs.readFile(claudePath, 'utf-8');
|
||||
expect(content).toContain('<!-- OPENSPEC:START -->');
|
||||
expect(content).toContain('OpenSpec Project');
|
||||
expect(content).toContain('OpenSpec Instructions');
|
||||
expect(content).toContain('<!-- OPENSPEC:END -->');
|
||||
});
|
||||
|
||||
it('should update existing CLAUDE.md with markers', async () => {
|
||||
vi.mocked(prompts.select).mockResolvedValue('claude');
|
||||
queueSelections('claude', DONE);
|
||||
|
||||
const claudePath = path.join(testDir, 'CLAUDE.md');
|
||||
const existingContent = '# My Project Instructions\nCustom instructions here';
|
||||
@@ -81,22 +107,99 @@ describe('InitCommand', () => {
|
||||
|
||||
const updatedContent = await fs.readFile(claudePath, 'utf-8');
|
||||
expect(updatedContent).toContain('<!-- OPENSPEC:START -->');
|
||||
expect(updatedContent).toContain('OpenSpec Project');
|
||||
expect(updatedContent).toContain('OpenSpec Instructions');
|
||||
expect(updatedContent).toContain('<!-- OPENSPEC:END -->');
|
||||
expect(updatedContent).toContain('Custom instructions here');
|
||||
});
|
||||
|
||||
it('should throw error if OpenSpec already exists', async () => {
|
||||
const openspecPath = path.join(testDir, 'openspec');
|
||||
await fs.mkdir(openspecPath, { recursive: true });
|
||||
|
||||
await expect(initCommand.execute(testDir)).rejects.toThrow(
|
||||
/OpenSpec seems to already be initialized/
|
||||
);
|
||||
it('should create AGENTS.md in project root when AGENTS standard is selected', async () => {
|
||||
queueSelections('agents', DONE);
|
||||
|
||||
await initCommand.execute(testDir);
|
||||
|
||||
const rootAgentsPath = path.join(testDir, 'AGENTS.md');
|
||||
expect(await fileExists(rootAgentsPath)).toBe(true);
|
||||
|
||||
const content = await fs.readFile(rootAgentsPath, 'utf-8');
|
||||
expect(content).toContain('<!-- OPENSPEC:START -->');
|
||||
expect(content).toContain('OpenSpec Instructions');
|
||||
expect(content).toContain('<!-- OPENSPEC:END -->');
|
||||
|
||||
const claudeExists = await fileExists(path.join(testDir, 'CLAUDE.md'));
|
||||
expect(claudeExists).toBe(false);
|
||||
});
|
||||
|
||||
it('should create Claude slash command files with templates', async () => {
|
||||
queueSelections('claude', DONE);
|
||||
|
||||
await initCommand.execute(testDir);
|
||||
|
||||
const claudeProposal = path.join(testDir, '.claude/commands/openspec/proposal.md');
|
||||
const claudeApply = path.join(testDir, '.claude/commands/openspec/apply.md');
|
||||
const claudeArchive = path.join(testDir, '.claude/commands/openspec/archive.md');
|
||||
|
||||
expect(await fileExists(claudeProposal)).toBe(true);
|
||||
expect(await fileExists(claudeApply)).toBe(true);
|
||||
expect(await fileExists(claudeArchive)).toBe(true);
|
||||
|
||||
const proposalContent = await fs.readFile(claudeProposal, 'utf-8');
|
||||
expect(proposalContent).toContain('name: OpenSpec: Proposal');
|
||||
expect(proposalContent).toContain('<!-- OPENSPEC:START -->');
|
||||
expect(proposalContent).toContain('**Guardrails**');
|
||||
|
||||
const applyContent = await fs.readFile(claudeApply, 'utf-8');
|
||||
expect(applyContent).toContain('name: OpenSpec: Apply');
|
||||
expect(applyContent).toContain('Work through tasks sequentially');
|
||||
|
||||
const archiveContent = await fs.readFile(claudeArchive, 'utf-8');
|
||||
expect(archiveContent).toContain('name: OpenSpec: Archive');
|
||||
expect(archiveContent).toContain('openspec archive <id>');
|
||||
expect(archiveContent).toContain('`--skip-specs` only for tooling-only work');
|
||||
});
|
||||
|
||||
it('should create Cursor slash command files with templates', async () => {
|
||||
queueSelections('cursor', DONE);
|
||||
|
||||
await initCommand.execute(testDir);
|
||||
|
||||
const cursorProposal = path.join(testDir, '.cursor/commands/openspec-proposal.md');
|
||||
const cursorApply = path.join(testDir, '.cursor/commands/openspec-apply.md');
|
||||
const cursorArchive = path.join(testDir, '.cursor/commands/openspec-archive.md');
|
||||
|
||||
expect(await fileExists(cursorProposal)).toBe(true);
|
||||
expect(await fileExists(cursorApply)).toBe(true);
|
||||
expect(await fileExists(cursorArchive)).toBe(true);
|
||||
|
||||
const proposalContent = await fs.readFile(cursorProposal, 'utf-8');
|
||||
expect(proposalContent).toContain('name: /openspec-proposal');
|
||||
expect(proposalContent).toContain('<!-- OPENSPEC:END -->');
|
||||
|
||||
const applyContent = await fs.readFile(cursorApply, 'utf-8');
|
||||
expect(applyContent).toContain('id: openspec-apply');
|
||||
expect(applyContent).toContain('Work through tasks sequentially');
|
||||
|
||||
const archiveContent = await fs.readFile(cursorArchive, 'utf-8');
|
||||
expect(archiveContent).toContain('name: /openspec-archive');
|
||||
expect(archiveContent).toContain('openspec list --specs');
|
||||
});
|
||||
|
||||
it('should add new tool when OpenSpec already exists', async () => {
|
||||
queueSelections('claude', DONE, 'cursor', DONE);
|
||||
await initCommand.execute(testDir);
|
||||
await initCommand.execute(testDir);
|
||||
|
||||
const cursorProposal = path.join(testDir, '.cursor/commands/openspec-proposal.md');
|
||||
expect(await fileExists(cursorProposal)).toBe(true);
|
||||
});
|
||||
|
||||
it('should error when extend mode selects no tools', async () => {
|
||||
queueSelections('claude', DONE, DONE);
|
||||
await initCommand.execute(testDir);
|
||||
await expect(initCommand.execute(testDir)).rejects.toThrow(/OpenSpec seems to already be initialized/);
|
||||
});
|
||||
|
||||
it('should handle non-existent target directory', async () => {
|
||||
vi.mocked(prompts.select).mockResolvedValue('claude');
|
||||
queueSelections('claude', DONE);
|
||||
|
||||
const newDir = path.join(testDir, 'new-project');
|
||||
await initCommand.execute(newDir);
|
||||
@@ -106,7 +209,7 @@ describe('InitCommand', () => {
|
||||
});
|
||||
|
||||
it('should display success message with selected tool name', async () => {
|
||||
vi.mocked(prompts.select).mockResolvedValue('claude');
|
||||
queueSelections('claude', DONE);
|
||||
const logSpy = vi.spyOn(console, 'log');
|
||||
|
||||
await initCommand.execute(testDir);
|
||||
@@ -114,32 +217,51 @@ describe('InitCommand', () => {
|
||||
const calls = logSpy.mock.calls.flat().join('\n');
|
||||
expect(calls).toContain('Copy these prompts to Claude Code');
|
||||
});
|
||||
|
||||
it('should reference AGENTS compatible assistants in success message', async () => {
|
||||
queueSelections('agents', DONE);
|
||||
const logSpy = vi.spyOn(console, 'log');
|
||||
|
||||
await initCommand.execute(testDir);
|
||||
|
||||
const calls = logSpy.mock.calls.flat().join('\n');
|
||||
expect(calls).toContain('Copy these prompts to your AGENTS.md-compatible assistant');
|
||||
});
|
||||
});
|
||||
|
||||
describe('AI tool selection', () => {
|
||||
it('should prompt for AI tool selection', async () => {
|
||||
const selectMock = vi.mocked(prompts.select);
|
||||
selectMock.mockResolvedValue('claude');
|
||||
|
||||
queueSelections('claude', DONE);
|
||||
|
||||
await initCommand.execute(testDir);
|
||||
|
||||
expect(selectMock).toHaveBeenCalledWith(
|
||||
|
||||
expect(mockPrompt).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
message: 'Which AI tool do you use?'
|
||||
baseMessage: expect.stringContaining('Which AI tools do you use?')
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle different AI tool selections', async () => {
|
||||
// For now, only Claude is available, but test the structure
|
||||
vi.mocked(prompts.select).mockResolvedValue('claude');
|
||||
|
||||
queueSelections('claude', DONE);
|
||||
|
||||
await initCommand.execute(testDir);
|
||||
|
||||
// When other tools are added, we'd test their specific configurations here
|
||||
const claudePath = path.join(testDir, 'CLAUDE.md');
|
||||
expect(await fileExists(claudePath)).toBe(true);
|
||||
});
|
||||
|
||||
it('should mark existing tools as already configured during extend mode', async () => {
|
||||
queueSelections('claude', DONE, 'cursor', DONE);
|
||||
await initCommand.execute(testDir);
|
||||
await initCommand.execute(testDir);
|
||||
|
||||
const secondRunArgs = mockPrompt.mock.calls[1][0];
|
||||
const claudeChoice = secondRunArgs.choices.find((choice: any) => choice.value === 'claude');
|
||||
expect(claudeChoice.configured).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('error handling', () => {
|
||||
@@ -157,6 +279,7 @@ describe('InitCommand', () => {
|
||||
return originalCheck.call(fs, filePath, ...args);
|
||||
});
|
||||
|
||||
queueSelections('claude', DONE);
|
||||
await expect(initCommand.execute(readOnlyDir)).rejects.toThrow(
|
||||
/Insufficient permissions/
|
||||
);
|
||||
@@ -180,4 +303,4 @@ async function directoryExists(dirPath: string): Promise<boolean> {
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+150
-19
@@ -5,6 +5,7 @@ import { ToolRegistry } from '../../src/core/configurators/registry.js';
|
||||
import path from 'path';
|
||||
import fs from 'fs/promises';
|
||||
import os from 'os';
|
||||
import { randomUUID } from 'crypto';
|
||||
|
||||
describe('UpdateCommand', () => {
|
||||
let testDir: string;
|
||||
@@ -12,7 +13,7 @@ describe('UpdateCommand', () => {
|
||||
|
||||
beforeEach(async () => {
|
||||
// Create a temporary test directory
|
||||
testDir = path.join(os.tmpdir(), `openspec-test-${Date.now()}`);
|
||||
testDir = path.join(os.tmpdir(), `openspec-test-${randomUUID()}`);
|
||||
await fs.mkdir(testDir, { recursive: true });
|
||||
|
||||
// Create openspec directory
|
||||
@@ -50,14 +51,47 @@ More content after.`;
|
||||
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('OpenSpec Instructions');
|
||||
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'
|
||||
);
|
||||
const [logMessage] = consoleSpy.mock.calls[0];
|
||||
expect(logMessage).toContain('Updated OpenSpec instructions (openspec/AGENTS.md');
|
||||
expect(logMessage).toContain('AGENTS.md (created)');
|
||||
expect(logMessage).toContain('Updated AI tool files: CLAUDE.md');
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should refresh existing Claude slash command files', async () => {
|
||||
const proposalPath = path.join(testDir, '.claude/commands/openspec/proposal.md');
|
||||
await fs.mkdir(path.dirname(proposalPath), { recursive: true });
|
||||
const initialContent = `---
|
||||
name: OpenSpec: Proposal
|
||||
description: Old description
|
||||
category: OpenSpec
|
||||
tags: [openspec, change]
|
||||
---
|
||||
<!-- OPENSPEC:START -->
|
||||
Old slash content
|
||||
<!-- OPENSPEC:END -->`;
|
||||
await fs.writeFile(proposalPath, initialContent);
|
||||
|
||||
const consoleSpy = vi.spyOn(console, 'log');
|
||||
|
||||
await updateCommand.execute(testDir);
|
||||
|
||||
const updated = await fs.readFile(proposalPath, 'utf-8');
|
||||
expect(updated).toContain('name: OpenSpec: Proposal');
|
||||
expect(updated).toContain('**Guardrails**');
|
||||
expect(updated).toContain('Validate with `openspec validate <id> --strict`');
|
||||
expect(updated).not.toContain('Old slash content');
|
||||
|
||||
const [logMessage] = consoleSpy.mock.calls[0];
|
||||
expect(logMessage).toContain('Updated OpenSpec instructions (openspec/AGENTS.md');
|
||||
expect(logMessage).toContain('AGENTS.md (created)');
|
||||
expect(logMessage).toContain('Updated slash commands: .claude/commands/openspec/proposal.md');
|
||||
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
|
||||
@@ -73,13 +107,46 @@ More content after.`;
|
||||
expect(fileExists).toBe(false);
|
||||
});
|
||||
|
||||
it('should refresh existing Cursor slash command files', async () => {
|
||||
const cursorPath = path.join(testDir, '.cursor/commands/openspec-apply.md');
|
||||
await fs.mkdir(path.dirname(cursorPath), { recursive: true });
|
||||
const initialContent = `---
|
||||
name: /openspec-apply
|
||||
id: openspec-apply
|
||||
category: OpenSpec
|
||||
description: Old description
|
||||
---
|
||||
<!-- OPENSPEC:START -->
|
||||
Old body
|
||||
<!-- OPENSPEC:END -->`;
|
||||
await fs.writeFile(cursorPath, initialContent);
|
||||
|
||||
const consoleSpy = vi.spyOn(console, 'log');
|
||||
|
||||
await updateCommand.execute(testDir);
|
||||
|
||||
const updated = await fs.readFile(cursorPath, 'utf-8');
|
||||
expect(updated).toContain('id: openspec-apply');
|
||||
expect(updated).toContain('Work through tasks sequentially');
|
||||
expect(updated).not.toContain('Old body');
|
||||
|
||||
const [logMessage] = consoleSpy.mock.calls[0];
|
||||
expect(logMessage).toContain('Updated OpenSpec instructions (openspec/AGENTS.md');
|
||||
expect(logMessage).toContain('AGENTS.md (created)');
|
||||
expect(logMessage).toContain('Updated slash commands: .cursor/commands/openspec-apply.md');
|
||||
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
|
||||
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)');
|
||||
const [logMessage] = consoleSpy.mock.calls[0];
|
||||
expect(logMessage).toContain('Updated OpenSpec instructions (openspec/AGENTS.md');
|
||||
expect(logMessage).toContain('AGENTS.md (created)');
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
|
||||
@@ -89,18 +156,42 @@ More content after.`;
|
||||
// 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.mkdir(path.dirname(claudePath), { recursive: true });
|
||||
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'
|
||||
);
|
||||
const [logMessage] = consoleSpy.mock.calls[0];
|
||||
expect(logMessage).toContain('Updated OpenSpec instructions (openspec/AGENTS.md');
|
||||
expect(logMessage).toContain('AGENTS.md (created)');
|
||||
expect(logMessage).toContain('Updated AI tool files: CLAUDE.md');
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should skip creating missing slash commands during update', async () => {
|
||||
const proposalPath = path.join(testDir, '.claude/commands/openspec/proposal.md');
|
||||
await fs.mkdir(path.dirname(proposalPath), { recursive: true });
|
||||
await fs.writeFile(proposalPath, `---
|
||||
name: OpenSpec: Proposal
|
||||
description: Existing file
|
||||
category: OpenSpec
|
||||
tags: [openspec, change]
|
||||
---
|
||||
<!-- OPENSPEC:START -->
|
||||
Old content
|
||||
<!-- OPENSPEC:END -->`);
|
||||
|
||||
await updateCommand.execute(testDir);
|
||||
|
||||
const applyExists = await FileSystemUtils.fileExists(path.join(testDir, '.claude/commands/openspec/apply.md'));
|
||||
const archiveExists = await FileSystemUtils.fileExists(path.join(testDir, '.claude/commands/openspec/archive.md'));
|
||||
|
||||
expect(applyExists).toBe(false);
|
||||
expect(archiveExists).toBe(false);
|
||||
});
|
||||
|
||||
it('should never create new AI tool files', async () => {
|
||||
// Get all configurators
|
||||
const configurators = ToolRegistry.getAll();
|
||||
@@ -112,23 +203,62 @@ More content after.`;
|
||||
for (const configurator of configurators) {
|
||||
const configPath = path.join(testDir, configurator.configFileName);
|
||||
const fileExists = await FileSystemUtils.fileExists(configPath);
|
||||
expect(fileExists).toBe(false);
|
||||
if (configurator.configFileName === 'AGENTS.md') {
|
||||
expect(fileExists).toBe(true);
|
||||
} else {
|
||||
expect(fileExists).toBe(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('should update README.md in openspec directory', async () => {
|
||||
it('should update AGENTS.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);
|
||||
// Check that AGENTS.md was created/updated
|
||||
const agentsPath = path.join(testDir, 'openspec', 'AGENTS.md');
|
||||
const fileExists = await FileSystemUtils.fileExists(agentsPath);
|
||||
expect(fileExists).toBe(true);
|
||||
|
||||
const content = await fs.readFile(readmePath, 'utf-8');
|
||||
const content = await fs.readFile(agentsPath, 'utf-8');
|
||||
expect(content).toContain('# OpenSpec Instructions');
|
||||
});
|
||||
|
||||
it('should create root AGENTS.md with managed block when missing', async () => {
|
||||
await updateCommand.execute(testDir);
|
||||
|
||||
const rootAgentsPath = path.join(testDir, 'AGENTS.md');
|
||||
const exists = await FileSystemUtils.fileExists(rootAgentsPath);
|
||||
expect(exists).toBe(true);
|
||||
|
||||
const content = await fs.readFile(rootAgentsPath, 'utf-8');
|
||||
expect(content).toContain('<!-- OPENSPEC:START -->');
|
||||
expect(content).toContain('OpenSpec Instructions');
|
||||
expect(content).toContain('<!-- OPENSPEC:END -->');
|
||||
});
|
||||
|
||||
it('should refresh root AGENTS.md while preserving surrounding content', async () => {
|
||||
const rootAgentsPath = path.join(testDir, 'AGENTS.md');
|
||||
const original = `# Custom intro\n\n<!-- OPENSPEC:START -->\nOld content\n<!-- OPENSPEC:END -->\n\n# Footnotes`;
|
||||
await fs.writeFile(rootAgentsPath, original);
|
||||
|
||||
const consoleSpy = vi.spyOn(console, 'log');
|
||||
|
||||
await updateCommand.execute(testDir);
|
||||
|
||||
const updated = await fs.readFile(rootAgentsPath, 'utf-8');
|
||||
expect(updated).toContain('# Custom intro');
|
||||
expect(updated).toContain('# Footnotes');
|
||||
expect(updated).toContain('OpenSpec Instructions');
|
||||
expect(updated).not.toContain('Old content');
|
||||
|
||||
const [logMessage] = consoleSpy.mock.calls[0];
|
||||
expect(logMessage).toContain('Updated OpenSpec instructions (openspec/AGENTS.md, AGENTS.md)');
|
||||
expect(logMessage).not.toContain('AGENTS.md (created)');
|
||||
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
|
||||
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 });
|
||||
@@ -161,9 +291,10 @@ More content after.`;
|
||||
|
||||
// Should report the failure
|
||||
expect(errorSpy).toHaveBeenCalled();
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
'Updated OpenSpec instructions (README.md)\nFailed to update: CLAUDE.md'
|
||||
);
|
||||
const [logMessage] = consoleSpy.mock.calls[0];
|
||||
expect(logMessage).toContain('Updated OpenSpec instructions (openspec/AGENTS.md');
|
||||
expect(logMessage).toContain('AGENTS.md (created)');
|
||||
expect(logMessage).toContain('Failed to update: CLAUDE.md');
|
||||
|
||||
// Restore permissions for cleanup
|
||||
await fs.chmod(claudePath, 0o644);
|
||||
@@ -171,4 +302,4 @@ More content after.`;
|
||||
errorSpy.mockRestore();
|
||||
writeSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,13 +2,14 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { FileSystemUtils } from '../../src/utils/file-system.js';
|
||||
|
||||
describe('FileSystemUtils', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
testDir = path.join(os.tmpdir(), `openspec-test-${Date.now()}`);
|
||||
testDir = path.join(os.tmpdir(), `openspec-test-${randomUUID()}`);
|
||||
await fs.mkdir(testDir, { recursive: true });
|
||||
});
|
||||
|
||||
@@ -159,4 +160,4 @@ describe('FileSystemUtils', () => {
|
||||
expect(hasPermission).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user