@fission-ai/openspec 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,7 +15,7 @@
15
15
  <a href="https://nodejs.org/"><img alt="node version" src="https://img.shields.io/node/v/@fission-ai/openspec?style=flat-square" /></a>
16
16
  <a href="./LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square" /></a>
17
17
  <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>
18
- <a href="https://discord.gg/saTQQGQZ"><img alt="Discord" src="https://img.shields.io/discord/1411657095639601154?logo=discord&logoColor=white&style=flat-square" /></a>
18
+ <a href="https://discord.gg/saTQQGQZ"><img alt="Discord" src="https://img.shields.io/badge/Discord-Join%20the%20community-5865F2?logo=discord&logoColor=white&style=flat-square" /></a>
19
19
  </p>
20
20
 
21
21
  <p align="center">
@@ -185,13 +185,13 @@ You: Please archive the change
185
185
  (Shortcut for tools with slash commands: /openspec:archive add-profile-filters)
186
186
 
187
187
  AI: I'll archive the add-profile-filters change.
188
- *Runs: openspec archive add-profile-filters*
188
+ *Runs: openspec archive add-profile-filters --yes*
189
189
  ✓ Change archived successfully. Specs updated. Ready for the next feature!
190
190
  ```
191
191
 
192
192
  Or run the command yourself in terminal:
193
193
  ```bash
194
- $ openspec archive add-profile-filters # Archive the completed change
194
+ $ openspec archive add-profile-filters --yes # Archive the completed change without prompts
195
195
  ```
196
196
 
197
197
  **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".
@@ -203,7 +203,7 @@ openspec list # View active change folders
203
203
  openspec view # Interactive dashboard of specs and changes
204
204
  openspec show <change> # Display change details (proposal, tasks, spec updates)
205
205
  openspec validate <change> # Check spec formatting and structure
206
- openspec archive <change> # Move a completed change into archive/
206
+ openspec archive <change> [--yes|-y] # Move a completed change into archive/ (non-interactive with --yes)
207
207
  ```
208
208
 
209
209
  ## Example: How AI Creates OpenSpec Files
@@ -33,7 +33,8 @@ export class JsonConverter {
33
33
  return JSON.stringify(jsonChange, null, 2);
34
34
  }
35
35
  extractNameFromPath(filePath) {
36
- const parts = filePath.split('/');
36
+ const normalizedPath = filePath.replaceAll('\\', '/');
37
+ const parts = normalizedPath.split('/');
37
38
  for (let i = parts.length - 1; i >= 0; i--) {
38
39
  if (parts[i] === 'specs' || parts[i] === 'changes') {
39
40
  if (i < parts.length - 1) {
@@ -41,8 +42,9 @@ export class JsonConverter {
41
42
  }
42
43
  }
43
44
  }
44
- const fileName = parts[parts.length - 1];
45
- return fileName.replace('.md', '');
45
+ const fileName = parts[parts.length - 1] ?? '';
46
+ const dotIndex = fileName.lastIndexOf('.');
47
+ return dotIndex > 0 ? fileName.slice(0, dotIndex) : fileName;
46
48
  }
47
49
  }
48
50
  //# sourceMappingURL=json-converter.js.map
package/dist/core/init.js CHANGED
@@ -7,16 +7,11 @@ import { TemplateManager } from './templates/index.js';
7
7
  import { ToolRegistry } from './configurators/registry.js';
8
8
  import { SlashCommandRegistry } from './configurators/slash/registry.js';
9
9
  import { AI_TOOLS, OPENSPEC_DIR_NAME, } from './config.js';
10
+ import { PALETTE } from './styles/palette.js';
10
11
  const PROGRESS_SPINNER = {
11
12
  interval: 80,
12
13
  frames: ['░░░', '▒░░', '▒▒░', '▒▒▒', '▓▒▒', '▓▓▒', '▓▓▓', '▒▓▓', '░▒▓'],
13
14
  };
14
- const PALETTE = {
15
- white: chalk.hex('#f4f4f4'),
16
- lightGray: chalk.hex('#c8c8c8'),
17
- midGray: chalk.hex('#8a8a8a'),
18
- darkGray: chalk.hex('#4a4a4a'),
19
- };
20
15
  const LETTER_MAP = {
21
16
  O: [' ████ ', '██ ██', '██ ██', '██ ██', ' ████ '],
22
17
  P: ['█████ ', '██ ██', '█████ ', '██ ', '██ '],
@@ -0,0 +1,7 @@
1
+ export declare const PALETTE: {
2
+ white: import("chalk").ChalkInstance;
3
+ lightGray: import("chalk").ChalkInstance;
4
+ midGray: import("chalk").ChalkInstance;
5
+ darkGray: import("chalk").ChalkInstance;
6
+ };
7
+ //# sourceMappingURL=palette.d.ts.map
@@ -0,0 +1,8 @@
1
+ import chalk from 'chalk';
2
+ export const PALETTE = {
3
+ white: chalk.hex('#f4f4f4'),
4
+ lightGray: chalk.hex('#c8c8c8'),
5
+ midGray: chalk.hex('#8a8a8a'),
6
+ darkGray: chalk.hex('#4a4a4a')
7
+ };
8
+ //# sourceMappingURL=palette.js.map
@@ -0,0 +1,2 @@
1
+ export declare const agentsRootStubTemplate = "# OpenSpec Instructions\n\nThese instructions are for AI assistants working in this project.\n\nAlways open `@/openspec/AGENTS.md` when the request:\n- Mentions planning or proposals (words like proposal, spec, change, plan)\n- Introduces new capabilities, breaking changes, architecture shifts, or big performance/security work\n- Sounds ambiguous and you need the authoritative spec before coding\n\nUse `@/openspec/AGENTS.md` to learn:\n- How to create and apply change proposals\n- Spec format and conventions\n- Project structure and guidelines\n\nKeep this managed block so 'openspec update' can refresh the instructions.\n";
2
+ //# sourceMappingURL=agents-root-stub.d.ts.map
@@ -0,0 +1,17 @@
1
+ export const agentsRootStubTemplate = `# OpenSpec Instructions
2
+
3
+ These instructions are for AI assistants working in this project.
4
+
5
+ Always open \`@/openspec/AGENTS.md\` when the request:
6
+ - Mentions planning or proposals (words like proposal, spec, change, plan)
7
+ - Introduces new capabilities, breaking changes, architecture shifts, or big performance/security work
8
+ - Sounds ambiguous and you need the authoritative spec before coding
9
+
10
+ Use \`@/openspec/AGENTS.md\` to learn:
11
+ - How to create and apply change proposals
12
+ - Spec format and conventions
13
+ - Project structure and guidelines
14
+
15
+ Keep this managed block so 'openspec update' can refresh the instructions.
16
+ `;
17
+ //# sourceMappingURL=agents-root-stub.js.map
@@ -1,2 +1,2 @@
1
- export declare const agentsTemplate = "# OpenSpec Instructions\n\nInstructions for AI coding assistants using OpenSpec for spec-driven development.\n\n## TL;DR Quick Checklist\n\n- Search existing work: `openspec spec list --long`, `openspec list` (use `rg` only for full-text search)\n- Decide scope: new capability vs modify existing capability\n- Pick a unique `change-id`: kebab-case, verb-led (`add-`, `update-`, `remove-`, `refactor-`)\n- Scaffold: `proposal.md`, `tasks.md`, `design.md` (only if needed), and delta specs per affected capability\n- Write deltas: use `## ADDED|MODIFIED|REMOVED|RENAMED Requirements`; include at least one `#### Scenario:` per requirement\n- Validate: `openspec validate [change-id] --strict` and fix issues\n- Request approval: Do not start implementation until proposal is approved\n\n## Three-Stage Workflow\n\n### Stage 1: Creating Changes\nCreate proposal when you need to:\n- Add features or functionality\n- Make breaking changes (API, schema)\n- Change architecture or patterns \n- Optimize performance (changes behavior)\n- Update security patterns\n\nTriggers (examples):\n- \"Help me create a change proposal\"\n- \"Help me plan a change\"\n- \"Help me create a proposal\"\n- \"I want to create a spec proposal\"\n- \"I want to create a spec\"\n\nLoose matching guidance:\n- Contains one of: `proposal`, `change`, `spec`\n- With one of: `create`, `plan`, `make`, `start`, `help`\n\nSkip proposal for:\n- Bug fixes (restore intended behavior)\n- Typos, formatting, comments\n- Dependency updates (non-breaking)\n- Configuration changes\n- Tests for existing behavior\n\n**Workflow**\n1. Review `openspec/project.md`, `openspec list`, and `openspec list --specs` to understand current context.\n2. Choose a unique verb-led `change-id` and scaffold `proposal.md`, `tasks.md`, optional `design.md`, and spec deltas under `openspec/changes/<id>/`.\n3. Draft spec deltas using `## ADDED|MODIFIED|REMOVED Requirements` with at least one `#### Scenario:` per requirement.\n4. Run `openspec validate <id> --strict` and resolve any issues before sharing the proposal.\n\n### Stage 2: Implementing Changes\n1. **Read proposal.md** - Understand what's being built\n2. **Read design.md** (if exists) - Review technical decisions\n3. **Read tasks.md** - Get implementation checklist\n4. **Implement tasks sequentially** - Complete in order\n5. **Mark complete immediately** - Update `- [x]` after each task\n6. **Approval gate** - Do not start implementation until the proposal is reviewed and approved\n\n### Stage 3: Archiving Changes\nAfter deployment, create separate PR to:\n- Move `changes/[name]/` \u2192 `changes/archive/YYYY-MM-DD-[name]/`\n- Update `specs/` if capabilities changed\n- Use `openspec archive [change] --skip-specs` for tooling-only changes\n- Run `openspec validate --strict` to confirm the archived change passes checks\n\n## Before Any Task\n\n**Context Checklist:**\n- [ ] Read relevant specs in `specs/[capability]/spec.md`\n- [ ] Check pending changes in `changes/` for conflicts\n- [ ] Read `openspec/project.md` for conventions\n- [ ] Run `openspec list` to see active changes\n- [ ] Run `openspec list --specs` to see existing capabilities\n\n**Before Creating Specs:**\n- Always check if capability already exists\n- Prefer modifying existing specs over creating duplicates\n- Use `openspec show [spec]` to review current state\n- If request is ambiguous, ask 1\u20132 clarifying questions before scaffolding\n\n### Search Guidance\n- Enumerate specs: `openspec spec list --long` (or `--json` for scripts)\n- Enumerate changes: `openspec list` (or `openspec change list --json` - deprecated but available)\n- Show details:\n - Spec: `openspec show <spec-id> --type spec` (use `--json` for filters)\n - Change: `openspec show <change-id> --json --deltas-only`\n- Full-text search (use ripgrep): `rg -n \"Requirement:|Scenario:\" openspec/specs`\n\n## Quick Start\n\n### CLI Commands\n\n```bash\n# Essential commands\nopenspec list # List active changes\nopenspec list --specs # List specifications\nopenspec show [item] # Display change or spec\nopenspec diff [change] # Show spec differences\nopenspec validate [item] # Validate changes or specs\nopenspec archive [change] # Archive after deployment\n\n# Project management\nopenspec init [path] # Initialize OpenSpec\nopenspec update [path] # Update instruction files\n\n# Interactive mode\nopenspec show # Prompts for selection\nopenspec validate # Bulk validation mode\n\n# Debugging\nopenspec show [change] --json --deltas-only\nopenspec validate [change] --strict\n```\n\n### Command Flags\n\n- `--json` - Machine-readable output\n- `--type change|spec` - Disambiguate items\n- `--strict` - Comprehensive validation\n- `--no-interactive` - Disable prompts\n- `--skip-specs` - Archive without spec updates\n\n## Directory Structure\n\n```\nopenspec/\n\u251C\u2500\u2500 project.md # Project conventions\n\u251C\u2500\u2500 specs/ # Current truth - what IS built\n\u2502 \u2514\u2500\u2500 [capability]/ # Single focused capability\n\u2502 \u251C\u2500\u2500 spec.md # Requirements and scenarios\n\u2502 \u2514\u2500\u2500 design.md # Technical patterns\n\u251C\u2500\u2500 changes/ # Proposals - what SHOULD change\n\u2502 \u251C\u2500\u2500 [change-name]/\n\u2502 \u2502 \u251C\u2500\u2500 proposal.md # Why, what, impact\n\u2502 \u2502 \u251C\u2500\u2500 tasks.md # Implementation checklist\n\u2502 \u2502 \u251C\u2500\u2500 design.md # Technical decisions (optional; see criteria)\n\u2502 \u2502 \u2514\u2500\u2500 specs/ # Delta changes\n\u2502 \u2502 \u2514\u2500\u2500 [capability]/\n\u2502 \u2502 \u2514\u2500\u2500 spec.md # ADDED/MODIFIED/REMOVED\n\u2502 \u2514\u2500\u2500 archive/ # Completed changes\n```\n\n## Creating Change Proposals\n\n### Decision Tree\n\n```\nNew request?\n\u251C\u2500 Bug fix restoring spec behavior? \u2192 Fix directly\n\u251C\u2500 Typo/format/comment? \u2192 Fix directly \n\u251C\u2500 New feature/capability? \u2192 Create proposal\n\u251C\u2500 Breaking change? \u2192 Create proposal\n\u251C\u2500 Architecture change? \u2192 Create proposal\n\u2514\u2500 Unclear? \u2192 Create proposal (safer)\n```\n\n### Proposal Structure\n\n1. **Create directory:** `changes/[change-id]/` (kebab-case, verb-led, unique)\n\n2. **Write proposal.md:**\n```markdown\n## Why\n[1-2 sentences on problem/opportunity]\n\n## What Changes\n- [Bullet list of changes]\n- [Mark breaking changes with **BREAKING**]\n\n## Impact\n- Affected specs: [list capabilities]\n- Affected code: [key files/systems]\n```\n\n3. **Create spec deltas:** `specs/[capability]/spec.md`\n```markdown\n## ADDED Requirements\n### Requirement: New Feature\nThe system SHALL provide...\n\n#### Scenario: Success case\n- **WHEN** user performs action\n- **THEN** expected result\n\n## MODIFIED Requirements\n### Requirement: Existing Feature\n[Complete modified requirement]\n\n## REMOVED Requirements\n### Requirement: Old Feature\n**Reason**: [Why removing]\n**Migration**: [How to handle]\n```\nIf multiple capabilities are affected, create multiple delta files under `changes/[change-id]/specs/<capability>/spec.md`\u2014one per capability.\n\n4. **Create tasks.md:**\n```markdown\n## 1. Implementation\n- [ ] 1.1 Create database schema\n- [ ] 1.2 Implement API endpoint\n- [ ] 1.3 Add frontend component\n- [ ] 1.4 Write tests\n```\n\n5. **Create design.md when needed:**\nCreate `design.md` if any of the following apply; otherwise omit it:\n- Cross-cutting change (multiple services/modules) or a new architectural pattern\n- New external dependency or significant data model changes\n- Security, performance, or migration complexity\n- Ambiguity that benefits from technical decisions before coding\n\nMinimal `design.md` skeleton:\n```markdown\n## Context\n[Background, constraints, stakeholders]\n\n## Goals / Non-Goals\n- Goals: [...]\n- Non-Goals: [...]\n\n## Decisions\n- Decision: [What and why]\n- Alternatives considered: [Options + rationale]\n\n## Risks / Trade-offs\n- [Risk] \u2192 Mitigation\n\n## Migration Plan\n[Steps, rollback]\n\n## Open Questions\n- [...]\n```\n\n## Spec File Format\n\n### Critical: Scenario Formatting\n\n**CORRECT** (use #### headers):\n```markdown\n#### Scenario: User login success\n- **WHEN** valid credentials provided\n- **THEN** return JWT token\n```\n\n**WRONG** (don't use bullets or bold):\n```markdown\n- **Scenario: User login** \u274C\n**Scenario**: User login \u274C\n### Scenario: User login \u274C\n```\n\nEvery requirement MUST have at least one scenario.\n\n### Requirement Wording\n- Use SHALL/MUST for normative requirements (avoid should/may unless intentionally non-normative)\n\n### Delta Operations\n\n- `## ADDED Requirements` - New capabilities\n- `## MODIFIED Requirements` - Changed behavior\n- `## REMOVED Requirements` - Deprecated features\n- `## RENAMED Requirements` - Name changes\n\nHeaders matched with `trim(header)` - whitespace ignored.\n\n#### When to use ADDED vs MODIFIED\n- ADDED: Introduces a new capability or sub-capability that can stand alone as a requirement. Prefer ADDED when the change is orthogonal (e.g., adding \"Slash Command Configuration\") rather than altering the semantics of an existing requirement.\n- MODIFIED: Changes the behavior, scope, or acceptance criteria of an existing requirement. Always paste the full, updated requirement content (header + all scenarios). The archiver will replace the entire requirement with what you provide here; partial deltas will drop previous details.\n- RENAMED: Use when only the name changes. If you also change behavior, use RENAMED (name) plus MODIFIED (content) referencing the new name.\n\nCommon pitfall: Using MODIFIED to add a new concern without including the previous text. This causes loss of detail at archive time. If you aren\u2019t explicitly changing the existing requirement, add a new requirement under ADDED instead.\n\nAuthoring a MODIFIED requirement correctly:\n1) Locate the existing requirement in `openspec/specs/<capability>/spec.md`.\n2) Copy the entire requirement block (from `### Requirement: ...` through its scenarios).\n3) Paste it under `## MODIFIED Requirements` and edit to reflect the new behavior.\n4) Ensure the header text matches exactly (whitespace-insensitive) and keep at least one `#### Scenario:`.\n\nExample for RENAMED:\n```markdown\n## RENAMED Requirements\n- FROM: `### Requirement: Login`\n- TO: `### Requirement: User Authentication`\n```\n\n## Troubleshooting\n\n### Common Errors\n\n**\"Change must have at least one delta\"**\n- Check `changes/[name]/specs/` exists with .md files\n- Verify files have operation prefixes (## ADDED Requirements)\n\n**\"Requirement must have at least one scenario\"**\n- Check scenarios use `#### Scenario:` format (4 hashtags)\n- Don't use bullet points or bold for scenario headers\n\n**Silent scenario parsing failures**\n- Exact format required: `#### Scenario: Name`\n- Debug with: `openspec show [change] --json --deltas-only`\n\n### Validation Tips\n\n```bash\n# Always use strict mode for comprehensive checks\nopenspec validate [change] --strict\n\n# Debug delta parsing\nopenspec show [change] --json | jq '.deltas'\n\n# Check specific requirement\nopenspec show [spec] --json -r 1\n```\n\n## Happy Path Script\n\n```bash\n# 1) Explore current state\nopenspec spec list --long\nopenspec list\n# Optional full-text search:\n# rg -n \"Requirement:|Scenario:\" openspec/specs\n# rg -n \"^#|Requirement:\" openspec/changes\n\n# 2) Choose change id and scaffold\nCHANGE=add-two-factor-auth\nmkdir -p openspec/changes/$CHANGE/{specs/auth}\nprintf \"## Why\\n...\\n\\n## What Changes\\n- ...\\n\\n## Impact\\n- ...\\n\" > openspec/changes/$CHANGE/proposal.md\nprintf \"## 1. Implementation\\n- [ ] 1.1 ...\\n\" > openspec/changes/$CHANGE/tasks.md\n\n# 3) Add deltas (example)\ncat > openspec/changes/$CHANGE/specs/auth/spec.md << 'EOF'\n## ADDED Requirements\n### Requirement: Two-Factor Authentication\nUsers MUST provide a second factor during login.\n\n#### Scenario: OTP required\n- **WHEN** valid credentials are provided\n- **THEN** an OTP challenge is required\nEOF\n\n# 4) Validate\nopenspec validate $CHANGE --strict\n```\n\n## Multi-Capability Example\n\n```\nopenspec/changes/add-2fa-notify/\n\u251C\u2500\u2500 proposal.md\n\u251C\u2500\u2500 tasks.md\n\u2514\u2500\u2500 specs/\n \u251C\u2500\u2500 auth/\n \u2502 \u2514\u2500\u2500 spec.md # ADDED: Two-Factor Authentication\n \u2514\u2500\u2500 notifications/\n \u2514\u2500\u2500 spec.md # ADDED: OTP email notification\n```\n\nauth/spec.md\n```markdown\n## ADDED Requirements\n### Requirement: Two-Factor Authentication\n...\n```\n\nnotifications/spec.md\n```markdown\n## ADDED Requirements\n### Requirement: OTP Email Notification\n...\n```\n\n## Best Practices\n\n### Simplicity First\n- Default to <100 lines of new code\n- Single-file implementations until proven insufficient\n- Avoid frameworks without clear justification\n- Choose boring, proven patterns\n\n### Complexity Triggers\nOnly add complexity with:\n- Performance data showing current solution too slow\n- Concrete scale requirements (>1000 users, >100MB data)\n- Multiple proven use cases requiring abstraction\n\n### Clear References\n- Use `file.ts:42` format for code locations\n- Reference specs as `specs/auth/spec.md`\n- Link related changes and PRs\n\n### Capability Naming\n- Use verb-noun: `user-auth`, `payment-capture`\n- Single purpose per capability\n- 10-minute understandability rule\n- Split if description needs \"AND\"\n\n### Change ID Naming\n- Use kebab-case, short and descriptive: `add-two-factor-auth`\n- Prefer verb-led prefixes: `add-`, `update-`, `remove-`, `refactor-`\n- Ensure uniqueness; if taken, append `-2`, `-3`, etc.\n\n## Tool Selection Guide\n\n| Task | Tool | Why |\n|------|------|-----|\n| Find files by pattern | Glob | Fast pattern matching |\n| Search code content | Grep | Optimized regex search |\n| Read specific files | Read | Direct file access |\n| Explore unknown scope | Task | Multi-step investigation |\n\n## Error Recovery\n\n### Change Conflicts\n1. Run `openspec list` to see active changes\n2. Check for overlapping specs\n3. Coordinate with change owners\n4. Consider combining proposals\n\n### Validation Failures\n1. Run with `--strict` flag\n2. Check JSON output for details\n3. Verify spec file format\n4. Ensure scenarios properly formatted\n\n### Missing Context\n1. Read project.md first\n2. Check related specs\n3. Review recent archives\n4. Ask for clarification\n\n## Quick Reference\n\n### Stage Indicators\n- `changes/` - Proposed, not yet built\n- `specs/` - Built and deployed\n- `archive/` - Completed changes\n\n### File Purposes\n- `proposal.md` - Why and what\n- `tasks.md` - Implementation steps\n- `design.md` - Technical decisions\n- `spec.md` - Requirements and behavior\n\n### CLI Essentials\n```bash\nopenspec list # What's in progress?\nopenspec show [item] # View details\nopenspec diff [change] # What's changing?\nopenspec validate --strict # Is it correct?\nopenspec archive [change] # Mark complete\n```\n\nRemember: Specs are truth. Changes are proposals. Keep them in sync.\n";
1
+ export declare const agentsTemplate = "# OpenSpec Instructions\n\nInstructions for AI coding assistants using OpenSpec for spec-driven development.\n\n## TL;DR Quick Checklist\n\n- Search existing work: `openspec spec list --long`, `openspec list` (use `rg` only for full-text search)\n- Decide scope: new capability vs modify existing capability\n- Pick a unique `change-id`: kebab-case, verb-led (`add-`, `update-`, `remove-`, `refactor-`)\n- Scaffold: `proposal.md`, `tasks.md`, `design.md` (only if needed), and delta specs per affected capability\n- Write deltas: use `## ADDED|MODIFIED|REMOVED|RENAMED Requirements`; include at least one `#### Scenario:` per requirement\n- Validate: `openspec validate [change-id] --strict` and fix issues\n- Request approval: Do not start implementation until proposal is approved\n\n## Three-Stage Workflow\n\n### Stage 1: Creating Changes\nCreate proposal when you need to:\n- Add features or functionality\n- Make breaking changes (API, schema)\n- Change architecture or patterns \n- Optimize performance (changes behavior)\n- Update security patterns\n\nTriggers (examples):\n- \"Help me create a change proposal\"\n- \"Help me plan a change\"\n- \"Help me create a proposal\"\n- \"I want to create a spec proposal\"\n- \"I want to create a spec\"\n\nLoose matching guidance:\n- Contains one of: `proposal`, `change`, `spec`\n- With one of: `create`, `plan`, `make`, `start`, `help`\n\nSkip proposal for:\n- Bug fixes (restore intended behavior)\n- Typos, formatting, comments\n- Dependency updates (non-breaking)\n- Configuration changes\n- Tests for existing behavior\n\n**Workflow**\n1. Review `openspec/project.md`, `openspec list`, and `openspec list --specs` to understand current context.\n2. Choose a unique verb-led `change-id` and scaffold `proposal.md`, `tasks.md`, optional `design.md`, and spec deltas under `openspec/changes/<id>/`.\n3. Draft spec deltas using `## ADDED|MODIFIED|REMOVED Requirements` with at least one `#### Scenario:` per requirement.\n4. Run `openspec validate <id> --strict` and resolve any issues before sharing the proposal.\n\n### Stage 2: Implementing Changes\nTrack these steps as TODOs and complete them one by one.\n1. **Read proposal.md** - Understand what's being built\n2. **Read design.md** (if exists) - Review technical decisions\n3. **Read tasks.md** - Get implementation checklist\n4. **Implement tasks sequentially** - Complete in order\n5. **Confirm completion** - Ensure every item in `tasks.md` is finished before updating statuses\n6. **Update checklist** - After all work is done, set every task to `- [x]` so the list reflects reality\n7. **Approval gate** - Do not start implementation until the proposal is reviewed and approved\n\n### Stage 3: Archiving Changes\nAfter deployment, create separate PR to:\n- Move `changes/[name]/` \u2192 `changes/archive/YYYY-MM-DD-[name]/`\n- Update `specs/` if capabilities changed\n- Use `openspec archive [change] --skip-specs --yes` for tooling-only changes\n- Run `openspec validate --strict` to confirm the archived change passes checks\n\n## Before Any Task\n\n**Context Checklist:**\n- [ ] Read relevant specs in `specs/[capability]/spec.md`\n- [ ] Check pending changes in `changes/` for conflicts\n- [ ] Read `openspec/project.md` for conventions\n- [ ] Run `openspec list` to see active changes\n- [ ] Run `openspec list --specs` to see existing capabilities\n\n**Before Creating Specs:**\n- Always check if capability already exists\n- Prefer modifying existing specs over creating duplicates\n- Use `openspec show [spec]` to review current state\n- If request is ambiguous, ask 1\u20132 clarifying questions before scaffolding\n\n### Search Guidance\n- Enumerate specs: `openspec spec list --long` (or `--json` for scripts)\n- Enumerate changes: `openspec list` (or `openspec change list --json` - deprecated but available)\n- Show details:\n - Spec: `openspec show <spec-id> --type spec` (use `--json` for filters)\n - Change: `openspec show <change-id> --json --deltas-only`\n- Full-text search (use ripgrep): `rg -n \"Requirement:|Scenario:\" openspec/specs`\n\n## Quick Start\n\n### CLI Commands\n\n```bash\n# Essential commands\nopenspec list # List active changes\nopenspec list --specs # List specifications\nopenspec show [item] # Display change or spec\nopenspec diff [change] # Show spec differences\nopenspec validate [item] # Validate changes or specs\nopenspec archive [change] [--yes|-y] # Archive after deployment (add --yes for non-interactive runs)\n\n# Project management\nopenspec init [path] # Initialize OpenSpec\nopenspec update [path] # Update instruction files\n\n# Interactive mode\nopenspec show # Prompts for selection\nopenspec validate # Bulk validation mode\n\n# Debugging\nopenspec show [change] --json --deltas-only\nopenspec validate [change] --strict\n```\n\n### Command Flags\n\n- `--json` - Machine-readable output\n- `--type change|spec` - Disambiguate items\n- `--strict` - Comprehensive validation\n- `--no-interactive` - Disable prompts\n- `--skip-specs` - Archive without spec updates\n- `--yes`/`-y` - Skip confirmation prompts (non-interactive archive)\n\n## Directory Structure\n\n```\nopenspec/\n\u251C\u2500\u2500 project.md # Project conventions\n\u251C\u2500\u2500 specs/ # Current truth - what IS built\n\u2502 \u2514\u2500\u2500 [capability]/ # Single focused capability\n\u2502 \u251C\u2500\u2500 spec.md # Requirements and scenarios\n\u2502 \u2514\u2500\u2500 design.md # Technical patterns\n\u251C\u2500\u2500 changes/ # Proposals - what SHOULD change\n\u2502 \u251C\u2500\u2500 [change-name]/\n\u2502 \u2502 \u251C\u2500\u2500 proposal.md # Why, what, impact\n\u2502 \u2502 \u251C\u2500\u2500 tasks.md # Implementation checklist\n\u2502 \u2502 \u251C\u2500\u2500 design.md # Technical decisions (optional; see criteria)\n\u2502 \u2502 \u2514\u2500\u2500 specs/ # Delta changes\n\u2502 \u2502 \u2514\u2500\u2500 [capability]/\n\u2502 \u2502 \u2514\u2500\u2500 spec.md # ADDED/MODIFIED/REMOVED\n\u2502 \u2514\u2500\u2500 archive/ # Completed changes\n```\n\n## Creating Change Proposals\n\n### Decision Tree\n\n```\nNew request?\n\u251C\u2500 Bug fix restoring spec behavior? \u2192 Fix directly\n\u251C\u2500 Typo/format/comment? \u2192 Fix directly \n\u251C\u2500 New feature/capability? \u2192 Create proposal\n\u251C\u2500 Breaking change? \u2192 Create proposal\n\u251C\u2500 Architecture change? \u2192 Create proposal\n\u2514\u2500 Unclear? \u2192 Create proposal (safer)\n```\n\n### Proposal Structure\n\n1. **Create directory:** `changes/[change-id]/` (kebab-case, verb-led, unique)\n\n2. **Write proposal.md:**\n```markdown\n## Why\n[1-2 sentences on problem/opportunity]\n\n## What Changes\n- [Bullet list of changes]\n- [Mark breaking changes with **BREAKING**]\n\n## Impact\n- Affected specs: [list capabilities]\n- Affected code: [key files/systems]\n```\n\n3. **Create spec deltas:** `specs/[capability]/spec.md`\n```markdown\n## ADDED Requirements\n### Requirement: New Feature\nThe system SHALL provide...\n\n#### Scenario: Success case\n- **WHEN** user performs action\n- **THEN** expected result\n\n## MODIFIED Requirements\n### Requirement: Existing Feature\n[Complete modified requirement]\n\n## REMOVED Requirements\n### Requirement: Old Feature\n**Reason**: [Why removing]\n**Migration**: [How to handle]\n```\nIf multiple capabilities are affected, create multiple delta files under `changes/[change-id]/specs/<capability>/spec.md`\u2014one per capability.\n\n4. **Create tasks.md:**\n```markdown\n## 1. Implementation\n- [ ] 1.1 Create database schema\n- [ ] 1.2 Implement API endpoint\n- [ ] 1.3 Add frontend component\n- [ ] 1.4 Write tests\n```\n\n5. **Create design.md when needed:**\nCreate `design.md` if any of the following apply; otherwise omit it:\n- Cross-cutting change (multiple services/modules) or a new architectural pattern\n- New external dependency or significant data model changes\n- Security, performance, or migration complexity\n- Ambiguity that benefits from technical decisions before coding\n\nMinimal `design.md` skeleton:\n```markdown\n## Context\n[Background, constraints, stakeholders]\n\n## Goals / Non-Goals\n- Goals: [...]\n- Non-Goals: [...]\n\n## Decisions\n- Decision: [What and why]\n- Alternatives considered: [Options + rationale]\n\n## Risks / Trade-offs\n- [Risk] \u2192 Mitigation\n\n## Migration Plan\n[Steps, rollback]\n\n## Open Questions\n- [...]\n```\n\n## Spec File Format\n\n### Critical: Scenario Formatting\n\n**CORRECT** (use #### headers):\n```markdown\n#### Scenario: User login success\n- **WHEN** valid credentials provided\n- **THEN** return JWT token\n```\n\n**WRONG** (don't use bullets or bold):\n```markdown\n- **Scenario: User login** \u274C\n**Scenario**: User login \u274C\n### Scenario: User login \u274C\n```\n\nEvery requirement MUST have at least one scenario.\n\n### Requirement Wording\n- Use SHALL/MUST for normative requirements (avoid should/may unless intentionally non-normative)\n\n### Delta Operations\n\n- `## ADDED Requirements` - New capabilities\n- `## MODIFIED Requirements` - Changed behavior\n- `## REMOVED Requirements` - Deprecated features\n- `## RENAMED Requirements` - Name changes\n\nHeaders matched with `trim(header)` - whitespace ignored.\n\n#### When to use ADDED vs MODIFIED\n- ADDED: Introduces a new capability or sub-capability that can stand alone as a requirement. Prefer ADDED when the change is orthogonal (e.g., adding \"Slash Command Configuration\") rather than altering the semantics of an existing requirement.\n- MODIFIED: Changes the behavior, scope, or acceptance criteria of an existing requirement. Always paste the full, updated requirement content (header + all scenarios). The archiver will replace the entire requirement with what you provide here; partial deltas will drop previous details.\n- RENAMED: Use when only the name changes. If you also change behavior, use RENAMED (name) plus MODIFIED (content) referencing the new name.\n\nCommon pitfall: Using MODIFIED to add a new concern without including the previous text. This causes loss of detail at archive time. If you aren\u2019t explicitly changing the existing requirement, add a new requirement under ADDED instead.\n\nAuthoring a MODIFIED requirement correctly:\n1) Locate the existing requirement in `openspec/specs/<capability>/spec.md`.\n2) Copy the entire requirement block (from `### Requirement: ...` through its scenarios).\n3) Paste it under `## MODIFIED Requirements` and edit to reflect the new behavior.\n4) Ensure the header text matches exactly (whitespace-insensitive) and keep at least one `#### Scenario:`.\n\nExample for RENAMED:\n```markdown\n## RENAMED Requirements\n- FROM: `### Requirement: Login`\n- TO: `### Requirement: User Authentication`\n```\n\n## Troubleshooting\n\n### Common Errors\n\n**\"Change must have at least one delta\"**\n- Check `changes/[name]/specs/` exists with .md files\n- Verify files have operation prefixes (## ADDED Requirements)\n\n**\"Requirement must have at least one scenario\"**\n- Check scenarios use `#### Scenario:` format (4 hashtags)\n- Don't use bullet points or bold for scenario headers\n\n**Silent scenario parsing failures**\n- Exact format required: `#### Scenario: Name`\n- Debug with: `openspec show [change] --json --deltas-only`\n\n### Validation Tips\n\n```bash\n# Always use strict mode for comprehensive checks\nopenspec validate [change] --strict\n\n# Debug delta parsing\nopenspec show [change] --json | jq '.deltas'\n\n# Check specific requirement\nopenspec show [spec] --json -r 1\n```\n\n## Happy Path Script\n\n```bash\n# 1) Explore current state\nopenspec spec list --long\nopenspec list\n# Optional full-text search:\n# rg -n \"Requirement:|Scenario:\" openspec/specs\n# rg -n \"^#|Requirement:\" openspec/changes\n\n# 2) Choose change id and scaffold\nCHANGE=add-two-factor-auth\nmkdir -p openspec/changes/$CHANGE/{specs/auth}\nprintf \"## Why\\n...\\n\\n## What Changes\\n- ...\\n\\n## Impact\\n- ...\\n\" > openspec/changes/$CHANGE/proposal.md\nprintf \"## 1. Implementation\\n- [ ] 1.1 ...\\n\" > openspec/changes/$CHANGE/tasks.md\n\n# 3) Add deltas (example)\ncat > openspec/changes/$CHANGE/specs/auth/spec.md << 'EOF'\n## ADDED Requirements\n### Requirement: Two-Factor Authentication\nUsers MUST provide a second factor during login.\n\n#### Scenario: OTP required\n- **WHEN** valid credentials are provided\n- **THEN** an OTP challenge is required\nEOF\n\n# 4) Validate\nopenspec validate $CHANGE --strict\n```\n\n## Multi-Capability Example\n\n```\nopenspec/changes/add-2fa-notify/\n\u251C\u2500\u2500 proposal.md\n\u251C\u2500\u2500 tasks.md\n\u2514\u2500\u2500 specs/\n \u251C\u2500\u2500 auth/\n \u2502 \u2514\u2500\u2500 spec.md # ADDED: Two-Factor Authentication\n \u2514\u2500\u2500 notifications/\n \u2514\u2500\u2500 spec.md # ADDED: OTP email notification\n```\n\nauth/spec.md\n```markdown\n## ADDED Requirements\n### Requirement: Two-Factor Authentication\n...\n```\n\nnotifications/spec.md\n```markdown\n## ADDED Requirements\n### Requirement: OTP Email Notification\n...\n```\n\n## Best Practices\n\n### Simplicity First\n- Default to <100 lines of new code\n- Single-file implementations until proven insufficient\n- Avoid frameworks without clear justification\n- Choose boring, proven patterns\n\n### Complexity Triggers\nOnly add complexity with:\n- Performance data showing current solution too slow\n- Concrete scale requirements (>1000 users, >100MB data)\n- Multiple proven use cases requiring abstraction\n\n### Clear References\n- Use `file.ts:42` format for code locations\n- Reference specs as `specs/auth/spec.md`\n- Link related changes and PRs\n\n### Capability Naming\n- Use verb-noun: `user-auth`, `payment-capture`\n- Single purpose per capability\n- 10-minute understandability rule\n- Split if description needs \"AND\"\n\n### Change ID Naming\n- Use kebab-case, short and descriptive: `add-two-factor-auth`\n- Prefer verb-led prefixes: `add-`, `update-`, `remove-`, `refactor-`\n- Ensure uniqueness; if taken, append `-2`, `-3`, etc.\n\n## Tool Selection Guide\n\n| Task | Tool | Why |\n|------|------|-----|\n| Find files by pattern | Glob | Fast pattern matching |\n| Search code content | Grep | Optimized regex search |\n| Read specific files | Read | Direct file access |\n| Explore unknown scope | Task | Multi-step investigation |\n\n## Error Recovery\n\n### Change Conflicts\n1. Run `openspec list` to see active changes\n2. Check for overlapping specs\n3. Coordinate with change owners\n4. Consider combining proposals\n\n### Validation Failures\n1. Run with `--strict` flag\n2. Check JSON output for details\n3. Verify spec file format\n4. Ensure scenarios properly formatted\n\n### Missing Context\n1. Read project.md first\n2. Check related specs\n3. Review recent archives\n4. Ask for clarification\n\n## Quick Reference\n\n### Stage Indicators\n- `changes/` - Proposed, not yet built\n- `specs/` - Built and deployed\n- `archive/` - Completed changes\n\n### File Purposes\n- `proposal.md` - Why and what\n- `tasks.md` - Implementation steps\n- `design.md` - Technical decisions\n- `spec.md` - Requirements and behavior\n\n### CLI Essentials\n```bash\nopenspec list # What's in progress?\nopenspec show [item] # View details\nopenspec diff [change] # What's changing?\nopenspec validate --strict # Is it correct?\nopenspec archive [change] [--yes|-y] # Mark complete (add --yes for automation)\n```\n\nRemember: Specs are truth. Changes are proposals. Keep them in sync.\n";
2
2
  //# sourceMappingURL=agents-template.d.ts.map
@@ -47,18 +47,20 @@ Skip proposal for:
47
47
  4. Run \`openspec validate <id> --strict\` and resolve any issues before sharing the proposal.
48
48
 
49
49
  ### Stage 2: Implementing Changes
50
+ Track these steps as TODOs and complete them one by one.
50
51
  1. **Read proposal.md** - Understand what's being built
51
52
  2. **Read design.md** (if exists) - Review technical decisions
52
53
  3. **Read tasks.md** - Get implementation checklist
53
54
  4. **Implement tasks sequentially** - Complete in order
54
- 5. **Mark complete immediately** - Update \`- [x]\` after each task
55
- 6. **Approval gate** - Do not start implementation until the proposal is reviewed and approved
55
+ 5. **Confirm completion** - Ensure every item in \`tasks.md\` is finished before updating statuses
56
+ 6. **Update checklist** - After all work is done, set every task to \`- [x]\` so the list reflects reality
57
+ 7. **Approval gate** - Do not start implementation until the proposal is reviewed and approved
56
58
 
57
59
  ### Stage 3: Archiving Changes
58
60
  After deployment, create separate PR to:
59
61
  - Move \`changes/[name]/\` → \`changes/archive/YYYY-MM-DD-[name]/\`
60
62
  - Update \`specs/\` if capabilities changed
61
- - Use \`openspec archive [change] --skip-specs\` for tooling-only changes
63
+ - Use \`openspec archive [change] --skip-specs --yes\` for tooling-only changes
62
64
  - Run \`openspec validate --strict\` to confirm the archived change passes checks
63
65
 
64
66
  ## Before Any Task
@@ -95,7 +97,7 @@ openspec list --specs # List specifications
95
97
  openspec show [item] # Display change or spec
96
98
  openspec diff [change] # Show spec differences
97
99
  openspec validate [item] # Validate changes or specs
98
- openspec archive [change] # Archive after deployment
100
+ openspec archive [change] [--yes|-y] # Archive after deployment (add --yes for non-interactive runs)
99
101
 
100
102
  # Project management
101
103
  openspec init [path] # Initialize OpenSpec
@@ -117,6 +119,7 @@ openspec validate [change] --strict
117
119
  - \`--strict\` - Comprehensive validation
118
120
  - \`--no-interactive\` - Disable prompts
119
121
  - \`--skip-specs\` - Archive without spec updates
122
+ - \`--yes\`/\`-y\` - Skip confirmation prompts (non-interactive archive)
120
123
 
121
124
  ## Directory Structure
122
125
 
@@ -447,7 +450,7 @@ openspec list # What's in progress?
447
450
  openspec show [item] # View details
448
451
  openspec diff [change] # What's changing?
449
452
  openspec validate --strict # Is it correct?
450
- openspec archive [change] # Mark complete
453
+ openspec archive [change] [--yes|-y] # Mark complete (add --yes for automation)
451
454
  \`\`\`
452
455
 
453
456
  Remember: Specs are truth. Changes are proposals. Keep them in sync.
@@ -1,2 +1,2 @@
1
- export { agentsTemplate as claudeTemplate } from './agents-template.js';
1
+ export { agentsRootStubTemplate as claudeTemplate } from './agents-root-stub.js';
2
2
  //# sourceMappingURL=claude-template.d.ts.map
@@ -1,2 +1,2 @@
1
- export { agentsTemplate as claudeTemplate } from './agents-template.js';
1
+ export { agentsRootStubTemplate as claudeTemplate } from './agents-root-stub.js';
2
2
  //# sourceMappingURL=claude-template.js.map
@@ -1,6 +1,7 @@
1
1
  import { agentsTemplate } from './agents-template.js';
2
2
  import { projectTemplate } from './project-template.js';
3
3
  import { claudeTemplate } from './claude-template.js';
4
+ import { agentsRootStubTemplate } from './agents-root-stub.js';
4
5
  import { getSlashCommandBody } from './slash-command-templates.js';
5
6
  export class TemplateManager {
6
7
  static getTemplates(context = {}) {
@@ -19,7 +20,7 @@ export class TemplateManager {
19
20
  return claudeTemplate;
20
21
  }
21
22
  static getAgentsStandardTemplate() {
22
- return agentsTemplate;
23
+ return agentsRootStubTemplate;
23
24
  }
24
25
  static getSlashCommandBody(id) {
25
26
  return getSlashCommandBody(id);
@@ -16,10 +16,12 @@ const proposalReferences = `**Reference**
16
16
  - Search existing requirements with \`rg -n "Requirement:|Scenario:" openspec/specs\` before writing new ones.
17
17
  - Explore the codebase with \`rg <keyword>\`, \`ls\`, or direct file reads so proposals align with current implementation realities.`;
18
18
  const applySteps = `**Steps**
19
+ Track these steps as TODOs and complete them one by one.
19
20
  1. Read \`changes/<id>/proposal.md\`, \`design.md\` (if present), and \`tasks.md\` to confirm scope and acceptance criteria.
20
21
  2. Work through tasks sequentially, keeping edits minimal and focused on the requested change.
21
- 3. Mark each task \`- [x]\` immediately after completing it to keep the checklist in sync.
22
- 4. Reference \`openspec list\` or \`openspec show <item>\` when additional context is required.`;
22
+ 3. Confirm completion before updating statuses—make sure every item in \`tasks.md\` is finished.
23
+ 4. Update the checklist after all work is done so each task is marked \`- [x]\` and reflects reality.
24
+ 5. Reference \`openspec list\` or \`openspec show <item>\` when additional context is required.`;
23
25
  const applyReferences = `**Reference**
24
26
  - Use \`openspec show <id> --json --deltas-only\` if you need additional context from the proposal while implementing.`;
25
27
  const archiveSteps = `**Steps**
@@ -1,10 +1,9 @@
1
1
  import path from 'path';
2
2
  import { FileSystemUtils } from '../utils/file-system.js';
3
- import { OPENSPEC_DIR_NAME, OPENSPEC_MARKERS } from './config.js';
4
- import { agentsTemplate } from './templates/agents-template.js';
5
- import { TemplateManager } from './templates/index.js';
3
+ import { OPENSPEC_DIR_NAME } from './config.js';
6
4
  import { ToolRegistry } from './configurators/registry.js';
7
5
  import { SlashCommandRegistry } from './configurators/slash/registry.js';
6
+ import { agentsTemplate } from './templates/agents-template.js';
8
7
  export class UpdateCommand {
9
8
  async execute(projectPath) {
10
9
  const resolvedProjectPath = path.resolve(projectPath);
@@ -16,34 +15,36 @@ export class UpdateCommand {
16
15
  }
17
16
  // 2. Update AGENTS.md (full replacement)
18
17
  const agentsPath = path.join(openspecPath, 'AGENTS.md');
19
- const rootAgentsPath = path.join(resolvedProjectPath, 'AGENTS.md');
20
- const rootAgentsExisted = await FileSystemUtils.fileExists(rootAgentsPath);
21
18
  await FileSystemUtils.writeFile(agentsPath, agentsTemplate);
22
- const agentsStandardContent = TemplateManager.getAgentsStandardTemplate();
23
- await FileSystemUtils.updateFileWithMarkers(rootAgentsPath, agentsStandardContent, OPENSPEC_MARKERS.start, OPENSPEC_MARKERS.end);
24
19
  // 3. Update existing AI tool configuration files only
25
20
  const configurators = ToolRegistry.getAll();
26
21
  const slashConfigurators = SlashCommandRegistry.getAll();
27
- let updatedFiles = [];
28
- let failedFiles = [];
29
- let updatedSlashFiles = [];
30
- let failedSlashTools = [];
22
+ const updatedFiles = [];
23
+ const createdFiles = [];
24
+ const failedFiles = [];
25
+ const updatedSlashFiles = [];
26
+ const failedSlashTools = [];
31
27
  for (const configurator of configurators) {
32
28
  const configFilePath = path.join(resolvedProjectPath, configurator.configFileName);
33
- // Only update if the file already exists
34
- if (await FileSystemUtils.fileExists(configFilePath)) {
35
- try {
36
- if (!await FileSystemUtils.canWriteFile(configFilePath)) {
37
- throw new Error(`Insufficient permissions to modify ${configurator.configFileName}`);
38
- }
39
- await configurator.configure(resolvedProjectPath, openspecPath);
40
- updatedFiles.push(configurator.configFileName);
29
+ const fileExists = await FileSystemUtils.fileExists(configFilePath);
30
+ const shouldConfigure = fileExists || configurator.configFileName === 'AGENTS.md';
31
+ if (!shouldConfigure) {
32
+ continue;
33
+ }
34
+ try {
35
+ if (fileExists && !await FileSystemUtils.canWriteFile(configFilePath)) {
36
+ throw new Error(`Insufficient permissions to modify ${configurator.configFileName}`);
41
37
  }
42
- catch (error) {
43
- failedFiles.push(configurator.configFileName);
44
- console.error(`Failed to update ${configurator.configFileName}: ${error instanceof Error ? error.message : String(error)}`);
38
+ await configurator.configure(resolvedProjectPath, openspecPath);
39
+ updatedFiles.push(configurator.configFileName);
40
+ if (!fileExists) {
41
+ createdFiles.push(configurator.configFileName);
45
42
  }
46
43
  }
44
+ catch (error) {
45
+ failedFiles.push(configurator.configFileName);
46
+ console.error(`Failed to update ${configurator.configFileName}: ${error instanceof Error ? error.message : String(error)}`);
47
+ }
47
48
  }
48
49
  for (const slashConfigurator of slashConfigurators) {
49
50
  if (!slashConfigurator.isAvailable) {
@@ -51,30 +52,34 @@ export class UpdateCommand {
51
52
  }
52
53
  try {
53
54
  const updated = await slashConfigurator.updateExisting(resolvedProjectPath, openspecPath);
54
- updatedSlashFiles = updatedSlashFiles.concat(updated);
55
+ updatedSlashFiles.push(...updated);
55
56
  }
56
57
  catch (error) {
57
58
  failedSlashTools.push(slashConfigurator.toolId);
58
59
  console.error(`Failed to update slash commands for ${slashConfigurator.toolId}: ${error instanceof Error ? error.message : String(error)}`);
59
60
  }
60
61
  }
61
- // 4. Success message (ASCII-safe)
62
- const instructionUpdates = ['openspec/AGENTS.md'];
63
- instructionUpdates.push(`AGENTS.md${rootAgentsExisted ? '' : ' (created)'}`);
64
- const messages = [`Updated OpenSpec instructions (${instructionUpdates.join(', ')})`];
65
- if (updatedFiles.length > 0) {
66
- messages.push(`Updated AI tool files: ${updatedFiles.join(', ')}`);
62
+ const summaryParts = [];
63
+ const instructionFiles = ['openspec/AGENTS.md'];
64
+ if (updatedFiles.includes('AGENTS.md')) {
65
+ instructionFiles.push(createdFiles.includes('AGENTS.md') ? 'AGENTS.md (created)' : 'AGENTS.md');
67
66
  }
68
- if (updatedSlashFiles.length > 0) {
69
- messages.push(`Updated slash commands: ${updatedSlashFiles.join(', ')}`);
67
+ summaryParts.push(`Updated OpenSpec instructions (${instructionFiles.join(', ')})`);
68
+ const aiToolFiles = updatedFiles.filter((file) => file !== 'AGENTS.md');
69
+ if (aiToolFiles.length > 0) {
70
+ summaryParts.push(`Updated AI tool files: ${aiToolFiles.join(', ')}`);
70
71
  }
71
- if (failedFiles.length > 0) {
72
- messages.push(`Failed to update: ${failedFiles.join(', ')}`);
72
+ if (updatedSlashFiles.length > 0) {
73
+ summaryParts.push(`Updated slash commands: ${updatedSlashFiles.join(', ')}`);
73
74
  }
74
- if (failedSlashTools.length > 0) {
75
- messages.push(`Failed slash command updates: ${failedSlashTools.join(', ')}`);
75
+ const failedItems = [
76
+ ...failedFiles,
77
+ ...failedSlashTools.map((toolId) => `slash command refresh (${toolId})`),
78
+ ];
79
+ if (failedItems.length > 0) {
80
+ summaryParts.push(`Failed to update: ${failedItems.join(', ')}`);
76
81
  }
77
- console.log(messages.join('\n'));
82
+ console.log(summaryParts.join(' | '));
78
83
  }
79
84
  }
80
85
  //# sourceMappingURL=update.js.map
@@ -297,7 +297,8 @@ export class Validator {
297
297
  return msg;
298
298
  }
299
299
  extractNameFromPath(filePath) {
300
- const parts = filePath.split('/');
300
+ const normalizedPath = filePath.replaceAll('\\', '/');
301
+ const parts = normalizedPath.split('/');
301
302
  // Look for the directory name after 'specs' or 'changes'
302
303
  for (let i = parts.length - 1; i >= 0; i--) {
303
304
  if (parts[i] === 'specs' || parts[i] === 'changes') {
@@ -307,8 +308,9 @@ export class Validator {
307
308
  }
308
309
  }
309
310
  // Fallback to filename without extension if not in expected structure
310
- const fileName = parts[parts.length - 1];
311
- return fileName.replace('.md', '');
311
+ const fileName = parts[parts.length - 1] ?? '';
312
+ const dotIndex = fileName.lastIndexOf('.');
313
+ return dotIndex > 0 ? fileName.slice(0, dotIndex) : fileName;
312
314
  }
313
315
  createReport(issues) {
314
316
  const errors = issues.filter(i => i.level === 'ERROR').length;
@@ -1,5 +1,34 @@
1
1
  import { promises as fs } from 'fs';
2
2
  import path from 'path';
3
+ function isMarkerOnOwnLine(content, markerIndex, markerLength) {
4
+ let leftIndex = markerIndex - 1;
5
+ while (leftIndex >= 0 && content[leftIndex] !== '\n') {
6
+ const char = content[leftIndex];
7
+ if (char !== ' ' && char !== '\t' && char !== '\r') {
8
+ return false;
9
+ }
10
+ leftIndex--;
11
+ }
12
+ let rightIndex = markerIndex + markerLength;
13
+ while (rightIndex < content.length && content[rightIndex] !== '\n') {
14
+ const char = content[rightIndex];
15
+ if (char !== ' ' && char !== '\t' && char !== '\r') {
16
+ return false;
17
+ }
18
+ rightIndex++;
19
+ }
20
+ return true;
21
+ }
22
+ function findMarkerIndex(content, marker, fromIndex = 0) {
23
+ let currentIndex = content.indexOf(marker, fromIndex);
24
+ while (currentIndex !== -1) {
25
+ if (isMarkerOnOwnLine(content, currentIndex, marker.length)) {
26
+ return currentIndex;
27
+ }
28
+ currentIndex = content.indexOf(marker, currentIndex + marker.length);
29
+ }
30
+ return -1;
31
+ }
3
32
  export class FileSystemUtils {
4
33
  static async createDirectory(dirPath) {
5
34
  await fs.mkdir(dirPath, { recursive: true });
@@ -56,9 +85,14 @@ export class FileSystemUtils {
56
85
  let existingContent = '';
57
86
  if (await this.fileExists(filePath)) {
58
87
  existingContent = await this.readFile(filePath);
59
- const startIndex = existingContent.indexOf(startMarker);
60
- const endIndex = existingContent.indexOf(endMarker);
88
+ const startIndex = findMarkerIndex(existingContent, startMarker);
89
+ const endIndex = startIndex !== -1
90
+ ? findMarkerIndex(existingContent, endMarker, startIndex + startMarker.length)
91
+ : findMarkerIndex(existingContent, endMarker);
61
92
  if (startIndex !== -1 && endIndex !== -1) {
93
+ if (endIndex < startIndex) {
94
+ throw new Error(`Invalid marker state in ${filePath}. End marker appears before start marker.`);
95
+ }
62
96
  const before = existingContent.substring(0, startIndex);
63
97
  const after = existingContent.substring(endIndex + endMarker.length);
64
98
  existingContent = before + startMarker + '\n' + content + '\n' + endMarker + after;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fission-ai/openspec",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "AI-native system for spec-driven development",
5
5
  "keywords": [
6
6
  "openspec",