Compare commits

...
Author SHA1 Message Date
TabishB 7e5054f003 Add CLI path visibility guidance 2026-05-06 04:01:08 +10:00
Tabish Bidiwale f510581b6c Fix Windows workspace path aliases (#1050) 2026-05-05 17:22:23 +00:00
Tabish Bidiwale 7c3acccaf7 [codex] Add workspace setup commands (#1046)
* add workspace setup commands

* Address workspace review comments

* Address completion review nitpicks

* Improve workspace command UX

* Address workspace review comments
2026-05-04 14:06:40 +00:00
Tabish Bidiwale 435458be56 archive workspace foundation (#1045) 2026-05-04 05:32:18 +00:00
JiangWayandClaude Opus 4.7 76c80f80f3 docs: add Community Schemas section + README entry (#1043)
Adds a "Community Schemas" section to docs/customization.md cataloging
community-maintained schema bundles distributed via standalone
repositories. Modeled after github/spec-kit's community extension
catalog (https://github.com/github/spec-kit/tree/main/extensions).

The first entry is `superpowers-bridge` from JiangWay/openspec-schemas
— born from the proposal in PR #970 and now maintained externally.

Also adds a brief 4-line "Community schemas" introductory section in
README.md (between Docs and Why OpenSpec) pointing readers to the
catalog. Documentation only; no code or schema changes.

Refs: #970

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 01:58:25 +00:00
Tabish Bidiwale 0ca74762dc fix windows workspace data dir paths (#1038) 2026-05-01 23:59:20 +00:00
Tabish Bidiwale e6d81ba0f6 [codex] Complete workspace foundation and setup specs (#1029)
* docs: define workspace foundation and setup specs

* Complete workspace foundation

* Document workspace beta status

* Address workspace PR review comments
2026-05-01 17:36:38 +00:00
davseby 2d189ce5e0 fix: make requirement header parsing case-insensitive (#1031)
* fix: make requirement header parsing case-insensitive

* fix: add tests and cover the rest of requirement header places
2026-05-01 15:55:09 +00:00
Tabish Bidiwale 44e4beeee8 fix omz completion compinit setup (#1033) 2026-05-01 15:30:14 +00:00
Tabish Bidiwale a974c67986 docs: clarify Bun install still requires Node (#1032) 2026-05-01 15:29:51 +00:00
Tabish Bidiwale 485c97e97d [codex] Include sync in core workflow defaults (#1030)
* Include sync in core workflow defaults

* Add old core custom profile sync hint

* Update workflows sync default docs
2026-05-01 14:20:28 +00:00
Yousa 347f0277e3 docs: sync tool ID lists with AI_TOOLS source of truth (#1027)
* docs: sync tool ID lists with AI_TOOLS source of truth

Fixes missing tool IDs in docs/cli.md and docs/supported-tools.md that
drifted from src/core/config.ts (AI_TOOLS).

- docs/cli.md: add bob, forgecode, junie, lingma (25 -> 29)
- docs/supported-tools.md: add lingma, align order with config.ts (28 -> 29)

Follow-up to #1003.

* docs: address AICR feedback on tool ID ordering and table entry

Address review comments from Copilot and CodeRabbit on PR #1027:

- docs/cli.md: reorder lingma to match AI_TOOLS position (between qoder and qwen)
- docs/supported-tools.md: same reordering in the --tools list
- docs/supported-tools.md: add missing Lingma row to Tool Directory Reference
  table (inserted alphabetically between Kiro and OpenCode, matching existing
  table convention)

Verified all three documentation surfaces against AI_TOOLS (29 tools):
- cli.md list: order matches src/core/config.ts
- supported-tools.md list: order matches src/core/config.ts
- supported-tools.md table: set equals AI_TOOLS (alphabetical-by-display-name
  order preserved per existing convention).
2026-04-30 13:49:59 +00:00
Tabish Bidiwale cb9641a450 docs: add workspace reimplementation proposal slices (#1025)
* docs: propose workspace reimplementation slices

* docs: add workspace reimplementation roadmap readme

* docs: add workspace poc reference guide

* docs: add workspace reimplementation entrypoint
2026-04-30 11:03:17 +00:00
Yousa 342ed43e69 feat: add Kimi CLI skills-only support (#1003)
* feat: add Kimi CLI skills-only support

* test: relax Kimi adapterless log assertion
2026-04-30 07:38:48 +00:00
101 changed files with 8311 additions and 187 deletions
+2
View File
@@ -0,0 +1,2 @@
---
---
+7
View File
@@ -0,0 +1,7 @@
---
"@fission-ai/openspec": patch
---
### Bug Fixes
- **CLI path visibility**: OpenSpec now documents editor and agent PATH mismatches, warns during global installs when the detected CLI bin directory is not on PATH, and generates workflow skills with guidance for resolving `openspec` through `OPENSPEC_BIN` or an absolute path.
+11
View File
@@ -0,0 +1,11 @@
---
"@fission-ai/openspec": minor
---
### New Features
- **Kimi CLI support** — OpenSpec can now initialize Kimi CLI as a supported skills-only tool using `.kimi/skills/`
### Other
- Added Kimi-specific docs and init coverage aligned with skill-based `/skill:openspec-*` usage
+7
View File
@@ -0,0 +1,7 @@
---
"@fission-ai/openspec": minor
---
### New Features
- Include the sync workflow in the default core profile so new installs generate `/opsx:sync` skills and commands by default.
+8 -1
View File
@@ -96,7 +96,7 @@ openspec init
Now tell your AI: `/opsx:propose <what-you-want-to-build>`
If you want the expanded workflow (`/opsx:new`, `/opsx:continue`, `/opsx:ff`, `/opsx:verify`, `/opsx:sync`, `/opsx:bulk-archive`, `/opsx:onboard`), select it with `openspec config profile` and apply with `openspec update`.
If you want the expanded workflow (`/opsx:new`, `/opsx:continue`, `/opsx:ff`, `/opsx:verify`, `/opsx:bulk-archive`, `/opsx:onboard`), select it with `openspec config profile` and apply with `openspec update`.
> [!NOTE]
> Not sure if your tool is supported? [View the full list](docs/supported-tools.md) – we support 25+ tools and growing.
@@ -115,6 +115,13 @@ If you want the expanded workflow (`/opsx:new`, `/opsx:continue`, `/opsx:ff`, `/
→ **[Customization](docs/customization.md)**: make it yours
## Community schemas
Third-party schema bundles distributed via standalone repositories — these provide opinionated workflows that integrate OpenSpec with other tools, similar to how [github/spec-kit's community extension catalog](https://github.com/github/spec-kit/tree/main/extensions) handles tool integrations.
→ **[Browse the catalog](docs/customization.md#community-schemas)** in the customization docs.
## Why OpenSpec?
AI coding assistants are powerful but unpredictable when requirements live only in chat history. OpenSpec adds a lightweight spec layer so you agree on what to build before any code is written.
+470
View File
@@ -0,0 +1,470 @@
# Workspace Reimplementation Direction
Date: 2026-04-30
Fresh-agent entry point: read `WORKSPACE_REIMPLEMENTATION_START_HERE.md` first, then return to this document for the full product direction.
This document captures the intended direction for reimplementing OpenSpec workspace support from scratch, based on what we learned from the workspace POC.
The reimplementation should be ordered around the path a real user takes through OpenSpec:
```text
set up workspace
-> link repos or folders
-> open workspace
-> explore across repos or folders
-> create proposal
-> apply one repo slice
-> verify
-> archive
```
The goal is not to rebuild every POC mechanism. The goal is to get one user-facing capability working at a time, in the same order a user would naturally create, implement, verify, and archive a change.
## North Star
A user should think:
```text
I have a multi-repo product goal.
I set up an OpenSpec workspace.
I open it with my agent.
The agent can see the linked repos or folders.
We explore until the scope is clear.
Then we create a proposal.
Then we implement one repo slice at a time.
```
They should not think:
```text
I need to create a change so repos become visible.
I need to materialize repo-local artifacts.
I need to understand implementation-specific workspace machinery.
I need to manage target metadata separately from proposal files.
```
The core product rule is:
```text
Workspace visibility is not change commitment.
```
Linked repos or folders are planning context. Creating a change is a planning commitment. Applying a change is an implementation workflow.
## Build Order
### 1. Workspace Setup And Links
First make workspace setup boring and solid.
User goal:
```text
Create a planning home and link the repos or folders OpenSpec should know about.
```
Expected surface:
```bash
openspec workspace setup
openspec workspace setup --no-interactive --name platform --link /path/to/api --link web=/path/to/web
openspec workspace list
openspec workspace ls
openspec workspace link /path/to/api
openspec workspace link api-service /path/to/api
openspec workspace relink api /new/path/to/api
openspec workspace doctor
```
Expected outcome:
```text
workspace-folder/
changes/
.openspec-workspace/
workspace.yaml
local.yaml
```
Product decisions:
- Use `.openspec-workspace/`, not `.openspec/`, for workspace metadata.
- Keep `changes/` visible in the workspace folder.
- Keep setup as the only public creation path for the first release; do not expose `workspace create`.
- Use `workspace link` and `workspace relink`, not POC-era `add-repo` or `update-repo`.
- Allow linked repos or folders without repo-local `openspec/` state.
- Keep stable link names in shared workspace state and local paths in machine-local state.
- Make `doctor` show link names, resolved paths, repo-local specs paths when present, and suggested fixes.
Defer:
- Agent launch and workspace open behavior.
- Preferred-agent prompts.
- Owner or handoff metadata.
- Workspace change creation or target selection.
- Branches.
- Worktrees.
- Apply.
- Archive.
- Complex target lifecycle.
Done when a user can set up a workspace, link repos or folders, list known workspaces, relink local paths, and run `doctor` to see exactly what OpenSpec can resolve.
### 2. Workspace Open
Next make the workspace openable in the way users expect.
User goal:
```text
Open this multi-repo planning context with my coding agent.
```
Expected surface:
```bash
openspec workspace open
openspec workspace open --agent codex
openspec workspace open --agent github-copilot
```
Product behavior:
- `workspace open` opens the coordination workspace plus linked repos or folders.
- Repo visibility is default.
- Change selection is optional focus, not the mechanism for repo access.
- `--agent` should be a one-session override by default. Persisting the preferred agent should require an explicit preference-setting action.
For GitHub Copilot, generate or open a `.code-workspace` file with:
```text
workspace folder
linked repo or folder A
linked repo or folder B
```
For Claude and Codex, attach the linked repo or folder directories through the agent's supported mechanism.
Defer:
- `workspace open --change`.
- In-session upgrade flows.
- Per-change attachment restrictions.
Done when opening a workspace gives the agent visibility into the coordination root and all linked repos or folders.
### 3. Agent Guidance And Explore
Then make exploration work.
User goal:
```text
Tell the agent a rough product goal and have it inspect the repos before creating a proposal.
```
Expected user prompt:
```text
Explore how we should make the OpenSpec docs available on the landing page.
Look across the linked repos or folders, but do not implement yet.
```
Agent behavior:
- Understand it is in workspace mode.
- Inspect linked repos or folders.
- Explain likely affected repos.
- Ask for clarification only when needed.
- Avoid implementation edits during explore.
Build:
- Workspace-level `AGENTS.md` guidance.
- Normal OpenSpec skills and commands in workspace sessions.
- Workspace-specific guidance layered on top of normal `/explore`, not replacing it.
Defer:
- Proposal artifact generation.
- Target confirmation commands.
- Apply context providers.
Done when a user can open a workspace and run a useful cross-repo exploration without creating a dummy change.
### 4. Proposal Creation
Only after explore works, build proposal creation.
User goal:
```text
Now that we understand the scope, capture the plan.
```
Expected user prompt:
```text
Create a proposal for this change.
Target the repos that are actually affected.
```
Preferred artifact shape:
```text
changes/integrate-docs/
proposal.md
design.md
tasks.md
specs/
openspec/
docs-conventions/spec.md
landing/
docs-routing/spec.md
```
Key workflow rule:
```text
/explore may leave targets unknown.
/propose may discover targets.
/propose must confirm targets before saying ready for apply.
```
Targets should be represented by the proposal artifacts themselves where possible. If there is `specs/landing/...`, then `landing` is in scope. Avoid a separate required `targets: [...]` metadata list as the active source of truth.
Defer:
- Repo-local materialization.
- Worktree selection.
- Multi-repo implementation.
- Archive.
Done when a user can explore, then create a workspace proposal with repo-scoped specs and tasks.
### 5. Status
Before implementation, make status excellent.
User goal:
```text
Where are we, what repos are involved, and is this ready to implement?
```
Expected surface:
```bash
openspec status
openspec status --change integrate-docs
```
Human output should answer:
```text
Change: integrate-docs
Scope: openspec, landing
Proposal: present
Design: present
Tasks: present
Ready for apply: yes/no
```
Status should also catch structural mistakes:
- Unknown repo folder under `specs/`.
- Missing tasks.
- No confirmed affected repo.
- Linked repo or folder path missing.
Done when the agent and user can trust status before applying.
### 6. Apply One Repo Slice
Only now build `/apply`.
User goal:
```text
Implement the planned slice for one repo.
```
Expected user prompt:
```text
/apply integrate-docs for landing
```
Product contract:
```text
/apply means implement.
```
It does not mean:
```text
copy planning files
materialize repo-local OpenSpec state
create the proposal files for the first time
```
Agent behavior:
1. Ask OpenSpec for apply context.
2. Read proposal, design, tasks, and relevant specs.
3. Confirm the target repo checkout.
4. Edit only that repo.
5. Update workspace tasks.
6. Run relevant checks.
This likely wants a normalized context command internally, but that is supporting machinery:
```json
{
"mode": "workspace",
"change": "integrate-docs",
"target": "landing",
"implementationRoot": "/repos/openspec-landing",
"contextFiles": [
"changes/integrate-docs/proposal.md",
"changes/integrate-docs/design.md",
"changes/integrate-docs/tasks.md",
"changes/integrate-docs/specs/landing/docs-routing/spec.md"
],
"allowedEditRoots": [
"/repos/openspec-landing"
],
"tasksFile": "changes/integrate-docs/tasks.md"
}
```
Defer:
- Applying multiple repos at once.
- Automatic branch creation.
- Worktree management.
- Repo-local OpenSpec mirroring.
Done when one repo slice can be implemented from the central workspace plan.
### 7. Verify
Then build verification.
User goal:
```text
Check whether the implemented repo slice satisfies the plan.
```
Expected prompt:
```text
/verify integrate-docs for landing
```
Behavior:
- Read the same normalized context as `/apply`.
- Inspect the implementation checkout.
- Check tasks and specs for that repo.
- Run repo validation.
- Report gaps clearly.
Default behavior should verify one repo slice. Whole-workspace verification can come later.
Done when a user can verify one implemented repo slice against the central workspace plan.
### 8. Archive
Archive comes last in the first complete loop.
User goal:
```text
The change is done. Move it out of active planning.
```
Expected prompt:
```text
/archive integrate-docs
```
Behavior:
- Require all targeted repo slices to be complete or explicitly accepted.
- Archive the workspace change.
- Do not require repo-local planning copies unless OpenSpec later decides that repo-local archival matters.
Done when a user can complete the full lifecycle:
```text
workspace setup
-> link repos or folders
-> open
-> explore
-> propose
-> apply repo A
-> apply repo B
-> verify
-> archive
```
## Implementation Discipline
Build only the next user-visible step.
The sequence should stay grounded in these questions:
```text
1. Can I set up the workspace?
2. Can I see my linked repos or folders?
3. Can my agent explore them?
4. Can we capture a proposal?
5. Can status tell us if it is ready?
6. Can the agent implement one repo slice?
7. Can we verify it?
8. Can we archive it?
```
Avoid starting with internal abstractions unless they are required for the next user-visible capability.
Do not start with:
- Target metadata machinery.
- Materialization.
- Adapter abstractions.
- Branch orchestration.
- Worktree orchestration.
- Multi-repo apply.
Those may matter later, but they should not define the first reimplementation path.
## Product Shape
The workspace should feel like OpenSpec's normal workflow stretched across multiple repos, not a second product with its own lifecycle.
The durable product model is:
```text
workspace = durable planning home
links = repos or folders visible for planning
proposal = scoped planning commitment
repo slice = one affected repo or folder in the plan
branch/worktree = implementation checkout
/apply = implement one selected repo slice
```
Keep the user journey simple:
```text
Open the workspace.
Ask the agent to explore.
Create the proposal when scope is clear.
Implement one repo slice at a time.
Verify.
Archive.
```
+67
View File
@@ -0,0 +1,67 @@
# Workspace Reimplementation Start Here
This is the grep-friendly entry point for agents working on the workspace reimplementation.
Useful search terms:
```text
workspace reimplementation
workspace poc
workspace-poc
workspace reference guide
workspace roadmap
fresh agent
start here
```
## Start Here
Read these files in order:
1. `WORKSPACE_REIMPLEMENTATION_DIRECTION.md`
2. `openspec/changes/workspace-reimplementation-roadmap/README.md`
3. `openspec/changes/workspace-reimplementation-roadmap/POC_REFERENCE_GUIDE.md`
4. The proposal for the next implementation slice
The POC reference commit is:
```text
workspace-poc @ 79a45ac043f414e63d13e08b9da83b135cb20a39
```
Use the POC as research material. Do not merge it into an implementation branch. Do not preserve its architecture unless a slice proposal or design explicitly decides to do so.
## Implementation Order
Implement these flat OpenSpec changes in order:
1. `workspace-foundation`
2. `workspace-create-and-register-repos`
3. `workspace-open-agent-context`
4. `workspace-change-planning`
5. `workspace-apply-repo-slice`
6. `workspace-verify-and-archive`
`workspace-reimplementation-roadmap` is the continuity and reference container for the plan.
## Before Editing
For the slice you are about to implement, inspect the pinned POC commit using `POC_REFERENCE_GUIDE.md`, then write down:
```text
POC findings for <slice>:
User behavior to preserve:
- ...
Tests or examples worth translating:
- ...
Implementation shortcuts to avoid:
- ...
Open design questions:
- ...
```
Capture durable findings in the relevant OpenSpec artifact so future sessions do not depend on chat history.
+105 -2
View File
@@ -7,6 +7,7 @@ The OpenSpec CLI (`openspec`) provides terminal commands for project setup, vali
| Category | Commands | Purpose |
|----------|----------|---------|
| **Setup** | `init`, `update` | Initialize and update OpenSpec in your project |
| **Workspaces (beta)** | `workspace setup`, `workspace list`, `workspace ls`, `workspace link`, `workspace relink`, `workspace doctor` | Set up planning across linked repos or folders |
| **Browsing** | `list`, `view`, `show` | Explore changes and specs |
| **Validation** | `validate` | Check changes and specs for issues |
| **Lifecycle** | `archive` | Finalize completed changes |
@@ -46,6 +47,11 @@ These commands support `--json` output for programmatic use by AI agents and scr
| `openspec instructions` | Get next steps | `--json` for agent instructions |
| `openspec templates` | Find template paths | `--json` for path resolution |
| `openspec schemas` | List available schemas | `--json` for schema discovery |
| `openspec workspace setup --no-interactive` | Create a workspace with explicit inputs | `--json` for structured setup output |
| `openspec workspace list` | Browse known workspaces | `--json` for typed workspace objects |
| `openspec workspace link` | Link a repo or folder | `--json` for structured link output |
| `openspec workspace relink` | Repair a linked path | `--json` for structured link output |
| `openspec workspace doctor` | Check one workspace | `--json` for structured status output |
---
@@ -67,7 +73,7 @@ These options work with all commands:
Initialize OpenSpec in your project. Creates the folder structure and configures AI tool integrations.
Default behavior uses global config defaults: profile `core`, delivery `both`, workflows `propose, explore, apply, archive`.
Default behavior uses global config defaults: profile `core`, delivery `both`, workflows `propose, explore, apply, sync, archive`.
```
openspec init [path] [options]
@@ -89,7 +95,7 @@ openspec init [path] [options]
`--profile custom` uses whatever workflows are currently selected in global config (`openspec config profile`).
**Supported tool IDs (`--tools`):** `amazon-q`, `antigravity`, `auggie`, `claude`, `cline`, `codex`, `codebuddy`, `continue`, `costrict`, `crush`, `cursor`, `factory`, `gemini`, `github-copilot`, `iflow`, `kilocode`, `kiro`, `opencode`, `pi`, `qoder`, `qwen`, `roocode`, `trae`, `windsurf`
**Supported tool IDs (`--tools`):** `amazon-q`, `antigravity`, `auggie`, `bob`, `claude`, `cline`, `codex`, `forgecode`, `codebuddy`, `continue`, `costrict`, `crush`, `cursor`, `factory`, `gemini`, `github-copilot`, `iflow`, `junie`, `kilocode`, `kimi`, `kiro`, `opencode`, `pi`, `qoder`, `lingma`, `qwen`, `roocode`, `trae`, `windsurf`
**Examples:**
@@ -159,6 +165,103 @@ openspec update
---
## Workspace Commands
Workspace commands are under active development and are not ready for use yet. Do not build external automation, integrations, or long-lived workflows on top of this command surface; command behavior, state files, and JSON output can change at any point.
Coordination workspaces are planning homes for work that spans multiple repos or folders. Workspace visibility is not change commitment: link the repos or folders OpenSpec should know about, then create changes when you are ready to plan specific work.
### `openspec workspace setup`
Create a workspace in the standard OpenSpec workspace location and link at least one existing repo or folder.
```bash
openspec workspace setup [options]
```
**Options:**
| Option | Description |
|--------|-------------|
| `--name <name>` | Workspace name. Names must be kebab-case |
| `--link <path>` | Link an existing repo or folder and infer the link name from the folder name |
| `--link <name>=<path>` | Link an existing repo or folder with an explicit link name |
| `--no-interactive` | Disable prompts; requires `--name` and at least one `--link` |
| `--json` | Output JSON; requires `--no-interactive` |
**Examples:**
```bash
openspec workspace setup
openspec workspace setup --no-interactive --name platform --link /repos/api --link web=/repos/web
openspec workspace setup --no-interactive --json --name checkout --link /repos/platform/apps/checkout
```
Setup prints the workspace location, planning path, linked repos or folders, and a workspace check. It does not ask for a preferred agent or open the workspace.
### `openspec workspace list`
List known OpenSpec workspaces from the local registry.
```bash
openspec workspace list [--json]
openspec workspace ls [--json]
```
The list shows each workspace location and linked repos or folders. Stale registry records are reported but not changed.
### `openspec workspace link`
Record an existing repo or folder for one workspace.
```bash
openspec workspace link [name] <path> [options]
```
**Options:**
| Option | Description |
|--------|-------------|
| `--workspace <name>` | Select a known workspace from the local registry |
| `--json` | Output JSON |
| `--no-interactive` | Disable workspace picker prompts |
**Examples:**
```bash
openspec workspace link /repos/api
openspec workspace link api-service /repos/api
openspec workspace link --workspace platform /repos/platform/apps/checkout
```
The path must already exist. Relative paths are resolved against the command's current directory before OpenSpec stores the verified absolute path in machine-local workspace state. Linked paths can be full repos, packages, services, apps, or folders without repo-local `openspec/` state.
### `openspec workspace relink`
Repair or change the local path for an existing link.
```bash
openspec workspace relink <name> <path> [options]
```
The path must already exist. Relink updates only the machine-local path for the stable link name.
### `openspec workspace doctor`
Check what one workspace can resolve on the current machine.
```bash
openspec workspace doctor [options]
```
Doctor shows the workspace location, planning path, linked repos or folders, missing paths, repo-local specs paths when present, and suggested fixes. It reports issues only; it does not repair them automatically.
Commands that need one workspace use the current workspace when run from inside a workspace folder or subdirectory. From elsewhere, pass `--workspace <name>`, select from the picker in an interactive terminal, or rely on the only known workspace when exactly one exists. In `--json` or `--no-interactive` mode, ambiguous selection fails with a structured status error and suggests `--workspace <name>`.
JSON responses use typed objects plus `status` arrays. Primary data lives in `workspace`, `workspaces`, or `link`; warnings and errors live in `status`.
---
## Browsing Commands
### `openspec list`
+2 -1
View File
@@ -13,6 +13,7 @@ For workflow patterns and when to use each command, see [Workflows](workflows.md
| `/opsx:propose` | Create a change and generate planning artifacts in one step |
| `/opsx:explore` | Think through ideas before committing to a change |
| `/opsx:apply` | Implement tasks from the change |
| `/opsx:sync` | Merge delta specs into main specs |
| `/opsx:archive` | Archive a completed change |
### Expanded Workflow Commands (custom workflow selection)
@@ -23,7 +24,6 @@ For workflow patterns and when to use each command, see [Workflows](workflows.md
| `/opsx:continue` | Create the next artifact based on dependencies |
| `/opsx:ff` | Fast-forward: create all planning artifacts at once |
| `/opsx:verify` | Validate implementation matches artifacts |
| `/opsx:sync` | Merge delta specs into main specs |
| `/opsx:bulk-archive` | Archive multiple changes at once |
| `/opsx:onboard` | Guided tutorial through the complete workflow |
@@ -618,6 +618,7 @@ Different AI tools use slightly different command syntax. Use the format that ma
| Cursor | `/opsx-propose`, `/opsx-apply` |
| Windsurf | `/opsx-propose`, `/opsx-apply` |
| Copilot (IDE) | `/opsx-propose`, `/opsx-apply` |
| Kimi CLI | Skill-based invocations such as `/skill:openspec-propose`, `/skill:openspec-apply-change` (no generated `opsx-*` command files) |
| Trae | Skill-based invocations such as `/openspec-propose`, `/openspec-apply-change` (no generated `opsx-*` command files) |
The intent is the same across tools, but how commands are surfaced can differ by integration.
+117
View File
@@ -49,6 +49,123 @@ OpenSpec organizes your work into two main areas:
This separation is key. You can work on multiple changes in parallel without conflicts. You can review a change before it affects the main specs. And when you archive a change, its deltas merge cleanly into the source of truth.
## Coordination Workspaces
Workspace support is under active development and is not ready for use yet. Do not build external automation, integrations, or long-lived workflows on top of workspace behavior; the commands, state files, and JSON output can change at any point.
The commands below provide the first setup flow for planning across linked repos or folders.
Repo-local OpenSpec projects are the right default when one repo owns the planning, implementation, and archive flow. Some work spans several repos or folders. For that case, an OpenSpec coordination workspace is the durable planning home.
The workspace mental model is:
```text
workspace = where related cross-repo changes live
link = a stable name for a repo or folder the workspace can plan against
change = one feature, fix, project, or other planned piece of work
```
A workspace has a different shape from a repo-local project:
```text
workspace-folder/
├── changes/ # Workspace-level planning
└── .openspec-workspace/
├── workspace.yaml # Shared workspace identity and link names
└── local.yaml # This machine's local paths
```
Repo-local OpenSpec state keeps the existing shape:
```text
repo-root/
└── openspec/
├── specs/
└── changes/
```
That distinction matters. The workspace folder is a coordination surface for planning across linked repos or folders. Each repo's `openspec/` directory remains the home for repo-owned specs, repo-local changes, and implementation planning. Users do not need to run repo-local `openspec init` inside a workspace folder.
Stable link names are how workspace planning refers to repos and folders. The shared workspace state keeps names such as `api`, `web`, or `checkout`; each machine maps those names to its own local paths in `.openspec-workspace/local.yaml`.
```yaml
# .openspec-workspace/workspace.yaml
version: 1
name: platform
links:
api: {}
web: {}
```
```yaml
# .openspec-workspace/local.yaml
version: 1
paths:
api: /repos/api
web: /repos/web
```
OpenSpec-created workspaces exclude `.openspec-workspace/local.yaml` from portable collaboration state by default. `.openspec-workspace/workspace.yaml` remains portable because it stores the workspace name and stable link names, not one user's absolute checkout paths.
Linked paths can be full repos, folders inside a large monorepo, or other existing folders. They do not need repo-local `openspec/` state before they can participate in workspace planning. Later implementation, verify, or archive workflows may require more repo readiness, but planning visibility starts with the link.
```text
multi-repo:
api -> /repos/api
web -> /repos/web
large monorepo:
billing -> /repos/platform/services/billing
checkout -> /repos/platform/apps/checkout
```
Managed workspaces live under the standard OpenSpec data directory:
```text
getGlobalDataDir()/workspaces
```
That means `$XDG_DATA_HOME/openspec/workspaces` when `XDG_DATA_HOME` is set, `~/.local/share/openspec/workspaces` on Unix-style fallback, and `%LOCALAPPDATA%\openspec\workspaces` on native Windows fallback. Native Windows shells, PowerShell, and WSL2 each keep the path strings for the runtime running OpenSpec. This foundation does not translate between `D:\repo`, `/mnt/d/repo`, and UNC WSL paths.
OpenSpec also keeps a machine-local registry at:
```text
getGlobalDataDir()/workspaces/registry.yaml
```
The registry maps workspace names to workspace locations so later global commands can list or select known workspaces from anywhere. It is only an index. Each workspace folder remains authoritative for its own `.openspec-workspace/workspace.yaml` and `.openspec-workspace/local.yaml`, so stale registry records can be reported and repaired without redefining the workspace itself.
Workspace visibility is not change commitment. Set up a workspace when OpenSpec should know which repos or folders are relevant; create a change later when you are ready to plan a feature, fix, project, or other piece of work.
Useful commands:
```bash
# Guided setup
openspec workspace setup
# Automation-friendly setup
openspec workspace setup --no-interactive --name platform --link /repos/api --link web=/repos/web
# See known workspaces from the local registry
openspec workspace list
openspec workspace ls
# Add or repair links for the selected workspace
openspec workspace link /repos/api
openspec workspace link api-service /repos/api
openspec workspace relink api-service /new/path/to/api
# Check what this machine can resolve
openspec workspace doctor
openspec workspace doctor --workspace platform
```
`workspace setup` always creates the workspace in the standard workspace location, records it in the local registry, shows the workspace location, and requires at least one linked repo or folder. `workspace link` and `workspace relink` record existing folders only; they do not create, copy, move, initialize, or edit the linked repo or folder.
Workspace commands that need one workspace can run from anywhere with `--workspace <name>`. If you run them inside a workspace folder or subdirectory, OpenSpec uses that current workspace. If several known workspaces are available and you do not pass `--workspace <name>`, human commands show a picker; `--json` and `--no-interactive` fail with a structured status error instead of prompting.
Direct workspace commands support JSON output for scripts. JSON responses keep primary data in `workspace`, `workspaces`, or `link` objects and report warnings or errors in `status` arrays. Healthy objects use `status: []`.
## Specs
Specs describe your system's behavior using structured requirements and scenarios.
+14
View File
@@ -337,6 +337,20 @@ Then edit `schema.yaml` to add:
---
## Community Schemas
OpenSpec also supports community-maintained schemas distributed via standalone repositories. These provide opinionated workflows that integrate OpenSpec with other tools or systems, similar to how [github/spec-kit's community extension catalog](https://github.com/github/spec-kit/tree/main/extensions) works for spec-kit.
Community schemas are not vendored into OpenSpec core — they live in their own repositories with their own release cadence. To use one, copy the schema bundle into your project's `openspec/schemas/<schema-name>/` directory (each repo's README has install instructions).
| Schema | Maintainer | Repository | Description |
|--------|-----------|-----------|-------------|
| `superpowers-bridge` | @JiangWay | [JiangWay/openspec-schemas](https://github.com/JiangWay/openspec-schemas/tree/main/superpowers-bridge) | Integrates OpenSpec's artifact governance with [obra/superpowers](https://github.com/obra/superpowers) execution skills (brainstorming, writing-plans, TDD via subagents, code review, finishing). Adds an evidence-first `retrospective` artifact filling a gap Superpowers does not natively cover. |
> Want to contribute a community schema? Open an issue with a link to your repository, or submit a PR adding a row to this table.
---
## See Also
- [CLI Reference: Schema Commands](cli.md#schema-commands) - Full command documentation
+2 -2
View File
@@ -9,7 +9,7 @@ OpenSpec helps you and your AI coding assistant agree on what to build before an
**Default quick path (core profile):**
```text
/opsx:propose ──► /opsx:apply ──► /opsx:archive
/opsx:propose ──► /opsx:apply ──► /opsx:sync ──► /opsx:archive
```
**Expanded path (custom workflow selection):**
@@ -18,7 +18,7 @@ OpenSpec helps you and your AI coding assistant agree on what to build before an
/opsx:new ──► /opsx:ff or /opsx:continue ──► /opsx:apply ──► /opsx:verify ──► /opsx:archive
```
The default global profile is `core`, which includes `propose`, `explore`, `apply`, and `archive`. You can enable the expanded workflow commands with `openspec config profile` and then `openspec update`.
The default global profile is `core`, which includes `propose`, `explore`, `apply`, `sync`, and `archive`. You can enable the expanded workflow commands with `openspec config profile` and then `openspec update`.
## What OpenSpec Creates
+41
View File
@@ -26,6 +26,9 @@ yarn global add @fission-ai/openspec@latest
### bun
Bun can install OpenSpec globally, but OpenSpec currently runs on Node.js.
You still need Node.js 20.19.0 or higher available on `PATH`.
```bash
bun add -g @fission-ai/openspec@latest
```
@@ -67,6 +70,44 @@ Or add to your development environment in `flake.nix`:
openspec --version
```
## Troubleshooting PATH Visibility
If `openspec --version` works in one terminal but fails in an editor, AI agent,
GUI app, or automation, OpenSpec is usually installed correctly but that process
started with a different `PATH`.
Global package managers create an executable shim in a bin directory, then your
shell or launcher must put that directory on `PATH`. Common ways to inspect the
directory are:
```bash
# npm
printf '%s/bin\n' "$(npm prefix -g)"
# pnpm
pnpm bin -g
# bun
bun pm bin -g
# current shell
command -v openspec
```
Make sure the environment that launches your editor, agent, GUI app, or
automation includes the package-manager bin directory. For shell startup files,
keep this to a minimal `PATH` export in a file that the target environment
actually reads. Do not move interactive setup such as prompts, themes,
completions, or commands that can block into always-loaded startup files.
To bypass global bin discovery while debugging, run OpenSpec through a package
manager:
```bash
npx -y @fission-ai/openspec@latest --version
pnpm dlx @fission-ai/openspec@latest --version
```
## Next Steps
After installing, initialize OpenSpec in your project:
+3 -2
View File
@@ -8,7 +8,7 @@ OPSX replaces the old phase-locked workflow with a fluid, action-based approach.
| Aspect | Legacy | OPSX |
|--------|--------|------|
| **Commands** | `/openspec:proposal`, `/openspec:apply`, `/openspec:archive` | Default: `/opsx:propose`, `/opsx:apply`, `/opsx:archive` (expanded workflow commands optional) |
| **Commands** | `/openspec:proposal`, `/openspec:apply`, `/openspec:archive` | Default: `/opsx:propose`, `/opsx:apply`, `/opsx:sync`, `/opsx:archive` (expanded workflow commands optional) |
| **Workflow** | Create all artifacts at once | Create incrementally or all at once—your choice |
| **Going back** | Awkward phase gates | Natural—update any artifact anytime |
| **Customization** | Fixed structure | Schema-driven, fully hackable |
@@ -84,7 +84,7 @@ Don't worry about getting it perfect. We're still learning what works best here,
Both `openspec init` and `openspec update` detect legacy files and guide you through the same cleanup process. Use whichever fits your situation:
- New installs default to profile `core` (`propose`, `explore`, `apply`, `archive`).
- New installs default to profile `core` (`propose`, `explore`, `apply`, `sync`, `archive`).
- Migrated installs preserve your previously installed workflows by writing a `custom` profile when needed.
### Using `openspec init`
@@ -561,6 +561,7 @@ project/
│ ├── openspec-propose/ # default core profile
│ ├── openspec-explore/
│ ├── openspec-apply-change/
│ ├── openspec-sync-specs/
│ └── ... # expanded profile adds new/continue/ff/etc.
├── CLAUDE.md # OpenSpec markers removed, your content preserved
└── AGENTS.md # OpenSpec markers removed, your content preserved
+3 -3
View File
@@ -65,7 +65,7 @@ openspec init
This creates skills in `.claude/skills/` (or equivalent) that AI coding assistants auto-detect.
By default, OpenSpec uses the `core` workflow profile (`propose`, `explore`, `apply`, `archive`). If you want the expanded workflow commands (`new`, `continue`, `ff`, `verify`, `sync`, `bulk-archive`, `onboard`), configure them with `openspec config profile` and apply with `openspec update`.
By default, OpenSpec uses the `core` workflow profile (`propose`, `explore`, `apply`, `sync`, `archive`). If you want the expanded workflow commands (`new`, `continue`, `ff`, `verify`, `bulk-archive`, `onboard`), configure them with `openspec config profile` and apply with `openspec update`.
During setup, you'll be prompted to create a **project config** (`openspec/config.yaml`). This is optional but recommended.
@@ -164,7 +164,7 @@ rules:
| `/opsx:ff` | Fast-forward planning artifacts (expanded workflow) |
| `/opsx:apply` | Implement tasks, updating artifacts as needed |
| `/opsx:verify` | Validate implementation against artifacts (expanded workflow) |
| `/opsx:sync` | Sync delta specs to main (expanded workflow, optional) |
| `/opsx:sync` | Sync delta specs to main (default workflow, optional) |
| `/opsx:archive` | Archive when done |
| `/opsx:bulk-archive` | Archive multiple completed changes (expanded workflow) |
| `/opsx:onboard` | Guided walkthrough of an end-to-end change (expanded workflow) |
@@ -313,7 +313,7 @@ Think of it like git branches:
## Architecture Deep Dive
This section explains how OPSX works under the hood and how it compares to the legacy workflow.
Examples in this section use the expanded command set (`new`, `continue`, etc.); default `core` users can map the same flow to `propose → apply → archive`.
Examples in this section use the expanded command set (`new`, `continue`, etc.); default `core` users can map the same flow to `propose → apply → sync → archive`.
### Philosophy: Phases vs Actions
+6 -3
View File
@@ -13,9 +13,10 @@ By default, OpenSpec uses the `core` profile, which includes:
- `propose`
- `explore`
- `apply`
- `sync`
- `archive`
You can enable expanded workflows (`new`, `continue`, `ff`, `verify`, `sync`, `bulk-archive`, `onboard`) via `openspec config profile`, then run `openspec update`.
You can enable expanded workflows (`new`, `continue`, `ff`, `verify`, `bulk-archive`, `onboard`) via `openspec config profile`, then run `openspec update`.
## Tool Directory Reference
@@ -40,7 +41,9 @@ You can enable expanded workflows (`new`, `continue`, `ff`, `verify`, `sync`, `b
| iFlow (`iflow`) | `.iflow/skills/openspec-*/SKILL.md` | `.iflow/commands/opsx-<id>.md` |
| Junie (`junie`) | `.junie/skills/openspec-*/SKILL.md` | `.junie/commands/opsx-<id>.md` |
| Kilo Code (`kilocode`) | `.kilocode/skills/openspec-*/SKILL.md` | `.kilocode/workflows/opsx-<id>.md` |
| Kimi CLI (`kimi`) | `.kimi/skills/openspec-*/SKILL.md` | Not generated (no command adapter; use skill-based `/skill:openspec-*` invocations) |
| Kiro (`kiro`) | `.kiro/skills/openspec-*/SKILL.md` | `.kiro/prompts/opsx-<id>.prompt.md` |
| Lingma (`lingma`) | `.lingma/skills/openspec-*/SKILL.md` | `.lingma/commands/opsx/<id>.md` |
| OpenCode (`opencode`) | `.opencode/skills/openspec-*/SKILL.md` | `.opencode/commands/opsx-<id>.md` |
| Pi (`pi`) | `.pi/skills/openspec-*/SKILL.md` | `.pi/prompts/opsx-<id>.md` |
| Qoder (`qoder`) | `.qoder/skills/openspec-*/SKILL.md` | `.qoder/commands/opsx/<id>.md` |
@@ -71,13 +74,13 @@ openspec init --tools none
openspec init --profile core
```
**Available tool IDs (`--tools`):** `amazon-q`, `antigravity`, `auggie`, `bob`, `claude`, `cline`, `codex`, `codebuddy`, `continue`, `costrict`, `crush`, `cursor`, `factory`, `forgecode`, `gemini`, `github-copilot`, `iflow`, `junie`, `kilocode`, `kiro`, `opencode`, `pi`, `qoder`, `qwen`, `roocode`, `trae`, `windsurf`
**Available tool IDs (`--tools`):** `amazon-q`, `antigravity`, `auggie`, `bob`, `claude`, `cline`, `codex`, `forgecode`, `codebuddy`, `continue`, `costrict`, `crush`, `cursor`, `factory`, `gemini`, `github-copilot`, `iflow`, `junie`, `kilocode`, `kimi`, `kiro`, `opencode`, `pi`, `qoder`, `lingma`, `qwen`, `roocode`, `trae`, `windsurf`
## Workflow-Dependent Installation
OpenSpec installs workflow artifacts based on selected workflows:
- **Core profile (default):** `propose`, `explore`, `apply`, `archive`
- **Core profile (default):** `propose`, `explore`, `apply`, `sync`, `archive`
- **Custom selection:** any subset of all workflow IDs:
`propose`, `explore`, `new`, `continue`, `apply`, `ff`, `sync`, `archive`, `bulk-archive`, `verify`, `onboard`
+3 -2
View File
@@ -36,17 +36,18 @@ New installs default to `core`, which provides:
- `/opsx:propose`
- `/opsx:explore`
- `/opsx:apply`
- `/opsx:sync`
- `/opsx:archive`
Typical flow:
```text
/opsx:propose ──► /opsx:apply ──► /opsx:archive
/opsx:propose ──► /opsx:apply ──► /opsx:sync ──► /opsx:archive
```
### Expanded/Full Workflow (custom selection)
If you want explicit scaffold-and-build commands (`/opsx:new`, `/opsx:continue`, `/opsx:ff`, `/opsx:verify`, `/opsx:sync`, `/opsx:bulk-archive`, `/opsx:onboard`), enable them with:
If you want explicit scaffold-and-build commands (`/opsx:new`, `/opsx:continue`, `/opsx:ff`, `/opsx:verify`, `/opsx:bulk-archive`, `/opsx:onboard`), enable them with:
```bash
openspec config profile
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-04-23
@@ -0,0 +1,3 @@
# add-kimi-cli-skills-only-support
Add Kimi CLI as a supported skills-only tool without a command adapter
@@ -0,0 +1,85 @@
## Context
Kimi CLI is not another Claude/Codex-style adapter target. Its extension model is built around discovered skills, not external command files:
- skills are discovered from `.kimi/skills/`
- skills are exposed as `/skill:<name>`
- no stable `.kimi/commands/` or prompt-file loading mechanism was found in the Kimi CLI codebase
OpenSpec's existing architecture can already represent that shape:
- `AI_TOOLS` can advertise a `skillsDir`
- `init` can install skills for any selected tool with `skillsDir`
- when command generation is attempted for a tool without an adapter, OpenSpec already records `commandsSkipped`
## Goals
- Add Kimi CLI using the same narrow `skills-only` pattern already used by Trae
- Keep the implementation small: metadata, docs, and a focused regression test
- Make the spec text match the current code path for adapterless tools
## Non-Goals
- designing a Kimi-specific command adapter without upstream support
- changing tool capability modeling across the whole generation pipeline
- reworking `delivery=commands` behavior for all adapterless tools
## Decisions
### 1. Represent Kimi CLI as an adapterless tool with `.kimi`
Add a new `AI_TOOLS` entry:
```ts
{ name: 'Kimi CLI', value: 'kimi', available: true, successLabel: 'Kimi CLI', skillsDir: '.kimi' }
```
This matches Kimi CLI's project-local skills root and lets existing init/update detection paths treat it as a supported tool.
### 2. Do not add a Kimi command adapter
No `src/core/command-generation/adapters/kimi.ts` file will be added, and the command adapter registry will remain unchanged.
Rationale:
- Kimi CLI exposes skills dynamically as `/skill:<name>`
- the previous upstream PR stalled specifically because no legitimate adapter target was available
- adding a fake `.kimi/commands/...` path would create behavior OpenSpec cannot justify against upstream Kimi CLI behavior
### 3. Document Kimi by its real invocation surface
Kimi documentation in OpenSpec must use Kimi's actual skill invocation form:
- supported-tools: no generated command files, use `/skill:openspec-*`
- commands doc: examples such as `/skill:openspec-propose`
The docs must not claim generated `opsx-*` files or `/openspec-*` direct invocations for Kimi.
### 4. Keep the change compatible with existing Trae-style behavior
This change intentionally follows the current adapterless-tool behavior already present in the codebase:
- skills are created whenever delivery includes skills
- command generation is skipped when no adapter exists
- init output reports `Commands skipped for: kimi (no adapter)`
This keeps the Kimi change small and avoids overlapping implementation work already captured in `add-tool-command-surface-capabilities`.
## Test Strategy
Add one focused regression test in `test/core/init.test.ts`:
- configure `delivery=both`
- run init with `--tools kimi`
- verify Kimi skills are created under `.kimi/skills/...`
- verify init reports the skipped command generation path for `kimi`
That test is enough for this narrow change because:
- adapterless update behavior already has generic coverage
- CLI tool-id rendering is derived from `AI_TOOLS`
- no command adapter or path formatting logic is being introduced
## Risks / Trade-offs
The main trade-off is scope: Kimi will inherit the current adapterless-tool behavior, including the broader limitation that `delivery=commands` is not yet capability-aware for skills-invocable tools. That is acceptable for this change because it matches the existing Trae/ForgeCode model and keeps the implementation aligned with verified Kimi CLI behavior.
@@ -0,0 +1,38 @@
## Why
OpenSpec already has user demand for Kimi CLI support, but the previous upstream attempt stalled because it assumed Kimi needed a command adapter. Local review of the Kimi CLI codebase shows a different integration surface: Kimi discovers `SKILL.md` files from `.kimi/skills/` and exposes them through `/skill:<name>`, but it does not provide a stable, file-based custom command directory like Claude Code or Codex.
OpenSpec already supports tools that install skills without a command adapter. Trae and ForgeCode are the existing examples. Kimi should follow the same pattern instead of introducing undocumented `.kimi/commands/...` behavior.
## What Changes
- Add Kimi CLI as a supported tool in `AI_TOOLS` with `skillsDir: '.kimi'`
- Document Kimi CLI as a skills-only integration in supported tools and command usage docs
- Align change specs so `cli-init` explicitly allows selected tools with `skillsDir` but no registered command adapter
## Capabilities
### New Capabilities
_None._
### Modified Capabilities
- `ai-tool-paths`: define the `.kimi` skills root for Kimi CLI
- `cli-init`: clarify that adapterless tools remain valid selections and skip command-file generation with an informational message
## Impact
- `src/core/config.ts` - add Kimi CLI tool metadata
- `docs/supported-tools.md` - add Kimi CLI row and tool id
- `docs/commands.md` - document `/skill:openspec-*` usage for Kimi CLI
- `docs/cli.md` - include `kimi` in the supported `--tools` list
- `test/core/init.test.ts` - cover Kimi CLI as an adapterless tool during init
## Non-Goals
- Adding `src/core/command-generation/adapters/kimi.ts`
- Defining a `.kimi/commands/...` output path
- Changing the broader delivery model for adapterless tools under `delivery=commands`
That broader capability-aware delivery work is already being explored separately in `add-tool-command-surface-capabilities`. This change stays narrow and follows the existing Trae/ForgeCode pattern.
@@ -0,0 +1,12 @@
# ai-tool-paths Delta Specification
## MODIFIED Requirements
### Requirement: Path configuration for supported tools
The `AI_TOOLS` array SHALL include `skillsDir` for tools that support the Agent Skills specification.
#### Scenario: Kimi CLI paths defined
- **WHEN** looking up the `kimi` tool
- **THEN** `skillsDir` SHALL be `.kimi`
@@ -0,0 +1,37 @@
# cli-init Delta Specification
## MODIFIED Requirements
### Requirement: Slash Command Generation
The command SHALL generate opsx slash commands only for selected tools that have a registered command adapter, while keeping adapterless tools valid for skill generation.
#### Scenario: Generating slash commands for a tool with a registered adapter
- **WHEN** a tool with a registered command adapter is selected during initialization
- **THEN** create 9 slash command files using the tool's command adapter:
- `/opsx:explore`
- `/opsx:new`
- `/opsx:continue`
- `/opsx:apply`
- `/opsx:ff`
- `/opsx:verify`
- `/opsx:sync`
- `/opsx:archive`
- `/opsx:bulk-archive`
- **AND** use tool-specific path conventions (e.g., `.claude/commands/opsx/` for Claude)
- **AND** include tool-specific frontmatter format
#### Scenario: Selected tool has no command adapter
- **GIVEN** a selected tool has `skillsDir` configured but no registered command adapter
- **WHEN** initialization includes command generation
- **THEN** skill generation for that tool SHALL still remain valid
- **AND** command-file generation SHALL be skipped for that tool
- **AND** the command output SHALL include `Commands skipped for: <tool-id> (no adapter)`
#### Scenario: Kimi CLI skips command-file generation
- **WHEN** the user selects Kimi CLI during initialization
- **THEN** OpenSpec SHALL treat it as a supported tool with `skillsDir: '.kimi'`
- **AND** command-file generation SHALL be skipped because no Kimi adapter is registered
@@ -0,0 +1,22 @@
## 1. Change Artifacts
- [x] 1.1 Write proposal, design, and spec deltas for Kimi CLI skills-only support
## 2. Tool Metadata
- [x] 2.1 Add `Kimi CLI` to `src/core/config.ts` with `value: 'kimi'` and `skillsDir: '.kimi'`
## 3. Documentation
- [x] 3.1 Update `docs/supported-tools.md` with a Kimi CLI row that clearly states there is no command adapter
- [x] 3.2 Update `docs/commands.md` to document Kimi CLI usage via `/skill:openspec-*`
- [x] 3.3 Update `docs/cli.md` so the supported `--tools` list includes `kimi`
## 4. Tests
- [x] 4.1 Add a targeted init regression test for `--tools kimi` under adapterless command generation
## 5. Validation
- [x] 5.1 Validate the change artifacts with `openspec validate`
- [x] 5.2 Run targeted tests and fix any regressions
@@ -0,0 +1,208 @@
## Product Model
An OpenSpec workspace is the durable planning home for work that spans multiple repos or folders.
It should feel like this:
```text
workspace = where related changes live
link = a named repo or folder the workspace can plan against
change = one feature, fix, project, or other planned piece of work
```
The foundation intentionally avoids the rest of the workflow. It only defines how OpenSpec recognizes a workspace, where managed workspaces live, how linked paths are represented, and how shared state differs from local state.
A workspace is not a feature. It can hold many changes over time. The linked repos or folders provide planning context, while the code stays where it is.
## Workspace Shape
OpenSpec workspaces use this shape:
```text
workspace-root/
changes/ # workspace-level proposals, tasks, specs
.openspec-workspace/
workspace.yaml # shared workspace information
local.yaml # this machine's paths and preferences
```
The user-facing planning surface is `changes/`. The identity file that makes the directory a workspace is `.openspec-workspace/workspace.yaml`.
Repo-local projects keep the existing shape:
```text
repo-root/
openspec/
specs/
changes/
```
That distinction lets a user or agent tell which surface they are working in:
```text
coordination workspace -> shared cross-repo planning
repo-local project -> repo-owned specs and implementation planning
```
Users should not run repo-local `openspec init` inside the workspace root. A workspace is already an OpenSpec coordination surface; it is not a product repo adopting repo-local OpenSpec.
## Workspace Names
A workspace name is a simple folder-style identifier, not a display name.
The name must be usable as a folder name in the current runtime. It must not be empty, must not be `.` or `..`, and must not contain path separators.
OpenSpec should not maintain a cross-platform reserved-name list in this slice. Setup/create flows should let filesystem creation surface OS-specific invalid folder names, then report that failure clearly.
The same workspace name is stored in `.openspec-workspace/workspace.yaml`, used as the default managed workspace folder name, and used as the local registry name.
## Shared And Local State
Workspace state follows a simple sharing rule:
```text
share stable link names and planning
keep local checkout paths local
```
Expected shared state:
```yaml
version: 1
name: platform
links:
api: {}
web: {}
```
Expected local state:
```yaml
version: 1
paths:
api: /repos/api
web: /repos/web
```
Later slices can expand these shapes, but the product rule should stay stable: a shared workspace should not commit one user's absolute checkout paths.
OpenSpec-created workspaces should include an ignore rule for `.openspec-workspace/local.yaml` so local checkout paths are not accidentally shared. `.openspec-workspace/workspace.yaml` remains the portable workspace identity and link-name state.
## Workspace Location
OpenSpec should create managed workspaces in one standard place:
```text
getGlobalDataDir()/workspaces
```
That reuses existing OpenSpec data-directory behavior:
- `$XDG_DATA_HOME/openspec/workspaces` when `XDG_DATA_HOME` is set
- `~/.local/share/openspec/workspaces` on Unix/macOS fallback
- `%LOCALAPPDATA%\openspec\workspaces` on native Windows fallback
This slice intentionally does not define a workspace-specific environment-variable, command, or configuration override for managed workspace storage. Tests should rely on existing global data-directory controls and test helpers instead of a separate workspace-home override.
This is deliberately quiet. The product should not ask most users where workspaces should live.
OpenSpec should show the resolved workspace path after setup. Quiet defaults should avoid a prompt, not hide where planning files were created.
## Local Workspace Registry
OpenSpec should keep a lightweight local registry of known workspaces:
```text
getGlobalDataDir()/workspaces/registry.yaml
```
Expected registry state:
```yaml
version: 1
workspaces:
platform: /Users/tabish/.local/share/openspec/workspaces/platform
checkout: /Users/tabish/.local/share/openspec/workspaces/checkout
```
The registry is a local index, not the source of truth. It exists so workspace commands can work from anywhere, show a picker when multiple workspaces exist, and list known workspaces without scanning arbitrary folders.
Each workspace folder remains authoritative for its own `.openspec-workspace/workspace.yaml` and `.openspec-workspace/local.yaml`. If a registry entry points at a missing or invalid workspace, later check/list flows can report that and suggest a repair.
## Windows And WSL2
Path behavior is runtime-local:
- PowerShell/native Windows uses Windows paths and Windows data-directory fallback.
- WSL2 uses Linux paths and Linux/XDG fallback inside WSL.
- Local repo paths are stored as the user supplied them for the current runtime.
Examples:
```text
PowerShell:
default base -> %LOCALAPPDATA%\openspec\workspaces
WSL2:
default base -> ~/.local/share/openspec/workspaces
```
This slice should not translate between `D:\repo`, `/mnt/d/repo`, and `\\wsl$` paths. Cross-runtime translation can be reconsidered later if an agent-launch workflow requires it.
## Link Names
A link name is the stable way to refer to a repo or folder inside workspace planning.
The local path can vary by machine:
```text
shared link name: landing
Tabish path: /Users/tabish/repos/landing
Windows path: D:\repos\landing
WSL2 path: /mnt/d/repos/landing
```
Later workflows should refer to `landing` in workspace planning, status, and apply context. The local path is only how the current machine finds that repo or folder.
Link names are intentionally minimal: they must be non-empty, must not be `.` or `..`, must not contain path separators, and must be unique within the workspace.
The owning repo or folder remains the home of canonical specs and implementation work. The workspace makes the cross-boundary plan legible; it does not take ownership away from the linked repos or folders.
Link names are normally inferred from the folder basename in guided flows. Direct flows can allow an explicit name when the default would conflict or be unclear.
## Linked Repos And Folders
Workspace planning visibility should not require repo-local OpenSpec state.
That matters for two common cases:
- a repo has not adopted OpenSpec yet, but still needs to be considered in planning
- a large monorepo has folders such as packages, services, or apps that should be planned like separate areas, without each folder having its own `openspec/`
Foundation should allow the link model to describe both:
```text
multi-repo:
api -> /repos/api
web -> /repos/web
large monorepo:
billing -> /repos/platform/services/billing
checkout -> /repos/platform/apps/checkout
```
Later apply/verify/archive workflows can decide what extra readiness is needed for implementation. Planning should be able to start before that.
Linking only records the relationship between a workspace link name and a local path. It must not create, copy, move, initialize, or edit files inside the linked repo or folder.
Repo-local spec availability is computed when needed. For example, `repo_specs_path` can be reported by a later doctor command when a linked path contains `openspec/specs`, but that path should not be treated as required workspace state.
## Later Slices
This foundation stops before user-facing workspace workflows:
- `workspace-create-and-register-repos` owns setup, link, relink, list, and doctor behavior.
- `workspace-open-agent-context` owns agent launch context.
- `workspace-change-planning` owns workspace proposals and repo scope.
- `workspace-apply-repo-slice` owns implementation of one repo slice.
- `workspace-verify-and-archive` owns completion and archive behavior.
@@ -0,0 +1,142 @@
## Why
Users need a workspace to feel like the obvious home for planning across multiple repos or folders.
They should be able to think:
```text
I have repos or folders that are often planned together.
I create an OpenSpec workspace.
That workspace is where changes live.
My code stays where it is.
OpenSpec links the workspace to those local paths.
```
A workspace is not a feature. It is the durable planning home. Individual features, fixes, and projects are changes inside the workspace.
Users should not have to choose a storage location, create a change early, or understand internal workspace state before OpenSpec can orient itself.
The POC proved that workspace state is useful. This reimplementation should turn that into a simple product model that users and agents can explain without special-case vocabulary.
## What Changes
This change defines the user-facing foundation for OpenSpec workspaces.
An OpenSpec workspace has a recognizable planning home:
```text
workspace-root/
changes/
.openspec-workspace/
```
`changes/` is where workspace-level planning lives. `.openspec-workspace/` identifies the directory as an OpenSpec workspace and stores workspace state.
OpenSpec-managed workspaces live in one standard location:
```text
<global-data-dir>/workspaces/
```
Users should not need to choose that location. OpenSpec still shows the workspace path after setup so users know where planning files live. This foundation slice does not provide a workspace-specific environment-variable or configuration override for managed workspace storage.
OpenSpec also keeps a lightweight local registry of known workspaces on the current machine. The registry powers global commands, pickers, and listing, but each workspace folder remains the source of truth.
Workspace state is split by user expectation:
- shared workspace information can move between machines
- local checkout paths stay local to each machine
- linked repos and folders are referred to by stable link names, not by absolute paths
A linked path can be a full repo, a folder inside a monorepo, or another existing folder the workspace should plan against. A linked path does not need repo-local `openspec/` state before it can be included in workspace planning. Repo-local OpenSpec state may still matter later for implementation, verification, or archive workflows, but it is not a prerequisite for planning visibility.
Native Windows/PowerShell and WSL2 are both supported. Each runtime uses its own path conventions. OpenSpec does not translate paths between Windows and WSL in this foundation slice.
## Outcome
After this change, later workspace features can rely on one clear product contract:
- OpenSpec can tell when the user is inside a workspace.
- OpenSpec knows where to create managed workspaces by default.
- OpenSpec can keep a local registry of known workspaces.
- A workspace has one visible planning area: `changes/`.
- Workspace state is distinguishable from repo-local `openspec/` state.
- Shared workspace state does not force one user's local paths onto another user.
- Workspace planning can reference existing repos or folders by stable link names.
- Linked repos or folders do not need repo-local OpenSpec state for workspace planning.
- Multi-repo and large-monorepo work can use the same workspace planning model.
- Repo-owned specs and implementation remain owned by their repos or source areas.
- Windows, PowerShell, and WSL2 path behavior is predictable.
This change does not deliver the full workspace workflow. It gives `workspace-create-and-register-repos` the foundation it needs to add the first user-facing commands.
## POC Findings
Behavior to preserve:
- A workspace is a durable coordination home for cross-repo planning.
- The workspace has a visible `changes/` directory at its root.
- Linked repos and folders provide the context the workspace can plan against.
- Stable link names matter more than local checkout paths.
- Local machine paths should not become shared workspace state.
- Canonical specs and implementation still belong to the owning repos.
Lessons to carry forward:
- The POC's hidden `.openspec/` workspace metadata shape made workspace state too easy to confuse with repo-local OpenSpec state.
- Users should not need to run repo-local `openspec init` inside the workspace root.
- The POC's requirement that registered repos already have `openspec/` is too strict for planning. Repos and folders should be linkable before they adopt repo-local OpenSpec state.
- Repo or folder visibility should not depend on creating a change.
- Workspace setup should not imply repo-local implementation, branch, worktree, apply, verify, or archive behavior.
- `add-repo` is too narrow for the user-facing model. Linking an existing repo or folder is clearer.
## Decisions
- Workspace identity directory: `.openspec-workspace/`.
- Workspace identity file: `.openspec-workspace/workspace.yaml`.
- Workspace name: a valid folder name for the current OS, excluding empty names, `.`/`..`, and path separators.
- Workspace name usage: stored in `workspace.yaml`, used as the default managed workspace folder name, and used as the local registry name.
- Planning surface: top-level `changes/`.
- Local machine state: `.openspec-workspace/local.yaml`.
- Local machine state exclusion: OpenSpec-created workspaces exclude `.openspec-workspace/local.yaml` from portable collaboration state by default.
- Local workspace registry: `<global-data-dir>/workspaces/registry.yaml`.
- Default workspace base: `<global-data-dir>/workspaces/`.
- Platform behavior: native Windows and WSL2 each use the path conventions of the runtime running OpenSpec.
- Linked paths may be full repos, monorepo folders, or other existing folders.
- Link names: non-empty stable names, unique within a workspace, excluding `.`/`..` and path separators.
- Repo-local `openspec/` state is not required for workspace planning visibility.
- Linking records the relationship only; it does not create, copy, move, initialize, or edit files in the linked repo or folder.
Planning dependency:
- None. This is the first implementation slice.
## Non-Goals
- No complete `openspec workspace setup`, `openspec workspace link`, or `openspec workspace relink` flow yet.
- No public `openspec workspace create` command in the first user-facing workspace flow.
- No user-facing command, environment variable, or configuration setting for changing the standard workspace location.
- No question that asks users where OpenSpec should store workspaces by default.
- No automatic Windows-to-WSL or WSL-to-Windows path translation.
- No workspace-open agent launch behavior.
- No workspace-level proposal creation.
- No repo-slice apply, verify, archive, branch, or worktree behavior.
- No copying workspace planning files into linked repos or folders as a side effect of creating, detecting, or linking a workspace.
## Capabilities
### New Capabilities
- `workspace-foundation`: Defines the product foundation for OpenSpec workspaces.
### Modified Capabilities
- `openspec-conventions`: Describes how coordination workspaces differ from repo-local OpenSpec projects.
## Impact
- Workspace recognition and path behavior.
- Workspace state parsing.
- Local workspace registry parsing.
- Documentation and agent guidance for the workspace mental model.
- Later workspace slices should build on this contract instead of redefining workspace storage, identity, registry, or path behavior.
@@ -0,0 +1,29 @@
## ADDED Requirements
### Requirement: Workspace Product Language
OpenSpec conventions SHALL describe coordination workspaces in user-facing product terms.
#### Scenario: Describing workspace structure
- **WHEN** OpenSpec documentation describes workspace support
- **THEN** it SHALL present a workspace as the planning home for work across linked repos or folders
- **AND** it SHALL describe `changes/` as the workspace planning area
#### Scenario: Avoiding internal workspace vocabulary
- **WHEN** OpenSpec documentation explains what a workspace includes
- **THEN** it SHALL prefer plain product language such as "repos or folders"
- **AND** it SHALL avoid user-facing reliance on terms such as "working set", "code area", "entry", "alias", or "local overlay"
#### Scenario: Distinguishing workspaces from changes
- **WHEN** OpenSpec documentation explains workspace planning
- **THEN** it SHALL describe a workspace as a durable planning home
- **AND** it SHALL describe individual features, fixes, and projects as changes inside the workspace
#### Scenario: Distinguishing workspace and repo-local surfaces
- **WHEN** OpenSpec documentation compares workspace and repo-local flows
- **THEN** it SHALL explain that workspace planning lives in the workspace root
- **AND** it SHALL explain that repo-local specs and changes continue to live under each repo's `openspec/` directory
#### Scenario: Sequencing the workspace roadmap
- **WHEN** workspace reimplementation work is split across multiple active changes
- **THEN** conventions SHALL allow those changes to remain flat siblings under `openspec/changes/`
- **AND** dependency order MAY be documented in proposal prose until formal change stacking metadata is available
@@ -0,0 +1,199 @@
## ADDED Requirements
### Requirement: Recognizable Workspace Home
OpenSpec SHALL give users and agents a recognizable workspace home for cross-repo planning.
#### Scenario: Planning across linked repos or folders
- **WHEN** a user creates an OpenSpec workspace for repos or folders they plan across
- **THEN** the workspace SHALL provide a durable planning home
- **AND** the workspace SHALL be able to hold multiple changes over time
#### Scenario: Working from inside a workspace
- **GIVEN** a user runs OpenSpec from a workspace root or one of its subdirectories
- **WHEN** OpenSpec resolves the current workspace
- **THEN** it SHALL identify the workspace root
- **AND** it SHALL use the workspace root's `changes/` directory as the workspace planning area
#### Scenario: Avoiding accidental workspace mode
- **GIVEN** a directory has `changes/` but is not an OpenSpec workspace
- **WHEN** OpenSpec resolves the current workspace
- **THEN** it SHALL avoid treating that directory as a workspace
- **AND** it SHALL enter workspace mode only when the workspace identity file is present
### Requirement: Stable Workspace Name
OpenSpec SHALL use one folder-style workspace name across workspace identity, managed storage, and the local registry.
#### Scenario: Using one workspace name
- **WHEN** OpenSpec creates or registers a managed workspace
- **THEN** the workspace name SHALL be stored in `.openspec-workspace/workspace.yaml`
- **AND** the same name SHALL be used as the default managed workspace folder name
- **AND** the same name SHALL be used as the local registry name
#### Scenario: Rejecting invalid folder-style names
- **WHEN** OpenSpec accepts a workspace name
- **THEN** it SHALL reject empty names, `.` or `..`, and names containing path separators
- **AND** setup or create flows SHALL report OS-level folder creation failures clearly
### Requirement: Dedicated Workspace Identity
OpenSpec SHALL distinguish a coordination workspace from a repo-local OpenSpec project.
#### Scenario: Reading workspace identity
- **WHEN** OpenSpec reads or writes workspace identity and workspace state
- **THEN** it SHALL use `.openspec-workspace/`
#### Scenario: Preserving repo-local OpenSpec projects
- **GIVEN** a repo-local OpenSpec project uses `openspec/`
- **WHEN** that repo is linked to a workspace
- **THEN** OpenSpec SHALL continue treating `openspec/` as that repo's local OpenSpec directory
- **AND** workspace planning SHALL remain anchored in the workspace root
#### Scenario: Avoiding repo-local initialization in the workspace root
- **WHEN** a user is working from an OpenSpec workspace root
- **THEN** OpenSpec SHALL treat that root as a workspace coordination surface
- **AND** users SHALL not need to initialize a repo-local `openspec/` project inside the workspace root
### Requirement: Safe Workspace Sharing
OpenSpec SHALL keep shared workspace information separate from local machine paths.
#### Scenario: Sharing workspace planning
- **WHEN** a workspace is shared with another user or machine
- **THEN** shared workspace information SHALL include portable workspace identity and stable link names
- **AND** it SHALL not require another user to reuse the original user's absolute checkout paths
#### Scenario: Keeping checkout paths local
- **WHEN** OpenSpec stores local paths for a workspace
- **THEN** those paths SHALL be treated as local to the current machine and runtime
- **AND** another machine MAY map the same link names to different local paths
#### Scenario: Preserving runtime-local paths
- **WHEN** OpenSpec reads or writes local workspace paths
- **THEN** it SHALL preserve path strings valid for the current runtime
- **AND** it SHALL support native Windows paths and WSL2/Linux paths as local state values
#### Scenario: Excluding local state from portable collaboration
- **WHEN** OpenSpec creates a workspace
- **THEN** it SHALL exclude `.openspec-workspace/local.yaml` from portable collaboration state by default
- **AND** `.openspec-workspace/workspace.yaml` SHALL remain the portable workspace identity and link-name state
### Requirement: Standard Workspace Location
OpenSpec SHALL use a standard location for OpenSpec-managed workspaces without asking most users to choose one.
#### Scenario: Using the standard workspace location
- **WHEN** OpenSpec needs the location for OpenSpec-managed workspaces
- **THEN** it SHALL use `<global-data-dir>/workspaces`
- **AND** `<global-data-dir>` SHALL follow existing OpenSpec XDG and platform data directory behavior
#### Scenario: Avoiding workspace-specific storage overrides
- **WHEN** OpenSpec resolves the location for OpenSpec-managed workspaces
- **THEN** it SHALL not use a workspace-specific environment variable, command, or configuration setting in this slice
- **AND** managed workspace storage SHALL remain under `<global-data-dir>/workspaces`
#### Scenario: Running from native Windows
- **WHEN** OpenSpec runs from native Windows shells such as PowerShell
- **AND** `XDG_DATA_HOME` is not set
- **THEN** OpenSpec SHALL store managed workspaces under the Windows global data location
- **AND** paths SHALL follow native Windows path behavior
#### Scenario: Running from WSL2
- **WHEN** OpenSpec runs from WSL2
- **THEN** OpenSpec SHALL store managed workspaces under the Linux/XDG data location inside WSL
- **AND** paths SHALL follow Linux path behavior inside WSL
#### Scenario: Using the workspace location automatically
- **WHEN** OpenSpec creates or resolves OpenSpec-managed workspaces in later workflows
- **THEN** it SHALL use the resolved workspace location by default
- **AND** users SHALL be able to follow the normal workspace flow without choosing a storage location
#### Scenario: Showing the workspace path
- **WHEN** OpenSpec creates a workspace in the standard workspace location
- **THEN** it SHALL report the workspace path to the user
- **AND** it SHALL not hide where planning files were created
#### Scenario: Staying in the current runtime
- **WHEN** OpenSpec resolves workspace paths or local repo paths
- **THEN** it SHALL interpret paths for the runtime running OpenSpec
- **AND** Windows, UNC WSL, and WSL mount paths SHALL remain explicit user-provided paths
### Requirement: Local Workspace Registry
OpenSpec SHALL keep a lightweight local registry of known workspaces on the current machine.
#### Scenario: Recording known workspaces
- **WHEN** OpenSpec creates or learns about a managed workspace
- **THEN** it SHALL be able to record the workspace name and path in a local registry
- **AND** the registry SHALL be machine-local state
#### Scenario: Keeping workspace folders authoritative
- **WHEN** OpenSpec reads workspace details
- **THEN** each workspace folder's `.openspec-workspace/workspace.yaml` SHALL remain the source of truth for that workspace
- **AND** the local registry SHALL act only as an index of known workspace paths
#### Scenario: Finding workspaces from anywhere
- **WHEN** a later workspace command runs outside a workspace directory
- **THEN** OpenSpec MAY use the local registry to find known workspaces
- **AND** commands that need one workspace MAY use the registry to support an interactive picker
### Requirement: Stable Link Names
OpenSpec SHALL use stable link names to refer to repos and folders in workspace planning.
#### Scenario: Referring to a repo or folder in workspace planning
- **WHEN** workspace state or later workspace planning artifacts refer to a linked repo or folder
- **THEN** they SHALL use the stable link name
- **AND** the same link name SHALL remain valid even when local checkout paths differ
#### Scenario: Reusing link names across machines
- **WHEN** a workspace is used on another machine
- **THEN** link names SHALL remain stable
- **AND** local checkout paths MAY differ on that machine
#### Scenario: Rejecting invalid link names
- **WHEN** OpenSpec accepts a workspace link name
- **THEN** it SHALL reject empty names, `.` or `..`, and names containing path separators
- **AND** link names SHALL be unique within the workspace
### Requirement: Linked Repos And Folders
OpenSpec SHALL allow workspace planning to include linked repos and folders before they have repo-local OpenSpec state.
#### Scenario: Planning with a repo that has not adopted OpenSpec
- **WHEN** a workspace links a repo path that does not yet contain repo-local `openspec/`
- **THEN** the repo SHALL still be available for workspace-level planning
- **AND** implementation readiness MAY be handled by a later workflow
#### Scenario: Planning across monorepo folders
- **WHEN** planning spans multiple packages, services, apps, or directories inside one monorepo
- **THEN** the workspace SHALL be able to link those folders separately
- **AND** each folder SHALL not need its own repo-local `openspec/` directory to participate in workspace planning
#### Scenario: Treating repos and folders consistently
- **WHEN** a workspace plan includes both separate repos and folders inside a monorepo
- **THEN** OpenSpec SHALL use the same planning model for both
- **AND** users SHALL not need to create different kinds of workspace plans for multi-repo and monorepo changes
#### Scenario: Recording links without changing targets
- **WHEN** OpenSpec records a link between a workspace and a local repo or folder
- **THEN** it SHALL store the link in workspace state
- **AND** it SHALL not create, copy, move, initialize, or edit files inside the linked repo or folder
### Requirement: Planning Before Implementation
OpenSpec SHALL treat workspace creation and detection as planning setup, not implementation.
#### Scenario: Creating or detecting a workspace
- **WHEN** a workspace exists
- **THEN** OpenSpec SHALL treat it as a place for workspace-level planning
- **AND** repo implementation files SHALL remain unchanged until an explicit implementation workflow runs
#### Scenario: Deferring repo implementation
- **WHEN** repo-local implementation, apply, verify, or archive behavior is needed
- **THEN** that behavior SHALL require an explicit later workspace workflow
### Requirement: Repo Ownership Boundaries
OpenSpec SHALL keep repo ownership legible when planning happens in a workspace.
#### Scenario: Planning across owned repos
- **WHEN** a workspace plan refers to behavior owned by a repo or source area
- **THEN** that owner SHALL remain the home for canonical specs and implementation work
- **AND** the workspace SHALL make the cross-boundary plan visible without taking ownership away from that owner
#### Scenario: Drafting before ownership is clear
- **WHEN** cross-repo behavior is still being explored and ownership is not clear
- **THEN** the workspace MAY hold planning notes or draft behavior
- **AND** those drafts SHALL remain distinguishable from canonical repo-owned specs
@@ -0,0 +1,56 @@
## 1. POC Findings And Model Decisions
- [x] 1.1 Capture the foundation POC findings in the proposal/design artifacts
- [x] 1.2 Settle `.openspec-workspace/` as the workspace metadata directory
- [x] 1.3 Define the minimal workspace root shape and root marker
- [x] 1.4 Define committed workspace state versus machine-local workspace state
- [x] 1.5 Capture that workspace setup is useful only after at least one repo or folder is linked
- [x] 1.6 Capture that repo-owned specs and implementation remain owned by repos
- [x] 1.7 Capture that planning can include repos or monorepo folders without repo-local OpenSpec state
- [x] 1.8 Capture that workspaces hold many changes and are not feature containers
- [x] 1.9 Capture `link`/`relink` as the user-facing model instead of `add-repo`/`update-repo`
## 2. Foundation Helpers
- [x] 2.1 Add workspace path constants and helpers for `.openspec-workspace/`, `workspace.yaml`, `local.yaml`, and root `changes/`
- [x] 2.2 Add workspace root detection from an arbitrary starting directory
- [x] 2.3 Add typed parsing and validation for minimal shared workspace state
- [x] 2.4 Add typed parsing and validation for minimal machine-local workspace state
- [x] 2.5 Ensure repo-local `openspec/` projects are not mistaken for coordination workspaces
- [x] 2.6 Add a standard workspace location resolver using `getGlobalDataDir()/workspaces`
- [x] 2.7 Ensure workspace path helpers use platform path APIs and avoid hardcoded POSIX separators
- [x] 2.8 Add local workspace registry path constants and helpers
## 3. Metadata And Local State
- [x] 3.1 Define the versioned shared-state shape with workspace name and stable link map
- [x] 3.2 Define the versioned local-state shape with stable link names mapped to local paths
- [x] 3.3 Ensure local-state files are treated as machine-local and OpenSpec-created workspaces exclude `.openspec-workspace/local.yaml` from portable collaboration state
- [x] 3.4 Add validation for invalid versions, invalid link names, malformed link maps, and malformed local path maps
- [x] 3.5 Preserve native Windows and WSL2 path strings when reading and writing local path state
- [x] 3.6 Define the versioned local registry shape with workspace names mapped to workspace roots
- [x] 3.7 Ensure the local registry is treated as a convenience index, not the workspace source of truth
## 4. Documentation And Guidance
- [x] 4.1 Document the coordination workspace mental model
- [x] 4.2 Document how `.openspec-workspace/` differs from repo-local `openspec/`
- [x] 4.3 Document stable link names as the way to refer to linked repos and folders
- [x] 4.4 Document which behavior is intentionally deferred to later workspace slices
- [x] 4.5 Document native Windows/PowerShell and WSL2 path behavior for managed workspace storage
- [x] 4.6 Document linked repos/folders without repo-local OpenSpec and large-monorepo planning behavior
- [x] 4.7 Document the local workspace registry and global command model
## 5. Verification
- [x] 5.1 Add unit tests for root detection and non-detection cases
- [x] 5.2 Add unit tests for shared-state and local-state parsing
- [x] 5.3 Add unit tests for standard workspace location resolution with XDG/Linux fallback and native Windows fallback
- [x] 5.4 Add unit tests that local-state parsing preserves native Windows and WSL2-style paths
- [x] 5.5 Add unit tests for repo-local compatibility boundaries
- [x] 5.6 Add tests or docs coverage that linked repos/folders do not require repo-local `openspec/`
- [x] 5.7 Add tests or docs coverage for monorepo folder links under the same workspace model
- [x] 5.8 Add tests for local registry parsing and stale registry entries
- [x] 5.9 Add tests or docs coverage for `.openspec-workspace/local.yaml` exclusion in OpenSpec-created workspaces
- [x] 5.10 Run `openspec validate workspace-foundation --strict`
- [x] 5.11 Run targeted test coverage for the new workspace foundation helpers
@@ -0,0 +1,48 @@
## Why
After a workspace proposal exists, users need a practical way to implement one repo slice at a time.
In the proper workspace model, apply means implementation:
```text
Take the selected workspace change.
Take the selected repo slice.
Open or use the right checkout.
Implement that slice while preserving the workspace plan.
```
It should not mean copying or materializing planning files into every repo as a user-facing workflow.
## What Changes
Add the repo-slice apply workflow for workspace changes:
- select a workspace change
- select one target repo alias
- resolve the local checkout for that alias
- provide the agent with the workspace plan and repo-specific implementation context
- track progress without making the workspace lose ownership of the plan
The workflow should support implementation across separate branches or sessions while keeping the workspace proposal as the continuity layer.
Planning dependency:
- Depends on `workspace-change-planning`.
## Capabilities
### New Capabilities
- `workspace-repo-slice-apply`: Applies one repo slice of a workspace change as an implementation workflow.
### Modified Capabilities
- `cli-artifact-workflow`: Defines workspace apply as implementation rather than materialization.
- `context-injection`: Supplies repo-specific implementation context from a workspace change.
## Impact
- Workspace apply command behavior.
- Agent handoff text for repo-slice implementation.
- Local checkout resolution and branch/worktree assumptions.
- Tests that apply operates on one target repo slice and does not require copying workspace planning artifacts as the primary user contract.
@@ -0,0 +1,47 @@
## Why
Once repos are visible and the agent has workspace context, the user should be able to plan a cross-repo change without immediately materializing repo-local artifacts.
The user goal is:
```text
Explore the product goal across repos.
Decide the scope.
Create one workspace-level proposal that identifies the repo slices.
```
Planning should be the commitment point. Repo visibility alone should remain lightweight.
## What Changes
Add workspace-level change planning:
- create a workspace change from the coordination root
- capture the product goal once
- identify target repos by registered alias
- let the agent explore before committing to implementation slices
- keep the workspace as the planning source of truth
This slice should avoid rebuilding the POC's materialization-first behavior. Repo-local artifacts should not be created merely because a workspace change exists.
Planning dependency:
- Depends on `workspace-open-agent-context`.
## Capabilities
### New Capabilities
- `workspace-change-planning`: Creates and manages workspace-level proposals for cross-repo goals.
### Modified Capabilities
- `change-creation`: Adds workspace-aware change creation semantics and target repo selection.
- `openspec-conventions`: Defines the relationship between workspace-level planning and repo-local implementation work.
## Impact
- Workspace change creation.
- Target repo metadata and validation.
- Agent instructions for proposing cross-repo changes.
- Tests that registered repos are visible before change creation and that creating a change does not imply repo-local materialization.
@@ -0,0 +1,356 @@
## Product Shape
This slice is the first user-facing step after `workspace-foundation`.
The user experience should be:
```text
I set up a workspace.
I link the repos or folders it should know about.
I can list my workspaces later.
I can ask OpenSpec what is broken and how to fix it.
```
No change proposal is required yet.
## Links
A workspace link is a stable name plus a local path on the current machine.
Examples:
```text
api -> /repos/api
web -> /repos/web
checkout -> /repos/platform/apps/checkout
billing -> /repos/platform/services/billing
```
The path may point at a full repo or a folder inside a large monorepo. It may point at a repo or folder that has not adopted repo-local OpenSpec yet.
The product language should say "repos or folders". It should avoid "working set", "code area", "entry", "alias", and "local overlay" in user-facing output.
Path handling should behave like a folder picker. The user may type a relative or absolute path, but OpenSpec should verify that it points to an existing folder, convert it to an absolute path relative to the command's current working directory when needed, and store that verified absolute path in local workspace state. OpenSpec should not store the raw string the user typed.
Path conversion stays in the current runtime. Native Windows paths, WSL2 paths, and Unix paths should not be translated across runtimes. Where duplicate-path detection needs canonical comparisons, OpenSpec may compare canonical existing paths internally, but it should store and display the verified absolute path for the current runtime.
## Names
Workspace names should be kebab-case:
```text
platform
checkout-web
api2
```
Invalid workspace names include uppercase letters, underscores, dots, spaces, leading hyphens, trailing hyphens, empty names, dot names, and path separators. Interactive setup should explain the expected form and let the user retry. Non-interactive setup should fail with the same expectation in the error message.
Link names should keep the folder-style validation from `workspace-foundation`: they must not be empty, must not be `.` or `..`, must not contain path separators, and must be unique inside the workspace. This lets inferred link names match existing folder basenames without forcing users to rename local folders for workspace planning.
Link names are normally inferred from the folder basename:
```text
/repos/api -> api
/repos/platform/apps/checkout -> checkout
```
If the inferred name conflicts, interactive setup should show the conflicting name and the existing path it maps to, then ask for a different name. Non-interactive setup and direct `workspace link` should fail with a clear message instead of silently overwriting.
Duplicate-name errors should be specific:
```text
Cannot use link name 'api' because another link already uses that name.
Existing link:
api -> /repos/api
Choose a different name:
openspec workspace link archived-api /archive/api
If you meant to change the existing link path:
openspec workspace relink api /archive/api
```
This slice does not add a separate link-rename command. Renaming a link can be considered later if users need it, but v1 should keep the command model crisp: `link` adds a new link, and `relink` changes the local path for an existing link.
## Commands
### `workspace setup`
Guided onboarding:
- create a workspace in the standard workspace location
- ask for a workspace name
- require at least one existing repo or folder path
- infer link names from folder names
- let the user add more repos or folders with a simple repeated prompt
- record the workspace in the local workspace registry
- run `workspace doctor`
- print the workspace location, planning path, linked repos or folders, and next useful commands
This slice should not ask for preferred agent or open the workspace with an agent. Those belong to `workspace-open-agent-context`.
Setup should support a non-interactive mode for automation:
```bash
openspec workspace setup --no-interactive --name platform --link /path/to/api --link web=/path/to/web
```
In non-interactive mode, setup should fail cleanly unless the user provides a valid workspace name and at least one valid link. `--link` should accept either a path, which infers the name from the folder basename, or `name=path`.
There is no public `workspace create` command in this slice. Setup is the creation flow.
### `workspace list`
Show known OpenSpec-managed workspaces from the local workspace registry.
`workspace ls` should behave the same way.
The output should answer what exists and what each workspace links to:
```yaml
workspaces:
- name: platform
location: /.../openspec/workspaces/platform
links:
- name: api
path: /repos/api
- name: web
path: /repos/web
- name: checkout
location: /.../openspec/workspaces/checkout
links:
- name: app
path: /repos/platform/apps/checkout
```
List should keep deep validation for `workspace doctor`. It can still report obviously stale workspace registry entries if a known workspace location no longer exists. Stale registry entries are report-only in this slice: `workspace list` should not delete, rewrite, or repair registry entries, and this slice should not add a `workspace forget` command.
For JSON output, list should use typed workspace objects with a structured `status` array for issues:
```json
{
"workspaces": [
{
"name": "platform",
"root": "/.../openspec/workspaces/platform",
"links": [
{
"name": "api",
"path": "/repos/api",
"status": []
}
],
"status": []
},
{
"name": "old-platform",
"root": "/.../openspec/workspaces/old-platform",
"links": [],
"status": [
{
"severity": "error",
"code": "workspace_root_missing",
"message": "Workspace location does not exist.",
"fix": "Remove or repair the local registry entry."
}
]
}
],
"status": []
}
```
### `workspace link [name] <path>`
Record an existing repo or folder path for the selected workspace.
Supported forms:
```bash
openspec workspace link /path/to/api
openspec workspace link api-service /path/to/api
```
The one-argument form infers the link name from the folder basename. The two-argument form lets the user choose the link name.
The path must exist. The command should accept:
- full repo roots
- monorepo folders such as packages, services, and apps
- repos or folders without repo-local `openspec/`
If the user passes a relative path, OpenSpec should resolve it against the command's current working directory before writing local state.
If the path has repo-local OpenSpec state, OpenSpec can report the repo specs path in doctor output. If it does not, OpenSpec should still allow workspace planning.
`workspace link` only records the link. It must not create, copy, move, initialize, or edit files in the linked repo or folder.
### `workspace relink <name> <path>`
Repair or change the local path for an existing link.
Relink should use the same path handling as link: require an existing folder, resolve relative inputs to absolute runtime-local paths, and store the verified path.
This slice should keep relink focused on path repair. It should not include owner or handoff metadata; that language was too process-heavy in the POC and can be revisited later if users need contact or notes fields.
### `workspace doctor`
Explain one selected workspace from the user's machine. If the command is run from a workspace folder or subdirectory and `--workspace <name>` is not provided, doctor should use that current workspace. Otherwise it should follow the normal workspace-selection rules.
Doctor should inspect:
- workspace location
- workspace planning path
- linked repos and folders
- whether each local path exists
- repo-local specs path when present
- missing local paths
- local names that are not in shared workspace state
- shared link names that are missing local paths
- suggested fixes for each issue
Doctor should not scan every known workspace in the local registry by default. Broad registry visibility belongs to `workspace list`. A future `workspace doctor --all` can be considered later if users need global workspace diagnostics.
Doctor should report issues and suggested fixes. It should not repair anything automatically.
Registry cleanup remains out of scope. If doctor cannot inspect the selected workspace because the registry points at a missing or invalid workspace location, it should report that selected-workspace issue through status entries and stop before inspecting links. Other stale registry entries should be surfaced by `workspace list`, not by selected-workspace doctor.
Human output should be readable by default: a short workspace summary, linked repo or folder rows, and a clear issues section when anything needs attention. It should not be raw JSON or a rigid YAML dump.
JSON output should follow the object/status pattern: primary data lives in typed objects, and diagnostics live in `status` arrays. A healthy object has `status: []`. Status entries should include `severity`, `code`, `message`, and optional `target` and `fix` fields.
```json
{
"workspace": {
"name": "platform",
"root": "/.../openspec/workspaces/platform",
"planning_path": "/.../openspec/workspaces/platform/changes",
"links": [
{
"name": "api",
"path": "/repos/api",
"repo_specs_path": "/repos/api/openspec/specs",
"status": []
},
{
"name": "web",
"path": "/old/path/web",
"repo_specs_path": null,
"status": [
{
"severity": "error",
"code": "linked_path_missing",
"message": "Linked path does not exist.",
"target": "links.web.path",
"fix": "openspec workspace relink web /path/to/web"
}
]
}
],
"status": []
},
"status": []
}
```
## Workspace Selection
Workspace commands should work from anywhere.
Commands that do not need one workspace:
- `workspace setup`
- `workspace list`
- `workspace ls`
Commands that need one workspace:
- `workspace link`
- `workspace relink`
- `workspace doctor`
If the current command needs one workspace and `--workspace <name>` is not provided:
- use the current workspace when running from inside a workspace
- otherwise show an interactive picker when multiple known workspaces exist
- otherwise select the only known workspace
- otherwise explain that no workspaces exist and suggest `openspec workspace setup`
The current workspace wins even if it is not in the local workspace registry. This supports manually created or shared workspace folders. In that case commands should continue and include a non-fatal warning status:
```json
{
"severity": "warning",
"code": "workspace_not_in_local_registry",
"message": "This workspace is not recorded in the local workspace registry.",
"target": "workspace.root",
"fix": "Run a mutating workspace command from this workspace, such as workspace link or workspace relink, to record it locally."
}
```
For human output, this should be a short warning rather than a blocking error. Successful mutating commands that use an unregistered current workspace, such as `workspace link` or `workspace relink`, should record the workspace name and location in the local registry after the mutation succeeds. Non-mutating commands such as `workspace doctor` should not write registry state; they should only report the warning. This slice should not add a standalone `workspace register` or `workspace join` command.
In non-interactive mode, commands that need one workspace should fail when selection is ambiguous and suggest `--workspace <name>`.
`--json` should also suppress prompting for commands that need one workspace. If a command would otherwise show a picker, JSON mode should fail with a structured status error and suggest `--workspace <name>`.
## Machine-Local Files
Workspace creation should make machine-local state safe by default.
The workspace should ignore:
```text
/.openspec-workspace/local.yaml
```
The local workspace registry should also be machine-local:
```text
<global-data-dir>/workspaces/registry.yaml
```
Generated agent launch surfaces can be ignored by `workspace-open-agent-context` when that slice creates them.
## JSON Output
Interactive setup does not need JSON output as its primary contract. Non-interactive setup and direct commands should support JSON output for scripting:
- `workspace setup --no-interactive --json`
- `workspace list --json`
- `workspace link --json`
- `workspace relink --json`
- `workspace doctor --json`
`workspace setup --json` should require `--no-interactive`. If a user runs `workspace setup --json` without `--no-interactive`, setup should fail clearly because an interactive wizard cannot produce clean JSON. Direct commands such as `workspace list --json`, `workspace link --json`, `workspace relink --json`, and `workspace doctor --json` do not require `--no-interactive`, but JSON mode should disable prompts and fail on ambiguous workspace selection.
JSON output should use object/status structure across commands:
- primary entities such as `workspace`, `workspaces`, or `link` carry the durable data
- `status` arrays carry warnings, errors, and suggested fixes
- status entries use stable `code` values plus human-readable `message` text
- command-level `status` describes the whole response
- object-level `status` describes that specific workspace or link
## POC Adjustments
Keep:
- guided setup as the default first run
- direct list/link/check commands
- shared state separate from local paths
- clean non-interactive failure when required setup inputs are missing
- JSON output for non-interactive/direct commands
Change:
- do not expose public `workspace create` in the first release
- do not require repo-local OpenSpec state to link a repo or folder
- use `workspace link` instead of `workspace add-repo`
- use `workspace relink` instead of `workspace update-repo`
- do not save a preferred agent during setup
- do not offer to open the workspace from setup
- require setup to link at least one existing repo or folder
- keep relink behavior focused on path repair rather than owner or handoff metadata
- do not use "working set", "code area", "entry", "alias", or "local overlay" in human-facing output
@@ -0,0 +1,128 @@
## Why
Note: the change id keeps the older "register repos" wording for continuity. User-facing product language in this slice is `workspace setup`, `workspace link`, `workspace relink`, and "linked repos or folders."
Users start workspace work by creating a planning home and linking the repos or folders OpenSpec should know about.
They should not have to create a change before OpenSpec can see the relevant repos, monorepo folders, packages, services, or apps.
The product rule is:
```text
Workspace visibility is not change commitment.
```
A workspace is the durable planning home. A change is a feature, fix, project, or other planned piece of work inside that workspace.
## What Changes
Add the first user-facing workspace setup flow:
```text
Set up a workspace.
Link existing repos or folders.
List known workspaces and what they link to.
Check what OpenSpec can resolve and how to fix problems.
```
Expected user surface:
```bash
openspec workspace setup
openspec workspace setup --no-interactive --name platform --link /path/to/api --link web=/path/to/web
openspec workspace list
openspec workspace ls
openspec workspace link /path/to/api
openspec workspace link api-service /path/to/api
openspec workspace relink api /new/path/to/api
openspec workspace doctor
```
`workspace setup` is the creation path for users. It should ask for the workspace name first, create the workspace in the standard location, require at least one existing repo or folder path, infer link names from folder names, show the workspace location, and run a check at the end so the user knows what OpenSpec can see.
Workspace names should be kebab-case so they are clean managed-folder names and stable registry identifiers. Link names should keep the folder-style validation from `workspace-foundation` because they are often inferred directly from existing repo or folder basenames.
`workspace setup --no-interactive` is the automation path. It should require enough flags to create a useful workspace, including a workspace name and at least one link.
`workspace list` shows known OpenSpec-managed workspaces from the local workspace registry, including each workspace location and linked repos or folders.
`workspace link` records an existing local repo or folder path for the selected workspace. It should support a simple form that infers the link name from the folder name and an explicit-name form for conflicts or clarity. Linking does not create, copy, move, initialize, or edit files in the linked repo or folder.
Linking should behave like selecting a folder from a picker: OpenSpec verifies the folder exists, resolves relative inputs to an absolute path in the current runtime, and stores that verified path instead of the raw input string.
When a link name is already in use, OpenSpec should preserve the existing link and show the conflicting name with the existing path. The error should suggest choosing a different link name, or using `workspace relink <name> <path>` if the user intended to change the existing link's path.
`workspace relink` lets users repair or change the local path for an existing link without recreating the workspace. It should not introduce owner or handoff metadata in this slice.
`workspace doctor` explains what the current machine can resolve for one selected workspace: the workspace location, the workspace planning path, linked repos or folders, missing paths, repo-local specs paths when present, and suggested fixes. It should infer the current workspace when run from inside a workspace. It reports issues but does not repair them automatically.
Workspace commands should work globally. When a command needs one workspace and the user did not specify it, OpenSpec should use the local registry to show an interactive picker. In non-interactive mode, it should fail with a clear message and suggest `--workspace <name>`.
When a command runs from inside a valid workspace that is not in the local registry, OpenSpec should still use that current workspace. It should surface a non-fatal warning status that the workspace is not known locally, and successful mutating commands such as `workspace link` or `workspace relink` should record that workspace in the local registry after they update workspace state.
Machine-readable output should separate workspace or link objects from status entries. Status should be an array of structured issues instead of scattering fields such as `root_status`, `issue`, or `fix` through the primary object shape.
Interactive behavior should be disabled whenever output must be script-safe. `--no-interactive` means no prompts, and `--json` should fail instead of prompting when selection or setup inputs are ambiguous. `workspace setup --json` should require `--no-interactive` so JSON setup always uses the explicit automation path.
Planning dependency:
- Depends on `workspace-foundation`.
## POC Findings
Behavior to preserve:
- `workspace setup` was the friendly onboarding path.
- `workspace list` made managed workspaces discoverable.
- A direct automation path is still useful, but it should live under `workspace setup --no-interactive`.
- Link repair is useful, but owner or handoff metadata should not carry forward in this slice.
- `workspace doctor` was the right place to answer "what does OpenSpec know about this workspace?"
- Shared workspace state and local paths were stored separately.
- Setup failed cleanly when non-interactive inputs were incomplete.
- Created workspaces excluded machine-local path state from portable workspace state.
Behavior to change:
- The POC required linked repo paths to already contain repo-local `openspec/`. This should become an implementation-readiness signal, not a planning prerequisite.
- The POC used repo-only language. This slice should use "repos or folders" for user-facing text.
- The public command should be `workspace link`, not `workspace add-repo`.
- The repair command should be `workspace relink`, not `workspace update-repo`.
- Public `workspace create` should be removed for the first release. Setup should be the creation flow.
- The POC's `setup` flow stored preferred agent and open behavior. Agent launch preferences belong to `workspace-open-agent-context`, not this slice.
- Human output should avoid implementation terms such as working set, code area, entry, alias, or local overlay.
- `setup` should require at least one linked repo or folder so the created workspace is immediately useful.
## Non-Goals
- No public `openspec workspace create` command in this first release.
- No agent launch or workspace open behavior.
- No preferred agent prompts or saved agent preference.
- No owner or handoff metadata fields.
- No workspace change creation or target selection.
- No apply, verify, archive, branch, or worktree behavior.
- No requirement that linked repos or folders have repo-local OpenSpec state.
- No automatic repair behavior in `workspace doctor`.
- No registry cleanup command such as `workspace forget`; stale registry entries are report-only in this slice.
- No standalone `workspace register` or `workspace join` command; unregistered current workspaces are usable, and mutating workspace commands can record them locally.
## Capabilities
### New Capabilities
- `workspace-links`: Lets users set up a workspace, link repos or folders, list known workspaces, and check workspace resolution before change creation.
### Modified Capabilities
- `cli-artifact-workflow`: Introduces workspace setup commands that happen before change creation.
- `workspace-foundation`: Tightens workspace names to kebab-case while keeping folder-style link names.
## Impact
- `openspec workspace setup`
- `openspec workspace list`
- `openspec workspace ls`
- `openspec workspace link`
- `openspec workspace relink`
- `openspec workspace doctor`
- Local workspace registry usage from `workspace-foundation`.
- Docs and generated guidance that explain linked repos or folders as planning context, not implementation commitment.
@@ -0,0 +1,24 @@
## ADDED Requirements
### Requirement: Workspace Setup Commands
The CLI artifact workflow SHALL expose workspace setup commands before change creation.
#### Scenario: Preparing workspace planning before a change
- **WHEN** a user needs to prepare workspace planning across repos or folders
- **THEN** the CLI SHALL provide commands to set up, list, link, relink, and doctor workspaces
- **AND** those commands SHALL not require an active workspace change
#### Scenario: Listing workspaces with a short command
- **WHEN** a user wants a concise workspace list command
- **THEN** the CLI SHALL support `openspec workspace ls`
- **AND** it SHALL behave the same as `openspec workspace list`
#### Scenario: Keeping setup separate from agent launch
- **WHEN** a user completes workspace setup
- **THEN** the setup workflow SHALL leave agent launch and workspace open behavior to a later workflow
- **AND** setup SHALL not require a preferred agent choice
#### Scenario: Avoiding public direct creation
- **WHEN** users create a workspace in the first workspace setup flow
- **THEN** the CLI SHALL use `openspec workspace setup`
- **AND** it SHALL not expose `openspec workspace create` as the public creation path
@@ -0,0 +1,35 @@
## MODIFIED Requirements
### Requirement: Stable Workspace Name
OpenSpec SHALL use one kebab-case workspace name across workspace identity, managed storage, and the local registry.
#### Scenario: Using one workspace name
- **WHEN** OpenSpec creates or records a managed workspace
- **THEN** the workspace name SHALL be stored in `.openspec-workspace/workspace.yaml`
- **AND** the same name SHALL be used as the default managed workspace folder name
- **AND** the same name SHALL be used as the local registry name
#### Scenario: Rejecting invalid workspace names
- **WHEN** OpenSpec accepts a workspace name
- **THEN** it SHALL require kebab-case names using lowercase letters, numbers, and single hyphen separators
- **AND** it SHALL reject empty names, dot names, names with leading or trailing hyphens, names with repeated hyphens, uppercase letters, spaces, underscores, dots, and path separators
- **AND** setup flows SHALL report OS-level folder creation failures clearly
### Requirement: Stable Link Names
OpenSpec SHALL use stable folder-style link names to refer to repos and folders in workspace planning.
#### Scenario: Referring to a repo or folder in workspace planning
- **WHEN** workspace state or later workspace planning artifacts refer to a linked repo or folder
- **THEN** they SHALL use the stable link name
- **AND** the same link name SHALL remain valid even when local checkout paths differ
#### Scenario: Reusing link names across machines
- **WHEN** a workspace is used on another machine
- **THEN** link names SHALL remain stable
- **AND** local checkout paths MAY differ on that machine
#### Scenario: Rejecting invalid link names
- **WHEN** OpenSpec accepts a workspace link name
- **THEN** it SHALL reject empty names, `.` or `..`, and names containing path separators
- **AND** link names SHALL be unique within the workspace
- **AND** link names SHALL not be required to use workspace-name kebab-case
@@ -0,0 +1,356 @@
## ADDED Requirements
### Requirement: Guided Workspace Setup
OpenSpec SHALL provide a guided setup flow for users starting workspace planning.
#### Scenario: Creating a workspace through setup
- **WHEN** a user runs `openspec workspace setup`
- **THEN** OpenSpec SHALL guide the user through creating an OpenSpec workspace
- **AND** the workspace SHALL use the standard workspace location from the workspace foundation
#### Scenario: Asking for the workspace name first
- **WHEN** interactive setup starts
- **THEN** OpenSpec SHALL ask for the workspace name before asking for repos or folders
- **AND** workspace names SHALL use kebab-case with lowercase letters, numbers, and hyphens
#### Scenario: Retrying an invalid workspace name during setup
- **WHEN** an interactive user enters an invalid workspace name
- **THEN** OpenSpec SHALL explain that workspace names must be kebab-case
- **AND** it SHALL let the user enter another workspace name before continuing setup
#### Scenario: Linking a required first repo or folder
- **WHEN** setup asks for repos or folders
- **THEN** the user SHALL provide at least one existing repo or folder path
- **AND** setup SHALL not finish successfully until at least one path is linked
#### Scenario: Inferring link names during setup
- **WHEN** the user provides a repo or folder path during setup
- **THEN** OpenSpec SHALL infer the link name from the folder basename
- **AND** it SHALL ask for a different name only when the inferred name conflicts
#### Scenario: Handling inferred link name conflicts during setup
- **GIVEN** setup infers a link name that already exists in the workspace
- **WHEN** setup is interactive
- **THEN** OpenSpec SHALL show the conflicting link name and the existing path for that link
- **AND** it SHALL ask the user for a different link name before continuing
#### Scenario: Preserving folder-style link names
- **WHEN** OpenSpec accepts a workspace link name
- **THEN** it SHALL allow folder-style names that are valid under the workspace foundation link-name rules
- **AND** it SHALL not require link names to use the stricter workspace-name kebab-case rule
#### Scenario: Adding multiple repos or folders during setup
- **WHEN** setup links a repo or folder
- **THEN** OpenSpec SHALL let the user add another repo or folder with a simple repeated prompt
- **AND** each linked path SHALL be recorded without editing the target repo or folder
#### Scenario: Storing verified absolute paths during setup
- **WHEN** setup links a repo or folder path
- **THEN** OpenSpec SHALL verify that the path resolves to an existing folder
- **AND** it SHALL store an absolute runtime-local path in machine-local state instead of the raw user input
- **AND** relative inputs SHALL be resolved against the command's current working directory
#### Scenario: Preserving equals signs in setup link paths
- **WHEN** non-interactive setup receives a `--link` value that resolves to an existing folder and contains `=`
- **THEN** OpenSpec SHALL treat the full value as the path
- **AND** it SHALL infer the link name from the folder basename
- **AND** explicit `--link <name>=<path>` inputs SHALL preserve `=` characters inside `<path>`
#### Scenario: Running setup with non-interactive inputs
- **WHEN** `openspec workspace setup --no-interactive` receives a workspace name and at least one valid link
- **THEN** OpenSpec SHALL create the workspace without prompts
- **AND** it SHALL support repeated `--link` values
#### Scenario: Non-interactive setup duplicate link names
- **WHEN** `openspec workspace setup --no-interactive` receives two links with the same inferred or explicit name
- **THEN** OpenSpec SHALL fail with a clear duplicate link-name error
- **AND** the error SHALL show the conflicting link name and the first path using that name
- **AND** it SHALL suggest using explicit `--link <name>=<path>` values with different names
#### Scenario: Missing non-interactive setup inputs
- **WHEN** `openspec workspace setup --no-interactive` is missing a workspace name or link
- **THEN** OpenSpec SHALL fail with a clear message
- **AND** it SHALL explain which flags are required
#### Scenario: Finishing setup
- **WHEN** setup finishes
- **THEN** OpenSpec SHALL show the workspace location, planning path, and linked repos or folders
- **AND** it SHALL check what the current machine can resolve
#### Scenario: Recording created workspaces locally
- **WHEN** setup creates a workspace
- **THEN** OpenSpec SHALL record it in the local workspace registry
- **AND** the workspace folder SHALL remain the source of truth for workspace state
#### Scenario: Reusing an existing workspace name during setup
- **GIVEN** a managed workspace already exists with the requested name
- **WHEN** a user runs setup with that workspace name
- **THEN** OpenSpec SHALL explain that the workspace already exists
- **AND** it SHALL not overwrite the existing workspace
### Requirement: Workspace Discovery
OpenSpec SHALL let users see the OpenSpec-managed workspaces available on the current machine.
#### Scenario: Listing workspaces
- **WHEN** a user runs `openspec workspace list`
- **THEN** OpenSpec SHALL list known managed workspaces
- **AND** each workspace SHALL include the workspace name, workspace location, and linked repos or folders
#### Scenario: Using the short list command
- **WHEN** a user runs `openspec workspace ls`
- **THEN** OpenSpec SHALL behave the same as `openspec workspace list`
#### Scenario: Listing when no workspaces exist
- **WHEN** a user runs `openspec workspace list`
- **AND** no managed workspaces exist
- **THEN** OpenSpec SHALL say that no workspaces were found
- **AND** it SHALL show the user how to create one
#### Scenario: Listing stale registry entries
- **WHEN** the local registry contains a workspace location that no longer exists
- **THEN** `workspace list` SHALL report the stale workspace entry
- **AND** it SHALL avoid silently deleting registry state
- **AND** it SHALL avoid rewriting or repairing registry state automatically
#### Scenario: Avoiding registry cleanup commands
- **WHEN** users inspect stale workspace registry entries in this slice
- **THEN** OpenSpec SHALL treat stale entries as report-only diagnostics
- **AND** it SHALL not expose a registry cleanup command such as `workspace forget`
### Requirement: Global Workspace Commands
OpenSpec SHALL let workspace commands run from outside workspace directories.
#### Scenario: Selecting a workspace by flag
- **WHEN** a command that needs one workspace receives `--workspace <name>`
- **THEN** OpenSpec SHALL use that workspace from the local registry
- **AND** it SHALL fail clearly if the workspace name is unknown
#### Scenario: Using the current workspace
- **GIVEN** the command runs from a workspace folder or subdirectory
- **WHEN** the command needs one workspace and no `--workspace` flag is provided
- **THEN** OpenSpec SHALL use the current workspace
#### Scenario: Using an unregistered current workspace
- **GIVEN** the command runs from a valid workspace folder or subdirectory
- **AND** that workspace is not recorded in the local workspace registry
- **WHEN** the command needs one workspace and no `--workspace <name>` flag is provided
- **THEN** OpenSpec SHALL use the current workspace
- **AND** it SHALL include a non-fatal warning status with code `workspace_not_in_local_registry`
- **AND** the warning SHALL explain how the user can get the workspace recorded locally
#### Scenario: Recording an unregistered current workspace after mutation
- **GIVEN** a mutating workspace command uses a valid current workspace that is not recorded in the local workspace registry
- **WHEN** `workspace link` or `workspace relink` succeeds
- **THEN** OpenSpec SHALL record the workspace name and location in the local workspace registry
#### Scenario: Doctor does not register current workspaces
- **GIVEN** `workspace doctor` uses a valid current workspace that is not recorded in the local workspace registry
- **WHEN** doctor finishes
- **THEN** OpenSpec SHALL report the non-fatal registry warning
- **AND** it SHALL not write registry state
#### Scenario: Picking from multiple workspaces
- **GIVEN** multiple known workspaces exist
- **WHEN** an interactive command needs one workspace and none is specified
- **THEN** OpenSpec SHALL show a workspace picker
- **AND** the picker SHALL include workspace names and paths
#### Scenario: Ambiguous non-interactive workspace selection
- **GIVEN** multiple known workspaces exist
- **WHEN** a non-interactive command needs one workspace and none is specified
- **THEN** OpenSpec SHALL fail with a clear message
- **AND** it SHALL suggest passing `--workspace <name>`
#### Scenario: Ambiguous JSON workspace selection
- **GIVEN** multiple known workspaces exist
- **WHEN** a command running with `--json` needs one workspace and none is specified
- **THEN** OpenSpec SHALL fail without showing a picker
- **AND** it SHALL emit a structured status error
- **AND** it SHALL suggest passing `--workspace <name>`
#### Scenario: No known workspaces for a command that needs one
- **GIVEN** no known workspaces exist in the local registry
- **AND** the command is not running from a workspace folder or subdirectory
- **WHEN** `workspace link`, `workspace relink`, `workspace doctor`, or another command that needs one workspace runs without `--workspace <name>`
- **THEN** OpenSpec SHALL fail without showing a picker regardless of interactive mode
- **AND** it SHALL print `No known OpenSpec workspaces. Run 'openspec workspace setup' first.`
- **AND** it SHALL explain that `--workspace <name>` can be used after at least one workspace is known locally
### Requirement: Workspace Links
OpenSpec SHALL let users link existing repos or folders to a workspace before creating a change.
#### Scenario: Linking with an inferred name
- **WHEN** a user runs `openspec workspace link <path>`
- **THEN** OpenSpec SHALL infer the link name from the folder basename
- **AND** it SHALL store the verified absolute local path as machine-local state
#### Scenario: Linking with an explicit name
- **WHEN** a user runs `openspec workspace link <name> <path>`
- **THEN** OpenSpec SHALL use the explicit link name for planning
- **AND** it SHALL store the verified absolute local path as machine-local state
#### Scenario: Requiring an existing path
- **WHEN** a user links a repo or folder path
- **THEN** the path SHALL exist on the current machine
- **AND** OpenSpec SHALL reject missing paths with a clear message
#### Scenario: Resolving linked paths before storage
- **WHEN** a user links a repo or folder path
- **THEN** OpenSpec SHALL store the verified absolute path for the current runtime
- **AND** relative inputs SHALL be resolved against the command's current working directory
- **AND** OpenSpec SHALL not translate paths between native Windows, WSL2, and Unix runtimes
#### Scenario: Linking a monorepo folder
- **WHEN** a user links a package, service, app, or directory inside a monorepo
- **THEN** OpenSpec SHALL store it as a workspace link
- **AND** it SHALL not require that folder to have its own repo-local `openspec/` directory
#### Scenario: Linking without repo-local OpenSpec
- **WHEN** a user links a path that does not contain repo-local OpenSpec state
- **THEN** OpenSpec SHALL keep that repo or folder available for workspace planning
- **AND** it SHALL not treat missing repo-local OpenSpec state as a link failure
#### Scenario: Link records only
- **WHEN** a user links a repo or folder
- **THEN** OpenSpec SHALL record workspace state and local path state
- **AND** it SHALL not create, copy, move, initialize, or edit files in the linked repo or folder
#### Scenario: Blocking link when local state is invalid
- **GIVEN** the workspace machine-local state file exists but cannot be parsed or validated
- **WHEN** a user runs `openspec workspace link`
- **THEN** OpenSpec SHALL fail with status code `workspace_local_state_invalid`
- **AND** it SHALL not rewrite shared workspace state or machine-local path state
#### Scenario: Reusing a link name
- **GIVEN** a workspace already has a link with a given name
- **WHEN** a user tries to link another path with the same name
- **THEN** OpenSpec SHALL explain that the link name is already in use by another link
- **AND** it SHALL show the existing link name and existing path
- **AND** it SHALL suggest choosing a different link name
- **AND** it SHALL suggest `workspace relink <name> <path>` when the user intended to change the existing link path
- **AND** it SHALL preserve the existing link unless the user explicitly relinks it
### Requirement: Workspace Relinks
OpenSpec SHALL let users update existing link paths without recreating the workspace.
#### Scenario: Updating a local path
- **GIVEN** a workspace has a link
- **WHEN** a user runs `openspec workspace relink <name> <path>`
- **THEN** OpenSpec SHALL keep the stable link name
- **AND** it SHALL update the machine-local path for the current machine to the verified absolute path
#### Scenario: Requiring an existing relink path
- **WHEN** a user relinks to a new path
- **THEN** the new path SHALL exist on the current machine
- **AND** OpenSpec SHALL reject missing paths with a clear message
#### Scenario: Resolving relink paths before storage
- **WHEN** a user relinks to a new path
- **THEN** OpenSpec SHALL store the verified absolute path for the current runtime
- **AND** relative inputs SHALL be resolved against the command's current working directory
#### Scenario: Blocking relink when local state is invalid
- **GIVEN** the workspace machine-local state file exists but cannot be parsed or validated
- **WHEN** a user runs `openspec workspace relink`
- **THEN** OpenSpec SHALL fail with status code `workspace_local_state_invalid`
- **AND** it SHALL not rewrite machine-local path state
#### Scenario: Updating an unknown link
- **WHEN** a user tries to relink a link that does not exist
- **THEN** OpenSpec SHALL explain that the link name is unknown
- **AND** it SHALL preserve existing workspace state
#### Scenario: Avoiding owner and handoff fields
- **WHEN** users link or relink repos or folders in this slice
- **THEN** OpenSpec SHALL not ask for owner or handoff metadata
- **AND** link maintenance SHALL focus on names and local paths
### Requirement: Workspace Health Check
OpenSpec SHALL explain what the current machine can resolve for a workspace.
#### Scenario: Doctor checks one selected workspace
- **WHEN** a user runs `openspec workspace doctor`
- **THEN** OpenSpec SHALL inspect one selected workspace
- **AND** it SHALL not scan every known workspace in the local registry by default
#### Scenario: Doctor infers the current workspace
- **GIVEN** the command runs from a workspace folder or subdirectory
- **WHEN** the user runs `openspec workspace doctor` without `--workspace <name>`
- **THEN** OpenSpec SHALL inspect the current workspace
#### Scenario: Checking a healthy workspace
- **WHEN** a user runs `openspec workspace doctor`
- **THEN** OpenSpec SHALL show the workspace location and workspace planning path
- **AND** it SHALL show linked repos or folders and which paths resolve on the current machine
#### Scenario: Selected workspace location is missing
- **GIVEN** the selected workspace comes from the local registry
- **AND** the registered workspace location is missing or invalid
- **WHEN** a user runs `openspec workspace doctor`
- **THEN** OpenSpec SHALL report a selected-workspace status error
- **AND** it SHALL not attempt to inspect links for that workspace
#### Scenario: Reporting repo-local specs paths
- **WHEN** a linked repo or folder resolves
- **THEN** doctor SHALL report `repo_specs_path` when repo-local `openspec/specs` exists
- **AND** it SHALL report `repo_specs_path: null` when repo-local specs are not present
#### Scenario: Checking missing paths
- **WHEN** a link points to a path that is missing on the current machine
- **THEN** doctor SHALL identify the affected link name
- **AND** it SHALL include a suggested `workspace relink` fix
#### Scenario: Checking shared and local state drift
- **WHEN** shared workspace state and machine-local path state do not agree
- **THEN** doctor SHALL explain which link names are affected
- **AND** it SHALL distinguish shared workspace links from local-only paths
#### Scenario: Reporting invalid local state
- **WHEN** list or doctor reads a workspace whose machine-local state file cannot be parsed or validated
- **THEN** OpenSpec SHALL report status code `workspace_local_state_invalid`
- **AND** it SHALL avoid treating the invalid local state as an empty path map for mutation or repair suggestions
- **AND** it SHALL not rewrite workspace registry state or machine-local path state
#### Scenario: Reporting without auto-repair
- **WHEN** doctor finds issues
- **THEN** it SHALL report all issues it can find
- **AND** it SHALL not automatically repair workspace state
#### Scenario: Using readable human output
- **WHEN** doctor prints human output
- **THEN** it SHALL show a readable workspace summary, linked repos or folders, and issues when present
- **AND** it SHALL avoid printing raw JSON or relying on a rigid YAML dump as the default human experience
### Requirement: Scriptable Workspace Setup Commands
OpenSpec SHALL provide JSON output for direct workspace setup commands.
#### Scenario: Requesting JSON output
- **WHEN** a user passes `--json` to direct workspace setup commands
- **THEN** OpenSpec SHALL print machine-readable output
- **AND** the output SHALL avoid extra human-readable text
- **AND** the output SHALL separate primary objects from structured `status` entries
#### Scenario: Setup JSON requires non-interactive setup
- **WHEN** a user runs `openspec workspace setup --json` without `--no-interactive`
- **THEN** OpenSpec SHALL fail clearly
- **AND** it SHALL explain that `workspace setup --json` requires `--no-interactive`
#### Scenario: JSON output disables prompts
- **WHEN** a direct workspace setup command runs with `--json`
- **THEN** OpenSpec SHALL avoid interactive prompts
- **AND** it SHALL fail with structured status output when required choices are ambiguous
#### Scenario: JSON status entry shape
- **WHEN** a direct workspace setup command reports warnings, errors, or suggested fixes in JSON output
- **THEN** each status entry SHALL include a stable `code`, a `severity`, and a human-readable `message`
- **AND** status entries MAY include `target` and `fix` fields when a specific object field or suggested command is useful
#### Scenario: JSON object status shape
- **WHEN** a direct workspace setup command emits JSON for workspace, link, or list objects
- **THEN** each object MAY include a `status` array for object-specific warnings or errors
- **AND** the top-level response SHALL include a `status` array for command-level warnings or errors
- **AND** healthy objects and healthy responses SHALL use an empty `status` array
#### Scenario: Commands with JSON output
- **WHEN** users run `workspace setup --no-interactive`, `workspace list`, `workspace link`, `workspace relink`, or `workspace doctor`
- **THEN** each command SHALL support JSON output
@@ -0,0 +1,121 @@
## 1. POC Findings And Scope
- [x] 1.1 Confirm `setup`, `list`, and `doctor` belong to this slice
- [x] 1.2 Capture that setup should not own preferred agent or workspace open behavior
- [x] 1.3 Capture that linked repos or folders and monorepo paths are allowed without repo-local OpenSpec state
- [x] 1.4 Capture decisions for JSON output, `ls`, `.gitignore`, non-interactive setup, required first link, and relink behavior
- [x] 1.5 Capture that public `workspace create` is out of scope for the first release
- [x] 1.6 Capture `link`/`relink` as the user-facing commands
## 2. Workspace Setup
- [x] 2.1 Implement `openspec workspace setup` as the only public creation path
- [x] 2.2 Prompt for workspace name first in interactive setup
- [x] 2.3 Validate workspace names as kebab-case and let interactive users retry invalid names
- [x] 2.4 Require at least one existing repo or folder path during setup
- [x] 2.5 Infer link names from folder basenames during setup
- [x] 2.6 Let users add more repos or folders with a simple repeated prompt
- [x] 2.7 Run `workspace doctor` after setup and show a readable summary
- [x] 2.8 Print the workspace location, planning path, linked repos or folders, and next useful commands
- [x] 2.9 Keep preferred agent prompts and workspace opening out of this slice
- [x] 2.10 Add `.gitignore` handling for machine-local workspace state
- [x] 2.11 Record created workspaces in the local workspace registry
- [x] 2.12 Add tests for native Windows/PowerShell and WSL2-compatible path construction where practical
## 3. Non-Interactive Setup
- [x] 3.1 Add `workspace setup --no-interactive --name <name> --link <path>` support
- [x] 3.2 Support repeated `--link` values
- [x] 3.3 Support `--link <path>` with inferred names
- [x] 3.4 Support `--link <name>=<path>` with explicit names
- [x] 3.5 Fail cleanly when non-interactive setup is missing a name or at least one link
- [x] 3.6 Resolve relative link paths to verified absolute runtime-local paths before storing local state
- [x] 3.7 Require `--no-interactive` when `workspace setup --json` is used
- [x] 3.8 Add `--json` output for non-interactive setup
- [x] 3.9 Preserve the interactive setup UX when `--no-interactive` is not passed
## 4. Workspace Listing
- [x] 4.1 Implement `openspec workspace list`
- [x] 4.2 Add `workspace ls` as an alias for `workspace list`
- [x] 4.3 List known OpenSpec-managed workspaces from the local workspace registry
- [x] 4.4 Handle the no-workspaces case with a clear next step
- [x] 4.5 Show each workspace location and linked repos or folders
- [x] 4.6 Report stale registry entries with status entries without deleting, rewriting, or repairing registry state
- [x] 4.7 Add JSON output with typed workspace objects and structured status arrays
## 5. Workspace Selection
- [x] 5.1 Make workspace commands work from outside workspace directories
- [x] 5.2 Add `--workspace <name>` to commands that need one workspace
- [x] 5.3 Use the current workspace when running from inside a workspace
- [x] 5.4 Use unregistered current workspaces with a non-fatal warning status
- [x] 5.5 Record unregistered current workspaces in the local registry after successful `workspace link` or `workspace relink`
- [x] 5.6 Keep `workspace doctor` diagnostic-only when the current workspace is unregistered
- [x] 5.7 Show an interactive picker when multiple known workspaces exist and no workspace is specified
- [x] 5.8 Select the only known workspace automatically when there is exactly one
- [x] 5.9 Fail clearly in non-interactive mode when workspace selection is ambiguous
- [x] 5.10 Fail with structured status output instead of prompting when `--json` workspace selection is ambiguous
- [x] 5.11 Use the local workspace registry for workspace lookup
## 6. Workspace Links
- [x] 6.1 Implement `openspec workspace link <path>` with inferred link names
- [x] 6.2 Implement `openspec workspace link <name> <path>` with explicit link names
- [x] 6.3 Accept full repo roots and monorepo package/service/app folder paths
- [x] 6.4 Require linked paths to exist
- [x] 6.5 Allow links without repo-local `openspec/`
- [x] 6.6 Store stable link names in shared state and local paths in machine-local state
- [x] 6.7 Keep link names folder-style, and detect duplicate link names with a specific error that shows the existing link path and suggests a different name or `workspace relink`
- [x] 6.8 Resolve relative linked paths to verified absolute runtime-local paths before storing local state
- [x] 6.9 Preserve native Windows and WSL2-style paths as local path values without cross-runtime translation
- [x] 6.10 Ensure link only records state and does not edit the linked repo/folder
- [x] 6.11 Add `--json` output for `workspace link`
## 7. Workspace Relinks
- [x] 7.1 Implement `openspec workspace relink <name> <path>`
- [x] 7.2 Let users repair or change the local path for an existing link
- [x] 7.3 Require relink paths to exist
- [x] 7.4 Resolve relative relink paths to verified absolute runtime-local paths before storing local state
- [x] 7.5 Keep owner or handoff metadata out of this slice
- [x] 7.6 Add `--json` output for `workspace relink`
- [x] 7.7 Return a clear error for unknown link names
## 8. Workspace Doctor
- [x] 8.1 Implement `openspec workspace doctor` for one selected workspace only
- [x] 8.2 Show the workspace location and workspace planning path
- [x] 8.3 Show linked repos or folders in readable human output with a clear issues section
- [x] 8.4 Report missing local paths, missing filesystem paths, local-only names, and selected-workspace location problems
- [x] 8.5 Report `repo_specs_path` when repo-local `openspec/specs` exists and `null` otherwise
- [x] 8.6 Include suggested fixes for each issue
- [x] 8.7 Avoid automatic repair behavior
- [x] 8.8 Add JSON output with typed workspace/link objects and structured status arrays
- [x] 8.9 Keep stale registry cleanup commands such as `workspace forget` out of this slice
## 9. Documentation And Guidance
- [x] 9.1 Document setup/list/link/relink/doctor in user-facing product language
- [x] 9.2 Document linked repos or folders and large-monorepo folder links
- [x] 9.3 Document that workspace visibility is not change commitment
- [x] 9.4 Avoid "working set", "code area", "entry", "alias", and "local overlay" in human-facing docs
- [x] 9.5 Document JSON output support and the object/status response pattern for non-interactive/direct commands
- [x] 9.6 Document global command behavior, workspace picker behavior, and `--workspace <name>`
- [x] 9.7 Document that setup controls workspace storage and always shows the workspace location
## 10. Verification
- [x] 10.1 Run `openspec validate workspace-create-and-register-repos --strict`
- [x] 10.2 Run targeted command tests for workspace setup/list/link/relink/doctor, including doctor inferring the current workspace
- [x] 10.3 Run targeted tests for links without repo-local OpenSpec and monorepo folder links
- [x] 10.4 Run targeted tests for JSON output, `ls`, `.gitignore`, non-interactive setup, required first link, verified absolute path storage, and JSON/no-interactive prompt suppression
- [x] 10.5 Run targeted tests for global command selection, unregistered current workspace handling, and local workspace registry behavior
## 11. Review Fixes
- [x] 11.1 Preserve `=` characters in inferred setup link paths while keeping explicit `--link <name>=<path>` support
- [x] 11.2 Add reusable core helpers for optional local state reads and setup link input parsing
- [x] 11.3 Fail `workspace link` and `workspace relink` before mutation when local state is invalid
- [x] 11.4 Report invalid local state distinctly in `workspace list` and `workspace doctor`
- [x] 11.5 Add regression tests for equals-sign setup paths and malformed local state behavior
@@ -0,0 +1,44 @@
## Why
After a user creates a workspace and links repos or folders, they need to open that workspace with an agent and have the agent understand the working set immediately.
The user should not need to explain where every repo lives, which aliases matter, or whether they are currently planning versus implementing. The workspace should provide that context.
## What Changes
Add the workspace-open experience:
```text
Open this workspace with my agent.
The agent sees the workspace location, linked repos or folders, current changes, and relevant instructions.
```
Links are the planning context. The local registry is only a workspace-discovery index for finding known workspaces on the current machine.
The launch context should separate stable guidance from dynamic runtime scope:
- stable behavior belongs in workspace-level agent guidance where possible
- dynamic scope belongs in the launch prompt or equivalent runtime context
- linked repos or folders should be visible even when no change is active
- change-scoped sessions should include the selected change and target repo context
Planning dependency:
- Depends on `workspace-create-and-register-repos`.
## Capabilities
### New Capabilities
- `workspace-agent-context`: Opens a workspace session with enough dynamic context for an agent to reason across linked repos or folders.
### Modified Capabilities
- `context-injection`: Extends context construction to include workspace location, workspace links, active workspace changes, and selected change scope.
## Impact
- `openspec workspace open`
- Workspace prompt and agent-launch context.
- Generated or committed agent guidance for workspace mode.
- Tests for opening outside a workspace, opening a workspace by name, and opening change-scoped workspace sessions.
@@ -0,0 +1,259 @@
# Workspace POC Reference Guide
This guide is for a fresh agent starting a new session with no prior context about the workspace POC.
Root entry point: `WORKSPACE_REIMPLEMENTATION_START_HERE.md`.
The goal is not to continue the POC. The goal is to use it as research material before reimplementing workspace support cleanly from the current base.
## Reference Point
Use this exact commit as the stable reference:
```text
workspace-poc @ 79a45ac043f414e63d13e08b9da83b135cb20a39
```
Do not rely only on the moving branch name. Do not merge this commit into the implementation branch. Do not cherry-pick from it unless a later proposal explicitly decides that a small piece should be preserved.
## What The POC Was Trying To Prove
Start from the user journey:
```text
create workspace
-> add repos
-> open workspace with an agent
-> explore across repos
-> create a proposal
-> apply one repo slice
-> verify
-> archive
```
The POC is useful if it helps answer:
- What did the user experience feel like when workspace mode worked?
- Which CLI surfaces made the workflow easier to understand?
- Which tests captured real product expectations?
- Which implementation choices were shortcuts that should not survive?
- Which terminology became misleading once the desired product shape was clearer?
## First Files To Read
Read these from the POC commit before implementation:
```text
WORKSPACE_REIMPLEMENTATION_DIRECTION.md
WORKSPACE_POC_FOLLOWUP_NOTES.md
docs/workspace.md
docs/workspace-demo.md
docs/cli.md
src/commands/workspace.ts
src/core/workspace/open.ts
test/commands/workspace/open.test.ts
test/core/workspace/open.test.ts
test/cli-e2e/workspace/workspace-open-cli.test.ts
```
Optional deeper context:
```text
workspace-poc-explorer.html
workspace-poc-phase-playground.html
copilot-session-d4e9c61e-readable.md
copilot-session-d4e9c61e-timeline.md
```
The optional files are historical research aids. Use them to understand how the POC evolved, not as implementation requirements.
## How To Inspect The POC Safely
Preferred approach: use a separate worktree or read files directly from the pinned commit.
Example direct reads:
```bash
git show 79a45ac043f414e63d13e08b9da83b135cb20a39:WORKSPACE_REIMPLEMENTATION_DIRECTION.md
git show 79a45ac043f414e63d13e08b9da83b135cb20a39:src/commands/workspace.ts
git diff origin/main...79a45ac043f414e63d13e08b9da83b135cb20a39 --stat
```
Example separate worktree:
```bash
git worktree add ../openspec-workspace-poc 79a45ac043f414e63d13e08b9da83b135cb20a39
```
Keep the implementation branch based on the current target branch. The POC worktree is for reading and running tests only.
## What To Bring Back
Before implementing a slice, come back with a short POC findings note:
```text
POC findings for <slice>:
User behavior to preserve:
- ...
Tests or examples worth translating:
- ...
Implementation shortcuts to avoid:
- ...
Open design questions:
- ...
```
Put durable findings in the relevant OpenSpec proposal or design artifact. Do not leave important decisions only in chat.
## Slice-Specific Reading
### `workspace-foundation`
Focus on:
- workspace folder shape
- metadata directory naming
- local versus committed state
- stable workspace name semantics
Read:
```text
WORKSPACE_REIMPLEMENTATION_DIRECTION.md
WORKSPACE_POC_FOLLOWUP_NOTES.md
docs/workspace.md
src/commands/workspace.ts
```
Bring back:
- the storage model worth keeping
- the metadata naming decision
- any compatibility risks with repo-local `openspec/`
### `workspace-create-and-register-repos`
Focus on:
- how a user creates a workspace
- how repos or folders are linked
- what `doctor` or equivalent status output should explain
- how POC `create`/`add-repo` behavior maps to the target `setup`/`link`/`relink`/`doctor` flow before change creation
- how planning-only repos and monorepo modules differ from implementation-ready repo-local OpenSpec projects
Read:
```text
docs/workspace.md
docs/workspace-demo.md
src/commands/workspace.ts
test/commands/workspace/setup.test.ts
```
Bring back:
- expected commands
- expected files
- validation behavior for bad paths, duplicate workspace names, missing paths, planning-only links, and duplicate link names
### `workspace-open-agent-context`
Focus on:
- what context the agent receives
- how linked repos or folders become visible
- how one-session agent selection should work
- what should be stable guidance versus dynamic launch context
Read:
```text
WORKSPACE_POC_FOLLOWUP_NOTES.md
src/commands/workspace.ts
src/core/workspace/open.ts
test/commands/workspace/open.test.ts
test/core/workspace/open.test.ts
test/cli-e2e/workspace/workspace-open-cli.test.ts
```
Bring back:
- launch-context requirements
- agent-specific behavior to preserve
- prompt or guidance text that should become stable instructions
### `workspace-change-planning`
Focus on:
- when repo scope becomes a planning commitment
- whether targets should be inferred from artifacts
- how proposal, design, tasks, and specs should be arranged
Read:
```text
WORKSPACE_REIMPLEMENTATION_DIRECTION.md
docs/workspace.md
docs/workspace-demo.md
```
Bring back:
- the artifact shape to use
- how targets should be confirmed
- which POC target metadata ideas should be avoided or deferred
### `workspace-apply-repo-slice`
Focus on:
- the terminology decision that apply means implementation
- what context the agent needs to implement one repo slice
- why materialization should not be the user-facing contract
Read:
```text
WORKSPACE_REIMPLEMENTATION_DIRECTION.md
WORKSPACE_POC_FOLLOWUP_NOTES.md
```
Bring back:
- the normalized apply context shape
- the user-facing apply contract
- any POC materialization behavior that should be explicitly rejected
### `workspace-verify-and-archive`
Focus on:
- partial repo completion versus full workspace completion
- how verification should report gaps
- how archive should avoid forcing repo-local planning copies
Read:
```text
WORKSPACE_REIMPLEMENTATION_DIRECTION.md
docs/workspace-demo.md
```
Bring back:
- the minimum useful verify behavior
- the archive preconditions
- the distinction between repo-slice completion and workspace hard-done state
## Ground Rules
- Treat the POC as evidence, not inheritance.
- Preserve user-visible lessons before preserving code.
- Prefer current repo patterns over POC-only abstractions.
- Implement one user-visible step at a time.
- Update this roadmap when a POC lesson changes a later slice.
@@ -0,0 +1,71 @@
# Workspace Reimplementation Roadmap
This change is the continuity layer for reimplementing workspace support across multiple sessions and branches.
Root entry point for fresh agents: `WORKSPACE_REIMPLEMENTATION_START_HERE.md`.
The user journey we are implementing is:
```text
create workspace
-> add repos
-> open workspace with agent context
-> plan a cross-repo change
-> implement one repo slice
-> verify and archive
```
The POC branch is reference material only:
```text
workspace-poc @ 79a45ac043f414e63d13e08b9da83b135cb20a39
```
Use it to understand behavior, tests, and lessons learned. Do not merge it or preserve its architecture by default. The full source direction document from that branch is copied at the repository root as `WORKSPACE_REIMPLEMENTATION_DIRECTION.md`.
Fresh agents should read `POC_REFERENCE_GUIDE.md` before implementing any slice. That guide explains how to inspect the pinned POC commit, which files to read for each slice, and what findings to bring back into the OpenSpec artifacts.
## Change Order
Implement the flat sibling changes in this order:
1. `workspace-foundation`
2. `workspace-create-and-register-repos`
3. `workspace-open-agent-context`
4. `workspace-change-planning`
5. `workspace-apply-repo-slice`
6. `workspace-verify-and-archive`
OpenSpec currently discovers active changes as immediate directories under `openspec/changes/`, and change names are kebab-case identifiers. Keep these changes as flat siblings until formal change-stacking metadata is available.
## Dependency Notes
`workspace-foundation` establishes the storage, root detection, and naming model. Every later slice should build on that model instead of redefining workspace metadata.
`workspace-create-and-register-repos` creates the workspace and makes linked repos or folders visible before a change exists. Linked items may be full repos, monorepo modules, or planning-only folders. This preserves the product rule that workspace visibility is not change commitment.
`workspace-open-agent-context` gives the agent the workspace location, linked repos or folders, active changes, and selected change scope.
`workspace-change-planning` creates the workspace-level planning commitment and identifies target repo slices.
`workspace-apply-repo-slice` treats apply as implementation of one selected repo slice, not materialization of workspace planning files.
`workspace-verify-and-archive` makes cross-repo progress visible and separates partial repo completion from final workspace completion.
## Session Handoff Prompt
Use this prompt at the start of future implementation sessions:
```text
Continue the workspace reimplementation roadmap. Read
openspec/changes/workspace-reimplementation-roadmap/README.md and
openspec/changes/workspace-reimplementation-roadmap/POC_REFERENCE_GUIDE.md
first, then pick up the next unfinished flat sibling change in order. Use
workspace-poc at 79a45ac043f414e63d13e08b9da83b135cb20a39 as reference
material only. Preserve intended behavior, but reimplement cleanly from the
current base. Before editing, summarize the POC findings for the slice.
```
## Branching Guidance
Each sibling change may be implemented on its own branch or PR. Keep decisions that affect later slices in this README or in the relevant proposal so future sessions do not depend on chat history.
@@ -0,0 +1,53 @@
## Why
Workspace support needs to be reimplemented as a user-facing workflow, not carried forward as a direct port of the proof of concept.
A user should be able to say they have a multi-repo product goal, create a workspace, add the relevant repos, open that workspace with an agent, plan the change, implement one repo slice at a time, verify it, and archive it. The POC branch captured useful behavior and discovery, but its implementation should remain reference material rather than the base architecture.
This roadmap also needs to survive multiple sessions and branches. Current OpenSpec change discovery treats active changes as flat immediate directories under `openspec/changes/`, and change names are kebab-case identifiers rather than nested paths. This change is therefore a flat planning container with sibling proposal changes instead of nested child changes.
Reference material:
- `workspace-poc` at `79a45ac043f414e63d13e08b9da83b135cb20a39`
- `WORKSPACE_REIMPLEMENTATION_DIRECTION.md` on that branch
- `WORKSPACE_POC_FOLLOWUP_NOTES.md` on that branch
## What Changes
Add a lightweight roadmap for reimplementing workspace support as a stack of flat sibling OpenSpec changes:
- `workspace-foundation`
- `workspace-create-and-register-repos`
- `workspace-open-agent-context`
- `workspace-change-planning`
- `workspace-apply-repo-slice`
- `workspace-verify-and-archive`
Each sibling change owns one step in the lived user journey. Dependencies are documented in proposal prose for now. When change stacking metadata lands, this roadmap can be migrated to explicit `parent` and `dependsOn` metadata.
The intended order is:
```text
workspace-foundation
-> workspace-create-and-register-repos
-> workspace-open-agent-context
-> workspace-change-planning
-> workspace-apply-repo-slice
-> workspace-verify-and-archive
```
## Capabilities
### New Capabilities
- `workspace-reimplementation-roadmap`: Coordinates the workspace reimplementation plan across multiple flat OpenSpec changes.
### Modified Capabilities
- `openspec-conventions`: Clarifies that this workspace effort uses flat sibling changes until nested or stacked change metadata is supported.
## Impact
- Planning only in this PR.
- Future changes will affect workspace metadata, workspace CLI flows, agent context construction, workspace change planning, repo-slice application, verification, and archive behavior.
- No runtime behavior changes are introduced by this roadmap proposal.
@@ -0,0 +1,47 @@
## Why
Users need to know whether a cross-repo workspace change is complete without flattening all repo progress into one ambiguous done state.
The desired lifecycle is:
```text
Verify each repo slice.
See which slices are complete or still open.
Archive repo-local results when appropriate.
Archive the workspace change when the cross-repo goal is done.
```
Verification and archive should make the user's cross-repo status clearer, not force them to reason about internal artifact placement.
## What Changes
Add workspace-aware verify and archive behavior:
- verify workspace-level change structure and target repo status
- show per-repo slice progress
- support repo-local archive work where needed
- support explicit workspace-level archive when the coordinated goal is complete
- avoid treating partial repo completion as full workspace completion
Planning dependency:
- Depends on `workspace-apply-repo-slice`.
## Capabilities
### New Capabilities
- `workspace-verify-archive`: Verifies and archives workspace changes with per-repo progress visibility.
### Modified Capabilities
- `cli-archive`: Adds workspace-aware archive semantics.
- `opsx-verify-skill`: Adds workspace verification guidance.
- `opsx-archive-skill`: Adds workspace archive guidance.
## Impact
- Workspace status, verify, and archive behavior.
- Per-repo slice completion reporting.
- Workspace-level hard-done marker or equivalent archive state.
- Tests for partial completion, final workspace archive, and compatibility with standalone repo-local archive flows.
+8 -1
View File
@@ -5,6 +5,12 @@ context: |
Package manager: pnpm
CLI framework: Commander.js
Product language:
- Write OpenSpec proposals and specs in user-facing product behavior language
- Requirements should describe the experience, observable behavior, and product contract
- Avoid implementation-negative SHALL statements when a positive user outcome can express the same rule
- Put internal mechanisms in design.md or tasks.md unless the mechanism is itself part of the user-facing contract
Cross-platform requirements:
- This tool runs on macOS, Linux, AND Windows
- Always use path.join() or path.resolve() for file paths - never hardcode slashes
@@ -16,7 +22,8 @@ rules:
specs:
- Include scenarios for Windows path handling when dealing with file paths
- Requirements involving paths must specify cross-platform behavior
- Be explicit about mechanisms, not just outcomes (say HOW, not just WHAT)
- Prefer user-facing product behavior and observable outcomes over internal implementation mechanics
- Include HOW details only when the mechanism is part of the product contract
- If we generate artifacts, specify deletion/modification by explicit list lookup, not pattern matching
tasks:
- Add Windows CI verification as a task when changes involve file paths
@@ -77,7 +77,7 @@ We researched how similar tools handle config layering:
| **ESLint (flat)** | Single root config | *Deliberately killed cascading* - "complexity exploded exponentially" |
| **Turborepo** | Root + package extends | Per-package `turbo.json` with `extends: ["//"]` for overrides |
| **Nx** | Integrated vs Package-based | Two modes - shared root OR per-package. Hard to migrate from integrated. |
| **pnpm** | Workspace root defines scope | `pnpm-workspace.yaml` at root. Dependencies can be shared or per-package |
| **pnpm** | Workspace file defines package scope | `pnpm-workspace.yaml` at the package-set root. Dependencies can be shared or per-package |
| **Claude Code** | Global + Project | `~/.claude/` for global, `.claude/` per-project. No workspace tracking. |
| **Kiro** | Distributed per-root | Each folder has `.kiro/`. Aggregated display, no inheritance. |
+5 -2
View File
@@ -2,7 +2,6 @@
## Purpose
Define AI tool path metadata used to generate OpenSpec skills and commands in tool-specific directories.
## Requirements
### Requirement: AIToolOption skillsDir field
@@ -38,6 +37,11 @@ The `AI_TOOLS` array SHALL include `skillsDir` for tools that support the Agent
- **WHEN** looking up the `windsurf` tool
- **THEN** `skillsDir` SHALL be `.windsurf`
#### Scenario: Kimi CLI paths defined
- **WHEN** looking up the `kimi` tool
- **THEN** `skillsDir` SHALL be `.kimi`
#### Scenario: Tools without skillsDir
- **WHEN** a tool has no `skillsDir` defined
@@ -57,4 +61,3 @@ The system SHALL handle paths correctly across operating systems.
- **WHEN** constructing skill paths on macOS or Linux
- **THEN** the system SHALL use `path.join()` for consistency
+17 -3
View File
@@ -200,11 +200,11 @@ The command SHALL generate Agent Skills for selected AI tools.
### Requirement: Slash Command Generation
The command SHALL generate opsx slash commands for selected AI tools.
The command SHALL generate opsx slash commands only for selected tools that have a registered command adapter, while keeping adapterless tools valid for skill generation.
#### Scenario: Generating slash commands for a tool
#### Scenario: Generating slash commands for a tool with a registered adapter
- **WHEN** a tool is selected during initialization
- **WHEN** a tool with a registered command adapter is selected during initialization
- **THEN** create 9 slash command files using the tool's command adapter:
- `/opsx:explore`
- `/opsx:new`
@@ -218,6 +218,20 @@ The command SHALL generate opsx slash commands for selected AI tools.
- **AND** use tool-specific path conventions (e.g., `.claude/commands/opsx/` for Claude)
- **AND** include tool-specific frontmatter format
#### Scenario: Selected tool has no command adapter
- **GIVEN** a selected tool has `skillsDir` configured but no registered command adapter
- **WHEN** initialization includes command generation
- **THEN** skill generation for that tool SHALL still remain valid
- **AND** command-file generation SHALL be skipped for that tool
- **AND** the command output SHALL include `Commands skipped for: <tool-id> (no adapter)`
#### Scenario: Kimi CLI skips command-file generation
- **WHEN** the user selects Kimi CLI during initialization
- **THEN** OpenSpec SHALL treat it as a supported tool with `skillsDir: '.kimi'`
- **AND** command-file generation SHALL be skipped because no Kimi adapter is registered
### Requirement: Config File Generation
The command SHALL create an OpenSpec config file with schema settings.
@@ -245,6 +245,34 @@ OpenSpec CLI design SHALL use verbs as top-level commands with nouns provided as
- **THEN** `openspec show` and `openspec validate` SHALL accept `--type spec|change`
- **AND** the help text SHALL document this clearly
### Requirement: Workspace Product Language
OpenSpec conventions SHALL describe coordination workspaces in user-facing product terms.
#### Scenario: Describing workspace structure
- **WHEN** OpenSpec documentation describes workspace support
- **THEN** it SHALL present a workspace as the planning home for work across linked repos or folders
- **AND** it SHALL describe `changes/` as the workspace planning area
#### Scenario: Avoiding internal workspace vocabulary
- **WHEN** OpenSpec documentation explains what a workspace includes
- **THEN** it SHALL prefer plain product language such as "repos or folders"
- **AND** it SHALL avoid user-facing reliance on terms such as "working set", "code area", "entry", "alias", or "local overlay"
#### Scenario: Distinguishing workspaces from changes
- **WHEN** OpenSpec documentation explains workspace planning
- **THEN** it SHALL describe a workspace as a durable planning home
- **AND** it SHALL describe individual features, fixes, and projects as changes inside the workspace
#### Scenario: Distinguishing workspace and repo-local surfaces
- **WHEN** OpenSpec documentation compares workspace and repo-local flows
- **THEN** it SHALL explain that workspace planning lives in the workspace folder
- **AND** it SHALL explain that repo-local specs and changes continue to live under each repo's `openspec/` directory
#### Scenario: Sequencing the workspace roadmap
- **WHEN** workspace reimplementation work is split across multiple active changes
- **THEN** conventions SHALL allow those changes to remain flat siblings under `openspec/changes/`
- **AND** dependency order MAY be documented in proposal prose until formal change stacking metadata is available
## Core Principles
The system SHALL follow these principles:
+205
View File
@@ -0,0 +1,205 @@
# workspace-foundation Specification
## Purpose
Define the product and storage foundation for OpenSpec coordination workspaces,
including workspace identity, shared versus local state, managed storage,
registry behavior, stable link names, and repo ownership boundaries.
## Requirements
### Requirement: Recognizable Workspace Home
OpenSpec SHALL give users and agents a recognizable workspace home for cross-repo planning.
#### Scenario: Planning across linked repos or folders
- **WHEN** a user creates an OpenSpec workspace for repos or folders they plan across
- **THEN** the workspace SHALL provide a durable planning home
- **AND** the workspace SHALL be able to hold multiple changes over time
#### Scenario: Working from inside a workspace
- **GIVEN** a user runs OpenSpec from a workspace folder or one of its subdirectories
- **WHEN** OpenSpec resolves the current workspace
- **THEN** it SHALL identify the workspace location
- **AND** it SHALL use the workspace location's `changes/` directory as the workspace planning area
#### Scenario: Avoiding accidental workspace mode
- **GIVEN** a directory has `changes/` but is not an OpenSpec workspace
- **WHEN** OpenSpec resolves the current workspace
- **THEN** it SHALL avoid treating that directory as a workspace
- **AND** it SHALL enter workspace mode only when the workspace identity file is present
### Requirement: Stable Workspace Name
OpenSpec SHALL use one folder-style workspace name across workspace identity, managed storage, and the local registry.
#### Scenario: Using one workspace name
- **WHEN** OpenSpec creates or registers a managed workspace
- **THEN** the workspace name SHALL be stored in `.openspec-workspace/workspace.yaml`
- **AND** the same name SHALL be used as the default managed workspace folder name
- **AND** the same name SHALL be used as the local registry name
#### Scenario: Rejecting invalid folder-style names
- **WHEN** OpenSpec accepts a workspace name
- **THEN** it SHALL reject empty names, `.` or `..`, and names containing path separators
- **AND** setup or create flows SHALL report OS-level folder creation failures clearly
### Requirement: Dedicated Workspace Identity
OpenSpec SHALL distinguish a coordination workspace from a repo-local OpenSpec project.
#### Scenario: Reading workspace identity
- **WHEN** OpenSpec reads or writes workspace identity and workspace state
- **THEN** it SHALL use `.openspec-workspace/`
#### Scenario: Preserving repo-local OpenSpec projects
- **GIVEN** a repo-local OpenSpec project uses `openspec/`
- **WHEN** that repo is linked to a workspace
- **THEN** OpenSpec SHALL continue treating `openspec/` as that repo's local OpenSpec directory
- **AND** workspace planning SHALL remain anchored in the workspace folder
#### Scenario: Avoiding repo-local initialization in the workspace folder
- **WHEN** a user is working from an OpenSpec workspace folder
- **THEN** OpenSpec SHALL treat that folder as a workspace coordination surface
- **AND** users SHALL not need to initialize a repo-local `openspec/` project inside the workspace folder
### Requirement: Safe Workspace Sharing
OpenSpec SHALL keep shared workspace information separate from local machine paths.
#### Scenario: Sharing workspace planning
- **WHEN** a workspace is shared with another user or machine
- **THEN** shared workspace information SHALL include portable workspace identity and stable link names
- **AND** it SHALL not require another user to reuse the original user's absolute checkout paths
#### Scenario: Keeping checkout paths local
- **WHEN** OpenSpec stores local paths for a workspace
- **THEN** those paths SHALL be treated as local to the current machine and runtime
- **AND** another machine MAY map the same link names to different local paths
#### Scenario: Preserving runtime-local paths
- **WHEN** OpenSpec reads or writes machine-local path state
- **THEN** it SHALL preserve path strings valid for the current runtime
- **AND** it SHALL support native Windows paths and WSL2/Linux paths as local state values
#### Scenario: Excluding local state from portable collaboration
- **WHEN** OpenSpec creates a workspace
- **THEN** it SHALL exclude `.openspec-workspace/local.yaml` from portable collaboration state by default
- **AND** `.openspec-workspace/workspace.yaml` SHALL remain the portable workspace identity and link-name state
### Requirement: Standard Workspace Location
OpenSpec SHALL use a standard location for OpenSpec-managed workspaces without asking most users to choose one.
#### Scenario: Using the standard workspace location
- **WHEN** OpenSpec needs the location for OpenSpec-managed workspaces
- **THEN** it SHALL use `<global-data-dir>/workspaces`
- **AND** `<global-data-dir>` SHALL follow existing OpenSpec XDG and platform data directory behavior
#### Scenario: Avoiding workspace-specific storage overrides
- **WHEN** OpenSpec resolves the location for OpenSpec-managed workspaces
- **THEN** it SHALL not use a workspace-specific environment variable, command, or configuration setting in this slice
- **AND** managed workspace storage SHALL remain under `<global-data-dir>/workspaces`
#### Scenario: Running from native Windows
- **WHEN** OpenSpec runs from native Windows shells such as PowerShell
- **AND** `XDG_DATA_HOME` is not set
- **THEN** OpenSpec SHALL store managed workspaces under the Windows global data location
- **AND** paths SHALL follow native Windows path behavior
#### Scenario: Running from WSL2
- **WHEN** OpenSpec runs from WSL2
- **THEN** OpenSpec SHALL store managed workspaces under the Linux/XDG data location inside WSL
- **AND** paths SHALL follow Linux path behavior inside WSL
#### Scenario: Using the workspace location automatically
- **WHEN** OpenSpec creates or resolves OpenSpec-managed workspaces in later workflows
- **THEN** it SHALL use the resolved workspace location by default
- **AND** users SHALL be able to follow the normal workspace flow without choosing a storage location
#### Scenario: Showing the workspace location
- **WHEN** OpenSpec creates a workspace in the standard workspace location
- **THEN** it SHALL report the workspace location to the user
- **AND** it SHALL not hide where planning files were created
#### Scenario: Staying in the current runtime
- **WHEN** OpenSpec resolves workspace locations or local repo paths
- **THEN** it SHALL interpret paths for the runtime running OpenSpec
- **AND** Windows, UNC WSL, and WSL mount paths SHALL remain explicit user-provided paths
### Requirement: Local Workspace Registry
OpenSpec SHALL keep a lightweight local registry of known workspaces on the current machine.
#### Scenario: Recording known workspaces
- **WHEN** OpenSpec creates or learns about a managed workspace
- **THEN** it SHALL be able to record the workspace name and location in a local registry
- **AND** the registry SHALL be machine-local state
#### Scenario: Keeping workspace folders authoritative
- **WHEN** OpenSpec reads workspace details
- **THEN** each workspace folder's `.openspec-workspace/workspace.yaml` SHALL remain the source of truth for that workspace
- **AND** the local registry SHALL act only as an index of known workspace locations
#### Scenario: Finding workspaces from anywhere
- **WHEN** a later workspace command runs outside a workspace directory
- **THEN** OpenSpec MAY use the local registry to find known workspaces
- **AND** commands that need one workspace MAY use the registry to support an interactive picker
### Requirement: Stable Link Names
OpenSpec SHALL use stable link names to refer to repos and folders in workspace planning.
#### Scenario: Referring to a repo or folder in workspace planning
- **WHEN** workspace state or later workspace planning artifacts refer to a linked repo or folder
- **THEN** they SHALL use the stable link name
- **AND** the same link name SHALL remain valid even when local checkout paths differ
#### Scenario: Reusing link names across machines
- **WHEN** a workspace is used on another machine
- **THEN** link names SHALL remain stable
- **AND** local checkout paths MAY differ on that machine
#### Scenario: Rejecting invalid link names
- **WHEN** OpenSpec accepts a workspace link name
- **THEN** it SHALL reject empty names, `.` or `..`, and names containing path separators
- **AND** link names SHALL be unique within the workspace
### Requirement: Linked Repos And Folders
OpenSpec SHALL allow workspace planning to include linked repos and folders before they have repo-local OpenSpec state.
#### Scenario: Planning with a repo that has not adopted OpenSpec
- **WHEN** a workspace links a repo path that does not yet contain repo-local `openspec/`
- **THEN** the repo SHALL still be available for workspace-level planning
- **AND** implementation readiness MAY be handled by a later workflow
#### Scenario: Planning across monorepo folders
- **WHEN** planning spans multiple packages, services, apps, or directories inside one monorepo
- **THEN** the workspace SHALL be able to link those folders separately
- **AND** each folder SHALL not need its own repo-local `openspec/` directory to participate in workspace planning
#### Scenario: Treating repos and folders consistently
- **WHEN** a workspace plan includes both separate repos and folders inside a monorepo
- **THEN** OpenSpec SHALL use the same planning model for both
- **AND** users SHALL not need to create different kinds of workspace plans for multi-repo and monorepo changes
#### Scenario: Recording links without changing targets
- **WHEN** OpenSpec records a link between a workspace and a local repo or folder
- **THEN** it SHALL store the link in workspace state
- **AND** it SHALL not create, copy, move, initialize, or edit files inside the linked repo or folder
### Requirement: Planning Before Implementation
OpenSpec SHALL treat workspace creation and detection as planning setup, not implementation.
#### Scenario: Creating or detecting a workspace
- **WHEN** a workspace exists
- **THEN** OpenSpec SHALL treat it as a place for workspace-level planning
- **AND** repo implementation files SHALL remain unchanged until an explicit implementation workflow runs
#### Scenario: Deferring repo implementation
- **WHEN** repo-local implementation, apply, verify, or archive behavior is needed
- **THEN** that behavior SHALL require an explicit later workspace workflow
### Requirement: Repo Ownership Boundaries
OpenSpec SHALL keep repo ownership legible when planning happens in a workspace.
#### Scenario: Planning across owned repos
- **WHEN** a workspace plan refers to behavior owned by a repo or source area
- **THEN** that owner SHALL remain the home for canonical specs and implementation work
- **AND** the workspace SHALL make the cross-boundary plan visible without taking ownership away from that owner
#### Scenario: Drafting before ownership is clear
- **WHEN** cross-repo behavior is still being explored and ownership is not clear
- **THEN** the workspace MAY hold planning notes or draft behavior
- **AND** those drafts SHALL remain distinguishable from canonical repo-owned specs
+116 -4
View File
@@ -1,13 +1,13 @@
#!/usr/bin/env node
/**
* Postinstall script that hints about shell completions
* Postinstall script that hints about shell completions and CLI path visibility
*
* Completion installation is opt-in: the user must run
* `openspec completion install` explicitly. This script only
* prints a one-line tip after npm install.
* prints lightweight tips after npm install.
*
* The tip is suppressed when:
* The tips are suppressed when:
* - CI=true environment variable is set
* - OPENSPEC_NO_COMPLETIONS=1 environment variable is set
* - dist/ directory doesn't exist (dev setup scenario)
@@ -15,12 +15,121 @@
* The script never fails npm install - all errors are caught and handled gracefully.
*/
import { promises as fs } from 'fs';
import { constants as fsConstants, promises as fs } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const EXECUTABLE_NAMES = process.platform === 'win32'
? ['openspec.cmd', 'openspec.ps1', 'openspec']
: ['openspec'];
function getEnv(name) {
return process.env[name] || process.env[name.toUpperCase()];
}
function isTruthy(value) {
return value ? ['1', 'true', 'yes'].includes(value.toLowerCase()) : false;
}
function isLikelyGlobalInstall() {
return isTruthy(getEnv('npm_config_global')) || getEnv('npm_config_location') === 'global';
}
function normalizeForComparison(value) {
const resolved = path.resolve(value);
return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
}
function pathEntries() {
return (process.env.PATH || '')
.split(path.delimiter)
.filter(Boolean)
.map(normalizeForComparison);
}
function isOnPath(dir) {
const normalizedDir = normalizeForComparison(dir);
return pathEntries().includes(normalizedDir);
}
function addCandidateDir(dirs, dir) {
if (!dir) return;
dirs.set(normalizeForComparison(dir), dir);
}
function getPrefixBinDir(prefix) {
return process.platform === 'win32' ? prefix : path.join(prefix, 'bin');
}
function getCandidateCliBinDirs() {
const dirs = new Map();
addCandidateDir(dirs, getEnv('npm_config_global_bin_dir'));
addCandidateDir(dirs, getEnv('npm_config_bin'));
addCandidateDir(dirs, getEnv('PNPM_HOME'));
const npmPrefix = getEnv('npm_config_prefix');
if (npmPrefix) {
addCandidateDir(dirs, getPrefixBinDir(npmPrefix));
}
const bunInstall = getEnv('BUN_INSTALL');
if (bunInstall) {
addCandidateDir(dirs, path.join(bunInstall, 'bin'));
}
return [...dirs.values()];
}
async function directoryHasOpenSpecBin(dir) {
for (const executableName of EXECUTABLE_NAMES) {
try {
await fs.access(path.join(dir, executableName), fsConstants.X_OK);
return true;
} catch {
// Continue checking other executable names.
}
}
return false;
}
async function getCliBinDirsMissingFromPath() {
if (!isLikelyGlobalInstall()) {
return [];
}
const missingDirs = [];
for (const dir of getCandidateCliBinDirs()) {
if (isOnPath(dir)) continue;
if (await directoryHasOpenSpecBin(dir)) {
missingDirs.push(dir);
}
}
return missingDirs;
}
function printPathVisibilityHint(missingDirs) {
if (missingDirs.length === 0) return;
console.log('');
console.log(
'OpenSpec was installed, but this shell may not find the CLI because these bin directories are not on PATH:'
);
for (const dir of missingDirs) {
console.log(` ${dir}`);
}
console.log('');
console.log(
'If `openspec --version` fails in an editor, agent, GUI app, or automation, add the relevant package-manager bin directory to the PATH used by that environment.'
);
console.log(
'See: https://github.com/Fission-AI/OpenSpec/blob/main/docs/installation.md#troubleshooting-path-visibility'
);
}
/**
* Check if we should skip installation
@@ -71,6 +180,9 @@ async function main() {
// Completions are opt-in — just print a hint
console.log(`\nTip: Run 'openspec completion install' for shell completions`);
const missingDirs = await getCliBinDirsMissingFromPath();
printPathVisibilityHint(missingDirs);
} catch (error) {
// Fail gracefully - never break npm install
}
+43 -5
View File
@@ -1,7 +1,7 @@
#!/bin/bash
# Test script for postinstall.js
# Tests different scenarios: normal install, CI, opt-out
# Tests different scenarios: normal install, CI, opt-out, PATH hints
set -e
@@ -13,6 +13,10 @@ echo ""
# Save original environment
ORIGINAL_CI="${CI:-}"
ORIGINAL_OPENSPEC_NO_COMPLETIONS="${OPENSPEC_NO_COMPLETIONS:-}"
ORIGINAL_NPM_CONFIG_GLOBAL="${npm_config_global:-}"
ORIGINAL_NPM_CONFIG_PREFIX="${npm_config_prefix:-}"
ORIGINAL_PATH="$PATH"
NODE_BIN="$(command -v node)"
# Test 1: Normal install
echo "Test 1: Normal install (should print tip about completions)"
@@ -22,16 +26,36 @@ unset OPENSPEC_NO_COMPLETIONS
node scripts/postinstall.js
echo ""
# Test 2: CI environment (should skip silently)
echo "Test 2: CI=true (should skip silently)"
# Test 2: Global install with CLI bin missing from PATH (should print PATH hint)
echo "Test 2: Global install with CLI bin missing from PATH (should print PATH hint)"
echo "--------------------------------------"
TMP_PREFIX="$(mktemp -d)"
TMP_HOME="$(mktemp -d)"
mkdir -p "$TMP_PREFIX/bin"
printf '#!/bin/sh\nexit 0\n' > "$TMP_PREFIX/bin/openspec"
chmod +x "$TMP_PREFIX/bin/openspec"
unset CI
unset OPENSPEC_NO_COMPLETIONS
export npm_config_global=true
export npm_config_prefix="$TMP_PREFIX"
HOME="$TMP_HOME" PNPM_HOME="$TMP_HOME/no-pnpm" PATH="/usr/bin:/bin" "$NODE_BIN" scripts/postinstall.js
rm -rf "$TMP_PREFIX"
rm -rf "$TMP_HOME"
unset npm_config_global
unset npm_config_prefix
export PATH="$ORIGINAL_PATH"
echo ""
# Test 3: CI environment (should skip silently)
echo "Test 3: CI=true (should skip silently)"
echo "--------------------------------------"
export CI=true
node scripts/postinstall.js
echo "[No output expected - skipped due to CI]"
echo ""
# Test 3: Opt-out flag (should skip silently)
echo "Test 3: OPENSPEC_NO_COMPLETIONS=1 (should skip silently)"
# Test 4: Opt-out flag (should skip silently)
echo "Test 4: OPENSPEC_NO_COMPLETIONS=1 (should skip silently)"
echo "--------------------------------------"
unset CI
export OPENSPEC_NO_COMPLETIONS=1
@@ -52,6 +76,20 @@ else
unset OPENSPEC_NO_COMPLETIONS
fi
if [ -n "$ORIGINAL_NPM_CONFIG_GLOBAL" ]; then
export npm_config_global="$ORIGINAL_NPM_CONFIG_GLOBAL"
else
unset npm_config_global
fi
if [ -n "$ORIGINAL_NPM_CONFIG_PREFIX" ]; then
export npm_config_prefix="$ORIGINAL_NPM_CONFIG_PREFIX"
else
unset npm_config_prefix
fi
export PATH="$ORIGINAL_PATH"
echo "======================================"
echo "All tests completed successfully!"
echo "======================================"
+2
View File
@@ -16,6 +16,7 @@ import { CompletionCommand } from '../commands/completion.js';
import { FeedbackCommand } from '../commands/feedback.js';
import { registerConfigCommand } from '../commands/config.js';
import { registerSchemaCommand } from '../commands/schema.js';
import { registerWorkspaceCommand } from '../commands/workspace.js';
import {
statusCommand,
instructionsCommand,
@@ -285,6 +286,7 @@ program
registerSpecCommand(program);
registerConfigCommand(program);
registerSchemaCommand(program);
registerWorkspaceCommand(program);
// Top-level validate command
program
+7
View File
@@ -279,6 +279,13 @@ export class CompletionCommand {
}
break;
}
case 'schemas': {
const schemaNames = await this.completionProvider.getSchemaNames();
for (const name of schemaNames) {
console.log(`${name}\tschema`);
}
break;
}
case 'archived-changes': {
const archivedIds = await getArchivedChangeIds();
for (const id of archivedIds) {
+622
View File
@@ -0,0 +1,622 @@
import { Command } from 'commander';
import chalk from 'chalk';
import * as nodeFs from 'node:fs';
import * as path from 'node:path';
import { listWorkspaceRegistryEntries } from '../core/workspace/index.js';
import { isInteractive, resolveNoInteractive } from '../utils/interactive.js';
import {
addWorkspaceLink,
createManagedWorkspace,
inferLinkName,
loadWorkspaceForDoctor,
loadWorkspaceForList,
parseSetupLinks,
readRegistry,
resolveExistingDirectory,
updateWorkspaceLink,
validateLinkNameForCommand,
validateWorkspaceNameForSetup,
} from './workspace/operations.js';
import { selectWorkspaceForCommand } from './workspace/selection.js';
import {
WorkspaceCliError,
WorkspaceLinkMutationPayload,
WorkspaceListOutput,
WorkspaceLinkOptions,
WorkspaceListOptions,
WorkspaceOutput,
WorkspaceSetupOptions,
WorkspaceStatus,
appendStatus,
asErrorMessage,
asStatus,
} from './workspace/types.js';
function printJson(payload: unknown): void {
console.log(JSON.stringify(payload, null, 2));
}
const workspacePromptTheme = {
prefix: '',
style: {
answer: (text: string) => chalk.cyan(text),
defaultAnswer: (text: string) => chalk.dim(text),
error: (text: string) => chalk.red(text),
help: (text: string) => chalk.dim(text),
highlight: (text: string) => chalk.cyan(text),
key: (text: string) => chalk.cyan(text),
message: (text: string) => chalk.bold(text),
},
};
const workspaceSelectTheme = {
...workspacePromptTheme,
icon: {
cursor: chalk.cyan('>'),
},
style: {
...workspacePromptTheme.style,
keysHelpTip: (keys: [key: string, action: string][]) =>
chalk.dim(keys.map(([key, action]) => `${key}: ${action}`).join(' | ')),
},
};
function printWorkspaceSetupIntro(): void {
console.log(chalk.bold('Workspace setup'));
console.log('');
}
function isPromptCancellationError(error: unknown): boolean {
return (
error instanceof Error &&
(error.name === 'ExitPromptError' || error.message.includes('force closed the prompt with SIGINT'))
);
}
async function promptWorkspaceName(initialName?: string): Promise<string> {
if (initialName) {
return validateWorkspaceNameForSetup(initialName);
}
const { input } = await import('@inquirer/prompts');
console.log(chalk.bold('[1/3] Name the workspace'));
console.log(chalk.dim('Use a stable name for the repo group, e.g. platform.'));
console.log('');
return input({
message: 'Workspace name:',
required: true,
theme: workspacePromptTheme,
validate(value: string) {
try {
validateWorkspaceNameForSetup(value);
return true;
} catch {
return 'Workspace names must be kebab-case with lowercase letters, numbers, and single hyphen separators.';
}
},
});
}
async function promptExistingPath(message: string, defaultPath?: string): Promise<string> {
const { input } = await import('@inquirer/prompts');
const pathInput = await input({
message,
default: defaultPath,
prefill: defaultPath ? 'editable' : undefined,
required: true,
theme: workspacePromptTheme,
validate(value: string) {
const resolvedPath = path.isAbsolute(value)
? path.resolve(value)
: path.resolve(process.cwd(), value);
return nodeFs.existsSync(resolvedPath) && nodeFs.statSync(resolvedPath).isDirectory()
? true
: 'Enter an existing repo or folder path.';
},
});
return resolveExistingDirectory(pathInput);
}
async function promptLinkName(existingLinks: Record<string, string>): Promise<string> {
const { input } = await import('@inquirer/prompts');
return input({
message: 'Link name:',
required: true,
theme: workspacePromptTheme,
validate(value: string) {
try {
validateLinkNameForCommand(value);
} catch (error) {
return asErrorMessage(error);
}
if (existingLinks[value]) {
return `Link name '${value}' is already linked to ${existingLinks[value]}.`;
}
return true;
},
});
}
async function promptSetupLinks(): Promise<Record<string, string>> {
const { select } = await import('@inquirer/prompts');
const links: Record<string, string> = {};
console.log('');
console.log(chalk.bold('[2/3] Link repos or folders'));
console.log(chalk.dim('Start with the current directory, or enter another repo path.'));
console.log('');
while (true) {
const linkCount = Object.keys(links).length;
const resolvedPath = await promptExistingPath(
linkCount === 0 ? 'Repo or folder path:' : 'Another repo or folder path:',
linkCount === 0 ? '.' : undefined
);
let linkName = inferLinkName(resolvedPath);
try {
validateLinkNameForCommand(linkName);
} catch {
linkName = await promptLinkName(links);
}
if (links[linkName]) {
console.log(`Link name '${linkName}' is already linked to ${links[linkName]}.`);
linkName = await promptLinkName(links);
}
links[linkName] = resolvedPath;
console.log(chalk.green(`Added link '${linkName}'`));
console.log(chalk.dim(` ${resolvedPath}`));
const nextAction = await select({
message: 'Continue',
default: 'finish',
choices: [
{
name: 'Create workspace files',
short: 'Create workspace files',
value: 'finish',
description: 'Run a workspace check after setup',
},
{
name: 'Add another repo or folder',
short: 'Add another',
value: 'add',
description: 'Include another local directory in this workspace',
},
],
theme: workspaceSelectTheme,
});
if (nextAction === 'finish') {
return links;
}
}
}
function printStatusLines(statuses: WorkspaceStatus[]): void {
for (const status of statuses) {
const label = status.severity === 'warning' ? 'Warning' : 'Issue';
console.log(`${label}: ${status.message}`);
if (status.fix) {
console.log(`Fix: ${status.fix}`);
}
}
}
function printLinksHuman(links: WorkspaceOutput['links']): void {
if (links.length === 0) {
console.log(' (no linked repos or folders)');
return;
}
for (const link of links) {
const suffix = link.status.some((status) => status.severity === 'error') ? ' [issue]' : '';
console.log(` ${link.name} -> ${link.path ?? '(no local path recorded)'}${suffix}`);
if (link.repo_specs_path) {
console.log(` repo specs: ${link.repo_specs_path}`);
}
}
}
function collectWorkspaceIssues(workspace: WorkspaceListOutput): WorkspaceStatus[] {
return [
...workspace.status,
...workspace.links.flatMap((link) => link.status),
];
}
function printDoctorHuman(result: { workspace: WorkspaceOutput; status: WorkspaceStatus[] }): void {
console.log(`Workspace: ${result.workspace.name}`);
console.log(`Location: ${result.workspace.root}`);
console.log(`Planning path: ${result.workspace.planning_path}`);
console.log('');
printStatusLines(result.status);
if (result.status.length > 0) {
console.log('');
}
console.log('Linked repos or folders:');
printLinksHuman(result.workspace.links);
const issues = collectWorkspaceIssues(result.workspace);
if (issues.length === 0) {
console.log('');
console.log('No workspace issues found.');
return;
}
console.log('');
console.log('Issues:');
for (const issue of issues) {
console.log(` - ${issue.message}`);
if (issue.target) {
console.log(` Target: ${issue.target}`);
}
if (issue.fix) {
console.log(` Fix: ${issue.fix}`);
}
}
}
function printWorkspaceListHuman(workspaces: WorkspaceListOutput[]): void {
console.log(chalk.bold(`OpenSpec workspaces (${workspaces.length})`));
for (const workspace of workspaces) {
console.log('');
console.log(chalk.bold(workspace.name));
console.log(` Location: ${workspace.root}`);
if (workspace.status.length > 0) {
console.log(' Status:');
for (const status of workspace.status) {
const statusLabel = status.severity === 'warning' ? chalk.yellow('Warning') : chalk.red('Issue');
console.log(` ${statusLabel}: ${status.message}`);
if (status.fix) {
console.log(` Fix: ${status.fix}`);
}
}
}
console.log(` Linked repos or folders (${workspace.links.length}):`);
if (workspace.links.length === 0) {
console.log(chalk.dim(' (none)'));
continue;
}
for (const link of workspace.links) {
const suffix = link.status.some((status) => status.severity === 'error') ? chalk.red(' [issue]') : '';
console.log(` ${link.name} -> ${link.path ?? '(no local path recorded)'}${suffix}`);
if (link.repo_specs_path) {
console.log(chalk.dim(` repo specs: ${link.repo_specs_path}`));
}
}
}
}
function printWorkspaceCheckSummaryHuman(result: { workspace: WorkspaceOutput; status: WorkspaceStatus[] }): void {
printStatusLines(result.status);
const issues = collectWorkspaceIssues(result.workspace);
if (issues.length === 0) {
console.log(' No workspace issues found.');
return;
}
console.log(' Issues:');
for (const issue of issues) {
console.log(` - ${issue.message}`);
if (issue.target) {
console.log(` Target: ${issue.target}`);
}
if (issue.fix) {
console.log(` Fix: ${issue.fix}`);
}
}
}
function printLinkMutationHuman(
heading: string,
payload: WorkspaceLinkMutationPayload
): void {
printStatusLines(payload.status);
console.log(heading);
console.log(` ${payload.link.name} -> ${payload.link.path}`);
console.log(`Workspace: ${payload.workspace.name}`);
}
class WorkspaceCommand {
async setup(options: WorkspaceSetupOptions = {}): Promise<void> {
try {
const noInteractive = resolveNoInteractive(options);
if (options.json && !noInteractive) {
throw new WorkspaceCliError(
'workspace setup --json requires --no-interactive.',
'setup_json_requires_no_interactive',
{
fix: 'openspec workspace setup --no-interactive --json --name <name> --link <path>',
}
);
}
const interactive = !noInteractive && isInteractive(options);
if (interactive) {
printWorkspaceSetupIntro();
}
if (!interactive && (!options.name || (options.link ?? []).length === 0)) {
throw new WorkspaceCliError(
'workspace setup --no-interactive requires --name <name> and at least one --link <path>.',
'missing_setup_inputs',
{
fix: 'openspec workspace setup --no-interactive --name platform --link /path/to/repo',
}
);
}
const workspaceName = interactive
? await promptWorkspaceName(options.name)
: validateWorkspaceNameForSetup(options.name ?? '');
const links = interactive ? await promptSetupLinks() : await parseSetupLinks(options.link);
if (Object.keys(links).length === 0) {
throw new WorkspaceCliError(
'workspace setup --no-interactive requires --name <name> and at least one --link <path>.',
'missing_setup_inputs',
{
fix: 'openspec workspace setup --no-interactive --name platform --link /path/to/repo',
}
);
}
if (interactive) {
console.log('');
console.log(chalk.bold('[3/3] Create workspace files'));
}
const workspace = await createManagedWorkspace(workspaceName, links);
const doctorResult = await loadWorkspaceForDoctor({
name: workspace.name,
root: workspace.root,
status: [],
unregisteredCurrentWorkspace: false,
});
if (options.json) {
printJson({
workspace: doctorResult.workspace,
status: doctorResult.status,
});
return;
}
console.log(chalk.green('Workspace setup complete'));
console.log('');
printWorkspaceListHuman([doctorResult.workspace]);
console.log('');
console.log(`Planning path: ${doctorResult.workspace.planning_path}`);
console.log('');
console.log('Workspace check:');
printWorkspaceCheckSummaryHuman(doctorResult);
console.log('');
console.log('Next useful commands:');
console.log(` openspec workspace doctor --workspace ${workspace.name}`);
console.log(' openspec workspace list');
} catch (error) {
this.handleFailure(options.json, { workspace: null, status: [] }, error);
}
}
async list(options: WorkspaceListOptions = {}): Promise<void> {
try {
const registry = await readRegistry();
const entries = listWorkspaceRegistryEntries(registry);
const workspaces = await Promise.all(entries.map((entry) => loadWorkspaceForList(entry)));
const payload = { workspaces, status: [] as WorkspaceStatus[] };
if (options.json) {
printJson(payload);
return;
}
if (workspaces.length === 0) {
console.log("No OpenSpec workspaces found. Run 'openspec workspace setup' first.");
return;
}
printWorkspaceListHuman(workspaces);
} catch (error) {
this.handleFailure(options.json, { workspaces: [], status: [] }, error);
}
}
async link(
nameOrPath: string | undefined,
linkPath: string | undefined,
options: WorkspaceLinkOptions = {}
): Promise<void> {
try {
if (!nameOrPath) {
throw new WorkspaceCliError(
'workspace link requires a repo or folder path.',
'missing_link_path',
{
fix: 'openspec workspace link /path/to/repo',
}
);
}
const selected = await selectWorkspaceForCommand(options, 'link');
const payload = await addWorkspaceLink(selected, nameOrPath, linkPath);
if (options.json) {
printJson(payload);
return;
}
printLinkMutationHuman('Linked repo or folder:', payload);
} catch (error) {
this.handleFailure(options.json, { workspace: null, link: null, status: [] }, error);
}
}
async relink(
linkNameInput: string | undefined,
linkPath: string | undefined,
options: WorkspaceLinkOptions = {}
): Promise<void> {
try {
if (!linkNameInput || !linkPath) {
throw new WorkspaceCliError(
'workspace relink requires a link name and repo or folder path.',
'missing_relink_arguments',
{
fix: 'openspec workspace relink <name> /path/to/repo',
}
);
}
const selected = await selectWorkspaceForCommand(options, 'relink');
const payload = await updateWorkspaceLink(selected, linkNameInput, linkPath);
if (options.json) {
printJson(payload);
return;
}
printLinkMutationHuman('Relinked repo or folder:', payload);
} catch (error) {
this.handleFailure(options.json, { workspace: null, link: null, status: [] }, error);
}
}
async doctor(options: WorkspaceLinkOptions = {}): Promise<void> {
try {
const selected = await selectWorkspaceForCommand(options, 'doctor');
const result = await loadWorkspaceForDoctor(selected);
if (options.json) {
printJson(result);
return;
}
printDoctorHuman(result);
} catch (error) {
this.handleFailure(options.json, { workspace: null, status: [] }, error);
}
}
private handleFailure<T extends { status: WorkspaceStatus[] }>(
json: boolean | undefined,
payload: T,
error: unknown
): void {
if (!json && isPromptCancellationError(error)) {
console.error('Cancelled.');
process.exitCode = 130;
return;
}
if (json) {
printJson(appendStatus(payload, asStatus(error)));
process.exitCode = 1;
return;
}
const status = asStatus(error);
console.error(`Error: ${status.message}`);
if (status.fix) {
console.error(`Fix: ${status.fix}`);
}
process.exitCode = 1;
}
}
function collectOption(value: string, previous: string[]): string[] {
return [...previous, value];
}
function addWorkspaceSelectionOptions(command: Command): Command {
return command
.option('--workspace <name>', 'Workspace name from the local workspace registry')
.option('--json', 'Output as JSON')
.option('--no-interactive', 'Disable prompts');
}
export function registerWorkspaceCommand(program: Command): void {
const workspaceCommand = new WorkspaceCommand();
const workspace = program
.command('workspace')
.description('Set up and inspect coordination workspaces');
workspace
.command('setup')
.description('Set up a workspace and link existing repos or folders')
.option('--name <name>', 'Workspace name')
.option('--link <link>', 'Repo or folder link. Use <path> or <name>=<path>.', collectOption, [])
.option('--json', 'Output as JSON')
.option('--no-interactive', 'Disable prompts')
.action(async (options: WorkspaceSetupOptions) => {
await workspaceCommand.setup(options);
});
workspace
.command('list')
.description('List known OpenSpec workspaces')
.option('--json', 'Output as JSON')
.action(async (options: WorkspaceListOptions) => {
await workspaceCommand.list(options);
});
workspace
.command('ls')
.description('List known OpenSpec workspaces')
.option('--json', 'Output as JSON')
.action(async (options: WorkspaceListOptions) => {
await workspaceCommand.list(options);
});
addWorkspaceSelectionOptions(
workspace
.command('link [nameOrPath] [path]')
.description('Link an existing repo or folder to a workspace')
).action(async (
nameOrPath: string | undefined,
linkPath: string | undefined,
options: WorkspaceLinkOptions
) => {
await workspaceCommand.link(nameOrPath, linkPath, options);
});
addWorkspaceSelectionOptions(
workspace
.command('relink <name> <path>')
.description('Update the local path for an existing workspace link')
).action(async (
linkName: string | undefined,
linkPath: string | undefined,
options: WorkspaceLinkOptions
) => {
await workspaceCommand.relink(linkName, linkPath, options);
});
addWorkspaceSelectionOptions(
workspace
.command('doctor')
.description('Check what a workspace can resolve on this machine')
).action(async (options: WorkspaceLinkOptions) => {
await workspaceCommand.doctor(options);
});
// Intentionally no public `workspace create` command in this slice.
}
+703
View File
@@ -0,0 +1,703 @@
import * as nodeFs from 'node:fs';
import * as path from 'node:path';
import {
WorkspaceLocalState,
WorkspaceRegistryEntry,
WorkspaceRegistryState,
WorkspaceSharedState,
getManagedWorkspaceRoot,
getWorkspaceChangesDir,
getWorkspacePortableIgnorePatterns,
isWorkspaceRoot,
parseWorkspaceSetupLinkInput,
readOptionalWorkspaceLocalState,
readWorkspaceRegistryState,
readWorkspaceSharedState,
validateWorkspaceLinkName,
validateWorkspaceName,
writeWorkspaceLocalState,
writeWorkspaceRegistryState,
writeWorkspaceSharedState,
} from '../../core/workspace/index.js';
import { FileSystemUtils } from '../../utils/file-system.js';
import {
SelectedWorkspace,
WorkspaceCliError,
WorkspaceLinkMutationPayload,
WorkspaceLinkOutput,
WorkspaceListOutput,
WorkspaceOutput,
WorkspaceStatus,
asErrorMessage,
makeStatus,
} from './types.js';
const fs = nodeFs.promises;
function emptyRegistry(): WorkspaceRegistryState {
return { version: 1, workspaces: {} };
}
function emptyLocalState(): WorkspaceLocalState {
return { version: 1, paths: {} };
}
export async function readRegistry(): Promise<WorkspaceRegistryState> {
return (await readWorkspaceRegistryState()) ?? emptyRegistry();
}
async function recordWorkspaceInRegistry(name: string, workspaceRoot: string): Promise<void> {
const registry = await readRegistry();
const recordedWorkspaceRoot = normalizeExistingPathForStorage(workspaceRoot);
await writeWorkspaceRegistryState({
version: 1,
workspaces: {
...registry.workspaces,
[name]: recordedWorkspaceRoot,
},
});
}
export async function directoryExists(dirPath: string): Promise<boolean> {
try {
return (await fs.stat(dirPath)).isDirectory();
} catch {
return false;
}
}
async function fileExists(filePath: string): Promise<boolean> {
try {
return (await fs.stat(filePath)).isFile();
} catch {
return false;
}
}
function normalizeExistingPathForStorage(existingPath: string): string {
return process.platform === 'win32'
? FileSystemUtils.canonicalizeExistingPath(existingPath)
: existingPath;
}
export async function resolveExistingDirectory(
inputPath: string,
cwd = process.cwd()
): Promise<string> {
if (inputPath.length === 0) {
throw new WorkspaceCliError('Repo or folder path must not be empty.', 'linked_path_empty', {
target: 'link.path',
fix: 'Choose an existing repo or folder path.',
});
}
const resolvedPath = path.isAbsolute(inputPath)
? path.resolve(inputPath)
: path.resolve(cwd, inputPath);
if (!(await directoryExists(resolvedPath))) {
throw new WorkspaceCliError(
`Path '${inputPath}' is not an existing folder.`,
'linked_path_missing',
{
target: 'link.path',
fix: 'Choose an existing repo or folder path.',
}
);
}
return normalizeExistingPathForStorage(resolvedPath);
}
export function inferLinkName(absolutePath: string): string {
return path.basename(absolutePath);
}
function normalizeLinksForOutput(
sharedState: WorkspaceSharedState,
localState: WorkspaceLocalState | null
): WorkspaceLinkOutput[] {
return Object.keys(sharedState.links)
.sort((a, b) => a.localeCompare(b))
.map((name) => ({
name,
path: localState?.paths[name] ?? null,
status: [],
}));
}
function formatDuplicateLinkMessage(
linkName: string,
existingPath: string | null,
replacementPath: string
): string {
return [
`Cannot use link name '${linkName}' because another link already uses that name.`,
'Existing link:',
` ${linkName} -> ${existingPath ?? '(no local path recorded)'}`,
'',
'Choose a different link name:',
` openspec workspace link archived-${linkName} ${replacementPath}`,
'',
'If you meant to change the existing link path:',
` openspec workspace relink ${linkName} ${replacementPath}`,
].join('\n');
}
function duplicateLinkError(
linkName: string,
existingPath: string | null,
replacementPath: string
): WorkspaceCliError {
return new WorkspaceCliError(
formatDuplicateLinkMessage(linkName, existingPath, replacementPath),
'duplicate_link_name',
{
target: `links.${linkName}`,
fix: `Choose a different link name or run 'openspec workspace relink ${linkName} ${replacementPath}'.`,
}
);
}
function duplicateSetupLinkError(
linkName: string,
existingPath: string,
replacementPath: string
): WorkspaceCliError {
return new WorkspaceCliError(
[
`Cannot use link name '${linkName}' because another setup link already uses that name.`,
'Existing link:',
` ${linkName} -> ${existingPath}`,
'',
'Use explicit --link <name>=<path> values with different names.',
].join('\n'),
'duplicate_link_name',
{
target: `links.${linkName}`,
fix: `Use explicit --link ${linkName}-alt=${replacementPath} with a different link name.`,
}
);
}
export function validateWorkspaceNameForSetup(name: string): string {
try {
return validateWorkspaceName(name);
} catch {
throw new WorkspaceCliError(
'Workspace name must be kebab-case with lowercase letters, numbers, and single hyphen separators.',
'invalid_workspace_name',
{
target: 'workspace.name',
}
);
}
}
export function validateLinkNameForCommand(name: string): string {
try {
return validateWorkspaceLinkName(name);
} catch (error) {
throw new WorkspaceCliError(asErrorMessage(error), 'invalid_link_name', {
target: 'link.name',
});
}
}
function localStateInvalidStatus(error: unknown): WorkspaceStatus {
return makeStatus(
'error',
'workspace_local_state_invalid',
`Machine-local paths could not be read: ${asErrorMessage(error)}`,
{
target: 'workspace.local_state',
fix: 'Repair or remove .openspec-workspace/local.yaml, then run openspec workspace relink <name> <path> for affected links.',
}
);
}
async function readLocalStateForMutation(workspaceRoot: string): Promise<WorkspaceLocalState> {
try {
return (await readOptionalWorkspaceLocalState(workspaceRoot)) ?? emptyLocalState();
} catch (error) {
const status = localStateInvalidStatus(error);
throw new WorkspaceCliError(status.message, status.code, {
target: status.target,
fix: status.fix,
});
}
}
async function ensureWorkspaceGitignore(workspaceRoot: string): Promise<void> {
const gitignorePath = path.join(workspaceRoot, '.gitignore');
const patterns = getWorkspacePortableIgnorePatterns();
const existingContent = (await fileExists(gitignorePath))
? await fs.readFile(gitignorePath, 'utf-8')
: '';
const existingLines = new Set(
existingContent
.split(/\r?\n/u)
.map((line) => line.trim())
.filter((line) => line.length > 0)
);
const missingPatterns = patterns.filter((pattern) => !existingLines.has(pattern));
if (missingPatterns.length === 0) {
return;
}
const prefix = existingContent.length > 0 && !existingContent.endsWith('\n') ? '\n' : '';
const content = `${existingContent}${prefix}${missingPatterns.join('\n')}\n`;
await fs.writeFile(gitignorePath, content, 'utf-8');
}
export async function createManagedWorkspace(
name: string,
links: Record<string, string>
): Promise<WorkspaceOutput> {
const workspaceName = validateWorkspaceNameForSetup(name);
const workspaceRoot = getManagedWorkspaceRoot(workspaceName);
const registry = await readRegistry();
if (registry.workspaces[workspaceName]) {
throw new WorkspaceCliError(
`Workspace '${workspaceName}' is already recorded in the local workspace registry at ${registry.workspaces[workspaceName]}.`,
'workspace_already_exists',
{
target: 'workspace.name',
}
);
}
if (await directoryExists(workspaceRoot)) {
throw new WorkspaceCliError(
`Workspace '${workspaceName}' already exists at ${workspaceRoot}.`,
'workspace_already_exists',
{
target: 'workspace.root',
}
);
}
let createdWorkspaceRoot = false;
try {
await FileSystemUtils.createDirectory(path.dirname(workspaceRoot));
await fs.mkdir(workspaceRoot);
createdWorkspaceRoot = true;
await FileSystemUtils.createDirectory(getWorkspaceChangesDir(workspaceRoot));
await writeWorkspaceSharedState(workspaceRoot, {
version: 1,
name: workspaceName,
links: Object.fromEntries(Object.keys(links).map((linkName) => [linkName, {}])),
});
await writeWorkspaceLocalState(workspaceRoot, {
version: 1,
paths: links,
});
await ensureWorkspaceGitignore(workspaceRoot);
await recordWorkspaceInRegistry(workspaceName, workspaceRoot);
} catch (error) {
if (createdWorkspaceRoot) {
try {
await fs.rm(workspaceRoot, { recursive: true, force: true });
} catch {
// Preserve the original creation failure; callers can retry or inspect the path.
}
}
throw new WorkspaceCliError(
`Could not create workspace '${workspaceName}': ${asErrorMessage(error)}`,
'workspace_create_failed',
{
target: 'workspace.root',
}
);
}
return {
name: workspaceName,
root: workspaceRoot,
planning_path: getWorkspaceChangesDir(workspaceRoot),
links: Object.entries(links)
.sort(([a], [b]) => a.localeCompare(b))
.map(([linkName, linkPath]) => ({
name: linkName,
path: linkPath,
status: [],
})),
status: [],
};
}
export async function parseSetupLinks(
linkInputs: string[] | undefined
): Promise<Record<string, string>> {
const links: Record<string, string> = {};
for (const rawLink of linkInputs ?? []) {
const parsed = await parseWorkspaceSetupLinkInput(rawLink);
const resolvedPath = await resolveExistingDirectory(parsed.pathInput);
const linkName = validateLinkNameForCommand(parsed.name ?? inferLinkName(resolvedPath));
if (links[linkName]) {
throw duplicateSetupLinkError(linkName, links[linkName], resolvedPath);
}
links[linkName] = resolvedPath;
}
return links;
}
export async function loadWorkspaceForList(
entry: WorkspaceRegistryEntry
): Promise<WorkspaceListOutput> {
const workspaceStatus: WorkspaceStatus[] = [];
if (!(await directoryExists(entry.workspaceRoot)) || !(await isWorkspaceRoot(entry.workspaceRoot))) {
return {
name: entry.name,
root: entry.workspaceRoot,
links: [],
status: [
makeStatus('error', 'workspace_root_missing', 'Workspace location does not exist.', {
target: 'workspace.root',
fix: 'Remove or repair the local registry record.',
}),
],
};
}
let sharedState: WorkspaceSharedState;
let localState: WorkspaceLocalState | null = null;
try {
sharedState = await readWorkspaceSharedState(entry.workspaceRoot);
} catch (error) {
return {
name: entry.name,
root: entry.workspaceRoot,
links: [],
status: [
makeStatus(
'error',
'workspace_state_invalid',
`Workspace state could not be read: ${asErrorMessage(error)}`,
{
target: 'workspace.root',
fix: 'Repair the workspace state files before using this workspace.',
}
),
],
};
}
try {
localState = await readOptionalWorkspaceLocalState(entry.workspaceRoot);
} catch (error) {
workspaceStatus.push(localStateInvalidStatus(error));
}
return {
name: sharedState.name,
root: entry.workspaceRoot,
links: normalizeLinksForOutput(sharedState, localState),
status: workspaceStatus,
};
}
export async function loadWorkspaceForDoctor(
selected: SelectedWorkspace
): Promise<{ workspace: WorkspaceOutput; status: WorkspaceStatus[] }> {
const commandStatus = [...selected.status];
const workspaceStatus: WorkspaceStatus[] = [];
const planningPath = getWorkspaceChangesDir(selected.root);
if (!(await directoryExists(selected.root)) || !(await isWorkspaceRoot(selected.root))) {
return {
workspace: {
name: selected.name,
root: selected.root,
planning_path: planningPath,
links: [],
status: [
makeStatus(
'error',
'selected_workspace_root_missing',
'Selected workspace location does not exist or is not a valid workspace.',
{
target: 'workspace.root',
fix: 'Repair the local workspace registry record or choose another workspace.',
}
),
],
},
status: commandStatus,
};
}
let sharedState: WorkspaceSharedState;
let localState: WorkspaceLocalState;
let localStateInvalid = false;
try {
sharedState = await readWorkspaceSharedState(selected.root);
} catch (error) {
return {
workspace: {
name: selected.name,
root: selected.root,
planning_path: planningPath,
links: [],
status: [
makeStatus(
'error',
'workspace_state_invalid',
`Workspace state could not be read: ${asErrorMessage(error)}`,
{
target: 'workspace.root',
fix: 'Repair .openspec-workspace/workspace.yaml before using this workspace.',
}
),
],
},
status: commandStatus,
};
}
try {
const optionalLocalState = await readOptionalWorkspaceLocalState(selected.root);
localState = optionalLocalState ?? emptyLocalState();
if (!optionalLocalState) {
workspaceStatus.push(
makeStatus(
'warning',
'workspace_local_state_missing',
'Machine-local paths are not recorded yet.',
{
target: 'workspace.local_state',
fix: 'Run openspec workspace relink <name> <path> for each linked repo or folder on this machine.',
}
)
);
}
} catch (error) {
localState = emptyLocalState();
localStateInvalid = true;
workspaceStatus.push(localStateInvalidStatus(error));
}
if (!(await directoryExists(planningPath))) {
workspaceStatus.push(
makeStatus(
'error',
'workspace_planning_path_missing',
'Workspace planning path does not exist.',
{
target: 'workspace.planning_path',
fix: `Create ${planningPath} or recreate the workspace with openspec workspace setup.`,
}
)
);
}
const sharedNames = new Set(Object.keys(sharedState.links));
const localNames = new Set(Object.keys(localState.paths));
const linkNames = [...new Set([...sharedNames, ...localNames])].sort((a, b) =>
a.localeCompare(b)
);
const links: WorkspaceLinkOutput[] = [];
for (const linkName of linkNames) {
const linkStatus: WorkspaceStatus[] = [];
const localPath = localState.paths[linkName] ?? null;
let repoSpecsPath: string | null = null;
if (!sharedNames.has(linkName)) {
linkStatus.push(
makeStatus(
'warning',
'local_path_without_shared_link',
'Local path is recorded without a shared workspace link.',
{
target: `links.${linkName}`,
fix: `Add a shared link with openspec workspace link ${linkName} ${localPath ?? '/path/to/folder'} or remove the local-only path from .openspec-workspace/local.yaml.`,
}
)
);
}
if (sharedNames.has(linkName) && !localPath && !localStateInvalid) {
linkStatus.push(
makeStatus(
'error',
'linked_path_missing_from_local_state',
'Shared link does not have a local path on this machine.',
{
target: `links.${linkName}.path`,
fix: `openspec workspace relink ${linkName} /path/to/${linkName}`,
}
)
);
}
if (localPath) {
if (await directoryExists(localPath)) {
const candidateSpecsPath = path.join(localPath, 'openspec', 'specs');
repoSpecsPath = (await directoryExists(candidateSpecsPath)) ? candidateSpecsPath : null;
} else {
linkStatus.push(
makeStatus('error', 'linked_path_missing', 'Linked path does not exist.', {
target: `links.${linkName}.path`,
fix: `openspec workspace relink ${linkName} /path/to/${linkName}`,
})
);
}
}
links.push({
name: linkName,
path: localPath,
repo_specs_path: repoSpecsPath,
status: linkStatus,
});
}
return {
workspace: {
name: sharedState.name,
root: selected.root,
planning_path: planningPath,
links,
status: workspaceStatus,
},
status: commandStatus,
};
}
async function readWorkspaceForMutation(
selected: SelectedWorkspace
): Promise<{ sharedState: WorkspaceSharedState; localState: WorkspaceLocalState }> {
if (!(await directoryExists(selected.root)) || !(await isWorkspaceRoot(selected.root))) {
throw new WorkspaceCliError(
`Workspace location does not exist for '${selected.name}': ${selected.root}`,
'selected_workspace_root_missing',
{
target: 'workspace.root',
fix: 'Run openspec workspace list to inspect known workspaces.',
}
);
}
return {
sharedState: await readWorkspaceSharedState(selected.root),
localState: await readLocalStateForMutation(selected.root),
};
}
async function recordSelectedWorkspaceAfterMutation(selected: SelectedWorkspace): Promise<void> {
if (selected.unregisteredCurrentWorkspace) {
await recordWorkspaceInRegistry(selected.name, selected.root);
}
}
function buildLinkMutationPayload(
selected: SelectedWorkspace,
sharedState: WorkspaceSharedState,
localState: WorkspaceLocalState,
linkName: string,
linkPath: string
): WorkspaceLinkMutationPayload {
return {
workspace: {
name: sharedState.name,
root: selected.root,
planning_path: getWorkspaceChangesDir(selected.root),
links: normalizeLinksForOutput(sharedState, localState),
status: [],
},
link: {
name: linkName,
path: linkPath,
status: [],
},
status: selected.status,
};
}
export async function addWorkspaceLink(
selected: SelectedWorkspace,
nameOrPath: string,
linkPath?: string
): Promise<WorkspaceLinkMutationPayload> {
const explicitName = linkPath ? nameOrPath : undefined;
const pathInput = linkPath ?? nameOrPath;
const resolvedPath = await resolveExistingDirectory(pathInput);
const linkName = validateLinkNameForCommand(explicitName ?? inferLinkName(resolvedPath));
const { sharedState, localState } = await readWorkspaceForMutation(selected);
if (sharedState.links[linkName]) {
throw duplicateLinkError(linkName, localState.paths[linkName] ?? null, resolvedPath);
}
const updatedSharedState: WorkspaceSharedState = {
...sharedState,
links: {
...sharedState.links,
[linkName]: {},
},
};
const updatedLocalState: WorkspaceLocalState = {
version: 1,
paths: {
...localState.paths,
[linkName]: resolvedPath,
},
};
await writeWorkspaceSharedState(selected.root, updatedSharedState);
await writeWorkspaceLocalState(selected.root, updatedLocalState);
await recordSelectedWorkspaceAfterMutation(selected);
return buildLinkMutationPayload(
selected,
updatedSharedState,
updatedLocalState,
linkName,
resolvedPath
);
}
export async function updateWorkspaceLink(
selected: SelectedWorkspace,
linkNameInput: string,
linkPath: string
): Promise<WorkspaceLinkMutationPayload> {
const linkName = validateLinkNameForCommand(linkNameInput);
const resolvedPath = await resolveExistingDirectory(linkPath);
const { sharedState, localState } = await readWorkspaceForMutation(selected);
if (!sharedState.links[linkName]) {
throw new WorkspaceCliError(`Unknown workspace link '${linkName}'.`, 'unknown_link_name', {
target: `links.${linkName}`,
fix: 'Run openspec workspace doctor to see linked repos or folders.',
});
}
const updatedLocalState: WorkspaceLocalState = {
version: 1,
paths: {
...localState.paths,
[linkName]: resolvedPath,
},
};
await writeWorkspaceLocalState(selected.root, updatedLocalState);
await recordSelectedWorkspaceAfterMutation(selected);
return buildLinkMutationPayload(selected, sharedState, updatedLocalState, linkName, resolvedPath);
}
+127
View File
@@ -0,0 +1,127 @@
import {
findWorkspaceRoot,
listWorkspaceRegistryEntries,
readWorkspaceSharedState,
} from '../../core/workspace/index.js';
import { FileSystemUtils } from '../../utils/file-system.js';
import { isInteractive, resolveNoInteractive } from '../../utils/interactive.js';
import { readRegistry, validateWorkspaceNameForSetup } from './operations.js';
import {
SelectedWorkspace,
WorkspaceCliError,
WorkspaceSelectionOptions,
makeStatus,
} from './types.js';
function normalizeRegistryRootForComparison(workspaceRoot: string): string {
return process.platform === 'win32'
? FileSystemUtils.canonicalizeExistingPath(workspaceRoot)
: workspaceRoot;
}
export async function selectWorkspaceForCommand(
options: WorkspaceSelectionOptions,
commandName: string
): Promise<SelectedWorkspace> {
const registry = await readRegistry();
if (options.workspace) {
const workspaceName = validateWorkspaceNameForSetup(options.workspace);
const registryRoot = registry.workspaces[workspaceName];
if (!registryRoot) {
throw new WorkspaceCliError(
`Unknown OpenSpec workspace '${workspaceName}'.`,
'workspace_not_found',
{
target: 'workspace.name',
fix: 'Run openspec workspace list to see known workspaces.',
}
);
}
return {
name: workspaceName,
root: registryRoot,
status: [],
unregisteredCurrentWorkspace: false,
};
}
const currentWorkspaceRoot = await findWorkspaceRoot(process.cwd());
if (currentWorkspaceRoot) {
const sharedState = await readWorkspaceSharedState(currentWorkspaceRoot);
const registeredRoot = registry.workspaces[sharedState.name];
const isRegistered =
registeredRoot !== undefined &&
normalizeRegistryRootForComparison(registeredRoot) === currentWorkspaceRoot;
const warning = makeStatus(
'warning',
'workspace_not_in_local_registry',
'This workspace is not recorded in the local workspace registry.',
{
target: 'workspace.root',
fix: 'Run a mutating workspace command from this workspace, such as workspace link or workspace relink, to record it locally.',
}
);
return {
name: sharedState.name,
root: currentWorkspaceRoot,
status: isRegistered ? [] : [warning],
unregisteredCurrentWorkspace: !isRegistered,
};
}
const entries = listWorkspaceRegistryEntries(registry);
if (entries.length === 0) {
throw new WorkspaceCliError(
"No known OpenSpec workspaces. Run 'openspec workspace setup' first.\nAfter at least one workspace is known locally, you can also pass --workspace <name>.",
'no_known_workspaces',
{
target: 'workspace.name',
fix: 'openspec workspace setup',
}
);
}
if (entries.length === 1) {
const [entry] = entries;
return {
name: entry.name,
root: entry.workspaceRoot,
status: [],
unregisteredCurrentWorkspace: false,
};
}
if (options.json || resolveNoInteractive(options) || !isInteractive(options)) {
throw new WorkspaceCliError(
'Multiple OpenSpec workspaces are known. Pass --workspace <name>.',
'workspace_selection_ambiguous',
{
target: 'workspace.name',
fix: `openspec workspace ${commandName} --workspace <name>`,
}
);
}
const { select } = await import('@inquirer/prompts');
const selectedName = await select({
message: 'Select workspace:',
choices: entries.map((entry) => ({
name: `${entry.name} (${entry.workspaceRoot})`,
value: entry.name,
})),
});
return {
name: selectedName,
root: registry.workspaces[selectedName],
status: [],
unregisteredCurrentWorkspace: false,
};
}
+119
View File
@@ -0,0 +1,119 @@
export type StatusSeverity = 'error' | 'warning';
export interface WorkspaceStatus {
severity: StatusSeverity;
code: string;
message: string;
target?: string;
fix?: string;
}
export interface WorkspaceLinkOutput {
name: string;
path: string | null;
repo_specs_path?: string | null;
status: WorkspaceStatus[];
}
export interface WorkspaceOutput {
name: string;
root: string;
planning_path: string;
links: WorkspaceLinkOutput[];
status: WorkspaceStatus[];
}
export interface WorkspaceListOutput {
name: string;
root: string;
links: WorkspaceLinkOutput[];
status: WorkspaceStatus[];
}
export interface WorkspaceSetupOptions {
name?: string;
link?: string[];
json?: boolean;
noInteractive?: boolean;
interactive?: boolean;
}
export interface WorkspaceSelectionOptions {
workspace?: string;
json?: boolean;
noInteractive?: boolean;
interactive?: boolean;
}
export type WorkspaceLinkOptions = WorkspaceSelectionOptions;
export interface WorkspaceListOptions {
json?: boolean;
}
export interface SelectedWorkspace {
name: string;
root: string;
status: WorkspaceStatus[];
unregisteredCurrentWorkspace: boolean;
}
export interface WorkspaceLinkMutationPayload {
workspace: WorkspaceOutput;
link: {
name: string;
path: string;
status: WorkspaceStatus[];
};
status: WorkspaceStatus[];
}
export class WorkspaceCliError extends Error {
readonly status: WorkspaceStatus;
constructor(message: string, code: string, options: { target?: string; fix?: string } = {}) {
super(message);
this.status = {
severity: 'error',
code,
message,
...options,
};
}
}
export function makeStatus(
severity: StatusSeverity,
code: string,
message: string,
options: { target?: string; fix?: string } = {}
): WorkspaceStatus {
return {
severity,
code,
message,
...options,
};
}
export function asErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
export function asStatus(error: unknown): WorkspaceStatus {
if (error instanceof WorkspaceCliError) {
return error.status;
}
return makeStatus('error', 'workspace_error', asErrorMessage(error));
}
export function appendStatus<T extends { status: WorkspaceStatus[] }>(
payload: T,
status: WorkspaceStatus
): T {
return {
...payload,
status: [...payload.status, status],
};
}
+100
View File
@@ -155,6 +155,106 @@ export const COMMAND_REGISTRY: CommandDefinition[] = [
},
],
},
{
name: 'workspace',
description: 'Set up and inspect coordination workspaces',
flags: [],
subcommands: [
{
name: 'setup',
description: 'Set up a workspace and link existing repos or folders',
flags: [
{
name: 'name',
description: 'Workspace name',
takesValue: true,
},
{
name: 'link',
description: 'Repo or folder link. Use <path> or <name>=<path>',
takesValue: true,
},
COMMON_FLAGS.json,
COMMON_FLAGS.noInteractive,
],
},
{
name: 'list',
description: 'List known OpenSpec workspaces',
flags: [
COMMON_FLAGS.json,
],
},
{
name: 'ls',
description: 'List known OpenSpec workspaces',
flags: [
COMMON_FLAGS.json,
],
},
{
name: 'link',
description: 'Link an existing repo or folder to a workspace',
acceptsPositional: true,
positionals: [
{
name: 'name-or-path',
type: 'path',
optional: true,
},
{
name: 'path',
type: 'path',
},
],
flags: [
{
name: 'workspace',
description: 'Workspace name from the local workspace registry',
takesValue: true,
},
COMMON_FLAGS.json,
COMMON_FLAGS.noInteractive,
],
},
{
name: 'relink',
description: 'Update the local path for an existing workspace link',
acceptsPositional: true,
positionals: [
{
name: 'name',
},
{
name: 'path',
type: 'path',
},
],
flags: [
{
name: 'workspace',
description: 'Workspace name from the local workspace registry',
takesValue: true,
},
COMMON_FLAGS.json,
COMMON_FLAGS.noInteractive,
],
},
{
name: 'doctor',
description: 'Check what a workspace can resolve on this machine',
flags: [
{
name: 'workspace',
description: 'Workspace name from the local workspace registry',
takesValue: true,
},
COMMON_FLAGS.json,
COMMON_FLAGS.noInteractive,
],
},
],
},
{
name: 'feedback',
description: 'Submit feedback about OpenSpec',
@@ -1,4 +1,5 @@
import { getActiveChangeIds, getSpecIds } from '../../utils/item-discovery.js';
import { listSchemas } from '../artifact-graph/index.js';
/**
* Cache entry for completion data
@@ -17,6 +18,7 @@ export class CompletionProvider {
private readonly cacheTTL: number;
private changeCache: CacheEntry<string[]> | null = null;
private specCache: CacheEntry<string[]> | null = null;
private schemaCache: CacheEntry<string[]> | null = null;
/**
* Creates a new completion provider
@@ -81,6 +83,31 @@ export class CompletionProvider {
return specIds;
}
/**
* Get all schema names for completion
*
* @returns Array of schema names
*/
async getSchemaNames(): Promise<string[]> {
const now = Date.now();
// Check if cache is valid
if (this.schemaCache && now - this.schemaCache.timestamp < this.cacheTTL) {
return this.schemaCache.data;
}
// Fetch fresh data
const schemaNames = listSchemas(this.projectRoot);
// Update cache
this.schemaCache = {
data: schemaNames,
timestamp: now,
};
return schemaNames;
}
/**
* Get both change and spec IDs for completion
*
@@ -101,6 +128,7 @@ export class CompletionProvider {
clearCache(): void {
this.changeCache = null;
this.specCache = null;
this.schemaCache = null;
}
/**
@@ -111,6 +139,7 @@ export class CompletionProvider {
getCacheStats(): {
changeCache: { valid: boolean; age?: number };
specCache: { valid: boolean; age?: number };
schemaCache: { valid: boolean; age?: number };
} {
const now = Date.now();
@@ -123,6 +152,10 @@ export class CompletionProvider {
valid: this.specCache !== null && now - this.specCache.timestamp < this.cacheTTL,
age: this.specCache ? now - this.specCache.timestamp : undefined,
},
schemaCache: {
valid: this.schemaCache !== null && now - this.schemaCache.timestamp < this.cacheTTL,
age: this.schemaCache ? now - this.schemaCache.timestamp : undefined,
},
};
}
}
@@ -1,4 +1,9 @@
import { CompletionGenerator, CommandDefinition, FlagDefinition } from '../types.js';
import {
CompletionGenerator,
CommandDefinition,
FlagDefinition,
PositionalDefinition,
} from '../types.js';
import { BASH_DYNAMIC_HELPERS } from '../templates/bash-templates.js';
/**
@@ -109,14 +114,14 @@ complete -F _openspec_completion openspec
for (const subcmd of cmd.subcommands) {
lines.push(`${indent} ${subcmd.name})`);
lines.push(...this.generateArgumentCompletion(subcmd, indent + ' '));
lines.push(...this.generateArgumentCompletion(subcmd, indent + ' ', 3));
lines.push(`${indent} ;;`);
}
lines.push(`${indent}esac`);
} else {
// No subcommands, just complete arguments
lines.push(...this.generateArgumentCompletion(cmd, indent));
lines.push(...this.generateArgumentCompletion(cmd, indent, 2));
}
return lines;
@@ -125,7 +130,11 @@ complete -F _openspec_completion openspec
/**
* Generate argument completion (flags and positional arguments)
*/
private generateArgumentCompletion(cmd: CommandDefinition, indent: string): string[] {
private generateArgumentCompletion(
cmd: CommandDefinition,
indent: string,
firstPositionalWordIndex: number
): string[] {
const lines: string[] = [];
// Check for flag completion
@@ -145,7 +154,14 @@ complete -F _openspec_completion openspec
}
// Handle positional completions
if (cmd.acceptsPositional) {
if (cmd.positionals && cmd.positionals.length > 0) {
lines.push(...this.generateIndexedPositionalCompletion(
cmd.positionals,
cmd.flags,
firstPositionalWordIndex,
indent
));
} else if (cmd.acceptsPositional) {
lines.push(...this.generatePositionalCompletion(cmd.positionalType, indent));
}
@@ -168,6 +184,9 @@ complete -F _openspec_completion openspec
case 'change-or-spec-id':
lines.push(`${indent}_openspec_complete_items`);
break;
case 'schema-name':
lines.push(`${indent}_openspec_complete_schemas`);
break;
case 'shell':
lines.push(`${indent}local shells="zsh bash fish powershell"`);
lines.push(`${indent}COMPREPLY=($(compgen -W "$shells" -- "$cur"))`);
@@ -180,6 +199,73 @@ complete -F _openspec_completion openspec
return lines;
}
private generateIndexedPositionalCompletion(
positionals: PositionalDefinition[],
flags: FlagDefinition[],
firstPositionalWordIndex: number,
indent: string
): string[] {
const lines: string[] = [];
const valueFlagCases = this.generateValueFlagCases(flags);
if (valueFlagCases.length > 0) {
lines.push(`${indent}case "$prev" in`);
lines.push(`${indent} ${valueFlagCases.join('|')}) return 0 ;;`);
lines.push(`${indent}esac`);
lines.push('');
}
lines.push(`${indent}local positional_index=0`);
lines.push(`${indent}local skip_next=0`);
lines.push(`${indent}local i`);
lines.push(`${indent}for ((i = ${firstPositionalWordIndex}; i < cword; i++)); do`);
lines.push(`${indent} if [[ $skip_next -eq 1 ]]; then`);
lines.push(`${indent} skip_next=0`);
lines.push(`${indent} continue`);
lines.push(`${indent} fi`);
lines.push(`${indent} case "\${words[i]}" in`);
if (valueFlagCases.length > 0) {
lines.push(`${indent} ${valueFlagCases.join('|')}) skip_next=1 ;;`);
lines.push(`${indent} ${valueFlagCases.map((flag) => `${flag}=*`).join('|')}) ;;`);
}
lines.push(`${indent} -*) ;;`);
lines.push(`${indent} *) ((positional_index++)) ;;`);
lines.push(`${indent} esac`);
lines.push(`${indent}done`);
lines.push('');
lines.push(`${indent}case "$positional_index" in`);
for (const [index, positional] of positionals.entries()) {
const completion = this.generateIndexedPositionalCase(positional, indent + ' ');
if (completion.length === 0) continue;
lines.push(`${indent} ${index})`);
lines.push(...completion);
lines.push(`${indent} ;;`);
}
lines.push(`${indent}esac`);
return lines;
}
private generateValueFlagCases(flags: FlagDefinition[]): string[] {
return flags
.filter((flag) => flag.takesValue)
.flatMap((flag) => [
`--${flag.name}`,
...(flag.short ? [`-${flag.short}`] : []),
]);
}
private generateIndexedPositionalCase(
positional: PositionalDefinition,
indent: string
): string[] {
return this.generatePositionalCompletion(positional.type, indent);
}
/**
* Escape command/subcommand names for safe use in Bash scripts
@@ -163,6 +163,9 @@ ${commandCompletions}`;
case 'change-or-spec-id':
lines.push(`complete -c openspec -n '${condition}' -a '(__fish_openspec_items)' -f`);
break;
case 'schema-name':
lines.push(`complete -c openspec -n '${condition}' -a '(__fish_openspec_schemas)' -f`);
break;
case 'shell':
lines.push(`complete -c openspec -n '${condition}' -a 'zsh bash fish powershell' -f`);
break;
@@ -1,4 +1,9 @@
import { CompletionGenerator, CommandDefinition, FlagDefinition } from '../types.js';
import {
CompletionGenerator,
CommandDefinition,
FlagDefinition,
PositionalDefinition,
} from '../types.js';
import { POWERSHELL_DYNAMIC_HELPERS } from '../templates/powershell-templates.js';
/**
@@ -123,14 +128,14 @@ Register-ArgumentCompleter -CommandName openspec -ScriptBlock $openspecCompleter
for (const subcmd of cmd.subcommands) {
lines.push(`${indent} "${subcmd.name}" {`);
lines.push(...this.generateArgumentCompletion(subcmd, indent + ' '));
lines.push(...this.generateArgumentCompletion(subcmd, indent + ' ', 3));
lines.push(`${indent} }`);
}
lines.push(`${indent}}`);
} else {
// No subcommands
lines.push(...this.generateArgumentCompletion(cmd, indent));
lines.push(...this.generateArgumentCompletion(cmd, indent, 2));
}
return lines;
@@ -139,7 +144,11 @@ Register-ArgumentCompleter -CommandName openspec -ScriptBlock $openspecCompleter
/**
* Generate argument completion (flags and positional)
*/
private generateArgumentCompletion(cmd: CommandDefinition, indent: string): string[] {
private generateArgumentCompletion(
cmd: CommandDefinition,
indent: string,
firstPositionalTokenIndex: number
): string[] {
const lines: string[] = [];
// Flag completion
@@ -167,13 +176,85 @@ Register-ArgumentCompleter -CommandName openspec -ScriptBlock $openspecCompleter
}
// Positional completion
if (cmd.acceptsPositional) {
if (cmd.positionals && cmd.positionals.length > 0) {
lines.push(...this.generateIndexedPositionalCompletion(
cmd.positionals,
cmd.flags,
firstPositionalTokenIndex,
indent
));
} else if (cmd.acceptsPositional) {
lines.push(...this.generatePositionalCompletion(cmd.positionalType, indent));
}
return lines;
}
private generateIndexedPositionalCompletion(
positionals: PositionalDefinition[],
flags: FlagDefinition[],
firstPositionalTokenIndex: number,
indent: string
): string[] {
const lines: string[] = [];
const valueFlags = this.generateValueFlags(flags);
if (valueFlags.length > 0) {
const flagList = valueFlags.map((flag) => `"${flag}"`).join(', ');
lines.push(`${indent}if (@(${flagList}) -contains $tokens[$commandCount - 2]) { return }`);
lines.push('');
}
lines.push(`${indent}$positionalIndex = 0`);
lines.push(`${indent}$skipNext = $false`);
lines.push(`${indent}for ($i = ${firstPositionalTokenIndex}; $i -lt ($commandCount - 1); $i++) {`);
lines.push(`${indent} if ($skipNext) {`);
lines.push(`${indent} $skipNext = $false`);
lines.push(`${indent} continue`);
lines.push(`${indent} }`);
lines.push(`${indent} $token = $tokens[$i]`);
if (valueFlags.length > 0) {
const flagList = valueFlags.map((flag) => `"${flag}"`).join(', ');
lines.push(`${indent} if (@(${flagList}) -contains $token) {`);
lines.push(`${indent} $skipNext = $true`);
lines.push(`${indent} continue`);
lines.push(`${indent} }`);
lines.push(`${indent} if ($token -match "^(${valueFlags.map((flag) => this.escapeRegex(flag)).join('|')})=.*") { continue }`);
}
lines.push(`${indent} if ($token -like "-*") { continue }`);
lines.push(`${indent} $positionalIndex++`);
lines.push(`${indent}}`);
lines.push('');
lines.push(`${indent}switch ($positionalIndex) {`);
for (const [index, positional] of positionals.entries()) {
const completion = this.generatePositionalCompletion(positional.type, indent + ' ');
if (completion.length === 0) continue;
lines.push(`${indent} ${index} {`);
lines.push(...completion);
lines.push(`${indent} }`);
}
lines.push(`${indent}}`);
return lines;
}
private generateValueFlags(flags: FlagDefinition[]): string[] {
return flags
.filter((flag) => flag.takesValue)
.flatMap((flag) => [
`--${flag.name}`,
...(flag.short ? [`-${flag.short}`] : []),
]);
}
private escapeRegex(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
/**
* Generate positional argument completion
*/
@@ -197,6 +278,11 @@ Register-ArgumentCompleter -CommandName openspec -ScriptBlock $openspecCompleter
lines.push(`${indent} [System.Management.Automation.CompletionResult]::new($_, $_, "ParameterValue", $_)`);
lines.push(`${indent}}`);
break;
case 'schema-name':
lines.push(`${indent}Get-OpenSpecSchemas | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {`);
lines.push(`${indent} [System.Management.Automation.CompletionResult]::new($_, $_, "ParameterValue", "Schema: $_")`);
lines.push(`${indent}}`);
break;
case 'shell':
lines.push(`${indent}$shells = @("zsh", "bash", "fish", "powershell")`);
lines.push(`${indent}$shells | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {`);
@@ -1,4 +1,9 @@
import { CompletionGenerator, CommandDefinition, FlagDefinition } from '../types.js';
import {
CompletionGenerator,
CommandDefinition,
FlagDefinition,
PositionalDefinition,
} from '../types.js';
import { ZSH_DYNAMIC_HELPERS } from '../templates/zsh-templates.js';
/**
@@ -139,16 +144,7 @@ compdef _openspec openspec
lines.push(' ' + this.generateFlagSpec(flag) + ' \\');
}
// Add positional argument completion
if (cmd.acceptsPositional) {
const positionalSpec = this.generatePositionalSpec(cmd.positionalType);
lines.push(' ' + positionalSpec);
} else {
// Remove trailing backslash from last flag
if (lines[lines.length - 1].endsWith(' \\')) {
lines[lines.length - 1] = lines[lines.length - 1].slice(0, -2);
}
}
this.appendPositionalSpecs(lines, cmd);
}
lines.push('}');
@@ -179,16 +175,7 @@ compdef _openspec openspec
lines.push(' ' + this.generateFlagSpec(flag) + ' \\');
}
// Add positional argument completion
if (subcmd.acceptsPositional) {
const positionalSpec = this.generatePositionalSpec(subcmd.positionalType);
lines.push(' ' + positionalSpec);
} else {
// Remove trailing backslash from last flag
if (lines[lines.length - 1].endsWith(' \\')) {
lines[lines.length - 1] = lines[lines.length - 1].slice(0, -2);
}
}
this.appendPositionalSpecs(lines, subcmd);
lines.push('}');
@@ -241,6 +228,8 @@ compdef _openspec openspec
return "'*: :_openspec_complete_specs'";
case 'change-or-spec-id':
return "'*: :_openspec_complete_items'";
case 'schema-name':
return "'*: :_openspec_complete_schemas'";
case 'path':
return "'*:path:_files'";
case 'shell':
@@ -250,6 +239,61 @@ compdef _openspec openspec
}
}
private appendPositionalSpecs(lines: string[], cmd: CommandDefinition): void {
const positionalSpecs = this.generatePositionalSpecs(cmd);
if (positionalSpecs.length === 0) {
if (lines[lines.length - 1].endsWith(' \\')) {
lines[lines.length - 1] = lines[lines.length - 1].slice(0, -2);
}
return;
}
for (const [index, spec] of positionalSpecs.entries()) {
const suffix = index === positionalSpecs.length - 1 ? '' : ' \\';
lines.push(' ' + spec + suffix);
}
}
private generatePositionalSpecs(cmd: CommandDefinition): string[] {
if (cmd.positionals && cmd.positionals.length > 0) {
return cmd.positionals.map((positional, index) =>
this.generateIndexedPositionalSpec(positional, index + 1)
);
}
if (cmd.acceptsPositional) {
return [this.generatePositionalSpec(cmd.positionalType)];
}
return [];
}
private generateIndexedPositionalSpec(
positional: PositionalDefinition,
index: number
): string {
const name = this.escapeDescription(positional.name);
const separator = positional.optional ? '::' : ':';
switch (positional.type) {
case 'change-id':
return `'${index}${separator}${name}:_openspec_complete_changes'`;
case 'spec-id':
return `'${index}${separator}${name}:_openspec_complete_specs'`;
case 'change-or-spec-id':
return `'${index}${separator}${name}:_openspec_complete_items'`;
case 'schema-name':
return `'${index}${separator}${name}:_openspec_complete_schemas'`;
case 'path':
return `'${index}${separator}${name}:_files'`;
case 'shell':
return `'${index}${separator}${name}:(zsh bash fish powershell)'`;
default:
return `'${index}${separator}${name}:'`;
}
}
/**
* Escape special characters in descriptions
*/
@@ -166,27 +166,6 @@ export class ZshInstaller {
}
}
/**
* Check if fpath configuration is needed for a given directory
* Used to verify if Oh My Zsh (or other) completions directory is already in fpath
*
* @param completionsDir - Directory to check for in fpath
* @returns true if configuration is needed, false if directory is already referenced
*/
private async needsFpathConfig(completionsDir: string): Promise<boolean> {
try {
const zshrcPath = this.getZshrcPath();
const content = await fs.readFile(zshrcPath, 'utf-8');
// Check if fpath already includes this directory
return !content.includes(completionsDir);
} catch (error) {
// If we can't read .zshrc, assume config is needed
console.debug(`Unable to read .zshrc to check fpath config: ${error instanceof Error ? error.message : String(error)}`);
return true;
}
}
/**
* Remove .zshrc configuration
* Used during uninstallation
@@ -287,17 +266,10 @@ export class ZshInstaller {
// Write the completion script
await fs.writeFile(targetPath, completionScript, 'utf-8');
// Auto-configure .zshrc
// Auto-configure .zshrc for standard Zsh only.
// Oh My Zsh loads custom/completions and runs compinit itself.
let zshrcConfigured = false;
if (isOhMyZsh) {
// For Oh My Zsh, verify that custom/completions is in fpath
// If not, add it to .zshrc
const needsConfig = await this.needsFpathConfig(targetDir);
if (needsConfig) {
zshrcConfigured = await this.configureZshrc(targetDir);
}
} else {
// Standard Zsh always needs .zshrc configuration
if (!isOhMyZsh) {
zshrcConfigured = await this.configureZshrc(targetDir);
}
@@ -21,4 +21,10 @@ _openspec_complete_items() {
local items
items=$(openspec __complete changes 2>/dev/null | cut -f1; openspec __complete specs 2>/dev/null | cut -f1)
COMPREPLY=($(compgen -W "$items" -- "$cur"))
}
_openspec_complete_schemas() {
local schemas
schemas=$(openspec __complete schemas 2>/dev/null | cut -f1)
COMPREPLY=($(compgen -W "$schemas" -- "$cur"))
}`;
@@ -37,4 +37,10 @@ end
function __fish_openspec_items
__fish_openspec_changes
__fish_openspec_specs
end
function __fish_openspec_schemas
openspec __complete schemas 2>/dev/null | while read -l id desc
printf '%s\\t%s\\n' "$id" "$desc"
end
end`;
@@ -22,4 +22,13 @@ function Get-OpenSpecSpecs {
}
}
}
function Get-OpenSpecSchemas {
$output = openspec __complete schemas 2>$null
if ($output) {
$output | ForEach-Object {
($_ -split "\\t")[0]
}
}
}
`;
@@ -33,4 +33,13 @@ _openspec_complete_items() {
items+=("$id:$desc")
done < <(openspec __complete specs 2>/dev/null)
_describe "item" items
}
# Use openspec __complete to get available schemas
_openspec_complete_schemas() {
local -a schemas
while IFS=$'\\t' read -r id desc; do
schemas+=("$id:$desc")
done < <(openspec __complete schemas 2>/dev/null)
_describe "schema" schemas
}`;
+34 -1
View File
@@ -30,6 +30,34 @@ export interface FlagDefinition {
values?: string[];
}
export type PositionalType =
| 'change-id'
| 'spec-id'
| 'change-or-spec-id'
| 'path'
| 'shell'
| 'schema-name';
/**
* Definition of a positional argument.
*/
export interface PositionalDefinition {
/**
* Positional name used in generated shell metadata.
*/
name: string;
/**
* Type of positional argument for dynamic completion.
*/
type?: PositionalType;
/**
* Whether this positional is optional in the CLI syntax.
*/
optional?: boolean;
}
/**
* Definition of a CLI command
*/
@@ -69,7 +97,12 @@ export interface CommandDefinition {
* - 'schema-name': Complete with available schema names
* - undefined: No specific completion
*/
positionalType?: 'change-id' | 'spec-id' | 'change-or-spec-id' | 'path' | 'shell' | 'schema-name';
positionalType?: PositionalType;
/**
* Ordered positional arguments when a command accepts more than one.
*/
positionals?: PositionalDefinition[];
}
/**
+1
View File
@@ -38,6 +38,7 @@ export const AI_TOOLS: AIToolOption[] = [
{ name: 'iFlow', value: 'iflow', available: true, successLabel: 'iFlow', skillsDir: '.iflow' },
{ name: 'Junie', value: 'junie', available: true, successLabel: 'Junie', skillsDir: '.junie' },
{ name: 'Kilo Code', value: 'kilocode', available: true, successLabel: 'Kilo Code', skillsDir: '.kilocode' },
{ name: 'Kimi CLI', value: 'kimi', available: true, successLabel: 'Kimi CLI', skillsDir: '.kimi' },
{ name: 'Kiro', value: 'kiro', available: true, successLabel: 'Kiro', skillsDir: '.kiro' },
{ name: 'OpenCode', value: 'opencode', available: true, successLabel: 'OpenCode', skillsDir: '.opencode' },
{ name: 'Pi', value: 'pi', available: true, successLabel: 'Pi', skillsDir: '.pi' },
+23 -8
View File
@@ -63,27 +63,42 @@ export function getGlobalConfigDir(): string {
* - Unix/macOS fallback: ~/.local/share/openspec/
* - Windows fallback: %LOCALAPPDATA%/openspec/
*/
export function getGlobalDataDir(): string {
export interface GlobalDataDirOptions {
env?: NodeJS.ProcessEnv;
platform?: NodeJS.Platform;
homedir?: string;
}
function joinGlobalDataPath(platform: NodeJS.Platform, ...segments: string[]): string {
return platform === 'win32'
? path.win32.join(...segments)
: path.posix.join(...segments);
}
export function getGlobalDataDir(options: GlobalDataDirOptions = {}): string {
const env = options.env ?? process.env;
const platform = options.platform ?? os.platform();
// XDG_DATA_HOME takes precedence on all platforms when explicitly set
const xdgDataHome = process.env.XDG_DATA_HOME;
const xdgDataHome = env.XDG_DATA_HOME;
if (xdgDataHome) {
return path.join(xdgDataHome, GLOBAL_DATA_DIR_NAME);
return joinGlobalDataPath(platform, xdgDataHome, GLOBAL_DATA_DIR_NAME);
}
const platform = os.platform();
const homedir = options.homedir ?? os.homedir();
if (platform === 'win32') {
// Windows: use %LOCALAPPDATA%
const localAppData = process.env.LOCALAPPDATA;
const localAppData = env.LOCALAPPDATA;
if (localAppData) {
return path.join(localAppData, GLOBAL_DATA_DIR_NAME);
return joinGlobalDataPath(platform, localAppData, GLOBAL_DATA_DIR_NAME);
}
// Fallback for Windows if LOCALAPPDATA is not set
return path.join(os.homedir(), 'AppData', 'Local', GLOBAL_DATA_DIR_NAME);
return joinGlobalDataPath(platform, homedir, 'AppData', 'Local', GLOBAL_DATA_DIR_NAME);
}
// Unix/macOS fallback: ~/.local/share
return path.join(os.homedir(), '.local', 'share', GLOBAL_DATA_DIR_NAME);
return joinGlobalDataPath(platform, homedir, '.local', 'share', GLOBAL_DATA_DIR_NAME);
}
/**
+4 -1
View File
@@ -3,10 +3,13 @@ export {
GLOBAL_CONFIG_DIR_NAME,
GLOBAL_CONFIG_FILE_NAME,
GLOBAL_DATA_DIR_NAME,
type GlobalDataDirOptions,
type GlobalConfig,
getGlobalConfigDir,
getGlobalConfigPath,
getGlobalConfig,
saveGlobalConfig,
getGlobalDataDir
} from './global-config.js';
} from './global-config.js';
export * from './workspace/index.js';
+5 -5
View File
@@ -16,7 +16,7 @@ export function normalizeRequirementName(name: string): string {
return name.trim();
}
const REQUIREMENT_HEADER_REGEX = /^###\s*Requirement:\s*(.+)\s*$/;
const REQUIREMENT_HEADER_REGEX = /^###\s*Requirement:\s*(.+)\s*$/i;
/**
* Extracts the Requirements section from a spec file and parses requirement blocks.
@@ -58,7 +58,7 @@ export function extractRequirementsSection(content: string): RequirementsSection
let preambleLines: string[] = [];
// Collect preamble lines until first requirement header
while (cursor < sectionBodyLines.length && !/^###\s+Requirement:/.test(sectionBodyLines[cursor])) {
while (cursor < sectionBodyLines.length && !REQUIREMENT_HEADER_REGEX.test(sectionBodyLines[cursor])) {
preambleLines.push(sectionBodyLines[cursor]);
cursor++;
}
@@ -76,7 +76,7 @@ export function extractRequirementsSection(content: string): RequirementsSection
cursor++;
// Gather lines until next requirement header or end of section
const bodyLines: string[] = [headerLineCandidate];
while (cursor < sectionBodyLines.length && !/^###\s+Requirement:/.test(sectionBodyLines[cursor]) && !/^##\s+/.test(sectionBodyLines[cursor])) {
while (cursor < sectionBodyLines.length && !REQUIREMENT_HEADER_REGEX.test(sectionBodyLines[cursor]) && !/^##\s+/.test(sectionBodyLines[cursor])) {
bodyLines.push(sectionBodyLines[cursor]);
cursor++;
}
@@ -176,7 +176,7 @@ function parseRequirementBlocksFromSection(sectionBody: string): RequirementBloc
let i = 0;
while (i < lines.length) {
// Seek next requirement header
while (i < lines.length && !/^###\s+Requirement:/.test(lines[i])) i++;
while (i < lines.length && !REQUIREMENT_HEADER_REGEX.test(lines[i])) i++;
if (i >= lines.length) break;
const headerLine = lines[i];
const m = headerLine.match(REQUIREMENT_HEADER_REGEX);
@@ -184,7 +184,7 @@ function parseRequirementBlocksFromSection(sectionBody: string): RequirementBloc
const name = normalizeRequirementName(m[1]);
const buf: string[] = [headerLine];
i++;
while (i < lines.length && !/^###\s+Requirement:/.test(lines[i]) && !/^##\s+/.test(lines[i])) {
while (i < lines.length && !REQUIREMENT_HEADER_REGEX.test(lines[i]) && !/^##\s+/.test(lines[i])) {
buf.push(lines[i]);
i++;
}
+1 -1
View File
@@ -1,7 +1,7 @@
const REQUIREMENTS_SECTION_HEADER = /^##\s+Requirements\s*$/i;
const TOP_LEVEL_SECTION_HEADER = /^##\s+/;
const DELTA_HEADER = /^##\s+(ADDED|MODIFIED|REMOVED|RENAMED)\s+Requirements\s*$/i;
const REQUIREMENT_HEADER = /^###\s+Requirement:\s*(.+)\s*$/;
const REQUIREMENT_HEADER = /^###\s+Requirement:\s*(.+)\s*$/i;
export interface MainSpecStructureIssue {
kind: 'delta-header' | 'requirement-outside-requirements';
+1 -1
View File
@@ -11,7 +11,7 @@ import type { Profile } from './global-config.js';
* Core workflows included in the 'core' profile.
* These provide the streamlined experience for new users.
*/
export const CORE_WORKFLOWS = ['propose', 'explore', 'apply', 'archive'] as const;
export const CORE_WORKFLOWS = ['propose', 'explore', 'apply', 'sync', 'archive'] as const;
/**
* All available workflows in the system.
+13 -2
View File
@@ -31,6 +31,13 @@ import {
} from '../templates/skill-templates.js';
import type { CommandContent } from '../command-generation/index.js';
const DEFAULT_COMPATIBILITY = 'Requires openspec CLI.';
const OPENSPEC_CLI_VISIBILITY_GUIDANCE = `## OpenSpec CLI Visibility
The workflow below uses the \`openspec\` command. If this agent shell cannot find it, do not assume OpenSpec is absent; editor, agent, GUI, and automation shells may inherit a different \`PATH\` than the user's terminal.
Use \`OPENSPEC_BIN\` when it is set, otherwise start with \`openspec\`. If that command is not found, resolve the package-manager global bin directory or ask the user for the absolute executable path, then use that path for every \`openspec\` invocation in this workflow.`;
/**
* Skill template with directory name and workflow ID mapping.
*/
@@ -129,21 +136,25 @@ export function generateSkillContent(
generatedByVersion: string,
transformInstructions?: (instructions: string) => string
): string {
const compatibility = template.compatibility || DEFAULT_COMPATIBILITY;
const instructions = transformInstructions
? transformInstructions(template.instructions)
: template.instructions;
const body = compatibility.toLowerCase().includes('openspec cli')
? `${OPENSPEC_CLI_VISIBILITY_GUIDANCE}\n\n${instructions}`
: instructions;
return `---
name: ${template.name}
description: ${template.description}
license: ${template.license || 'MIT'}
compatibility: ${template.compatibility || 'Requires openspec CLI.'}
compatibility: ${compatibility}
metadata:
author: ${template.metadata?.author || 'openspec'}
version: "${template.metadata?.version || '1.0'}"
generatedBy: "${generatedByVersion}"
---
${instructions}
${body}
`;
}
+1 -1
View File
@@ -287,7 +287,7 @@ export async function buildUpdatedSpec(
throw new Error(`${specName} MODIFIED failed for header "### Requirement: ${mod.name}" - not found`);
}
// Replace block with provided raw (ensure header line matches key)
const modHeaderMatch = mod.raw.split('\n')[0].match(/^###\s*Requirement:\s*(.+)\s*$/);
const modHeaderMatch = mod.raw.split('\n')[0].match(/^###\s*Requirement:\s*(.+)\s*$/i);
if (!modHeaderMatch || normalizeRequirementName(modHeaderMatch[1]) !== key) {
throw new Error(
`${specName} MODIFIED failed for header "### Requirement: ${mod.name}" - header mismatch in content`
+13 -6
View File
@@ -24,19 +24,26 @@ function getOnboardInstructions(): string {
## Preflight
Before starting, check if the OpenSpec CLI is installed:
Before starting, check whether the OpenSpec CLI is visible to this shell:
\`\`\`bash
# Unix/macOS
openspec --version 2>&1 || echo "CLI_NOT_INSTALLED"
OPENSPEC_CMD="\${OPENSPEC_BIN:-openspec}"
if command -v "$OPENSPEC_CMD" >/dev/null 2>&1 || [ -x "$OPENSPEC_CMD" ]; then
"$OPENSPEC_CMD" --version
else
echo "CLI_NOT_ON_PATH"
fi
# Windows (PowerShell)
# if (Get-Command openspec -ErrorAction SilentlyContinue) { openspec --version } else { echo "CLI_NOT_INSTALLED" }
# $OpenSpecCmd = if ($env:OPENSPEC_BIN) { $env:OPENSPEC_BIN } else { "openspec" }
# if (Get-Command $OpenSpecCmd -ErrorAction SilentlyContinue) { & $OpenSpecCmd --version } else { echo "CLI_NOT_ON_PATH" }
\`\`\`
**If CLI not installed:**
> OpenSpec CLI is not installed. Install it first, then come back to \`/opsx:onboard\`.
**If CLI is not visible:**
> OpenSpec CLI is not visible to this shell. If it is installed in another terminal, add its package-manager bin directory to the PATH used by this editor, agent, or automation, or set OPENSPEC_BIN to the absolute executable path.
Stop here if not installed.
Stop here if no usable CLI command can be found.
---
+26 -1
View File
@@ -34,7 +34,7 @@ import {
type LegacyDetectionResult,
} from './legacy-cleanup.js';
import { isInteractive } from '../utils/interactive.js';
import { getGlobalConfig, type Delivery } from './global-config.js';
import { getGlobalConfig, type Delivery, type Profile } from './global-config.js';
import { getProfileWorkflows, ALL_WORKFLOWS } from './profiles.js';
import { getAvailableTools } from './available-tools.js';
import {
@@ -50,6 +50,7 @@ import {
const require = createRequire(import.meta.url);
const { version: OPENSPEC_VERSION } = require('../../package.json');
const OLD_CORE_WORKFLOWS = ['propose', 'explore', 'apply', 'archive'] as const;
/**
* Options for the update command.
@@ -155,6 +156,7 @@ export class UpdateCommand {
// Still check for new tool directories and extra workflows
this.detectNewTools(resolvedProjectPath, configuredTools);
this.displayExtraWorkflowsNote(resolvedProjectPath, configuredTools, desiredWorkflows);
this.displayOldCoreCustomProfileNote(profile, globalConfig.workflows);
return;
}
@@ -282,6 +284,7 @@ export class UpdateCommand {
// 14. Display note about extra workflows not in profile
this.displayExtraWorkflowsNote(resolvedProjectPath, configuredAndNewTools, desiredWorkflows);
this.displayOldCoreCustomProfileNote(profile, globalConfig.workflows);
// 15. List affected tools
if (updatedTools.length > 0) {
@@ -369,6 +372,28 @@ export class UpdateCommand {
}
}
/**
* Suggest opting back into core when a custom profile still matches the old
* pre-sync core set. Keep custom profiles user-owned; do not mutate them.
*/
private displayOldCoreCustomProfileNote(profile: Profile, workflows?: readonly string[]): void {
if (profile !== 'custom' || !workflows) {
return;
}
const workflowSet = new Set(workflows);
const matchesOldCore =
workflowSet.size === OLD_CORE_WORKFLOWS.length &&
OLD_CORE_WORKFLOWS.every((workflow) => workflowSet.has(workflow));
if (!matchesOldCore) {
return;
}
console.log(chalk.dim('Note: The core profile now includes sync. Your custom profile is preserving the old core workflow set.'));
console.log(chalk.dim('Run `openspec config profile core` and then `openspec update` to add sync.'));
}
/**
* Removes skill directories for workflows when delivery changed to commands-only.
* Returns the number of directories removed.
+453
View File
@@ -0,0 +1,453 @@
import * as nodeFs from 'node:fs';
import * as path from 'node:path';
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
import { z } from 'zod';
import { getGlobalDataDir } from '../global-config.js';
import { FileSystemUtils } from '../../utils/file-system.js';
const fs = nodeFs.promises;
export const WORKSPACE_METADATA_DIR_NAME = '.openspec-workspace';
export const WORKSPACE_SHARED_STATE_FILE_NAME = 'workspace.yaml';
export const WORKSPACE_LOCAL_STATE_FILE_NAME = 'local.yaml';
export const WORKSPACE_CHANGES_DIR_NAME = 'changes';
export const MANAGED_WORKSPACES_DIR_NAME = 'workspaces';
export const WORKSPACE_REGISTRY_FILE_NAME = 'registry.yaml';
export const WORKSPACE_LOCAL_STATE_IGNORE_PATTERN = `${WORKSPACE_METADATA_DIR_NAME}/${WORKSPACE_LOCAL_STATE_FILE_NAME}`;
export interface WorkspaceSharedState {
version: 1;
name: string;
links: Record<string, WorkspaceLinkState>;
}
export type WorkspaceLinkState = Record<string, unknown>;
export interface WorkspaceLocalState {
version: 1;
paths: Record<string, string>;
}
export interface WorkspaceRegistryState {
version: 1;
workspaces: Record<string, string>;
}
export interface WorkspaceRegistryEntry {
name: string;
workspaceRoot: string;
}
export interface WorkspacePathOptions {
globalDataDir?: string;
}
function joinWorkspacePath(basePath: string, ...segments: string[]): string {
return FileSystemUtils.joinPath(basePath, ...segments);
}
export function getWorkspaceMetadataDir(workspaceRoot: string): string {
return joinWorkspacePath(workspaceRoot, WORKSPACE_METADATA_DIR_NAME);
}
export function getWorkspaceSharedStatePath(workspaceRoot: string): string {
return joinWorkspacePath(
getWorkspaceMetadataDir(workspaceRoot),
WORKSPACE_SHARED_STATE_FILE_NAME
);
}
export function getWorkspaceLocalStatePath(workspaceRoot: string): string {
return joinWorkspacePath(
getWorkspaceMetadataDir(workspaceRoot),
WORKSPACE_LOCAL_STATE_FILE_NAME
);
}
export function getWorkspaceChangesDir(workspaceRoot: string): string {
return joinWorkspacePath(workspaceRoot, WORKSPACE_CHANGES_DIR_NAME);
}
export function getManagedWorkspacesDir(options: WorkspacePathOptions = {}): string {
return joinWorkspacePath(options.globalDataDir ?? getGlobalDataDir(), MANAGED_WORKSPACES_DIR_NAME);
}
export function getManagedWorkspaceRoot(
workspaceName: string,
options: WorkspacePathOptions = {}
): string {
validateWorkspaceName(workspaceName);
return joinWorkspacePath(getManagedWorkspacesDir(options), workspaceName);
}
export function getWorkspaceRegistryPath(options: WorkspacePathOptions = {}): string {
return joinWorkspacePath(getManagedWorkspacesDir(options), WORKSPACE_REGISTRY_FILE_NAME);
}
export function getWorkspacePortableIgnorePatterns(): string[] {
return [WORKSPACE_LOCAL_STATE_IGNORE_PATTERN];
}
function validateFolderStyleName(name: string, label: string): string {
if (name.length === 0) {
throw new Error(`${label} must not be empty`);
}
if (name === '.' || name === '..') {
throw new Error(`${label} must not be '${name}'`);
}
if (/[\\/]/u.test(name)) {
throw new Error(`${label} must not contain path separators`);
}
return name;
}
export function validateWorkspaceName(name: string): string {
validateFolderStyleName(name, 'Workspace name');
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(name)) {
throw new Error(
'Workspace name must be kebab-case with lowercase letters, numbers, and single hyphen separators'
);
}
return name;
}
export function validateWorkspaceLinkName(name: string): string {
return validateFolderStyleName(name, 'Workspace link name');
}
export function isValidWorkspaceName(name: string): boolean {
try {
validateWorkspaceName(name);
return true;
} catch {
return false;
}
}
export function isValidWorkspaceLinkName(name: string): boolean {
try {
validateWorkspaceLinkName(name);
return true;
} catch {
return false;
}
}
async function pathIsFile(filePath: string): Promise<boolean> {
try {
return (await fs.stat(filePath)).isFile();
} catch {
return false;
}
}
async function pathIsDirectory(dirPath: string): Promise<boolean> {
try {
return (await fs.stat(dirPath)).isDirectory();
} catch {
return false;
}
}
export async function isWorkspaceRoot(candidateRoot: string): Promise<boolean> {
return pathIsFile(getWorkspaceSharedStatePath(candidateRoot));
}
async function getSearchStartDirectory(startPath: string): Promise<string> {
const resolvedStart = path.resolve(startPath);
try {
const stats = await fs.stat(resolvedStart);
return stats.isDirectory() ? resolvedStart : path.dirname(resolvedStart);
} catch {
return resolvedStart;
}
}
export async function findWorkspaceRoot(startPath = process.cwd()): Promise<string | null> {
let currentDir = await getSearchStartDirectory(startPath);
while (true) {
if (await isWorkspaceRoot(currentDir)) {
return process.platform === 'win32'
? FileSystemUtils.canonicalizeExistingPath(currentDir)
: currentDir;
}
const parentDir = path.dirname(currentDir);
if (parentDir === currentDir) {
return null;
}
currentDir = parentDir;
}
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
const PlainObjectSchema = z.custom<Record<string, unknown>>(isPlainObject, {
message: 'must be an object',
});
const SharedStateSchema = z.object({
version: z.literal(1),
name: z.string(),
links: z.record(z.string(), PlainObjectSchema),
}).strict();
const LocalStateSchema = z.object({
version: z.literal(1),
paths: z.record(z.string(), z.string()),
}).strict();
const RegistryStateSchema = z.object({
version: z.literal(1),
workspaces: z.record(z.string(), z.string()),
}).strict();
function formatZodIssues(error: z.ZodError): string {
return error.issues
.map((issue) => {
const location = issue.path.length > 0 ? issue.path.join('.') : 'root';
return `${location}: ${issue.message}`;
})
.join('; ');
}
function parseYamlObject(content: string, label: string): unknown {
try {
return parseYaml(content);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Invalid ${label}: ${message}`);
}
}
function assertValidMapKeys(
keys: string[],
validator: (name: string) => string,
label: string
): void {
for (const key of keys) {
try {
validator(key);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Invalid ${label} '${key}': ${message}`);
}
}
}
export function parseWorkspaceSharedState(content: string): WorkspaceSharedState {
const raw = parseYamlObject(content, 'workspace shared state');
const result = SharedStateSchema.safeParse(raw);
if (!result.success) {
throw new Error(`Invalid workspace shared state: ${formatZodIssues(result.error)}`);
}
validateWorkspaceName(result.data.name);
assertValidMapKeys(
Object.keys(result.data.links),
validateWorkspaceLinkName,
'workspace link name'
);
return {
version: 1,
name: result.data.name,
links: result.data.links,
};
}
export function parseWorkspaceLocalState(content: string): WorkspaceLocalState {
const raw = parseYamlObject(content, 'workspace local state');
const result = LocalStateSchema.safeParse(raw);
if (!result.success) {
throw new Error(`Invalid workspace local state: ${formatZodIssues(result.error)}`);
}
assertValidMapKeys(
Object.keys(result.data.paths),
validateWorkspaceLinkName,
'workspace local path name'
);
return {
version: 1,
paths: result.data.paths,
};
}
export function parseWorkspaceRegistryState(content: string): WorkspaceRegistryState {
const raw = parseYamlObject(content, 'workspace registry state');
const result = RegistryStateSchema.safeParse(raw);
if (!result.success) {
throw new Error(`Invalid workspace registry state: ${formatZodIssues(result.error)}`);
}
assertValidMapKeys(
Object.keys(result.data.workspaces),
validateWorkspaceName,
'workspace registry name'
);
return {
version: 1,
workspaces: result.data.workspaces,
};
}
export function serializeWorkspaceSharedState(state: WorkspaceSharedState): string {
validateWorkspaceName(state.name);
assertValidMapKeys(Object.keys(state.links), validateWorkspaceLinkName, 'workspace link name');
for (const [linkName, linkState] of Object.entries(state.links)) {
if (!isPlainObject(linkState)) {
throw new Error(`Invalid workspace link '${linkName}': link state must be an object`);
}
}
return stringifyYaml({
version: 1,
name: state.name,
links: state.links,
});
}
export function serializeWorkspaceLocalState(state: WorkspaceLocalState): string {
assertValidMapKeys(
Object.keys(state.paths),
validateWorkspaceLinkName,
'workspace local path name'
);
for (const [linkName, localPath] of Object.entries(state.paths)) {
if (typeof localPath !== 'string') {
throw new Error(`Invalid workspace local path '${linkName}': path must be a string`);
}
}
return stringifyYaml({
version: 1,
paths: state.paths,
});
}
export function serializeWorkspaceRegistryState(state: WorkspaceRegistryState): string {
assertValidMapKeys(
Object.keys(state.workspaces),
validateWorkspaceName,
'workspace registry name'
);
for (const [workspaceName, workspaceRoot] of Object.entries(state.workspaces)) {
if (typeof workspaceRoot !== 'string') {
throw new Error(`Invalid workspace registry entry '${workspaceName}': path must be a string`);
}
}
return stringifyYaml({
version: 1,
workspaces: state.workspaces,
});
}
export function listWorkspaceRegistryEntries(
registry: WorkspaceRegistryState
): WorkspaceRegistryEntry[] {
return Object.entries(registry.workspaces)
.map(([name, workspaceRoot]) => ({ name, workspaceRoot }))
.sort((a, b) => a.name.localeCompare(b.name));
}
export async function readWorkspaceSharedState(workspaceRoot: string): Promise<WorkspaceSharedState> {
return parseWorkspaceSharedState(
await fs.readFile(getWorkspaceSharedStatePath(workspaceRoot), 'utf-8')
);
}
export async function readWorkspaceLocalState(workspaceRoot: string): Promise<WorkspaceLocalState> {
return parseWorkspaceLocalState(
await fs.readFile(getWorkspaceLocalStatePath(workspaceRoot), 'utf-8')
);
}
function isFileNotFoundError(error: unknown): boolean {
return (
typeof error === 'object' &&
error !== null &&
'code' in error &&
(error as NodeJS.ErrnoException).code === 'ENOENT'
);
}
export async function readOptionalWorkspaceLocalState(
workspaceRoot: string
): Promise<WorkspaceLocalState | null> {
try {
return await readWorkspaceLocalState(workspaceRoot);
} catch (error) {
if (isFileNotFoundError(error)) {
return null;
}
throw error;
}
}
export async function writeWorkspaceSharedState(
workspaceRoot: string,
state: WorkspaceSharedState
): Promise<void> {
await FileSystemUtils.writeFile(
getWorkspaceSharedStatePath(workspaceRoot),
serializeWorkspaceSharedState(state)
);
}
export async function writeWorkspaceLocalState(
workspaceRoot: string,
state: WorkspaceLocalState
): Promise<void> {
await FileSystemUtils.writeFile(
getWorkspaceLocalStatePath(workspaceRoot),
serializeWorkspaceLocalState(state)
);
}
export async function readWorkspaceRegistryState(
options: WorkspacePathOptions = {}
): Promise<WorkspaceRegistryState | null> {
const registryPath = getWorkspaceRegistryPath(options);
if (!(await pathIsFile(registryPath))) {
return null;
}
return parseWorkspaceRegistryState(await fs.readFile(registryPath, 'utf-8'));
}
export async function writeWorkspaceRegistryState(
state: WorkspaceRegistryState,
options: WorkspacePathOptions = {}
): Promise<void> {
await FileSystemUtils.writeFile(
getWorkspaceRegistryPath(options),
serializeWorkspaceRegistryState(state)
);
}
export async function workspaceChangesDirExists(workspaceRoot: string): Promise<boolean> {
return pathIsDirectory(getWorkspaceChangesDir(workspaceRoot));
}
+2
View File
@@ -0,0 +1,2 @@
export * from './foundation.js';
export * from './link-input.js';
+51
View File
@@ -0,0 +1,51 @@
import * as nodeFs from 'node:fs';
import * as path from 'node:path';
const fs = nodeFs.promises;
export interface WorkspaceParsedLinkInput {
name?: string;
pathInput: string;
}
export interface WorkspaceLinkInputParseOptions {
cwd?: string;
}
async function directoryExists(inputPath: string, cwd: string): Promise<boolean> {
if (inputPath.length === 0) {
return false;
}
const resolvedPath = path.isAbsolute(inputPath)
? path.resolve(inputPath)
: path.resolve(cwd, inputPath);
try {
return (await fs.stat(resolvedPath)).isDirectory();
} catch {
return false;
}
}
export async function parseWorkspaceSetupLinkInput(
value: string,
options: WorkspaceLinkInputParseOptions = {}
): Promise<WorkspaceParsedLinkInput> {
const cwd = options.cwd ?? process.cwd();
if (await directoryExists(value, cwd)) {
return { pathInput: value };
}
const separatorIndex = value.indexOf('=');
if (separatorIndex === -1) {
return { pathInput: value };
}
return {
name: value.slice(0, separatorIndex),
pathInput: value.slice(separatorIndex + 1),
};
}
+3 -1
View File
@@ -134,7 +134,9 @@ describe('openspec CLI e2e basics', () => {
const result = await runCLI(['init', '--tools', 'all'], {
cwd: emptyProjectDir,
env: { CODEX_HOME: codexHome },
timeoutMs: 20000,
});
expect(result.timedOut).toBe(false);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('OpenSpec Setup Complete');
@@ -143,7 +145,7 @@ describe('openspec CLI e2e basics', () => {
const cursorSkillPath = path.join(emptyProjectDir, '.cursor/skills/openspec-explore/SKILL.md');
expect(await fileExists(claudeSkillPath)).toBe(true);
expect(await fileExists(cursorSkillPath)).toBe(true);
});
}, 25000);
it('initializes with --tools list option', async () => {
const projectDir = await prepareFixture('tmp-init');
+9
View File
@@ -244,6 +244,15 @@ describe('CompletionCommand', () => {
});
});
describe('dynamic completion data', () => {
it('should output schema names for shell completion', async () => {
await command.complete({ type: 'schemas' });
expect(consoleLogSpy).toHaveBeenCalledWith('spec-driven\tschema');
expect(process.exitCode).toBe(0);
});
});
describe('shell detection integration', () => {
it('should show appropriate error when detected shell is unsupported', async () => {
vi.mocked(shellDetection.detectShell).mockReturnValue({ shell: undefined, detected: 'tcsh' });
+24 -23
View File
@@ -64,12 +64,12 @@ describe('deriveProfileFromWorkflowSelection', () => {
it('returns custom when selection is a superset of core workflows', async () => {
const { deriveProfileFromWorkflowSelection } = await import('../../src/commands/config.js');
expect(deriveProfileFromWorkflowSelection(['propose', 'explore', 'apply', 'archive', 'new'])).toBe('custom');
expect(deriveProfileFromWorkflowSelection(['propose', 'explore', 'apply', 'sync', 'archive', 'new'])).toBe('custom');
});
it('returns core when selection has exactly core workflows in different order', async () => {
const { deriveProfileFromWorkflowSelection } = await import('../../src/commands/config.js');
expect(deriveProfileFromWorkflowSelection(['archive', 'apply', 'explore', 'propose'])).toBe('core');
expect(deriveProfileFromWorkflowSelection(['archive', 'sync', 'apply', 'explore', 'propose'])).toBe('core');
});
});
@@ -95,6 +95,7 @@ describe('config profile interactive flow', () => {
'openspec-propose',
'openspec-explore',
'openspec-apply-change',
'openspec-sync-specs',
'openspec-archive-change',
];
for (const dirName of coreSkillDirs) {
@@ -103,7 +104,7 @@ describe('config profile interactive flow', () => {
fs.writeFileSync(skillPath, `name: ${dirName}\n`, 'utf-8');
}
const coreCommands = ['propose', 'explore', 'apply', 'archive'];
const coreCommands = ['propose', 'explore', 'apply', 'sync', 'archive'];
for (const commandId of coreCommands) {
const commandPath = path.join(projectDir, '.claude', 'commands', 'opsx', `${commandId}.md`);
fs.mkdirSync(path.dirname(commandPath), { recursive: true });
@@ -111,14 +112,14 @@ describe('config profile interactive flow', () => {
}
}
function addExtraSyncWorkflowArtifacts(projectDir: string): void {
const syncSkillPath = path.join(projectDir, '.claude', 'skills', 'openspec-sync-specs', 'SKILL.md');
fs.mkdirSync(path.dirname(syncSkillPath), { recursive: true });
fs.writeFileSync(syncSkillPath, 'name: openspec-sync-specs\n', 'utf-8');
function addExtraVerifyWorkflowArtifacts(projectDir: string): void {
const verifySkillPath = path.join(projectDir, '.claude', 'skills', 'openspec-verify-change', 'SKILL.md');
fs.mkdirSync(path.dirname(verifySkillPath), { recursive: true });
fs.writeFileSync(verifySkillPath, 'name: openspec-verify-change\n', 'utf-8');
const syncCommandPath = path.join(projectDir, '.claude', 'commands', 'opsx', 'sync.md');
fs.mkdirSync(path.dirname(syncCommandPath), { recursive: true });
fs.writeFileSync(syncCommandPath, '# sync\n', 'utf-8');
const verifyCommandPath = path.join(projectDir, '.claude', 'commands', 'opsx', 'verify.md');
fs.mkdirSync(path.dirname(verifyCommandPath), { recursive: true });
fs.writeFileSync(verifyCommandPath, '# verify\n', 'utf-8');
}
beforeEach(() => {
@@ -157,7 +158,7 @@ describe('config profile interactive flow', () => {
const { saveGlobalConfig, getGlobalConfig } = await import('../../src/core/global-config.js');
const { select, checkbox } = await getPromptMocks();
saveGlobalConfig({ featureFlags: {}, profile: 'core', delivery: 'both', workflows: ['propose', 'explore', 'apply', 'archive'] });
saveGlobalConfig({ featureFlags: {}, profile: 'core', delivery: 'both', workflows: ['propose', 'explore', 'apply', 'sync', 'archive'] });
select.mockResolvedValueOnce('delivery');
select.mockResolvedValueOnce('skills');
@@ -172,7 +173,7 @@ describe('config profile interactive flow', () => {
const { saveGlobalConfig } = await import('../../src/core/global-config.js');
const { select } = await getPromptMocks();
saveGlobalConfig({ featureFlags: {}, profile: 'core', delivery: 'both', workflows: ['propose', 'explore', 'apply', 'archive'] });
saveGlobalConfig({ featureFlags: {}, profile: 'core', delivery: 'both', workflows: ['propose', 'explore', 'apply', 'sync', 'archive'] });
select.mockResolvedValueOnce('keep');
await runConfigCommand(['profile']);
@@ -200,7 +201,7 @@ describe('config profile interactive flow', () => {
const { ALL_WORKFLOWS } = await import('../../src/core/profiles.js');
const { select, checkbox } = await getPromptMocks();
saveGlobalConfig({ featureFlags: {}, profile: 'core', delivery: 'both', workflows: ['propose', 'explore', 'apply', 'archive'] });
saveGlobalConfig({ featureFlags: {}, profile: 'core', delivery: 'both', workflows: ['propose', 'explore', 'apply', 'sync', 'archive'] });
select.mockResolvedValueOnce('workflows');
checkbox.mockResolvedValueOnce(['propose', 'explore']);
@@ -244,9 +245,9 @@ describe('config profile interactive flow', () => {
const { saveGlobalConfig } = await import('../../src/core/global-config.js');
const { select, checkbox } = await getPromptMocks();
saveGlobalConfig({ featureFlags: {}, profile: 'core', delivery: 'both', workflows: ['propose', 'explore', 'apply', 'archive'] });
saveGlobalConfig({ featureFlags: {}, profile: 'core', delivery: 'both', workflows: ['propose', 'explore', 'apply', 'sync', 'archive'] });
select.mockResolvedValueOnce('workflows');
checkbox.mockResolvedValueOnce(['propose', 'explore', 'apply', 'archive']);
checkbox.mockResolvedValueOnce(['propose', 'explore', 'apply', 'sync', 'archive']);
await runConfigCommand(['profile']);
@@ -270,7 +271,7 @@ describe('config profile interactive flow', () => {
const { saveGlobalConfig, getGlobalConfigPath } = await import('../../src/core/global-config.js');
const { select, confirm } = await getPromptMocks();
saveGlobalConfig({ featureFlags: {}, profile: 'core', delivery: 'both', workflows: ['propose', 'explore', 'apply', 'archive'] });
saveGlobalConfig({ featureFlags: {}, profile: 'core', delivery: 'both', workflows: ['propose', 'explore', 'apply', 'sync', 'archive'] });
const configPath = getGlobalConfigPath();
const beforeContent = fs.readFileSync(configPath, 'utf-8');
@@ -290,7 +291,7 @@ describe('config profile interactive flow', () => {
const { saveGlobalConfig } = await import('../../src/core/global-config.js');
const { select } = await getPromptMocks();
saveGlobalConfig({ featureFlags: {}, profile: 'core', delivery: 'both', workflows: ['propose', 'explore', 'apply', 'archive'] });
saveGlobalConfig({ featureFlags: {}, profile: 'core', delivery: 'both', workflows: ['propose', 'explore', 'apply', 'sync', 'archive'] });
setupDriftedProjectArtifacts(tempDir);
select.mockResolvedValueOnce('keep');
@@ -304,7 +305,7 @@ describe('config profile interactive flow', () => {
const { saveGlobalConfig } = await import('../../src/core/global-config.js');
const { select } = await getPromptMocks();
saveGlobalConfig({ featureFlags: {}, profile: 'core', delivery: 'both', workflows: ['propose', 'explore', 'apply', 'archive'] });
saveGlobalConfig({ featureFlags: {}, profile: 'core', delivery: 'both', workflows: ['propose', 'explore', 'apply', 'sync', 'archive'] });
setupSyncedCoreBothArtifacts(tempDir);
select.mockResolvedValueOnce('keep');
@@ -318,7 +319,7 @@ describe('config profile interactive flow', () => {
const { saveGlobalConfig } = await import('../../src/core/global-config.js');
const { select, confirm } = await getPromptMocks();
saveGlobalConfig({ featureFlags: {}, profile: 'core', delivery: 'both', workflows: ['propose', 'explore', 'apply', 'archive'] });
saveGlobalConfig({ featureFlags: {}, profile: 'core', delivery: 'both', workflows: ['propose', 'explore', 'apply', 'sync', 'archive'] });
setupDriftedProjectArtifacts(tempDir);
select.mockResolvedValueOnce('delivery');
select.mockResolvedValueOnce('both');
@@ -334,9 +335,9 @@ describe('config profile interactive flow', () => {
const { saveGlobalConfig } = await import('../../src/core/global-config.js');
const { select } = await getPromptMocks();
saveGlobalConfig({ featureFlags: {}, profile: 'core', delivery: 'both', workflows: ['propose', 'explore', 'apply', 'archive'] });
saveGlobalConfig({ featureFlags: {}, profile: 'core', delivery: 'both', workflows: ['propose', 'explore', 'apply', 'sync', 'archive'] });
setupSyncedCoreBothArtifacts(tempDir);
addExtraSyncWorkflowArtifacts(tempDir);
addExtraVerifyWorkflowArtifacts(tempDir);
select.mockResolvedValueOnce('keep');
await runConfigCommand(['profile']);
@@ -349,7 +350,7 @@ describe('config profile interactive flow', () => {
const { saveGlobalConfig, getGlobalConfig } = await import('../../src/core/global-config.js');
const { select, confirm } = await getPromptMocks();
saveGlobalConfig({ featureFlags: {}, profile: 'core', delivery: 'both', workflows: ['propose', 'explore', 'apply', 'archive'] });
saveGlobalConfig({ featureFlags: {}, profile: 'core', delivery: 'both', workflows: ['propose', 'explore', 'apply', 'sync', 'archive'] });
fs.mkdirSync(path.join(tempDir, 'openspec'), { recursive: true });
select.mockResolvedValueOnce('delivery');
@@ -376,7 +377,7 @@ describe('config profile interactive flow', () => {
const config = getGlobalConfig();
expect(config.profile).toBe('core');
expect(config.delivery).toBe('skills');
expect(config.workflows).toEqual(['propose', 'explore', 'apply', 'archive']);
expect(config.workflows).toEqual(['propose', 'explore', 'apply', 'sync', 'archive']);
expect(select).not.toHaveBeenCalled();
expect(checkbox).not.toHaveBeenCalled();
expect(confirm).not.toHaveBeenCalled();
+1 -1
View File
@@ -223,7 +223,7 @@ describe('config profile command', () => {
const result = getGlobalConfig();
expect(result.profile).toBe('core');
expect(result.delivery).toBe('skills'); // preserved
expect(result.workflows).toEqual(['propose', 'explore', 'apply', 'archive']);
expect(result.workflows).toEqual(['propose', 'explore', 'apply', 'sync', 'archive']);
});
it('custom workflow selection should set profile to custom', async () => {
+276
View File
@@ -0,0 +1,276 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { Command } from 'commander';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import {
getManagedWorkspaceRoot,
getWorkspaceLocalStatePath,
parseWorkspaceLocalState,
} from '../../src/core/workspace/index.js';
vi.mock('@inquirer/prompts', () => ({
input: vi.fn(),
confirm: vi.fn(),
select: vi.fn(),
}));
async function runWorkspaceCommand(args: string[]): Promise<void> {
const { registerWorkspaceCommand } = await import('../../src/commands/workspace.js');
const program = new Command();
registerWorkspaceCommand(program);
await program.parseAsync(['node', 'openspec', 'workspace', ...args]);
}
async function getPromptMocks(): Promise<{
input: ReturnType<typeof vi.fn>;
confirm: ReturnType<typeof vi.fn>;
select: ReturnType<typeof vi.fn>;
}> {
const prompts = await import('@inquirer/prompts');
return {
input: prompts.input as unknown as ReturnType<typeof vi.fn>,
confirm: prompts.confirm as unknown as ReturnType<typeof vi.fn>,
select: prompts.select as unknown as ReturnType<typeof vi.fn>,
};
}
describe('workspace command interactive flows', () => {
let tempDir: string;
let dataHome: string;
let originalEnv: NodeJS.ProcessEnv;
let originalCwd: string;
let originalStdinTTY: boolean | undefined;
let originalExitCode: string | number | undefined;
let consoleLogSpy: ReturnType<typeof vi.spyOn>;
let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
vi.resetModules();
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'openspec-workspace-interactive-'));
dataHome = path.join(tempDir, 'data');
originalEnv = { ...process.env };
originalCwd = process.cwd();
originalStdinTTY = (process.stdin as NodeJS.ReadStream & { isTTY?: boolean }).isTTY;
originalExitCode = process.exitCode;
process.env = {
...process.env,
XDG_DATA_HOME: dataHome,
OPENSPEC_TELEMETRY: '0',
};
delete process.env.CI;
delete process.env.OPEN_SPEC_INTERACTIVE;
process.chdir(tempDir);
(process.stdin as NodeJS.ReadStream & { isTTY?: boolean }).isTTY = true;
process.exitCode = undefined;
consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
process.env = originalEnv;
process.chdir(originalCwd);
(process.stdin as NodeJS.ReadStream & { isTTY?: boolean }).isTTY = originalStdinTTY;
process.exitCode = originalExitCode;
fs.rmSync(tempDir, { recursive: true, force: true });
consoleLogSpy.mockRestore();
consoleErrorSpy.mockRestore();
vi.clearAllMocks();
});
function mkdir(relativePath: string): string {
const dir = path.join(tempDir, relativePath);
fs.mkdirSync(dir, { recursive: true });
return dir;
}
function readLocalState(workspaceName: string) {
const workspaceRoot = getManagedWorkspaceRoot(workspaceName);
return parseWorkspaceLocalState(
fs.readFileSync(getWorkspaceLocalStatePath(workspaceRoot), 'utf-8')
);
}
it('asks for the workspace name first and validates kebab-case before asking for links', async () => {
const api = mkdir('repos/api');
const { input, confirm, select } = await getPromptMocks();
input.mockImplementation(async (options: { message: string; validate?: (value: string) => true | string }) => {
if (options.message === 'Workspace name:') {
expect(options.validate?.('Bad_Name')).toBe(
'Workspace names must be kebab-case with lowercase letters, numbers, and single hyphen separators.'
);
return 'platform';
}
if (options.message === 'Repo or folder path:') {
expect(options.validate?.('missing-api')).toBe('Enter an existing repo or folder path.');
return api;
}
throw new Error(`Unexpected input prompt: ${options.message}`);
});
select.mockResolvedValueOnce('finish');
await runWorkspaceCommand(['setup']);
expect(process.exitCode).toBeUndefined();
expect(input.mock.calls.map((call) => call[0].message)).toEqual([
'Workspace name:',
'Repo or folder path:',
]);
expect(input.mock.calls[0][0]).toEqual(
expect.objectContaining({
theme: expect.objectContaining({ prefix: '' }),
})
);
expect(confirm).not.toHaveBeenCalled();
expect(select.mock.calls[0][0]).toEqual(
expect.objectContaining({
message: 'Continue',
default: 'finish',
choices: expect.arrayContaining([
expect.objectContaining({ value: 'finish' }),
expect.objectContaining({ value: 'add' }),
]),
})
);
expect(readLocalState('platform').paths).toEqual({ api });
});
it('handles prompt cancellation without printing the raw SIGINT error', async () => {
const { input } = await getPromptMocks();
const cancellationError = new Error('User force closed the prompt with SIGINT');
cancellationError.name = 'ExitPromptError';
input.mockRejectedValueOnce(cancellationError);
await runWorkspaceCommand(['setup']);
expect(process.exitCode).toBe(130);
expect(consoleErrorSpy).toHaveBeenCalledWith('Cancelled.');
expect(consoleErrorSpy).not.toHaveBeenCalledWith(
expect.stringContaining('User force closed the prompt with SIGINT')
);
});
it('lets users add another path and rename an inferred link-name conflict', async () => {
const firstApi = mkdir('repos/current/api');
const secondApi = mkdir('repos/archive/api');
const { input, confirm, select } = await getPromptMocks();
input.mockImplementation(async (options: { message: string; validate?: (value: string) => true | string }) => {
if (options.message === 'Workspace name:') {
return 'platform';
}
if (options.message === 'Repo or folder path:') {
return firstApi;
}
if (options.message === 'Another repo or folder path:') {
return secondApi;
}
if (options.message === 'Link name:') {
expect(options.validate?.('api')).toBe(`Link name 'api' is already linked to ${firstApi}.`);
expect(options.validate?.('api-archive')).toBe(true);
return 'api-archive';
}
throw new Error(`Unexpected input prompt: ${options.message}`);
});
select.mockResolvedValueOnce('add').mockResolvedValueOnce('finish');
await runWorkspaceCommand(['setup']);
expect(process.exitCode).toBeUndefined();
expect(input.mock.calls.map((call) => call[0].message)).toEqual([
'Workspace name:',
'Repo or folder path:',
'Another repo or folder path:',
'Link name:',
]);
expect(confirm).not.toHaveBeenCalled();
expect(consoleLogSpy).toHaveBeenCalledWith(
`Link name 'api' is already linked to ${firstApi}.`
);
expect(readLocalState('platform').paths).toEqual({
api: firstApi,
'api-archive': secondApi,
});
});
it('asks for a link name when the inferred basename is invalid', async () => {
const linkedRoot = path.parse(tempDir).root;
const { input, confirm, select } = await getPromptMocks();
input.mockImplementation(async (options: { message: string; validate?: (value: string) => true | string }) => {
if (options.message === 'Workspace name:') {
return 'platform';
}
if (options.message === 'Repo or folder path:') {
return linkedRoot;
}
if (options.message === 'Link name:') {
expect(options.validate?.('')).toBe('Workspace link name must not be empty');
expect(options.validate?.('root')).toBe(true);
return 'root';
}
throw new Error(`Unexpected input prompt: ${options.message}`);
});
select.mockResolvedValueOnce('finish');
await runWorkspaceCommand(['setup']);
expect(process.exitCode).toBeUndefined();
expect(input.mock.calls.map((call) => call[0].message)).toEqual([
'Workspace name:',
'Repo or folder path:',
'Link name:',
]);
expect(confirm).not.toHaveBeenCalled();
expect(readLocalState('platform').paths).toEqual({
root: linkedRoot,
});
});
it('shows an interactive workspace picker when multiple workspaces are known', async () => {
const api = mkdir('repos/api');
const web = mkdir('repos/web');
const { select } = await getPromptMocks();
await runWorkspaceCommand(['setup', '--no-interactive', '--name', 'platform', '--link', `api=${api}`]);
await runWorkspaceCommand(['setup', '--no-interactive', '--name', 'checkout-web', '--link', `web=${web}`]);
consoleLogSpy.mockClear();
select.mockResolvedValueOnce('checkout-web');
await runWorkspaceCommand(['doctor']);
expect(process.exitCode).toBeUndefined();
expect(select).toHaveBeenCalledTimes(1);
expect(select.mock.calls[0][0]).toEqual(
expect.objectContaining({
message: 'Select workspace:',
choices: expect.arrayContaining([
expect.objectContaining({
name: expect.stringContaining('platform'),
value: 'platform',
}),
expect.objectContaining({
name: expect.stringContaining('checkout-web'),
value: 'checkout-web',
}),
]),
})
);
expect(consoleLogSpy).toHaveBeenCalledWith('Workspace: checkout-web');
});
});
+910
View File
@@ -0,0 +1,910 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { COMMAND_REGISTRY } from '../../src/core/completions/command-registry.js';
import {
createManagedWorkspace,
resolveExistingDirectory,
} from '../../src/commands/workspace/operations.js';
import {
WORKSPACE_CHANGES_DIR_NAME,
WORKSPACE_LOCAL_STATE_FILE_NAME,
WORKSPACE_LOCAL_STATE_IGNORE_PATTERN,
WORKSPACE_METADATA_DIR_NAME,
WORKSPACE_SHARED_STATE_FILE_NAME,
getManagedWorkspaceRoot,
getWorkspaceLocalStatePath,
getWorkspaceRegistryPath,
getWorkspaceSharedStatePath,
parseWorkspaceLocalState,
parseWorkspaceRegistryState,
parseWorkspaceSharedState,
} from '../../src/core/workspace/index.js';
import { FileSystemUtils } from '../../src/utils/file-system.js';
import { runCLI, type RunCLIResult } from '../helpers/run-cli.js';
describe('workspace command', () => {
let tempDir: string;
let dataHome: string;
let env: NodeJS.ProcessEnv;
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'openspec-workspace-command-'));
dataHome = path.join(tempDir, 'data');
env = {
XDG_DATA_HOME: dataHome,
OPEN_SPEC_INTERACTIVE: '0',
OPENSPEC_TELEMETRY: '0',
};
});
afterEach(() => {
fs.rmSync(tempDir, { recursive: true, force: true });
});
function mkdir(relativePath: string): string {
const dir = path.join(tempDir, relativePath);
fs.mkdirSync(dir, { recursive: true });
return dir;
}
function parseJson(result: RunCLIResult): any {
try {
return JSON.parse(result.stdout);
} catch (error) {
throw new Error(
`Could not parse JSON.\nCommand: ${result.command}\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}\n${String(error)}`
);
}
}
async function setupWorkspace(name = 'platform', links: string[] = []): Promise<any> {
const result = await runCLI(
['workspace', 'setup', '--no-interactive', '--json', '--name', name, ...links.flatMap((link) => ['--link', link])],
{ cwd: tempDir, env }
);
expect(result.exitCode).toBe(0);
return parseJson(result);
}
function readLocalState(workspaceRoot: string) {
return parseWorkspaceLocalState(
fs.readFileSync(getWorkspaceLocalStatePath(workspaceRoot), 'utf-8')
);
}
function readSharedState(workspaceRoot: string) {
return parseWorkspaceSharedState(
fs.readFileSync(getWorkspaceSharedStatePath(workspaceRoot), 'utf-8')
);
}
it('sets up a workspace with required links, records local state, and lists it through ls', async () => {
const api = mkdir('repos/api');
mkdir('repos/api/openspec/specs');
const checkout = mkdir('repos/platform/apps/checkout');
const setup = await setupWorkspace('platform', [`api=${api}`, checkout]);
expect(setup.status).toEqual([]);
expect(setup.workspace.name).toBe('platform');
expect(setup.workspace.links).toEqual([
expect.objectContaining({
name: 'api',
path: api,
repo_specs_path: path.join(api, 'openspec', 'specs'),
status: [],
}),
expect.objectContaining({
name: 'checkout',
path: checkout,
repo_specs_path: null,
status: [],
}),
]);
const workspaceRoot = setup.workspace.root;
const sharedState = parseWorkspaceSharedState(
fs.readFileSync(getWorkspaceSharedStatePath(workspaceRoot), 'utf-8')
);
const localState = parseWorkspaceLocalState(
fs.readFileSync(getWorkspaceLocalStatePath(workspaceRoot), 'utf-8')
);
const registry = parseWorkspaceRegistryState(
fs.readFileSync(
getWorkspaceRegistryPath({ globalDataDir: path.join(dataHome, 'openspec') }),
'utf-8'
)
);
expect(sharedState).toEqual({
version: 1,
name: 'platform',
links: {
api: {},
checkout: {},
},
});
expect(localState.paths).toEqual({
api,
checkout,
});
expect(registry.workspaces.platform).toBe(workspaceRoot);
expect(fs.readFileSync(path.join(workspaceRoot, '.gitignore'), 'utf-8')).toContain(
WORKSPACE_LOCAL_STATE_IGNORE_PATTERN
);
const list = await runCLI(['workspace', 'ls', '--json'], { cwd: tempDir, env });
expect(list.exitCode).toBe(0);
const listPayload = parseJson(list);
expect(listPayload.workspaces).toEqual([
expect.objectContaining({
name: 'platform',
root: workspaceRoot,
links: [
expect.objectContaining({ name: 'api', path: api, status: [] }),
expect.objectContaining({ name: 'checkout', path: checkout, status: [] }),
],
status: [],
}),
]);
});
it('preserves equals signs in inferred and explicit setup link paths', async () => {
const inferred = mkdir('repos/foo=bar');
const explicit = mkdir('repos/api=service');
const setup = await setupWorkspace('equals-paths', [inferred, `api=${explicit}`]);
expect(setup.workspace.links).toEqual([
expect.objectContaining({
name: 'api',
path: explicit,
status: [],
}),
expect.objectContaining({
name: 'foo=bar',
path: inferred,
status: [],
}),
]);
const localState = parseWorkspaceLocalState(
fs.readFileSync(getWorkspaceLocalStatePath(setup.workspace.root), 'utf-8')
);
expect(localState.paths).toEqual({
api: explicit,
'foo=bar': inferred,
});
});
it('resolves relative setup, link, and relink paths before storing local state', async () => {
const project = mkdir('project');
fs.mkdirSync(path.join(project, 'repos', 'api'), { recursive: true });
fs.mkdirSync(path.join(project, 'services', 'billing'), { recursive: true });
fs.mkdirSync(path.join(project, 'archive', 'billing'), { recursive: true });
const resolvedProject = fs.realpathSync.native(project);
const setup = await runCLI(
[
'workspace',
'setup',
'--no-interactive',
'--json',
'--name',
'platform',
'--link',
'repos/api',
],
{ cwd: project, env }
);
expect(setup.exitCode).toBe(0);
const setupPayload = parseJson(setup);
expect(readLocalState(setupPayload.workspace.root).paths.api).toBe(
path.join(resolvedProject, 'repos', 'api')
);
const link = await runCLI(['workspace', 'link', 'services/billing', '--json'], {
cwd: project,
env,
});
expect(link.exitCode).toBe(0);
expect(parseJson(link).link).toEqual(
expect.objectContaining({
name: 'billing',
path: path.join(resolvedProject, 'services', 'billing'),
})
);
const relink = await runCLI(
['workspace', 'relink', 'billing', 'archive/billing', '--json'],
{ cwd: project, env }
);
expect(relink.exitCode).toBe(0);
expect(parseJson(relink).link).toEqual(
expect.objectContaining({
name: 'billing',
path: path.join(resolvedProject, 'archive', 'billing'),
})
);
expect(readLocalState(setupPayload.workspace.root).paths).toEqual({
api: path.join(resolvedProject, 'repos', 'api'),
billing: path.join(resolvedProject, 'archive', 'billing'),
});
});
it('canonicalizes existing link directories on Windows before storing local paths', async () => {
const api = mkdir('repos/api');
const canonicalApi = path.join(tempDir, 'canonical', 'api');
const originalPlatform = process.platform;
const canonicalize = vi
.spyOn(FileSystemUtils, 'canonicalizeExistingPath')
.mockImplementation((targetPath) => (targetPath === api ? canonicalApi : targetPath));
Object.defineProperty(process, 'platform', { value: 'win32' });
try {
await expect(resolveExistingDirectory(api)).resolves.toBe(canonicalApi);
expect(canonicalize).toHaveBeenCalledWith(api);
} finally {
canonicalize.mockRestore();
Object.defineProperty(process, 'platform', { value: originalPlatform });
}
});
it('rejects duplicate setup link names without creating or rewriting a workspace', async () => {
const firstApi = mkdir('repos/current/api');
const secondApi = mkdir('repos/archive/api');
const duplicate = await runCLI(
[
'workspace',
'setup',
'--no-interactive',
'--json',
'--name',
'platform',
'--link',
firstApi,
'--link',
secondApi,
],
{ cwd: tempDir, env }
);
expect(duplicate.exitCode).toBe(1);
expect(parseJson(duplicate).status[0]).toEqual(
expect.objectContaining({
code: 'duplicate_link_name',
message: expect.stringContaining(firstApi),
fix: expect.stringContaining('--link api-alt='),
})
);
expect(fs.existsSync(getWorkspaceRegistryPath({ globalDataDir: path.join(dataHome, 'openspec') }))).toBe(false);
});
it('removes a partially created workspace when setup fails after creating the root', async () => {
const api = mkdir('repos/api');
const originalDataHome = process.env.XDG_DATA_HOME;
process.env.XDG_DATA_HOME = dataHome;
const writeFileSpy = vi
.spyOn(FileSystemUtils, 'writeFile')
.mockRejectedValueOnce(new Error('disk full'));
try {
await expect(createManagedWorkspace('platform', { api })).rejects.toMatchObject({
status: {
code: 'workspace_create_failed',
},
});
} finally {
writeFileSpy.mockRestore();
if (originalDataHome === undefined) {
delete process.env.XDG_DATA_HOME;
} else {
process.env.XDG_DATA_HOME = originalDataHome;
}
}
const globalDataDir = path.join(dataHome, 'openspec');
expect(fs.existsSync(getManagedWorkspaceRoot('platform', { globalDataDir }))).toBe(false);
expect(fs.existsSync(getWorkspaceRegistryPath({ globalDataDir }))).toBe(false);
});
it('rejects existing workspace names without overwriting workspace state', async () => {
const api = mkdir('repos/api');
const web = mkdir('repos/web');
const setup = await setupWorkspace('platform', [`api=${api}`]);
const workspaceRoot = setup.workspace.root;
const sharedBefore = fs.readFileSync(getWorkspaceSharedStatePath(workspaceRoot), 'utf-8');
const localBefore = fs.readFileSync(getWorkspaceLocalStatePath(workspaceRoot), 'utf-8');
const markerPath = path.join(workspaceRoot, WORKSPACE_CHANGES_DIR_NAME, 'sentinel.txt');
fs.writeFileSync(markerPath, 'keep me');
const duplicate = await runCLI(
[
'workspace',
'setup',
'--no-interactive',
'--json',
'--name',
'platform',
'--link',
`web=${web}`,
],
{ cwd: tempDir, env }
);
expect(duplicate.exitCode).toBe(1);
expect(parseJson(duplicate).status[0]).toEqual(
expect.objectContaining({
code: 'workspace_already_exists',
target: 'workspace.name',
})
);
expect(fs.readFileSync(getWorkspaceSharedStatePath(workspaceRoot), 'utf-8')).toBe(sharedBefore);
expect(fs.readFileSync(getWorkspaceLocalStatePath(workspaceRoot), 'utf-8')).toBe(localBefore);
expect(fs.readFileSync(markerPath, 'utf-8')).toBe('keep me');
});
it('fails setup cleanly for missing automation inputs and JSON without no-interactive', async () => {
const api = mkdir('repos/api');
const noWorkspaces = await runCLI(['workspace', 'list'], { cwd: tempDir, env });
expect(noWorkspaces.exitCode).toBe(0);
expect(noWorkspaces.stdout).toContain("No OpenSpec workspaces found. Run 'openspec workspace setup' first.");
const missing = await runCLI(['workspace', 'setup', '--no-interactive', '--json'], {
cwd: tempDir,
env,
});
expect(missing.exitCode).toBe(1);
expect(parseJson(missing).status[0]).toEqual(
expect.objectContaining({
code: 'missing_setup_inputs',
severity: 'error',
})
);
const jsonInteractive = await runCLI(
['workspace', 'setup', '--json', '--name', 'platform', '--link', api],
{ cwd: tempDir, env }
);
expect(jsonInteractive.exitCode).toBe(1);
expect(parseJson(jsonInteractive).status[0]).toEqual(
expect.objectContaining({
code: 'setup_json_requires_no_interactive',
})
);
const invalidName = await runCLI(
['workspace', 'setup', '--no-interactive', '--json', '--name', 'Bad_Name', '--link', api],
{ cwd: tempDir, env }
);
expect(invalidName.exitCode).toBe(1);
expect(parseJson(invalidName).status[0]).toEqual(
expect.objectContaining({
code: 'invalid_workspace_name',
message: expect.stringContaining('kebab-case'),
})
);
const noKnown = await runCLI(['workspace', 'doctor', '--json'], { cwd: tempDir, env });
expect(noKnown.exitCode).toBe(1);
expect(parseJson(noKnown).status[0]).toEqual(
expect.objectContaining({
code: 'no_known_workspaces',
})
);
});
it('rejects missing setup, link, and relink paths with structured status', async () => {
const api = mkdir('repos/api');
const billing = mkdir('repos/billing');
const missingSetupPath = await runCLI(
[
'workspace',
'setup',
'--no-interactive',
'--json',
'--name',
'missing-setup-path',
'--link',
'missing-api',
],
{ cwd: tempDir, env }
);
expect(missingSetupPath.exitCode).toBe(1);
expect(parseJson(missingSetupPath).status[0]).toEqual(
expect.objectContaining({
code: 'linked_path_missing',
target: 'link.path',
})
);
await setupWorkspace('platform', [`api=${api}`]);
const missingLinkPath = await runCLI(
['workspace', 'link', 'missing-service', '--json'],
{ cwd: tempDir, env }
);
expect(missingLinkPath.exitCode).toBe(1);
expect(parseJson(missingLinkPath).status[0]).toEqual(
expect.objectContaining({
code: 'linked_path_missing',
target: 'link.path',
})
);
const link = await runCLI(['workspace', 'link', 'billing', billing, '--json'], {
cwd: tempDir,
env,
});
expect(link.exitCode).toBe(0);
const missingRelinkPath = await runCLI(
['workspace', 'relink', 'billing', 'missing-billing', '--json'],
{ cwd: tempDir, env }
);
expect(missingRelinkPath.exitCode).toBe(1);
expect(parseJson(missingRelinkPath).status[0]).toEqual(
expect.objectContaining({
code: 'linked_path_missing',
target: 'link.path',
})
);
});
it('links, rejects duplicate link names, relinks, and reports unknown relinks', async () => {
const api = mkdir('repos/api');
const billing = mkdir('repos/platform/services/billing');
const billingNew = mkdir('repos/archive/billing');
const duplicate = mkdir('repos/duplicate-billing');
await setupWorkspace('platform', [`api=${api}`]);
const link = await runCLI(['workspace', 'link', billing, '--json'], { cwd: tempDir, env });
expect(link.exitCode).toBe(0);
expect(parseJson(link).link).toEqual(
expect.objectContaining({
name: 'billing',
path: billing,
status: [],
})
);
const duplicateResult = await runCLI(
['workspace', 'link', 'billing', duplicate, '--json'],
{ cwd: tempDir, env }
);
expect(duplicateResult.exitCode).toBe(1);
expect(parseJson(duplicateResult).status[0]).toEqual(
expect.objectContaining({
code: 'duplicate_link_name',
message: expect.stringContaining('already uses that name'),
})
);
const relink = await runCLI(['workspace', 'relink', 'billing', billingNew, '--json'], {
cwd: tempDir,
env,
});
expect(relink.exitCode).toBe(0);
expect(parseJson(relink).link).toEqual(
expect.objectContaining({
name: 'billing',
path: billingNew,
})
);
const unknown = await runCLI(['workspace', 'relink', 'web', billingNew, '--json'], {
cwd: tempDir,
env,
});
expect(unknown.exitCode).toBe(1);
expect(parseJson(unknown).status[0]).toEqual(
expect.objectContaining({
code: 'unknown_link_name',
})
);
});
it('links monorepo folders without editing the linked folder', async () => {
const api = mkdir('repos/api');
const packageDir = mkdir('monorepo/apps/checkout');
const sentinelPath = path.join(packageDir, 'package.json');
fs.writeFileSync(sentinelPath, '{"name":"checkout"}\n');
const entriesBefore = fs.readdirSync(packageDir).sort();
await setupWorkspace('platform', [`api=${api}`]);
const link = await runCLI(['workspace', 'link', packageDir, '--json'], {
cwd: tempDir,
env,
});
expect(link.exitCode).toBe(0);
expect(parseJson(link).link).toEqual(
expect.objectContaining({
name: 'checkout',
path: packageDir,
})
);
expect(fs.readFileSync(sentinelPath, 'utf-8')).toBe('{"name":"checkout"}\n');
expect(fs.readdirSync(packageDir).sort()).toEqual(entriesBefore);
expect(fs.existsSync(path.join(packageDir, 'openspec'))).toBe(false);
expect(fs.existsSync(path.join(packageDir, WORKSPACE_METADATA_DIR_NAME))).toBe(false);
});
it('fails link and relink without rewriting malformed local state', async () => {
const api = mkdir('repos/api');
const billing = mkdir('repos/billing');
const setup = await setupWorkspace('broken-local', [`api=${api}`]);
const sharedPath = getWorkspaceSharedStatePath(setup.workspace.root);
const localPath = getWorkspaceLocalStatePath(setup.workspace.root);
const sharedBefore = fs.readFileSync(sharedPath, 'utf-8');
const malformedLocalState = 'version: 1\npaths: []\n';
fs.writeFileSync(localPath, malformedLocalState);
const link = await runCLI(
['workspace', 'link', 'billing', billing, '--workspace', 'broken-local', '--json'],
{ cwd: tempDir, env }
);
expect(link.exitCode).toBe(1);
expect(parseJson(link).status[0]).toEqual(
expect.objectContaining({
code: 'workspace_local_state_invalid',
target: 'workspace.local_state',
})
);
expect(fs.readFileSync(sharedPath, 'utf-8')).toBe(sharedBefore);
expect(fs.readFileSync(localPath, 'utf-8')).toBe(malformedLocalState);
const relink = await runCLI(
['workspace', 'relink', 'api', billing, '--workspace', 'broken-local', '--json'],
{ cwd: tempDir, env }
);
expect(relink.exitCode).toBe(1);
expect(parseJson(relink).status[0]).toEqual(
expect.objectContaining({
code: 'workspace_local_state_invalid',
target: 'workspace.local_state',
})
);
expect(fs.readFileSync(sharedPath, 'utf-8')).toBe(sharedBefore);
expect(fs.readFileSync(localPath, 'utf-8')).toBe(malformedLocalState);
});
it('reports stale registry entries without rewriting the registry', async () => {
const api = mkdir('repos/api');
const setup = await setupWorkspace('platform', [`api=${api}`]);
const registryPath = getWorkspaceRegistryPath({ globalDataDir: path.join(dataHome, 'openspec') });
const registryBefore = fs.readFileSync(registryPath, 'utf-8');
fs.rmSync(setup.workspace.root, { recursive: true, force: true });
const list = await runCLI(['workspace', 'list', '--json'], { cwd: tempDir, env });
expect(list.exitCode).toBe(0);
expect(parseJson(list).workspaces[0].status[0]).toEqual(
expect.objectContaining({
code: 'workspace_root_missing',
})
);
const doctor = await runCLI(['workspace', 'doctor', '--workspace', 'platform', '--json'], {
cwd: tempDir,
env,
});
expect(doctor.exitCode).toBe(0);
expect(parseJson(doctor).workspace.status[0]).toEqual(
expect.objectContaining({
code: 'selected_workspace_root_missing',
})
);
expect(fs.readFileSync(registryPath, 'utf-8')).toBe(registryBefore);
});
it('reports malformed local state in list and doctor without rewriting files', async () => {
const api = mkdir('repos/api');
const setup = await setupWorkspace('doctor-local-invalid', [`api=${api}`]);
const localPath = getWorkspaceLocalStatePath(setup.workspace.root);
const registryPath = getWorkspaceRegistryPath({ globalDataDir: path.join(dataHome, 'openspec') });
const malformedLocalState = 'version: 1\npaths: []\n';
const registryBefore = fs.readFileSync(registryPath, 'utf-8');
fs.writeFileSync(localPath, malformedLocalState);
const list = await runCLI(['workspace', 'list', '--json'], { cwd: tempDir, env });
expect(list.exitCode).toBe(0);
expect(parseJson(list).workspaces[0].status[0]).toEqual(
expect.objectContaining({
code: 'workspace_local_state_invalid',
})
);
const humanList = await runCLI(['workspace', 'list'], { cwd: tempDir, env });
expect(humanList.exitCode).toBe(0);
expect(humanList.stdout).toContain('Linked repos or folders (1):');
expect(humanList.stdout).toContain('api -> (no local path recorded)');
const doctor = await runCLI(
['workspace', 'doctor', '--workspace', 'doctor-local-invalid', '--json'],
{ cwd: tempDir, env }
);
expect(doctor.exitCode).toBe(0);
const doctorPayload = parseJson(doctor);
expect(doctorPayload.workspace.status[0]).toEqual(
expect.objectContaining({
code: 'workspace_local_state_invalid',
target: 'workspace.local_state',
})
);
expect(doctorPayload.workspace.links[0]).toEqual(
expect.objectContaining({
name: 'api',
path: null,
status: [],
})
);
expect(fs.readFileSync(localPath, 'utf-8')).toBe(malformedLocalState);
expect(fs.readFileSync(registryPath, 'utf-8')).toBe(registryBefore);
});
it('reports shared/local drift and missing paths without repairing workspace state', async () => {
const api = mkdir('repos/api');
const localOnly = mkdir('repos/local-only');
const setup = await setupWorkspace('platform', [`api=${api}`]);
const workspaceRoot = setup.workspace.root;
const registryPath = getWorkspaceRegistryPath({ globalDataDir: path.join(dataHome, 'openspec') });
const missingApiPath = path.join(tempDir, 'repos', 'missing-api');
const sharedDrift = `version: 1
name: platform
links:
api: {}
web: {}
`;
const localDrift = `version: 1
paths:
api: ${missingApiPath}
local-only: ${localOnly}
`;
fs.writeFileSync(getWorkspaceSharedStatePath(workspaceRoot), sharedDrift);
fs.writeFileSync(getWorkspaceLocalStatePath(workspaceRoot), localDrift);
fs.rmSync(path.join(workspaceRoot, WORKSPACE_CHANGES_DIR_NAME), { recursive: true, force: true });
const registryBefore = fs.readFileSync(registryPath, 'utf-8');
const doctor = await runCLI(['workspace', 'doctor', '--workspace', 'platform', '--json'], {
cwd: tempDir,
env,
});
expect(doctor.exitCode).toBe(0);
const payload = parseJson(doctor);
expect(payload.workspace.status).toEqual([
expect.objectContaining({
code: 'workspace_planning_path_missing',
target: 'workspace.planning_path',
}),
]);
expect(payload.workspace.links).toEqual([
expect.objectContaining({
name: 'api',
path: missingApiPath,
status: [
expect.objectContaining({
code: 'linked_path_missing',
fix: expect.stringContaining('workspace relink api'),
}),
],
}),
expect.objectContaining({
name: 'local-only',
path: localOnly,
status: [
expect.objectContaining({
code: 'local_path_without_shared_link',
severity: 'warning',
}),
],
}),
expect.objectContaining({
name: 'web',
path: null,
status: [
expect.objectContaining({
code: 'linked_path_missing_from_local_state',
fix: expect.stringContaining('workspace relink web'),
}),
],
}),
]);
expect(fs.readFileSync(getWorkspaceSharedStatePath(workspaceRoot), 'utf-8')).toBe(sharedDrift);
expect(fs.readFileSync(getWorkspaceLocalStatePath(workspaceRoot), 'utf-8')).toBe(localDrift);
expect(fs.readFileSync(registryPath, 'utf-8')).toBe(registryBefore);
});
it('uses current unregistered workspaces for doctor and records them after link', async () => {
const manualRoot = path.join(tempDir, 'manual-workspace');
const nested = path.join(manualRoot, WORKSPACE_CHANGES_DIR_NAME, 'add-billing');
const api = mkdir('repos/api');
fs.mkdirSync(path.join(manualRoot, WORKSPACE_METADATA_DIR_NAME), { recursive: true });
fs.mkdirSync(nested, { recursive: true });
fs.writeFileSync(
path.join(manualRoot, WORKSPACE_METADATA_DIR_NAME, WORKSPACE_SHARED_STATE_FILE_NAME),
'version: 1\nname: manual-workspace\nlinks: {}\n'
);
fs.writeFileSync(
path.join(manualRoot, WORKSPACE_METADATA_DIR_NAME, WORKSPACE_LOCAL_STATE_FILE_NAME),
'version: 1\npaths: {}\n'
);
const registryPath = getWorkspaceRegistryPath({ globalDataDir: path.join(dataHome, 'openspec') });
const doctor = await runCLI(['workspace', 'doctor', '--json'], { cwd: nested, env });
expect(doctor.exitCode).toBe(0);
expect(parseJson(doctor).status[0]).toEqual(
expect.objectContaining({
code: 'workspace_not_in_local_registry',
severity: 'warning',
})
);
expect(fs.existsSync(registryPath)).toBe(false);
const link = await runCLI(['workspace', 'link', 'api', api, '--json'], {
cwd: nested,
env,
});
expect(link.exitCode).toBe(0);
expect(parseJson(link).status[0]).toEqual(
expect.objectContaining({
code: 'workspace_not_in_local_registry',
})
);
const registry = parseWorkspaceRegistryState(fs.readFileSync(registryPath, 'utf-8'));
expect(registry.workspaces['manual-workspace']).toBe(fs.realpathSync.native(manualRoot));
});
it('fails JSON workspace selection when multiple known workspaces are available', async () => {
const api = mkdir('repos/api');
const web = mkdir('repos/web');
await setupWorkspace('platform', [`api=${api}`]);
await setupWorkspace('checkout-web', [`web=${web}`]);
const doctor = await runCLI(['workspace', 'doctor', '--json'], { cwd: tempDir, env });
expect(doctor.exitCode).toBe(1);
expect(parseJson(doctor).status[0]).toEqual(
expect.objectContaining({
code: 'workspace_selection_ambiguous',
fix: expect.stringContaining('--workspace <name>'),
})
);
});
it('uses --workspace for explicit selection and reports unknown workspace names', async () => {
const api = mkdir('repos/api');
const web = mkdir('repos/web');
await setupWorkspace('platform', [`api=${api}`]);
const checkout = await setupWorkspace('checkout-web', [`web=${web}`]);
const doctor = await runCLI(
['workspace', 'doctor', '--workspace', 'checkout-web', '--json'],
{ cwd: tempDir, env }
);
expect(doctor.exitCode).toBe(0);
expect(parseJson(doctor).workspace).toEqual(
expect.objectContaining({
name: 'checkout-web',
root: checkout.workspace.root,
})
);
const unknown = await runCLI(
['workspace', 'doctor', '--workspace', 'unknown-workspace', '--json'],
{ cwd: tempDir, env }
);
expect(unknown.exitCode).toBe(1);
expect(parseJson(unknown).status[0]).toEqual(
expect.objectContaining({
code: 'workspace_not_found',
target: 'workspace.name',
})
);
});
it('fails non-interactive ambiguous workspace selection in human output mode', async () => {
const api = mkdir('repos/api');
const web = mkdir('repos/web');
await setupWorkspace('platform', [`api=${api}`]);
await setupWorkspace('checkout-web', [`web=${web}`]);
const doctor = await runCLI(['workspace', 'doctor', '--no-interactive'], {
cwd: tempDir,
env,
});
expect(doctor.exitCode).toBe(1);
expect(doctor.stderr).toContain('Multiple OpenSpec workspaces are known. Pass --workspace <name>.');
expect(doctor.stderr).toContain('openspec workspace doctor --workspace <name>');
});
it('prints readable human output for setup, list, and doctor', async () => {
const api = mkdir('repos/api');
const setup = await runCLI(
['workspace', 'setup', '--no-interactive', '--name', 'platform', '--link', `api=${api}`],
{ cwd: tempDir, env }
);
expect(setup.exitCode).toBe(0);
expect(setup.stdout).toContain('Workspace setup complete');
expect(setup.stdout).toContain('OpenSpec workspaces (1)');
expect(setup.stdout).toContain('Location:');
expect(setup.stdout).not.toContain('Root:');
expect(setup.stdout).toContain('Linked repos or folders (1):');
expect(setup.stdout).toContain(`api -> ${api}`);
expect(setup.stdout).toContain('Planning path:');
expect(setup.stdout).toContain('Workspace check:');
expect(setup.stdout).toContain('No workspace issues found.');
expect(setup.stdout).toContain('Next useful commands:');
const list = await runCLI(['workspace', 'list'], { cwd: tempDir, env });
expect(list.exitCode).toBe(0);
expect(list.stdout).toContain('OpenSpec workspaces (1)');
expect(list.stdout).toContain('platform');
expect(list.stdout).toContain('Location:');
expect(list.stdout).not.toContain('Root:');
expect(list.stdout).toContain('Linked repos or folders (1):');
expect(list.stdout).toContain(`api -> ${api}`);
const doctor = await runCLI(['workspace', 'doctor', '--workspace', 'platform'], {
cwd: tempDir,
env,
});
expect(doctor.exitCode).toBe(0);
expect(doctor.stdout).toContain('Workspace: platform');
expect(doctor.stdout).toContain('Location:');
expect(doctor.stdout).not.toContain('Root:');
expect(doctor.stdout).toContain('Planning path:');
expect(doctor.stdout).toContain('Linked repos or folders:');
expect(doctor.stdout).toContain('No workspace issues found.');
});
it('does not expose workspace create as a public command', async () => {
const help = await runCLI(['workspace', '--help'], { cwd: tempDir, env });
expect(help.exitCode).toBe(0);
expect(help.stdout).toContain('setup');
expect(help.stdout).toContain('link');
expect(help.stdout).toContain('relink');
expect(help.stdout).not.toMatch(/\bcreate\b/u);
});
it('registers workspace subcommands for shell completions', () => {
const workspace = COMMAND_REGISTRY.find((command) => command.name === 'workspace');
const link = workspace?.subcommands?.find((command) => command.name === 'link');
const relink = workspace?.subcommands?.find((command) => command.name === 'relink');
expect(workspace?.subcommands?.map((command) => command.name)).toEqual([
'setup',
'list',
'ls',
'link',
'relink',
'doctor',
]);
expect(link?.positionals).toEqual([
{ name: 'name-or-path', type: 'path', optional: true },
{ name: 'path', type: 'path' },
]);
expect(relink?.positionals).toEqual([
{ name: 'name' },
{ name: 'path', type: 'path' },
]);
});
});
@@ -332,6 +332,23 @@ describe('BashGenerator', () => {
expect(script).toContain('compgen -f');
});
it('should handle positional arguments for schema names', () => {
const commands: CommandDefinition[] = [
{
name: 'schema',
description: 'Manage schemas',
acceptsPositional: true,
positionalType: 'schema-name',
flags: [],
},
];
const script = generator.generate(commands);
expect(script).toContain('_openspec_complete_schemas');
expect(script).toContain('openspec __complete schemas 2>/dev/null');
});
it('should generate dynamic completion helper for changes', () => {
const commands: CommandDefinition[] = [
{
@@ -294,6 +294,23 @@ describe('FishGenerator', () => {
expect(script).toContain('powershell');
});
it('should handle positional arguments for schema names', () => {
const commands: CommandDefinition[] = [
{
name: 'schema',
description: 'Manage schemas',
acceptsPositional: true,
positionalType: 'schema-name',
flags: [],
},
];
const script = generator.generate(commands);
expect(script).toContain('__fish_openspec_schemas');
expect(script).toContain('openspec __complete schemas 2>/dev/null');
});
it('should generate dynamic completion helper for changes', () => {
const commands: CommandDefinition[] = [
{
@@ -353,6 +353,23 @@ describe('PowerShellGenerator', () => {
expect(script).toContain('"init"');
});
it('should handle positional arguments for schema names', () => {
const commands: CommandDefinition[] = [
{
name: 'schema',
description: 'Manage schemas',
acceptsPositional: true,
positionalType: 'schema-name',
flags: [],
},
];
const script = generator.generate(commands);
expect(script).toContain('Get-OpenSpecSchemas');
expect(script).toContain('openspec __complete schemas 2>$null');
});
it('should generate dynamic completion helper for changes', () => {
const commands: CommandDefinition[] = [
{
@@ -268,6 +268,50 @@ describe('ZshGenerator', () => {
expect(script).toContain("'*:path:_files'");
});
it('should handle positional arguments for schema names', () => {
const commands: CommandDefinition[] = [
{
name: 'schema',
description: 'Manage schemas',
acceptsPositional: true,
positionalType: 'schema-name',
flags: [],
},
];
const script = generator.generate(commands);
expect(script).toContain("'*: :_openspec_complete_schemas'");
expect(script).toContain('_openspec_complete_schemas()');
});
it('should emit optional indexed positional arguments with double-colon syntax', () => {
const commands: CommandDefinition[] = [
{
name: 'workspace',
description: 'Manage workspaces',
flags: [],
subcommands: [
{
name: 'link',
description: 'Link a folder',
acceptsPositional: true,
positionals: [
{ name: 'name-or-path', type: 'path', optional: true },
{ name: 'path', type: 'path' },
],
flags: [],
},
],
},
];
const script = generator.generate(commands);
expect(script).toContain("'1::name-or-path:_files'");
expect(script).toContain("'2:path:_files'");
});
it('should escape special characters in descriptions', () => {
const commands: CommandDefinition[] = [
{
@@ -167,6 +167,7 @@ describe('ZshInstaller', () => {
const result = await installer.install(testScript);
expect(result.zshrcConfigured).toBe(false);
expect(result.instructions).toBeDefined();
expect(result.instructions!.length).toBeGreaterThan(0);
// Should include guidance about verifying fpath for Oh My Zsh
@@ -630,28 +631,29 @@ describe('ZshInstaller', () => {
expect(content).toContain('compinit');
});
it('should configure .zshrc for Oh My Zsh when fpath is missing', async () => {
it('should not configure .zshrc for Oh My Zsh', async () => {
const ohMyZshPath = path.join(testHomeDir, '.oh-my-zsh');
await fs.mkdir(ohMyZshPath, { recursive: true });
const zshrcPath = path.join(testHomeDir, '.zshrc');
const originalZshrc = [
'export ZSH="$HOME/.oh-my-zsh"',
'source "$ZSH/oh-my-zsh.sh"',
'',
].join('\n');
await fs.writeFile(zshrcPath, originalZshrc);
const result = await installer.install(testScript);
expect(result.success).toBe(true);
expect(result.isOhMyZsh).toBe(true);
// Should configure .zshrc if fpath doesn't already include the directory
expect(result.zshrcConfigured).toBe(true);
expect(result.zshrcConfigured).toBe(false);
// Verify .zshrc was created with fpath configuration
const zshrcPath = path.join(testHomeDir, '.zshrc');
const exists = await fs.access(zshrcPath).then(() => true).catch(() => false);
expect(exists).toBe(true);
if (exists) {
const content = await fs.readFile(zshrcPath, 'utf-8');
expect(content).toContain('fpath=');
// Check for custom/completions or custom\completions (Windows path separator)
expect(content).toMatch(/custom[/\\]completions/);
}
const content = await fs.readFile(zshrcPath, 'utf-8');
expect(content).toBe(originalZshrc);
expect(content).not.toContain('# OPENSPEC:START');
expect(content).not.toContain('autoload -Uz compinit');
expect(content).not.toContain('compinit');
expect(result.instructions!.join('\n')).toContain('Oh My Zsh');
});
it('should not include manual instructions when .zshrc was auto-configured', async () => {
+39
View File
@@ -6,6 +6,7 @@ import * as os from 'node:os';
import {
getGlobalConfigDir,
getGlobalConfigPath,
getGlobalDataDir,
getGlobalConfig,
saveGlobalConfig,
GLOBAL_CONFIG_DIR_NAME,
@@ -95,6 +96,44 @@ describe('global-config', () => {
});
});
describe('getGlobalDataDir', () => {
it('should use POSIX separators for Unix-like platform overrides', () => {
expect(
getGlobalDataDir({
env: {},
platform: 'linux',
homedir: '/home/tabish',
})
).toBe('/home/tabish/.local/share/openspec');
expect(
getGlobalDataDir({
env: { XDG_DATA_HOME: '/var/data' },
platform: 'darwin',
homedir: '/Users/tabish',
})
).toBe('/var/data/openspec');
});
it('should use Windows separators for native Windows platform overrides', () => {
expect(
getGlobalDataDir({
env: {},
platform: 'win32',
homedir: 'C:\\Users\\Tabish',
})
).toBe('C:\\Users\\Tabish\\AppData\\Local\\openspec');
expect(
getGlobalDataDir({
env: { LOCALAPPDATA: 'D:\\Users\\Tabish\\AppData\\Local' },
platform: 'win32',
homedir: 'C:\\Users\\Tabish',
})
).toBe('D:\\Users\\Tabish\\AppData\\Local\\openspec');
});
});
describe('getGlobalConfig', () => {
it('should return defaults when config file does not exist', () => {
process.env.XDG_CONFIG_HOME = tempDir;
+28 -4
View File
@@ -82,11 +82,12 @@ describe('InitCommand', () => {
await initCommand.execute(testDir);
// Core profile: propose, explore, apply, archive
// Core profile: propose, explore, apply, sync, archive
const coreSkillNames = [
'openspec-propose',
'openspec-explore',
'openspec-apply-change',
'openspec-sync-specs',
'openspec-archive-change',
];
@@ -105,7 +106,6 @@ describe('InitCommand', () => {
'openspec-new-change',
'openspec-continue-change',
'openspec-ff-change',
'openspec-sync-specs',
'openspec-bulk-archive-change',
'openspec-verify-change',
];
@@ -121,11 +121,12 @@ describe('InitCommand', () => {
await initCommand.execute(testDir);
// Core profile: propose, explore, apply, archive
// Core profile: propose, explore, apply, sync, archive
const coreCommandNames = [
'opsx/propose.md',
'opsx/explore.md',
'opsx/apply.md',
'opsx/sync.md',
'opsx/archive.md',
];
@@ -139,7 +140,6 @@ describe('InitCommand', () => {
'opsx/new.md',
'opsx/continue.md',
'opsx/ff.md',
'opsx/sync.md',
'opsx/bulk-archive.md',
'opsx/verify.md',
];
@@ -168,6 +168,30 @@ describe('InitCommand', () => {
expect(await fileExists(skillFile)).toBe(true);
});
it('should support Kimi CLI as an adapterless skills-only tool', async () => {
saveGlobalConfig({
featureFlags: {},
profile: 'core',
delivery: 'both',
});
const initCommand = new InitCommand({ tools: 'kimi', force: true });
await initCommand.execute(testDir);
const skillFile = path.join(testDir, '.kimi', 'skills', 'openspec-explore', 'SKILL.md');
expect(await fileExists(skillFile)).toBe(true);
const commandsDir = path.join(testDir, '.kimi', 'commands');
expect(await directoryExists(commandsDir)).toBe(false);
const logCalls = (console.log as unknown as { mock: { calls: unknown[][] } }).mock.calls.flat().map(String);
expect(
logCalls.some(
(entry) => entry.includes('Commands skipped for: kimi') && entry.includes('(no adapter)'),
),
).toBe(true);
});
it('should create skills for multiple tools at once', async () => {
const initCommand = new InitCommand({ tools: 'claude,cursor', force: true });
@@ -0,0 +1,46 @@
import { describe, it, expect } from 'vitest';
import { extractRequirementsSection, parseDeltaSpec } from '../../../src/core/parsers/requirement-blocks.js';
describe('extractRequirementsSection', () => {
it('parses canonical ### Requirement: headers', () => {
const result = extractRequirementsSection(`## Requirements\n### Requirement: Foo\nThe system SHALL foo.\n`);
expect(result.bodyBlocks.length).toBe(1);
expect(result.bodyBlocks[0].name).toBe('Foo');
});
it('regression: parses mixed-case ### requirement: headers without silently dropping them', () => {
const variants = [
'### requirement: Lowercase',
'### REQUIREMENT: Uppercase',
'### Requirement: Canonical',
];
for (const header of variants) {
const result = extractRequirementsSection(`## Requirements\n${header}\nThe system SHALL foo.\n`);
expect(result.bodyBlocks.length).toBeGreaterThan(0);
expect(result.bodyBlocks[0].name).toBe(header.replace(/^###\s*requirement:\s*/i, ''));
}
});
it('regression: parses ###Requirement: header with no space after ### without silently dropping it', () => {
const result = extractRequirementsSection(`## Requirements\n###Requirement: NoSpace\nThe system SHALL foo.\n`);
expect(result.bodyBlocks.length).toBe(1);
expect(result.bodyBlocks[0].name).toBe('NoSpace');
});
it('regression: multiple blocks where first uses no-space header are all parsed', () => {
const content = `## Requirements\n###Requirement: First\nThe system SHALL first.\n\n### Requirement: Second\nThe system SHALL second.\n`;
const result = extractRequirementsSection(content);
expect(result.bodyBlocks.length).toBe(2);
expect(result.bodyBlocks[0].name).toBe('First');
expect(result.bodyBlocks[1].name).toBe('Second');
});
});
describe('parseDeltaSpec', () => {
it('regression: parses ###Requirement: header with no space in delta ADDED section', () => {
const content = `## ADDED Requirements\n###Requirement: NoSpace\nThe system SHALL foo.\n`;
const result = parseDeltaSpec(content);
expect(result.added.length).toBe(1);
expect(result.added[0].name).toBe('NoSpace');
});
});
+2 -2
View File
@@ -83,8 +83,8 @@ describe('profile sync drift detection', () => {
it('detects drift when extra workflows are installed for both delivery', () => {
setupCoreSkills(tempDir);
setupCoreCommands(tempDir);
writeSkill(tempDir, 'sync');
writeCommand(tempDir, 'sync');
writeSkill(tempDir, 'new');
writeCommand(tempDir, 'new');
const hasDrift = hasProjectConfigDrift(tempDir, CORE_WORKFLOWS, 'both');
expect(hasDrift).toBe(true);
+2 -2
View File
@@ -8,8 +8,8 @@ import {
describe('profiles', () => {
describe('CORE_WORKFLOWS', () => {
it('should contain the four core workflows', () => {
expect(CORE_WORKFLOWS).toEqual(['propose', 'explore', 'apply', 'archive']);
it('should contain the default core workflows', () => {
expect(CORE_WORKFLOWS).toEqual(['propose', 'explore', 'apply', 'sync', 'archive']);
});
it('should be a subset of ALL_WORKFLOWS', () => {
+18
View File
@@ -225,6 +225,23 @@ describe('skill-generation', () => {
expect(content).toContain('author: openspec');
expect(content).toContain('version: "1.0"');
expect(content).toContain('generatedBy: "0.24.0"');
expect(content).toContain('## OpenSpec CLI Visibility');
expect(content).toContain('OPENSPEC_BIN');
});
it('should prepend CLI visibility guidance for OpenSpec CLI skills', () => {
const template = {
name: 'cli-skill',
description: 'Uses the CLI',
instructions: 'Run openspec list.',
compatibility: 'Requires openspec CLI.',
};
const content = generateSkillContent(template, '0.24.0');
expect(content).toContain('## OpenSpec CLI Visibility');
expect(content).toContain('agent, GUI, and automation shells may inherit a different `PATH`');
expect(content).toContain('Run openspec list.');
});
it('should embed the provided version in generatedBy field', () => {
@@ -249,6 +266,7 @@ describe('skill-generation', () => {
name: 'test',
description: 'Test',
instructions: 'Body content',
compatibility: 'Standalone test fixture',
};
const content = generateSkillContent(template, '0.23.0');
@@ -36,7 +36,7 @@ const EXPECTED_FUNCTION_HASHES: Record<string, string> = {
getApplyChangeSkillTemplate: '6238712ba8cd2fd099c4f3bac13436f758fc6ac776fb8be19547f2b195240bfd',
getFfChangeSkillTemplate: 'a7332fb14c8dc3f9dec71f5d332790b4a8488191e7db4ab6132ccbefecf9ded9',
getSyncSpecsSkillTemplate: 'bded184e4c345619148de2c0ad80a5b527d4ffe45c87cc785889b9329e0f465b',
getOnboardSkillTemplate: 'c9e719a02d2ae7f74a0e978f9ad4e767c1921248a9e3724c3321c58a15c38ba9',
getOnboardSkillTemplate: 'b78d8479da5dc92432d81a6d29c56b6cbfed723a0750c7868a07966d58d47f76',
getOpsxExploreCommandTemplate: 'b421b88c7a532385f7b1404736d7893eb35a05573b4a04a96f72379ac1bbf148',
getOpsxNewCommandTemplate: '62eee32d6d81a376e7be845d0891e28e6262ad07482f9bfe6af12a9f0366c364',
getOpsxContinueCommandTemplate: '8bbaedcc95287f9e822572608137df4f49ad54cedfb08d3342d0d1c4e9716caa',
@@ -47,7 +47,7 @@ const EXPECTED_FUNCTION_HASHES: Record<string, string> = {
getOpsxSyncCommandTemplate: '378d035fe7cc30be3e027b66dcc4b8afc78ef1c8369c39479c9b05a582fb5ccf',
getVerifyChangeSkillTemplate: '40dde29051a0ba204295b74e49e87b6e9ff30c8b89ff0e791b4f955b4595de59',
getOpsxArchiveCommandTemplate: 'b44cc9748109f61687f9f596604b037bc3ea803abc143b22f09a76aebd98b493',
getOpsxOnboardCommandTemplate: 'fce531f952e939ee85a41848fc21e4cc720b0f3eb62737adc3a51ee6ad2dfc57',
getOpsxOnboardCommandTemplate: '34c3081988e4a890adad5efb7c6474a3ddca96d9ed2d28a9daac7b4f182a5735',
getOpsxBulkArchiveCommandTemplate: '0d77c82de43840a28c74f5181cb21e33b9a9d00454adf4bc92bdc9e69817d6f5',
getOpsxVerifyCommandTemplate: 'd7c0444863faabb16abb091bc40ee56d985ae4bfa9a4db1e622ca8ba03c32fed',
getOpsxProposeSkillTemplate: 'd67f937d44650e9c61d2158c865309fbab23cb3f50a3d4868a640a97776e3999',
@@ -56,17 +56,17 @@ const EXPECTED_FUNCTION_HASHES: Record<string, string> = {
};
const EXPECTED_GENERATED_SKILL_CONTENT_HASHES: Record<string, string> = {
'openspec-explore': '08e1ec9958eb04653707dd3e198c3fd69cf1b3acd3cf95a1022693cca83c60fc',
'openspec-new-change': 'c324a7ace1f244aa3f534ac8e3370a2c11190d6d1b85a315f26a211398310f0f',
'openspec-continue-change': '463cf0b980ec9c3c24774414ef2a3e48e9faa8577bc8748990f45ab3d5efe960',
'openspec-apply-change': '38ad2cb645827eda555f20e1ac9d483e1d75bae4c817c0669474aaa8c12c0421',
'openspec-ff-change': '672c3a5b8df152d959b15bd7ae2be7a75ab7b8eaa2ec1e0daa15c02479b27937',
'openspec-sync-specs': 'b8859cf454379a19ca35dbf59eedca67306607f44a355327f9dc851114e50bde',
'openspec-archive-change': 'f83c85452bd47de0dee6b8efbcea6a62534f8a175480e9044f3043f887cebf0f',
'openspec-bulk-archive-change': '10477399bb07c7ba67f78e315bd68fb1901af8866720545baf4c62a6a679493b',
'openspec-verify-change': 'b6dc1b87940be9d6125b834831c8619019aec9a9748995f72bf981b6f08b67f8',
'openspec-onboard': 'c1444e026028210efd699110f7e9079bcb486d85ccf27f743213a81cb1084303',
'openspec-propose': '20e36dabefb90e232bad0667292bd5007ec280f8fc4fc995dbc4282bf45a22e7',
'openspec-explore': 'ad1178ca328ee6c4a44c42d5a39bb115fc0708778feded3339f35ed7bd82800e',
'openspec-new-change': 'f555ab9b1385e78e5d96e9e08bfe7c2035449c7349be21669e671aefbd0d7d4a',
'openspec-continue-change': 'a9e827be428a5f300aa3ff4a379403a7a3ac378ce0b790c99c0fbe2e14404625',
'openspec-apply-change': '8f8e6594ed8dffa854a2c3373b2674c814419063f0bb9ab79d98c5e18fd21aa6',
'openspec-ff-change': 'a61b501beb63dd625dd1b7c46243705c2746005a7673b2120a2cbca36d9eb831',
'openspec-sync-specs': '2075928ed531ab226bd3a05c67d386226eb0a3ec71e08f708e4837feeeb41a29',
'openspec-archive-change': '66fdcdd43c2a51d70823cf4d3d1eb174273b9350dd651b1113b5458b4ec81a99',
'openspec-bulk-archive-change': '7aa32f345f7b44d52619b4efa92589e0ab3cd671ae559bac1c156bb3251cda2b',
'openspec-verify-change': '5ea8266080e006319a604e5deac6f4ecb3a4d0e03c3e77b99897d3b62f70892e',
'openspec-onboard': '48511ff0e8aec12784dba58ec94f2ad61b1bbc8de4f73b47ca60ecea788a6db9',
'openspec-propose': '217b1ca83dc520207b4da584d3699791ece48a24eb164b524a1320189f61549b',
};
function stableStringify(value: unknown): string {
+42 -6
View File
@@ -155,10 +155,11 @@ Old instructions content
await updateCommand.execute(testDir);
// Verify core profile skill files were created/updated (propose, explore, apply, archive)
// Verify core profile skill files were created/updated (propose, explore, apply, sync, archive)
const coreSkillNames = [
'openspec-explore',
'openspec-apply-change',
'openspec-sync-specs',
'openspec-archive-change',
'openspec-propose',
];
@@ -179,7 +180,6 @@ Old instructions content
'openspec-new-change',
'openspec-continue-change',
'openspec-ff-change',
'openspec-sync-specs',
'openspec-bulk-archive-change',
'openspec-verify-change',
];
@@ -233,8 +233,8 @@ Old instructions content
await updateCommand.execute(testDir);
// Verify core profile commands were created (propose, explore, apply, archive)
const coreCommandIds = ['explore', 'apply', 'archive', 'propose'];
// Verify core profile commands were created (propose, explore, apply, sync, archive)
const coreCommandIds = ['explore', 'apply', 'sync', 'archive', 'propose'];
const commandsDir = path.join(testDir, '.claude', 'commands', 'opsx');
for (const cmdId of coreCommandIds) {
const cmdFile = path.join(commandsDir, `${cmdId}.md`);
@@ -243,7 +243,7 @@ Old instructions content
}
// Verify non-core commands are NOT created
const nonCoreCommandIds = ['new', 'continue', 'ff', 'sync', 'bulk-archive', 'verify'];
const nonCoreCommandIds = ['new', 'continue', 'ff', 'bulk-archive', 'verify'];
for (const cmdId of nonCoreCommandIds) {
const cmdFile = path.join(commandsDir, `${cmdId}.md`);
const exists = await FileSystemUtils.fileExists(cmdFile);
@@ -1324,6 +1324,7 @@ More user content after markers.
'openspec-propose',
'openspec-explore',
'openspec-apply-change',
'openspec-sync-specs',
'openspec-archive-change',
];
@@ -1426,6 +1427,41 @@ More user content after markers.
)).toBe(false);
});
it('should suggest core preset when custom profile preserves the old core workflow set', async () => {
setMockConfig({
featureFlags: {},
profile: 'custom',
delivery: 'both',
workflows: ['propose', 'explore', 'apply', 'archive'],
});
const initCommand = new InitCommand({ tools: 'claude', force: true });
await initCommand.execute(testDir);
const consoleSpy = vi.spyOn(console, 'log');
await updateCommand.execute(testDir);
const calls = consoleSpy.mock.calls.map(call =>
call.map(arg => String(arg)).join(' ')
);
expect(calls.some(call =>
call.includes('The core profile now includes sync')
)).toBe(true);
expect(calls.some(call =>
call.includes('openspec config profile core') && call.includes('openspec update')
)).toBe(true);
expect(await FileSystemUtils.fileExists(
path.join(testDir, '.claude', 'skills', 'openspec-sync-specs', 'SKILL.md')
)).toBe(false);
expect(await FileSystemUtils.fileExists(
path.join(testDir, '.claude', 'commands', 'opsx', 'sync.md')
)).toBe(false);
consoleSpy.mockRestore();
});
it('should respect skills-only delivery setting', async () => {
setMockConfig({
featureFlags: {},
@@ -1569,7 +1605,7 @@ content
});
it('should remove workflows outside profile during update sync', async () => {
// Set core profile (propose, explore, apply, archive)
// Set core profile (propose, explore, apply, sync, archive)
setMockConfig({
featureFlags: {},
profile: 'core',

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