mirror of
https://github.com/Fission-AI/OpenSpec.git
synced 2026-10-04 06:18:24 +08:00
Compare commits
32
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a55a5c9eb4 | ||
|
|
c482f1b47a | ||
|
|
2ae0484ac7 | ||
|
|
8c65b47abe | ||
|
|
9c9e57daa1 | ||
|
|
c7ca76cb4f | ||
|
|
06bd3999bf | ||
|
|
821097079a | ||
|
|
42e3118b0c | ||
|
|
a785c2a99a | ||
|
|
af513191eb | ||
|
|
efbbf3b9f1 | ||
|
|
6105211163 | ||
|
|
b3d31d224d | ||
|
|
9ae6141eb1 | ||
|
|
d84069a3ae | ||
|
|
8c974f8a80 | ||
|
|
25289b510d | ||
|
|
d070d08aa8 | ||
|
|
6539ceb54a | ||
|
|
c29b06da42 | ||
|
|
4a2b23942c | ||
|
|
807b9d32a6 | ||
|
|
b3d05d2f78 | ||
|
|
9848242587 | ||
|
|
5e0d21d1ed | ||
|
|
31d85d0e8b | ||
|
|
bc3666d702 | ||
|
|
970b9f6e2d | ||
|
|
5cb84a775e | ||
|
|
adc63069a9 | ||
|
|
f8eca37796 |
@@ -8,8 +8,13 @@ permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
prepare:
|
||||
if: github.repository == 'Fission-AI/OpenSpec'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
@@ -24,14 +29,22 @@ jobs:
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
scope: '@fission-ai'
|
||||
always-auth: true
|
||||
|
||||
- run: pnpm install --frozen-lockfile
|
||||
|
||||
# Opens/updates the Version Packages PR; no publishing here
|
||||
# Opens/updates the Version Packages PR; publishes when the Version PR merges
|
||||
- name: Create/Update Version PR
|
||||
uses: changesets/action@v1
|
||||
with:
|
||||
title: 'chore(release): version packages'
|
||||
createGithubReleases: true
|
||||
# Use CI-specific release script: relies on version PR having been merged
|
||||
# so package.json already contains the bumped version.
|
||||
publish: pnpm run release:ci
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
name: Publish to npm
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch: {}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
group: publish-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
scope: '@fission-ai'
|
||||
always-auth: true
|
||||
|
||||
- run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build project
|
||||
run: pnpm run build
|
||||
|
||||
- name: Ensure running from a tag
|
||||
run: |
|
||||
if [[ "$GITHUB_REF" != refs/tags/* ]]; then
|
||||
echo "This workflow must run from a tag (got: $GITHUB_REF)";
|
||||
exit 1;
|
||||
fi
|
||||
|
||||
- name: Verify release tag matches package.json
|
||||
run: |
|
||||
TAG="${GITHUB_REF_NAME#v}"
|
||||
PKG_VERSION=$(node -p "require('./package.json').version")
|
||||
if [ "$TAG" != "$PKG_VERSION" ]; then
|
||||
echo "Tag v$TAG does not match package.json $PKG_VERSION"; exit 1
|
||||
fi
|
||||
|
||||
- name: Debug npm auth and context
|
||||
run: |
|
||||
test -n "$NODE_AUTH_TOKEN" || (echo "NODE_AUTH_TOKEN is missing" && exit 1)
|
||||
echo "NODE_AUTH_TOKEN present"
|
||||
npm --version
|
||||
pnpm --version
|
||||
node --version
|
||||
npm config get registry
|
||||
npm whoami
|
||||
npm ping
|
||||
|
||||
- run: pnpm test
|
||||
|
||||
- name: Publish
|
||||
run: pnpm publish --access public --provenance --no-git-checks
|
||||
@@ -1,19 +1,18 @@
|
||||
# Repository Guidelines
|
||||
<!-- OPENSPEC:START -->
|
||||
# OpenSpec Instructions
|
||||
|
||||
## Project Structure & Module Organization
|
||||
OpenSpec ships as a TypeScript-first CLI. Source code lives in `src`, with feature logic in `core`, interactive flows in `cli`, reusable helpers in `utils`, and command wiring in `commands`. After `pnpm run build`, deliverables land in `dist` and feed the published entry point `bin/openspec.js`. Specs and change proposals reside in `openspec/specs` and `openspec/changes`; update them whenever behavior shifts so automation stays aligned. Shared assets live in `assets`, and Vitest suites in `test` mirror the source layout for easy cross-reference.
|
||||
These instructions are for AI assistants working in this project.
|
||||
|
||||
## Build, Test, and Development Commands
|
||||
Run `pnpm install` to sync dependencies. `pnpm run build` compiles TypeScript to `dist` and must stay green before release. Use `pnpm run dev` for a `tsc --watch` loop and `pnpm run dev:cli` to rebuild then execute the local CLI. `pnpm test` runs the Vitest suite once, `pnpm run test:watch` keeps it hot while iterating, and `pnpm run test:coverage` verifies instrumentation thresholds. Use `pnpm run changeset` when preparing a release entry.
|
||||
Always open `@/openspec/AGENTS.md` when the request:
|
||||
- Mentions planning or proposals (words like proposal, spec, change, plan)
|
||||
- Introduces new capabilities, breaking changes, architecture shifts, or big performance/security work
|
||||
- Sounds ambiguous and you need the authoritative spec before coding
|
||||
|
||||
## Coding Style & Naming Conventions
|
||||
We follow idiomatic TypeScript with ES modules, 2-space indentation, and semicolons. Prefer named exports from index barrels and keep filenames kebab-cased (e.g., `list-command.ts`). Classes use `PascalCase`, functions and variables use `camelCase`, and constants representing flags may use `SCREAMING_SNAKE_CASE`. Keep modules small, colocate helpers under `src/utils`, and avoid new dependencies without spec-backed justification.
|
||||
Use `@/openspec/AGENTS.md` to learn:
|
||||
- How to create and apply change proposals
|
||||
- Spec format and conventions
|
||||
- Project structure and guidelines
|
||||
|
||||
## Testing Guidelines
|
||||
Every behavior change needs Vitest coverage under `test`, co-located by feature (e.g., `test/core/update.test.ts`). Name suites after the module under test and lean on `vitest.setup.ts` for shared configuration. Run `pnpm test` before pushing and add regression cases for each bug fix or spec requirement.
|
||||
Keep this managed block so 'openspec update' can refresh the instructions.
|
||||
|
||||
## Commit & Pull Request Guidelines
|
||||
Commits follow Conventional Commits (`type(scope): subject`) and stay single-line. Reference the touched module in the scope when practical. Each PR should summarize the spec or issue it fulfills, list manual verification steps, and note updates to any `openspec/` assets. Include CLI output snippets or screenshots when the UX changes, and ensure CI and coverage checks pass before requesting review.
|
||||
|
||||
## OpenSpec Workflow Tips
|
||||
Treat specs as the contract: update `openspec/project.md` or the relevant `openspec/specs/*.md` before coding, then run `pnpm run dev:cli` to validate the CLI against the revised artifacts. `openspec list --specs` confirms the catalog, and `openspec change` drafts proposals—commit these alongside code so reviewers can trace rationale to implementation.
|
||||
<!-- OPENSPEC:END -->
|
||||
|
||||
@@ -1,5 +1,55 @@
|
||||
# @fission-ai/openspec
|
||||
|
||||
## 0.9.2
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 2ae0484: Fix cross-platform path handling issues. This release includes fixes for joinPath behavior and slash command path resolution to ensure OpenSpec works correctly across all platforms.
|
||||
|
||||
## 0.9.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 8210970: Fix OpenSpec not working on Windows when Codex integration is selected. This release includes fixes for cross-platform path handling and normalization to ensure OpenSpec works correctly on Windows systems.
|
||||
|
||||
## 0.9.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- efbbf3b: Add support for Codex and GitHub Copilot slash commands with YAML frontmatter and $ARGUMENTS
|
||||
|
||||
## Unreleased
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- Add GitHub Copilot slash command support. OpenSpec now writes prompts to `.github/prompts/openspec-{proposal,apply,archive}.prompt.md` with YAML frontmatter and `$ARGUMENTS` placeholder, and refreshes them on `openspec update`.
|
||||
|
||||
## 0.8.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- d070d08: Fix CLI version mismatch and add a release guard that validates the packed tarball prints the same version as package.json via `openspec --version`.
|
||||
|
||||
## 0.8.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- c29b06d: Add Windsurf support.
|
||||
- Add Codex slash command support. OpenSpec now writes prompts directly to Codex's global directory (`~/.codex/prompts` or `$CODEX_HOME/prompts`) and refreshes them on `openspec update`.
|
||||
|
||||
## 0.7.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- Add native Kilo Code workflow integration so `openspec init` and `openspec update` manage `.kilocode/workflows/openspec-*.md` files.
|
||||
- Always scaffold the managed root `AGENTS.md` hand-off stub and regroup the AI tool prompts during init/update to keep instructions consistent.
|
||||
|
||||
## 0.6.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- Slim the generated root agent instructions down to a managed hand-off stub and update the init/update flows to refresh it safely.
|
||||
|
||||
## 0.5.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
<a href="https://nodejs.org/"><img alt="node version" src="https://img.shields.io/node/v/@fission-ai/openspec?style=flat-square" /></a>
|
||||
<a href="./LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square" /></a>
|
||||
<a href="https://conventionalcommits.org"><img alt="Conventional Commits" src="https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg?style=flat-square" /></a>
|
||||
<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>
|
||||
<a href="https://discord.gg/YctCnvvshC"><img alt="Discord" src="https://img.shields.io/badge/Discord-Join%20the%20community-5865F2?logo=discord&logoColor=white&style=flat-square" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -23,7 +23,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
Follow <a href="https://x.com/0xTab">@0xTab on X</a> for updates · Join the <a href="https://discord.gg/saTQQGQZ">OpenSpec Discord</a> for help and questions.
|
||||
Follow <a href="https://x.com/0xTab">@0xTab on X</a> for updates · Join the <a href="https://discord.gg/YctCnvvshC">OpenSpec Discord</a> for help and questions.
|
||||
</p>
|
||||
|
||||
# OpenSpec
|
||||
@@ -40,6 +40,15 @@ Key outcomes:
|
||||
- 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 OpenSpec compares (at a glance)
|
||||
|
||||
- **Lightweight**: simple workflow, no API keys, minimal setup.
|
||||
- **Brownfield-first**: works great beyond 0→1. OpenSpec separates the source of truth from proposals: `openspec/specs/` (current truth) and `openspec/changes/` (proposed updates). This keeps diffs explicit and manageable across features.
|
||||
- **Change tracking**: proposals, tasks, and spec deltas live together; archiving merges the approved updates back into specs.
|
||||
- **Compared to spec-kit & Kiro**: those shine for brand-new features (0→1). OpenSpec also excels when modifying existing behavior (1→n), especially when updates span multiple specs.
|
||||
|
||||
See the full comparison in [How OpenSpec Compares](#how-openspec-compares).
|
||||
|
||||
## How It Works
|
||||
|
||||
```
|
||||
@@ -84,13 +93,19 @@ These tools have built-in OpenSpec commands. Select the OpenSpec integration whe
|
||||
| **Claude Code** | `/openspec:proposal`, `/openspec:apply`, `/openspec:archive` |
|
||||
| **Cursor** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` |
|
||||
| **OpenCode** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` |
|
||||
| **Kilo Code** | `/openspec-proposal.md`, `/openspec-apply.md`, `/openspec-archive.md` (`.kilocode/workflows/`) |
|
||||
| **Windsurf** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` (`.windsurf/workflows/`) |
|
||||
| **Codex** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` (global: `~/.codex/prompts`, auto-installed) |
|
||||
| **GitHub Copilot** | `/openspec-proposal`, `/openspec-apply`, `/openspec-archive` (`.github/prompts/`) |
|
||||
|
||||
Kilo Code discovers team workflows automatically. Save the generated files under `.kilocode/workflows/` and trigger them from the command palette with `/openspec-proposal.md`, `/openspec-apply.md`, or `/openspec-archive.md`.
|
||||
|
||||
#### 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 • Gemini CLI • GitHub Copilot • Others |
|
||||
| Amp • Jules • Gemini CLI • Others |
|
||||
|
||||
### Install & Initialize
|
||||
|
||||
@@ -121,8 +136,8 @@ openspec init
|
||||
```
|
||||
|
||||
**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
|
||||
- You'll be prompted to pick any natively supported AI tools (Claude Code, Cursor, OpenCode, etc.); other assistants always rely on the shared `AGENTS.md` stub
|
||||
- OpenSpec automatically configures slash commands for the tools you choose and always writes a managed `AGENTS.md` hand-off at the project root
|
||||
- A new `openspec/` directory structure is created in your project
|
||||
|
||||
**After setup:**
|
||||
@@ -194,7 +209,7 @@ Or run the command yourself in terminal:
|
||||
$ openspec archive add-profile-filters --yes # Archive the completed change without prompts
|
||||
```
|
||||
|
||||
**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".
|
||||
**Note:** Tools with native slash commands (Claude Code, Cursor, Codex) 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
|
||||
|
||||
@@ -292,6 +307,9 @@ Deltas are "patches" that show how specs change:
|
||||
|
||||
## How OpenSpec Compares
|
||||
|
||||
### vs. spec-kit
|
||||
OpenSpec’s two-folder model (`openspec/specs/` for the current truth, `openspec/changes/` for proposed updates) keeps state and diffs separate. This scales when you modify existing features or touch multiple specs. spec-kit is strong for greenfield/0→1 but provides less structure for cross-spec updates and evolving features.
|
||||
|
||||
### vs. Kiro.dev
|
||||
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.
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
## Why
|
||||
- Codex (the VS Code extension formerly known as Codeium Chat) exposes "slash commands" by reading Markdown prompt files from `~/.codex/prompts/`. Each file name becomes the `/command` users can run, with YAML frontmatter for metadata (`description`, `argument-hint`) and `$ARGUMENTS` to capture user input. The workflow screenshot shared by Kevin Kern ("Codex problem analyzer") shows the format OpenSpec should target so teams can invoke curated workflows straight from the chat palette.
|
||||
- Teams already rely on OpenSpec to manage the slash-command surface area for Claude, Cursor, OpenCode, Kilo Code, and Windsurf. Leaving Codex out forces them to manually copy/paste OpenSpec guardrails into `~/.codex/prompts/*.md`, which drifts quickly and undermines the "single source of truth" promise of the CLI.
|
||||
- Codex commands live outside the repository (under the user's home directory), so shipping an automated configurator that both scaffolds the prompts and keeps them refreshed via `openspec update` eliminates error-prone manual steps and keeps OpenSpec instructions synchronized across assistants.
|
||||
|
||||
## What Changes
|
||||
- Add Codex to the `openspec init` tool picker with the same "already configured" detection we use for other editors, wiring an implementation that writes managed Markdown prompts directly to Codex's global directory (`~/.codex/prompts` or `$CODEX_HOME/prompts`) with OpenSpec marker blocks.
|
||||
- Produce three Codex prompt files—`openspec-proposal.md`, `openspec-apply.md`, and `openspec-archive.md`—whose content mirrors the shared slash-command templates while using YAML frontmatter (`description` and `argument-hint` fields) and `$ARGUMENTS` to capture all arguments as a single string (matching the GitHub Copilot pattern and official Codex specification).
|
||||
- Document Codex's global-only discovery and that OpenSpec writes prompts directly to `~/.codex/prompts` (or `$CODEX_HOME/prompts`).
|
||||
- Teach `openspec update` to refresh existing Codex prompts in-place (and only when they already exist) in the global directory, updating both frontmatter and body.
|
||||
- Document Codex support alongside other slash-command integrations and add regression coverage that exercises init/update behaviour against a temporary global prompts directory via `CODEX_HOME`.
|
||||
|
||||
## Impact
|
||||
- Specs: `cli-init`, `cli-update`
|
||||
- Code: `src/core/config.ts`, `src/core/configurators/slash/*`, `src/core/templates/slash-command-templates.ts`, CLI tool summaries, docs
|
||||
- Tests: integration coverage for Codex prompt scaffolding and refresh logic
|
||||
- Docs: README and CHANGELOG entries announcing Codex slash-command support
|
||||
|
||||
## Current Spec Reference
|
||||
- `specs/cli-init/spec.md`
|
||||
- Requirements cover init UX, directory scaffolding, AI tool configuration, and the existing slash-command support for Claude Code, Cursor, and OpenCode.
|
||||
- Our `## MODIFIED` delta in `changes/.../specs/cli-init/spec.md` copies the full "Slash Command Configuration" requirement (header, description, and all scenarios) before appending the new Codex scenario so archiving will retain every prior scenario.
|
||||
- `specs/cli-update/spec.md`
|
||||
- Requirements define update preconditions, template refresh behavior, and slash-command refresh logic for Claude Code, Cursor, and OpenCode.
|
||||
- The corresponding delta preserves the entire "Slash Command Updates" requirement while adding the Codex refresh scenario, ensuring the archive workflow replaces the block without losing the existing scenarios or the "Missing slash command file" guardrail.
|
||||
@@ -0,0 +1,56 @@
|
||||
## MODIFIED Requirements
|
||||
### Requirement: AI Tool Configuration
|
||||
The command SHALL configure AI coding assistants with OpenSpec instructions using a marker system.
|
||||
#### 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)
|
||||
- OpenCode (creates or refreshes `.opencode/command/openspec-*.md` slash commands)
|
||||
- Windsurf (creates or refreshes `.windsurf/workflows/openspec-*.md` workflows)
|
||||
- Kilo Code (creates or refreshes `.kilocode/workflows/openspec-*.md` workflows)
|
||||
- Codex (creates or refreshes global prompts at `~/.codex/prompts/openspec-*.md`)
|
||||
- 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: Slash Command Configuration
|
||||
The init command SHALL generate slash command files for supported editors using shared templates.
|
||||
|
||||
#### Scenario: Generating slash commands for Claude Code
|
||||
- **WHEN** the user selects Claude Code during initialization
|
||||
- **THEN** create `.claude/commands/openspec/proposal.md`, `.claude/commands/openspec/apply.md`, and `.claude/commands/openspec/archive.md`
|
||||
- **AND** populate each file from shared templates so command text matches other tools
|
||||
- **AND** each template includes instructions for the relevant OpenSpec workflow stage
|
||||
|
||||
#### Scenario: Generating slash commands for Cursor
|
||||
- **WHEN** the user selects Cursor during initialization
|
||||
- **THEN** create `.cursor/commands/openspec-proposal.md`, `.cursor/commands/openspec-apply.md`, and `.cursor/commands/openspec-archive.md`
|
||||
- **AND** populate each file from shared templates so command text matches other tools
|
||||
- **AND** each template includes instructions for the relevant OpenSpec workflow stage
|
||||
|
||||
#### Scenario: Generating slash commands for OpenCode
|
||||
- **WHEN** the user selects OpenCode during initialization
|
||||
- **THEN** create `.opencode/command/openspec-proposal.md`, `.opencode/command/openspec-apply.md`, and `.opencode/command/openspec-archive.md`
|
||||
- **AND** populate each file from shared templates so command text matches other tools
|
||||
- **AND** each template includes instructions for the relevant OpenSpec workflow stage
|
||||
|
||||
#### Scenario: Generating slash commands for Windsurf
|
||||
- **WHEN** the user selects Windsurf during initialization
|
||||
- **THEN** create `.windsurf/workflows/openspec-proposal.md`, `.windsurf/workflows/openspec-apply.md`, and `.windsurf/workflows/openspec-archive.md`
|
||||
- **AND** populate each file from shared templates (wrapped in OpenSpec markers) so workflow text matches other tools
|
||||
- **AND** each template includes instructions for the relevant OpenSpec workflow stage
|
||||
|
||||
#### Scenario: Generating slash commands for Kilo Code
|
||||
- **WHEN** the user selects Kilo Code during initialization
|
||||
- **THEN** create `.kilocode/workflows/openspec-proposal.md`, `.kilocode/workflows/openspec-apply.md`, and `.kilocode/workflows/openspec-archive.md`
|
||||
- **AND** populate each file from shared templates (wrapped in OpenSpec markers) so workflow text matches other tools
|
||||
- **AND** each template includes instructions for the relevant OpenSpec workflow stage
|
||||
|
||||
#### Scenario: Generating slash commands for Codex
|
||||
- **WHEN** the user selects Codex during initialization
|
||||
- **THEN** create global prompt files at `~/.codex/prompts/openspec-proposal.md`, `~/.codex/prompts/openspec-apply.md`, and `~/.codex/prompts/openspec-archive.md` (or under `$CODEX_HOME/prompts` if set)
|
||||
- **AND** populate each file from shared templates that map the first numbered placeholder (`$1`) to the primary user input (e.g., change identifier or question text)
|
||||
- **AND** wrap the generated content in OpenSpec markers so `openspec update` can refresh the prompts without touching surrounding custom notes
|
||||
@@ -0,0 +1,41 @@
|
||||
## MODIFIED Requirements
|
||||
### Requirement: Slash Command Updates
|
||||
The update command SHALL refresh existing slash command files for configured tools without creating new ones.
|
||||
|
||||
#### Scenario: Updating slash commands for Claude Code
|
||||
- **WHEN** `.claude/commands/openspec/` contains `proposal.md`, `apply.md`, and `archive.md`
|
||||
- **THEN** refresh each file using shared templates
|
||||
- **AND** ensure templates include instructions for the relevant workflow stage
|
||||
|
||||
#### Scenario: Updating slash commands for Cursor
|
||||
- **WHEN** `.cursor/commands/` contains `openspec-proposal.md`, `openspec-apply.md`, and `openspec-archive.md`
|
||||
- **THEN** refresh each file using shared templates
|
||||
- **AND** ensure templates include instructions for the relevant workflow stage
|
||||
|
||||
#### Scenario: Updating slash commands for OpenCode
|
||||
- **WHEN** `.opencode/command/` contains `openspec-proposal.md`, `openspec-apply.md`, and `openspec-archive.md`
|
||||
- **THEN** refresh each file using shared templates
|
||||
- **AND** ensure templates include instructions for the relevant workflow stage
|
||||
|
||||
#### Scenario: Updating slash commands for Windsurf
|
||||
- **WHEN** `.windsurf/workflows/` contains `openspec-proposal.md`, `openspec-apply.md`, and `openspec-archive.md`
|
||||
- **THEN** refresh each file using shared templates wrapped in OpenSpec markers
|
||||
- **AND** ensure templates include instructions for the relevant workflow stage
|
||||
- **AND** skip creating missing files (the update command only refreshes what already exists)
|
||||
|
||||
#### Scenario: Updating slash commands for Kilo Code
|
||||
- **WHEN** `.kilocode/workflows/` contains `openspec-proposal.md`, `openspec-apply.md`, and `openspec-archive.md`
|
||||
- **THEN** refresh each file using shared templates wrapped in OpenSpec markers
|
||||
- **AND** ensure templates include instructions for the relevant workflow stage
|
||||
- **AND** skip creating missing files (the update command only refreshes what already exists)
|
||||
|
||||
#### Scenario: Updating slash commands for Codex
|
||||
- **GIVEN** the global Codex prompt directory contains `openspec-proposal.md`, `openspec-apply.md`, and `openspec-archive.md`
|
||||
- **WHEN** a user runs `openspec update`
|
||||
- **THEN** refresh each file using the shared slash-command templates (including placeholder guidance)
|
||||
- **AND** preserve any unmanaged content outside the OpenSpec marker block
|
||||
- **AND** skip creation when a Codex prompt file is missing
|
||||
|
||||
#### Scenario: Missing slash command file
|
||||
- **WHEN** a tool lacks a slash command file
|
||||
- **THEN** do not create a new file during update
|
||||
@@ -0,0 +1,19 @@
|
||||
## 1. CLI integration
|
||||
- [x] 1.1 Add Codex to the init tool picker with display text that clarifies prompts live in the global `.codex/prompts/` directory and implement "already configured" detection by checking for managed Codex prompt files.
|
||||
- [x] 1.2 Implement a `CodexSlashCommandConfigurator` that writes `.codex/prompts/openspec-{proposal,apply,archive}.md`, ensuring the prompt directory exists and wrapping content in OpenSpec markers.
|
||||
// (No helper command required)
|
||||
- [x] 1.3 Register the configurator with the slash-command registry and include Codex in init/update wiring so both commands invoke the new configurator when appropriate.
|
||||
|
||||
## 2. Prompt templates
|
||||
- [x] 2.1 Extend the shared slash-command templates (or add a Codex-specific wrapper) to inject numbered placeholders (`$1`, `$2`, …) where Codex expects user-supplied arguments.
|
||||
- [x] 2.2 Verify generated Markdown stays within Codex's formatting expectations (no front matter, heading-first layout) and matches the problem-analyzer style shown in the reference screenshot.
|
||||
|
||||
## 3. Update support & tests
|
||||
- [x] 3.1 Update the `openspec update` flow to refresh existing Codex prompts without creating new ones when files are missing.
|
||||
- [x] 3.2 Add integration coverage that exercises init/update against a temporary global Codex prompts directory by setting `CODEX_HOME`, asserting marker preservation and idempotent updates.
|
||||
- [x] 3.3 Document Codex's global-only discovery and automatic installation in README and CHANGELOG.
|
||||
- [x] 3.3 Confirm error handling surfaces clear paths when the CLI cannot write to the Codex prompt directory (permissions, missing home directory, etc.).
|
||||
|
||||
## 4. Documentation
|
||||
- [x] 4.1 Document Codex slash-command support in the README and changelog alongside other assistant integrations.
|
||||
- [x] 4.2 Add a release note snippet that points Codex users to the generated `/openspec-proposal`, `/openspec-apply`, and `/openspec-archive` commands.
|
||||
@@ -0,0 +1,25 @@
|
||||
## Why
|
||||
- GitHub Copilot supports custom slash commands through markdown files in `.github/prompts/<name>.prompt.md`. Each file includes YAML frontmatter with a `description` label and uses `$ARGUMENTS` to capture user input. This format allows teams to expose curated workflows directly in Copilot's chat interface.
|
||||
- Teams already rely on OpenSpec to manage slash-command configurations for Claude Code, Cursor, OpenCode, Codex, Kilo Code, and Windsurf. Excluding GitHub Copilot forces developers to manually maintain OpenSpec prompts in `.github/prompts/`, which leads to drift and undermines OpenSpec's "single source of truth" promise.
|
||||
- GitHub Copilot discovers prompts from the repository's `.github/prompts/` directory, making it straightforward to version control and share across the team. Adding automated generation and refresh through `openspec init` and `openspec update` eliminates manual synchronization and keeps OpenSpec instructions consistent across all AI assistants.
|
||||
|
||||
## What Changes
|
||||
- Add GitHub Copilot to the `openspec init` tool picker with "already configured" detection similar to other editors, wiring an implementation that writes managed Markdown prompt files to `.github/prompts/` with OpenSpec marker blocks.
|
||||
- Generate three GitHub Copilot prompt files—`openspec-proposal.prompt.md`, `openspec-apply.prompt.md`, and `openspec-archive.prompt.md`—whose content mirrors shared slash-command templates while conforming to Copilot's frontmatter and `$ARGUMENTS` placeholder convention.
|
||||
- Document GitHub Copilot's repository-based discovery and that OpenSpec writes prompts to `.github/prompts/` with managed blocks.
|
||||
- Teach `openspec update` to refresh existing GitHub Copilot prompts in-place (only when they already exist) in the repository's `.github/prompts/` directory.
|
||||
- Document GitHub Copilot support alongside other slash-command integrations and add test coverage that exercises init/update behavior for `.github/prompts/` files.
|
||||
|
||||
## Impact
|
||||
- Specs: `cli-init`, `cli-update`
|
||||
- Code: `src/core/configurators/slash/github-copilot.ts` (new), `src/core/configurators/slash/registry.ts`, `src/core/templates/slash-command-templates.ts`, CLI tool summaries, docs
|
||||
- Tests: integration coverage for GitHub Copilot prompt scaffolding and refresh logic
|
||||
- Docs: README and CHANGELOG entries announcing GitHub Copilot slash-command support
|
||||
|
||||
## Current Spec Reference
|
||||
- `specs/cli-init/spec.md`
|
||||
- Requirements cover init UX, directory scaffolding, AI tool configuration, and existing slash-command support for Claude Code, Cursor, OpenCode, Codex, Kilo Code, and Windsurf.
|
||||
- Our `## MODIFIED` delta in `changes/.../specs/cli-init/spec.md` will copy the full "Slash Command Configuration" requirement (header, description, and all scenarios) before appending the new GitHub Copilot scenario so archiving retains every prior scenario.
|
||||
- `specs/cli-update/spec.md`
|
||||
- Requirements define update preconditions, template refresh behavior, and slash-command refresh logic for existing tools.
|
||||
- The corresponding delta preserves the entire "Slash Command Updates" requirement while adding the GitHub Copilot refresh scenario, ensuring the archive workflow replaces the block without losing existing scenarios or the "Missing slash command file" guardrail.
|
||||
@@ -0,0 +1,30 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Slash Command Configuration
|
||||
The init command SHALL generate slash command files for supported editors using shared templates.
|
||||
|
||||
#### Scenario: Generating slash commands for Claude Code
|
||||
- **WHEN** the user selects Claude Code during initialization
|
||||
- **THEN** create `.claude/commands/openspec/proposal.md`, `.claude/commands/openspec/apply.md`, and `.claude/commands/openspec/archive.md`
|
||||
- **AND** populate each file from shared templates so command text matches other tools
|
||||
- **AND** each template includes instructions for the relevant OpenSpec workflow stage
|
||||
|
||||
#### Scenario: Generating slash commands for Cursor
|
||||
- **WHEN** the user selects Cursor during initialization
|
||||
- **THEN** create `.cursor/commands/openspec-proposal.md`, `.cursor/commands/openspec-apply.md`, and `.cursor/commands/openspec-archive.md`
|
||||
- **AND** populate each file from shared templates so command text matches other tools
|
||||
- **AND** each template includes instructions for the relevant OpenSpec workflow stage
|
||||
|
||||
#### Scenario: Generating slash commands for OpenCode
|
||||
- **WHEN** the user selects OpenCode during initialization
|
||||
- **THEN** create `.opencode/commands/openspec-proposal.md`, `.opencode/commands/openspec-apply.md`, and `.opencode/commands/openspec-archive.md`
|
||||
- **AND** populate each file from shared templates so command text matches other tools
|
||||
- **AND** each template includes instructions for the relevant OpenSpec workflow stage
|
||||
|
||||
#### Scenario: Generating slash commands for GitHub Copilot
|
||||
- **WHEN** the user selects GitHub Copilot during initialization
|
||||
- **THEN** create `.github/prompts/openspec-proposal.prompt.md`, `.github/prompts/openspec-apply.prompt.md`, and `.github/prompts/openspec-archive.prompt.md`
|
||||
- **AND** populate each file with YAML frontmatter containing a `description` field that summarizes the workflow stage
|
||||
- **AND** include `$ARGUMENTS` placeholder to capture user input
|
||||
- **AND** wrap the shared template body with OpenSpec markers so `openspec update` can refresh the content
|
||||
- **AND** each template includes instructions for the relevant OpenSpec workflow stage
|
||||
@@ -0,0 +1,29 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Slash Command Updates
|
||||
The update command SHALL refresh existing slash command files for configured tools without creating new ones.
|
||||
|
||||
#### Scenario: Updating slash commands for Claude Code
|
||||
- **WHEN** `.claude/commands/openspec/` contains `proposal.md`, `apply.md`, and `archive.md`
|
||||
- **THEN** refresh each file using shared templates
|
||||
- **AND** ensure templates include instructions for the relevant workflow stage
|
||||
|
||||
#### Scenario: Updating slash commands for Cursor
|
||||
- **WHEN** `.cursor/commands/` contains `openspec-proposal.md`, `openspec-apply.md`, and `openspec-archive.md`
|
||||
- **THEN** refresh each file using shared templates
|
||||
- **AND** ensure templates include instructions for the relevant workflow stage
|
||||
|
||||
#### Scenario: Updating slash commands for OpenCode
|
||||
- **WHEN** `.opencode/command/` contains `openspec-proposal.md`, `openspec-apply.md`, and `openspec-archive.md`
|
||||
- **THEN** refresh each file using shared templates
|
||||
- **AND** ensure templates include instructions for the relevant workflow stage
|
||||
|
||||
#### Scenario: Updating slash commands for GitHub Copilot
|
||||
- **WHEN** `.github/prompts/` contains `openspec-proposal.prompt.md`, `openspec-apply.prompt.md`, and `openspec-archive.prompt.md`
|
||||
- **THEN** refresh each file using shared templates while preserving the YAML frontmatter
|
||||
- **AND** update only the OpenSpec-managed block between markers
|
||||
- **AND** ensure templates include instructions for the relevant workflow stage
|
||||
|
||||
#### Scenario: Missing slash command file
|
||||
- **WHEN** a tool lacks a slash command file
|
||||
- **THEN** do not create a new file during update
|
||||
@@ -0,0 +1,30 @@
|
||||
## Implementation Tasks
|
||||
|
||||
- [x] Create `src/core/configurators/slash/github-copilot.ts` implementing `SlashCommandConfigurator` base class
|
||||
- Implement `getRelativePath()` to return `.github/prompts/openspec-{proposal,apply,archive}.prompt.md`
|
||||
- Implement `getFrontmatter()` to generate YAML frontmatter with `description` field and include `$ARGUMENTS` placeholder
|
||||
- Implement `generateAll()` to create `.github/prompts/` directory and write three prompt files with frontmatter, markers, and shared template bodies
|
||||
- Implement `updateExisting()` to refresh only the managed block between markers while preserving frontmatter
|
||||
- Set `toolId = "github-copilot"` and `isAvailable = true`
|
||||
|
||||
- [x] Register GitHub Copilot configurator in `src/core/configurators/slash/registry.ts`
|
||||
- Import `GitHubCopilotSlashCommandConfigurator`
|
||||
- Add to `SLASH_COMMAND_CONFIGURATORS` array
|
||||
- Update tool picker display name to "GitHub Copilot"
|
||||
|
||||
- [x] Update `src/core/init.ts` to include GitHub Copilot in the AI tool selection prompt
|
||||
- Add GitHub Copilot to the available tools list with detection for existing `.github/prompts/openspec-*.prompt.md` files
|
||||
- Display "(already configured)" when prompt files exist
|
||||
|
||||
- [x] Update `src/core/update.ts` to refresh GitHub Copilot prompts when they exist
|
||||
- Call `updateExisting()` for GitHub Copilot configurator when `.github/prompts/` contains OpenSpec prompt files
|
||||
|
||||
- [x] Add integration tests for GitHub Copilot slash command generation
|
||||
- Test `generateAll()` creates three prompt files with correct structure (frontmatter + markers + body)
|
||||
- Test `updateExisting()` preserves frontmatter and only updates managed blocks
|
||||
- Test that missing prompt files are not created during update
|
||||
|
||||
- [x] Update documentation
|
||||
- Add GitHub Copilot to README slash-command support table
|
||||
- Document `.github/prompts/` as the discovery location
|
||||
- Add CHANGELOG entry for GitHub Copilot support
|
||||
@@ -0,0 +1,17 @@
|
||||
## Why
|
||||
- Kilo Code executes \"slash commands\" by loading markdown workflows from `.kilocode/workflows/` (or the global `~/.kilocode/workflows/`) and running them when a user types `/workflow-name.md`, making project-local workflow files the analogue to the slash-command files we already ship for other tools.\\
|
||||
([Workflows | Kilo Code Docs](https://kilocode.ai/docs/features/slash-commands/workflows))
|
||||
- Those workflows are plain markdown with step-by-step instructions that can call built-in tools and MCP integrations, so reusing OpenSpec's shared proposal/apply/archive bodies keeps behaviour aligned across assistants without inventing new content.
|
||||
- OpenSpec already detects configured tools and refreshes marker-wrapped files during `init`/`update`; extending the same mechanism to `.kilocode/workflows/openspec-*.md` ensures Kilo Code stays in sync with one source of truth.
|
||||
|
||||
## What Changes
|
||||
- Add Kilo Code to the `openspec init` tool picker with \"already configured\" detection, including wiring for extend mode so teams can refresh Kilo Code assets.
|
||||
- Implement a `KiloCodeSlashCommandConfigurator` that creates `.kilocode/workflows/openspec-{proposal,apply,archive}.md`, ensuring the workflow directory exists and wrapping shared content in OpenSpec markers (no front matter required).
|
||||
- Teach `openspec update` to refresh existing Kilo Code workflows (and only those that already exist) using the shared slash-command templates.
|
||||
- Update documentation, release notes, and integration tests so the new workflow support is covered alongside Claude, Cursor, OpenCode, and Windsurf.
|
||||
|
||||
## Impact
|
||||
- Specs: `cli-init`, `cli-update`
|
||||
- Code: `src/core/config.ts`, `src/core/configurators/(registry|slash/*)`, `src/core/templates/slash-command-templates.ts`, CLI wiring for tool summaries
|
||||
- Tests: init/update workflow coverage, regression for marker preservation in `.kilocode/workflows/`
|
||||
- Docs: README / CHANGELOG updates advertising Kilo Code workflow support
|
||||
@@ -0,0 +1,24 @@
|
||||
## MODIFIED Requirements
|
||||
### Requirement: AI Tool Configuration
|
||||
The command SHALL configure AI coding assistants with OpenSpec instructions using a marker system.
|
||||
#### 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)
|
||||
- OpenCode (creates or refreshes `.opencode/command/openspec-*.md` slash commands)
|
||||
- Windsurf (creates or refreshes `.windsurf/workflows/openspec-*.md` workflows)
|
||||
- Kilo Code (creates or refreshes `.kilocode/workflows/openspec-*.md` workflows)
|
||||
- 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: Slash Command Configuration
|
||||
The init command SHALL generate slash command files for supported editors using shared templates.
|
||||
#### Scenario: Generating slash commands for Kilo Code
|
||||
- **WHEN** the user selects Kilo Code during initialization
|
||||
- **THEN** create `.kilocode/workflows/openspec-proposal.md`, `.kilocode/workflows/openspec-apply.md`, and `.kilocode/workflows/openspec-archive.md`
|
||||
- **AND** populate each file from shared templates (wrapped in OpenSpec markers) so workflow text matches other tools
|
||||
- **AND** each template includes instructions for the relevant OpenSpec workflow stage
|
||||
@@ -0,0 +1,8 @@
|
||||
## MODIFIED Requirements
|
||||
### Requirement: Slash Command Updates
|
||||
The update command SHALL refresh existing slash command files for configured tools without creating new ones.
|
||||
#### Scenario: Updating slash commands for Kilo Code
|
||||
- **WHEN** `.kilocode/workflows/` contains `openspec-proposal.md`, `openspec-apply.md`, and `openspec-archive.md`
|
||||
- **THEN** refresh each file using shared templates wrapped in OpenSpec markers
|
||||
- **AND** ensure templates include instructions for the relevant workflow stage
|
||||
- **AND** skip creating missing files (the update command only refreshes what already exists)
|
||||
@@ -0,0 +1,15 @@
|
||||
## 1. CLI wiring
|
||||
- [x] 1.1 Add Kilo Code to the selectable AI tools in `openspec init`, including "already configured" detection and success summaries.
|
||||
- [x] 1.2 Register a `KiloCodeSlashCommandConfigurator` alongside other slash-command tools.
|
||||
|
||||
## 2. Workflow generation
|
||||
- [x] 2.1 Implement the configurator so it creates `.kilocode/workflows/` (if needed) and writes `openspec-{proposal,apply,archive}.md` with OpenSpec markers.
|
||||
- [x] 2.2 Reuse the shared slash-command bodies without front matter; verify resulting files stay Markdown-only with no extra metadata.
|
||||
|
||||
## 3. Update support
|
||||
- [x] 3.1 Ensure `openspec update` refreshes existing Kilo Code workflows while skipping ones that are absent.
|
||||
- [x] 3.2 Add regression coverage confirming marker content is replaced (not duplicated) during updates.
|
||||
|
||||
## 4. Documentation
|
||||
- [x] 4.1 Update README / docs to note Kilo Code workflow support and path (`.kilocode/workflows/`).
|
||||
- [x] 4.2 Mention the integration in CHANGELOG or release notes if applicable.
|
||||
@@ -0,0 +1,11 @@
|
||||
## Why
|
||||
Manual setup for new changes leads to formatting mistakes in spec deltas and slows agents who must recreate the same file skeletons for every proposal. A built-in scaffold command will generate compliant templates so assistants can focus on the change content instead of structure.
|
||||
|
||||
## What Changes
|
||||
- Add an `openspec scaffold <change-id>` CLI command that creates a change directory with validated `proposal.md`, `tasks.md`, and spec delta templates.
|
||||
- Update CLI documentation and quick-reference guidance so agents discover the scaffold workflow before drafting files manually.
|
||||
- Add automated coverage (unit/integ tests) to ensure the command respects existing naming rules and generated Markdown passes validation.
|
||||
|
||||
## Impact
|
||||
- Affected specs: `specs/cli-scaffold`
|
||||
- Affected code: `src/cli/index.ts`, `src/commands`, `docs/`
|
||||
@@ -0,0 +1,44 @@
|
||||
## ADDED Requirements
|
||||
### Requirement: Scaffolding Command Registration
|
||||
The CLI SHALL expose an `openspec scaffold <change-id>` command that validates the change identifier before generating files.
|
||||
|
||||
#### Scenario: Registering scaffold command
|
||||
- **WHEN** a user runs `openspec scaffold add-user-notifications`
|
||||
- **THEN** the CLI SHALL reject invalid identifiers (non kebab-case) before proceeding
|
||||
- **AND** display usage documentation via `openspec scaffold --help`
|
||||
- **AND** exit with code 0 after successful scaffolding
|
||||
|
||||
### Requirement: Change Directory Structure
|
||||
The scaffold command SHALL create the standard change workspace with proposal, tasks, optional design, and delta directories laid out according to OpenSpec conventions.
|
||||
|
||||
#### Scenario: Generating change workspace
|
||||
- **WHEN** scaffolding a new change with id `add-user-notifications`
|
||||
- **THEN** create `openspec/changes/add-user-notifications/`
|
||||
- **AND** generate `proposal.md`, `tasks.md`, and `design.md` (commented placeholder content) in that directory when missing
|
||||
- **AND** create `openspec/changes/add-user-notifications/specs/` ready for capability-specific deltas
|
||||
|
||||
### Requirement: Template Content Guidance
|
||||
The scaffold command SHALL populate generated Markdown files with OpenSpec-compliant templates so authors can copy, edit, and pass validation without reformatting.
|
||||
|
||||
#### Scenario: Populating proposal and tasks templates
|
||||
- **WHEN** the scaffold command writes `proposal.md`
|
||||
- **THEN** include the `## Why`, `## What Changes`, and `## Impact` headings with placeholder guidance text
|
||||
- **AND** ensure `tasks.md` starts with `## 1. Implementation` and numbered checklist items using `- [ ]` syntax
|
||||
- **AND** annotate optional sections (like `design.md`) with inline TODO comments so users understand when to keep or delete them
|
||||
|
||||
### Requirement: Delta Spec Creation
|
||||
The scaffold command SHALL create at least one capability delta file with correctly formatted requirement and scenario placeholders that guide authors to enter the actual behavior.
|
||||
|
||||
#### Scenario: Creating spec delta skeleton
|
||||
- **WHEN** scaffolding a change and the capability `cli-scaffold` is provided interactively or via flags
|
||||
- **THEN** generate `openspec/changes/add-user-notifications/specs/cli-scaffold/spec.md`
|
||||
- **AND** include `## ADDED Requirements` with at least one `### Requirement:` block and matching `#### Scenario:` entries that remind the author to replace placeholder text
|
||||
- **AND** ensure the generated delta passes `openspec validate add-user-notifications --strict` until the author edits it
|
||||
|
||||
### Requirement: Idempotent Execution
|
||||
The scaffold command SHALL be safe to rerun, preserving user edits while filling in any missing managed sections.
|
||||
|
||||
#### Scenario: Rerunning scaffold on existing change
|
||||
- **WHEN** the command is executed again for an existing change directory containing user-edited files
|
||||
- **THEN** leave existing content untouched except for managed placeholder regions or missing files that need creation
|
||||
- **AND** update the filesystem summary to highlight which files were skipped, created, or refreshed
|
||||
@@ -0,0 +1,11 @@
|
||||
## 1. CLI scaffolding command
|
||||
- [ ] 1.1 Register an `openspec scaffold` command in the CLI entrypoint with `change-id` argument validation.
|
||||
- [ ] 1.2 Implement generator logic that creates the change directory structure plus default `proposal.md`, `tasks.md`, and delta spec skeletons without overwriting existing populated files.
|
||||
|
||||
## 2. Templates and documentation
|
||||
- [ ] 2.1 Surface copy/paste templates and scaffold usage in the top-level quick reference for `openspec/AGENTS.md`.
|
||||
- [ ] 2.2 Refresh other CLI docs (`docs/`, README) to mention the scaffold workflow and link to instructions.
|
||||
|
||||
## 3. Test coverage
|
||||
- [ ] 3.1 Add unit tests covering name validation, file generation, and idempotent reruns.
|
||||
- [ ] 3.2 Add integration coverage ensuring generated files pass `openspec validate --strict` without manual edits.
|
||||
@@ -0,0 +1,17 @@
|
||||
## Why
|
||||
- Windsurf exposes "Workflows" as the vehicle for slash-like automation: saved Markdown files under `.windsurf/workflows/` that Cascade discovers across the workspace (including subdirectories and up to the git root), then executes when a user types `/workflow-name`. These files can be team-authored, must stay under 12k characters, and can call other workflows, making them the natural place to publish OpenSpec guidance for Windsurf users.\
|
||||
([Windsurf Workflows documentation](https://docs.windsurf.com/windsurf/cascade/workflows))
|
||||
- The Wave 12 changelog reiterates that workflows are invoked via slash commands and that Windsurf stores them in `.windsurf/workflows`, so the OpenSpec CLI just needs to generate Markdown there to participate in Windsurf's command palette.\
|
||||
("Custom Workflows" section, [Windsurf changelog](https://windsurf.com/changelog))
|
||||
- OpenSpec already ships shared command bodies for proposal/apply/archive and uses markers so commands stay up to date. Extending the same templates to Windsurf keeps behaviour consistent with Claude, Cursor, and OpenCode without inventing new content flows.
|
||||
|
||||
## What Changes
|
||||
- Add Windsurf to the CLI tool picker (`openspec init`) and the slash-command registry so selecting it scaffolds `.windsurf/workflows/openspec-proposal.md`, `openspec-apply.md`, and `openspec-archive.md` with marker-managed bodies.
|
||||
- Shape each Windsurf workflow with a short heading/description plus the existing OpenSpec guardrails/steps wrapped in markers, ensuring the total payload remains well below the 12,000 character limit.
|
||||
- Ensure `openspec update` refreshes existing Windsurf workflows (and only those that already exist) in-place, mirroring current behaviour for other editors.
|
||||
- Extend unit tests for init/update to cover Windsurf generation and updates, and update the README/tooling docs to advertise Windsurf support.
|
||||
|
||||
## Impact
|
||||
- Specs: `cli-init`, `cli-update`
|
||||
- Code: `src/core/configurators/slash/*`, `src/core/templates/slash-command-templates.ts`, CLI prompts, README
|
||||
- Tests: init/update integration coverage for Windsurf workflows
|
||||
@@ -0,0 +1,23 @@
|
||||
## MODIFIED Requirements
|
||||
### Requirement: AI Tool Configuration
|
||||
The command SHALL configure AI coding assistants with OpenSpec instructions using a marker system.
|
||||
#### 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)
|
||||
- OpenCode (creates or refreshes `.opencode/command/openspec-*.md` slash commands)
|
||||
- Windsurf (creates or refreshes `.windsurf/workflows/openspec-*.md` workflows)
|
||||
- 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: Slash Command Configuration
|
||||
The init command SHALL generate slash command files for supported editors using shared templates.
|
||||
#### Scenario: Generating slash commands for Windsurf
|
||||
- **WHEN** the user selects Windsurf during initialization
|
||||
- **THEN** create `.windsurf/workflows/openspec-proposal.md`, `.windsurf/workflows/openspec-apply.md`, and `.windsurf/workflows/openspec-archive.md`
|
||||
- **AND** populate each file from shared templates (wrapped in OpenSpec markers) so workflow text matches other tools
|
||||
- **AND** each template includes instructions for the relevant OpenSpec workflow stage
|
||||
@@ -0,0 +1,8 @@
|
||||
## MODIFIED Requirements
|
||||
### Requirement: Slash Command Updates
|
||||
The update command SHALL refresh existing slash command files for configured tools without creating new ones.
|
||||
#### Scenario: Updating slash commands for Windsurf
|
||||
- **WHEN** `.windsurf/workflows/` contains `openspec-proposal.md`, `openspec-apply.md`, and `openspec-archive.md`
|
||||
- **THEN** refresh each file using shared templates wrapped in OpenSpec markers
|
||||
- **AND** ensure templates include instructions for the relevant workflow stage
|
||||
- **AND** skip creating missing files (the update command only refreshes what already exists)
|
||||
@@ -0,0 +1,17 @@
|
||||
## 1. CLI wiring
|
||||
- [ ] 1.1 Add Windsurf to the selectable AI tools in `openspec init`, including "already configured" detection.
|
||||
- [ ] 1.2 Register a `WindsurfSlashCommandConfigurator` that writes workflows to `.windsurf/workflows/` and ensures the directory exists.
|
||||
- [ ] 1.3 Ensure `openspec update` pulls the Windsurf configurator when winds is selected and skips creation when files are absent.
|
||||
|
||||
## 2. Workflow templates
|
||||
- [ ] 2.1 Reuse the shared proposal/apply/archive bodies, adding Windsurf-specific headings/description before the OpenSpec markers.
|
||||
- [ ] 2.2 Confirm generated Markdown (per file) stays comfortably under the 12k character ceiling noted in the Windsurf docs.
|
||||
|
||||
## 3. Tests & safeguards
|
||||
- [ ] 3.1 Extend init tests to assert creation of `.windsurf/workflows/openspec-*.md` when Windsurf is chosen.
|
||||
- [ ] 3.2 Extend update tests to assert existing Windsurf workflows are refreshed and non-existent files are ignored.
|
||||
- [ ] 3.3 Add regression coverage for marker preservation inside Windsurf workflow files.
|
||||
|
||||
## 4. Documentation
|
||||
- [ ] 4.1 Update README (and any user-facing docs) to list Windsurf under native slash/workflow integrations.
|
||||
- [ ] 4.2 Call out Windsurf workflow support in release notes or CHANGELOG if applicable.
|
||||
@@ -0,0 +1,12 @@
|
||||
## Why
|
||||
Validation errors like "no deltas found" or "missing requirement text" do not tell agents how to recover, leading to repeated failures. Making error output specific about headers, required text, and next actions will help assistants fix issues in a single pass.
|
||||
|
||||
## What Changes
|
||||
- Extend `openspec validate` error reporting so each failure names the exact header, file, and expected structure, including concrete examples of compliant Markdown.
|
||||
- Tailor messages for the most common mistakes (missing delta sections, absent descriptive requirement text, missing scenarios) with actionable fixes and suggested debug commands.
|
||||
- Update docs/help output so the improved messaging is discoverable (e.g., `--help`, troubleshooting section).
|
||||
- Add regression coverage to lock in the richer messaging for the top validation paths.
|
||||
|
||||
## Impact
|
||||
- Affected specs: `specs/cli-validate`
|
||||
- Affected code: `src/commands/validate.ts`, `src/core/validation`, `docs/`
|
||||
@@ -0,0 +1,39 @@
|
||||
## MODIFIED Requirements
|
||||
### Requirement: Validation SHALL provide actionable remediation steps
|
||||
Validation output SHALL include specific guidance to fix each error, including expected structure, example headers, and suggested commands to verify fixes.
|
||||
|
||||
#### Scenario: No deltas found in change
|
||||
- **WHEN** validating a change with zero parsed deltas
|
||||
- **THEN** show error "No deltas found" with guidance:
|
||||
- Explain that change specs must include `## ADDED Requirements`, `## MODIFIED Requirements`, `## REMOVED Requirements`, or `## RENAMED Requirements`
|
||||
- Remind authors that files must live under `openspec/changes/{id}/specs/<capability>/spec.md`
|
||||
- Include an explicit note: "Spec delta files cannot start with titles before the operation headers"
|
||||
- Suggest running `openspec change show {id} --json --deltas-only` for debugging
|
||||
|
||||
#### Scenario: Missing required sections
|
||||
- **WHEN** a required section is missing
|
||||
- **THEN** include expected header names and a minimal skeleton:
|
||||
- For Spec: `## Purpose`, `## Requirements`
|
||||
- For Change: `## Why`, `## What Changes`
|
||||
- Provide an example snippet of the missing section with placeholder prose ready to copy
|
||||
- Mention the quick-reference section in `openspec/AGENTS.md` as the authoritative template
|
||||
|
||||
#### Scenario: Missing requirement descriptive text
|
||||
- **WHEN** a requirement header lacks descriptive text before scenarios
|
||||
- **THEN** emit an error explaining that `### Requirement:` lines must be followed by narrative text before any `#### Scenario:` headers
|
||||
- Show compliant example: "### Requirement: Foo" followed by "The system SHALL ..."
|
||||
- Suggest adding 1-2 sentences describing the normative behavior prior to listing scenarios
|
||||
- Reference the pre-validation checklist in `openspec/AGENTS.md`
|
||||
|
||||
### Requirement: Validator SHALL detect likely misformatted scenarios and warn with a fix
|
||||
The validator SHALL recognize bulleted lines that look like scenarios (e.g., lines beginning with WHEN/THEN/AND) and emit a targeted warning with a conversion example to `#### Scenario:`.
|
||||
|
||||
#### Scenario: Bulleted WHEN/THEN under a Requirement
|
||||
- **WHEN** bullets that start with WHEN/THEN/AND are found under a requirement without any `#### Scenario:` headers
|
||||
- **THEN** emit warning: "Scenarios must use '#### Scenario:' headers", and show a conversion template:
|
||||
```
|
||||
#### Scenario: Short name
|
||||
- **WHEN** ...
|
||||
- **THEN** ...
|
||||
- **AND** ...
|
||||
```
|
||||
@@ -0,0 +1,12 @@
|
||||
## 1. Messaging enhancements
|
||||
- [ ] 1.1 Inventory current validation failures and map each to the desired message improvements.
|
||||
- [ ] 1.2 Implement structured error builders that include file paths, normalized header names, and example fixes.
|
||||
- [ ] 1.3 Ensure `openspec validate --help` and troubleshooting docs mention the richer messages and debug tips.
|
||||
|
||||
## 2. Tests
|
||||
- [ ] 2.1 Add unit tests for representative errors (no deltas, missing requirement body, missing scenarios) asserting the new wording.
|
||||
- [ ] 2.2 Add integration coverage verifying the Next steps footer reflects contextual guidance.
|
||||
|
||||
## 3. Documentation
|
||||
- [ ] 3.1 Update troubleshooting sections and CLI docs with sample output from the enhanced errors.
|
||||
- [ ] 3.2 Note the change in CHANGELOG or release notes if applicable.
|
||||
@@ -0,0 +1,12 @@
|
||||
## Why
|
||||
Agents fumble proposal formatting because the essential Markdown templates and formatting rules are buried mid-document. Reorganizing `openspec/AGENTS.md` with a prominent quick-reference and embedded examples will help assistants follow the process without guesswork.
|
||||
|
||||
## What Changes
|
||||
- Restructure `openspec/AGENTS.md` so file formats and scaffold templates appear in a top-level quick-reference section before workflow prose.
|
||||
- Embed copy/paste templates for `proposal.md`, `tasks.md`, `design.md`, and spec deltas alongside inline examples within the workflow steps.
|
||||
- Add a pre-validation checklist that highlights the most common formatting pitfalls before running `openspec validate`.
|
||||
- Split content into beginner vs. advanced sections to progressively disclose complexity while keeping advanced guidance accessible.
|
||||
|
||||
## Impact
|
||||
- Affected specs: `specs/docs-agent-instructions`
|
||||
- Affected code: `openspec/AGENTS.md`, `docs/`
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
## ADDED Requirements
|
||||
### Requirement: Quick Reference Placement
|
||||
The AI instructions SHALL begin with a quick-reference section that surfaces required file structures, templates, and formatting rules before any narrative guidance.
|
||||
|
||||
#### Scenario: Loading templates at the top
|
||||
- **WHEN** `openspec/AGENTS.md` is regenerated or updated
|
||||
- **THEN** the first substantive section after the title SHALL provide copy-ready headings for `proposal.md`, `tasks.md`, spec deltas, and scenario formatting
|
||||
- **AND** link each template to the corresponding workflow step for deeper reading
|
||||
|
||||
### Requirement: Embedded Templates and Examples
|
||||
`openspec/AGENTS.md` SHALL include complete copy/paste templates and inline examples exactly where agents make corresponding edits.
|
||||
|
||||
#### Scenario: Providing file templates
|
||||
- **WHEN** authors reach the workflow guidance for drafting proposals and deltas
|
||||
- **THEN** provide fenced Markdown templates that match the required structure (`## Why`, `## ADDED Requirements`, `#### Scenario:` etc.)
|
||||
- **AND** accompany each template with a brief example showing correct header usage and scenario bullets
|
||||
|
||||
### Requirement: Pre-validation Checklist
|
||||
`openspec/AGENTS.md` SHALL offer a concise pre-validation checklist that highlights common formatting mistakes before running `openspec validate`.
|
||||
|
||||
#### Scenario: Highlighting common validation failures
|
||||
- **WHEN** a reader reaches the validation guidance
|
||||
- **THEN** present a checklist reminding them to verify requirement headers, scenario formatting, and delta sections
|
||||
- **AND** include reminders about at least `#### Scenario:` usage and descriptive requirement text before scenarios
|
||||
|
||||
### Requirement: Progressive Disclosure of Workflow Guidance
|
||||
The documentation SHALL separate beginner essentials from advanced topics so newcomers can focus on core steps without losing access to advanced workflows.
|
||||
|
||||
#### Scenario: Organizing beginner and advanced sections
|
||||
- **WHEN** reorganizing `openspec/AGENTS.md`
|
||||
- **THEN** keep an introductory section limited to the minimum steps (scaffold, draft, validate, request review)
|
||||
- **AND** move advanced topics (multi-capability changes, archiving details, tooling deep dives) into clearly labeled later sections
|
||||
- **AND** provide anchor links from the quick-reference to those advanced sections
|
||||
@@ -0,0 +1,11 @@
|
||||
## 1. Instruction redesign
|
||||
- [ ] 1.1 Draft a quick-reference section that surfaces file templates and formatting rules at the top of `openspec/AGENTS.md`.
|
||||
- [ ] 1.2 Reorganize the workflow narrative with inline examples and progressive disclosure for advanced topics.
|
||||
|
||||
## 2. Templates and checklists
|
||||
- [ ] 2.1 Add copy/paste templates for proposal, tasks, design, and spec delta files.
|
||||
- [ ] 2.2 Insert a pre-validation checklist capturing common lint failures before running `openspec validate`.
|
||||
|
||||
## 3. Documentation updates
|
||||
- [ ] 3.1 Update supporting docs or README pointers so contributors find the redesigned instructions.
|
||||
- [ ] 3.2 Confirm examples and references stay in sync with the new scaffold command guidance.
|
||||
@@ -0,0 +1,13 @@
|
||||
## Why
|
||||
The project root currently receives a full copy of the OpenSpec agent instructions, duplicating the content that also lives in `openspec/AGENTS.md`. When teams edit one copy but not the other, the files drift and onboarding assistants see conflicting guidance.
|
||||
|
||||
## What Changes
|
||||
- Keep generating the complete template in `openspec/AGENTS.md` during `openspec init` and follow-up updates.
|
||||
- Replace the root-level file (`AGENTS.md` or `CLAUDE.md`, depending on tool selection) with a short hand-off that explains the project uses OpenSpec and points directly to `openspec/AGENTS.md`.
|
||||
- Add a dedicated stub template so both the init and update flows reuse the same minimal copy instructions.
|
||||
- Update CLI tests and documentation to reflect the new root-level messaging and ensure the OpenSpec marker block still protects future updates.
|
||||
|
||||
## Impact
|
||||
- Affected specs: `cli-init`, `cli-update`
|
||||
- Affected code: `src/core/init.ts`, `src/core/update.ts`, `src/core/templates/agents-template.ts`
|
||||
- Update assets/readmes that mention the root `AGENTS.md` contents to reference the new stub message.
|
||||
@@ -0,0 +1,15 @@
|
||||
## 1. Templates
|
||||
- [x] 1.1 Add a shared stub template that renders the root agent instructions hand-off message.
|
||||
- [x] 1.2 Ensure the stub covers both `AGENTS.md` and `CLAUDE.md` variants.
|
||||
|
||||
## 2. Init Flow
|
||||
- [x] 2.1 Update `createInitArtifacts` to write the stub to the project root instead of the full instructions.
|
||||
- [x] 2.2 Preserve the managed block markers so future updates can overwrite the stub safely.
|
||||
|
||||
## 3. Update Flow
|
||||
- [x] 3.1 Make the update command refresh the root stub rather than the full instructions.
|
||||
- [x] 3.2 Confirm the update log output still reflects the files that changed.
|
||||
|
||||
## 4. Tests & Docs
|
||||
- [x] 4.1 Adjust CLI/init tests to match the new root content.
|
||||
- [x] 4.2 Document the stub message in `openspec/specs/cli-init` and `openspec/specs/cli-update` (and any relevant README snippets).
|
||||
@@ -0,0 +1,14 @@
|
||||
## Why
|
||||
- Users frequently scroll to a tool and press Enter without toggling it, resulting in no configuration changes.
|
||||
- The current workflow deviates from common CLI expectations where Enter confirms the highlighted item.
|
||||
- Aligning behavior with user expectations reduces friction during onboarding.
|
||||
|
||||
## What Changes
|
||||
- Update the init wizard so pressing Enter on a highlighted tool selects it before moving to the review step.
|
||||
- Adjust interactive instructions to clarify Enter selects the current tool and Space still toggles selections.
|
||||
- Refresh specs to capture the clarified behavior for the interactive menu.
|
||||
|
||||
## Impact
|
||||
- Users who press Enter without toggling now configure the highlighted tool instead of exiting with no selections.
|
||||
- Spacebar multi-select support remains unchanged for power users.
|
||||
- Documentation better reflects how the wizard behaves.
|
||||
@@ -0,0 +1,10 @@
|
||||
## MODIFIED Requirements
|
||||
### 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 Space and review selections with Enter
|
||||
- **AND** when Enter is pressed on a highlighted selectable tool that is not already selected, automatically add it to the selection before moving to review so the highlighted tool is configured
|
||||
- **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 Space toggles tools and Enter selects the highlighted tool before reviewing selections
|
||||
@@ -0,0 +1,8 @@
|
||||
## 1. Implementation
|
||||
- [x] Update the tool selection wizard to auto-select the highlighted tool when Enter is pressed without prior toggles.
|
||||
- [x] Refresh inline instructions copy so Enter behavior is clear.
|
||||
- [x] Adjust or add tests if needed to cover the new selection flow.
|
||||
|
||||
## 2. Validation
|
||||
- [x] Run `pnpm run build`.
|
||||
- [x] Run `pnpm test` (or targeted suite) if applicable.
|
||||
@@ -0,0 +1,15 @@
|
||||
## Why
|
||||
OpenSpec currently creates the root-level `AGENTS.md` stub only when teams explicitly select the "AGENTS.md standard" tool during `openspec init`. Projects that skip that checkbox never get a managed stub, so non-native assistants (Copilot, Codeium, etc.) have no entry point and later `openspec update` runs silently create the file without any context. We need to bake the stub into initialization, clarify the tool selection experience, and keep the update workflow aligned so every teammate lands on the right instructions from day one.
|
||||
|
||||
## What Changes
|
||||
- Update `openspec init` so the root `AGENTS.md` stub is always generated (first run and extend mode) and refreshed from a shared utility instead of being tied to a tool selection.
|
||||
- Redesign the AI tool selection wizard to split options into "Natively supported" (Claude, Cursor, OpenCode, …) and an informational "Other tools" section that explains the always-on `AGENTS.md` hand-off.
|
||||
- Adjust CLI specs, prompts, and success messaging to reflect the new categories while keeping extend-mode behaviour consistent.
|
||||
- Update automated tests and fixtures to cover the unconditional stub creation and the reworked prompt flow.
|
||||
- Refresh documentation and onboarding snippets so they no longer describe the stub as opt-in and instead call out the new grouping.
|
||||
- Ensure `openspec update` continues to reconcile both `openspec/AGENTS.md` and the root stub, documenting the expected behaviour so mismatched setups self-heal.
|
||||
|
||||
## Impact
|
||||
- Affected specs: `cli-init`, `cli-update`
|
||||
- Affected code: `src/core/init.ts`, `src/core/config.ts`, `src/core/configurators/agents.ts`, `src/core/templates/agents-root-stub.ts`, `src/core/update.ts`, related tests under `test/core/`
|
||||
- Docs & assets: README, CHANGELOG, any setup guides that reference choosing the "AGENTS.md standard" option
|
||||
@@ -0,0 +1,32 @@
|
||||
## MODIFIED Requirements
|
||||
### Requirement: AI Tool Configuration
|
||||
The command SHALL configure AI coding assistants with OpenSpec instructions using a grouped selection experience so teams can enable native integrations while always provisioning guidance for other assistants.
|
||||
|
||||
#### Scenario: Prompting for AI tool selection
|
||||
- **WHEN** run interactively
|
||||
- **THEN** present a multi-select wizard that separates options into two headings:
|
||||
- **Natively supported providers** shows each available first-party integration (Claude Code, Cursor, OpenCode, …) with checkboxes
|
||||
- **Other tools** explains that the root-level `AGENTS.md` stub is always generated for AGENTS-compatible assistants and cannot be deselected
|
||||
- **AND** mark already configured native tools with "(already configured)" to signal that choosing them will refresh managed content
|
||||
- **AND** keep disabled or unavailable providers labelled as "coming soon" so users know they cannot opt in yet
|
||||
- **AND** allow confirming the selection even when no native provider is chosen because the root stub remains enabled by default
|
||||
- **AND** change the base prompt copy in extend mode to "Which natively supported AI tools would you like to add or refresh?"
|
||||
|
||||
### Requirement: Exit Code Adjustments
|
||||
`openspec init` SHALL treat extend mode without new native tool selections as a successful refresh.
|
||||
|
||||
#### Scenario: Allowing empty extend runs
|
||||
- **WHEN** OpenSpec is already initialized and the user selects no additional natively supported tools
|
||||
- **THEN** complete successfully while refreshing the root `AGENTS.md` stub
|
||||
- **AND** exit with code 0
|
||||
|
||||
## ADDED Requirements
|
||||
### Requirement: Root instruction stub
|
||||
`openspec init` SHALL always scaffold the root-level `AGENTS.md` hand-off so every teammate finds the primary OpenSpec instructions.
|
||||
|
||||
#### Scenario: Creating root `AGENTS.md`
|
||||
- **GIVEN** the project may or may not already contain an `AGENTS.md` file
|
||||
- **WHEN** initialization completes in fresh or extend mode
|
||||
- **THEN** create or refresh `AGENTS.md` at the repository root using the managed marker block from `TemplateManager.getAgentsStandardTemplate()`
|
||||
- **AND** preserve any existing content outside the managed markers while replacing the stub text inside them
|
||||
- **AND** create the stub regardless of which native AI tools are selected
|
||||
@@ -0,0 +1,10 @@
|
||||
## MODIFIED Requirements
|
||||
### Requirement: Tool-Agnostic Updates
|
||||
The update command SHALL refresh OpenSpec-managed files in a predictable manner while respecting each team's chosen tooling.
|
||||
|
||||
#### Scenario: Updating files
|
||||
- **WHEN** updating files
|
||||
- **THEN** completely replace `openspec/AGENTS.md` with the latest template
|
||||
- **AND** create or refresh the root-level `AGENTS.md` stub using the managed marker block, even if the file was previously absent
|
||||
- **AND** update only the OpenSpec-managed sections inside existing AI tool files, leaving user-authored content untouched
|
||||
- **AND** avoid creating new native-tool configuration files (slash commands, CLAUDE.md, etc.) unless they already exist
|
||||
@@ -0,0 +1,11 @@
|
||||
## 1. Implementation
|
||||
- [ ] 1.1 Refactor `openspec init` to always generate the root `AGENTS.md` stub (initial run and extend mode) via shared helper logic.
|
||||
- [ ] 1.2 Rework the AI tool selection wizard to surface "Natively supported" vs "Other tools" groupings and make the stub non-optional.
|
||||
- [ ] 1.3 Update CLI messaging, templates, and configurators so the new flow stays in sync across init and update commands.
|
||||
- [ ] 1.4 Refresh unit/integration tests to cover the unconditional stub and the regrouped prompt layout.
|
||||
- [ ] 1.5 Update documentation, README snippets, and CHANGELOG entries that mention the opt-in `AGENTS.md` experience.
|
||||
|
||||
## 2. Validation
|
||||
- [ ] 2.1 Run `pnpm test` targeting CLI init/update suites.
|
||||
- [ ] 2.2 Execute `openspec validate update-cli-init-root-agents --strict`.
|
||||
- [ ] 2.3 Perform a manual smoke test: run `openspec init` in a temp directory, confirm stub + grouped prompts, rerun in extend mode.
|
||||
@@ -0,0 +1,49 @@
|
||||
## Why
|
||||
Today’s process requires maintainers to merge the Changesets PR, cut a tag, and draft the GitHub release by hand. npm publish then runs from our existing workflow after the GitHub release is published. The human-in-the-loop steps (versioning, tagging, release notes) slow us down and risk drift between npm, tags, and changelog.
|
||||
|
||||
## What Changes
|
||||
- Use the single `changesets/action` on pushes to `main` to either open/update the version PR or, when the release PR is merged, run our publish command automatically using repository secrets.
|
||||
- Add a `release` script that builds and runs `changeset publish` so the action handles version bumps, changelog commits, npm publish, and GitHub releases end-to-end.
|
||||
- Enable `createGithubReleases: true` so GitHub releases are created from the changeset data right after publishing.
|
||||
- Document the automated flow, required secrets, guardrails, and recovery steps (rollback, hotfixes).
|
||||
|
||||
## Two-Phase Rollout (Two PRs)
|
||||
1) Phase 1 — Dry run (no publish)
|
||||
- Update the existing `release-prepare.yml` to wire up `changesets/action` with `createGithubReleases: true` and a no-op `publish` command (e.g., `echo 'dry run'`).
|
||||
- Keep `.github/workflows/release-publish.yml` intact. This avoids any publish path changes while we verify that the version PR behavior and permissions are correct.
|
||||
- Add a repository guard (`if: github.repository == 'Fission-AI/OpenSpec'`) and a concurrency group for safety.
|
||||
|
||||
2) Phase 2 — Enable publish and consolidate
|
||||
- Add `"release": "pnpm run build && pnpm exec changeset publish"` to `package.json`.
|
||||
- Change `release-prepare.yml` to use `with: publish: pnpm run release` and `env: NPM_TOKEN: \\${{ secrets.NPM_TOKEN }}` plus the default `GITHUB_TOKEN`.
|
||||
- Remove `.github/workflows/release-publish.yml` to avoid double-publish. Publishing now happens when the version PR is merged.
|
||||
|
||||
## Guardrails
|
||||
- Concurrency: `concurrency: { group: release-\\${{ github.ref }}, cancel-in-progress: false }` on the workflow to serialize releases.
|
||||
- Repository/branch guard: run publish logic only on upstream `main` (`if: github.repository == 'Fission-AI/OpenSpec' && github.ref == 'refs/heads/main'`).
|
||||
- Permissions: ensure `contents: write` and `pull-requests: write` for opening/updating the version PR; `packages: read` optional.
|
||||
|
||||
## Rollback and Hotfixes
|
||||
- Rollback: revert the release PR merge (which reverts version bumps/changelog); if a tag or GitHub release was created, delete the tag and release; deprecate the npm version if necessary (`npm deprecate @fission-ai/openspec@x.y.z 'reason'`).
|
||||
- Hotfix (urgent, no pending changesets): create a changeset for the fix and merge the release PR; in emergencies, run a manual bump/publish but reconcile with Changesets by adding a follow-up changeset to align versions.
|
||||
|
||||
## Required Secrets
|
||||
- `NPM_TOKEN` with publish rights for the `@fission-ai` scope.
|
||||
- Default `GITHUB_TOKEN` (provided by GitHub) for opening/updating the version PR and creating GitHub releases.
|
||||
|
||||
## How the Maintainer Flow Changes
|
||||
| Step | Current process | Future process |
|
||||
| --- | --- | --- |
|
||||
| Prepare release | Merge changeset PR, then manually draft release notes and tags | Merge release PR; action updates versions and handles changelog automatically |
|
||||
| Publish npm package | Happens automatically after GitHub release | Happens automatically via `changeset publish` invoked by the action |
|
||||
| GitHub release | Draft manually and sync with changelog | Action creates GitHub releases from changeset data |
|
||||
| Docs/process | Follow manual tagging/release steps | Docs describe automated flow + recovery and hotfix paths |
|
||||
|
||||
## Impact
|
||||
- Automation: reuse `.github/workflows/release-prepare.yml` (phase 1: dry-run, phase 2: publish) and remove `.github/workflows/release-publish.yml` in phase 2.
|
||||
- Package metadata: add `release` script to `package.json`.
|
||||
- Docs: update README or `/docs` to show the automated flow, secrets, guardrails, and recovery steps.
|
||||
|
||||
## Acceptance Criteria
|
||||
- Phase 1: merges to `main` open/update a version PR; on merge, the action’s `publish` step is a no-op; no npm publish occurs; logs confirm intended behavior; GitHub releases creation is wired but inert due to no publish.
|
||||
- Phase 2: merges to `main` run `pnpm run release` from the action; npm package publishes successfully; GitHub release is created automatically; `.github/workflows/release-publish.yml` is removed; no duplicate publishes occur.
|
||||
@@ -0,0 +1,12 @@
|
||||
## 1. Release workflow automation
|
||||
- [ ] 1.1 Add a `.github/workflows/release.yml` that runs on pushes to `main`, sets up pnpm + Node 20, installs dependencies, and invokes `changesets/action@v1` with `publish: pnpm run release`.
|
||||
- [ ] 1.2 Configure the action with `createGithubReleases: true` and document required secrets (`NPM_TOKEN`, default `GITHUB_TOKEN`) plus recommended concurrency safeguards.
|
||||
- [ ] 1.3 Validate the workflow using `act` or a dry-run push to confirm the action opens release PRs when changesets exist and publishes when the release PR merge lands.
|
||||
|
||||
## 2. Package release script
|
||||
- [ ] 2.1 Add a `release` script to `package.json` that builds the project and runs `changeset publish` using pnpm.
|
||||
- [ ] 2.2 Ensure the script respects the existing `prepare`/`prepublishOnly` hooks to avoid duplicate builds and update documentation or scripts if adjustments are needed.
|
||||
|
||||
## 3. Documentation and recovery steps
|
||||
- [ ] 3.1 Update maintainer docs (e.g., README or `/docs`) with the end-to-end automated release flow, explicitly removing the manual tag/release steps that are no longer required and explaining how changesets drive the release PR.
|
||||
- [ ] 3.2 Document fallback steps for failed publishes (rerun workflow, manual publish) and the hotfix path when a release must be cut without pending changesets.
|
||||
@@ -38,7 +38,7 @@ The command SHALL generate required template files with appropriate content for
|
||||
|
||||
#### Scenario: Generating template files
|
||||
- **WHEN** initializing OpenSpec
|
||||
- **THEN** generate `AGENTS.md` containing complete OpenSpec instructions for AI assistants
|
||||
- **THEN** generate `openspec/AGENTS.md` containing complete OpenSpec instructions for AI assistants
|
||||
- **AND** generate `project.md` with project context template
|
||||
|
||||
### Requirement: AI Tool Configuration
|
||||
@@ -52,7 +52,7 @@ The command SHALL configure AI coding assistants with OpenSpec instructions base
|
||||
- **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)
|
||||
- AGENTS.md standard (creates or refreshes AGENTS.md stub 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
|
||||
@@ -65,16 +65,22 @@ The command SHALL properly configure selected AI tools with OpenSpec-specific in
|
||||
|
||||
- **WHEN** Claude Code is selected
|
||||
- **THEN** create or update `CLAUDE.md` in the project root directory (not inside openspec/)
|
||||
- **AND** populate the managed block with a short stub that points teammates to `@/openspec/AGENTS.md`
|
||||
|
||||
#### Scenario: Creating new CLAUDE.md
|
||||
|
||||
- **WHEN** CLAUDE.md does not exist
|
||||
- **THEN** create new file with OpenSpec content wrapped in markers:
|
||||
- **THEN** create new file with stub instructions wrapped in markers so the full workflow stays in `openspec/AGENTS.md`:
|
||||
```markdown
|
||||
<!-- OPENSPEC:START -->
|
||||
# OpenSpec Instructions
|
||||
|
||||
Instructions for AI coding assistants using OpenSpec for spec-driven development.
|
||||
This project uses OpenSpec to manage AI assistant workflows.
|
||||
|
||||
- Full guidance lives in '@/openspec/AGENTS.md'.
|
||||
- Keep this managed block so 'openspec update' can refresh the instructions.
|
||||
<!-- OPENSPEC:END -->
|
||||
```
|
||||
|
||||
### Requirement: Interactive Mode
|
||||
The command SHALL provide an interactive menu for AI tool selection with clear navigation instructions.
|
||||
@@ -168,4 +174,4 @@ Manual creation of OpenSpec structure is error-prone and creates adoption fricti
|
||||
- Consistent structure across all projects
|
||||
- Proper AI instruction files are always included
|
||||
- Quick onboarding for new projects
|
||||
- Clear conventions from the start
|
||||
- Clear conventions from the start
|
||||
|
||||
@@ -10,6 +10,7 @@ The update command SHALL update OpenSpec instruction files to the latest templat
|
||||
#### Scenario: Running update command
|
||||
- **WHEN** a user runs `openspec update`
|
||||
- **THEN** replace `openspec/AGENTS.md` with the latest template
|
||||
- **AND** if a root-level stub (`AGENTS.md`/`CLAUDE.md`) exists, refresh it so it points to `@/openspec/AGENTS.md`
|
||||
|
||||
### Requirement: Prerequisites
|
||||
|
||||
@@ -28,6 +29,7 @@ The update command SHALL handle file updates in a predictable and safe manner.
|
||||
#### Scenario: Updating files
|
||||
- **WHEN** updating files
|
||||
- **THEN** completely replace `openspec/AGENTS.md` with the latest template
|
||||
- **AND** if a root-level stub exists, update the managed block content so it keeps directing teammates to `@/openspec/AGENTS.md`
|
||||
|
||||
### Requirement: Tool-Agnostic Updates
|
||||
The update command SHALL handle file updates in a predictable and safe manner while respecting team tool choices.
|
||||
@@ -36,11 +38,12 @@ The update command SHALL handle file updates in a predictable and safe manner wh
|
||||
|
||||
- **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 the root-level `AGENTS.md` using the OpenSpec markers only when that file already exists, keeping the stub content that links to `@/openspec/AGENTS.md`
|
||||
- **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`
|
||||
- **AND** do not create new root-level stub files when none are present
|
||||
|
||||
### Requirement: Core Files Always Updated
|
||||
The update command SHALL always update the core OpenSpec files and display an ASCII-safe success message.
|
||||
@@ -48,6 +51,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/AGENTS.md` with the latest template
|
||||
- **AND** if a root-level stub exists, refresh it so it still directs contributors to `@/openspec/AGENTS.md`
|
||||
|
||||
### Requirement: Slash Command Updates
|
||||
The update command SHALL refresh existing slash command files for configured tools without creating new ones.
|
||||
@@ -63,7 +67,7 @@ The update command SHALL refresh existing slash command files for configured too
|
||||
- **AND** ensure templates include instructions for the relevant workflow stage
|
||||
|
||||
#### Scenario: Updating slash commands for OpenCode
|
||||
- **WHEN** `.opencode/commands/` contains `openspec-proposal.md`, `openspec-apply.md`, and `openspec-archive.md`
|
||||
- **WHEN** `.opencode/command/` contains `openspec-proposal.md`, `openspec-apply.md`, and `openspec-archive.md`
|
||||
- **THEN** refresh each file using shared templates
|
||||
- **AND** ensure templates include instructions for the relevant workflow stage
|
||||
|
||||
@@ -104,4 +108,4 @@ Users SHALL be able to:
|
||||
The update process SHALL be:
|
||||
- Simple and fast (no version checking)
|
||||
- Predictable (same result every time)
|
||||
- Self-contained (no network required)
|
||||
- Self-contained (no network required)
|
||||
|
||||
+5
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@fission-ai/openspec",
|
||||
"version": "0.5.0",
|
||||
"version": "0.9.2",
|
||||
"description": "AI-native system for spec-driven development",
|
||||
"keywords": [
|
||||
"openspec",
|
||||
@@ -46,6 +46,10 @@
|
||||
"test:coverage": "vitest --coverage",
|
||||
"prepare": "pnpm run build",
|
||||
"prepublishOnly": "pnpm run build",
|
||||
"check:pack-version": "node scripts/pack-version-check.mjs",
|
||||
"release": "pnpm run release:ci",
|
||||
"release:ci": "pnpm run check:pack-version && pnpm exec changeset publish",
|
||||
"release:local": "pnpm exec changeset version && pnpm run check:pack-version && pnpm exec changeset publish",
|
||||
"changeset": "changeset"
|
||||
},
|
||||
"engines": {
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
#!/usr/bin/env node
|
||||
// Guard: Ensure the packed tarball's CLI `--version` matches package.json.
|
||||
//
|
||||
// Notes:
|
||||
// - We intentionally use `npm pack` (not pnpm) because `npm pack --json` is
|
||||
// consistently supported and returns the tarball metadata we need. The
|
||||
// project uses pnpm for install/publish, but this guard only needs to pack
|
||||
// locally and verify the installed CLI output.
|
||||
// - `npm pack` triggers the package's `prepare` script (build), and
|
||||
// `changeset publish` triggers `prepublishOnly` (also builds here). This
|
||||
// means an explicit build is not strictly necessary for the guard.
|
||||
|
||||
import { execFileSync } from 'child_process';
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
|
||||
import { tmpdir } from 'os';
|
||||
import path from 'path';
|
||||
|
||||
function log(msg) {
|
||||
if (process.env.CI) return; // keep CI logs quiet by default
|
||||
console.log(msg);
|
||||
}
|
||||
|
||||
function run(cmd, args, opts = {}) {
|
||||
return execFileSync(cmd, args, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], ...opts });
|
||||
}
|
||||
|
||||
function npmPack() {
|
||||
try {
|
||||
const jsonOut = run('npm', ['pack', '--json', '--silent']);
|
||||
const arr = JSON.parse(jsonOut);
|
||||
if (Array.isArray(arr) && arr.length > 0) {
|
||||
const last = arr[arr.length - 1];
|
||||
const file = (last && typeof last === 'object' && last.filename) || (typeof last === 'string' ? last : null);
|
||||
if (file) return String(file).trim();
|
||||
}
|
||||
// Unexpected JSON shape or empty array; fallback to plain output
|
||||
const out = run('npm', ['pack', '--silent']).trim();
|
||||
const lines = out.split(/\r?\n/);
|
||||
return lines[lines.length - 1].trim();
|
||||
} catch (e) {
|
||||
// Fallback for environments not supporting --json
|
||||
const out = run('npm', ['pack', '--silent']).trim();
|
||||
const lines = out.split(/\r?\n/);
|
||||
return lines[lines.length - 1].trim();
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
const pkg = JSON.parse(readFileSync(path.join(process.cwd(), 'package.json'), 'utf-8'));
|
||||
const expected = pkg.version;
|
||||
|
||||
let work;
|
||||
let tgzPath;
|
||||
|
||||
try {
|
||||
log(`Packing @fission-ai/openspec@${expected}...`);
|
||||
const filename = npmPack();
|
||||
tgzPath = path.resolve(filename);
|
||||
log(`Created: ${tgzPath}`);
|
||||
|
||||
work = mkdtempSync(path.join(tmpdir(), 'openspec-pack-check-'));
|
||||
log(`Temp dir: ${work}`);
|
||||
|
||||
// Make a tiny project
|
||||
writeFileSync(
|
||||
path.join(work, 'package.json'),
|
||||
JSON.stringify({ name: 'pack-check', private: true }, null, 2)
|
||||
);
|
||||
|
||||
// Try to avoid noisy output and speed up
|
||||
const env = {
|
||||
...process.env,
|
||||
npm_config_loglevel: 'silent',
|
||||
npm_config_audit: 'false',
|
||||
npm_config_fund: 'false',
|
||||
npm_config_progress: 'false',
|
||||
};
|
||||
|
||||
// Install the tarball
|
||||
run('npm', ['install', tgzPath, '--silent', '--no-audit', '--no-fund'], { cwd: work, env });
|
||||
|
||||
// Run the installed CLI via Node to avoid bin resolution/platform issues
|
||||
const binRel = path.join('node_modules', '@fission-ai', 'openspec', 'bin', 'openspec.js');
|
||||
const actual = run(process.execPath, [binRel, '--version'], { cwd: work }).trim();
|
||||
|
||||
if (actual !== expected) {
|
||||
throw new Error(
|
||||
`Packed CLI version mismatch: expected ${expected}, got ${actual}. ` +
|
||||
'Ensure the dist is built and the CLI reads version from package.json.'
|
||||
);
|
||||
}
|
||||
|
||||
log('Version check passed.');
|
||||
} finally {
|
||||
// Always attempt cleanup
|
||||
if (work) {
|
||||
try { rmSync(work, { recursive: true, force: true }); } catch {}
|
||||
}
|
||||
if (tgzPath) {
|
||||
try { rmSync(tgzPath, { force: true }); } catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
main();
|
||||
console.log('✅ pack-version-check: OK');
|
||||
} catch (err) {
|
||||
console.error(`❌ pack-version-check: ${err.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
+8
-4
@@ -17,8 +17,12 @@ export interface AIToolOption {
|
||||
}
|
||||
|
||||
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: 'OpenCode (✅ OpenSpec custom slash commands available)', value: 'opencode', available: true, successLabel: 'OpenCode' },
|
||||
{ name: 'AGENTS.md (works with Codex, Amp, Copilot, …)', value: 'agents', available: true, successLabel: 'your AGENTS.md-compatible assistant' }
|
||||
{ name: 'Claude Code', value: 'claude', available: true, successLabel: 'Claude Code' },
|
||||
{ name: 'Cursor', value: 'cursor', available: true, successLabel: 'Cursor' },
|
||||
{ name: 'OpenCode', value: 'opencode', available: true, successLabel: 'OpenCode' },
|
||||
{ name: 'Kilo Code', value: 'kilocode', available: true, successLabel: 'Kilo Code' },
|
||||
{ name: 'Windsurf', value: 'windsurf', available: true, successLabel: 'Windsurf' },
|
||||
{ name: 'Codex', value: 'codex', available: true, successLabel: 'Codex' },
|
||||
{ name: 'GitHub Copilot', value: 'github-copilot', available: true, successLabel: 'GitHub Copilot' },
|
||||
{ name: 'AGENTS.md (works with Amp, VS Code, …)', value: 'agents', available: false, successLabel: 'your AGENTS.md-compatible assistant' }
|
||||
];
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import path from 'path';
|
||||
import { FileSystemUtils } from '../../../utils/file-system.js';
|
||||
import { TemplateManager, SlashCommandId } from '../../templates/index.js';
|
||||
import { OPENSPEC_MARKERS } from '../../config.js';
|
||||
@@ -28,7 +27,7 @@ export abstract class SlashCommandConfigurator {
|
||||
|
||||
for (const target of this.getTargets()) {
|
||||
const body = TemplateManager.getSlashCommandBody(target.id).trim();
|
||||
const filePath = path.join(projectPath, target.path);
|
||||
const filePath = FileSystemUtils.joinPath(projectPath, target.path);
|
||||
|
||||
if (await FileSystemUtils.fileExists(filePath)) {
|
||||
await this.updateBody(filePath, body);
|
||||
@@ -53,7 +52,7 @@ export abstract class SlashCommandConfigurator {
|
||||
const updated: string[] = [];
|
||||
|
||||
for (const target of this.getTargets()) {
|
||||
const filePath = path.join(projectPath, target.path);
|
||||
const filePath = FileSystemUtils.joinPath(projectPath, target.path);
|
||||
if (await FileSystemUtils.fileExists(filePath)) {
|
||||
const body = TemplateManager.getSlashCommandBody(target.id).trim();
|
||||
await this.updateBody(filePath, body);
|
||||
@@ -67,7 +66,14 @@ export abstract class SlashCommandConfigurator {
|
||||
protected abstract getRelativePath(id: SlashCommandId): string;
|
||||
protected abstract getFrontmatter(id: SlashCommandId): string | undefined;
|
||||
|
||||
private async updateBody(filePath: string, body: string): Promise<void> {
|
||||
// Resolve absolute path for a given slash command target. Subclasses may override
|
||||
// to redirect to tool-specific locations (e.g., global directories).
|
||||
resolveAbsolutePath(projectPath: string, id: SlashCommandId): string {
|
||||
const rel = this.getRelativePath(id);
|
||||
return FileSystemUtils.joinPath(projectPath, rel);
|
||||
}
|
||||
|
||||
protected 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);
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import path from "path";
|
||||
import os from "os";
|
||||
import { SlashCommandConfigurator } from "./base.js";
|
||||
import { SlashCommandId, TemplateManager } from "../../templates/index.js";
|
||||
import { FileSystemUtils } from "../../../utils/file-system.js";
|
||||
import { OPENSPEC_MARKERS } from "../../config.js";
|
||||
|
||||
// Use POSIX-style paths for consistent logging across platforms.
|
||||
const FILE_PATHS: Record<SlashCommandId, string> = {
|
||||
proposal: ".codex/prompts/openspec-proposal.md",
|
||||
apply: ".codex/prompts/openspec-apply.md",
|
||||
archive: ".codex/prompts/openspec-archive.md",
|
||||
};
|
||||
|
||||
export class CodexSlashCommandConfigurator extends SlashCommandConfigurator {
|
||||
readonly toolId = "codex";
|
||||
readonly isAvailable = true;
|
||||
|
||||
protected getRelativePath(id: SlashCommandId): string {
|
||||
return FILE_PATHS[id];
|
||||
}
|
||||
|
||||
protected getFrontmatter(id: SlashCommandId): string | undefined {
|
||||
// Codex supports YAML frontmatter with description and argument-hint fields,
|
||||
// plus $ARGUMENTS to capture all arguments as a single string.
|
||||
const frontmatter: Record<SlashCommandId, string> = {
|
||||
proposal: `---
|
||||
description: Scaffold a new OpenSpec change and validate strictly.
|
||||
argument-hint: request or feature description
|
||||
---
|
||||
|
||||
$ARGUMENTS`,
|
||||
apply: `---
|
||||
description: Implement an approved OpenSpec change and keep tasks in sync.
|
||||
argument-hint: change-id
|
||||
---
|
||||
|
||||
$ARGUMENTS`,
|
||||
archive: `---
|
||||
description: Archive a deployed OpenSpec change and update specs.
|
||||
argument-hint: change-id
|
||||
---
|
||||
|
||||
$ARGUMENTS`,
|
||||
};
|
||||
return frontmatter[id];
|
||||
}
|
||||
|
||||
private getGlobalPromptsDir(): string {
|
||||
const home = (process.env.CODEX_HOME && process.env.CODEX_HOME.trim())
|
||||
? process.env.CODEX_HOME.trim()
|
||||
: FileSystemUtils.joinPath(os.homedir(), ".codex");
|
||||
return FileSystemUtils.joinPath(home, "prompts");
|
||||
}
|
||||
|
||||
// Codex discovers prompts globally. Generate directly in the global directory
|
||||
// and wrap shared body with markers.
|
||||
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 promptsDir = this.getGlobalPromptsDir();
|
||||
const filePath = FileSystemUtils.joinPath(
|
||||
promptsDir,
|
||||
path.basename(target.path)
|
||||
);
|
||||
|
||||
await FileSystemUtils.createDirectory(path.dirname(filePath));
|
||||
|
||||
if (await FileSystemUtils.fileExists(filePath)) {
|
||||
await this.updateFullFile(filePath, target.id, 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}`);
|
||||
await FileSystemUtils.writeFile(filePath, sections.join("\n") + "\n");
|
||||
}
|
||||
|
||||
createdOrUpdated.push(target.path);
|
||||
}
|
||||
return createdOrUpdated;
|
||||
}
|
||||
|
||||
async updateExisting(projectPath: string, _openspecDir: string): Promise<string[]> {
|
||||
const updated: string[] = [];
|
||||
for (const target of this.getTargets()) {
|
||||
const promptsDir = this.getGlobalPromptsDir();
|
||||
const filePath = FileSystemUtils.joinPath(
|
||||
promptsDir,
|
||||
path.basename(target.path)
|
||||
);
|
||||
if (await FileSystemUtils.fileExists(filePath)) {
|
||||
const body = TemplateManager.getSlashCommandBody(target.id).trim();
|
||||
await this.updateFullFile(filePath, target.id, body);
|
||||
updated.push(target.path);
|
||||
}
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
// Update both frontmatter and body in an existing file
|
||||
private async updateFullFile(filePath: string, id: SlashCommandId, body: string): Promise<void> {
|
||||
const content = await FileSystemUtils.readFile(filePath);
|
||||
const startIndex = content.indexOf(OPENSPEC_MARKERS.start);
|
||||
|
||||
if (startIndex === -1) {
|
||||
throw new Error(`Missing OpenSpec start marker in ${filePath}`);
|
||||
}
|
||||
|
||||
// Replace everything before the start marker with the new frontmatter
|
||||
const frontmatter = this.getFrontmatter(id);
|
||||
const sections: string[] = [];
|
||||
if (frontmatter) sections.push(frontmatter.trim());
|
||||
sections.push(`${OPENSPEC_MARKERS.start}\n${body}\n${OPENSPEC_MARKERS.end}`);
|
||||
|
||||
await FileSystemUtils.writeFile(filePath, sections.join("\n") + "\n");
|
||||
}
|
||||
|
||||
// Resolve to the global prompts location for configuration detection
|
||||
resolveAbsolutePath(_projectPath: string, id: SlashCommandId): string {
|
||||
const promptsDir = this.getGlobalPromptsDir();
|
||||
const fileName = path.basename(FILE_PATHS[id]);
|
||||
return FileSystemUtils.joinPath(promptsDir, fileName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { SlashCommandConfigurator } from './base.js';
|
||||
import { SlashCommandId } from '../../templates/index.js';
|
||||
|
||||
const FILE_PATHS: Record<SlashCommandId, string> = {
|
||||
proposal: '.github/prompts/openspec-proposal.prompt.md',
|
||||
apply: '.github/prompts/openspec-apply.prompt.md',
|
||||
archive: '.github/prompts/openspec-archive.prompt.md'
|
||||
};
|
||||
|
||||
const FRONTMATTER: Record<SlashCommandId, string> = {
|
||||
proposal: `---
|
||||
description: Scaffold a new OpenSpec change and validate strictly.
|
||||
---
|
||||
|
||||
$ARGUMENTS`,
|
||||
apply: `---
|
||||
description: Implement an approved OpenSpec change and keep tasks in sync.
|
||||
---
|
||||
|
||||
$ARGUMENTS`,
|
||||
archive: `---
|
||||
description: Archive a deployed OpenSpec change and update specs.
|
||||
---
|
||||
|
||||
$ARGUMENTS`
|
||||
};
|
||||
|
||||
export class GitHubCopilotSlashCommandConfigurator extends SlashCommandConfigurator {
|
||||
readonly toolId = 'github-copilot';
|
||||
readonly isAvailable = true;
|
||||
|
||||
protected getRelativePath(id: SlashCommandId): string {
|
||||
return FILE_PATHS[id];
|
||||
}
|
||||
|
||||
protected getFrontmatter(id: SlashCommandId): string {
|
||||
return FRONTMATTER[id];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { SlashCommandConfigurator } from "./base.js";
|
||||
import { SlashCommandId } from "../../templates/index.js";
|
||||
|
||||
const FILE_PATHS: Record<SlashCommandId, string> = {
|
||||
proposal: ".kilocode/workflows/openspec-proposal.md",
|
||||
apply: ".kilocode/workflows/openspec-apply.md",
|
||||
archive: ".kilocode/workflows/openspec-archive.md"
|
||||
};
|
||||
|
||||
export class KiloCodeSlashCommandConfigurator extends SlashCommandConfigurator {
|
||||
readonly toolId = "kilocode";
|
||||
readonly isAvailable = true;
|
||||
|
||||
protected getRelativePath(id: SlashCommandId): string {
|
||||
return FILE_PATHS[id];
|
||||
}
|
||||
|
||||
protected getFrontmatter(_id: SlashCommandId): string | undefined {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
import { SlashCommandConfigurator } from './base.js';
|
||||
import { ClaudeSlashCommandConfigurator } from './claude.js';
|
||||
import { CursorSlashCommandConfigurator } from './cursor.js';
|
||||
import { WindsurfSlashCommandConfigurator } from './windsurf.js';
|
||||
import { KiloCodeSlashCommandConfigurator } from './kilocode.js';
|
||||
import { OpenCodeSlashCommandConfigurator } from './opencode.js';
|
||||
import { CodexSlashCommandConfigurator } from './codex.js';
|
||||
import { GitHubCopilotSlashCommandConfigurator } from './github-copilot.js';
|
||||
|
||||
export class SlashCommandRegistry {
|
||||
private static configurators: Map<string, SlashCommandConfigurator> = new Map();
|
||||
@@ -9,11 +13,19 @@ export class SlashCommandRegistry {
|
||||
static {
|
||||
const claude = new ClaudeSlashCommandConfigurator();
|
||||
const cursor = new CursorSlashCommandConfigurator();
|
||||
const windsurf = new WindsurfSlashCommandConfigurator();
|
||||
const kilocode = new KiloCodeSlashCommandConfigurator();
|
||||
const opencode = new OpenCodeSlashCommandConfigurator();
|
||||
const codex = new CodexSlashCommandConfigurator();
|
||||
const githubCopilot = new GitHubCopilotSlashCommandConfigurator();
|
||||
|
||||
this.configurators.set(claude.toolId, claude);
|
||||
this.configurators.set(cursor.toolId, cursor);
|
||||
this.configurators.set(windsurf.toolId, windsurf);
|
||||
this.configurators.set(kilocode.toolId, kilocode);
|
||||
this.configurators.set(opencode.toolId, opencode);
|
||||
this.configurators.set(codex.toolId, codex);
|
||||
this.configurators.set(githubCopilot.toolId, githubCopilot);
|
||||
}
|
||||
|
||||
static register(configurator: SlashCommandConfigurator): void {
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { SlashCommandConfigurator } from './base.js';
|
||||
import { SlashCommandId } from '../../templates/index.js';
|
||||
|
||||
const FILE_PATHS: Record<SlashCommandId, string> = {
|
||||
proposal: '.windsurf/workflows/openspec-proposal.md',
|
||||
apply: '.windsurf/workflows/openspec-apply.md',
|
||||
archive: '.windsurf/workflows/openspec-archive.md'
|
||||
};
|
||||
|
||||
export class WindsurfSlashCommandConfigurator extends SlashCommandConfigurator {
|
||||
readonly toolId = 'windsurf';
|
||||
readonly isAvailable = true;
|
||||
|
||||
protected getRelativePath(id: SlashCommandId): string {
|
||||
return FILE_PATHS[id];
|
||||
}
|
||||
|
||||
protected getFrontmatter(id: SlashCommandId): string | undefined {
|
||||
const descriptions: Record<SlashCommandId, string> = {
|
||||
proposal: 'Scaffold a new OpenSpec change and validate strictly.',
|
||||
apply: 'Implement an approved OpenSpec change and keep tasks in sync.',
|
||||
archive: 'Archive a deployed OpenSpec change and update specs.'
|
||||
};
|
||||
const description = descriptions[id];
|
||||
return `---\ndescription: ${description}\nauto_execution_mode: 3\n---`;
|
||||
}
|
||||
}
|
||||
+263
-77
@@ -22,19 +22,13 @@ import {
|
||||
OPENSPEC_DIR_NAME,
|
||||
AIToolOption,
|
||||
} from './config.js';
|
||||
import { PALETTE } from './styles/palette.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: ['█████ ', '██ ██', '█████ ', '██ ', '██ '],
|
||||
@@ -65,11 +59,24 @@ const parseToolLabel = (raw: string): ToolLabel => {
|
||||
};
|
||||
};
|
||||
|
||||
type ToolWizardChoice = {
|
||||
value: string;
|
||||
label: ToolLabel;
|
||||
configured: boolean;
|
||||
};
|
||||
const isSelectableChoice = (
|
||||
choice: ToolWizardChoice
|
||||
): choice is Extract<ToolWizardChoice, { selectable: true }> => choice.selectable;
|
||||
|
||||
type ToolWizardChoice =
|
||||
| {
|
||||
kind: 'heading' | 'info';
|
||||
value: string;
|
||||
label: ToolLabel;
|
||||
selectable: false;
|
||||
}
|
||||
| {
|
||||
kind: 'option';
|
||||
value: string;
|
||||
label: ToolLabel;
|
||||
configured: boolean;
|
||||
selectable: true;
|
||||
};
|
||||
|
||||
type ToolWizardConfig = {
|
||||
extendMode: boolean;
|
||||
@@ -82,21 +89,41 @@ type WizardStep = 'intro' | 'select' | 'review';
|
||||
|
||||
type ToolSelectionPrompt = (config: ToolWizardConfig) => Promise<string[]>;
|
||||
|
||||
type RootStubStatus = 'created' | 'updated' | 'skipped';
|
||||
|
||||
const ROOT_STUB_CHOICE_VALUE = '__root_stub__';
|
||||
|
||||
const OTHER_TOOLS_HEADING_VALUE = '__heading-other__';
|
||||
const LIST_SPACER_VALUE = '__list-spacer__';
|
||||
|
||||
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 selectableChoices = config.choices.filter(isSelectableChoice);
|
||||
const initialCursorIndex = config.choices.findIndex((choice) =>
|
||||
choice.selectable
|
||||
);
|
||||
const [cursor, setCursor] = useState<number>(
|
||||
initialCursorIndex === -1 ? 0 : initialCursorIndex
|
||||
);
|
||||
const [selected, setSelected] = useState<string[]>(() => {
|
||||
const initial = new Set(
|
||||
(config.initialSelected ?? []).filter((value) =>
|
||||
selectableChoices.some((choice) => choice.value === value)
|
||||
)
|
||||
);
|
||||
return selectableChoices
|
||||
.map((choice) => choice.value)
|
||||
.filter((value) => initial.has(value));
|
||||
});
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const selectedSet = new Set(selected);
|
||||
const pageSize = Math.max(Math.min(config.choices.length, 7), 1);
|
||||
const pageSize = Math.max(config.choices.length, 1);
|
||||
|
||||
const updateSelected = (next: Set<string>) => {
|
||||
const ordered = config.choices
|
||||
const ordered = selectableChoices
|
||||
.map((choice) => choice.value)
|
||||
.filter((value) => next.has(value));
|
||||
setSelected(ordered);
|
||||
@@ -106,8 +133,17 @@ const toolSelectionWizard = createPrompt<string[], ToolWizardConfig>(
|
||||
items: config.choices,
|
||||
active: cursor,
|
||||
pageSize,
|
||||
loop: config.choices.length > 1,
|
||||
loop: false,
|
||||
renderItem: ({ item, isActive }) => {
|
||||
if (!item.selectable) {
|
||||
const prefix = item.kind === 'info' ? ' ' : '';
|
||||
const textColor =
|
||||
item.kind === 'heading' ? PALETTE.lightGray : PALETTE.midGray;
|
||||
return `${PALETTE.midGray(' ')} ${PALETTE.midGray(' ')} ${textColor(
|
||||
`${prefix}${item.label.primary}`
|
||||
)}`;
|
||||
}
|
||||
|
||||
const isSelected = selectedSet.has(item.value);
|
||||
const cursorSymbol = isActive
|
||||
? PALETTE.white('›')
|
||||
@@ -116,13 +152,36 @@ const toolSelectionWizard = createPrompt<string[], ToolWizardConfig>(
|
||||
? PALETTE.white('◉')
|
||||
: PALETTE.midGray('○');
|
||||
const nameColor = isActive ? PALETTE.white : PALETTE.midGray;
|
||||
const label = `${nameColor(item.label.primary)}${
|
||||
item.configured ? PALETTE.midGray(' (already configured)') : ''
|
||||
}`;
|
||||
const annotation = item.label.annotation
|
||||
? PALETTE.midGray(` (${item.label.annotation})`)
|
||||
: '';
|
||||
const configuredNote = item.configured
|
||||
? PALETTE.midGray(' (already configured)')
|
||||
: '';
|
||||
const label = `${nameColor(item.label.primary)}${annotation}${configuredNote}`;
|
||||
return `${cursorSymbol} ${indicator} ${label}`;
|
||||
},
|
||||
});
|
||||
|
||||
const moveCursor = (direction: 1 | -1) => {
|
||||
if (selectableChoices.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
let nextIndex = cursor;
|
||||
while (true) {
|
||||
nextIndex = nextIndex + direction;
|
||||
if (nextIndex < 0 || nextIndex >= config.choices.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (config.choices[nextIndex]?.selectable) {
|
||||
setCursor(nextIndex);
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
useKeypress((key) => {
|
||||
if (step === 'intro') {
|
||||
if (isEnterKey(key)) {
|
||||
@@ -133,24 +192,20 @@ const toolSelectionWizard = createPrompt<string[], ToolWizardConfig>(
|
||||
|
||||
if (step === 'select') {
|
||||
if (isUpKey(key)) {
|
||||
const previousIndex =
|
||||
cursor <= 0 ? config.choices.length - 1 : cursor - 1;
|
||||
setCursor(previousIndex);
|
||||
moveCursor(-1);
|
||||
setError(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isDownKey(key)) {
|
||||
const nextIndex =
|
||||
cursor >= config.choices.length - 1 ? 0 : cursor + 1;
|
||||
setCursor(nextIndex);
|
||||
moveCursor(1);
|
||||
setError(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isSpaceKey(key)) {
|
||||
const current = config.choices[cursor];
|
||||
if (!current) return;
|
||||
if (!current || !current.selectable) return;
|
||||
|
||||
const next = new Set(selected);
|
||||
if (next.has(current.value)) {
|
||||
@@ -165,9 +220,15 @@ const toolSelectionWizard = createPrompt<string[], ToolWizardConfig>(
|
||||
}
|
||||
|
||||
if (isEnterKey(key)) {
|
||||
if (selected.length === 0) {
|
||||
setError('Select at least one AI tool to continue.');
|
||||
return;
|
||||
const current = config.choices[cursor];
|
||||
if (
|
||||
current &&
|
||||
current.selectable &&
|
||||
!selectedSet.has(current.value)
|
||||
) {
|
||||
const next = new Set(selected);
|
||||
next.add(current.value);
|
||||
updateSelected(next);
|
||||
}
|
||||
setStep('review');
|
||||
setError(null);
|
||||
@@ -175,7 +236,8 @@ const toolSelectionWizard = createPrompt<string[], ToolWizardConfig>(
|
||||
}
|
||||
|
||||
if (key.name === 'escape') {
|
||||
setSelected([]);
|
||||
const next = new Set<string>();
|
||||
updateSelected(next);
|
||||
setError(null);
|
||||
}
|
||||
return;
|
||||
@@ -185,7 +247,10 @@ const toolSelectionWizard = createPrompt<string[], ToolWizardConfig>(
|
||||
if (isEnterKey(key)) {
|
||||
const finalSelection = config.choices
|
||||
.map((choice) => choice.value)
|
||||
.filter((value) => selectedSet.has(value));
|
||||
.filter(
|
||||
(value) =>
|
||||
selectedSet.has(value) && value !== ROOT_STUB_CHOICE_VALUE
|
||||
);
|
||||
done(finalSelection);
|
||||
return;
|
||||
}
|
||||
@@ -197,9 +262,30 @@ const toolSelectionWizard = createPrompt<string[], ToolWizardConfig>(
|
||||
}
|
||||
});
|
||||
|
||||
const selectedNames = config.choices
|
||||
.filter((choice) => selectedSet.has(choice.value))
|
||||
.map((choice) => choice.label.primary);
|
||||
const rootStubChoice = selectableChoices.find(
|
||||
(choice) => choice.value === ROOT_STUB_CHOICE_VALUE
|
||||
);
|
||||
const rootStubSelected = rootStubChoice
|
||||
? selectedSet.has(ROOT_STUB_CHOICE_VALUE)
|
||||
: false;
|
||||
const nativeChoices = selectableChoices.filter(
|
||||
(choice) => choice.value !== ROOT_STUB_CHOICE_VALUE
|
||||
);
|
||||
const selectedNativeChoices = nativeChoices.filter((choice) =>
|
||||
selectedSet.has(choice.value)
|
||||
);
|
||||
|
||||
const formatSummaryLabel = (
|
||||
choice: Extract<ToolWizardChoice, { selectable: true }>
|
||||
) => {
|
||||
const annotation = choice.label.annotation
|
||||
? PALETTE.midGray(` (${choice.label.annotation})`)
|
||||
: '';
|
||||
const configuredNote = choice.configured
|
||||
? PALETTE.midGray(' (already configured)')
|
||||
: '';
|
||||
return `${PALETTE.white(choice.label.primary)}${annotation}${configuredNote}`;
|
||||
};
|
||||
|
||||
const stepIndex = step === 'intro' ? 1 : step === 'select' ? 2 : 3;
|
||||
const lines: string[] = [];
|
||||
@@ -222,22 +308,27 @@ const toolSelectionWizard = createPrompt<string[], ToolWizardConfig>(
|
||||
lines.push(PALETTE.white(config.baseMessage));
|
||||
lines.push(
|
||||
PALETTE.midGray(
|
||||
'Use ↑/↓ to move · Space to toggle · Enter to review selections.'
|
||||
'Use ↑/↓ to move · Space to toggle · Enter selects highlighted tool and reviews.'
|
||||
)
|
||||
);
|
||||
lines.push('');
|
||||
lines.push(page);
|
||||
lines.push('');
|
||||
if (selectedNames.length === 0) {
|
||||
lines.push(PALETTE.midGray('Selected configuration:'));
|
||||
if (rootStubSelected && rootStubChoice) {
|
||||
lines.push(
|
||||
`${PALETTE.midGray('Selected')}: ${PALETTE.midGray(
|
||||
'None selected yet'
|
||||
)}`
|
||||
` ${PALETTE.white('-')} ${formatSummaryLabel(rootStubChoice)}`
|
||||
);
|
||||
}
|
||||
if (selectedNativeChoices.length === 0) {
|
||||
lines.push(
|
||||
` ${PALETTE.midGray('- No natively supported providers selected')}`
|
||||
);
|
||||
} else {
|
||||
lines.push(PALETTE.midGray('Selected:'));
|
||||
selectedNames.forEach((name) => {
|
||||
lines.push(` ${PALETTE.white('-')} ${PALETTE.white(name)}`);
|
||||
selectedNativeChoices.forEach((choice) => {
|
||||
lines.push(
|
||||
` ${PALETTE.white('-')} ${formatSummaryLabel(choice)}`
|
||||
);
|
||||
});
|
||||
}
|
||||
} else {
|
||||
@@ -247,13 +338,23 @@ const toolSelectionWizard = createPrompt<string[], ToolWizardConfig>(
|
||||
);
|
||||
lines.push('');
|
||||
|
||||
if (selectedNames.length === 0) {
|
||||
if (rootStubSelected && rootStubChoice) {
|
||||
lines.push(
|
||||
PALETTE.midGray('No tools selected. Press Backspace to return.')
|
||||
`${PALETTE.white('▌')} ${formatSummaryLabel(rootStubChoice)}`
|
||||
);
|
||||
}
|
||||
|
||||
if (selectedNativeChoices.length === 0) {
|
||||
lines.push(
|
||||
PALETTE.midGray(
|
||||
'No natively supported providers selected. Universal instructions will still be applied.'
|
||||
)
|
||||
);
|
||||
} else {
|
||||
selectedNames.forEach((name) => {
|
||||
lines.push(`${PALETTE.white('▌')} ${PALETTE.white(name)}`);
|
||||
selectedNativeChoices.forEach((choice) => {
|
||||
lines.push(
|
||||
`${PALETTE.white('▌')} ${formatSummaryLabel(choice)}`
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -291,17 +392,6 @@ export class InitCommand {
|
||||
// Get configuration (after validation to avoid prompts if validation fails)
|
||||
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) =>
|
||||
@@ -341,7 +431,11 @@ export class InitCommand {
|
||||
|
||||
// Step 2: Configure AI tools
|
||||
const toolSpinner = this.startSpinner('Configuring AI tools...');
|
||||
await this.configureAITools(projectPath, openspecDir, config.aiTools);
|
||||
const rootStubStatus = await this.configureAITools(
|
||||
projectPath,
|
||||
openspecDir,
|
||||
config.aiTools
|
||||
);
|
||||
toolSpinner.stopAndPersist({
|
||||
symbol: PALETTE.white('▌'),
|
||||
text: PALETTE.white('AI tools configured'),
|
||||
@@ -354,7 +448,8 @@ export class InitCommand {
|
||||
refreshed,
|
||||
skippedExisting,
|
||||
skipped,
|
||||
extendMode
|
||||
extendMode,
|
||||
rootStubStatus
|
||||
);
|
||||
}
|
||||
|
||||
@@ -388,27 +483,69 @@ export class InitCommand {
|
||||
): 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
|
||||
? 'Which natively supported AI tools would you like to add or refresh?'
|
||||
: 'Which natively supported AI tools do you use?';
|
||||
const initialNativeSelection = extendMode
|
||||
? availableTools
|
||||
.filter((tool) => existingTools[tool.value])
|
||||
.map((tool) => tool.value)
|
||||
: [];
|
||||
|
||||
return this.prompt({
|
||||
extendMode,
|
||||
baseMessage,
|
||||
choices: availableTools.map((tool) => ({
|
||||
const initialSelected = Array.from(new Set(initialNativeSelection));
|
||||
|
||||
const choices: ToolWizardChoice[] = [
|
||||
{
|
||||
kind: 'heading',
|
||||
value: '__heading-native__',
|
||||
label: {
|
||||
primary:
|
||||
'Natively supported providers (✔ OpenSpec custom slash commands available)',
|
||||
},
|
||||
selectable: false,
|
||||
},
|
||||
...availableTools.map<ToolWizardChoice>((tool) => ({
|
||||
kind: 'option',
|
||||
value: tool.value,
|
||||
label: parseToolLabel(tool.name),
|
||||
configured: Boolean(existingTools[tool.value]),
|
||||
selectable: true,
|
||||
})),
|
||||
...(availableTools.length
|
||||
? ([
|
||||
{
|
||||
kind: 'info' as const,
|
||||
value: LIST_SPACER_VALUE,
|
||||
label: { primary: '' },
|
||||
selectable: false,
|
||||
},
|
||||
] as ToolWizardChoice[])
|
||||
: []),
|
||||
{
|
||||
kind: 'heading',
|
||||
value: OTHER_TOOLS_HEADING_VALUE,
|
||||
label: {
|
||||
primary:
|
||||
'Other tools (use Universal AGENTS.md for Amp, VS Code, GitHub Copilot, …)',
|
||||
},
|
||||
selectable: false,
|
||||
},
|
||||
{
|
||||
kind: 'option',
|
||||
value: ROOT_STUB_CHOICE_VALUE,
|
||||
label: {
|
||||
primary: 'Universal AGENTS.md',
|
||||
annotation: 'always available',
|
||||
},
|
||||
configured: extendMode,
|
||||
selectable: true,
|
||||
},
|
||||
];
|
||||
|
||||
return this.prompt({
|
||||
extendMode,
|
||||
baseMessage,
|
||||
choices,
|
||||
initialSelected,
|
||||
});
|
||||
}
|
||||
@@ -437,8 +574,11 @@ export class InitCommand {
|
||||
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;
|
||||
const absolute = slashConfigurator.resolveAbsolutePath(
|
||||
projectPath,
|
||||
target.id
|
||||
);
|
||||
if (await FileSystemUtils.fileExists(absolute)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -481,7 +621,12 @@ export class InitCommand {
|
||||
projectPath: string,
|
||||
openspecDir: string,
|
||||
toolIds: string[]
|
||||
): Promise<void> {
|
||||
): Promise<RootStubStatus> {
|
||||
const rootStubStatus = await this.configureRootAgentsStub(
|
||||
projectPath,
|
||||
openspecDir
|
||||
);
|
||||
|
||||
for (const toolId of toolIds) {
|
||||
const configurator = ToolRegistry.get(toolId);
|
||||
if (configurator && configurator.isAvailable) {
|
||||
@@ -493,6 +638,25 @@ export class InitCommand {
|
||||
await slashConfigurator.generateAll(projectPath, openspecDir);
|
||||
}
|
||||
}
|
||||
|
||||
return rootStubStatus;
|
||||
}
|
||||
|
||||
private async configureRootAgentsStub(
|
||||
projectPath: string,
|
||||
openspecDir: string
|
||||
): Promise<RootStubStatus> {
|
||||
const configurator = ToolRegistry.get('agents');
|
||||
if (!configurator || !configurator.isAvailable) {
|
||||
return 'skipped';
|
||||
}
|
||||
|
||||
const stubPath = path.join(projectPath, configurator.configFileName);
|
||||
const existed = await FileSystemUtils.fileExists(stubPath);
|
||||
|
||||
await configurator.configure(projectPath, openspecDir);
|
||||
|
||||
return existed ? 'updated' : 'created';
|
||||
}
|
||||
|
||||
private displaySuccessMessage(
|
||||
@@ -501,7 +665,8 @@ export class InitCommand {
|
||||
refreshed: AIToolOption[],
|
||||
skippedExisting: AIToolOption[],
|
||||
skipped: AIToolOption[],
|
||||
extendMode: boolean
|
||||
extendMode: boolean,
|
||||
rootStubStatus: RootStubStatus
|
||||
): void {
|
||||
console.log(); // Empty line for spacing
|
||||
const successHeadline = extendMode
|
||||
@@ -512,6 +677,16 @@ export class InitCommand {
|
||||
console.log();
|
||||
console.log(PALETTE.lightGray('Tool summary:'));
|
||||
const summaryLines = [
|
||||
rootStubStatus === 'created'
|
||||
? `${PALETTE.white('▌')} ${PALETTE.white(
|
||||
'Root AGENTS.md stub created for other assistants'
|
||||
)}`
|
||||
: null,
|
||||
rootStubStatus === 'updated'
|
||||
? `${PALETTE.lightGray('▌')} ${PALETTE.lightGray(
|
||||
'Root AGENTS.md stub refreshed for other assistants'
|
||||
)}`
|
||||
: null,
|
||||
created.length
|
||||
? `${PALETTE.white('▌')} ${PALETTE.white(
|
||||
'Created:'
|
||||
@@ -586,6 +761,16 @@ export class InitCommand {
|
||||
'────────────────────────────────────────────────────────────\n'
|
||||
)
|
||||
);
|
||||
|
||||
// Codex heads-up: prompts installed globally
|
||||
const selectedToolIds = new Set(selectedTools.map((t) => t.value));
|
||||
if (selectedToolIds.has('codex')) {
|
||||
console.log(PALETTE.white('Codex setup note'));
|
||||
console.log(
|
||||
PALETTE.midGray('Prompts installed to ~/.codex/prompts (or $CODEX_HOME/prompts).')
|
||||
);
|
||||
console.log();
|
||||
}
|
||||
}
|
||||
|
||||
private formatToolNames(tools: AIToolOption[]): string {
|
||||
@@ -593,7 +778,8 @@ export class InitCommand {
|
||||
.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 === 0)
|
||||
return PALETTE.lightGray('your AGENTS.md-compatible assistant');
|
||||
if (names.length === 1) return PALETTE.white(names[0]);
|
||||
|
||||
const base = names.slice(0, -1).map((name) => PALETTE.white(name));
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import chalk from 'chalk';
|
||||
|
||||
export const PALETTE = {
|
||||
white: chalk.hex('#f4f4f4'),
|
||||
lightGray: chalk.hex('#c8c8c8'),
|
||||
midGray: chalk.hex('#8a8a8a'),
|
||||
darkGray: chalk.hex('#4a4a4a')
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
export const agentsRootStubTemplate = `# OpenSpec Instructions
|
||||
|
||||
These instructions are for AI assistants working in this project.
|
||||
|
||||
Always open \`@/openspec/AGENTS.md\` when the request:
|
||||
- Mentions planning or proposals (words like proposal, spec, change, plan)
|
||||
- Introduces new capabilities, breaking changes, architecture shifts, or big performance/security work
|
||||
- Sounds ambiguous and you need the authoritative spec before coding
|
||||
|
||||
Use \`@/openspec/AGENTS.md\` to learn:
|
||||
- How to create and apply change proposals
|
||||
- Spec format and conventions
|
||||
- Project structure and guidelines
|
||||
|
||||
Keep this managed block so 'openspec update' can refresh the instructions.
|
||||
`;
|
||||
@@ -1 +1 @@
|
||||
export { agentsTemplate as claudeTemplate } from './agents-template.js';
|
||||
export { agentsRootStubTemplate as claudeTemplate } from './agents-root-stub.js';
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { agentsTemplate } from './agents-template.js';
|
||||
import { projectTemplate, ProjectContext } from './project-template.js';
|
||||
import { claudeTemplate } from './claude-template.js';
|
||||
import { agentsRootStubTemplate } from './agents-root-stub.js';
|
||||
import { getSlashCommandBody, SlashCommandId } from './slash-command-templates.js';
|
||||
|
||||
export interface Template {
|
||||
@@ -27,7 +28,7 @@ export class TemplateManager {
|
||||
}
|
||||
|
||||
static getAgentsStandardTemplate(): string {
|
||||
return agentsTemplate;
|
||||
return agentsRootStubTemplate;
|
||||
}
|
||||
|
||||
static getSlashCommandBody(id: SlashCommandId): string {
|
||||
|
||||
@@ -3,7 +3,7 @@ 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.`;
|
||||
- Refer to \`openspec/AGENTS.md\` (located inside the \`openspec/\` directory—run \`ls openspec\` or \`openspec update\` if you don't see it) 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.`;
|
||||
|
||||
@@ -12,7 +12,7 @@ const proposalSteps = `**Steps**
|
||||
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.
|
||||
5. Draft spec deltas in \`changes/<id>/specs/<capability>/spec.md\` (one folder per capability) 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.`;
|
||||
|
||||
|
||||
+78
-49
@@ -1,10 +1,9 @@
|
||||
import path from 'path';
|
||||
import { FileSystemUtils } from '../utils/file-system.js';
|
||||
import { OPENSPEC_DIR_NAME, OPENSPEC_MARKERS } from './config.js';
|
||||
import { agentsTemplate } from './templates/agents-template.js';
|
||||
import { TemplateManager } from './templates/index.js';
|
||||
import { OPENSPEC_DIR_NAME } from './config.js';
|
||||
import { ToolRegistry } from './configurators/registry.js';
|
||||
import { SlashCommandRegistry } from './configurators/slash/registry.js';
|
||||
import { agentsTemplate } from './templates/agents-template.js';
|
||||
|
||||
export class UpdateCommand {
|
||||
async execute(projectPath: string): Promise<void> {
|
||||
@@ -19,41 +18,51 @@ export class UpdateCommand {
|
||||
|
||||
// 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[] = [];
|
||||
|
||||
const updatedFiles: string[] = [];
|
||||
const createdFiles: string[] = [];
|
||||
const failedFiles: string[] = [];
|
||||
const updatedSlashFiles: string[] = [];
|
||||
const failedSlashTools: string[] = [];
|
||||
|
||||
for (const configurator of configurators) {
|
||||
const configFilePath = path.join(resolvedProjectPath, configurator.configFileName);
|
||||
|
||||
// Only update if the file already exists
|
||||
if (await FileSystemUtils.fileExists(configFilePath)) {
|
||||
try {
|
||||
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) {
|
||||
failedFiles.push(configurator.configFileName);
|
||||
console.error(`Failed to update ${configurator.configFileName}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
const configFilePath = path.join(
|
||||
resolvedProjectPath,
|
||||
configurator.configFileName
|
||||
);
|
||||
const fileExists = await FileSystemUtils.fileExists(configFilePath);
|
||||
const shouldConfigure =
|
||||
fileExists || configurator.configFileName === 'AGENTS.md';
|
||||
|
||||
if (!shouldConfigure) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
if (fileExists && !await FileSystemUtils.canWriteFile(configFilePath)) {
|
||||
throw new Error(
|
||||
`Insufficient permissions to modify ${configurator.configFileName}`
|
||||
);
|
||||
}
|
||||
|
||||
await configurator.configure(resolvedProjectPath, openspecPath);
|
||||
updatedFiles.push(configurator.configFileName);
|
||||
|
||||
if (!fileExists) {
|
||||
createdFiles.push(configurator.configFileName);
|
||||
}
|
||||
} catch (error) {
|
||||
failedFiles.push(configurator.configFileName);
|
||||
console.error(
|
||||
`Failed to update ${configurator.configFileName}: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,38 +72,58 @@ export class UpdateCommand {
|
||||
}
|
||||
|
||||
try {
|
||||
const updated = await slashConfigurator.updateExisting(resolvedProjectPath, openspecPath);
|
||||
updatedSlashFiles = updatedSlashFiles.concat(updated);
|
||||
const updated = await slashConfigurator.updateExisting(
|
||||
resolvedProjectPath,
|
||||
openspecPath
|
||||
);
|
||||
updatedSlashFiles.push(...updated);
|
||||
} catch (error) {
|
||||
failedSlashTools.push(slashConfigurator.toolId);
|
||||
console.error(
|
||||
`Failed to update slash commands for ${slashConfigurator.toolId}: ${error instanceof Error ? error.message : String(error)}`
|
||||
`Failed to update slash commands for ${slashConfigurator.toolId}: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Success message (ASCII-safe)
|
||||
const instructionUpdates = ['openspec/AGENTS.md'];
|
||||
instructionUpdates.push(`AGENTS.md${rootAgentsExisted ? '' : ' (created)'}`);
|
||||
const summaryParts: string[] = [];
|
||||
const instructionFiles: string[] = ['openspec/AGENTS.md'];
|
||||
|
||||
const messages: string[] = [`Updated OpenSpec instructions (${instructionUpdates.join(', ')})`];
|
||||
|
||||
if (updatedFiles.length > 0) {
|
||||
messages.push(`Updated AI tool files: ${updatedFiles.join(', ')}`);
|
||||
if (updatedFiles.includes('AGENTS.md')) {
|
||||
instructionFiles.push(
|
||||
createdFiles.includes('AGENTS.md') ? 'AGENTS.md (created)' : 'AGENTS.md'
|
||||
);
|
||||
}
|
||||
|
||||
summaryParts.push(
|
||||
`Updated OpenSpec instructions (${instructionFiles.join(', ')})`
|
||||
);
|
||||
|
||||
const aiToolFiles = updatedFiles.filter((file) => file !== 'AGENTS.md');
|
||||
if (aiToolFiles.length > 0) {
|
||||
summaryParts.push(`Updated AI tool files: ${aiToolFiles.join(', ')}`);
|
||||
}
|
||||
|
||||
if (updatedSlashFiles.length > 0) {
|
||||
messages.push(`Updated slash commands: ${updatedSlashFiles.join(', ')}`);
|
||||
}
|
||||
|
||||
if (failedFiles.length > 0) {
|
||||
messages.push(`Failed to update: ${failedFiles.join(', ')}`);
|
||||
// Normalize to forward slashes for cross-platform log consistency
|
||||
const normalized = updatedSlashFiles.map((p) => p.replace(/\\/g, '/'));
|
||||
summaryParts.push(`Updated slash commands: ${normalized.join(', ')}`);
|
||||
}
|
||||
|
||||
if (failedSlashTools.length > 0) {
|
||||
messages.push(`Failed slash command updates: ${failedSlashTools.join(', ')}`);
|
||||
const failedItems = [
|
||||
...failedFiles,
|
||||
...failedSlashTools.map(
|
||||
(toolId) => `slash command refresh (${toolId})`
|
||||
),
|
||||
];
|
||||
|
||||
if (failedItems.length > 0) {
|
||||
summaryParts.push(`Failed to update: ${failedItems.join(', ')}`);
|
||||
}
|
||||
|
||||
console.log(messages.join('\n'));
|
||||
|
||||
console.log(summaryParts.join(' | '));
|
||||
|
||||
// No additional notes
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,11 +38,11 @@ export const VALIDATION_MESSAGES = {
|
||||
|
||||
// Guidance snippets (appended to primary messages for remediation)
|
||||
GUIDE_NO_DELTAS:
|
||||
'No deltas found. Ensure your change has a specs/ directory with .md files using delta headers (## ADDED/MODIFIED/REMOVED/RENAMED Requirements) and that each requirement includes at least one "#### Scenario:" block. Tip: run "openspec change show <change-id> --json --deltas-only" to inspect parsed deltas.',
|
||||
'No deltas found. Ensure your change has a specs/ directory with capability folders (e.g. specs/http-server/spec.md) containing .md files that use delta headers (## ADDED/MODIFIED/REMOVED/RENAMED Requirements) and that each requirement includes at least one "#### Scenario:" block. Tip: run "openspec change show <change-id> --json --deltas-only" to inspect parsed deltas.',
|
||||
GUIDE_MISSING_SPEC_SECTIONS:
|
||||
'Missing required sections. Expected headers: "## Purpose" and "## Requirements". Example:\n## Purpose\n[brief purpose]\n\n## Requirements\n### Requirement: Clear requirement statement\nUsers SHALL ...\n\n#### Scenario: Descriptive name\n- **WHEN** ...\n- **THEN** ...',
|
||||
GUIDE_MISSING_CHANGE_SECTIONS:
|
||||
'Missing required sections. Expected headers: "## Why" and "## What Changes". Ensure deltas are documented in specs/ using delta headers.',
|
||||
GUIDE_SCENARIO_FORMAT:
|
||||
'Scenarios must use level-4 headers. Convert bullet lists into:\n#### Scenario: Short name\n- **WHEN** ...\n- **THEN** ...\n- **AND** ...',
|
||||
} as const;
|
||||
} as const;
|
||||
|
||||
@@ -1,7 +1,74 @@
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
function isMarkerOnOwnLine(content: string, markerIndex: number, markerLength: number): boolean {
|
||||
let leftIndex = markerIndex - 1;
|
||||
while (leftIndex >= 0 && content[leftIndex] !== '\n') {
|
||||
const char = content[leftIndex];
|
||||
if (char !== ' ' && char !== '\t' && char !== '\r') {
|
||||
return false;
|
||||
}
|
||||
leftIndex--;
|
||||
}
|
||||
|
||||
let rightIndex = markerIndex + markerLength;
|
||||
while (rightIndex < content.length && content[rightIndex] !== '\n') {
|
||||
const char = content[rightIndex];
|
||||
if (char !== ' ' && char !== '\t' && char !== '\r') {
|
||||
return false;
|
||||
}
|
||||
rightIndex++;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function findMarkerIndex(
|
||||
content: string,
|
||||
marker: string,
|
||||
fromIndex = 0
|
||||
): number {
|
||||
let currentIndex = content.indexOf(marker, fromIndex);
|
||||
|
||||
while (currentIndex !== -1) {
|
||||
if (isMarkerOnOwnLine(content, currentIndex, marker.length)) {
|
||||
return currentIndex;
|
||||
}
|
||||
|
||||
currentIndex = content.indexOf(marker, currentIndex + marker.length);
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
export class FileSystemUtils {
|
||||
private static isWindowsBasePath(basePath: string): boolean {
|
||||
return /^[A-Za-z]:[\\/]/.test(basePath) || basePath.startsWith('\\');
|
||||
}
|
||||
|
||||
private static normalizeSegments(segments: string[]): string[] {
|
||||
return segments
|
||||
.flatMap((segment) => segment.split(/[\\/]+/u))
|
||||
.filter((part) => part.length > 0);
|
||||
}
|
||||
|
||||
static joinPath(basePath: string, ...segments: string[]): string {
|
||||
const normalizedSegments = this.normalizeSegments(segments);
|
||||
|
||||
if (this.isWindowsBasePath(basePath)) {
|
||||
const normalizedBasePath = path.win32.normalize(basePath);
|
||||
return normalizedSegments.length
|
||||
? path.win32.join(normalizedBasePath, ...normalizedSegments)
|
||||
: normalizedBasePath;
|
||||
}
|
||||
|
||||
const posixBasePath = basePath.replace(/\\/g, '/');
|
||||
|
||||
return normalizedSegments.length
|
||||
? path.posix.join(posixBasePath, ...normalizedSegments)
|
||||
: path.posix.normalize(posixBasePath);
|
||||
}
|
||||
|
||||
static async createDirectory(dirPath: string): Promise<void> {
|
||||
await fs.mkdir(dirPath, { recursive: true });
|
||||
}
|
||||
@@ -70,10 +137,18 @@ export class FileSystemUtils {
|
||||
if (await this.fileExists(filePath)) {
|
||||
existingContent = await this.readFile(filePath);
|
||||
|
||||
const startIndex = existingContent.indexOf(startMarker);
|
||||
const endIndex = existingContent.indexOf(endMarker);
|
||||
|
||||
const startIndex = findMarkerIndex(existingContent, startMarker);
|
||||
const endIndex = startIndex !== -1
|
||||
? findMarkerIndex(existingContent, endMarker, startIndex + startMarker.length)
|
||||
: findMarkerIndex(existingContent, endMarker);
|
||||
|
||||
if (startIndex !== -1 && endIndex !== -1) {
|
||||
if (endIndex < startIndex) {
|
||||
throw new Error(
|
||||
`Invalid marker state in ${filePath}. End marker appears before start marker.`
|
||||
);
|
||||
}
|
||||
|
||||
const before = existingContent.substring(0, startIndex);
|
||||
const after = existingContent.substring(endIndex + endMarker.length);
|
||||
existingContent = before + startMarker + '\n' + content + '\n' + endMarker + after;
|
||||
@@ -109,4 +184,4 @@ export class FileSystemUtils {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+231
-11
@@ -36,6 +36,7 @@ function queueSelections(...values: string[]) {
|
||||
describe('InitCommand', () => {
|
||||
let testDir: string;
|
||||
let initCommand: InitCommand;
|
||||
let prevCodexHome: string | undefined;
|
||||
|
||||
beforeEach(async () => {
|
||||
testDir = path.join(os.tmpdir(), `openspec-init-test-${Date.now()}`);
|
||||
@@ -44,6 +45,10 @@ describe('InitCommand', () => {
|
||||
mockPrompt.mockReset();
|
||||
initCommand = new InitCommand({ prompt: mockPrompt });
|
||||
|
||||
// Route Codex global directory into the test sandbox
|
||||
prevCodexHome = process.env.CODEX_HOME;
|
||||
process.env.CODEX_HOME = path.join(testDir, '.codex');
|
||||
|
||||
// Mock console.log to suppress output during tests
|
||||
vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
});
|
||||
@@ -51,6 +56,8 @@ describe('InitCommand', () => {
|
||||
afterEach(async () => {
|
||||
await fs.rm(testDir, { recursive: true, force: true });
|
||||
vi.restoreAllMocks();
|
||||
if (prevCodexHome === undefined) delete process.env.CODEX_HOME;
|
||||
else process.env.CODEX_HOME = prevCodexHome;
|
||||
});
|
||||
|
||||
describe('execute', () => {
|
||||
@@ -106,7 +113,8 @@ describe('InitCommand', () => {
|
||||
|
||||
const content = await fs.readFile(claudePath, 'utf-8');
|
||||
expect(content).toContain('<!-- OPENSPEC:START -->');
|
||||
expect(content).toContain('OpenSpec Instructions');
|
||||
expect(content).toContain("@/openspec/AGENTS.md");
|
||||
expect(content).toContain('openspec update');
|
||||
expect(content).toContain('<!-- OPENSPEC:END -->');
|
||||
});
|
||||
|
||||
@@ -122,13 +130,58 @@ describe('InitCommand', () => {
|
||||
|
||||
const updatedContent = await fs.readFile(claudePath, 'utf-8');
|
||||
expect(updatedContent).toContain('<!-- OPENSPEC:START -->');
|
||||
expect(updatedContent).toContain('OpenSpec Instructions');
|
||||
expect(updatedContent).toContain("@/openspec/AGENTS.md");
|
||||
expect(updatedContent).toContain('openspec update');
|
||||
expect(updatedContent).toContain('<!-- OPENSPEC:END -->');
|
||||
expect(updatedContent).toContain('Custom instructions here');
|
||||
});
|
||||
|
||||
it('should create AGENTS.md in project root when AGENTS standard is selected', async () => {
|
||||
queueSelections('agents', DONE);
|
||||
it('should create Windsurf workflows when Windsurf is selected', async () => {
|
||||
queueSelections('windsurf', DONE);
|
||||
|
||||
await initCommand.execute(testDir);
|
||||
|
||||
const wsProposal = path.join(
|
||||
testDir,
|
||||
'.windsurf/workflows/openspec-proposal.md'
|
||||
);
|
||||
const wsApply = path.join(
|
||||
testDir,
|
||||
'.windsurf/workflows/openspec-apply.md'
|
||||
);
|
||||
const wsArchive = path.join(
|
||||
testDir,
|
||||
'.windsurf/workflows/openspec-archive.md'
|
||||
);
|
||||
|
||||
expect(await fileExists(wsProposal)).toBe(true);
|
||||
expect(await fileExists(wsApply)).toBe(true);
|
||||
expect(await fileExists(wsArchive)).toBe(true);
|
||||
|
||||
const proposalContent = await fs.readFile(wsProposal, 'utf-8');
|
||||
expect(proposalContent).toContain('---');
|
||||
expect(proposalContent).toContain('description: Scaffold a new OpenSpec change and validate strictly.');
|
||||
expect(proposalContent).toContain('auto_execution_mode: 3');
|
||||
expect(proposalContent).toContain('<!-- OPENSPEC:START -->');
|
||||
expect(proposalContent).toContain('**Guardrails**');
|
||||
|
||||
const applyContent = await fs.readFile(wsApply, 'utf-8');
|
||||
expect(applyContent).toContain('---');
|
||||
expect(applyContent).toContain('description: Implement an approved OpenSpec change and keep tasks in sync.');
|
||||
expect(applyContent).toContain('auto_execution_mode: 3');
|
||||
expect(applyContent).toContain('<!-- OPENSPEC:START -->');
|
||||
expect(applyContent).toContain('Work through tasks sequentially');
|
||||
|
||||
const archiveContent = await fs.readFile(wsArchive, 'utf-8');
|
||||
expect(archiveContent).toContain('---');
|
||||
expect(archiveContent).toContain('description: Archive a deployed OpenSpec change and update specs.');
|
||||
expect(archiveContent).toContain('auto_execution_mode: 3');
|
||||
expect(archiveContent).toContain('<!-- OPENSPEC:START -->');
|
||||
expect(archiveContent).toContain('Run `openspec archive <id> --yes`');
|
||||
});
|
||||
|
||||
it('should always create AGENTS.md in project root', async () => {
|
||||
queueSelections(DONE);
|
||||
|
||||
await initCommand.execute(testDir);
|
||||
|
||||
@@ -137,7 +190,8 @@ describe('InitCommand', () => {
|
||||
|
||||
const content = await fs.readFile(rootAgentsPath, 'utf-8');
|
||||
expect(content).toContain('<!-- OPENSPEC:START -->');
|
||||
expect(content).toContain('OpenSpec Instructions');
|
||||
expect(content).toContain("@/openspec/AGENTS.md");
|
||||
expect(content).toContain('openspec update');
|
||||
expect(content).toContain('<!-- OPENSPEC:END -->');
|
||||
|
||||
const claudeExists = await fileExists(path.join(testDir, 'CLAUDE.md'));
|
||||
@@ -262,6 +316,126 @@ describe('InitCommand', () => {
|
||||
expect(archiveContent).toContain('openspec list --specs');
|
||||
});
|
||||
|
||||
it('should create Codex prompts with templates and placeholders', async () => {
|
||||
queueSelections('codex', DONE);
|
||||
|
||||
await initCommand.execute(testDir);
|
||||
|
||||
const proposalPath = path.join(
|
||||
testDir,
|
||||
'.codex/prompts/openspec-proposal.md'
|
||||
);
|
||||
const applyPath = path.join(
|
||||
testDir,
|
||||
'.codex/prompts/openspec-apply.md'
|
||||
);
|
||||
const archivePath = path.join(
|
||||
testDir,
|
||||
'.codex/prompts/openspec-archive.md'
|
||||
);
|
||||
|
||||
expect(await fileExists(proposalPath)).toBe(true);
|
||||
expect(await fileExists(applyPath)).toBe(true);
|
||||
expect(await fileExists(archivePath)).toBe(true);
|
||||
|
||||
const proposalContent = await fs.readFile(proposalPath, 'utf-8');
|
||||
expect(proposalContent).toContain('description: Scaffold a new OpenSpec change and validate strictly.');
|
||||
expect(proposalContent).toContain('argument-hint: request or feature description');
|
||||
expect(proposalContent).toContain('$ARGUMENTS');
|
||||
expect(proposalContent).toContain('<!-- OPENSPEC:START -->');
|
||||
expect(proposalContent).toContain('**Guardrails**');
|
||||
|
||||
const applyContent = await fs.readFile(applyPath, 'utf-8');
|
||||
expect(applyContent).toContain('description: Implement an approved OpenSpec change and keep tasks in sync.');
|
||||
expect(applyContent).toContain('argument-hint: change-id');
|
||||
expect(applyContent).toContain('$ARGUMENTS');
|
||||
expect(applyContent).toContain('Work through tasks sequentially');
|
||||
|
||||
const archiveContent = await fs.readFile(archivePath, 'utf-8');
|
||||
expect(archiveContent).toContain('description: Archive a deployed OpenSpec change and update specs.');
|
||||
expect(archiveContent).toContain('argument-hint: change-id');
|
||||
expect(archiveContent).toContain('$ARGUMENTS');
|
||||
expect(archiveContent).toContain('openspec archive <id> --yes');
|
||||
});
|
||||
|
||||
it('should create Kilo Code workflows with templates', async () => {
|
||||
queueSelections('kilocode', DONE);
|
||||
|
||||
await initCommand.execute(testDir);
|
||||
|
||||
const proposalPath = path.join(
|
||||
testDir,
|
||||
'.kilocode/workflows/openspec-proposal.md'
|
||||
);
|
||||
const applyPath = path.join(
|
||||
testDir,
|
||||
'.kilocode/workflows/openspec-apply.md'
|
||||
);
|
||||
const archivePath = path.join(
|
||||
testDir,
|
||||
'.kilocode/workflows/openspec-archive.md'
|
||||
);
|
||||
|
||||
expect(await fileExists(proposalPath)).toBe(true);
|
||||
expect(await fileExists(applyPath)).toBe(true);
|
||||
expect(await fileExists(archivePath)).toBe(true);
|
||||
|
||||
const proposalContent = await fs.readFile(proposalPath, 'utf-8');
|
||||
expect(proposalContent).toContain('<!-- OPENSPEC:START -->');
|
||||
expect(proposalContent).toContain('**Guardrails**');
|
||||
expect(proposalContent).not.toContain('---\n');
|
||||
|
||||
const applyContent = await fs.readFile(applyPath, 'utf-8');
|
||||
expect(applyContent).toContain('Work through tasks sequentially');
|
||||
expect(applyContent).not.toContain('---\n');
|
||||
|
||||
const archiveContent = await fs.readFile(archivePath, 'utf-8');
|
||||
expect(archiveContent).toContain('openspec list --specs');
|
||||
expect(archiveContent).not.toContain('---\n');
|
||||
});
|
||||
|
||||
it('should create GitHub Copilot prompt files with templates', async () => {
|
||||
queueSelections('github-copilot', DONE);
|
||||
|
||||
await initCommand.execute(testDir);
|
||||
|
||||
const proposalPath = path.join(
|
||||
testDir,
|
||||
'.github/prompts/openspec-proposal.prompt.md'
|
||||
);
|
||||
const applyPath = path.join(
|
||||
testDir,
|
||||
'.github/prompts/openspec-apply.prompt.md'
|
||||
);
|
||||
const archivePath = path.join(
|
||||
testDir,
|
||||
'.github/prompts/openspec-archive.prompt.md'
|
||||
);
|
||||
|
||||
expect(await fileExists(proposalPath)).toBe(true);
|
||||
expect(await fileExists(applyPath)).toBe(true);
|
||||
expect(await fileExists(archivePath)).toBe(true);
|
||||
|
||||
const proposalContent = await fs.readFile(proposalPath, 'utf-8');
|
||||
expect(proposalContent).toContain('---');
|
||||
expect(proposalContent).toContain('description: Scaffold a new OpenSpec change and validate strictly.');
|
||||
expect(proposalContent).toContain('$ARGUMENTS');
|
||||
expect(proposalContent).toContain('<!-- OPENSPEC:START -->');
|
||||
expect(proposalContent).toContain('**Guardrails**');
|
||||
|
||||
const applyContent = await fs.readFile(applyPath, 'utf-8');
|
||||
expect(applyContent).toContain('---');
|
||||
expect(applyContent).toContain('description: Implement an approved OpenSpec change and keep tasks in sync.');
|
||||
expect(applyContent).toContain('$ARGUMENTS');
|
||||
expect(applyContent).toContain('Work through tasks sequentially');
|
||||
|
||||
const archiveContent = await fs.readFile(archivePath, 'utf-8');
|
||||
expect(archiveContent).toContain('---');
|
||||
expect(archiveContent).toContain('description: Archive a deployed OpenSpec change and update specs.');
|
||||
expect(archiveContent).toContain('$ARGUMENTS');
|
||||
expect(archiveContent).toContain('openspec archive <id> --yes');
|
||||
});
|
||||
|
||||
it('should add new tool when OpenSpec already exists', async () => {
|
||||
queueSelections('claude', DONE, 'cursor', DONE);
|
||||
await initCommand.execute(testDir);
|
||||
@@ -274,12 +448,10 @@ describe('InitCommand', () => {
|
||||
expect(await fileExists(cursorProposal)).toBe(true);
|
||||
});
|
||||
|
||||
it('should error when extend mode selects no tools', async () => {
|
||||
it('should allow extend mode with no additional native tools', async () => {
|
||||
queueSelections('claude', DONE, DONE);
|
||||
await initCommand.execute(testDir);
|
||||
await expect(initCommand.execute(testDir)).rejects.toThrow(
|
||||
/OpenSpec seems to already be initialized/
|
||||
);
|
||||
await expect(initCommand.execute(testDir)).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('should handle non-existent target directory', async () => {
|
||||
@@ -303,7 +475,7 @@ describe('InitCommand', () => {
|
||||
});
|
||||
|
||||
it('should reference AGENTS compatible assistants in success message', async () => {
|
||||
queueSelections('agents', DONE);
|
||||
queueSelections(DONE);
|
||||
const logSpy = vi.spyOn(console, 'log');
|
||||
|
||||
await initCommand.execute(testDir);
|
||||
@@ -323,7 +495,9 @@ describe('InitCommand', () => {
|
||||
|
||||
expect(mockPrompt).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
baseMessage: expect.stringContaining('Which AI tools do you use?'),
|
||||
baseMessage: expect.stringContaining(
|
||||
'Which natively supported AI tools do you use?'
|
||||
),
|
||||
})
|
||||
);
|
||||
});
|
||||
@@ -350,6 +524,52 @@ describe('InitCommand', () => {
|
||||
);
|
||||
expect(claudeChoice.configured).toBe(true);
|
||||
});
|
||||
|
||||
it('should preselect Kilo Code when workflows already exist', async () => {
|
||||
queueSelections('kilocode', DONE, 'kilocode', DONE);
|
||||
await initCommand.execute(testDir);
|
||||
await initCommand.execute(testDir);
|
||||
|
||||
const secondRunArgs = mockPrompt.mock.calls[1][0];
|
||||
const preselected = secondRunArgs.initialSelected ?? [];
|
||||
expect(preselected).toContain('kilocode');
|
||||
});
|
||||
|
||||
it('should mark Windsurf as already configured during extend mode', async () => {
|
||||
queueSelections('windsurf', DONE, 'windsurf', DONE);
|
||||
await initCommand.execute(testDir);
|
||||
await initCommand.execute(testDir);
|
||||
|
||||
const secondRunArgs = mockPrompt.mock.calls[1][0];
|
||||
const wsChoice = secondRunArgs.choices.find(
|
||||
(choice: any) => choice.value === 'windsurf'
|
||||
);
|
||||
expect(wsChoice.configured).toBe(true);
|
||||
});
|
||||
|
||||
it('should mark Codex as already configured during extend mode', async () => {
|
||||
queueSelections('codex', DONE, 'codex', DONE);
|
||||
await initCommand.execute(testDir);
|
||||
await initCommand.execute(testDir);
|
||||
|
||||
const secondRunArgs = mockPrompt.mock.calls[1][0];
|
||||
const codexChoice = secondRunArgs.choices.find(
|
||||
(choice: any) => choice.value === 'codex'
|
||||
);
|
||||
expect(codexChoice.configured).toBe(true);
|
||||
});
|
||||
|
||||
it('should mark GitHub Copilot as already configured during extend mode', async () => {
|
||||
queueSelections('github-copilot', DONE, 'github-copilot', DONE);
|
||||
await initCommand.execute(testDir);
|
||||
await initCommand.execute(testDir);
|
||||
|
||||
const secondRunArgs = mockPrompt.mock.calls[1][0];
|
||||
const githubCopilotChoice = secondRunArgs.choices.find(
|
||||
(choice: any) => choice.value === 'github-copilot'
|
||||
);
|
||||
expect(githubCopilotChoice.configured).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('error handling', () => {
|
||||
|
||||
+237
-3
@@ -10,6 +10,7 @@ import { randomUUID } from 'crypto';
|
||||
describe('UpdateCommand', () => {
|
||||
let testDir: string;
|
||||
let updateCommand: UpdateCommand;
|
||||
let prevCodexHome: string | undefined;
|
||||
|
||||
beforeEach(async () => {
|
||||
// Create a temporary test directory
|
||||
@@ -21,11 +22,17 @@ describe('UpdateCommand', () => {
|
||||
await fs.mkdir(openspecDir, { recursive: true });
|
||||
|
||||
updateCommand = new UpdateCommand();
|
||||
|
||||
// Route Codex global directory into the test sandbox
|
||||
prevCodexHome = process.env.CODEX_HOME;
|
||||
process.env.CODEX_HOME = path.join(testDir, '.codex');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
// Clean up test directory
|
||||
await fs.rm(testDir, { recursive: true, force: true });
|
||||
if (prevCodexHome === undefined) delete process.env.CODEX_HOME;
|
||||
else process.env.CODEX_HOME = prevCodexHome;
|
||||
});
|
||||
|
||||
it('should update only existing CLAUDE.md file', async () => {
|
||||
@@ -51,7 +58,8 @@ More content after.`;
|
||||
const updatedContent = await fs.readFile(claudePath, 'utf-8');
|
||||
expect(updatedContent).toContain('<!-- OPENSPEC:START -->');
|
||||
expect(updatedContent).toContain('<!-- OPENSPEC:END -->');
|
||||
expect(updatedContent).toContain('OpenSpec Instructions');
|
||||
expect(updatedContent).toContain("@/openspec/AGENTS.md");
|
||||
expect(updatedContent).toContain('openspec update');
|
||||
expect(updatedContent).toContain('Some existing content here');
|
||||
expect(updatedContent).toContain('More content after');
|
||||
|
||||
@@ -191,6 +199,230 @@ Old body
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should refresh existing Kilo Code workflows', async () => {
|
||||
const kilocodePath = path.join(
|
||||
testDir,
|
||||
'.kilocode/workflows/openspec-apply.md'
|
||||
);
|
||||
await fs.mkdir(path.dirname(kilocodePath), { recursive: true });
|
||||
const initialContent = `<!-- OPENSPEC:START -->
|
||||
Old body
|
||||
<!-- OPENSPEC:END -->`;
|
||||
await fs.writeFile(kilocodePath, initialContent);
|
||||
|
||||
const consoleSpy = vi.spyOn(console, 'log');
|
||||
|
||||
await updateCommand.execute(testDir);
|
||||
|
||||
const updated = await fs.readFile(kilocodePath, 'utf-8');
|
||||
expect(updated).toContain('Work through tasks sequentially');
|
||||
expect(updated).not.toContain('Old body');
|
||||
expect(updated.startsWith('<!-- OPENSPEC:START -->')).toBe(true);
|
||||
|
||||
const [logMessage] = consoleSpy.mock.calls[0];
|
||||
expect(logMessage).toContain(
|
||||
'Updated slash commands: .kilocode/workflows/openspec-apply.md'
|
||||
);
|
||||
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should refresh existing Windsurf workflows', async () => {
|
||||
const wsPath = path.join(
|
||||
testDir,
|
||||
'.windsurf/workflows/openspec-apply.md'
|
||||
);
|
||||
await fs.mkdir(path.dirname(wsPath), { recursive: true });
|
||||
const initialContent = `## OpenSpec: Apply (Windsurf)
|
||||
Intro
|
||||
<!-- OPENSPEC:START -->
|
||||
Old body
|
||||
<!-- OPENSPEC:END -->`;
|
||||
await fs.writeFile(wsPath, initialContent);
|
||||
|
||||
const consoleSpy = vi.spyOn(console, 'log');
|
||||
|
||||
await updateCommand.execute(testDir);
|
||||
|
||||
const updated = await fs.readFile(wsPath, 'utf-8');
|
||||
expect(updated).toContain('Work through tasks sequentially');
|
||||
expect(updated).not.toContain('Old body');
|
||||
expect(updated).toContain('## OpenSpec: Apply (Windsurf)');
|
||||
|
||||
const [logMessage] = consoleSpy.mock.calls[0];
|
||||
expect(logMessage).toContain(
|
||||
'Updated slash commands: .windsurf/workflows/openspec-apply.md'
|
||||
);
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should refresh existing Codex prompts', async () => {
|
||||
const codexPath = path.join(
|
||||
testDir,
|
||||
'.codex/prompts/openspec-apply.md'
|
||||
);
|
||||
await fs.mkdir(path.dirname(codexPath), { recursive: true });
|
||||
const initialContent = `---\ndescription: Old description\nargument-hint: old-hint\n---\n\n$ARGUMENTS\n<!-- OPENSPEC:START -->\nOld body\n<!-- OPENSPEC:END -->`;
|
||||
await fs.writeFile(codexPath, initialContent);
|
||||
|
||||
const consoleSpy = vi.spyOn(console, 'log');
|
||||
|
||||
await updateCommand.execute(testDir);
|
||||
|
||||
const updated = await fs.readFile(codexPath, 'utf-8');
|
||||
expect(updated).toContain('description: Implement an approved OpenSpec change and keep tasks in sync.');
|
||||
expect(updated).toContain('argument-hint: change-id');
|
||||
expect(updated).toContain('$ARGUMENTS');
|
||||
expect(updated).toContain('Work through tasks sequentially');
|
||||
expect(updated).not.toContain('Old body');
|
||||
expect(updated).not.toContain('Old description');
|
||||
|
||||
const [logMessage] = consoleSpy.mock.calls[0];
|
||||
expect(logMessage).toContain(
|
||||
'Updated slash commands: .codex/prompts/openspec-apply.md'
|
||||
);
|
||||
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should not create missing Codex prompts on update', async () => {
|
||||
const codexApply = path.join(
|
||||
testDir,
|
||||
'.codex/prompts/openspec-apply.md'
|
||||
);
|
||||
|
||||
// Only create apply; leave proposal and archive missing
|
||||
await fs.mkdir(path.dirname(codexApply), { recursive: true });
|
||||
await fs.writeFile(
|
||||
codexApply,
|
||||
'---\ndescription: Old\nargument-hint: old\n---\n\n$ARGUMENTS\n<!-- OPENSPEC:START -->\nOld\n<!-- OPENSPEC:END -->'
|
||||
);
|
||||
|
||||
await updateCommand.execute(testDir);
|
||||
|
||||
const codexProposal = path.join(
|
||||
testDir,
|
||||
'.codex/prompts/openspec-proposal.md'
|
||||
);
|
||||
const codexArchive = path.join(
|
||||
testDir,
|
||||
'.codex/prompts/openspec-archive.md'
|
||||
);
|
||||
|
||||
// Confirm they weren't created by update
|
||||
await expect(FileSystemUtils.fileExists(codexProposal)).resolves.toBe(false);
|
||||
await expect(FileSystemUtils.fileExists(codexArchive)).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('should refresh existing GitHub Copilot prompts', async () => {
|
||||
const ghPath = path.join(
|
||||
testDir,
|
||||
'.github/prompts/openspec-apply.prompt.md'
|
||||
);
|
||||
await fs.mkdir(path.dirname(ghPath), { recursive: true });
|
||||
const initialContent = `---
|
||||
description: Implement an approved OpenSpec change and keep tasks in sync.
|
||||
---
|
||||
|
||||
$ARGUMENTS
|
||||
<!-- OPENSPEC:START -->
|
||||
Old body
|
||||
<!-- OPENSPEC:END -->`;
|
||||
await fs.writeFile(ghPath, initialContent);
|
||||
|
||||
const consoleSpy = vi.spyOn(console, 'log');
|
||||
|
||||
await updateCommand.execute(testDir);
|
||||
|
||||
const updated = await fs.readFile(ghPath, 'utf-8');
|
||||
expect(updated).toContain('description: Implement an approved OpenSpec change and keep tasks in sync.');
|
||||
expect(updated).toContain('$ARGUMENTS');
|
||||
expect(updated).toContain('Work through tasks sequentially');
|
||||
expect(updated).not.toContain('Old body');
|
||||
|
||||
const [logMessage] = consoleSpy.mock.calls[0];
|
||||
expect(logMessage).toContain(
|
||||
'Updated slash commands: .github/prompts/openspec-apply.prompt.md'
|
||||
);
|
||||
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should not create missing GitHub Copilot prompts on update', async () => {
|
||||
const ghApply = path.join(
|
||||
testDir,
|
||||
'.github/prompts/openspec-apply.prompt.md'
|
||||
);
|
||||
|
||||
// Only create apply; leave proposal and archive missing
|
||||
await fs.mkdir(path.dirname(ghApply), { recursive: true });
|
||||
await fs.writeFile(
|
||||
ghApply,
|
||||
'---\ndescription: Old\n---\n\n$ARGUMENTS\n<!-- OPENSPEC:START -->\nOld\n<!-- OPENSPEC:END -->'
|
||||
);
|
||||
|
||||
await updateCommand.execute(testDir);
|
||||
|
||||
const ghProposal = path.join(
|
||||
testDir,
|
||||
'.github/prompts/openspec-proposal.prompt.md'
|
||||
);
|
||||
const ghArchive = path.join(
|
||||
testDir,
|
||||
'.github/prompts/openspec-archive.prompt.md'
|
||||
);
|
||||
|
||||
// Confirm they weren't created by update
|
||||
await expect(FileSystemUtils.fileExists(ghProposal)).resolves.toBe(false);
|
||||
await expect(FileSystemUtils.fileExists(ghArchive)).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('should preserve Windsurf content outside markers during update', async () => {
|
||||
const wsPath = path.join(
|
||||
testDir,
|
||||
'.windsurf/workflows/openspec-proposal.md'
|
||||
);
|
||||
await fs.mkdir(path.dirname(wsPath), { recursive: true });
|
||||
const initialContent = `## Custom Intro Title\nSome intro text\n<!-- OPENSPEC:START -->\nOld body\n<!-- OPENSPEC:END -->\n\nFooter stays`;
|
||||
await fs.writeFile(wsPath, initialContent);
|
||||
|
||||
await updateCommand.execute(testDir);
|
||||
|
||||
const updated = await fs.readFile(wsPath, 'utf-8');
|
||||
expect(updated).toContain('## Custom Intro Title');
|
||||
expect(updated).toContain('Footer stays');
|
||||
expect(updated).not.toContain('Old body');
|
||||
expect(updated).toContain('Validate with `openspec validate <id> --strict`');
|
||||
});
|
||||
|
||||
it('should not create missing Windsurf workflows on update', async () => {
|
||||
const wsApply = path.join(
|
||||
testDir,
|
||||
'.windsurf/workflows/openspec-apply.md'
|
||||
);
|
||||
// Only create apply; leave proposal and archive missing
|
||||
await fs.mkdir(path.dirname(wsApply), { recursive: true });
|
||||
await fs.writeFile(
|
||||
wsApply,
|
||||
'<!-- OPENSPEC:START -->\nOld\n<!-- OPENSPEC:END -->'
|
||||
);
|
||||
|
||||
await updateCommand.execute(testDir);
|
||||
|
||||
const wsProposal = path.join(
|
||||
testDir,
|
||||
'.windsurf/workflows/openspec-proposal.md'
|
||||
);
|
||||
const wsArchive = path.join(
|
||||
testDir,
|
||||
'.windsurf/workflows/openspec-archive.md'
|
||||
);
|
||||
|
||||
// Confirm they weren't created by update
|
||||
await expect(FileSystemUtils.fileExists(wsProposal)).resolves.toBe(false);
|
||||
await expect(FileSystemUtils.fileExists(wsArchive)).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('should handle no AI tool files present', async () => {
|
||||
// Execute update command with no AI tool files
|
||||
const consoleSpy = vi.spyOn(console, 'log');
|
||||
@@ -303,7 +535,8 @@ Old content
|
||||
|
||||
const content = await fs.readFile(rootAgentsPath, 'utf-8');
|
||||
expect(content).toContain('<!-- OPENSPEC:START -->');
|
||||
expect(content).toContain('OpenSpec Instructions');
|
||||
expect(content).toContain("@/openspec/AGENTS.md");
|
||||
expect(content).toContain('openspec update');
|
||||
expect(content).toContain('<!-- OPENSPEC:END -->');
|
||||
});
|
||||
|
||||
@@ -319,7 +552,8 @@ Old content
|
||||
const updated = await fs.readFile(rootAgentsPath, 'utf-8');
|
||||
expect(updated).toContain('# Custom intro');
|
||||
expect(updated).toContain('# Footnotes');
|
||||
expect(updated).toContain('OpenSpec Instructions');
|
||||
expect(updated).toContain("@/openspec/AGENTS.md");
|
||||
expect(updated).toContain('openspec update');
|
||||
expect(updated).not.toContain('Old content');
|
||||
|
||||
const [logMessage] = consoleSpy.mock.calls[0];
|
||||
|
||||
@@ -160,4 +160,52 @@ describe('FileSystemUtils', () => {
|
||||
expect(hasPermission).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('joinPath', () => {
|
||||
it('should join POSIX-style paths', () => {
|
||||
const result = FileSystemUtils.joinPath(
|
||||
'/tmp/project',
|
||||
'.claude/commands/openspec/proposal.md'
|
||||
);
|
||||
expect(result).toBe('/tmp/project/.claude/commands/openspec/proposal.md');
|
||||
});
|
||||
|
||||
it('should join Linux home directory paths', () => {
|
||||
const result = FileSystemUtils.joinPath(
|
||||
'/home/dev/workspace/openspec',
|
||||
'.cursor/commands/install.md'
|
||||
);
|
||||
expect(result).toBe('/home/dev/workspace/openspec/.cursor/commands/install.md');
|
||||
});
|
||||
|
||||
it('should join Windows drive-letter paths with backslashes', () => {
|
||||
const result = FileSystemUtils.joinPath(
|
||||
'C:\\Users\\dev\\project',
|
||||
'.claude/commands/openspec/proposal.md'
|
||||
);
|
||||
expect(result).toBe(
|
||||
'C:\\Users\\dev\\project\\.claude\\commands\\openspec\\proposal.md'
|
||||
);
|
||||
});
|
||||
|
||||
it('should join Windows paths that use forward slashes', () => {
|
||||
const result = FileSystemUtils.joinPath(
|
||||
'D:/workspace/app',
|
||||
'.cursor/commands/openspec-apply.md'
|
||||
);
|
||||
expect(result).toBe(
|
||||
'D:\\workspace\\app\\.cursor\\commands\\openspec-apply.md'
|
||||
);
|
||||
});
|
||||
|
||||
it('should join UNC-style Windows paths', () => {
|
||||
const result = FileSystemUtils.joinPath(
|
||||
'\\server\\share\\repo',
|
||||
'.windsurf/workflows/openspec-archive.md'
|
||||
);
|
||||
expect(result).toBe(
|
||||
'\\server\\share\\repo\\.windsurf\\workflows\\openspec-archive.md'
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -248,5 +248,40 @@ Line 5 with gap`;
|
||||
const result = await fs.readFile(filePath, 'utf-8');
|
||||
expect(result).toContain(content);
|
||||
});
|
||||
|
||||
it('should ignore inline mentions of markers when updating content', async () => {
|
||||
const filePath = path.join(testDir, 'inline-mentions.md');
|
||||
const existingFile = `Intro referencing markers like ${START_MARKER} and ${END_MARKER} inside text.
|
||||
|
||||
${START_MARKER}
|
||||
Original content
|
||||
${END_MARKER}
|
||||
`;
|
||||
|
||||
await fs.writeFile(filePath, existingFile);
|
||||
|
||||
await FileSystemUtils.updateFileWithMarkers(
|
||||
filePath,
|
||||
'Updated content',
|
||||
START_MARKER,
|
||||
END_MARKER
|
||||
);
|
||||
|
||||
const firstResult = await fs.readFile(filePath, 'utf-8');
|
||||
expect(firstResult).toContain('Intro referencing markers like');
|
||||
expect(firstResult).toContain('Updated content');
|
||||
expect(firstResult.match(new RegExp(START_MARKER, 'g'))?.length).toBe(2);
|
||||
expect(firstResult.match(new RegExp(END_MARKER, 'g'))?.length).toBe(2);
|
||||
|
||||
await FileSystemUtils.updateFileWithMarkers(
|
||||
filePath,
|
||||
'Updated content',
|
||||
START_MARKER,
|
||||
END_MARKER
|
||||
);
|
||||
|
||||
const secondResult = await fs.readFile(filePath, 'utf-8');
|
||||
expect(secondResult).toBe(firstResult);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user