1. OpenSpec 命令执行过程与 Claude Code 提示词详解

OpenSpec 命令执行过程与 Claude Code 提示词详解

本文档记录每个 OpenSpec 命令执行后,生成并传递给 Claude Code Agent 的完整提示词(Prompt)内容。


提示词生成架构

arduino 复制代码
┌─────────────────────────────────────────────────────────────────┐
│                    提示词生成管线                                  │
│                                                                 │
│  用户触发 /opsx:propose  /opsx:apply  等                         │
│       │                                                         │
│       ▼                                                         │
│  ┌─────────────────────┐                                       │
│  │ Skill/Command 模板   │  ← 静态提示词(预定义在 TypeScript 中)  │
│  │ TypeScript 文件      │     定义 Agent 的步骤、规则、Guardrails │
│  └──────────┬──────────┘                                       │
│             │                                                   │
│             ▼                                                   │
│  ┌─────────────────────┐                                       │
│  │ openspec CLI 调用    │  ← 动态数据注入                         │
│  │ status / instructions│     schema instruction, template,     │
│  └──────────┬──────────┘     context, rules, dependencies       │
│             │                                                   │
│             ▼                                                   │
│  ┌─────────────────────┐                                       │
│  │ instruction-loader   │  ← 组装 ArtifactInstructions JSON     │
│  │ generateInstructions()│    合并: schema + template + config   │
│  └──────────┬──────────┘                                       │
│             │                                                   │
│             ▼                                                   │
│  ┌─────────────────────┐                                       │
│  │ Claude Code Agent    │  ← 接收完整提示词,执行任务              │
│  │ 读取 JSON 或文本输出  │                                       │
│  └─────────────────────┘                                       │
└─────────────────────────────────────────────────────────────────┘

提示词分为 两层

层级 来源 内容
静态层 src/core/templates/workflows/*.ts Skill/Command 的完整指令模板,定义 Agent 的行为步骤
动态层 src/core/artifact-graph/instruction-loader.ts 每次 CLI 调用时注入的上下文:schema instruction、template、context、rules、dependencies

一、EXPLORE 阶段提示词

触发命令: /opsx:explore

Skill 模板来源 : src/core/templates/workflows/explore.ts

完整提示词(简化版,核心部分):

markdown 复制代码
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.

**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files,
search code, and investigate the codebase, but you must NEVER write code or implement
features. If the user asks you to implement something, remind them to exit explore mode
first and create a change proposal.

**This is a stance, not a workflow.** There are no fixed steps, no required sequence,
no mandatory outputs. You're a thinking partner helping the user explore.

---

## The Stance

- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions
- **Visual** - Use ASCII diagrams liberally
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions
- **Grounded** - Explore the actual codebase when relevant

---

## What You Might Do

Depending on what the user brings:

**Explore the problem space**
- Ask clarifying questions
- Challenge assumptions
- Reframe the problem
- Find analogies

**Investigate the codebase**
- Map existing architecture
- Find integration points
- Identify patterns already in use
- Surface hidden complexity

**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)

**Visualize** (use ASCII diagrams)

**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations

---

## OpenSpec Awareness

### Check for context
At the start:
  openspec list --json

### When no change exists
Think freely. When insights crystallize, offer:
- "This feels solid enough to start a change. Want me to create a proposal?"

### When a change exists
1. Read existing artifacts for context
   - openspec/changes/<name>/proposal.md
   - openspec/changes/<name>/design.md
   - openspec/changes/<name>/tasks.md
2. Reference them naturally in conversation
3. Offer to capture when decisions are made:
   | Insight Type         | Where to Capture            |
   |---------------------|-----------------------------|
   | New requirement     | specs/<capability>/spec.md  |
   | Design decision     | design.md                   |
   | Scope changed       | proposal.md                 |
   | New work identified | tasks.md                    |

---

## Guardrails
- **Don't implement** - Never write code
- **Don't fake understanding** - Dig deeper
- **Don't rush** - Discovery is thinking time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

特点 : 这是一个"思考姿态"而非工作流。没有固定步骤,不强制输出。核心约束是 不写代码


二、PROPOSE 阶段提示词

触发命令: /opsx:propose <描述>

Skill 模板来源 : src/core/templates/workflows/propose.ts

第 1 层:静态 Skill 提示词(定义 Agent 行为)

sql 复制代码
Propose a new change - create the change and generate all artifacts in one step.

I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)

When ready to implement, run /opsx:apply

---

**Input**: The user's request should include a change name (kebab-case) OR a description.

**Steps**

1. **If no clear input provided, ask what they want to build**
   Use the AskUserQuestion tool to ask:
   > "What change do you want to work on? Describe what you want to build or fix."
   From their description, derive a kebab-case name (e.g., "add user authentication" → add-user-auth).
   **IMPORTANT**: Do NOT proceed without understanding what the user wants to build.

2. **Create the change directory**
   openspec new change "<name>"
   This creates a scaffolded change at openspec/changes/<name>/ with .openspec.yaml.

3. **Get the artifact build order**
   openspec status --change "<name>" --json
   Parse the JSON to get:
   - applyRequires: array of artifact IDs needed before implementation (e.g., ["tasks"])
   - artifacts: list of all artifacts with their status and dependencies

4. **Create artifacts in sequence until apply-ready**
   Use the TodoWrite tool to track progress.
   Loop through artifacts in dependency order:

   a. For each artifact that is ready (dependencies satisfied):
      - Get instructions:
        openspec instructions <artifact-id> --change "<name>" --json
      - The instructions JSON includes:
        - context: Project background (constraints for you - do NOT include in output)
        - rules: Artifact-specific rules (constraints for you - do NOT include in output)
        - template: The structure to use for your output file
        - instruction: Schema-specific guidance for this artifact type
        - resolvedOutputPath: Resolved path to write the artifact
        - dependencies: Completed artifacts to read for context
      - Read any completed dependency files for context
      - Create the artifact file using template as the structure
      - Apply context and rules as constraints - but do NOT copy them into the file
      - Show brief progress: "Created <artifact-id>"

   b. Continue until all applyRequires artifacts are complete

   c. If an artifact requires user input:
      - Use AskUserQuestion tool to clarify

5. **Show final status**
   openspec status --change "<name>"

**Guardrails**
- Create ALL artifacts needed for implementation
- Always read dependency artifacts before creating a new one
- context and rules are constraints for YOU, not content for the file
- Do NOT copy <context>, <rules>, <project_context> blocks into the artifact

第 2 层:动态指令(每个制品的提示词)

当 Agent 执行 openspec instructions <artifact-id> --change "<name>" --json 时,CLI 返回的 JSON 结构:

proposal 制品的完整指令 JSON:
json 复制代码
{
  "changeName": "add-jwt-auth",
  "artifactId": "proposal",
  "schemaName": "spec-driven",
  "changeDir": "/project/openspec/changes/add-jwt-auth",
  "outputPath": "proposal.md",
  "resolvedOutputPath": "/project/openspec/changes/add-jwt-auth/proposal.md",
  "description": "Initial proposal document outlining the change",
  "instruction": "Create the proposal document that establishes WHY this change is needed.\n\nSections:\n- **Why**: 1-2 sentences on the problem or opportunity...\n- **What Changes**: Bullet list of changes...\n- **Capabilities**: Identify which specs will be created or modified...\n- **Impact**: Affected code, APIs, dependencies...",
  "context": "项目配置文件中的上下文描述(如:这是一个电商平台后端,使用 Node.js + TypeScript)",
  "rules": ["使用 TypeScript 严格模式", "API 必须返回标准错误格式"],
  "template": "## Why\n<!-- Explain the motivation for this change -->\n\n## What Changes\n<!-- Describe what will change -->\n\n## Capabilities\n### New Capabilities\n- `<name>`: <brief description>\n\n### Modified Capabilities\n- `<existing-name>`: <what requirement is changing>\n\n## Impact\n<!-- Affected code, APIs, dependencies, systems -->",
  "dependencies": [],
  "unlocks": ["specs", "design"]
}

文本格式输出 (当不使用 --json 时):

xml 复制代码
<artifact id="proposal" change="add-jwt-auth" schema="spec-driven">

<task>
Create the proposal artifact for change "add-jwt-auth".
Initial proposal document outlining the change
</task>

<project_context>
<!-- This is background information for you. Do NOT include this in your output. -->
这是一个电商平台后端,使用 Node.js + TypeScript
</project_context>

<rules>
<!-- These are constraints for you to follow. Do NOT include this in your output. -->
- 使用 TypeScript 严格模式
- API 必须返回标准错误格式
</rules>

<output>
Write to: /project/openspec/changes/add-jwt-auth/proposal.md
</output>

<instruction>
Create the proposal document that establishes WHY this change is needed.

Sections:
- **Why**: 1-2 sentences on the problem or opportunity. What problem does this solve? Why now?
- **What Changes**: Bullet list of changes. Be specific about new capabilities, modifications, or removals.
- **Capabilities**: Identify which specs will be created or modified...
- **Impact**: Affected code, APIs, dependencies, or systems.
</instruction>

<template>
<!-- Use this as the structure for your output file. Fill in the sections. -->
## Why
<!-- Explain the motivation for this change -->

## What Changes
<!-- Describe what will change -->

## Capabilities
### New Capabilities
- `<name>`: <brief description>

### Modified Capabilities
- `<existing-name>`: <what requirement is changing>

## Impact
<!-- Affected code, APIs, dependencies, systems -->
</template>

<success_criteria>
<!-- To be defined in schema validation rules -->
</success_criteria>

<unlocks>
Completing this artifact enables: specs, design
</unlocks>

</artifact>
specs 制品的完整指令 JSON:
json 复制代码
{
  "changeName": "add-jwt-auth",
  "artifactId": "specs",
  "schemaName": "spec-driven",
  "outputPath": "specs/**/*.md",
  "resolvedOutputPath": "/project/openspec/changes/add-jwt-auth/specs/",
  "instruction": "Create specification files that define WHAT the system should do.\n\nCreate one spec file per capability listed in the proposal's Capabilities section.\n\nDelta operations (use ## headers):\n- **ADDED Requirements**: New capabilities\n- **MODIFIED Requirements**: Changed behavior\n- **REMOVED Requirements**: Deprecated features\n- **RENAMED Requirements**: Name changes only\n\nFormat requirements:\n- Each requirement: `### Requirement: <name>`\n- Use SHALL/MUST for normative requirements\n- Each scenario: `#### Scenario: <name>` with WHEN/THEN format\n- Every requirement MUST have at least one scenario.",
  "dependencies": [
    {
      "id": "proposal",
      "done": true,
      "path": "proposal.md",
      "description": "Initial proposal document outlining the change"
    }
  ],
  "unlocks": ["tasks"]
}

文本格式输出:

xml 复制代码
<artifact id="specs" change="add-jwt-auth" schema="spec-driven">

<task>
Create the specs artifact for change "add-jwt-auth".
Detailed specifications for the change
</task>

<dependencies>
Read these files for context before creating this artifact:

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

<output>
Write to: /project/openspec/changes/add-jwt-auth/specs/
</output>

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

Create one spec file per capability listed in the proposal's Capabilities section.

Delta operations (use ## headers):
- **ADDED Requirements**: New capabilities
- **MODIFIED Requirements**: Changed behavior - MUST include full updated content
- **REMOVED Requirements**: Deprecated features - MUST include Reason and Migration
- **RENAMED Requirements**: Name changes only

Format requirements:
- Each requirement: ### Requirement: <name> followed by description
- Use SHALL/MUST for normative requirements
- Each scenario: #### Scenario: <name> with WHEN/THEN format
- CRITICAL: Scenarios MUST use exactly 4 hashtags (####)
- Every requirement MUST have at least one scenario
</instruction>

<template>
<!-- Use this as the structure for your output file. -->
## ADDED Requirements

### Requirement: <!-- requirement name -->
<!-- requirement text -->

#### Scenario: <!-- scenario name -->
- **WHEN** <!-- condition -->
- **THEN** <!-- expected outcome -->
</template>

<unlocks>
Completing this artifact enables: tasks
</unlocks>

</artifact>
design 制品的完整指令:
xml 复制代码
<artifact id="design" change="add-jwt-auth" schema="spec-driven">

<task>
Create the design artifact for change "add-jwt-auth".
Technical design document with implementation details
</task>

<dependencies>
Read these files for context before creating this artifact:

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

<output>
Write to: /project/openspec/changes/add-jwt-auth/design.md
</output>

<instruction>
Create the design document that explains HOW to implement the change.

When to include design.md (create only if any apply):
- Cross-cutting change (multiple services/modules) or new architectural pattern
- New external dependency or significant data model changes
- Security, performance, or migration complexity
- Ambiguity that benefits from technical decisions before coding

Sections:
- **Context**: Background, current state, constraints, stakeholders
- **Goals / Non-Goals**: What this design achieves and explicitly excludes
- **Decisions**: Key technical choices with rationale (why X over Y?)
- **Risks / Trade-offs**: Known limitations. Format: [Risk] → Mitigation
- **Migration Plan**: Steps to deploy, rollback strategy (if applicable)
- **Open Questions**: Outstanding decisions or unknowns to resolve
</instruction>

<template>
## Context
<!-- Background and current state -->

## Goals / Non-Goals
**Goals:** <!-- What this design aims to achieve -->
**Non-Goals:** <!-- What is explicitly out of scope -->

## Decisions
<!-- Key design decisions and rationale -->

## Risks / Trade-offs
<!-- Known risks and trade-offs -->
</template>

<unlocks>
Completing this artifact enables: tasks
</unlocks>

</artifact>
tasks 制品的完整指令:
xml 复制代码
<artifact id="tasks" change="add-jwt-auth" schema="spec-driven">

<task>
Create the tasks artifact for change "add-jwt-auth".
Implementation checklist with trackable tasks
</task>

<dependencies>
Read these files for context before creating this artifact:

<dependency id="specs" status="done">
  <path>/project/openspec/changes/add-jwt-auth/specs/auth/spec.md</path>
  <description>Detailed specifications for the change</description>
</dependency>

<dependency id="design" status="done">
  <path>/project/openspec/changes/add-jwt-auth/design.md</path>
  <description>Technical design document with implementation details</description>
</dependency>
</dependencies>

<output>
Write to: /project/openspec/changes/add-jwt-auth/tasks.md
</output>

<instruction>
Create the task list that breaks down the implementation work.

**IMPORTANT: Follow the template below exactly.** The apply phase parses
checkbox format to track progress. Tasks not using `- [ ]` won't be tracked.

Guidelines:
- Group related tasks under ## numbered headings
- Each task MUST be a checkbox: `- [ ] X.Y Task description`
- Tasks should be small enough to complete in one session
- Order tasks by dependency
</instruction>

<template>
## 1. <!-- Task Group Name -->
- [ ] 1.1 <!-- Task description -->
- [ ] 1.2 <!-- Task description -->
</template>

</artifact>

schema.yaml 中的 instruction 字段(注入到提示词中)

来自 schemas/spec-driven/schema.yaml,这是 schema 级别的指令 ,会被 instruction-loader.ts 注入到每个制品的 instruction 字段:

yaml 复制代码
# proposal 的 instruction
instruction: |
  Create the proposal document that establishes WHY this change is needed.

  Sections:
  - **Why**: 1-2 sentences on the problem or opportunity. What problem does this solve? Why now?
  - **What Changes**: Bullet list of changes. Be specific about new capabilities, modifications, or removals.
    Mark breaking changes with **BREAKING**.
  - **Capabilities**: Identify which specs will be created or modified:
    - **New Capabilities**: List capabilities being introduced. Each becomes a new specs/<name>/spec.md.
    - **Modified Capabilities**: List existing capabilities whose REQUIREMENTS are changing.
  - **Impact**: Affected code, APIs, dependencies, or systems.

  IMPORTANT: The Capabilities section is critical. It creates the contract between
  proposal and specs phases. Research existing specs before filling this in.

# specs 的 instruction
instruction: |
  Create specification files that define WHAT the system should do.

  Create one spec file per capability listed in the proposal's Capabilities section.

  Delta operations (use ## headers):
  - **ADDED Requirements**: New capabilities
  - **MODIFIED Requirements**: Changed behavior - MUST include full updated content
  - **REMOVED Requirements**: Deprecated features - MUST include Reason and Migration
  - **RENAMED Requirements**: Name changes only

  Format requirements:
  - Each requirement: ### Requirement: <name> followed by description
  - Use SHALL/MUST for normative requirements (avoid should/may)
  - Each scenario: #### Scenario: <name> with WHEN/THEN format
  - CRITICAL: Scenarios MUST use exactly 4 hashtags (####)
  - Every requirement MUST have at least one scenario.

# design 的 instruction
instruction: |
  Create the design document that explains HOW to implement the change.

  When to include design.md (create only if any apply):
  - Cross-cutting change (multiple services/modules) or new architectural pattern
  - New external dependency or significant data model changes
  - Security, performance, or migration complexity

  Sections:
  - **Context**: Background, current state, constraints, stakeholders
  - **Goals / Non-Goals**: What this design achieves and explicitly excludes
  - **Decisions**: Key technical choices with rationale (why X over Y?)
  - **Risks / Trade-offs**: Known limitations. Format: [Risk] → Mitigation

# tasks 的 instruction
instruction: |
  Create the task list that breaks down the implementation work.

  **IMPORTANT: Follow the template below exactly.** The apply phase parses
  checkbox format to track progress. Tasks not using `- [ ]` won't be tracked.

  Guidelines:
  - Group related tasks under ## numbered headings
  - Each task MUST be a checkbox: `- [ ] X.Y Task description`
  - Tasks should be small enough to complete in one session
  - Order tasks by dependency

三、APPLY 阶段提示词

触发命令: /opsx:apply [变更名称]

Skill 模板来源 : src/core/templates/workflows/apply-change.ts

第 1 层:静态 Skill 提示词

sql 复制代码
Implement tasks from an OpenSpec change.

**Input**: Optionally specify a change name. If omitted, check if it can be inferred
from conversation context. If vague or ambiguous you MUST prompt for available changes.

**Steps**

1. **Select the change**
   If a name is provided, use it. Otherwise:
   - Infer from conversation context
   - Auto-select if only one active change exists
   - If ambiguous, run `openspec list --json` and use AskUserQuestion tool
   Always announce: "Using change: <name>"

2. **Check status to understand the schema**
   openspec status --change "<name>" --json
   Parse the JSON to understand:
   - schemaName: The workflow being used (e.g., "spec-driven")
   - Which artifact contains the tasks (typically "tasks" for spec-driven)

3. **Get apply instructions**
   openspec instructions apply --change "<name>" --json

   This returns:
   - contextFiles: artifact ID -> array of concrete file paths
   - Progress (total, complete, remaining)
   - Task list with status
   - Dynamic instruction based on current state

   Handle states:
   - state: "blocked" (missing artifacts): suggest using openspec-continue-change
   - state: "all_done": congratulate, suggest archive
   - Otherwise: proceed to implementation

4. **Read context files**
   Read every file path listed under contextFiles from the apply instructions output.
   - spec-driven: proposal, specs, design, tasks

5. **Show current progress**
   Display schema, progress, remaining tasks, dynamic instruction.

6. **Implement tasks (loop until done or blocked)**
   For each pending task:
   - Show which task is being worked on
   - Make the code changes required (keep changes minimal)
   - Mark task complete: `- [ ]` → `- [x]`
   - Continue to next task

   Pause if:
   - Task is unclear → ask for clarification
   - Implementation reveals a design issue → suggest updating artifacts
   - Error or blocker encountered → report and wait for guidance

7. **On completion or pause, show status**

第 2 层:动态 Apply 指令

当 Agent 执行 openspec instructions apply --change "<name>" --json 时:

Apply 指令 JSON:
json 复制代码
{
  "changeName": "add-jwt-auth",
  "changeDir": "/project/openspec/changes/add-jwt-auth",
  "schemaName": "spec-driven",
  "contextFiles": {
    "proposal": ["/project/openspec/changes/add-jwt-auth/proposal.md"],
    "specs": ["/project/openspec/changes/add-jwt-auth/specs/auth/spec.md"],
    "design": ["/project/openspec/changes/add-jwt-auth/design.md"],
    "tasks": ["/project/openspec/changes/add-jwt-auth/tasks.md"]
  },
  "progress": {
    "total": 7,
    "complete": 2,
    "remaining": 5
  },
  "tasks": [
    {"id": "1", "description": "1.1 Create JWT utility module", "done": true},
    {"id": "2", "description": "1.2 Add JWT dependency to package.json", "done": true},
    {"id": "3", "description": "2.1 Implement token generation endpoint", "done": false},
    {"id": "4", "description": "2.2 Add token validation middleware", "done": false},
    {"id": "5", "description": "2.3 Add token refresh endpoint", "done": false},
    {"id": "6", "description": "3.1 Write unit tests for JWT module", "done": false},
    {"id": "7", "description": "3.2 Write integration tests for auth flow", "done": false}
  ],
  "state": "in_progress",
  "instruction": "Read context files, work through pending tasks, mark complete as you go.\nPause if you hit blockers or need clarification."
}
Apply 指令文本格式:
markdown 复制代码
## Apply: add-jwt-auth
Schema: spec-driven

### Context Files
- proposal: /project/openspec/changes/add-jwt-auth/proposal.md
- specs: /project/openspec/changes/add-jwt-auth/specs/auth/spec.md
- design: /project/openspec/changes/add-jwt-auth/design.md
- tasks: /project/openspec/changes/add-jwt-auth/tasks.md

### Progress
2/7 complete

### Tasks
- [x] 1.1 Create JWT utility module
- [x] 1.2 Add JWT dependency to package.json
- [ ] 2.1 Implement token generation endpoint
- [ ] 2.2 Add token validation middleware
- [ ] 2.3 Add token refresh endpoint
- [ ] 3.1 Write unit tests for JWT module
- [ ] 3.2 Write integration tests for auth flow

### Instruction
Read context files, work through pending tasks, mark complete as you go.
Pause if you hit blockers or need clarification.
不同状态的 Apply 指令:

blocked 状态(制品未完成):

json 复制代码
{
  "state": "blocked",
  "missingArtifacts": ["design", "tasks"],
  "instruction": "Cannot apply this change yet. Missing artifacts: design, tasks.\nUse the openspec-continue-change skill to create the missing artifacts first."
}

all_done 状态(全部完成):

json 复制代码
{
  "state": "all_done",
  "progress": {"total": 7, "complete": 7, "remaining": 0},
  "instruction": "All tasks are complete! This change is ready to be archived.\nConsider running tests and reviewing the changes before archiving."
}

schema.yaml 中的 apply instruction:

yaml 复制代码
apply:
  requires: [tasks]
  tracks: tasks.md
  instruction: |
    Read context files, work through pending tasks, mark complete as you go.
    Pause if you hit blockers or need clarification.

这个 instruction 字段会被注入到 Apply 指令 JSON 的 instruction 字段中。


四、ARCHIVE 阶段提示词

触发命令: /opsx:archive [变更名称]

Skill 模板来源 : src/core/templates/workflows/archive-change.ts

完整提示词:

sql 复制代码
Archive a completed change in the experimental workflow.

**Input**: Optionally specify a change name. If omitted, check if it can be inferred
from conversation context. If vague or ambiguous you MUST prompt for available changes.

**Steps**

1. **If no change name provided, prompt for selection**
   Run `openspec list --json` to get available changes.
   Use the AskUserQuestion tool to let the user select.
   Show only active changes (not already archived).
   Include the schema used for each change if available.
   **IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.

2. **Check artifact completion status**
   Run `openspec status --change "<name>" --json`
   Parse the JSON to understand:
   - schemaName: The workflow being used
   - artifacts: List of artifacts with their status (done or other)

   If any artifacts are not done:
   - Display warning listing incomplete artifacts
   - Use AskUserQuestion tool to confirm user wants to proceed

3. **Check task completion status**
   Read the tasks file (typically tasks.md) to check for incomplete tasks.
   Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).

   If incomplete tasks found:
   - Display warning showing count of incomplete tasks
   - Use AskUserQuestion tool to confirm user wants to proceed

4. **Assess delta spec sync state**
   Check for delta specs at openspec/changes/<name>/specs/.
   If delta specs exist:
   - Compare each delta spec with its corresponding main spec
   - Determine what changes would be applied (adds, modifications, removals, renames)
   - Show a combined summary before prompting

   Prompt options:
   - If changes needed: "Sync now (recommended)", "Archive without syncing"
   - If already synced: "Archive now", "Sync anyway", "Cancel"

   If user chooses sync, use Task tool to invoke openspec-sync-specs.

5. **Perform the archive**
   mkdir -p openspec/changes/archive
   mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>

6. **Display summary**
   Show archive completion summary including:
   - Change name, Schema, Archive location, Spec sync status, Warnings

成功输出:

markdown 复制代码
## Archive Complete

**Change:** add-jwt-auth
**Schema:** spec-driven
**Archived to:** openspec/changes/archive/2026-06-18-add-jwt-auth/
**Specs:** ✓ Synced to main specs

All artifacts complete. All tasks complete.

五、其他工作流命令提示词

/opsx:new - 创建新变更

Skill 模板 : src/core/templates/workflows/new-change.ts

sql 复制代码
Start a new change using the experimental artifact-driven approach.

Steps:
1. If no clear input provided, ask what they want to build
2. Determine the workflow schema (default is spec-driven)
3. Create the change directory: openspec new change "<name>"
4. Show the artifact status
5. Get instructions for the first artifact
6. STOP and wait for user direction

关键区别:与 propose 不同,new 只创建目录,不生成制品。它停在第 6 步等待用户指示。

/opsx:continue - 继续创建制品

Skill 模板 : src/core/templates/workflows/continue-change.ts

vbnet 复制代码
Continue working on a change by creating the next artifact.

Steps:
1. Select the change
2. Get status: openspec status --change "<name>" --json
3. Find the next "ready" artifact (dependencies satisfied)
4. Get instructions: openspec instructions <artifact-id> --change "<name>" --json
5. Parse the JSON. Key fields:
   - context: Project background (constraints - do NOT include in output)
   - rules: Artifact-specific rules (constraints - do NOT include in output)
   - template: The structure to use for your output file
   - instruction: Schema-specific guidance
   - resolvedOutputPath: Where to write the artifact
   - dependencies: Completed artifacts to read for context
6. Read dependency files
7. Create the artifact file using template as structure
8. Show brief progress message

/opsx:ff (Fast-Forward) - 快速生成所有制品

Skill 模板 : src/core/templates/workflows/ff-change.ts

sql 复制代码
Fast-forward through artifact creation - generate everything needed to start
implementation in one go.

Steps:
1. Select the change
2. Get status to understand the schema
3. Loop through artifacts in dependency order
4. Create each artifact using openspec instructions <artifact-id> --json
5. Continue until all applyRequires artifacts are complete

与 propose 的区别:ff 假设变更目录已存在,只生成缺失的制品。propose 是先创建变更再生成制品。

/opsx:verify - 验证实现

Skill 模板 : src/core/templates/workflows/verify-change.ts

markdown 复制代码
Verify the implementation of a change against its specs, tasks, and design.

Verification dimensions:
1. Completeness: Are all tasks implemented?
2. Correctness: Does the implementation match the specs?
3. Coherence: Does the code follow the design decisions?

Steps:
1. Select the change
2. Read all context files (proposal, specs, design, tasks)
3. Review the actual code changes
4. Report findings for each dimension
5. Suggest fixes for any gaps

/opsx:sync - 同步 Delta Specs

Skill 模板 : src/core/templates/workflows/sync-specs.ts

vbnet 复制代码
Sync delta specs from a change to main specs.

This is an agent-driven operation - you will read delta specs and directly edit
main specs to apply the changes.

Delta operations:
- ADDED Requirements - New requirements to add
- MODIFIED Requirements - Changes to existing requirements
- REMOVED Requirements - Requirements to remove
- RENAMED Requirements - Requirements to rename

Steps:
1. Select the change
2. Read delta specs from openspec/changes/<name>/specs/
3. Read corresponding main specs from openspec/specs/
4. Apply delta operations to main specs
5. Show summary of changes applied

六、提示词组装完整流程

generateInstructions() 函数(instruction-loader.ts:273-341)

arduino 复制代码
generateInstructions(context, artifactId, projectRoot)
  │
  ├─ 1. 从 schema 获取 artifact 定义
  │    artifact = graph.getArtifact(artifactId)
  │    - id: "proposal"
  │    - generates: "proposal.md"
  │    - template: "proposal.md"
  │    - instruction: "Create the proposal document..."
  │    - requires: []
  │
  ├─ 2. 加载模板文件
  │    template = loadTemplate(schemaName, artifact.template)
  │    → 读取 schemas/spec-driven/templates/proposal.md
  │
  ├─ 3. 获取依赖信息
  │    dependencies = getDependencyInfo(artifact, graph, completed)
  │    → [{id: "proposal", done: true, path: "proposal.md", ...}]
  │
  ├─ 4. 获取解锁的制品
  │    unlocks = getUnlockedArtifacts(graph, artifactId)
  │    → ["specs", "design"]
  │
  ├─ 5. 读取项目配置(可选)
  │    projectConfig = readProjectConfig(projectRoot)
  │    → {context: "项目背景", rules: {proposal: [...]}}
  │
  └─ 6. 组装 ArtifactInstructions
       {
         changeName,
         artifactId,
         schemaName,
         outputPath: artifact.generates,
         resolvedOutputPath: join(changeDir, artifact.generates),
         existingOutputPaths: resolveArtifactOutputs(...),
         description: artifact.description,
         instruction: artifact.instruction,        // ← 来自 schema.yaml
         context: projectConfig.context,            // ← 来自项目配置
         rules: projectConfig.rules[artifactId],    // ← 来自项目配置
         template: templateContent,                 // ← 来自 .md 模板文件
         dependencies,                              // ← 依赖信息
         unlocks                                    // ← 解锁的制品
       }

提示词注入顺序

xml 复制代码
最终提示词 = 静态 Skill 提示词 + 动态 CLI 输出

┌──────────────────────────────────────────────────────────┐
│  静态 Skill 提示词 (TypeScript 模板)                      │
│  - Agent 行为步骤                                        │
│  - Guardrails                                           │
│  - 输出格式                                              │
└──────────────────────────────────────────────────────────┘
                          │
                          ▼
┌──────────────────────────────────────────────────────────┐
│  动态指令 JSON (openspec instructions --json)              │
│                                                          │
│  <context>     项目背景(AI 约束,不写入文件)              │
│  <rules>       制品特定规则(AI 约束,不写入文件)          │
│  <template>    输出结构(来自 .md 模板)                    │
│  <instruction> Schema 级指导(来自 schema.yaml)           │
│  <output>      写入路径                                   │
│  <dependencies> 依赖文件路径                               │
│  <unlocks>     解锁的制品                                  │
└──────────────────────────────────────────────────────────┘

七、完整示例:端到端提示词流

用户: /opsx:propose 实现 JWT 认证系统

Step 1: Propose Skill 加载

Agent 接收到的完整提示词 = propose.ts 中的完整指令模板。

Step 2: Agent 执行 openspec new change "add-jwt-auth"

创建目录结构:

bash 复制代码
openspec/changes/add-jwt-auth/
└── .openspec.yaml
Step 3: Agent 执行 openspec status --change "add-jwt-auth" --json
json 复制代码
{
  "changeName": "add-jwt-auth",
  "schemaName": "spec-driven",
  "applyRequires": ["tasks"],
  "artifacts": [
    {"id": "proposal", "status": "ready"},
    {"id": "specs", "status": "blocked", "missingDeps": ["proposal"]},
    {"id": "design", "status": "blocked", "missingDeps": ["proposal"]},
    {"id": "tasks", "status": "blocked", "missingDeps": ["specs", "design"]}
  ]
}
Step 4: Agent 执行 openspec instructions proposal --change "add-jwt-auth" --json

收到前面展示的 proposal 完整指令 JSON,创建 proposal.md

Step 5: 循环创建 specs, design, tasks

每个制品都收到各自的指令 JSON,包含:

  • 依赖制品的路径(如 proposal.md 已创建,specs 可以看到它)
  • schema 级别的 instruction(指导如何写这个制品)
  • template(输出结构)
  • context + rules(项目配置注入的约束)
Step 6: 用户执行 /opsx:apply add-jwt-auth

Agent 收到 apply Skill 提示词 → 调用 openspec instructions apply --json → 收到 tasks 列表 → 逐项实施。


八、关键设计模式总结

1. 约束与内容分离

swift 复制代码
Agent 看到的:
├── <context>      ← "这是一个电商平台后端"(约束,不写入文件)
├── <rules>        ← "使用 TypeScript 严格模式"(约束,不写入文件)
└── 生成的文件内容:  ← "## Why\n..."(写入 proposal.md)

Guardrail : contextrules 是 Agent 的内部约束,绝不能复制到制品文件中。

2. Schema 驱动

arduino 复制代码
schema.yaml 定义:
├── artifacts[].instruction  ← 每个制品的生成指导
├── apply.instruction        ← 实施阶段的操作指南
└── apply.requires           ← 实施前必须完成的制品

3. 依赖驱动执行

scss 复制代码
proposal (无依赖) → specs (依赖 proposal) → design (依赖 proposal) → tasks (依赖 specs + design)

Agent 只创建 status 为 "ready" 的制品。

4. 项目配置注入

yaml 复制代码
openspec/config.yaml (项目级配置):

context: |
  这是一个电商平台后端,使用 Node.js + TypeScript。
  使用 RESTful API 风格。

rules:
  proposal:
    - 提案必须包含影响分析
  tasks:
    - 每个任务必须可独立测试
    - 必须包含测试任务

这些会被注入到每个制品的 contextrules 字段中。


九、提示词源码位置索引

以下索引标注了每个提示词在源码中的具体生成位置,便于查看提示词生成逻辑。

9.1 静态层:Skill/Command 模板

阶段 文件路径 Skill 函数 Command 函数
Explore src/core/templates/workflows/explore.ts getOpsxExploreSkillTemplate() getOpsxExploreCommandTemplate()
Propose src/core/templates/workflows/propose.ts getOpsxProposeSkillTemplate() getOpsxProposeCommandTemplate() (L119-226)
Apply src/core/templates/workflows/apply-change.ts getApplyChangeSkillTemplate() (L9-165) getOpsxApplyCommandTemplate() (L167-322)
Archive src/core/templates/workflows/archive-change.ts getArchiveChangeSkillTemplate() (L9-123) getOpsxArchiveCommandTemplate() (L125-285)
New src/core/templates/workflows/new-change.ts getNewChangeSkillTemplate() getOpsxNewCommandTemplate()
Continue src/core/templates/workflows/continue-change.ts getContinueChangeSkillTemplate() getOpsxContinueCommandTemplate()
Fast-Forward src/core/templates/workflows/ff-change.ts getOpsxFastForwardSkillTemplate() getOpsxFastForwardCommandTemplate()
Verify src/core/templates/workflows/verify-change.ts getVerifyChangeSkillTemplate() getOpsxVerifyCommandTemplate()
Sync src/core/templates/workflows/sync-specs.ts getOpsxSyncSkillTemplate() getOpsxSyncCommandTemplate()
Bulk Archive src/core/templates/workflows/bulk-archive-change.ts getBulkArchiveChangeSkillTemplate() getOpsxBulkArchiveCommandTemplate()
Onboard src/core/templates/workflows/onboard.ts getOpsxOnboardSkillTemplate() getOpsxOnboardCommandTemplate()

9.2 动态层:指令组装引擎

功能 文件 函数 行号
组装制品提示词 JSON src/core/artifact-graph/instruction-loader.ts generateInstructions() L273-341
加载 .md 模板文件 src/core/artifact-graph/instruction-loader.ts loadTemplate() L179-212
获取依赖信息 src/core/artifact-graph/instruction-loader.ts getDependencyInfo() L346-360
获取解锁制品列表 src/core/artifact-graph/instruction-loader.ts getUnlockedArtifacts() L365-375
格式化变更状态 (status) src/core/artifact-graph/instruction-loader.ts formatChangeStatus() L383-459
加载变更上下文 src/core/artifact-graph/instruction-loader.ts loadChangeContext() L227-257
读取项目配置 (context/rules) src/core/artifact-graph/instruction-loader.ts generateInstructions() L288-321

9.3 动态层:Apply 指令组装

功能 文件 函数 行号
组装 Apply 指令 src/commands/workflow/instructions.ts generateApplyInstructions() L261-360
解析 tasks.md src/commands/workflow/instructions.ts parseTasksFile() L233-254
打印 Apply 文本指令 src/commands/workflow/instructions.ts printApplyInstructionsText() L401-456
打印制品文本指令 src/commands/workflow/instructions.ts printInstructionsText() L107-224
制品指令命令入口 src/commands/workflow/instructions.ts instructionsCommand() L46-105
Apply 指令命令入口 src/commands/workflow/instructions.ts applyInstructionsCommand() L362-399

9.4 Schema 级指令(注入到 instruction 字段)

制品 文件 YAML 路径 行号
proposal schemas/spec-driven/schema.yaml artifacts[0].instruction L9-27
specs schemas/spec-driven/schema.yaml artifacts[1].instruction L34-81
design schemas/spec-driven/schema.yaml artifacts[2].instruction L89-109
tasks schemas/spec-driven/schema.yaml artifacts[3].instruction L117-143
apply schemas/spec-driven/schema.yaml apply.instruction L151-153

9.5 Markdown 模板文件(注入到 template 字段)

制品 文件路径
proposal schemas/spec-driven/templates/proposal.md
spec schemas/spec-driven/templates/spec.md
design schemas/spec-driven/templates/design.md
tasks schemas/spec-driven/templates/tasks.md

9.6 项目配置(注入 context/rules)

功能 文件 函数
读取项目配置 src/core/project-config.ts readProjectConfig()
验证 rules artifact ID src/core/project-config.ts validateConfigRules()
配置嵌套值操作 src/core/config-schema.ts getNestedValue(), setNestedValue(), validateConfig()

9.7 核心调用链

bash 复制代码
用户触发 /opsx:propose
  │
  ▼
src/core/templates/workflows/propose.ts     ← 加载静态 Skill 提示词
  │  getOpsxProposeSkillTemplate()
  │
  ▼ Agent 执行 CLI
  │
  ├─ openspec new change  →  src/commands/workflow/new-change.ts
  ├─ openspec status      →  src/core/artifact-graph/instruction-loader.ts
  │                            formatChangeStatus()
  └─ openspec instructions
       │
       ├─ src/commands/workflow/instructions.ts
       │     instructionsCommand()  →  generateInstructions()
       │
       └─ src/core/artifact-graph/instruction-loader.ts
             generateInstructions()
               │
               ├─ loadTemplate()          ← 读取 schemas/*/templates/*.md
               ├─ getDependencyInfo()     ← 获取依赖状态
               ├─ getUnlockedArtifacts()  ← 获取解锁列表
               └─ readProjectConfig()     ← 注入 context + rules
css 复制代码
用户触发 /opsx:apply
  │
  ▼
src/core/templates/workflows/apply-change.ts  ← 加载静态 Apply Skill 提示词
  │  getApplyChangeSkillTemplate()
  │
  ▼ Agent 执行 CLI
  │
  ├─ openspec status --json
  │     → src/core/artifact-graph/instruction-loader.ts
  │         formatChangeStatus()
  │
  └─ openspec instructions apply --json
        → src/commands/workflow/instructions.ts
            generateApplyInstructions()
              │
              ├─ parseTasksFile()           ← 解析 tasks.md 中的 checkbox
              ├─ resolveArtifactOutputs()   ← 获取所有上下文文件路径
              ├─ resolveSchema()            ← 获取 schema.apply 配置
              └─ 返回: {contextFiles, progress, tasks, state, instruction}
相关推荐
自传.1 天前
尚硅谷 Vibe Coding|第三章(1) Claude Code深度使用与进阶技巧 学习笔记
笔记·学习·尚硅谷·vibecoding
文艺倾年1 天前
【强化学习】数学推导专题,20W字总结(十五)
人工智能·分布式·大模型·强化学习·vibecoding
Captaincc2 天前
TRAE AI创造力大赛,正式启动!
trae·vibecoding
Hector_zh5 天前
逐浪 · 第十一篇: Vibe Coding 下的效率定义与规范建设
人工智能·vibecoding
卡卡罗特AI5 天前
小米MiMoCode官网颜值高?Codex:拿来吧,您嘞!1:1完美复刻~
ai编程·vibecoding
win4r5 天前
Claude Fable 5 来了:这不是 Opus 的小升级,而是 Anthropic 给 Agent 时代递出的新牌
ai编程·claude·vibecoding
仿生狮子6 天前
怎么给CC上下文窗口免费扩容?
开源·claude·vibecoding
AlfredZhao6 天前
AI编程系列02:合并知识功能,给 AI 问数和 RAG 场景打基础
codex·vibecoding