跪拜 Guibai
← Back to the summary

OpenSpec in Practice: Write the Spec First, Then Let AI Write the Code

Technical Summary | OpenSpec in Practice: How to Write the Spec First, Then Let AI Write the Code

Author: 周末程序猿 Tags: 后端, AI编程

If you've used Claude Code, Codex, or Cursor to build a feature spanning multiple days, you've probably hit the same class of problem: requirements live only in dozens of chat turns; by the time you've modified the tenth file, no one remembers what was originally agreed; a new person picking it up can only guess intent from the diffs.

OpenSpec aims to fix that opening phase: before writing code, turn "what we're building" into Markdown files in the repository, so humans and AI talk to the same file.

SimpleBase is a Serverless infrastructure built for AI (<https://github.com/SimpleAI2026/SimpleBase), and all its AI-related code-writing parts use> AGENTS.md + OpenSpec spec-driven development. As of 2026-11-27, this repository has 12 capability baselines, 7 archived changes, and 7 in-flight changes. The first half of this article talks about OpenSpec itself; the practices and supplementary examples are all drawn from this real directory, not from hypothetical projects.

Project address: <https://github.com/Fission-AI/OpenSpec (MIT, official site> https://openspec.dev)

What It Actually Is

In one sentence: Spec-driven development (SDD) for AI coding assistants.

It is not a code generator, and it doesn't take over your IDE. It provides three things:

The official five principles are fluid not rigid / iterative not waterfall / easy not complex / built for brownfield not just greenfield / scalable from personal projects to enterprises. Translated into engineering language: no phase gates, any artifact is always editable; default assumes you're modifying an existing repository, not starting from scratch.

Differences from similar solutions (official stance): GitHub's Spec Kit is complete but heavy, with rigid phase gates, lots of Markdown and a Python environment; AWS's Kiro is strong but locks you into its IDE and models. OpenSpec only requires a CLI plus the editor you already use.

Core Model

SimpleBase/
├── openspec/
│   ├── config.yaml                       # Project context and artifact rules
│   ├── README.md                         # Single entry point for plans and change specs
│   ├── specs/                            # Current state: 12 capability baselines, divided by bounded context
│   │   ├── platform-architecture/spec.md
│   │   ├── data-service/spec.md
│   │   └── ops-governance/spec.md
│   └── changes/                          # Plans: changes not yet landed
│       ├── add-ops-maturity/
│       │   ├── proposal.md               # Why, what changes
│       │   ├── specs/ops-governance/spec.md   # delta: only behavior differences
│       │   ├── design.md                 # How to do it
│       │   ├── tasks.md                  # Checkable checklist
│       │   └── .openspec.yaml            # schema / created / skip_specs
│       └── archive/
│           └── 2026-11-26-add-row-level-access-control/

OpenSpec's two truths: specs current state and changes in-flight changes

Image

Figure: left side specs/ is the long-term current state; each change occupies its own directory and can run in parallel; archive merges deltas back into the main spec, then moves the change directory into changes/archive/.

Two key design decisions:

  1. A change contains a delta, not the whole spec. Only write ## ADDED Requirements (plus MODIFIED / REMOVED / RENAMED), and merge into specs/ only at archive time. The benefit is parallel changes don't overwrite the same spec file.
  2. Fixed filenames. The four artifacts proposal / specs / design / tasks are defined by the schema; the CLI and agent read and write using the same convention, not relying on verbal agreements like "remember to write the design doc first" in prompts.

Requirement writing is pure Markdown, no proprietary syntax. The following is not illustrative; it's taken from SimpleBase's in-flight change openspec/changes/add-ops-maturity/specs/ops-governance/spec.md:

### Requirement: HTTP readiness endpoint

The system SHALL provide `GET /v1/system/readiness`, returning the ready status and failure reason for each critical dependency.
This endpoint MUST have no write side effects; return 200 when all dependencies are ready, otherwise return 503.

#### Scenario: All dependencies ready
- **WHEN** an administrator calls the readiness endpoint and system library and other dependencies are available
- **THEN** return 200 with a structured ready list

#### Scenario: A dependency unavailable
- **WHEN** any dependency check fails
- **THEN** return 503, indicating the failed dependency and reason, without leaking credentials or DSN

This delta lists 4 ADDED Requirements side by side (retention cleanup, dead table, readiness endpoint, alert external notification); they merge into openspec/specs/ops-governance/spec.md only at archive time.

Requirement uses SHALL / MUST NOT to describe behavior contracts; Scenario uses WHEN / THEN to describe verifiable paths. This text is both your review point for the plan and the agent's subsequent self-check point.

Installation and Initialization

npm install -g @fission-ai/openspec@latest    # Requires Node.js >= 22.20
# Or
brew install openspec

Initialize in a project:

openspec init --tools codebuddy --scope project

--tools accepts more than 30 coding tools (claude, codex, cursor, codebuddy, gemini, copilot, etc.), or pass none to use CLI only. With 2.2.0 + codebuddy, it only drops these items:

openspec/config.yaml
openspec/specs/.gitkeep
openspec/changes/archive/.gitkeep
.agents/skills/openspec-*/SKILL.md        # 7 skills
.codebuddy/skills/openspec-*/SKILL.md     # same content, dropped again per tool directory

Note that the 2.x integration carrier is skills, not plugins and not MCP; the 1.x /opsx:* command system is retired. By default it installs 7: the entry point openspec, plus explore / propose / apply-change / update-change / archive-change / sync-specs. The other 6 (new / continue / ff / bulk-archive / verify / onboard) are not installed by default:

openspec config profile    # switch default / expanded
openspec update            # write new skills into each tool directory

openspec update has another daily use: after the team commits skills into Git, each project runs it once to ensure the local skill version matches the one in the repository.

CLI Overview

openspec -h (2.2.0) commands grouped by purpose:

Purpose Commands
Init and upgrade init、update、install
View list、show、view、status、context、doctor
Create new change、change、spec
Drive agent instructions(artifact / apply / archive)
Validate validate --strict
Finish archive
Customize config、schema、templates、schemas
Multi-repo and work views store(beta, separate planning repo)、workset(pure local work view)

What really distinguishes it from "writing docs" is instructions. The CLI doesn't hand you an empty template; it generates a tagged instruction that spells out "which file to write this time, which sections are mandatory, and what project constraints are non-negotiable." Below is real output from running openspec instructions specs --change add-ops-maturity in the SimpleBase repo (excerpt, absolute paths abbreviated as …/):

<artifact id="specs" change="add-ops-maturity" schema="spec-driven">

<task>
Create the specs artifact for change "add-ops-maturity".
</task>

<project_context>
SimpleBase:single-writer cloud database service (Go 1.25 + Echo v4 + Vue 3). All artifacts in Simplified Chinese, change-id in kebab-case.

Architecture paradigm: strategic DDD + hexagonal application services. Source of truth
openspec/specs/platform-architecture/spec.md;……

New code landing spots: HTTP/WS/SSH frames → api/<context>http; protocol primitives → api/httpkit;
multi-entry reuse or cross-request lifecycle → internal/agentrun or domain packages; ……

Non-negotiable: no new third-party dependencies, no build config changes beyond go.mod;
no changing public API paths / error shapes / SSE frame formats; system library only allows SELECT; ……
</project_context>

<dependencies>
<dependency id="proposal" status="done">
  <path>…/openspec/changes/add-ops-maturity/proposal.md</path>
  <description>Initial proposal document outlining the change</description>
</dependency>
</dependencies>

<output>
Write to: …/openspec/changes/add-ops-maturity/specs/**/*.md
</output>

<instruction>
Create specification files that define WHAT the system should do.

A spec is a behavior contract, not an implementation plan.

Avoid in specs:
- Internal class/function names
- Library or framework choices
- Step-by-step implementation details
</instruction>
</artifact>

<project_context> comes verbatim from context in openspec/config.yaml; <dependencies> requires the agent to re-read the completed proposal before writing specs; <instruction> also reminds "specs write observable behavior, not class names, dependency libraries, or implementation steps."

Adding --json is more practical. The core of openspec instructions apply --change <id> --json is three blocks: contextFiles (which files to read this time), tasks (each with line and done), and progress. For add-ops-maturity, it returned 4 contextFiles, 15 tasks, and progress: {total: 15, complete: 1, remaining: 14}. The agent doesn't need to guess where the task list is, and doesn't need to remember progress from the previous chat turn.

A Complete Change (SimpleBase Real Work)

Image

OpenSpec's closed loop for a change: from specs baseline to archive merge

Figure: six-step closed loop with three layers of responsibility. openspec CLI handles scaffolding, generating instructions, validation, and archiving; skills orchestrate the CLI into fixed flows agents can trigger; agents write the four artifacts per instructions; on archive, deltas merge back into specs/ and the baseline updates.

Take the real in-flight change add-ops-maturity in SimpleBase: it adds four production-ready capabilities—retention cleanup, hourly aggregation, HTTP readiness endpoint, and alert external notification; all four artifacts exist, and only 1 of 15 tasks is checked. The six steps below are the full walk from opening to archiving.

Step one, open a change.

openspec --version                    # 2.2.0
openspec new change add-ops-maturity --description "Add production-ready capabilities"
# Or let the agent trigger /openspec-propose "Add HTTP readiness endpoint"

The repository AGENTS.md requires change-id in verb-first kebab-case, artifacts produced in order proposal → specs → design → tasks, and no new plan/ directory.

Step two, see which artifact is missing.

$ openspec status --change add-ops-maturity
Change: add-ops-maturity
Schema: spec-driven
Change root: …/openspec/changes/add-ops-maturity
Progress: 4/4 artifacts complete

[x] proposal
[x] specs
[x] design
[x] tasks

All planning artifacts complete!
Next: openspec instructions apply --change "add-ops-maturity" --json

Right after new change, all four are [ ]; after writing the four artifacts, you see the output above. This step can be run anytime; modifying design mid-course doesn't require reopening.

Step three, generate each artifact.

openspec instructions proposal --change add-ops-maturity
openspec instructions specs    --change add-ops-maturity
openspec instructions design   --change add-ops-maturity
openspec instructions tasks    --change add-ops-maturity

Treat the <instruction> output as a writing outline, <project_context> as red lines, <dependencies> as mandatory reading; after each artifact, go back to step two to see status. To generate the full set at once, use the openspec-propose skill. This change's proposal explicitly states "no new third-party dependencies (SMTP uses standard library net/smtp, Webhook uses net/http)" and "data migration only deletes expired rows, no schema changes"—these constraints are subsequently injected with every instructions call, so they don't get lost mid-writing.

Step four, validate.

openspec validate add-ops-maturity --strict
# Change 'add-ops-maturity' is valid

This only checks format and delta sections; it doesn't compile code. Code correctness is left to later test gates.

Step five, implement.

openspec instructions apply --change add-ops-maturity --json

The agent gets contextFiles and unfinished tasks, modifies code in order, and immediately changes - [ ] to - [x] in tasks.md after each completion. A real checklist looks like this (excerpt):

## 2. Hourly aggregation table (legacy A2)

- [x] 2.1 Verify whether `sys_metric_rollups_hourly` is still zero read/write, record evidence
- [ ] 2.2 Remove the table by default and sync `schema.go`, `SystemTableCount`, and release notes

## 3. Readiness endpoint (legacy H1)

- [ ] 3.1 Reuse the doctor checker to implement `GET /v1/system/readiness`, requiring admin permission

## 5. Verification

- [ ] 5.1 `go test ./internal/systemdb ./internal/alerts ./internal/api ./internal/app` passes
- [ ] 5.2 `TestArchitectureGate` passes; new config items are not written to YAML secrets

Checkboxes are the progress bar. When resuming across days without reading chat history, run openspec list (output excerpt at time of writing):

$ openspec list
Changes:
  add-api-preview-modules-and-rate-limit        ✓ Complete
  fix-agent-skill-rejection-and-plan-output     ✓ Complete
  close-legacy-backlog                          6/54 tasks
  add-ops-maturity                              1/15 tasks
  complete-bi-dashboard                         0/12 tasks
  complete-home-starter-delivery                0/14 tasks
  add-godatabase-runtime-refactor               0/25 tasks

openspec/README.md also has a human-facing "in-flight change completion" checklist: the 38/38 rate-limit change states "architecture gate passed, frontend 1587 test cases passed, pending archive"; the 1/15 add-ops-maturity states "only dead-table review done"; the 6/54 close-legacy-backlog records the closed issue numbers. Progress, verification results, and leftover issues all live in files.

Step six, archive.

openspec archive add-ops-maturity   # run only after all 15 tasks are checked

archive does four things: validates the change, merges the delta into openspec/specs/, moves the directory to changes/archive/YYYY-MM-DD-<id>/, and reports merge counts (Specs to update, + added / ~ modified, and Totals). SimpleBase's 7 archived changes are all auditable, and openspec/README.md records them:

Archive directory Merged specs
2026-11-26-add-row-level-access-control specs/identity-access(+2)、specs/data-service(+2)
2026-11-26-add-object-storage-path-access specs/file-sites(+4)
2026-11-26-refactor-module-simplification No delta(skip_specs: true, pure equivalent refactor)

add-ops-maturity isn't archived yet, so no fictional completion output is provided here: the progress table shows 1/15, so it's still in flight.

Image

Four steps of merging delta into main spec during archive and two types of results

Figure: archive's four actions and two outcomes. Left side, a change writes only ADDED / MODIFIED / REMOVED differences; after merge, specs/ updates to the new current state; the original directory is kept by date.

Pure-document, pure-refactor, and toolchain changes write no delta; instead, set skip_specs: true in the change directory's .openspec.yaml (SimpleBase's approach, see next section case); -y skips confirmation, and unfinished tasks can also be archived (but with a warning).

What the Validator Actually Enforces

I tested each of these boundaries individually; worth knowing in advance:

✗ Requirement without #### Scenario      → ERROR, must have at least one scenario
✗ Section named ## Requirements          → ERROR, not a delta section, ignored
✗ Entire change has no delta             → ERROR, suggests using skip_specs: true
⚠ Requirement body without SHALL / MUST  → WARNING (RFC 2119 recommendation), non-blocking
⚠ proposal's Why shorter than 50 chars   → WARNING, non-blocking

Two details often overlooked: SHALL / MUST must be written as the first line under the ### Requirement: heading; writing it only in the heading doesn't count. Delta section names must be exactly ## ADDED/MODIFIED/REMOVED/RENAMED Requirements; writing ## Requirements means the requirement is ignored and won't enter the main spec at archive. SimpleBase puts openspec validate <id> --strict into AGENTS.md section 6, and CI adds validate --all --strict.

Real Case: How SimpleBase's openspec/ Runs in Daily Life

The previous section covered a single change vertically; this section views it from the repository perspective—how it becomes a daily development style.

Only one entry point. openspec/README.md declares this directory as the "single entry point for plans and change specs"; root AGENTS.md section 6 writes "new features, refactors, or behavior changes all go through OpenSpec" as a hard constraint. Before starting, the agent reads the openspec/specs/<capability>/spec.md baseline, then opens a change; it doesn't create a separate plan that only exists in chat.

Fixed six-step flow. Behavior changes must have a delta spec; pure refactors / tools / documentation set skip_specs: true in .openspec.yaml, not fabricating requirements to pass validation:

openspec --version
openspec new change <verb-first kebab-case> --description "…"
openspec instructions <artifact> --change <id>     # proposal → specs → design → tasks
openspec validate <id> --strict
openspec instructions apply --change <id> --json   # implement per tasks.md, check [x] as you go
openspec archive <id>                              # merge delta back into specs/

Baselines split by bounded context. specs/ has 12 capabilities: platform-architecture、identity-access、project-catalog、data-service、file-sites、automation、agent-collaboration、llm-gateway、sandbox、ops-governance、console-ui、dev-experience. platform-architecture/spec.md is the architecture source of truth; maintenance rules require specs to describe only observable behavior, not internal class names, dependency libraries, or implementation steps. For example, openspec/specs/ops-governance/spec.md (excerpt):

### Requirement: Health check and metrics

The service SHALL provide liveness and readiness probes; the readiness probe MUST reflect the state of critical dependencies such as the system library, and MUST NOT produce write side effects.

How three types of changes are categorized. The same directory convention accommodates entirely different work:

Situation Real example How to write it
Behavior addition add-row-level-access-control (archived) proposal points out the functional gap "only login, no authorization"; delta lands in identity-access(+2)and data-service(+2); after archive it becomes baseline
In-flight capability add-ops-maturity 4 ADDED Requirements + 15 tasks, push forward one [x] at a time, no archive until done
Equivalent refactor refactor-module-simplification、refactor-ui-simplification Set skip_specs: true in .openspec.yaml; proposal states clearly "no changes to public API / error shapes / SSE frame formats / DDL"; implementation records and comparison verification go in design.md

Pure-refactor changes have a three-line .openspec.yaml; behavior changes have no skip_specs:

schema: spec-driven
created: 2026-11-26
skip_specs: true

Multi-day and multi-person handoff. Progress has three layers: - [x] in tasks.md is machine-readable, openspec status --json / openspec list can be re-read any time, and the completion checklist in openspec/README.md (checked on 2026-11-27) is for humans. Two changes are 38/38 and 51/51 with verification passed and pending archive; close-legacy-backlog 6/54 records the closed issue numbers. Information lives in files, not chat history, and not "I remember where I left off."

How red lines actually take effect—three layers. First, context in openspec/config.yaml: injected into every artifact generation, carrying constraints that can't be inferred from reading code, like "new code landing spots", "system library only allows SELECT", "four nested independent modules must not import the root module". Second, the standing rules and acceptance criteria in root AGENTS.md. Third, code-side hard gates: TestArchitectureGate in internal/app/arch_gate_test.go, CGO_ENABLED=1 go build ./internal/... ./cmd/... plus go vet, go test ./..., gofmt, frontend yarn typecheck && yarn test && yarn build, and scripts/smoke.sh. validate --strict only ensures the spec structure is correct; whether behavior is correct is backed by these commands—this exactly fills OpenSpec's shortcoming of "only guaranteeing structure."

The biggest benefit is clear division of labor. "Why do it" stays in proposal, "how to do it" stays in design, "how far have we come" is recorded by tasks and README checklist, and "what is the current state" goes to specs. Each file owns a segment; the diff itself is a decision record; archive turns plans into current state, so the spec library doesn't accumulate outdated documents.

Making the Agent Actually Respect Project Constraints

This section is the most valuable part of OpenSpec from an engineering perspective: openspec/config.yaml is not a decorative file; its three sections are all injected into instructions. To confirm injection locations, I temporarily added markers to SimpleBase's config (removed after verification; the repo's official config only keeps context, while rules / operations are currently commented-out templates generated by the CLI):

schema: spec-driven

context:|
  PROJECT-CONTEXT-MARKER: all artifacts in Simplified Chinese.

rules:
proposal:
    - RULE-MARKER: proposal no more than 500 characters

operations:
apply:
    guidance:
      - GUIDANCE-MARKER: check each task immediately after completion

Corresponding injection locations:

Image

Path of injecting three config.yaml sections into agent instructions

Figure: each of the three sections has its own destination—context goes into <project_context> for all artifacts, rules.<artifact> goes only into that artifact's <rules>, operations.apply.guidance appears only in apply instructions during implementation.

SimpleBase's official context (excerpt):

context: |
  SimpleBase: single-writer cloud database service (Go 1.25 + Echo v4 + Vue 3). All artifacts in Simplified Chinese, change-id in kebab-case.

  Architecture paradigm: strategic DDD + hexagonal application services. Source of truth
  openspec/specs/platform-architecture/spec.md;
  constraint summary in root AGENTS.md "Architecture Rules" and internal/AGENTS.md.
  New code landing spots: HTTP/WS/SSH frames → api/<context>http; protocol primitives → api/httpkit;
  multi-entry reuse or cross-request lifecycle → internal/agentrun or domain packages; external system adaptation → agentbridge/dbbridge;
  assembly only → internal/app private.

  Non-negotiable: no new third-party dependencies, no build config changes beyond go.mod;
  no changing public API paths / error shapes / SSE frame formats; system library only allows SELECT;
  four nested independent modules (godatabase/gocloudagent/gosandbox/gofunction) must not import the root module;
  dependency direction enforced by TestArchitectureGate in internal/app.

  Pure refactor/tool/documentation changes set skip_specs:true in the change directory's .openspec.yaml,
  don't fabricate requirements to pass validation; behavior changes must have delta spec.

Note that this holds things the agent can't infer from reading code: layer landing spots, cross-module red lines, which changes can skip delta. Facts readable from the repository (module list, dependency graph) go into internal/README.md, not into context to avoid wasting window space.

This brings three practical benefits:

  1. Constraints are written once. No need to re-state "no new dependencies" every conversation. The agent automatically carries it when generating proposals and tasks.

  2. No need for AGENTS.md to carry all context. Standing AGENTS.md governs per-turn behavior; context is injected once per artifact generation; they divide labor rather than being alternatives.

  3. Pure refactors don't need to fabricate requirements. Set skip_specs: true in .openspec.yaml, and validation explicitly gives INFO instead of making you invent a fake Requirement (output like):

    Change 'pure-refactor' is valid ℹ [INFO] file: skip_specs is set in .openspec.yaml: change declares no spec-level behavior changes, zero deltas accepted

Differences from Similar Solutions, and When Not to Use It

After using it, what truly distinguishes OpenSpec from "have AI write a design doc" are the delta and archive mechanisms:

The cost must also be stated clearly: it only guarantees structure, not content quality. A Requirement written as nonsense can still pass validate, and falsely checked - [x] can still archive. So human review can't be skipped, and code-side tests and architecture gates can't be skipped.

I'd recommend against it in these scenarios:

Practice Guidelines

  1. openspec init --tools <your tool> --scope project, commit openspec/ into Git; write openspec/README.md as the single entry point.
  2. Start with only context, run two or three changes, then add rules based on actual pain points. Include layer landing spots and non-negotiable red lines; don't include facts you can get from reading code.
  3. One change does one thing, change-id in verb-first kebab-case; changes spanning three modules split into three changes.
  4. Requirements write behavior (SHALL / MUST NOT), specs/ writes only observable behavior; interface signatures, file paths, and implementation steps go to design and tasks.
  5. Every task must be verifiable (command plus expected output); check [x] immediately after completion, otherwise you can't tell "done" at archive.
  6. Pure refactor / documentation / toolchain changes set skip_specs: true in .openspec.yaml; don't fabricate requirements to pass validation; implementation records go in design.md.
  7. CI runs openspec validate --all --strict; to block "archive with unfinished tasks", add openspec validate --archived.
  8. Clear context before starting a long task (official advice); mid-way use openspec status --json, openspec list, and README completion table to re-read progress, not memory.
  9. Put acceptance gates on the code side: TestArchitectureGate, build / vet / test / gofmt, frontend typecheck / test / build, scripts/smoke.sh, and end-to-end scripts if necessary. validate only manages spec structure.
  10. To opt out of telemetry, openspec config set telemetry.enabled false, or set OPENSPEC_TELEMETRY=0 / DO_NOT_TRACK=1; it collects only command names and version numbers.

Finally

OpenSpec didn't invent a new format: Requirement and Scenario are old behavior-driven design patterns; proposal / design / tasks are an old combination of RFC and task lists. Its value lies in two things:

One is turning "alignment" into a commit. In SimpleBase, deltas from 7 archived changes have merged into 12 capability baselines; in-flight progress lands in tasks.md checkboxes and the README checklist; requirements are no longer chat transcripts but a set of files you can review, diff, and archive.

Two is giving AI a deterministic read/write contract. openspec instructions tells it which file to write, which sections, and what the project red lines are; openspec status tells it what's missing; openspec archive turns plans into current state, with no step relying on guessing from prompts.