ai-spec-dev 0.37.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +381 -1796
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,1899 +1,484 @@
1
- # ai-spec
1
+ <p align="center">
2
+ <img src="docs-assets/purpose/architecture-overview.svg" alt="ai-spec architecture" width="600" />
3
+ </p>
4
+
5
+ <h1 align="center">ai-spec</h1>
6
+
7
+ <p align="center">
8
+ <strong>AI-Driven Development Orchestrator</strong><br/>
9
+ From a single sentence to production-ready code — the complete development pipeline.
10
+ </p>
11
+
12
+ <p align="center">
13
+ <a href="https://github.com/hzhongzhong/ai-spec"><img src="https://img.shields.io/badge/GitHub-ai--spec-181717?logo=github" alt="GitHub" /></a>
14
+ <a href="https://www.npmjs.com/package/ai-spec-dev"><img src="https://img.shields.io/npm/v/ai-spec-dev?color=cb3837&logo=npm" alt="npm" /></a>
15
+ <img src="https://img.shields.io/badge/version-0.37.0-blue" alt="version" />
16
+ <img src="https://img.shields.io/badge/tests-409%20passed-brightgreen" alt="tests" />
17
+ <img src="https://img.shields.io/badge/providers-9-orange" alt="providers" />
18
+ <img src="https://img.shields.io/badge/license-MIT-green" alt="license" />
19
+ </p>
20
+
21
+ <p align="center">
22
+ <a href="#english">English</a> | <a href="#中文文档">中文</a>
23
+ </p>
2
24
 
3
- <details open>
4
- <summary>中文</summary>
25
+ ---
5
26
 
6
- GitHub: <https://github.com/hzhongzhong/ai-spec>
27
+ <h2 id="english">English</h2>
7
28
 
8
- > AI 驱动的功能开发编排工具 — 从一句话需求到可运行代码的完整流水线,支持单 Repo 及多 Repo 跨端联动
29
+ ### What is ai-spec?
9
30
 
10
- **单 Repo 模式:**
31
+ **ai-spec** is an AI-driven development orchestrator SDK & CLI that transforms a one-line requirement into production-ready code through a fully automated pipeline:
11
32
 
12
33
  ```
13
- 需求描述项目宪法项目感知 → Spec+Tasks → 交互式润色(Diff预览) → Spec质量预评估 → Approval Gate → DSL提取+校验 → DSL Gap Feedback(稀疏时定向补全文档) → Git 隔离 → 代码生成(同层并行) → TDD测试(--tdd) / 测试骨架 → 错误反馈自动修复 → 3-pass 代码审查 → Review→DSL Loop(结构性问题反写契约) → Harness Self-Eval → 经验积累(宪法§9)
34
+ RequirementConstitutionContext → Spec + Tasks → Interactive Refinement
35
+ → Quality Assessment → Approval Gate → DSL Extraction → Gap Feedback
36
+ → Git Isolation → Code Generation → TDD / Test Skeleton → Auto Error Fix
37
+ → 3-Pass Code Review → Review→DSL Loop → Harness Self-Eval → Knowledge Memory
14
38
  ```
15
39
 
16
- **多 Repo 模式(工作区):**
40
+ **Multi-Repo mode (Workspace):**
17
41
 
18
42
  ```
19
- 一句需求 → AI 拆分职责+UX决策 → [后端流水线 → DSL契约] → [前端流水线(注入后端契约)] → 全链路完成
43
+ One requirement → AI splits responsibilities → [Backend pipeline → DSL contract]
44
+ → [Frontend pipeline (injected with backend contract)] → Full-stack complete
20
45
  ```
21
46
 
22
- ***
23
-
24
- ## 目录
25
-
26
- - [快速开始](#快速开始)
27
- - [支持的模型](#支持的模型)
28
- - [命令总览](#命令总览)
29
- - [命令详解](#命令详解)
30
- - [工作流详解](#工作流详解)
31
- - [多 Repo 工作区模式](#多-repo-工作区模式)
32
- - [配置文件](#配置文件)
33
- - [全局安装](#全局安装)
34
- - [项目结构](#项目结构)
35
- - [Release Log](RELEASE_LOG.md)
47
+ ### Key Features
36
48
 
37
- ***
49
+ | Feature | Description |
50
+ |---------|-------------|
51
+ | **Two-Layer Contract** | Human-readable Spec + machine-readable DSL — bridging intent and implementation |
52
+ | **9 AI Providers** | Gemini, Claude, OpenAI, DeepSeek, Qwen, GLM, MiniMax, Doubao, MiMo |
53
+ | **Task-Layered Codegen** | `data → infra → service → api → view → route → test` — structured generation |
54
+ | **Project Constitution** | Self-evolving knowledge base (§1–§9) — AI learns from every review |
55
+ | **Dual Feedback Loops** | DSL Gap Loop + Review→DSL Loop — continuous contract refinement |
56
+ | **Harness Self-Eval** | Automated scoring: compliance 30% + DSL coverage 25% + compile 20% + review 25% |
57
+ | **VCR Recording** | Record & replay AI responses — zero-cost pipeline iteration |
58
+ | **Mock Server** | DSL → Express mock server + MSW handlers + proxy config — instant frontend dev |
59
+ | **OpenAPI Export** | DSL → OpenAPI 3.1.0 YAML/JSON — plug into Postman, Swagger UI, SDK generators |
60
+ | **Multi-Repo Workspace** | Cross-repo orchestration — backend DSL contract injected into frontend pipeline |
38
61
 
39
- ## 快速开始
62
+ ### Quick Start
40
63
 
41
64
  ```bash
42
- # 1. 安装依赖 & 构建
65
+ # Install & build
43
66
  npm install
44
67
  npm run build
45
68
 
46
- # 2. 设置 API Key(以 Gemini 为例)
69
+ # Set API key (Gemini example)
47
70
  export GEMINI_API_KEY=your_key_here
48
71
 
49
- # 3. 首次使用:生成项目宪法(可选,create 会自动触发)
72
+ # Initialize project constitution (optional — create auto-triggers it)
50
73
  ai-spec init
51
74
 
52
- # 4. 开始开发
53
- ai-spec create "给用户模块增加登录功能"
75
+ # Start developing
76
+ ai-spec create "Add login functionality to user module"
54
77
  ```
55
78
 
56
- 运行 `create` 后会依次经历以下步骤:
79
+ ### Pipeline Demo
57
80
 
58
81
  ```
59
82
  [1/6] Loading project context...
60
- Constitution : ✔ found (.ai-spec-constitution.md) ← 已有则直接使用
83
+ Constitution : ✔ found
61
84
  [2/6] Generating spec with gemini/gemini-2.5-pro...
62
85
  ✔ Spec generated. ✔ 7 tasks generated.
63
- [3/6] Interactive spec refinement... ← --fast 可跳过
64
- AI Changes ── +12 -3 lines ← AI 润色后彩色 diff
65
- [3.4/6] Spec quality assessment... ← --skip-assessment 可跳过
86
+ [3/6] Interactive spec refinement...
87
+ AI Changes ── +12 -3 lines
88
+ [3.4/6] Spec quality assessment...
66
89
  Coverage [████████░░] 8/10
67
- Clarity [██████░░░░] 6/10 ← DSL提取可能不准确
90
+ Clarity [██████░░░░] 6/10
68
91
  Constitution[█████████░] 9/10
69
- 未描述密码错误返回的错误码 (§5)
70
- [3.5/6] Approval Gatereview before code generation ← --auto 可跳过
71
- v1 v2: +12 -3 lines (彩色 diff 预览)
72
- Proceed / 📋 View full spec / ❌ Abort
73
- [DSL] Extracting structured DSL from spec... ← --skip-dsl 可跳过
74
- DSL valid
75
- Models : 2
76
- Endpoints : 4
77
- Behaviors : 1
78
- POST /api/v1/auth/login → 200
79
- ...
80
- [DSL+] DSL Gap feedback... ← DSL 稀疏时出现
81
- Found gap: missing_errors
82
- 🔧 Refine spec / Skip
83
- [4/6] Setting up git worktree...
84
- [5/6] ✔ Spec saved : specs/feature-user-login-v1.md (v1)
85
- DSL saved : specs/feature-user-login-v1.dsl.json
86
- Tasks saved: specs/feature-user-login-v1-tasks.json
87
- [6/6] Code generation (mode: api)...
88
- DSL loaded 4 endpoints, 2 models
89
- [████░░░░░░░░░░░░░░░░] 20% TASK-001 💾 Add schema
90
- [████████░░░░░░░░░░░░] 40% TASK-002 🔧 Service
91
- Task-based generation: 8/8 files written across 5 tasks.
92
- [7/10] Test skeleton generation... ← --skip-tests 可跳过
93
- + tests/auth.test.ts ← --tdd 时改为 TDD 真实断言
94
- + tests/auth.service.test.ts
95
- ✔ 2 test file(s) generated.
96
- [8/10] Error feedback loop... ← --skip-error-feedback 可跳过
97
- [cycle 1/2] Running tests: npm test
98
- Tests failed (3 error(s) captured)
99
- Attempting auto-fix (3 error(s))...
100
- ✔ Auto-fixed: src/services/authService.ts
101
- [cycle 2/2] Running tests: npm test
102
- Tests passed.
103
- All checks passed after 2 cycle(s).
104
- [9/10] Automated code review (3-pass: architecture + implementation + impact/complexity)...
105
- Pass 1/3: Architecture review...
106
- Pass 2/3: Implementation review...
107
- Pass 3/3: Impact & complexity assessment...
108
- 🌊 影响等级: 中 🧮 复杂度等级: 低
109
- [9.5/10] Review DSL feedback...
110
- Found 1 structural issue that should be fixed in Spec/DSL
111
- Suggested next step: ai-spec update "补充错误码与鉴权约束" --codegen
112
- [10/10] Harness Self-Eval...
113
- ─── Harness Self-Eval ───────────────────────────
114
- Score : [████████░░] 7.8/10
115
- DSL : 8/10 Compile: pass Review: 7.2/10
116
- Detail : Models: 3/4 (75%) Endpoints: 5 Files: 9
117
- Prompt : a3f2c1d8
118
- ─── Knowledge Memory ─────────────────────────────
119
- 2 lesson(s) appended to constitution (§9).
120
- Run ID: 20260326-143022-ab3f in 94.3s · 8 files written
121
- Log : .ai-spec-logs/20260326-143022-ab3f.json
122
- To undo changes: ai-spec restore 20260326-143022-ab3f
123
- ```
92
+ [DSL] Extracting structured DSL...
93
+ DSL validModels: 2 Endpoints: 4 Behaviors: 1
94
+ [6/6] Code generation (task-by-task)...
95
+ [████████████████████] 100% 8/8 files written
96
+ [7/10] Test skeleton 2 test files generated
97
+ [8/10] Error feedback → auto-fixed 3 errors in 2 cycles
98
+ [9/10] 3-pass code review → Score: 7.8/10
99
+ [10/10] Harness Self-Eval → 7.8/10
100
+ 2 lesson(s) → constitution §9
101
+ ```
102
+
103
+ ### Supported Providers
104
+
105
+ | Provider | Keyword | Env Variable | Default Model |
106
+ |----------|---------|-------------|---------------|
107
+ | MiMo (Xiaomi) | `mimo` | `MIMO_API_KEY` | `mimo-v2-pro` |
108
+ | Google Gemini | `gemini` | `GEMINI_API_KEY` | `gemini-2.5-pro` |
109
+ | Anthropic Claude | `claude` | `ANTHROPIC_API_KEY` | `claude-opus-4-6` |
110
+ | OpenAI | `openai` | `OPENAI_API_KEY` | `o3` |
111
+ | DeepSeek | `deepseek` | `DEEPSEEK_API_KEY` | `deepseek-chat` |
112
+ | Qwen | `qwen` | `DASHSCOPE_API_KEY` | `qwen3-235b-a22b` |
113
+ | GLM (Zhipu) | `glm` | `ZHIPU_API_KEY` | `glm-5` |
114
+ | MiniMax | `minimax` | `MINIMAX_API_KEY` | `MiniMax-Text-2.7` |
115
+ | Doubao | `doubao` | `ARK_API_KEY` | `doubao-pro-256k` |
116
+
117
+ ### Commands
118
+
119
+ ```
120
+ ai-spec init Analyze codebase, generate project constitution
121
+ ai-spec create [idea] Full pipeline: constitution spec → DSL → codegen → review → self-eval
122
+ ai-spec update [change] Incremental update: modify spec → re-extract DSL → regenerate affected files
123
+ ai-spec learn [lesson] Inject knowledge directly into constitution §9
124
+ ai-spec review [file] 3-pass AI code review (architecture + implementation + impact)
125
+ ai-spec export DSL → OpenAPI 3.1.0 YAML/JSON
126
+ ai-spec types DSL TypeScript types (models + endpoint types + API_ENDPOINTS)
127
+ ai-spec mock DSL Mock server + MSW handlers + proxy config
128
+ ai-spec dashboard Generate static HTML harness dashboard
129
+ ai-spec restore <runId> Rollback all files modified by a specific run
130
+ ai-spec model Interactive provider/model switcher
131
+ ai-spec config View/modify project configuration
132
+ ai-spec workspace init Initialize multi-repo workspace
133
+ ```
134
+
135
+ ### Architecture
136
+
137
+ ```
138
+ ┌─────────────────────────────────────────────────────────────────┐
139
+ │ ai-spec Pipeline │
140
+ ├─────────┬──────────┬──────────┬──────────┬──────────┬──────────┤
141
+ Context │ Spec │ DSL │ Codegen │ Review │ Eval │
142
+ Loader │Generator │Extractor │Generator │ 3-Pass │ Harness │
143
+ │ │ + Tasks │+Validate │Task-by- │+Feedback │Self-Eval
144
+ │ │ │+Gap Loop │ Task │ Loop │+Memory
145
+ ├─────────┴──────────┴──────────┴──────────┴──────────┴──────────┤
146
+ │ Provider Abstraction Layer │
147
+ │ Gemini │ Claude │ OpenAI │ DeepSeek │ Qwen │ GLM │ ... (×9) │
148
+ ├─────────────────────────────────────────────────────────────────┤
149
+ │ Output Generators │
150
+ │ OpenAPI Export │ TypeScript Types │ Mock Server │ Dashboard │
151
+ └─────────────────────────────────────────────────────────────────┘
152
+ ```
153
+
154
+ ### Two-Layer Contract System
155
+
156
+ ```
157
+ ┌──────────────────────┐ ┌──────────────────────┐
158
+ │ Feature Spec (md) │ │ SpecDSL (json) │
159
+ │ │ │ │
160
+ │ Human-readable │────▶│ Machine-readable │
161
+ │ Requirements doc │ │ Structured contract │
162
+ │ Reviewed by humans │ │ Consumed by tools │
163
+ └──────────────────────┘ └──────────────────────┘
164
+ │ │
165
+ ▼ ▼
166
+ Code Generation OpenAPI / Types /
167
+ (with DSL context) Mock Server / SDK
168
+ ```
169
+
170
+ ### Project Structure
171
+
172
+ ```
173
+ ai-spec/
174
+ ├── cli/ # CLI commands (commander.js)
175
+ │ ├── commands/ # create, init, review, mock, export, ...
176
+ │ └── index.ts # Entry point
177
+ ├── core/ # Core engine modules
178
+ │ ├── spec-generator.ts # 9-provider AI abstraction
179
+ │ ├── dsl-extractor.ts # Spec → DSL extraction
180
+ │ ├── dsl-validator.ts # Schema validation (no deps)
181
+ │ ├── code-generator.ts # Task-layered code generation
182
+ │ ├── reviewer.ts # 3-pass code review
183
+ │ ├── self-evaluator.ts # Harness scoring
184
+ │ ├── vcr.ts # Record & replay
185
+ │ ├── mock-server-generator.ts
186
+ │ ├── types-generator.ts
187
+ │ ├── openapi-exporter.ts
188
+ │ └── ... # 25+ modules
189
+ ├── prompts/ # All AI prompts (separated from logic)
190
+ ├── tests/ # 18 test files, 409 test cases
191
+ └── docs-assets/ # Architecture diagrams
192
+ ```
193
+
194
+ ### License
195
+
196
+ MIT
124
197
 
125
- ***
126
-
127
- ## 支持的模型
128
-
129
- | Provider | 关键词 | API Key 环境变量 | 默认模型 |
130
- | ---------------- | ---------- | ------------------- | ------------------ |
131
- | MiMo (Xiaomi) | `mimo` | `MIMO_API_KEY` | `mimo-v2-pro` |
132
- | Google Gemini | `gemini` | `GEMINI_API_KEY` | `gemini-2.5-pro` |
133
- | Anthropic Claude | `claude` | `ANTHROPIC_API_KEY` | `claude-opus-4-6` |
134
- | OpenAI | `openai` | `OPENAI_API_KEY` | `o3` |
135
- | DeepSeek | `deepseek` | `DEEPSEEK_API_KEY` | `deepseek-chat` |
136
- | 通义千问 | `qwen` | `DASHSCOPE_API_KEY` | `qwen3-235b-a22b` |
137
- | 智谱 GLM | `glm` | `ZHIPU_API_KEY` | `glm-5` |
138
- | MiniMax | `minimax` | `MINIMAX_API_KEY` | `MiniMax-Text-2.7` |
139
- | 豆包 Doubao | `doubao` | `ARK_API_KEY` | `doubao-pro-256k` |
140
-
141
- **各 provider 可用模型:**
142
-
143
- | Provider | 模型列表 |
144
- | -------- | ------------------------------------------------------------------------------------------------------- |
145
- | mimo | `mimo-v2-pro` |
146
- | gemini | `gemini-2.5-pro` · `gemini-2.5-flash` · `gemini-2.0-flash` · `gemini-2.0-flash-lite` · `gemini-1.5-pro` |
147
- | claude | `claude-opus-4-6` · `claude-sonnet-4-6` · `claude-haiku-4-5` · `claude-3-7-sonnet-20250219` |
148
- | openai | `o3` · `o3-mini` · `o1` · `o1-mini` · `gpt-4o` · `gpt-4o-mini` |
149
- | deepseek | `deepseek-chat`(V3)· `deepseek-reasoner`(R1) |
150
- | qwen | `qwen3-235b-a22b` · `qwen3-72b` · `qwen3-32b` · `qwen3-8b` · `qwen-max` · `qwen-plus` |
151
- | glm | `glm-5` · `glm-5-flash` · `glm-z1`(推理)· `glm-z1-flash` · `glm-4-plus` · `glm-4-flash` |
152
- | minimax | `MiniMax-Text-2.7` · `MiniMax-Text-01` · `abab6.5s-chat` |
153
- | doubao | `doubao-pro-256k` · `doubao-pro-128k` · `doubao-pro-32k` · `doubao-lite-128k` |
154
-
155
- > **兼容说明:**
156
- >
157
- > - MiMo:Anthropic messages 格式,自定义 `api-key` 鉴权头(非标准 Bearer),通过 axios 直接调用
158
- > - DeepSeek / Qwen / GLM / MiniMax / Doubao:OpenAI 兼容接口
159
- > - OpenAI o1/o3:自动切换为 `developer` role(不使用 `system`)
160
- > - Qwen3:自动注入 `enable_thinking: false` 避免 CoT 污染结构化输出
161
-
162
- 查看所有 provider 完整模型列表:
198
+ ---
163
199
 
164
- ```bash
165
- ai-spec model --list
166
- ```
200
+ <h2 id="中文文档">中文文档</h2>
167
201
 
168
- ***
202
+ ### ai-spec 是什么?
169
203
 
170
- ## 命令总览
204
+ **ai-spec** 是一个 AI 驱动的功能开发编排工具 SDK & CLI —— 从一句话需求到可运行代码的完整流水线,支持单 Repo 及多 Repo 跨端联动。
171
205
 
172
206
  ```
173
- ai-spec init 分析代码库,生成项目宪法(.ai-spec-constitution.md)
174
- ai-spec init --consolidate 整合宪法:将 §9 积累教训提炼归并到 §1–§8,清理冗余(Constitution Rebase)
175
- ai-spec create [idea] 完整工作流:宪法 context spec tasksrefineworktree → codegen → 测试生成 → 错误修复 → review → 经验积累
176
- ai-spec update [change] 增量更新:修改现有 Spec 重提取 DSL 识别受影响文件可选重新生成代码
177
- ai-spec learn [lesson] 零摩擦知识注入:直接将工程决策或教训写入宪法 §9(无需运行 review)
178
- ai-spec export DSL → OpenAPI 3.1.0 YAML/JSON(可导入 Postman / Swagger UI / openapi-generator)
179
- ai-spec types DSL → TypeScript 类型文件(models / endpoint request types / API_ENDPOINTS 常量)
180
- ai-spec mock 从 DSL 生成 Mock Server / 前端 Proxy 配置 / MSW Handlers(联调利器)
181
- ai-spec dashboard 生成静态 HTML Harness Dashboard(评分趋势 / prompt 版本对比 / 阶段耗时 / 错误统计)
182
- ai-spec review [file] 对当前 git diff 运行 3-pass AI 代码审查(架构层 + 实现层 + 影响面/复杂度),并打印评分趋势
183
- ai-spec restore <runId> 回滚指定 run 修改的所有文件至原始状态(配合 Run ID 使用)
184
- ai-spec model 交互式切换 AI provider / model,写入 .ai-spec.json
185
- ai-spec config 查看 / 修改 / 重置项目级配置
186
- ai-spec workspace init 初始化多 Repo 工作区(生成 .ai-spec-workspace.json)
187
- ai-spec workspace status 查看工作区内各 Repo 状态
207
+ 需求描述 → 项目宪法 → 项目感知 → Spec+Tasks → 交互式润色(Diff预览)
208
+ Spec质量预评估 Approval Gate DSL提取+校验 → DSL Gap Feedback
209
+ Git 隔离代码生成(同层并行)TDD测试/测试骨架错误反馈自动修复
210
+ → 3-pass 代码审查 ReviewDSL LoopHarness Self-Eval 经验积累(宪法§9)
188
211
  ```
189
212
 
190
- ### 所有命令与选项速查
191
-
192
- #### `ai-spec init`
213
+ **多 Repo 模式(工作区):**
193
214
 
194
215
  ```
195
- ai-spec init # 生成项目宪法(.ai-spec-constitution.md)
196
- ai-spec init --global # 生成全局宪法(.ai-spec-global-constitution.md)— 团队级跨项目规范
197
- ai-spec init --force # 强制覆盖已有宪法
198
- ai-spec init --consolidate # 整合宪法:§9 教训 → §1–§8 核心规则(Constitution Rebase)
199
- ai-spec init --consolidate --dry-run # 预览整合结果,不写入磁盘
200
- ai-spec init --provider <name> # 指定 provider
201
- ai-spec init --model <name> # 指定 model
202
- ai-spec init -k <key> # 指定 API Key
216
+ 一句需求 AI 拆分职责+UX决策 → [后端流水线 → DSL契约]
217
+ [前端流水线(注入后端契约)] 全链路完成
203
218
  ```
204
219
 
205
- #### `ai-spec create`
220
+ ### 核心特性
206
221
 
207
- ```
208
- ai-spec create "功能描述" # 最简用法(交互式询问)
209
- ai-spec create # 省略 idea 时交互式询问
222
+ | 特性 | 描述 |
223
+ |------|------|
224
+ | **双层契约体系** | 人类可读 Spec + 机器可读 DSL —— 打通意图与实现 |
225
+ | **9 大 AI 供应商** | Gemini、Claude、OpenAI、DeepSeek、通义千问、智谱GLM、MiniMax、豆包、MiMo |
226
+ | **分层任务代码生成** | `data → infra → service → api → view → route → test` 结构化生成 |
227
+ | **项目宪法** | 自进化知识库(§1–§9)—— AI 从每次审查中学习 |
228
+ | **双反馈环** | DSL Gap Loop + Review→DSL Loop —— 持续契约精炼 |
229
+ | **Harness 自评** | 自动化评分:合规性 30% + DSL覆盖 25% + 编译 20% + 审查 25% |
230
+ | **VCR 录制回放** | 录制并回放 AI 响应 —— 零成本流水线迭代 |
231
+ | **Mock 服务器** | DSL → Express Mock + MSW Handlers + 代理配置 —— 前端即时联调 |
232
+ | **OpenAPI 导出** | DSL → OpenAPI 3.1.0 YAML/JSON —— 对接 Postman、Swagger UI、SDK 生成器 |
233
+ | **多 Repo 工作区** | 跨仓库编排 —— 后端 DSL 契约自动注入前端流水线 |
210
234
 
211
- # Provider / Model
212
- --provider <name> # Spec 生成使用的 provider(默认 gemini)
213
- --model <name> # Spec 生成使用的模型
214
- -k, --key <key> # API Key
215
- --codegen-provider <name> # 代码生成使用的 provider
216
- --codegen-model <name> # 代码生成使用的模型
217
- --codegen-key <key> # 代码生成的 API Key
235
+ ### 快速开始
218
236
 
219
- # Codegen 模式
220
- --codegen <mode> # claude-code(默认)| api | plan
237
+ ```bash
238
+ # 安装依赖 & 构建
239
+ npm install
240
+ npm run build
221
241
 
222
- # 流程控制
223
- --fast # 跳过 Spec 交互式润色
224
- --auto # 全自动非交互模式(跳过 Approval Gate)
225
- --resume # 续跑:跳过已完成 task
242
+ # 设置 API Key(以 Gemini 为例)
243
+ export GEMINI_API_KEY=your_key_here
226
244
 
227
- # Worktree 控制
228
- --worktree # 强制创建 git worktree(前端项目默认自动跳过)
229
- --skip-worktree # 手动跳过 git worktree 创建
245
+ # 首次使用:生成项目宪法(可选,create 会自动触发)
246
+ ai-spec init
230
247
 
231
- # 跳过某步骤
232
- --skip-tasks # 跳过 Tasks 分解
233
- --skip-dsl # 跳过 DSL 提取
234
- --skip-tests # 跳过测试骨架生成
235
- --skip-error-feedback # 跳过错误反馈自动修复
236
- --skip-review # 跳过代码审查(同时跳过经验积累)
237
- --skip-assessment # 跳过 Spec 质量预评估(省一次 AI 调用)
238
- --force # 强制绕过 minSpecScore 质量门槛(score 不足时继续执行)
239
-
240
- # 模式增强
241
- --tdd # TDD 模式:在代码生成前写入真实断言测试,由 error feedback loop 驱动实现通过测试
248
+ # 开始开发
249
+ ai-spec create "给用户模块增加登录功能"
242
250
  ```
243
251
 
244
- > **Worktree 自动策略:**
245
- >
246
- > - 后端项目(Node.js / Go / PHP 等):默认创建 worktree 隔离分支
247
- > - 前端项目(React / Vue / Next / React-Native):**自动跳过 worktree**,直接在当前仓库生成代码
248
- > - 原因:worktree 不含 `node_modules`,前端 dev server 无法启动
249
- > - 如需强制 worktree 模式,加 `--worktree` flag
250
-
251
- #### `ai-spec review`
252
-
253
- ```
254
- ai-spec review # 自动检测最新 spec,审查当前 git diff
255
- ai-spec review specs/feature-xxx.md # 指定 spec 文件
256
- ai-spec review --provider <name> # 指定 provider
257
- ai-spec review --model <name> # 指定 model
258
- ```
252
+ ### 流水线演示
253
+
254
+ ```
255
+ [1/6] 加载项目上下文...
256
+ Constitution : found
257
+ [2/6] 使用 gemini/gemini-2.5-pro 生成 Spec...
258
+ ✔ Spec 已生成 ✔ 7 个任务已分解
259
+ [3/6] 交互式 Spec 润色...
260
+ AI Changes ── +12 -3 lines
261
+ [3.4/6] Spec 质量预评估...
262
+ 覆盖度 [████████░░] 8/10
263
+ 清晰度 [██████░░░░] 6/10
264
+ 一致性 [█████████░] 9/10
265
+ [DSL] 提取结构化 DSL...
266
+ ✔ DSL 校验通过 — 模型: 2 端点: 4 行为: 1
267
+ [6/6] 代码生成(逐任务)...
268
+ [████████████████████] 100% → 8/8 文件已写入
269
+ [7/10] 测试骨架 → 2 个测试文件
270
+ [8/10] 错误反馈 → 自动修复 3 个错误,2 轮完成
271
+ [9/10] 3-pass 代码审查 → 评分: 7.8/10
272
+ [10/10] Harness 自评 → 7.8/10
273
+ ✔ 2 条经验 → 宪法 §9
274
+ ```
275
+
276
+ ### 支持的模型
277
+
278
+ | Provider | 关键词 | API Key 环境变量 | 默认模型 |
279
+ |----------|--------|-----------------|----------|
280
+ | MiMo (小米) | `mimo` | `MIMO_API_KEY` | `mimo-v2-pro` |
281
+ | Google Gemini | `gemini` | `GEMINI_API_KEY` | `gemini-2.5-pro` |
282
+ | Anthropic Claude | `claude` | `ANTHROPIC_API_KEY` | `claude-opus-4-6` |
283
+ | OpenAI | `openai` | `OPENAI_API_KEY` | `o3` |
284
+ | DeepSeek | `deepseek` | `DEEPSEEK_API_KEY` | `deepseek-chat` |
285
+ | 通义千问 | `qwen` | `DASHSCOPE_API_KEY` | `qwen3-235b-a22b` |
286
+ | 智谱 GLM | `glm` | `ZHIPU_API_KEY` | `glm-5` |
287
+ | MiniMax | `minimax` | `MINIMAX_API_KEY` | `MiniMax-Text-2.7` |
288
+ | 豆包 Doubao | `doubao` | `ARK_API_KEY` | `doubao-pro-256k` |
259
289
 
260
- #### `ai-spec model`
290
+ <details>
291
+ <summary>各 Provider 完整模型列表</summary>
292
+
293
+ | Provider | 模型列表 |
294
+ |----------|---------|
295
+ | mimo | `mimo-v2-pro` |
296
+ | gemini | `gemini-2.5-pro` · `gemini-2.5-flash` · `gemini-2.0-flash` · `gemini-2.0-flash-lite` · `gemini-1.5-pro` |
297
+ | claude | `claude-opus-4-6` · `claude-sonnet-4-6` · `claude-haiku-4-5` · `claude-3-7-sonnet-20250219` |
298
+ | openai | `o3` · `o3-mini` · `o1` · `o1-mini` · `gpt-4o` · `gpt-4o-mini` |
299
+ | deepseek | `deepseek-chat`(V3)· `deepseek-reasoner`(R1) |
300
+ | qwen | `qwen3-235b-a22b` · `qwen3-72b` · `qwen3-32b` · `qwen3-8b` · `qwen-max` · `qwen-plus` |
301
+ | glm | `glm-5` · `glm-5-flash` · `glm-z1` · `glm-z1-flash` · `glm-4-plus` · `glm-4-flash` |
302
+ | minimax | `MiniMax-Text-2.7` · `MiniMax-Text-01` · `abab6.5s-chat` |
303
+ | doubao | `doubao-pro-256k` · `doubao-pro-128k` · `doubao-pro-32k` · `doubao-lite-128k` |
261
304
 
262
- ```
263
- ai-spec model # 交互式选择 provider + model
264
- ai-spec model --list # 列出所有 provider 和可用模型
265
- ```
305
+ </details>
266
306
 
267
- #### `ai-spec config`
307
+ ### 命令总览
268
308
 
269
309
  ```
270
- ai-spec config --show # 打印当前配置
271
- ai-spec config --provider <name> # 设置默认 spec provider
272
- ai-spec config --model <name> # 设置默认 spec model
273
- ai-spec config --codegen <mode> # 设置默认 codegen 模式
274
- ai-spec config --codegen-provider <name> # 设置默认 codegen provider
275
- ai-spec config --codegen-model <name> # 设置默认 codegen model
276
- ai-spec config --min-spec-score <n> # 设置 Spec 质量门槛(1-10,0 = 禁用)
277
- ai-spec config --reset # 清空配置文件
310
+ ai-spec init 分析代码库,生成项目宪法(.ai-spec-constitution.md)
311
+ ai-spec create [idea] 完整流水线:宪法 spec → DSL → 代码生成 → 审查 → 自评
312
+ ai-spec update [change] 增量更新:修改 Spec 重提取 DSL → 重新生成受影响文件
313
+ ai-spec learn [lesson] 零摩擦知识注入,直接写入宪法 §9
314
+ ai-spec review [file] 3-pass AI 代码审查(架构 + 实现 + 影响面)
315
+ ai-spec export DSL OpenAPI 3.1.0 YAML/JSON
316
+ ai-spec types DSL TypeScript 类型文件
317
+ ai-spec mock DSL Mock 服务器 + MSW Handlers + 代理配置
318
+ ai-spec dashboard 生成静态 HTML Harness Dashboard
319
+ ai-spec restore <runId> 回滚指定 run 修改的所有文件
320
+ ai-spec model 交互式切换 AI provider/model
321
+ ai-spec config 查看/修改项目配置
322
+ ai-spec workspace init 初始化多 Repo 工作区
278
323
  ```
279
324
 
280
- > **Spec 质量门槛(minSpecScore)**
281
- >
282
- > - 设置后,`create` 在 Approval Gate 前会运行质量评估,`overallScore` 低于阈值时阻断流程
283
- > - **`--auto`** **模式同样生效**:CI 环境中配置了门槛则强制执行,避免低质量 Spec 静默通过
284
- > - `--force` 可临时绕过(输出黄色警告)
285
- > - 未配置(默认 0)时评估仅为建议性,不阻断
325
+ <details>
326
+ <summary>命令详细选项</summary>
286
327
 
287
- #### `ai-spec learn`
328
+ #### `ai-spec create`
288
329
 
289
330
  ```
290
- ai-spec learn "教训或决策描述" # 直接写入宪法 §9
291
- ai-spec learn # 省略时交互式输入
292
- ```
331
+ ai-spec create "功能描述" # 最简用法
293
332
 
294
- > 适合混用其他 AI 工具(Cursor / Copilot)的团队:在任何场景发现问题或做出架构决策时,无需经过完整 review 流程,直接将知识写入宪法,下次 `create` 即生效。
333
+ # Provider / Model
334
+ --provider <name> # Spec 生成使用的 provider(默认 gemini)
335
+ --model <name> # Spec 生成使用的模型
336
+ --codegen-provider <name> # 代码生成使用的 provider
337
+ --codegen-model <name> # 代码生成使用的模型
338
+ --codegen <mode> # claude-code | api | plan
295
339
 
296
- #### `ai-spec workspace`
340
+ # 流程控制
341
+ --fast # 跳过 Spec 交互式润色
342
+ --auto # 全自动非交互模式
343
+ --resume # 续跑:跳过已完成 task
344
+ --tdd # TDD 模式
297
345
 
298
- ```
299
- ai-spec workspace init # 扫描并初始化工作区(生成 .ai-spec-workspace.json)
300
- ai-spec workspace init --name <n> # 指定工作区名称
301
- ai-spec workspace init --repos a,b # 仅纳入指定目录的 repo
302
- ai-spec workspace status # 列出工作区内所有 repo 及其类型/角色/宪法状态
346
+ # 跳过步骤
347
+ --skip-worktree # 跳过 git worktree
348
+ --skip-tasks # 跳过 Tasks 分解
349
+ --skip-dsl # 跳过 DSL 提取
350
+ --skip-tests # 跳过测试生成
351
+ --skip-error-feedback # 跳过错误反馈
352
+ --skip-review # 跳过代码审查
353
+ --skip-assessment # 跳过质量评估
354
+ --force # 绕过质量门槛
303
355
  ```
304
356
 
305
357
  #### `ai-spec update`
306
358
 
307
359
  ```
308
- ai-spec update "变更描述" # 自动找最新 Spec,生成更新版本(v1 → v2)
309
- ai-spec update # 省略描述时交互式询问
310
- ai-spec update --codegen # 更新 Spec + DSL 后,自动重新生成受影响文件
311
- ai-spec update --spec <path> # 指定要更新的 Spec 文件
312
- ai-spec update --skip-affected # 跳过受影响文件识别(只更新 Spec 和 DSL)
313
- ai-spec update --provider <name> # 指定 provider
314
- ai-spec update --codegen-provider <n> # 代码生成使用不同 provider
315
- ```
316
-
317
- #### `ai-spec export`
318
-
319
- ```
320
- ai-spec export # 读取最新 DSL,生成 openapi.yaml
321
- ai-spec export --format json # 生成 openapi.json
322
- ai-spec export --server <url> # 指定服务器 URL(默认 http://localhost:3000)
323
- ai-spec export --output <path> # 指定输出路径
324
- ai-spec export --dsl <path> # 指定 DSL 文件
360
+ ai-spec update "变更描述" # 自动找最新 Spec
361
+ ai-spec update --codegen # 更新后自动重新生成受影响文件
362
+ ai-spec update --spec <path> # 指定 Spec 文件
363
+ ai-spec update --skip-affected # 跳过受影响文件识别
325
364
  ```
326
365
 
327
366
  #### `ai-spec mock`
328
367
 
329
368
  ```
330
- ai-spec mock # 读取最新 DSL,生成 mock/server.js(Express 独立 Mock 服务器)
331
- ai-spec mock --port 3002 # 指定端口(默认 3001)
332
- ai-spec mock --proxy # 同时生成前端框架 Proxy 配置片段(Vite/Next.js/webpack 自动识别)
333
- ai-spec mock --msw # 同时生成 MSW Handlers(src/mocks/handlers.ts + browser.ts)
334
- ai-spec mock --dsl <path> # 指定 DSL 文件路径(默认自动寻找最新)
335
- ai-spec mock --workspace # 为工作区内所有后端 repo 批量生成 Mock
336
- ai-spec mock --serve --frontend <path> # 生成后直接启动 Mock 服务器 + 自动 patch 前端 Proxy
337
- ai-spec mock --restore --frontend <path> # 撤销 Proxy patch,停止 Mock 服务器
338
- ```
339
-
340
- ***
341
-
342
- ## 命令详解
343
-
344
- ### `ai-spec init`
345
-
346
- 分析当前项目的代码结构(路由、controllers、Prisma schema、错误处理模式),生成 `.ai-spec-constitution.md`。
347
-
348
- 该文件是项目的"宪法",所有后续 Spec 生成和代码生成都会自动遵守其中的规则。
349
-
350
- ```bash
351
- # 生成项目宪法
352
- ai-spec init
353
-
354
- # 指定 provider(默认使用 .ai-spec.json 配置)
355
- ai-spec init --provider claude --model claude-opus-4-6
356
-
357
- # 强制重新生成(覆盖已有文件)
358
- ai-spec init --force
359
- ```
360
-
361
- 生成内容包含:
362
-
363
- ```markdown
364
- # Project Constitution
365
- ## 1. 架构规则 ← 分层约束、模块组织
366
- ## 2. 命名规范 ← 文件名、函数名、路由路径
367
- ## 3. API 规范 ← 响应结构、错误码、认证模式
368
- ## 4. 数据层规范 ← ORM 访问规则、事务处理
369
- ## 5. 错误处理规范 ← 错误抛出和捕获模式
370
- ## 6. 禁区 ← 绝对不能违反的红线
371
- ## 7. 测试规范 ← 测试框架、文件位置
372
- ## 8. 共享配置文件清单 ← i18n/constants/enums/route-index,Append-Only,禁止新建平行文件
373
- ```
374
-
375
- > **自动触发**:如果项目目录下没有 `.ai-spec-constitution.md`,`ai-spec create` 会在 Step 1 自动运行 init,无需手动执行。
376
-
377
- **选项:**
378
-
379
- | 选项 | 说明 |
380
- | ------------------- | -------------------------------------------------- |
381
- | `--provider <name>` | 使用的 AI provider |
382
- | `--model <name>` | 使用的模型 |
383
- | `-k, --key <key>` | API Key |
384
- | `--force` | 覆盖已有宪法文件 |
385
- | `--global` | 生成团队级全局宪法(`.ai-spec-global-constitution.md`)而非项目宪法 |
386
- | `--consolidate` | 整合宪法:将 §9 提炼归并到 §1–§8,清理冗余 |
387
- | `--dry-run` | 配合 `--consolidate`:预览不写入 |
388
-
389
- > **全局宪法 vs 项目宪法**:全局宪法定义团队通用规范(错误码体系、认证模式、日志格式);项目宪法定义本项目特有规范(数据模型、路由前缀、特定限制)。运行时自动合并,项目宪法优先。
390
-
391
- #### Constitution Rebase — 为什么需要定期整合
392
-
393
- `ai-spec review` 每次运行后会把审查 issue 追加到宪法 §9。长期运行后 §9 会积累大量条目(重复措辞、已修复问题、不再适用的早期教训)。宪法被注入每次 AI 调用,超过 2000 字符后会被硬截断,越积越多反而降低效果。
394
-
395
- **建议频率**:§9 达到 8 条以上时(系统会自动提示),运行一次整合。
396
-
397
- ```bash
398
- # 预览效果(不写入)
399
- ai-spec init --consolidate --dry-run
400
-
401
- # 确认后执行
402
- ai-spec init --consolidate
403
- ```
404
-
405
- 整合过程:
406
-
407
- 1. AI 逐条审阅 §9,决定每条教训的去向:**LIFT**(提升至 §1–§8)/ **KEEP**(保留,最多 5 条)/ **DROP**(删除重复/已失效)
408
- 2. 展示彩色 diff,显示前后对比
409
- 3. 自动创建备份(`.ai-spec-constitution.backup-YYYY-MM-DD-HH-MM-SS.md`)后写入
410
-
411
- 典型效果:§9 从 14 条压缩到 4 条,宪法总行数减少 10–20%,核心章节获得新的精确规则。
412
-
413
- ***
414
-
415
- ### `ai-spec create [idea]`
416
-
417
- 启动完整的功能开发流水线。`idea` 参数省略时会交互式询问。
418
-
419
- ```bash
420
- # 最简用法
421
- ai-spec create "增加商品搜索功能"
422
-
423
- # 指定 provider / model
424
- ai-spec create "用户登录" --provider claude --model claude-opus-4-6
425
-
426
- # Spec 用 Claude,代码生成用 Qwen
427
- ai-spec create "购物车结算" \
428
- --provider claude \
429
- --codegen api \
430
- --codegen-provider qwen \
431
- --codegen-model qwen3-72b
432
-
433
- # 全自动模式(非交互,claude -p 执行,节省 token)
434
- ai-spec create "消息通知" --auto
435
-
436
- # 只生成 Spec + Tasks,不写代码
437
- ai-spec create "重构支付模块" --codegen plan --skip-worktree --skip-review
438
-
439
- # 跳过 Tasks 生成
440
- ai-spec create "小功能" --skip-tasks
441
- ```
442
-
443
- **完整选项:**
444
-
445
- | 选项 | 说明 | 默认值 |
446
- | --------------------------- | -------------------------------------------------------------------- | -------------- |
447
- | `--provider <name>` | Spec 生成使用的 provider | `gemini` |
448
- | `--model <name>` | Spec 生成使用的模型 | provider 默认模型 |
449
- | `-k, --key <key>` | API Key(优先级高于环境变量) | — |
450
- | `--codegen <mode>` | 代码生成模式:`claude-code` / `api` / `plan` | `claude-code` |
451
- | `--codegen-provider <name>` | 代码生成使用的 provider | 同 `--provider` |
452
- | `--codegen-model <name>` | 代码生成使用的模型 | — |
453
- | `--codegen-key <key>` | 代码生成的 API Key | — |
454
- | `--skip-worktree` | 跳过 git worktree 创建 | — |
455
- | `--skip-review` | 跳过最终代码审查 | — |
456
- | `--skip-tasks` | 跳过 Tasks 分解(只生成 Spec) | — |
457
- | `--auto` | 非交互模式:用 `claude -p` 执行,同时跳过 Approval Gate(节省 token) | — |
458
- | `--fast` | 跳过交互式 Spec 润色,直接进入代码生成(适合全自动流水线) | — |
459
- | `--resume` | 续跑模式:跳过 tasks.json 中已标记为 `done` 的任务 | — |
460
- | `--skip-dsl` | 跳过 DSL 提取步骤(适合简单功能或快速迭代) | — |
461
- | `--skip-tests` | 跳过测试骨架生成(需要 DSL;`--skip-dsl` 时自动跳过) | — |
462
- | `--skip-error-feedback` | 跳过错误反馈自动修复循环 | — |
463
- | `--tdd` | TDD 模式:代码生成前先写含真实断言的测试,error feedback loop 驱动实现让测试通过(最多 3 轮)。仅支持后端项目 | — |
464
- | `--skip-assessment` | 跳过 Approval Gate 前的 Spec 质量预评估(节省一次 AI 调用) | — |
465
-
466
- **`--codegen`** **三种模式:**
467
-
468
- | 模式 | 说明 |
469
- | ------------- | ---------------------------------------------------------------------------- |
470
- | `claude-code` | 启动 Claude Code CLI。`--auto` 时改为逐 task 运行 `claude -p`(增量执行,失败可 `--resume` 续跑) |
471
- | `api` | 调用 AI API 自动规划文件并逐文件生成。有 Tasks 文件时按 task 顺序生成,支持 `--resume` 续跑 |
472
- | `plan` | 仅输出实施方案,不写任何代码 |
473
-
474
- ***
475
-
476
- ### `ai-spec review [specFile]`
477
-
478
- 抓取当前目录的 git diff,让 AI 以架构师视角对照 Spec 进行代码审查。
479
-
480
- ```bash
481
- # 自动检测 specs/ 目录下最新的 Spec 文件
482
- ai-spec review
483
-
484
- # 指定 Spec 文件
485
- ai-spec review specs/feature-1234567890.md
486
-
487
- # 指定 provider
488
- ai-spec review --provider glm --model glm-5
489
- ```
490
-
491
- **3-pass 输出结构:**
492
-
493
- ```
494
- ─── Pass 1/3: Architecture review ───────────────
495
- ## ✅ 优点 (What's Good)
496
- ## ⚠️ 问题 (Issues Found)
497
- ## 💡 改进建议 (Suggestions)
498
- ## 📊 总体评价 (Overall Assessment) Score: X/10
499
-
500
- ─── Pass 2/3: Implementation review ─────────────
501
- ## ✅ 优点 (What's Good)
502
- ## ⚠️ 问题 (Issues Found)
503
- ## 🔁 历史问题复现 (Recurring Issues)
504
- ## 💡 改进建议 (Suggestions)
505
- ## 📊 综合评分 (Final Score) Score: X/10
506
-
507
- ─── Pass 3/3: Impact & complexity assessment ────
508
- ## 🌊 影响面评估 (Impact Assessment)
509
- 直接影响文件 / 间接范围 / Breaking Changes / 影响等级: 低|中|高
510
- ## 🧮 代码复杂度评估 (Complexity Assessment)
511
- 认知复杂度热点 / 耦合度 / 可维护性风险 / 复杂度等级: 低|中|高
512
-
513
- ─── Review Score Trend ──────────────────────────
514
- 2026-03-26 [████████░░] 8/10 影响:中 复杂度:低 feature-login-v1.md
515
- ```
516
-
517
- > Pass 3 的影响等级和复杂度等级会持久化到 `.ai-spec-reviews.json`,在历史趋势行中显示,三级颜色编码:高=红、中=黄、低=绿。
518
-
519
- > 提示:先执行 `git add .` 再运行 `ai-spec review`,确保所有变更都被纳入审查。
520
-
521
- ***
522
-
523
- ### `ai-spec model`
524
-
525
- 交互式 provider / model 切换器,结果写入当前目录的 `.ai-spec.json`。
526
-
527
- ```bash
528
- # 交互式选择
529
- ai-spec model
530
-
531
- # 查看所有可用 provider 和模型
532
- ai-spec model --list
533
- ```
534
-
535
- ***
536
-
537
- ### `ai-spec config`
538
-
539
- 管理当前项目的默认配置(`.ai-spec.json`)。
540
-
541
- ```bash
542
- ai-spec config --show
543
- ai-spec config --provider qwen --codegen api
544
- ai-spec config --codegen-provider glm --codegen-model glm-5
545
- ai-spec config --reset
546
- ```
547
-
548
- | 选项 | 说明 |
549
- | --------------------------- | ------------------- |
550
- | `--provider <name>` | 默认 spec provider |
551
- | `--model <name>` | 默认 spec model |
552
- | `--codegen <mode>` | 默认代码生成模式 |
553
- | `--codegen-provider <name>` | 默认 codegen provider |
554
- | `--codegen-model <name>` | 默认 codegen model |
555
- | `--show` | 打印当前配置 |
556
- | `--reset` | 清空配置文件 |
557
-
558
- ***
559
-
560
- ### `ai-spec workspace`
561
-
562
- 管理多 Repo 工作区,让 ai-spec 跨越单个项目边界,协同处理包含前端和后端的完整需求。
563
-
564
- ```bash
565
- # 在包含多个 repo 的父目录中执行
566
- cd ~/code/my-project # 下有 backend/ frontend/ 两个子目录
567
-
568
- # 初始化工作区
569
- ai-spec workspace init
570
-
571
- # 查看工作区状态
572
- ai-spec workspace status
573
- ```
574
-
575
- **`workspace init`** **输出示例:**
576
-
577
- ```
578
- ✔ Detected 2 repos:
579
- backend (node-express / backend) constitution: ✔
580
- frontend (react / frontend) constitution: ✘
581
- ✔ Workspace saved: .ai-spec-workspace.json
582
- ```
583
-
584
- **工作区配置文件(`.ai-spec-workspace.json`):**
585
-
586
- ```json
587
- {
588
- "name": "my-project",
589
- "repos": [
590
- { "name": "backend", "path": "backend", "type": "node-express", "role": "backend" },
591
- { "name": "frontend", "path": "frontend", "type": "react", "role": "frontend" }
592
- ]
593
- }
594
- ```
595
-
596
- 初始化完成后,在同一目录运行 `ai-spec create` 会自动进入**多 Repo 联动模式**(参见[多 Repo 工作区模式](#多-repo-工作区模式))。
597
-
598
- | 选项 | 说明 |
599
- | --------------- | -------------------------------------------------------------------------------------------------------- |
600
- | `--name <name>` | 工作区名称(默认取父目录名) |
601
- | `--repos <a,b>` | 只纳入指定目录(逗号分隔),不指定则自动扫描所有含 `package.json` / `go.mod` / `Cargo.toml` / `pom.xml` / `requirements.txt` 的子目录 |
602
-
603
- ***
604
-
605
- ### `ai-spec update [change]`
606
-
607
- `ai-spec create` 负责从零开始;`ai-spec update` 负责存量演进。这是日常迭代中最常用的命令。
608
-
609
- ```bash
610
- # 描述变更,自动找最新 Spec 并生成 v2
611
- ai-spec update "新增商品收藏功能,在 Product 模型上加 isFavorited 字段"
612
-
613
- # 更新完 Spec + DSL 后,自动重新生成受影响的代码文件
614
- ai-spec update "把价格字段从 Int 改为 Float" --codegen
615
-
616
- # 只更新 Spec 和 DSL,不识别受影响文件(快速)
617
- ai-spec update "修复描述文字" --skip-affected
618
- ```
619
-
620
- **三步流程:**
621
-
622
- ```
623
- [1/3] 更新 Spec
624
- AI 读取现有 Spec + 变更描述
625
- → 生成更新后的完整 Spec(保留未变更部分)
626
- → 写入 feature-xxx-v2.md
627
-
628
- [2/3] 更新 DSL
629
- 若存在现有 DSL → 定向更新(只改变了的端点/模型)
630
- 失败时降级为全量重提取
631
- → 写入 feature-xxx-v2.dsl.json
632
-
633
- [3/3] 识别受影响文件
634
- 对比新旧 DSL(新增/修改的端点、模型字段)
635
- → 输出需要 create/modify 的文件列表
636
- → --codegen 时自动重新生成这些文件
637
- ```
638
-
639
- | 选项 | 说明 |
640
- | --------------------------- | ----------------------- |
641
- | `--codegen` | 识别受影响文件后自动重新生成 |
642
- | `--spec <path>` | 指定要更新的 Spec 文件(默认自动找最新) |
643
- | `--skip-affected` | 跳过受影响文件识别 |
644
- | `--provider <name>` | Spec 更新使用的 provider |
645
- | `--codegen-provider <name>` | 代码生成使用的 provider |
646
-
647
- > **`--codegen`** **附带行为(v0.29.0+)**:
648
- >
649
- > - 每次 update 自动生成独立 Run ID,运行摘要(耗时、写入文件数)在结束时打印
650
- > - 写每个受影响文件前先快照原始内容(`.ai-spec-backup/<runId>/`),可用 `ai-spec restore <runId>` 精确回滚
651
- > - 完成后自动对更新后的 Spec 运行代码审查,结论写入宪法 §9(与 `create` 的知识积累机制一致)
652
-
653
- ***
654
-
655
- ### `ai-spec export`
656
-
657
- 将 DSL 导出为标准 OpenAPI 3.1.0,接入整个 OpenAPI 生态:
658
-
659
- ```bash
660
- # 生成 openapi.yaml(默认)
661
- ai-spec export
662
-
663
- # 生成 JSON 格式
664
- ai-spec export --format json
665
-
666
- # 指定生产服务器地址
667
- ai-spec export --server https://api.example.com --output docs/openapi.yaml
668
- ```
669
-
670
- **生成内容:**
671
-
672
- - DSL `models[]` → `components.schemas`(字段类型映射 + required 推断)
673
- - DSL `endpoints[]` → `paths`(路径参数 `:id` → `{id}`,query params,requestBody,success/error responses)
674
- - `auth: true` 端点 → `security: [{bearerAuth: []}]` + JWT `securitySchemes`
675
- - 通用 `ErrorResponse` schema(code + message)
676
-
677
- **下游工具链:**
678
-
679
- ```bash
680
- # 导入 Postman
681
- # File → Import → openapi.yaml
682
-
683
- # 生成 TypeScript SDK
684
- npx openapi-generator-cli generate -i openapi.yaml -g typescript-axios -o sdk/
685
-
686
- # 生成 Go SDK
687
- openapi-generator generate -i openapi.yaml -g go -o sdk/go/
688
-
689
- # 启动 Swagger UI
690
- npx @stoplight/prism-cli mock openapi.yaml
691
- ```
692
-
693
- | 选项 | 说明 |
694
- | --------------------- | --------------------------------------------------- |
695
- | `--format yaml\|json` | 输出格式(默认 yaml) |
696
- | `--server <url>` | OpenAPI servers\[0].url(默认 <http://localhost:3000)> |
697
- | `--output <path>` | 输出文件路径(默认 openapi.yaml) |
698
- | `--dsl <path>` | 指定 DSL 文件(默认自动寻找最新) |
699
-
700
- ***
701
-
702
- ### `ai-spec mock`
703
-
704
- `ai-spec create` 生成了接口 DSL 之后,后端还没有部署,前端无法联调。`ai-spec mock` 从 DSL 直接生成一个**零依赖独立 Mock 服务器**,让前后端可以立即并行开发。
705
-
706
- ```bash
707
- # 生成 mock/server.js(独立 Express 服务器,无需数据库)
708
- ai-spec mock
709
-
710
- # 同时生成前端 Proxy 配置片段(自动识别 Vite / Next.js / webpack)
711
- ai-spec mock --proxy
712
-
713
- # 同时生成 MSW Handlers(适合前端完全脱离后端运行)
714
- ai-spec mock --msw
715
-
716
- # 全部生成
717
- ai-spec mock --port 3002 --proxy --msw
718
-
719
- # 为工作区所有后端 repo 批量生成
720
- ai-spec mock --workspace
721
-
722
- # ── 一键联调(推荐)──────────────────────────────────────────
723
- # 生成 + 启动 Mock 服务器(后台) + 自动 patch 前端 Proxy
724
- ai-spec mock --serve --frontend ../my-frontend
725
-
726
- # 联调结束后恢复(撤销 Proxy patch,停止 Mock 服务器)
727
- ai-spec mock --restore --frontend ../my-frontend
728
- ```
729
-
730
- **`--serve`** **详解:**
731
-
732
- `--serve` 做以下三件事:
733
-
734
- 1. 在后台启动 `node mock/server.js`(PID 记录在 `.ai-spec-mock.lock.json`)
735
- 2. 根据前端框架自动 patch Proxy 配置:
736
- - **Vite**:生成 `vite.config.ai-spec-mock.ts`(mergeConfig 方式,非破坏性),在 `package.json` 添加 `dev:mock` 脚本
737
- - **CRA**:临时修改 `package.json` 的 `"proxy"` 字段(原值备份在 lock 文件)
738
- - **Next.js / webpack**:打印手动配置说明
739
- 3. 打印前端启动命令(`npm run dev:mock` 或 `npm start`)
740
-
741
- `--restore` 的逆操作:删除 `vite.config.ai-spec-mock.ts`、还原 `package.json`、发送 SIGTERM 到 Mock 服务器进程。
742
-
743
- **生成的文件:**
744
-
745
- | 文件 | 说明 |
746
- | -------------------------------- | ------------------------------------------------- |
747
- | `mock/server.js` | 独立 Express Mock 服务器,每个 DSL 端点对应一个路由,返回 fixture 数据 |
748
- | `mock/README.md` | 启动指南和端点表 |
749
- | `mock/proxy.vite.comment.txt` | Vite proxy 配置片段(检测到 vite.config.\* 时生成) |
750
- | `mock/proxy.next.comment.txt` | Next.js rewrites 配置片段(检测到 next.config.\* 时生成) |
751
- | `mock/proxy.webpack.comment.txt` | webpack devServer.proxy 配置片段(默认 fallback) |
752
- | `src/mocks/handlers.ts` | MSW 请求拦截 handlers(`--msw`) |
753
- | `src/mocks/browser.ts` | MSW browser worker 初始化(`--msw`) |
754
- | `vite.config.ai-spec-mock.ts` | 前端临时 Vite 配置(`--serve`,非破坏性,`--restore` 后删除) |
755
- | `.ai-spec-mock.lock.json` | Proxy patch 记录 + Mock 服务器 PID(`--restore` 后删除) |
756
-
757
- **Mock Server 特性:**
758
-
759
- - 无需数据库连接,无需任何运行时依赖(只需 `express`)
760
- - `auth: true` 的端点自动加 Bearer Token 验证中间件(模拟 401)
761
- - Fixture 数据从 DSL 数据模型的字段类型推断(String → `"example_xxx"`,DateTime → ISO 8601 字符串,etc.)
762
- - GET List 端点(描述含 "list"/"all")自动返回分页结构 `{ data: [...], total, page, pageSize }`
763
-
764
- **联调工作流(手动):**
765
-
766
- ```
767
- 后端 repo:
768
- ai-spec create "用户登录功能" # → 生成 DSL + 代码框架
769
- ai-spec mock # → 生成 mock/server.js
770
- node mock/server.js # → Mock 服务器运行在 localhost:3001
771
-
772
- 前端 repo:
773
- 配置 Proxy: 将 /api 代理到 localhost:3001 (参见 mock/proxy.*.txt)
774
- ```
775
-
776
- **联调工作流(一键,推荐):**
777
-
778
- ```bash
779
- # 后端 repo 执行(一条命令完成全部)
780
- cd backend-repo
781
- ai-spec mock --serve --frontend ../frontend-repo
782
- # → 自动生成 server.js,启动 Mock 服务器(后台),patch 前端 Proxy
783
-
784
- # 按提示在前端 repo 启动 Dev Server
785
- cd ../frontend-repo
786
- npm run dev:mock
787
- # → 打开浏览器,直接看到 Mock 数据
788
-
789
- # 联调结束
790
- cd ../backend-repo
791
- ai-spec mock --restore --frontend ../frontend-repo
792
- ```
793
-
794
- **工作区一键联调(`ai-spec create --serve`):**
795
-
796
- 在多 Repo 工作区模式下,加 `--serve` 标志,Pipeline 完成后自动执行上述流程:
797
-
798
- ```bash
799
- ai-spec create "用户登录功能" --serve
800
- # 完成后自动:生成 Mock → 启动服务器 → patch 前端 Proxy → 打印 dev 命令
801
- ```
802
-
803
- ***
804
-
805
- ## 工作流详解
806
-
807
- ### Step 1 — 项目宪法 + Context(宪法加载 & 项目感知)
808
-
809
- **项目宪法**(`.ai-spec-constitution.md`):
810
-
811
- - 存在时自动加载,注入到所有 Spec/代码生成 prompt 的最高优先级位置
812
- - 不存在时自动运行 `init` 生成后继续,生成失败则跳过(不阻断流程)
813
-
814
- **项目上下文**(自动扫描):
815
-
816
- - `package.json` → 依赖列表、技术栈识别(Express / Prisma / React / Vue 等)
817
- - `composer.json` → PHP 依赖列表、技术栈识别(Lumen / Laravel / Eloquent 等)
818
- - `pom.xml` / `build.gradle` → Java 依赖列表、技术栈识别(Spring Boot / MyBatis / RocketMQ 等);扫描 `**/src/main/java/**/*Controller.java` 作为 API 结构
819
- - `prisma/schema.prisma` → 数据库模型
820
- - `src/**/routes/**` / `src/**/controllers/**` → 路由文件(读取前 60 行)
821
- - `src/**/middleware/**/{error,notFound}.js` → 错误处理模式
822
- - `src/locales/**` / `src/i18n/**` / `src/constants/**` / `src/enums/**` 等 → **共享配置文件扫描**(见下文)
823
-
824
- **共享配置文件扫描(防止重复创建):**
825
-
826
- ContextLoader 会自动扫描以下类别的"单例配置文件",并将其路径和内容片段注入所有 Spec/Codegen prompt:
827
-
828
- | 类别 | 扫描路径 |
829
- | ----------- | ------------------------------------------------------------------ |
830
- | i18n | `src/locales/**`, `src/i18n/**`, `locales/**`, `public/locales/**` |
831
- | constants | `src/constants/**`, `src/**/constants.{ts,js}` |
832
- | enums | `src/enums/**`, `src/**/enums.{ts,js}` |
833
- | config | `src/config/**` |
834
- | route-index | `src/routes/**/index.{ts,js}`, `src/router/index.{ts,js}` |
835
-
836
- 这些文件会被标记为 **Append-Only**,AI 在规划阶段会收到明确指令:
837
-
838
- > "以上文件已存在,必须向其中追加内容,禁止新建同类平行文件"
839
-
840
- **项目宪法 §8** 也会自动记录这些文件路径,确保 `ai-spec init --force` 重跑后约束持久化。
841
-
842
- ***
843
-
844
- ### Step 2 — Spec 生成 + Tasks 分解
845
-
846
- **Spec 生成**:调用选定的 AI,生成结构化中文 Markdown Spec:
847
-
848
- ```
849
- # Feature Spec: {功能名称}
850
- ## 1. 功能概述
851
- ## 2. 背景与动机
852
- ## 3. 用户故事
853
- ## 4. 功能需求(核心功能 + 边界条件)
854
- ## 5. API 设计(接口列表 + 请求响应示例)
855
- ## 6. 数据模型(Prisma Schema)
856
- ## 7. 非功能性需求
857
- ## 8. 实施要点
858
- ```
859
-
860
- **Tasks 分解**(与 Spec 同步生成):
861
-
862
- Spec 保存后自动生成 `specs/feature-xxx-tasks.json`,包含按实施层级排序的任务列表:
863
-
864
- ```json
865
- [
866
- {
867
- "id": "TASK-001",
868
- "title": "Add UserFavorite Prisma model",
869
- "layer": "data",
870
- "filesToTouch": ["prisma/schema.prisma", "prisma/migrations/..."],
871
- "acceptanceCriteria": ["Migration runs successfully", "Table created"],
872
- "dependencies": [],
873
- "priority": "high"
874
- },
875
- {
876
- "id": "TASK-002",
877
- "layer": "service",
878
- "dependencies": ["TASK-001"],
879
- ...
880
- }
881
- ]
882
- ```
883
-
884
- 任务按层级顺序排列:`data → infra → service → api → test`
885
-
886
- 代码生成时(`api` 模式)如果检测到 Tasks 文件,自动切换为 **task-by-task 模式**,逐任务生成代码,精度更高。
887
-
888
- ***
889
-
890
- ### Step 3 — 交互式 Spec 润色
891
-
892
- 每轮提供三个选项:
893
-
894
- ```
895
- ? What would you like to do?
896
- ❯ ✅ Finalize — proceed to code generation
897
- 🤖 AI Polish — let AI improve clarity & completeness
898
- ✏️ Edit again — continue editing
899
- ```
900
-
901
- 选择 **AI Polish** 后,AI 改动完成时会自动展示彩色 diff,让你在打开编辑器前先看清楚改了什么:
902
-
903
- ```
904
- ── AI Changes ──────────────────────────────
905
- AI edits: +8 -2 lines
906
- ## 4. 功能需求
907
- - - 支持用户登录
908
- + + 支持用户名/手机号/邮箱多方式登录,失败超过 5 次触发验证码
909
- @@
910
- + + ### 边界条件
911
- + + - token 过期时间 24h,刷新机制...
912
- ────────────────────────────────────────────
913
- ```
914
-
915
- ***
916
-
917
- ### Step 3.4 — Spec 质量预评估
918
-
919
- Approval Gate 之前,系统对 Spec 进行一次 AI 质量检查,给出**建议性**评分,不阻断流程。
920
-
921
- **三个评分维度(0-10):**
922
-
923
- | 维度 | 衡量内容 |
924
- | --------------------- | -------------------------------------- |
925
- | **Coverage(覆盖度)** | 错误处理、边界条件、auth 规则是否都有描述? |
926
- | **Clarity(清晰度)** | API 契约是否清晰到可以可靠提取 DSL?response 结构是否明确? |
927
- | **Constitution(一致性)** | 是否与项目宪法保持一致?命名、错误码、约定有没有冲突? |
928
-
929
- ```
930
- [3.4/6] Spec quality assessment...
931
- ─── Spec Quality Assessment ─────────────────────
932
- Coverage [████████░░] 8/10 error handling, edge cases, auth
933
- Clarity [██████░░░░] 6/10 API contracts, response shapes
934
- Constitution[█████████░] 9/10 naming, error codes, conventions
935
- Overall [████████░░] 8/10
936
-
937
- ⚠ DSL extraction may be unreliable — clarityScore < 6
938
- Consider adding explicit request/response shapes before proceeding.
939
-
940
- Issues found (2):
941
- · §5 POST /users/login: 401 error response body format not specified
942
- · §6 UserFavorite model: missing unique constraint on (userId, itemId)
943
-
944
- Suggestions:
945
- 💡 在 §5 明确每个错误码对应的 response body 格式
946
- ─────────────────────────────────────────────────
947
- ```
948
-
949
- - 评分 < 6 时会出现黄色警告,但不阻止继续
950
- - **DSL 可提取性预警**:Clarity < 6 且无结构化 API 章节时,提示 DSL 提取可能不准确
951
- - `--skip-assessment` 跳过此步骤(节省一次 AI 调用);`--auto` 模式下自动跳过
952
-
953
- ***
954
-
955
- ### Step 3.5 — Approval Gate(人工确认)
956
-
957
- 润色完成后、进入代码生成之前,系统会暂停等待你确认:
958
-
369
+ ai-spec mock # 生成 mock/server.js
370
+ ai-spec mock --port 3002 # 指定端口
371
+ ai-spec mock --proxy # 生成前端 Proxy 配置
372
+ ai-spec mock --msw # 生成 MSW Handlers
373
+ ai-spec mock --serve --frontend <path> # 一键启动 + patch 前端 Proxy
374
+ ai-spec mock --restore --frontend <path> # 撤销 Proxy patch
959
375
  ```
960
- [3.5/6] Approval Gate — review before code generation
961
- Spec length : 87 lines / 620 words
962
- Tasks generated : 7
963
- Previous version: v1 (specs/feature-user-login-v1.md)
964
-
965
- ── Changes vs previous version ──────────────
966
- v1 → v2: +12 -3 lines
967
- + + ### 安全性
968
- + + - rate limiting: 每 IP 每分钟最多 10 次登录尝试
969
- ────────────────────────────────────────────
970
-
971
- ? Ready to proceed to code generation?
972
- ❯ ✅ Proceed — start code generation
973
- 📋 View full spec
974
- ❌ Abort
975
- ```
976
-
977
- - 选 **Proceed** → 继续,Spec 保存并开始代码生成
978
- - 选 **View full spec** → 终端内展示完整 Spec,再次询问是否继续
979
- - 选 **Abort** → 中止,Spec **不会**保存到磁盘
980
-
981
- > `--auto` 模式自动选 Proceed,跳过此步骤。
982
-
983
- ***
984
-
985
- ### Step DSL — DSL 提取与校验
986
-
987
- Approval Gate 通过后,系统自动将 Spec Markdown 转换为 **结构化 JSON DSL**,提取核心架构信息。
988
-
989
- **DSL 结构:**
990
-
991
- ```json
992
- {
993
- "version": "1.0",
994
- "feature": { "id": "user-login", "title": "用户登录", "description": "..." },
995
- "models": [
996
- {
997
- "name": "User",
998
- "fields": [
999
- { "name": "email", "type": "String", "required": true, "unique": true }
1000
- ],
1001
- "relations": ["has many Session"]
1002
- }
1003
- ],
1004
- "endpoints": [
1005
- {
1006
- "id": "EP-001",
1007
- "method": "POST",
1008
- "path": "/api/v1/auth/login",
1009
- "auth": false,
1010
- "request": { "body": { "email": "string", "password": "string" } },
1011
- "successStatus": 200,
1012
- "successDescription": "返回 JWT token",
1013
- "errors": [
1014
- { "status": 401, "code": "INVALID_CREDENTIALS", "description": "邮箱或密码错误" }
1015
- ]
1016
- }
1017
- ],
1018
- "behaviors": [
1019
- {
1020
- "id": "BHV-001",
1021
- "description": "连续登录失败超过 5 次锁定账号",
1022
- "trigger": "登录失败",
1023
- "constraints": ["失败计数存 Redis", "锁定 30 分钟"]
1024
- }
1025
- ]
1026
- }
1027
- ```
1028
-
1029
- **校验机制(无外部依赖):**
1030
376
 
1031
- - 所有必填字段存在且类型正确(`method` 枚举、`path` 以 `/` 开头、`auth` 为 boolean 等)
1032
- - 数组边界检查(models ≤ 50、endpoints ≤ 100 等),防止超大响应导致问题
1033
- - 失败时展示精确的字段路径错误,最多自动重试 2 次(第 2 次携带错误反馈)
1034
- - 2 次重试后仍失败 → 交互式询问:跳过继续 / 中止
1035
-
1036
- **前端/后端自动分叉:**
1037
-
1038
- 系统根据项目的 `package.json` 依赖自动检测是否为前端项目(`react` / `vue` / `next` / `react-native` / `expo`),并切换到对应的 DSL 提取策略:
1039
-
1040
- | 项目类型 | DSL 输出重心 |
1041
- | ----------------------- | ------------------------------------------------------ |
1042
- | 后端(Node/Express/Prisma) | `endpoints[]` + `models[]` + `behaviors[]` |
1043
- | 前端(React/Vue/Next) | `endpoints[]`(本前端调用的接口)+ `components[]`(ComponentSpec) |
1044
-
1045
- **`ComponentSpec`** **结构(前端专属):**
1046
-
1047
- ```json
1048
- {
1049
- "id": "CMP-001",
1050
- "name": "LikeButton",
1051
- "description": "点赞/取消点赞按钮,带乐观更新",
1052
- "props": [{ "name": "postId", "type": "string", "required": true }],
1053
- "events": [{ "name": "onLikeChange", "payload": "{ liked: boolean, count: number }" }],
1054
- "state": { "liked": "boolean", "count": "number", "loading": "boolean" },
1055
- "apiCalls": ["EP-001"]
1056
- }
1057
- ```
1058
-
1059
- **抗幻觉设计:**
1060
-
1061
- - Prompt 明确要求"只提取 Spec 中明确写出的内容,不推断、不补全"
1062
- - 空数组 `[]` 是正确输出,不强求每个字段都有内容
1063
- - 重试时把上次的错误字段路径和原因一并告知 AI,定向修复
1064
-
1065
- **输出文件:** `specs/feature-<slug>-v<N>.dsl.json`(与 spec 文件并排)
1066
-
1067
- **用于 codegen:** DSL(含 `components[]`)被转换为紧凑文本摘要注入 codegen prompt,提供精确的组件接口定义和端点签名。
1068
-
1069
- **用于下游产物:**
1070
-
1071
- - `ai-spec types`:DSL → TypeScript 类型文件(models、endpoint request types、`API_ENDPOINTS` 常量)
1072
- - `ai-spec export`:DSL → OpenAPI
1073
- - `ai-spec mock`:DSL → Mock Server / MSW / Proxy
1074
- - 工作区模式:后端 DSL 契约可直接注入前端流水线
1075
-
1076
- ### Step DSL+ — DSL Gap Feedback
1077
-
1078
- DSL 校验通过后,系统还会做一次**纯启发式的丰富度检查**,判断当前 DSL 是否“合法但过于稀疏”。
1079
-
1080
- 当前会检测几类典型缺口:
1081
-
1082
- - 没有 models 也没有 endpoints
1083
- - endpoint 描述过于泛化
1084
- - 多个 endpoint 全部没有 `errors`
1085
- - model 只有极少字段
1086
-
1087
- 交互模式下,如果检测到缺口,会给出两个选择:
1088
-
1089
- - `🔧 Refine spec`:AI 定向补全 Spec 中缺失的结构细节,然后自动重新提取 DSL
1090
- - `⏭ Skip`:保留当前 DSL,继续后续流水线
1091
-
1092
- > 这个反馈环只在 DSL 提取完成后、进入 worktree 之前运行;`--auto`、`--fast`、`--skip-dsl` 下会跳过。
1093
-
1094
- > `--skip-dsl` 跳过此步骤,`--auto` 模式下提取失败时自动跳过(不中断流水线)。
1095
-
1096
- ***
1097
-
1098
- ### Step 4 — Git Worktree(隔离工作区)
1099
-
1100
- ```
1101
- 原项目: ~/code/my-app/
1102
- worktree: ~/code/my-app-add-user-login/ ← 独立分支 feature/add-user-login
1103
- ```
1104
-
1105
- - 分支已存在时直接复用
1106
- - 不是 git 仓库时跳过,在原目录继续
1107
- - `--skip-worktree` 强制跳过
1108
-
1109
- ***
1110
-
1111
- ### Step 5 — 代码生成(增量 · 断点续传)
1112
-
1113
- Spec 保存时使用**版本化命名**:`feature-<slug>-v<N>.md`,同一 idea 每次运行自动递增版本号:
1114
-
1115
- ```
1116
- specs/
1117
- ├── feature-user-login-v1.md ← 第一次运行
1118
- ├── feature-user-login-v1-tasks.json
1119
- ├── feature-user-login-v2.md ← 修改后再次运行
1120
- └── feature-user-login-v2-tasks.json
1121
- ```
1122
-
1123
- **`claude-code`** **模式(默认)**
1124
-
1125
- - **交互模式**(默认):在 worktree 目录启动 Claude Code CLI,有 Tasks 文件时将任务列表注入 `.claude-prompt.txt`
1126
- - **`--auto`** **增量模式**:改为对每个 task 单独运行 `claude -p`,每个 task 完成后写入 checkpoint,进度实时显示:
1127
-
1128
- ```
1129
- [████░░░░░░░░░░░░░░░░] 20% → TASK-001 💾 Add UserFavorite Prisma model
1130
- [████████░░░░░░░░░░░░] 40% → TASK-002 🔧 Implement FavoriteService
1131
- [████████████░░░░░░░░] 60% → TASK-003 🌐 Add API routes
1132
- ✔ Incremental build: 3/3 tasks completed.
1133
- ```
1134
-
1135
- 检测到 `rtk` 已安装时自动切换为 `rtk claude` 执行。
1136
-
1137
- **`api`** **模式**
1138
-
1139
- 有 Tasks 文件时按 task 顺序生成,每个 task 单独 AI 调用:
1140
-
1141
- ```
1142
- [████░░░░░░░░░░░░░░░░] 20% → TASK-001 💾 Add schema
1143
- + prisma/schema.prisma... ✔
1144
- [████████░░░░░░░░░░░░] 40% → TASK-002 🔧 Service 层
1145
- + src/services/favoriteService.ts... ✔
1146
- ~ src/routes/client/index.ts... ✔
1147
- ```
1148
-
1149
- **跨 Task 一致性保障**:每个 task 完成后,写入的 `src/api*` / `src/service*` / `src/store*` / `src/composable*` 文件会被读回并缓存;后续 task 在 prompt 中可以看到这些文件的实际导出内容,确保路由/组件层 import 使用的函数名与 API 层一致(不再出现 `getTasks` vs `getTaskList` 的跨 task 幻觉)。当前 task 创建新路由模块文件时,也会自动携带对应 `routes/index.ts` 的精确注册指令。
1150
-
1151
- **分页参数 ground-truth 注入**:`frontend-context-loader` 自动扫描 `src/apis/`(及 `src/api/`、`src/services/` 等)中现有的 API 文件,找到包含分页字段(`pageIndex`/`pageSize`/`pageNum`/`current` 等)的 interface 及对应导出函数,作为 `paginationExample` 注入 prompt,并标注 "COPY THIS EXACTLY"。生成的列表接口将与项目现有接口使用完全相同的分页参数名称和 HTTP 方法(POST body 或 GET query)。
1152
-
1153
- **续跑(`--resume`)**
1154
-
1155
- 任一模式中,task 完成后状态写入 `tasks.json`(`"status": "done"`)。运行中断后加 `--resume` 可跳过已完成的 task:
1156
-
1157
- ```bash
1158
- # 第一次运行,中途中断
1159
- ai-spec create "用户收藏功能" --auto
1160
-
1161
- # 从上次中断位置续跑
1162
- ai-spec create "用户收藏功能" --auto --resume
1163
- ```
1164
-
1165
- **`plan`** **模式**
1166
-
1167
- 仅输出实施方案,不写入任何文件。
1168
-
1169
- ***
1170
-
1171
- ### Step 7 — 测试生成
1172
-
1173
- 测试生成有两种模式:**普通骨架模式**(默认)和 **TDD 模式**(`--tdd`)。
1174
-
1175
- ***
1176
-
1177
- #### 普通骨架模式(默认)
1178
-
1179
- 代码生成完成后,如果 DSL 提取成功,系统自动检测项目类型(前端/后端)并生成对应的测试骨架。
1180
-
1181
- **后端项目(Node.js / Express / Koa 等):**
1182
-
1183
- - 自动检测测试目录(`tests/` · `test/` · `__tests__/` · `spec/`,默认 `tests/`)
1184
- - 每个端点生成:成功路径测试、参数校验测试、鉴权测试(`auth: true` 时)
1185
- - 每个模型生成:创建测试、唯一约束测试(有 `unique` 字段时)
1186
- - 测试框架:Jest / Vitest 自动检测
1187
-
1188
- **前端项目(React / Vue / Next.js / React Native):**
1189
-
1190
- - 测试框架:自动检测 `@testing-library/react`(RTL) / `cypress` / `vitest` / `jest`
1191
- - 每个 `ComponentSpec` 生成:render 测试 / props 测试 / 交互事件测试 / loading 状态测试
1192
- - API hook 层生成独立测试文件(测试 hook,不测试 component 内部)
1193
- - 乐观更新流程:自动生成 rollback case(模拟 server error)
1194
- - 节流/防抖:自动生成 `jest.useFakeTimers()` 延迟行为测试
1195
-
1196
- > 测试骨架只生成 `describe/it` 结构,不实现断言(用 TODO 注释标出),供开发者补全。
1197
- > `--skip-tests` 跳过此步骤;`--skip-dsl` 时自动跳过。
1198
-
1199
- ***
1200
-
1201
- #### TDD 模式(`--tdd`)
1202
-
1203
- `--tdd` 改变了整个流程的顺序:**测试在代码生成之前写入**,测试有真实断言,初始状态全部失败,error feedback loop 驱动代码实现直到测试通过。
1204
-
1205
- ```
1206
- 普通模式:DSL → codegen → 测试骨架(TODO 注释)→ error feedback(2 轮)
1207
-
1208
- TDD 模式:DSL → TDD 测试(真实断言,全部 FAIL)→ codegen → error feedback(3 轮,以通过测试为目标)
1209
- ```
1210
-
1211
- **TDD 测试 vs 骨架对比:**
1212
-
1213
- ```typescript
1214
- // 骨架(普通模式)
1215
- it('should create a task', async () => {
1216
- // TODO: implement test
1217
- });
1218
-
1219
- // TDD 模式 — 真实断言,基于 DSL 生成
1220
- it('POST /api/v1/tasks → 201 with task data', async () => {
1221
- const res = await request(app)
1222
- .post('/api/v1/tasks')
1223
- .set('Authorization', 'Bearer test-token')
1224
- .send({ title: 'My task', status: 'todo', dueDate: '2026-12-31' });
1225
- expect(res.status).toBe(201);
1226
- expect(res.body.data).toMatchObject({ title: 'My task', status: 'todo' });
1227
- expect(res.body.data.id).toBeDefined();
1228
- });
1229
-
1230
- it('POST /api/v1/tasks → 400 MISSING_FIELD when title absent', async () => {
1231
- const res = await request(app)
1232
- .post('/api/v1/tasks')
1233
- .set('Authorization', 'Bearer test-token')
1234
- .send({ status: 'todo' });
1235
- expect(res.status).toBe(400);
1236
- expect(res.body.code).toBe('MISSING_FIELD');
1237
- });
1238
- ```
1239
-
1240
- **使用方式:**
1241
-
1242
- ```bash
1243
- ai-spec create "任务管理功能" --tdd
1244
- ai-spec create "任务管理功能" --tdd --codegen api
1245
- ```
1246
-
1247
- **注意事项:**
1248
-
1249
- - 仅支持**后端项目**(使用 supertest 做 HTTP 集成测试)
1250
- - 依赖 DSL 提取成功(Spec 需要有清晰的 API 设计章节);DSL 为空时退化为普通骨架模式
1251
- - error feedback loop 在 TDD 模式下最多运行 **3 轮**(普通模式 2 轮)
1252
-
1253
- ***
1254
-
1255
- ### Step 8 — 错误反馈自动修复
1256
-
1257
- 测试骨架生成后,系统自动运行项目已有的测试和 lint 命令,检测生成代码中的错误,并让 AI 自动修复,最多循环 2 次:
1258
-
1259
- **错误检测:**
1260
-
1261
- - 自动检测 `npm test` / `npx vitest run` / `npx jest --forceExit`
1262
- - 自动检测 `npm run lint` / `npx eslint .`
1263
- - 无检测到命令时跳过
1264
-
1265
- **修复流程(最多 2 个 cycle):**
1266
-
1267
- ```
1268
- [cycle 1/2] Running tests: npm test
1269
- ✘ Tests failed (3 error(s) captured)
1270
- Attempting auto-fix (3 error(s))...
1271
- ✔ Auto-fixed: src/services/authService.ts
1272
- [cycle 2/2] Running tests: npm test
1273
- ✔ Tests passed.
1274
- ✔ All checks passed after 2 cycle(s).
1275
- ```
1276
-
1277
- - 按文件分组错误,**依据 import 依赖图排序后**逐文件修复(被依赖文件先修,cascade 错误在 cycle 1 消除率更高)
1278
- - 每个文件修复 prompt 携带 DSL 上下文,避免「把错误藏起来」式修复
1279
- - 任一 cycle 全部通过则提前结束
1280
- - 2 次后仍有错误 → 给出警告提示(不中断流水线)
1281
-
1282
- > `--skip-error-feedback` 跳过此步骤。
1283
-
1284
- ***
1285
-
1286
- ### Step 9 — 代码审查 + 经验积累
1287
-
1288
- 与 Spec 一起发送给 AI,输出结构化审查报告:
1289
-
1290
- | 代码生成模式 | 审查方式 |
1291
- | ------------- | --------------------------------------- |
1292
- | `api` | 直接读取生成的文件内容(不依赖 git diff,生成后立即可审查) |
1293
- | `claude-code` | 抓取 worktree 中的 git diff(需先 `git add .`) |
1294
-
1295
- 审查完成后,系统自动从审查报告的 **⚠️ 问题** 章节提取可操作 issue,追加到项目宪法的 **§9 积累教训** 中:
1296
-
1297
- ```markdown
1298
- ## 9. 积累教训 (Accumulated Lessons)
1299
- - 🔒 **[2026-03-23]** 登录接口缺少 rate limiting,需在中间件层添加
1300
- - 🐛 **[2026-03-23]** 异步错误未被全局 error handler 捕获
1301
- - 📐 **[2026-03-23]** service 层直接使用了 req/res 对象,违反分层规范
1302
- ```
1303
-
1304
- - **自动分类**:security 🔒 / performance ⚡ / bug 🐛 / pattern 📐 / general 📝
1305
- - **自动去重**:相似内容(前 50 字符匹配)不重复追加
1306
- - 每次代码审查最多提取 10 条 issue
1307
- - 下次运行 `ai-spec create` 时,这些教训会随宪法注入所有 Spec/代码生成 prompt,避免重蹈覆辙
1308
-
1309
- > 审查每运行一次,宪法就"学到"一些新东西,随项目迭代持续进化。
1310
-
1311
- ### Step 9.5 — Review→DSL Loop
1312
-
1313
- 从 v0.33.0 开始,审查阶段不再只是“找问题并记到 §9”。如果 review 里发现的是**结构性问题**,例如:
1314
-
1315
- - Spec 缺失错误码 / 鉴权要求
1316
- - DSL 中 endpoint / model 信息过于稀疏
1317
- - 当前实现问题本质上来自契约不完整
1318
-
1319
- 系统会把这些发现整理成对 Spec / DSL 的改进建议,而不是直接把问题留给下一次人工返工。
1320
-
1321
- 推荐动作是:
1322
-
1323
- ```bash
1324
- ai-spec update "补充缺失的结构约束" --codegen
1325
- ```
1326
-
1327
- 也就是说,流水线从“单向生成”升级成了“review 之后还能反向修契约,再定向重生代码”的闭环。
1328
-
1329
- ***
1330
-
1331
- ### Step 10 — Harness Self-Eval
1332
-
1333
- 代码审查完成后自动执行,**零 AI 调用**,纯确定性评分:
1334
-
1335
- | 维度 | 评分逻辑 |
1336
- | -------------------- | ------------------------------------ |
1337
- | DSL Coverage (0-10) | 生成文件是否覆盖 DSL 声明的 endpoint 层和 model 层 |
1338
- | Compile Score (0-10) | error feedback 全通过 → 10;未通过 / 跳过 → 5 |
1339
- | Review Score (0-10) | 从 3-pass review 文本提取 `Score: X/10` |
1340
-
1341
- **Harness Score** = 加权平均(DSL 40% + Compile 30% + Review 30%)
1342
-
1343
- ```
1344
- ─── Harness Self-Eval ───────────────────────────
1345
- Score : [████████░░] 7.8/10
1346
- DSL : 8/10 Compile: pass Review: 7.2/10
1347
- Prompt : a3f2c1d8
1348
- ─────────────────────────────────────────────────
1349
- ```
1350
-
1351
- - `harnessScore` 和 `promptHash` 写入 RunLog(`.ai-spec-logs/<runId>.json`)
1352
- - 每次改动 prompt 文件后,`promptHash` 自动变化,结合 `harnessScore` 可量化 prompt 改动的效果
1353
- - `ai-spec logs` / `trend` / `dashboard` 会直接消费这些 RunLog,做运行回看、趋势对比和可视化报告
1354
-
1355
- ***
1356
-
1357
- ## 多 Repo 工作区模式
1358
-
1359
- 当父目录中存在 `.ai-spec-workspace.json` 时,`ai-spec create` 自动切换为**多 Repo 联动模式**,一句需求驱动前后端全链路实现。
1360
-
1361
- ### 快速示例
1362
-
1363
- ```bash
1364
- # 目录结构
1365
- ~/code/my-project/
1366
- ├── .ai-spec-workspace.json
1367
- ├── backend/ ← Node.js / Express API 服务
1368
- └── frontend/ ← React 应用
1369
-
1370
- # 在 my-project/ 下运行
1371
- cd ~/code/my-project
1372
- ai-spec create "实现用户点赞功能"
1373
- ```
1374
-
1375
- ### 多 Repo 流水线步骤
1376
-
1377
- ```
1378
- [W1] Loading project contexts...
1379
- ✔ backend (node-express / backend) constitution: ✔
1380
- ✔ frontend (react / frontend) constitution: ✘ (will auto-generate)
1381
-
1382
- [W2] Decomposing requirement across repos...
1383
- ✔ Decomposition complete.
1384
-
1385
- backend → 新增 POST /api/v1/posts/:id/like 接口,Like 模型,幂等处理
1386
- frontend → 点赞按钮交互:节流 300ms,乐观更新,失败回滚,成功后 re-fetch 详情
1387
-
1388
- [W3] Requirement decomposition preview:
1389
- ┌────────────────────────────────────────────────────────┐
1390
- │ backend [contract provider] │
1391
- │ POST /api/v1/posts/:id/like [auth required] │
1392
- │ DELETE /api/v1/posts/:id/like │
1393
- │ frontend depends on: backend │
1394
- │ UX: throttle 300ms · optimistic update · rollback │
1395
- │ re-fetch: GET /api/v1/posts/:id on success │
1396
- └────────────────────────────────────────────────────────┘
1397
- ? Proceed with per-repo pipelines? ✅ Yes / ❌ Abort
1398
-
1399
- ── Repo 1/2: backend ──────────────────────────────────────────
1400
- [1/9] Loading context (backend)...
1401
- [2/9] Generating spec...
1402
- [DSL] Extracting DSL... ✔ 2 endpoints, 1 model
1403
- ...(完整单 repo 流水线)...
1404
- [9/9] Code review + knowledge memory ✔
1405
-
1406
- ── Repo 2/2: frontend ─────────────────────────────────────────
1407
- [1/9] Loading context (frontend)...
1408
- [2/9] Generating spec... ← 自动注入后端 API Contract(端点、TS 类型定义)
1409
- ╔══ Backend API Contract (injected) ══╗
1410
- ║ POST /api/v1/posts/:id/like [auth]║
1411
- ║ interface LikePostRequest { ... } ║
1412
- ╚═════════════════════════════════════╝
1413
- ...(完整单 repo 流水线)...
1414
-
1415
- [W5] ✔ Multi-repo pipeline complete (2/2 repos succeeded)
1416
- Specs written:
1417
- backend/specs/feature-like-v1.md
1418
- frontend/specs/feature-like-v1.md
1419
- ```
1420
-
1421
- ### 核心设计
1422
-
1423
- | 能力 | 说明 |
1424
- | ------------------- | ---------------------------------------------------------------------------- |
1425
- | **需求自动拆分** | AI 将一句需求分解为每个 repo 的职责描述 |
1426
- | **UX 决策注入** | 前端自动获得:节流/防抖时间、是否乐观更新、失败回滚策略、成功后需 re-fetch 的接口列表 |
1427
- | **基于真实代码的 UX 决策** | 分解时注入前端已有的 hook/store/API wrapper 文件列表,AI 的 specIdea 会直接引用真实文件名而非泛泛描述 |
1428
- | **Contract Bridge** | 后端 DSL → TypeScript 接口定义 → 注入前端 Spec 生成 prompt,确保路径/方法/类型严格对齐 |
1429
- | **前端 Codegen 上下文** | API 模式代码生成时自动注入前端项目的 hook/store/API wrapper 现有代码,附注"extend, do NOT recreate" |
1430
- | **依赖顺序执行** | 按 backend → shared → frontend → mobile 顺序运行,后端先出产 contract |
1431
- | **容错隔离** | 单个 repo 失败不影响其他 repo;失败时打印错误并继续 |
1432
- | **优雅降级** | 未找到 `.ai-spec-workspace.json` 时静默退回单 repo 模式,无需任何配置 |
1433
-
1434
- ### UxDecision 字段说明
1435
-
1436
- 需求拆分时 AI 会为前端/移动端 repo 生成 `uxDecisions`:
1437
-
1438
- | 字段 | 类型 | 说明 |
1439
- | ------------------ | ----------- | --------------------- |
1440
- | `throttleMs` | `number?` | 按钮点击节流(ms),适用于频繁操作如点赞 |
1441
- | `debounceMs` | `number?` | 输入防抖(ms),适用于搜索框 |
1442
- | `optimisticUpdate` | `boolean` | 是否在服务端确认前先更新 UI |
1443
- | `reloadOnSuccess` | `string[]?` | 成功后需 re-fetch 的接口路径列表 |
1444
- | `errorRollback` | `boolean` | 乐观更新失败时是否回滚 UI 状态 |
1445
- | `loadingState` | `boolean` | 请求期间是否显示加载指示器 |
1446
- | `notes` | `string?` | 补充协调说明 |
1447
-
1448
- ***
1449
-
1450
- ## 多语言后端支持
1451
-
1452
- ai-spec 不绑定特定后端语言。`workspace init` 和 `detectRepoType()` 会自动识别以下项目类型:
1453
-
1454
- | 语言 / 框架 | 识别依据 | RepoType | Role |
1455
- | ----------------- | ----------------------------------------- | -------------- | ------- |
1456
- | Node.js / Express | `package.json` 含 `express` | `node-express` | backend |
1457
- | Node.js / Koa | `package.json` 含 `koa` | `node-koa` | backend |
1458
- | Go | 根目录存在 `go.mod` | `go` | backend |
1459
- | Rust | 根目录存在 `Cargo.toml` | `rust` | backend |
1460
- | Java (Maven) | 根目录存在 `pom.xml` | `java` | backend |
1461
- | Java (Gradle) | 根目录存在 `build.gradle` / `build.gradle.kts` | `java` | backend |
1462
-
1463
- > **Java 上下文提取**:`ContextLoader` 会解析 `pom.xml`(正则提取 `<artifactId>` 依赖列表 + `<maven.compiler.source>` Java 版本)并推断技术栈(Spring Boot、MyBatis、Dubbo、RocketMQ、Redis、OpenFeign 等);扫描 `**/src/main/java/**/*Controller.java` 作为 API 结构;读取 `application.properties/yml` 作为路由摘要。workspace `[W1]` 阶段会正常显示 `Java, Java 11, Spring Boot, RocketMQ... (N deps)` 而非 `unknown (0 deps)`。
1464
- > \| Python | 根目录存在 `requirements.txt` / `pyproject.toml` / `setup.py` | `python` | backend |
1465
- > \| **PHP / Lumen / Laravel** | **根目录存在** **`composer.json`** | **`php`** | **backend** |
1466
- > \| React | `package.json` 含 `react` | `react` | frontend |
1467
- > \| Next.js | `package.json` 含 `next` | `next` | frontend |
1468
- > \| Vue | `package.json` 含 `vue` | `vue` | frontend |
1469
- > \| React Native / Expo | `package.json` 含 `react-native` / `expo` | `react-native` | mobile |
1470
-
1471
- **错误反馈自动修复** (`error-feedback.ts`) 也针对各语言自动选择测试/Lint 命令:
1472
-
1473
- | 语言 | 测试命令 | Lint 命令 |
1474
- | ------------- | --------------------------------------------------- | ---------------------------------------- |
1475
- | Node.js | `npm test` / `npx vitest run` | `npm run lint` / `npx eslint .` |
1476
- | Go | `go test ./...` | `go vet ./...` |
1477
- | Rust | `cargo test` | `cargo clippy -- -D warnings` |
1478
- | Java (Maven) | `mvn test -q` | — |
1479
- | Java (Gradle) | `./gradlew test` | — |
1480
- | Python | `pytest` | `ruff check .` / `flake8 .` |
1481
- | **PHP** | **`./vendor/bin/phpunit`** 或 **`php artisan test`** | **`./vendor/bin/phpstan analyse`**(如已安装) |
1482
-
1483
- > **代码生成 Prompt 策略**:`ai-spec create` 和 `ai-spec update --codegen` 会根据自动检测的 `RepoType` 选择对应语言的 system prompt(`getCodeGenSystemPrompt(repoType)`)。Go 使用 Go 惯用写法,Python 匹配 FastAPI/Flask/Django,Java 使用 Spring Boot 分层模式,Rust 使用 Result\<T,E> 风格,**PHP 匹配 Lumen/Laravel 路由约定,使用 Eloquent ORM,PSR-12 规范**。
1484
-
1485
- ***
1486
-
1487
- ## 配置文件
1488
-
1489
- `.ai-spec.json` 存放在项目根目录,所有命令自动读取:
1490
-
1491
- ```json
1492
- {
1493
- "provider": "qwen",
1494
- "model": "qwen3-235b-a22b",
1495
- "codegen": "api",
1496
- "codegenProvider": "glm",
1497
- "codegenModel": "glm-5"
1498
- }
1499
- ```
1500
-
1501
- **优先级(从高到低):** 命令行参数 > `.ai-spec.json` > 内置默认值
1502
-
1503
- 项目根目录还有两个自动生成的文件:
1504
-
1505
- | 文件 | 说明 |
1506
- | -------------------------- | ---------------------------- |
1507
- | `.ai-spec-constitution.md` | 项目宪法,`init` 生成,所有命令自动读取 |
1508
- | `.ai-spec.json` | 模型配置,`config` / `model` 命令管理 |
1509
-
1510
- ### 共享宪法(跨项目规范)
1511
-
1512
- 除了项目级宪法,ai-spec 还支持**全局宪法**,将团队通用规范从单个项目提升到工作区/用户级别。
1513
-
1514
- **搜索顺序(优先级从高到低):**
1515
-
1516
- ```
1517
- 1. 工作区根目录 ~/code/my-project/.ai-spec-global-constitution.md
1518
- 2. 用户 home 目录 ~/.ai-spec-global-constitution.md
1519
- ```
1520
-
1521
- **生成全局宪法:**
1522
-
1523
- ```bash
1524
- # 在工作区根目录下生成(对该工作区所有 repo 生效)
1525
- cd ~/code/my-project
1526
- ai-spec init --global
1527
-
1528
- # 在 home 目录生成(对所有项目生效)
1529
- cd ~
1530
- ai-spec init --global
1531
- ```
1532
-
1533
- **注入规则:**
1534
-
1535
- 全局宪法 + 项目宪法在运行时自动合并,**项目规则优先级更高**:
1536
-
1537
- ```
1538
- <!-- BEGIN GLOBAL CONSTITUTION (team baseline — lower priority) -->
1539
- # Global Constitution
1540
- ## 1. 团队 API 规范 ← 所有服务通用的响应格式、错误码前缀
1541
- ## 2. 团队命名规范 ← 环境变量命名、路由前缀约定
1542
- ...
1543
- <!-- END GLOBAL CONSTITUTION -->
1544
-
1545
- <!-- BEGIN PROJECT CONSTITUTION (project-specific — HIGHER priority) -->
1546
- # Project Constitution
1547
- ## 1. 架构规则 ← 本项目特有的分层约束
1548
- ...
1549
- <!-- END PROJECT CONSTITUTION -->
1550
- ```
1551
-
1552
- 当 `ai-spec init` 检测到全局宪法时,会提示:
1553
-
1554
- ```
1555
- ℹ Global constitution detected: ~/code/my-project/.ai-spec-global-constitution.md
1556
- It will be merged with this project constitution at runtime.
1557
- Project rules take priority over global rules.
1558
- ```
1559
-
1560
- ***
1561
-
1562
- ## RTK 集成
1563
-
1564
- > RTK 仅对 **`claude-code`** **模式**有效,不影响 `api` 模式下对 GLM / Qwen / Gemini 等 provider 的直接 API 调用。
1565
-
1566
- RTK(Rust Token Killer)作为 Claude Code 的 hook 运行,拦截 Claude Code 会话中的 shell 命令输出(`git diff`、`git status`、`npm` 等),压缩后再返回给 Claude,从而减少 context 中的 token 消耗。
1567
-
1568
- 安装 RTK 后,`ai-spec` 在 `claude-code` 模式下自动检测并使用 `rtk claude` 替代 `claude` 执行:
377
+ #### `ai-spec export`
1569
378
 
1570
- ```bash
1571
- # 检测到 rtk 时的输出(仅 claude-code 模式)
1572
- ✓ RTK detected — using rtk claude for token savings
1573
379
  ```
1574
-
1575
- 配合 `--auto` 参数效果最佳(非交互执行,减少会话开销):
1576
-
1577
- ```bash
1578
- ai-spec create "功能描述" --auto
380
+ ai-spec export # 生成 openapi.yaml
381
+ ai-spec export --format json # JSON 格式
382
+ ai-spec export --server <url> # 指定服务器 URL
1579
383
  ```
1580
384
 
1581
- ***
385
+ </details>
1582
386
 
1583
- ## 全局安装
387
+ ### 工作流详解
1584
388
 
1585
- ```bash
1586
- npm run build
1587
- npm link
389
+ <details>
390
+ <summary>Step 1 — 项目宪法 + Context</summary>
1588
391
 
1589
- # 无参数运行 展示欢迎界面(版本、当前 provider、最近 spec 列表)
1590
- ai-spec
392
+ **项目宪法**(`.ai-spec-constitution.md`)包含 §1–§9 9 个章节,涵盖架构规则、命名规范、API 规范、数据层、错误处理、禁区、测试规范、共享配置清单、累积经验。
1591
393
 
1592
- # 在任意项目目录使用
1593
- ai-spec init # 生成项目宪法
1594
- ai-spec create "增加消息通知功能" # 开始开发
1595
- ai-spec review # 代码审查
1596
- ai-spec model --list # 查看所有模型
1597
- ```
394
+ 自动扫描的上下文包括:`package.json` / `composer.json` / `pom.xml` 依赖列表、Prisma schema、路由文件、错误处理模式、i18n/constants/enums 等共享配置。
1598
395
 
1599
- ***
396
+ **Constitution Rebase**:§9 积累超过 8 条时,运行 `ai-spec init --consolidate` 将经验提炼归并到 §1–§8。
397
+ </details>
1600
398
 
1601
- ## 项目结构
399
+ <details>
400
+ <summary>Step 2 — Spec 生成 + Tasks 分解</summary>
1602
401
 
1603
- ```
1604
- ai-spec-dev-poc/
1605
- ├── cli/
1606
- │ ├── index.ts # CLI 入口(42 行),组装所有命令
1607
- │ ├── utils.ts # 共享工具:loadConfig / resolveApiKey / AiSpecConfig
1608
- │ └── commands/
1609
- │ ├── create.ts # create — 完整单/多 Repo 流水线
1610
- │ ├── review.ts # review — AI 代码审查
1611
- │ ├── init.ts # init — 项目/全局宪法生成
1612
- │ ├── config.ts # config — 项目默认配置
1613
- │ ├── model.ts # model — 交互式 Provider/Model 选择
1614
- │ ├── workspace.ts # workspace — 多 Repo 工作区管理
1615
- │ ├── update.ts # update — Spec 变更增量代码生成
1616
- │ ├── export.ts # export — DSL → OpenAPI 导出
1617
- │ ├── mock.ts # mock — 独立 Mock Server 生成与启动
1618
- │ ├── learn.ts # learn — 直接向宪法 §9 追加经验
1619
- │ ├── restore.ts # restore — 回滚上次 run 写入的文件
1620
- │ ├── trend.ts # trend — Harness 评分趋势报表
1621
- │ ├── logs.ts # logs — 运行日志列表 / 阶段详情
1622
- │ ├── types.ts # types — DSL → TypeScript 类型文件
1623
- │ └── dashboard.ts # dashboard — 静态 HTML Harness Dashboard
1624
- ├── core/
1625
- │ ├── spec-generator.ts # 所有 AI Provider + SpecGenerator
1626
- │ ├── context-loader.ts # 项目上下文 + 宪法加载
1627
- │ ├── spec-refiner.ts # 交互式 Spec 润色(含 AI diff 预览)
1628
- │ ├── spec-versioning.ts # Spec 版本化:slug/版本递增/彩色 diff 引擎
1629
- │ ├── dsl-types.ts # SpecDSL 类型定义(扁平,无递归)
1630
- │ ├── dsl-validator.ts # DSL 校验器(迭代,无外部依赖)
1631
- │ ├── dsl-extractor.ts # AI 提取 + retry + DSL→codegen 摘要
1632
- │ ├── code-generator.ts # 三模式代码生成器(DSL注入 · 增量执行 · 进度条 · RTK感知 · 跨Task缓存)
1633
- │ ├── constitution-generator.ts # 项目宪法生成器
1634
- │ ├── task-generator.ts # Tasks 分解器(含断点续传状态)
1635
- │ ├── combined-generator.ts # Spec + Tasks 合并单次 AI 调用
1636
- │ ├── reviewer.ts # AI 代码审查(git diff / 文件内容双模式)
1637
- │ ├── test-generator.ts # 测试骨架生成器(DSL → Jest/Vitest 骨架)
1638
- │ ├── error-feedback.ts # 错误反馈自动修复(测试+lint检测 · 依赖图排序修复 · AI修复循环)
1639
- │ ├── prompt-hasher.ts # [v0.31.0] Prompt Hash:6 个核心 prompt 的 SHA-256 短 hash
1640
- │ ├── self-evaluator.ts # [v0.31.0] Harness Self-Eval:零 AI 调用,DSL覆盖+编译+review加权评分
1641
- │ ├── knowledge-memory.ts # 经验积累:审查 issue → 宪法§9
1642
- │ ├── workspace-loader.ts # [Phase 4] 工作区配置加载 + repo 类型自动检测
1643
- │ ├── requirement-decomposer.ts # [Phase 4] 需求跨 repo 拆分 + UX 决策生成
1644
- │ ├── contract-bridge.ts # [Phase 4] 后端 DSL → 前端 TS 接口契约桥接
1645
- │ ├── frontend-context-loader.ts # [v0.8] 前端深度感知(hook/store/API封装/测试框架/分页 pattern 检测;v0.30.0 升级为多行 import 解析,覆盖换行 named import 写法)
1646
- │ └── global-constitution.ts # [v0.8] 全局宪法:加载 / 合并 / 保存(跨项目共享规范)
1647
- ├── git/
1648
- │ └── worktree.ts # Git Worktree 管理
1649
- ├── prompts/
1650
- │ ├── spec.prompt.ts # Spec 生成 System Prompt
1651
- │ ├── codegen.prompt.ts # 代码生成 / 审查 System Prompt
1652
- │ ├── constitution.prompt.ts # 项目宪法生成 System Prompt
1653
- │ ├── tasks.prompt.ts # Tasks 分解 System Prompt
1654
- │ ├── dsl.prompt.ts # DSL 提取 System Prompt(含抗幻觉规则)
1655
- │ ├── testgen.prompt.ts # 测试骨架生成 System Prompt
1656
- │ ├── decompose.prompt.ts # [Phase 4] 需求拆分 System Prompt(含 UX 决策指南)
1657
- │ ├── frontend-spec.prompt.ts # [Phase 4] 前端 Spec 生成 Prompt(含 API 契约注入)
1658
- │ └── global-constitution.prompt.ts # [v0.8] 全局宪法生成 System Prompt(5 章跨端规范)
1659
- ├── specs/ # 生成的 Spec + DSL + Tasks 输出目录
1660
- │ ├── feature-<slug>-v1.md ← 版本化命名
1661
- │ ├── feature-<slug>-v1.dsl.json ← DSL(Phase 2 新增)
1662
- │ ├── feature-<slug>-v1-tasks.json
1663
- │ └── ...
1664
- ├── README.md
1665
- └── RELEASE_LOG.md # 版本变更记录
1666
- ```
402
+ Spec 按结构化模板生成:功能概述 → 背景动机 → 用户故事 → 功能需求 → API 设计 → 数据模型 → 非功能性需求 → 实施要点。
1667
403
 
404
+ Tasks 按实施层级排序:`data → infra → service → api → test`,代码生成时逐任务执行。
1668
405
  </details>
1669
406
 
1670
407
  <details>
1671
- <summary>English</summary>
1672
-
1673
- # ai-spec
408
+ <summary>Step 3 — 交互式润色 + 质量评估 + Approval Gate</summary>
1674
409
 
1675
- GitHub: <https://github.com/hzhongzhong/ai-spec>
1676
-
1677
- > An AI-driven feature delivery orchestrator that turns a short requirement into runnable code, with support for both single-repo development and multi-repo cross-stack workflows.
410
+ - **润色**:AI Polish 后展示彩色 diff,支持多轮编辑
411
+ - **质量评估**:Coverage / Clarity / Constitution 三维度 0-10 评分
412
+ - **Approval Gate**:展示版本差异,确认后进入代码生成
413
+ </details>
1678
414
 
1679
- **Single-repo pipeline**
415
+ <details>
416
+ <summary>Step DSL — 双层契约提取</summary>
1680
417
 
1681
- ```text
1682
- Requirement → Project Constitution → Project Context → Spec + Tasks → Interactive Refinement (with diff preview) → Spec Quality Assessment → Approval Gate → DSL Extraction + Validation → DSL Gap Feedback → Git Isolation → Code Generation (parallel by dependency layer) → TDD / Test Skeleton → Error Feedback Auto-Fix → 3-pass Review → Review→DSL Loop → Harness Self-Eval → Lesson Accumulation (§9)
1683
- ```
418
+ Spec → SpecDSL JSON(models + endpoints + behaviors + components)。内置校验(无外部依赖)、自动重试、前端/后端自动分叉。DSL Gap Feedback 检测稀疏契约并定向补全。
419
+ </details>
1684
420
 
1685
- **Workspace pipeline**
421
+ <details>
422
+ <summary>Step 6–10 — 代码生成 → 审查 → 自评</summary>
423
+
424
+ - **代码生成**:逐任务生成,DSL 上下文注入,支持 `claude-code` / `api` / `plan` 三种模式
425
+ - **测试骨架**:自动生成测试文件,TDD 模式支持真实断言
426
+ - **错误反馈**:自动捕获编译/测试错误,AI 定向修复,最多循环 2–3 轮
427
+ - **3-Pass 审查**:架构层 → 实现层 → 影响面/复杂度,结构性问题反写 DSL
428
+ - **Harness 自评**:合规性 + DSL覆盖 + 编译 + 审查 四维评分
429
+ - **经验积累**:审查发现的 issue 自动写入宪法 §9
430
+ </details>
1686
431
 
1687
- ```text
1688
- One requirement → AI decomposition + UX decisions → [Backend pipeline → DSL contract] → [Frontend pipeline with injected contract] → End-to-end delivery
432
+ ### 架构总览
433
+
434
+ ```
435
+ ┌─────────────────────────────────────────────────────────────────┐
436
+ │ ai-spec Pipeline │
437
+ ├─────────┬──────────┬──────────┬──────────┬──────────┬──────────┤
438
+ │ Context │ Spec │ DSL │ Codegen │ Review │ Eval │
439
+ │ Loader │Generator │Extractor │Generator │ 3-Pass │ Harness │
440
+ │ │ + Tasks │+Validate │Task-by- │+Feedback │Self-Eval │
441
+ │ │ │+Gap Loop │ Task │ Loop │+Memory │
442
+ ├─────────┴──────────┴──────────┴──────────┴──────────┴──────────┤
443
+ │ Provider 抽象层 │
444
+ │ Gemini │ Claude │ OpenAI │ DeepSeek │ Qwen │ GLM │ ... (×9) │
445
+ ├─────────────────────────────────────────────────────────────────┤
446
+ │ 输出生成器 │
447
+ │ OpenAPI 导出 │ TypeScript 类型 │ Mock 服务器 │ Dashboard │
448
+ └─────────────────────────────────────────────────────────────────┘
449
+ ```
450
+
451
+ ### 项目结构
452
+
453
+ ```
454
+ ai-spec/
455
+ ├── cli/ # CLI 命令层(commander.js)
456
+ │ ├── commands/ # create, init, review, mock, export, ...
457
+ │ └── index.ts # 入口
458
+ ├── core/ # 核心引擎(25+ 模块)
459
+ │ ├── spec-generator.ts # 9 Provider AI 抽象
460
+ │ ├── dsl-extractor.ts # Spec → DSL 提取
461
+ │ ├── dsl-validator.ts # Schema 校验(无外部依赖)
462
+ │ ├── code-generator.ts # 分层任务代码生成
463
+ │ ├── reviewer.ts # 3-pass 代码审查
464
+ │ ├── self-evaluator.ts # Harness 评分
465
+ │ ├── vcr.ts # 录制与回放
466
+ │ ├── mock-server-generator.ts
467
+ │ ├── types-generator.ts
468
+ │ ├── openapi-exporter.ts
469
+ │ └── ...
470
+ ├── prompts/ # 所有 AI Prompt(与逻辑分离)
471
+ ├── tests/ # 18 个测试文件,409 个测试用例
472
+ └── docs-assets/ # 架构图
1689
473
  ```
1690
474
 
1691
- ---
1692
-
1693
- ## Table of Contents
475
+ ### License
1694
476
 
1695
- - [Quick Start](#quick-start)
1696
- - [Supported Models](#supported-models)
1697
- - [Command Overview](#command-overview)
1698
- - [Workflow](#workflow)
1699
- - [Multi-Repo Workspace Mode](#multi-repo-workspace-mode)
1700
- - [Multi-language Backend Support](#multi-language-backend-support)
1701
- - [Configuration](#configuration)
1702
- - [Global Installation](#global-installation)
1703
- - [Project Structure](#project-structure)
1704
- - [Release Log](RELEASE_LOG.md)
477
+ MIT
1705
478
 
1706
479
  ---
1707
480
 
1708
- ## Quick Start
1709
-
1710
- ```bash
1711
- # 1. Install dependencies and build
1712
- npm install
1713
- npm run build
1714
-
1715
- # 2. Set an API key (Gemini example)
1716
- export GEMINI_API_KEY=your_key_here
1717
-
1718
- # 3. Optional first run: generate a project constitution
1719
- ai-spec init
1720
-
1721
- # 4. Start developing from a natural-language requirement
1722
- ai-spec create "add login support to the user module"
1723
- ```
1724
-
1725
- `ai-spec create` runs a structured pipeline: context loading, spec generation, interactive refinement, DSL extraction, optional DSL gap feedback, isolated git worktree setup, code generation, optional tests, error-feedback repair, review, contract feedback, and harness self-evaluation.
1726
-
1727
- ## Supported Models
1728
-
1729
- - Supports 9 AI providers: Gemini, Claude, OpenAI, DeepSeek, Qwen, GLM, MiniMax, Doubao, and MiMo
1730
- - Allows separate providers/models for spec generation and code generation
1731
- - Exposes interactive model switching through `ai-spec model`
1732
- - Adapts provider-specific request behavior internally
1733
-
1734
- ## Command Overview
1735
-
1736
- Core commands:
1737
-
1738
- - `ai-spec init` — generate or regenerate the project constitution
1739
- - `ai-spec create [idea]` — run the end-to-end generation pipeline
1740
- - `ai-spec review [specFile]` — run an independent 3-pass code review
1741
- - `ai-spec update [change]` — update the latest spec and regenerate impacted files
1742
- - `ai-spec export` — export OpenAPI and SDK artifacts
1743
- - `ai-spec mock` — generate mock servers, proxies, and MSW handlers
1744
- - `ai-spec workspace` — initialize and inspect workspace orchestration
1745
- - `ai-spec model` / `config` — manage provider and project defaults
1746
- - `ai-spec trend` / `logs` / `dashboard` — inspect harness-quality history
1747
- - `ai-spec types` — generate TypeScript types from DSL
1748
-
1749
- Important execution options:
1750
-
1751
- - Provider and model selection for spec/codegen
1752
- - Codegen mode selection: `claude-code`, `api`, `plan`
1753
- - Flow control flags such as `--auto`, `--fast`, `--skip-*`
1754
- - Worktree control for isolated generation
1755
- - Enhanced modes such as `--tdd`
1756
-
1757
- ## Workflow
1758
-
1759
- ### Step 1 — Constitution + Context
1760
-
1761
- - Loads `.ai-spec-constitution.md` if present
1762
- - Auto-generates one when missing
1763
- - Extracts project context such as dependencies, routes, schema, and structure
1764
-
1765
- ### Step 2 — Spec + Tasks
1766
-
1767
- - Generates a structured feature spec in Markdown
1768
- - Produces tasks that preserve dependency order
1769
- - Keeps the spec as the high-level human-readable contract
1770
-
1771
- ### Step 3 — Interactive Refinement
1772
-
1773
- - Lets the user inspect AI edits before code generation
1774
- - Shows a diff preview
1775
- - Supports a fast path for non-interactive execution
1776
-
1777
- ### Step 3.4 — Spec Quality Assessment
1778
-
1779
- - Scores coverage, clarity, and constitution alignment before codegen
1780
- - Highlights weak spots that may cause DSL or implementation drift
1781
-
1782
- ### Step 3.5 — Approval Gate
1783
-
1784
- - Requires explicit approval before code generation unless auto mode is enabled
1785
- - Keeps humans in the loop at the highest-leverage decision point
1786
-
1787
- ### Step DSL — DSL Extraction and Validation
1788
-
1789
- - Converts the spec into a structured DSL
1790
- - Validates endpoint, model, and behavior declarations
1791
- - Provides a stable, machine-readable contract for downstream stages
1792
- - Also powers downstream outputs such as TypeScript types, OpenAPI export, mock generation, and workspace contract injection
1793
-
1794
- ### Step DSL+ — DSL Gap Feedback
1795
-
1796
- - Detects “valid but too sparse” DSL structures after extraction
1797
- - Lets the user refine the spec before entering code generation
1798
- - Prevents weak contracts from flowing into later stages unchanged
1799
-
1800
- ### Step 4 — Git Worktree
1801
-
1802
- - Creates an isolated worktree for safer generation
1803
- - Reduces the risk of polluting the main working directory
1804
-
1805
- ### Step 5 — Code Generation
1806
-
1807
- - Generates code incrementally
1808
- - Runs tasks in dependency-aware layers
1809
- - Uses frontend and backend context to reduce hallucination
1810
-
1811
- ### Step 7 — Test Generation
1812
-
1813
- - Can generate test skeletons or run in TDD mode
1814
- - Reuses the project’s testing conventions when possible
1815
-
1816
- ### Step 8 — Error Feedback Auto-Fix
1817
-
1818
- - Detects compile, lint, and test failures
1819
- - Feeds real errors back into the repair loop
1820
- - Includes dependency-order fixes and project-aware remediation
1821
-
1822
- ### Step 9 — Review + Lesson Accumulation
1823
-
1824
- - Uses a 3-pass review strategy: architecture, implementation, and impact/complexity
1825
- - Writes recurring issues back into Constitution §9 as accumulated lessons
1826
-
1827
- ### Step 9.5 — Review→DSL Loop
1828
-
1829
- - Turns structural review findings into contract-level follow-up actions
1830
- - Encourages updating Spec / DSL first, then regenerating with `ai-spec update --codegen`
1831
- - Upgrades the pipeline from one-way generation to a corrective loop
1832
-
1833
- ### Step 10 — Harness Self-Eval
1834
-
1835
- - Computes deterministic quality signals with zero extra AI calls
1836
- - Records `harnessScore` and `promptHash`
1837
- - Feeds `logs`, `trend`, and `dashboard` for historical observability
1838
-
1839
- ## Multi-Repo Workspace Mode
1840
-
1841
- Workspace mode is designed for backend + frontend or multi-service repositories:
1842
-
1843
- - Detects or configures multiple repos under one workspace
1844
- - Runs backend repos first when they provide contracts
1845
- - Injects backend DSL contracts into downstream frontend spec generation
1846
- - Adds UX decisions so cross-repo work remains consistent
1847
-
1848
- Typical use cases:
1849
-
1850
- - Backend API + Web frontend
1851
- - Backend API + Mobile app
1852
- - Shared contract packages + multiple product surfaces
1853
-
1854
- ## Multi-language Backend Support
1855
-
1856
- The tool is not limited to one backend language. Current repo detection and context support cover:
1857
-
1858
- - Node.js / Express / Koa
1859
- - Java (Maven / Gradle)
1860
- - PHP / Lumen / Laravel
1861
- - Go
1862
- - Rust
1863
- - Python
1864
-
1865
- Code generation prompts are selected according to detected repo type so each stack receives stack-appropriate conventions.
1866
-
1867
- ## Configuration
1868
-
1869
- Supported configuration layers:
1870
-
1871
- - Project-level `.ai-spec.json`
1872
- - Workspace-level `.ai-spec-workspace.json`
1873
- - Project constitution `.ai-spec-constitution.md`
1874
- - Shared global constitution for cross-project rules
1875
-
1876
- The global constitution mechanism lets teams define reusable API, naming, and architectural rules once, then merge them into project-specific constitutions.
1877
-
1878
- ## Global Installation
1879
-
1880
- ```bash
1881
- npm install -g .
1882
- ai-spec
1883
- ```
1884
-
1885
- Running without arguments shows the welcome screen, current provider/model, and recent specs.
1886
-
1887
- ## Project Structure
1888
-
1889
- Main directories:
1890
-
1891
- - `cli/` — command entrypoints
1892
- - `core/` — orchestration, generation, review, validation, logging, and harness modules
1893
- - `prompts/` — provider-facing system prompts
1894
- - `specs/` — generated specs, DSL files, and task files
1895
- - `git/` — worktree management
1896
-
1897
- Key modules include constitution generation, DSL extraction, code generation, error feedback, self-evaluation, workspace loading, frontend context loading, logs/trend/dashboard reporting, and type generation.
1898
-
1899
- </details>
481
+ <p align="center">
482
+ Built with AI, for AI-driven development.<br/>
483
+ <a href="https://github.com/hzhongzhong/ai-spec">github.com/hzhongzhong/ai-spec</a>
484
+ </p>