@zeyue0329/xiaoma-cli 1.0.39 → 1.0.41

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 (27) hide show
  1. package/.idea/workspace.xml +1 -0
  2. package/.xiaoma-core/.coordinator-state.json +19 -0
  3. package/dist/agents/architect.txt +192 -0
  4. package/dist/agents/workflow-helper.txt +93 -0
  5. package/dist/teams/team-all.txt +245 -190
  6. package/dist/teams/team-fullstack-with-database.txt +2 -0
  7. package/dist/teams/team-fullstack.txt +2 -0
  8. package/dist/teams/team-no-ui.txt +2 -0
  9. package/docs/architecture/workflow-coordinator-implementation.md +1188 -0
  10. package/docs/prd/workflow-coordinator-prd.md +1214 -0
  11. package/package.json +1 -1
  12. package/tools/installer/package.json +1 -1
  13. package/tools/workflow-coordinator/README.md +38 -0
  14. package/tools/workflow-coordinator/USAGE.md +548 -0
  15. package/tools/workflow-coordinator/package-lock.json +4868 -0
  16. package/tools/workflow-coordinator/package.json +35 -0
  17. package/tools/workflow-coordinator/src/api/server.js +207 -0
  18. package/tools/workflow-coordinator/src/controller/workflow-controller.js +263 -0
  19. package/tools/workflow-coordinator/src/index.js +113 -0
  20. package/tools/workflow-coordinator/src/parser/workflow-parser.js +144 -0
  21. package/tools/workflow-coordinator/src/utils/state-manager.js +59 -0
  22. package/tools/workflow-coordinator/src/utils/validator.js +86 -0
  23. package/tools/workflow-coordinator/test/integration-test.js +266 -0
  24. package/tools/workflow-coordinator/test/quick-test.js +127 -0
  25. package/xiaoma-core/agents/architect.md +2 -0
  26. package/xiaoma-core/agents/workflow-helper.md +481 -0
  27. package/xiaoma-core/workflows/automated-requirements-analysis.yaml +11 -8
@@ -0,0 +1,1214 @@
1
+ # PRD: 工作流协调器 (Workflow Coordinator)
2
+
3
+ > **版本**: 2.0.0
4
+ > **作者**: Claude Code
5
+ > **日期**: 2025-11-13
6
+ > **状态**: Draft
7
+ > **修订**: 基于正确的架构理解重新编写
8
+
9
+ ---
10
+
11
+ ## 1. 产品概述
12
+
13
+ ### 1.1 背景
14
+
15
+ XiaoMa-CLI 当前通过 `workflow-executor` 智能体执行自动化工作流,但存在关键问题:
16
+ - AI 会在步骤间暂停询问用户"是否继续"
17
+ - 无法实现真正的端到端自动化
18
+ - 依赖 AI 判断而非程序逻辑控制流程
19
+
20
+ ### 1.2 产品定位
21
+
22
+ 开发一个**工作流协调器(Workflow Coordinator)**,作为外部进程运行,负责:
23
+ - 解析工作流YAML定义
24
+ - **监听** Claude Code 中智能体的执行结果
25
+ - **决策**下一步应该执行的步骤
26
+ - **发送指令**给 Claude Code 让其执行下一步
27
+
28
+ **关键理念**:
29
+ - ✅ Claude Code 负责执行(调用智能体、生成文档)
30
+ - ✅ 协调器负责流程控制(监听结果、决策下一步)
31
+ - ✅ 两者通过 HTTP API + 文件系统通信
32
+
33
+ ### 1.3 核心价值
34
+
35
+ - **完全自动化**: 协调器驱动整个流程,无需人工干预
36
+ - **职责分离**: Claude Code专注执行,协调器专注控制流
37
+ - **可靠性高**: 程序化的流程控制,结果可预测
38
+ - **易于扩展**: 支持新增工作流和智能体
39
+
40
+ ---
41
+
42
+ ## 2. 系统架构
43
+
44
+ ### 2.1 整体架构图
45
+
46
+ ```
47
+ ┌────────────────────────────────────────────────────────────────┐
48
+ │ 用户 │
49
+ │ - 启动工作流: xiaoma-coordinator start requirements-analysis │
50
+ └────────────────┬───────────────────────────────────────────────┘
51
+
52
+
53
+ ┌────────────────────────────────────────────────────────────────┐
54
+ │ 工作流协调器 (Workflow Coordinator) │
55
+ │ - 外部Node.js进程 │
56
+ │ - HTTP Server (端口3001) │
57
+ │ │
58
+ │ 核心功能: │
59
+ │ 1. 解析工作流YAML → 生成执行计划 │
60
+ │ 2. 启动HTTP服务,等待Claude Code回调 │
61
+ │ 3. 监听步骤完成事件 → 决策下一步 │
62
+ │ 4. 通过HTTP API返回下一步指令 │
63
+ │ 5. 状态持久化和恢复 │
64
+ └────────────┬────────────────────────────┬──────────────────────┘
65
+ │ │
66
+ │ HTTP API调用 │ 文件系统读写
67
+ │ │
68
+ ↓ ↓
69
+ ┌────────────────────────────────────────────────────────────────┐
70
+ │ Claude Code (IDE环境) │
71
+ │ │
72
+ │ 智能体执行层: │
73
+ │ - /analyst → 需求分析 │
74
+ │ - /architect → 架构分析/设计 │
75
+ │ - /pm → PRD创建/Epic拆分 │
76
+ │ - /po, /sm, /dev, /qa → 用户故事开发 │
77
+ │ │
78
+ │ 工作流助手智能体 (新增): │
79
+ │ - workflow-helper │
80
+ │ - 负责与协调器通信 │
81
+ │ - 接收协调器指令并执行 │
82
+ │ - 报告步骤完成状态 │
83
+ └────────────────────────────────────────────────────────────────┘
84
+
85
+
86
+ ┌────────────────────────────────────────────────────────────────┐
87
+ │ 文件系统 │
88
+ │ - 工作流定义: xiaoma-core/workflows/*.yaml │
89
+ │ - 输入文档: docs/req.txt │
90
+ │ - 输出文档: docs/prd/, docs/epics/, docs/architecture/ │
91
+ │ - 协调器状态: .xiaoma-core/.coordinator-state.json │
92
+ └────────────────────────────────────────────────────────────────┘
93
+ ```
94
+
95
+ ### 2.2 通信协议设计
96
+
97
+ #### 协议1: HTTP API (主要通信方式)
98
+
99
+ **协调器提供的API**:
100
+
101
+ ```yaml
102
+ API端点设计:
103
+
104
+ 1. POST /workflow/start
105
+ 描述: 启动工作流,获取第一步指令
106
+ 请求体:
107
+ {
108
+ "workflowId": "requirements-analysis",
109
+ "context": {
110
+ "projectRoot": "/path/to/project"
111
+ }
112
+ }
113
+ 响应体:
114
+ {
115
+ "success": true,
116
+ "workflowId": "requirements-analysis",
117
+ "workflowName": "自动化需求分析和架构设计流程",
118
+ "firstStep": {
119
+ "stepId": "requirements_analysis_and_elicitation",
120
+ "agent": "analyst",
121
+ "command": "/analyst",
122
+ "prompt": "执行需求分析...",
123
+ "inputFiles": ["docs/req.txt"],
124
+ "expectedOutputs": ["docs/requirements/requirements-analysis.md"]
125
+ }
126
+ }
127
+
128
+ 2. POST /workflow/step-complete
129
+ 描述: 报告步骤完成,获取下一步指令
130
+ 请求体:
131
+ {
132
+ "workflowId": "requirements-analysis",
133
+ "stepId": "requirements_analysis_and_elicitation",
134
+ "status": "success",
135
+ "outputs": [
136
+ {
137
+ "file": "docs/requirements/requirements-analysis.md",
138
+ "exists": true,
139
+ "size": 25600
140
+ }
141
+ ],
142
+ "duration": 1200000, // 毫秒
143
+ "errors": []
144
+ }
145
+ 响应体:
146
+ {
147
+ "success": true,
148
+ "hasNextStep": true,
149
+ "nextStep": {
150
+ "stepId": "analyze_existing_architecture",
151
+ "agent": "architect",
152
+ "command": "/architect",
153
+ "prompt": "分析现有架构...",
154
+ "inputFiles": ["src/", "pom.xml"],
155
+ "expectedOutputs": ["docs/architecture/current-architecture-analysis.md"]
156
+ },
157
+ "progress": {
158
+ "currentStepIndex": 2,
159
+ "totalSteps": 6,
160
+ "percentComplete": 33
161
+ }
162
+ }
163
+
164
+ 3. POST /workflow/step-failed
165
+ 描述: 报告步骤失败,协调器决策是否重试
166
+ 请求体:
167
+ {
168
+ "workflowId": "requirements-analysis",
169
+ "stepId": "create_brownfield_prd",
170
+ "error": "文件写入失败",
171
+ "errorDetails": "..."
172
+ }
173
+ 响应体:
174
+ {
175
+ "success": true,
176
+ "action": "retry", // 或 "abort"
177
+ "retryStep": {
178
+ "stepId": "create_brownfield_prd",
179
+ "agent": "pm",
180
+ "command": "/pm",
181
+ "prompt": "...",
182
+ "retryCount": 1,
183
+ "maxRetries": 3
184
+ }
185
+ }
186
+
187
+ 4. GET /workflow/status
188
+ 描述: 查询当前工作流状态
189
+ 响应体:
190
+ {
191
+ "workflowId": "requirements-analysis",
192
+ "status": "in_progress",
193
+ "currentStepIndex": 3,
194
+ "totalSteps": 6,
195
+ "completedSteps": ["step1", "step2"],
196
+ "currentStep": "step3",
197
+ "startTime": "2025-11-13T10:00:00Z",
198
+ "duration": 3600000
199
+ }
200
+
201
+ 5. POST /workflow/abort
202
+ 描述: 中止当前工作流
203
+ 请求体:
204
+ {
205
+ "workflowId": "requirements-analysis",
206
+ "reason": "用户取消"
207
+ }
208
+ 响应体:
209
+ {
210
+ "success": true,
211
+ "message": "工作流已中止,状态已保存"
212
+ }
213
+ ```
214
+
215
+ #### 协议2: 文件系统 (辅助通信方式)
216
+
217
+ 用于协调器无法实时监听的场景:
218
+
219
+ ```
220
+ 文件路径约定:
221
+
222
+ 1. 协调器状态文件
223
+ 路径: .xiaoma-core/.coordinator-state.json
224
+ 用途: 保存工作流执行状态
225
+ 格式:
226
+ {
227
+ "workflowId": "requirements-analysis",
228
+ "status": "in_progress",
229
+ "currentStepIndex": 3,
230
+ "completedSteps": [...],
231
+ "nextStep": {...}
232
+ }
233
+
234
+ 2. 步骤执行结果文件
235
+ 路径: .xiaoma-core/.step-result-{stepId}.json
236
+ 用途: Claude Code写入步骤执行结果
237
+ 格式:
238
+ {
239
+ "stepId": "requirements_analysis",
240
+ "status": "success",
241
+ "outputs": [...],
242
+ "duration": 1200000,
243
+ "timestamp": "2025-11-13T10:20:00Z"
244
+ }
245
+
246
+ 3. 下一步指令文件
247
+ 路径: .xiaoma-core/.next-instruction.json
248
+ 用途: 协调器写入,Claude Code读取
249
+ 格式:
250
+ {
251
+ "stepId": "analyze_existing_architecture",
252
+ "agent": "architect",
253
+ "command": "/architect",
254
+ "prompt": "...",
255
+ "inputFiles": [...]
256
+ }
257
+ ```
258
+
259
+ ---
260
+
261
+ ## 3. 核心功能需求
262
+
263
+ ### 3.1 工作流协调器 (外部进程)
264
+
265
+ #### F1: 工作流解析和执行计划生成
266
+
267
+ **功能描述**: 解析工作流YAML,生成完整的执行计划
268
+
269
+ **输入**:
270
+ - 工作流名称(如 `requirements-analysis`)
271
+ - 工作流YAML文件路径
272
+
273
+ **输出**:
274
+ - 执行计划对象,包含:
275
+ - 步骤序列
276
+ - 每个步骤的智能体、命令、提示词
277
+ - 输入输出文件
278
+ - 验证标准
279
+
280
+ **核心逻辑**:
281
+ ```javascript
282
+ class WorkflowCoordinator {
283
+ async parseWorkflow(workflowName) {
284
+ // 1. 加载YAML
285
+ const yamlContent = await fs.readFile(`xiaoma-core/workflows/${workflowName}.yaml`);
286
+ const workflowDef = yaml.parse(yamlContent);
287
+
288
+ // 2. 构建执行计划
289
+ const plan = {
290
+ metadata: workflowDef.workflow,
291
+ steps: workflowDef.workflow.sequence.map(step => ({
292
+ id: step.step,
293
+ agent: step.agent,
294
+ detailedSteps: step.detailed_steps,
295
+ requires: step.requires,
296
+ outputs: this.extractOutputs(step),
297
+ validationCriteria: step.validation_criteria
298
+ }))
299
+ };
300
+
301
+ return plan;
302
+ }
303
+ }
304
+ ```
305
+
306
+ ---
307
+
308
+ #### F2: HTTP服务器
309
+
310
+ **功能描述**: 启动HTTP服务,接收Claude Code的回调请求
311
+
312
+ **核心接口**:
313
+ - `POST /workflow/start` - 启动工作流
314
+ - `POST /workflow/step-complete` - 步骤完成
315
+ - `POST /workflow/step-failed` - 步骤失败
316
+ - `GET /workflow/status` - 查询状态
317
+ - `POST /workflow/abort` - 中止工作流
318
+
319
+ **实现方式**:
320
+ ```javascript
321
+ const express = require('express');
322
+
323
+ class CoordinatorServer {
324
+ constructor(coordinator) {
325
+ this.app = express();
326
+ this.coordinator = coordinator;
327
+ this.setupRoutes();
328
+ }
329
+
330
+ setupRoutes() {
331
+ // 启动工作流
332
+ this.app.post('/workflow/start', async (req, res) => {
333
+ const { workflowId, context } = req.body;
334
+ const result = await this.coordinator.startWorkflow(workflowId, context);
335
+ res.json(result);
336
+ });
337
+
338
+ // 步骤完成回调
339
+ this.app.post('/workflow/step-complete', async (req, res) => {
340
+ const { workflowId, stepId, status, outputs } = req.body;
341
+ const nextStep = await this.coordinator.onStepComplete(workflowId, stepId, outputs);
342
+ res.json(nextStep);
343
+ });
344
+
345
+ // 其他路由...
346
+ }
347
+
348
+ start(port = 3001) {
349
+ this.app.listen(port, () => {
350
+ console.log(`协调器HTTP服务已启动: http://localhost:${port}`);
351
+ });
352
+ }
353
+ }
354
+ ```
355
+
356
+ ---
357
+
358
+ #### F3: 步骤流程控制
359
+
360
+ **功能描述**: 根据当前步骤完成状态,决策下一步执行什么
361
+
362
+ **核心逻辑**:
363
+
364
+ ```javascript
365
+ class WorkflowCoordinator {
366
+ async onStepComplete(workflowId, stepId, outputs) {
367
+ // 1. 加载当前状态
368
+ const state = this.loadState(workflowId);
369
+
370
+ // 2. 验证步骤完成质量
371
+ const validationResult = this.validateStepOutputs(stepId, outputs);
372
+ if (!validationResult.passed) {
373
+ // 质量不达标,返回重试指令或修正建议
374
+ return {
375
+ success: false,
376
+ action: 'fix',
377
+ issues: validationResult.issues
378
+ };
379
+ }
380
+
381
+ // 3. 更新状态
382
+ state.completedSteps.push({
383
+ stepId: stepId,
384
+ outputs: outputs,
385
+ completedAt: Date.now()
386
+ });
387
+ state.currentStepIndex++;
388
+
389
+ // 4. 保存状态
390
+ this.saveState(workflowId, state);
391
+
392
+ // 5. 获取下一步
393
+ const nextStepDef = this.executionPlan.steps[state.currentStepIndex];
394
+
395
+ if (!nextStepDef) {
396
+ // 工作流完成
397
+ return {
398
+ success: true,
399
+ hasNextStep: false,
400
+ message: '工作流已完成',
401
+ summary: this.generateSummary(state)
402
+ };
403
+ }
404
+
405
+ // 6. 构建下一步指令
406
+ const nextStep = this.buildStepInstruction(nextStepDef, state);
407
+
408
+ return {
409
+ success: true,
410
+ hasNextStep: true,
411
+ nextStep: nextStep,
412
+ progress: {
413
+ currentStepIndex: state.currentStepIndex,
414
+ totalSteps: this.executionPlan.steps.length,
415
+ percentComplete: Math.round(state.currentStepIndex / this.executionPlan.steps.length * 100)
416
+ }
417
+ };
418
+ }
419
+
420
+ buildStepInstruction(stepDef, state) {
421
+ // 从 detailed_steps 中提取执行指令
422
+ const detailedSteps = stepDef.detailedSteps || [];
423
+
424
+ // 找到第一个需要执行的命令步骤
425
+ const commandStep = detailedSteps.find(ds =>
426
+ ds.command && (ds.command.startsWith('/') || ds.command.startsWith('*'))
427
+ );
428
+
429
+ return {
430
+ stepId: stepDef.id,
431
+ agent: stepDef.agent,
432
+ command: commandStep?.command || `/agent ${stepDef.agent}`,
433
+ prompt: commandStep?.prompt_template || '',
434
+ inputFiles: stepDef.requires || [],
435
+ expectedOutputs: stepDef.outputs || [],
436
+ detailedSteps: detailedSteps // 完整的详细步骤列表
437
+ };
438
+ }
439
+ }
440
+ ```
441
+
442
+ ---
443
+
444
+ #### F4: 状态持久化和恢复
445
+
446
+ **功能描述**: 保存工作流执行状态,支持中断恢复
447
+
448
+ **状态文件结构**:
449
+ ```json
450
+ {
451
+ "workflowId": "requirements-analysis",
452
+ "workflowName": "自动化需求分析和架构设计流程",
453
+ "status": "in_progress",
454
+ "startTime": "2025-11-13T10:00:00Z",
455
+ "currentStepIndex": 3,
456
+ "completedSteps": [
457
+ {
458
+ "stepId": "requirements_analysis_and_elicitation",
459
+ "agent": "analyst",
460
+ "outputs": ["docs/requirements/requirements-analysis.md"],
461
+ "startTime": "2025-11-13T10:01:00Z",
462
+ "endTime": "2025-11-13T10:20:00Z",
463
+ "duration": 1140000
464
+ },
465
+ {
466
+ "stepId": "analyze_existing_architecture",
467
+ "agent": "architect",
468
+ "outputs": ["docs/architecture/current-architecture-analysis.md"],
469
+ "startTime": "2025-11-13T10:20:00Z",
470
+ "endTime": "2025-11-13T10:35:00Z",
471
+ "duration": 900000
472
+ }
473
+ ],
474
+ "errors": [],
475
+ "retries": {}
476
+ }
477
+ ```
478
+
479
+ **恢复逻辑**:
480
+ ```javascript
481
+ async resumeWorkflow(workflowId) {
482
+ // 1. 加载状态
483
+ const state = this.loadState(workflowId);
484
+
485
+ if (!state) {
486
+ throw new Error('未找到可恢复的工作流状态');
487
+ }
488
+
489
+ // 2. 验证已完成步骤的输出文件
490
+ for (const completedStep of state.completedSteps) {
491
+ for (const outputFile of completedStep.outputs) {
492
+ if (!fs.existsSync(outputFile)) {
493
+ throw new Error(`输出文件缺失: ${outputFile}`);
494
+ }
495
+ }
496
+ }
497
+
498
+ // 3. 获取下一步指令
499
+ const nextStepDef = this.executionPlan.steps[state.currentStepIndex];
500
+ const nextStep = this.buildStepInstruction(nextStepDef, state);
501
+
502
+ return {
503
+ success: true,
504
+ resumeFrom: state.currentStepIndex,
505
+ nextStep: nextStep
506
+ };
507
+ }
508
+ ```
509
+
510
+ ---
511
+
512
+ #### F5: 质量门控验证
513
+
514
+ **功能描述**: 验证步骤输出是否符合质量标准
515
+
516
+ **验证维度**:
517
+ 1. 文件完整性: 所有声明的输出文件都已生成
518
+ 2. 文件非空: 文件大小 > 0
519
+ 3. 格式正确: Markdown/YAML/SQL格式验证
520
+
521
+ **实现**:
522
+ ```javascript
523
+ validateStepOutputs(stepId, outputs) {
524
+ const stepDef = this.executionPlan.steps.find(s => s.id === stepId);
525
+ const issues = [];
526
+
527
+ // 1. 检查所有预期输出文件
528
+ for (const expectedOutput of stepDef.outputs || []) {
529
+ const actualOutput = outputs.find(o => o.file === expectedOutput.file);
530
+
531
+ if (!actualOutput) {
532
+ issues.push({
533
+ level: 'error',
534
+ message: `输出文件未生成: ${expectedOutput.file}`
535
+ });
536
+ continue;
537
+ }
538
+
539
+ if (!actualOutput.exists) {
540
+ issues.push({
541
+ level: 'error',
542
+ message: `输出文件不存在: ${expectedOutput.file}`
543
+ });
544
+ }
545
+
546
+ if (actualOutput.size === 0) {
547
+ issues.push({
548
+ level: 'error',
549
+ message: `输出文件为空: ${expectedOutput.file}`
550
+ });
551
+ }
552
+ }
553
+
554
+ // 2. 根据validation_criteria验证
555
+ for (const criterion of stepDef.validationCriteria || []) {
556
+ // 实现具体的验证逻辑
557
+ }
558
+
559
+ return {
560
+ passed: issues.filter(i => i.level === 'error').length === 0,
561
+ issues: issues
562
+ };
563
+ }
564
+ ```
565
+
566
+ ---
567
+
568
+ ### 3.2 Claude Code集成层
569
+
570
+ #### F6: workflow-helper 智能体
571
+
572
+ **功能描述**: Claude Code中的新智能体,负责与协调器通信
573
+
574
+ **智能体定义** (`xiaoma-core/agents/workflow-helper.md`):
575
+
576
+ ```yaml
577
+ agent:
578
+ name: workflow-helper
579
+ id: workflow-helper
580
+ title: 工作流助手
581
+ role: 与工作流协调器通信,自动执行工作流步骤
582
+
583
+ persona:
584
+ role: 工作流自动化助手
585
+ focus: 执行协调器下发的指令,报告执行结果
586
+ core_principles:
587
+ - 严格按照协调器指令执行
588
+ - 自动切换智能体
589
+ - 自动报告步骤完成状态
590
+ - 不询问用户,完全自动化
591
+
592
+ commands:
593
+ - start-workflow {workflow-name}: 启动工作流
594
+ - execute-next-step: 执行下一步(由协调器指示)
595
+ - report-complete: 报告当前步骤完成
596
+ - report-failed: 报告当前步骤失败
597
+ - status: 查询当前工作流状态
598
+ ```
599
+
600
+ **核心功能**:
601
+
602
+ ```javascript
603
+ // workflow-helper 的执行逻辑
604
+
605
+ class WorkflowHelper {
606
+ constructor() {
607
+ this.coordinatorURL = 'http://localhost:3001';
608
+ }
609
+
610
+ // 命令: *start-workflow requirements-analysis
611
+ async startWorkflow(workflowName) {
612
+ console.log(`启动工作流: ${workflowName}`);
613
+
614
+ // 1. 调用协调器API
615
+ const response = await fetch(`${this.coordinatorURL}/workflow/start`, {
616
+ method: 'POST',
617
+ headers: { 'Content-Type': 'application/json' },
618
+ body: JSON.stringify({
619
+ workflowId: workflowName,
620
+ context: {
621
+ projectRoot: process.cwd()
622
+ }
623
+ })
624
+ });
625
+
626
+ const result = await response.json();
627
+
628
+ if (!result.success) {
629
+ console.error('启动失败:', result.error);
630
+ return;
631
+ }
632
+
633
+ console.log(`工作流: ${result.workflowName}`);
634
+ console.log(`总步骤数: ${result.firstStep ? '多步骤' : '未知'}`);
635
+
636
+ // 2. 执行第一步
637
+ await this.executeStep(result.firstStep);
638
+ }
639
+
640
+ // 执行单个步骤
641
+ async executeStep(stepInstruction) {
642
+ console.log(`\n执行步骤: ${stepInstruction.stepId}`);
643
+ console.log(`智能体: ${stepInstruction.agent}`);
644
+ console.log(`命令: ${stepInstruction.command}`);
645
+
646
+ const startTime = Date.now();
647
+
648
+ try {
649
+ // 3. 切换智能体(如果需要)
650
+ if (stepInstruction.command.startsWith('/')) {
651
+ console.log(`切换到智能体: ${stepInstruction.agent}`);
652
+ // 在Claude Code中切换智能体
653
+ // (这里需要实际的智能体切换实现)
654
+ }
655
+
656
+ // 4. 执行命令和prompt
657
+ console.log(`\n提示词:\n${stepInstruction.prompt}\n`);
658
+
659
+ // 这里Claude Code会实际执行智能体命令
660
+ // 比如 Analyst 执行需求分析,生成文档等
661
+ // 执行完成后,需要收集输出文件信息
662
+
663
+ // 5. 等待步骤完成(实际由智能体执行)
664
+ // 假设智能体执行完成后,我们能获取到输出信息
665
+
666
+ const outputs = this.collectStepOutputs(stepInstruction.expectedOutputs);
667
+
668
+ // 6. 报告步骤完成
669
+ await this.reportStepComplete({
670
+ workflowId: stepInstruction.workflowId || 'current',
671
+ stepId: stepInstruction.stepId,
672
+ status: 'success',
673
+ outputs: outputs,
674
+ duration: Date.now() - startTime
675
+ });
676
+
677
+ } catch (error) {
678
+ console.error(`步骤执行失败: ${error.message}`);
679
+
680
+ // 报告失败
681
+ await this.reportStepFailed({
682
+ workflowId: stepInstruction.workflowId || 'current',
683
+ stepId: stepInstruction.stepId,
684
+ error: error.message
685
+ });
686
+ }
687
+ }
688
+
689
+ // 报告步骤完成
690
+ async reportStepComplete(result) {
691
+ console.log(`\n报告步骤完成: ${result.stepId}`);
692
+
693
+ const response = await fetch(`${this.coordinatorURL}/workflow/step-complete`, {
694
+ method: 'POST',
695
+ headers: { 'Content-Type': 'application/json' },
696
+ body: JSON.stringify(result)
697
+ });
698
+
699
+ const nextStep = await response.json();
700
+
701
+ if (!nextStep.success) {
702
+ console.error('协调器响应失败:', nextStep.error);
703
+ return;
704
+ }
705
+
706
+ if (!nextStep.hasNextStep) {
707
+ console.log('\n🎉 工作流执行完成!');
708
+ console.log(nextStep.message);
709
+ return;
710
+ }
711
+
712
+ // 自动执行下一步(关键:不询问用户!)
713
+ console.log(`\n进度: ${nextStep.progress.percentComplete}% (${nextStep.progress.currentStepIndex}/${nextStep.progress.totalSteps})`);
714
+ console.log('→ 自动进入下一步骤...\n');
715
+
716
+ // 执行下一步
717
+ await this.executeStep(nextStep.nextStep);
718
+ }
719
+
720
+ // 收集步骤输出
721
+ collectStepOutputs(expectedOutputs) {
722
+ const outputs = [];
723
+
724
+ for (const expected of expectedOutputs) {
725
+ const filePath = expected.file || expected;
726
+
727
+ outputs.push({
728
+ file: filePath,
729
+ exists: fs.existsSync(filePath),
730
+ size: fs.existsSync(filePath) ? fs.statSync(filePath).size : 0
731
+ });
732
+ }
733
+
734
+ return outputs;
735
+ }
736
+ }
737
+ ```
738
+
739
+ ---
740
+
741
+ #### F7: MCP工具集成(可选增强)
742
+
743
+ 如果需要更深度的集成,可以开发MCP工具:
744
+
745
+ ```typescript
746
+ // mcp-server-workflow-coordinator/index.ts
747
+
748
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
749
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
750
+
751
+ const server = new Server({
752
+ name: 'workflow-coordinator',
753
+ version: '1.0.0',
754
+ }, {
755
+ capabilities: {
756
+ tools: {},
757
+ },
758
+ });
759
+
760
+ // 工具1: 启动工作流
761
+ server.setRequestHandler('tools/call', async (request) => {
762
+ if (request.params.name === 'start_workflow') {
763
+ const { workflowName } = request.params.arguments;
764
+
765
+ // 调用协调器API
766
+ const response = await fetch('http://localhost:3001/workflow/start', {
767
+ method: 'POST',
768
+ body: JSON.stringify({ workflowId: workflowName })
769
+ });
770
+
771
+ const result = await response.json();
772
+
773
+ return {
774
+ content: [{
775
+ type: 'text',
776
+ text: JSON.stringify(result, null, 2)
777
+ }]
778
+ };
779
+ }
780
+
781
+ // 工具2: 报告步骤完成
782
+ if (request.params.name === 'report_step_complete') {
783
+ const { stepId, outputs } = request.params.arguments;
784
+
785
+ const response = await fetch('http://localhost:3001/workflow/step-complete', {
786
+ method: 'POST',
787
+ body: JSON.stringify({ stepId, outputs })
788
+ });
789
+
790
+ const result = await response.json();
791
+
792
+ return {
793
+ content: [{
794
+ type: 'text',
795
+ text: JSON.stringify(result, null, 2)
796
+ }]
797
+ };
798
+ }
799
+ });
800
+
801
+ // 启动MCP服务器
802
+ const transport = new StdioServerTransport();
803
+ await server.connect(transport);
804
+ ```
805
+
806
+ ---
807
+
808
+ ## 4. 使用流程
809
+
810
+ ### 4.1 完整执行流程
811
+
812
+ ```
813
+ 用户执行命令:
814
+ ┌──────────────────────────────────────────────────┐
815
+ │ xiaoma-coordinator start requirements-analysis │
816
+ └──────────────────┬───────────────────────────────┘
817
+
818
+
819
+ 1. 协调器启动
820
+ ┌──────────────────────────────────────────────────┐
821
+ │ - 解析工作流YAML │
822
+ │ - 生成执行计划 │
823
+ │ - 启动HTTP服务(端口3001) │
824
+ │ - 等待Claude Code连接 │
825
+ └──────────────────┬───────────────────────────────┘
826
+
827
+
828
+ 2. 用户在Claude Code中启动工作流
829
+ ┌──────────────────────────────────────────────────┐
830
+ │ 在Claude Code CLI中执行: │
831
+ │ /workflow-helper │
832
+ │ *start-workflow requirements-analysis │
833
+ └──────────────────┬───────────────────────────────┘
834
+
835
+
836
+ 3. workflow-helper调用协调器API
837
+ ┌──────────────────────────────────────────────────┐
838
+ │ POST http://localhost:3001/workflow/start │
839
+ │ 请求体: { workflowId: "requirements-analysis" } │
840
+ └──────────────────┬───────────────────────────────┘
841
+
842
+
843
+ 4. 协调器返回第一步指令
844
+ ┌──────────────────────────────────────────────────┐
845
+ │ { │
846
+ │ firstStep: { │
847
+ │ stepId: "requirements_analysis", │
848
+ │ agent: "analyst", │
849
+ │ command: "/analyst", │
850
+ │ prompt: "执行需求分析..." │
851
+ │ } │
852
+ │ } │
853
+ └──────────────────┬───────────────────────────────┘
854
+
855
+
856
+ 5. workflow-helper执行第一步
857
+ ┌──────────────────────────────────────────────────┐
858
+ │ - 切换到 Analyst 智能体 │
859
+ │ - 执行需求分析 │
860
+ │ - 生成 docs/requirements/requirements-analysis.md│
861
+ └──────────────────┬───────────────────────────────┘
862
+
863
+
864
+ 6. workflow-helper报告步骤完成
865
+ ┌──────────────────────────────────────────────────┐
866
+ │ POST http://localhost:3001/workflow/step-complete│
867
+ │ 请求体: { │
868
+ │ stepId: "requirements_analysis", │
869
+ │ status: "success", │
870
+ │ outputs: [{ file: "docs/...", exists: true }] │
871
+ │ } │
872
+ └──────────────────┬───────────────────────────────┘
873
+
874
+
875
+ 7. 协调器决策下一步
876
+ ┌──────────────────────────────────────────────────┐
877
+ │ - 验证步骤1输出质量 │
878
+ │ - 更新状态 │
879
+ │ - 返回步骤2指令 │
880
+ │ { │
881
+ │ nextStep: { │
882
+ │ stepId: "analyze_architecture", │
883
+ │ agent: "architect", │
884
+ │ command: "/architect", │
885
+ │ prompt: "分析架构..." │
886
+ │ } │
887
+ │ } │
888
+ └──────────────────┬───────────────────────────────┘
889
+
890
+
891
+ 8. workflow-helper自动执行步骤2
892
+ ┌──────────────────────────────────────────────────┐
893
+ │ - 不询问用户,直接执行 │
894
+ │ - 切换到 Architect 智能体 │
895
+ │ - 执行架构分析 │
896
+ │ - 生成架构文档 │
897
+ └──────────────────┬───────────────────────────────┘
898
+
899
+
900
+ 9. 循环执行步骤3-6
901
+ ┌──────────────────────────────────────────────────┐
902
+ │ PM 创建PRD → PM 拆分Epic → Architect 设计架构 │
903
+ └──────────────────┬───────────────────────────────┘
904
+
905
+
906
+ 10. 工作流完成
907
+ ┌──────────────────────────────────────────────────┐
908
+ │ 协调器返回: { hasNextStep: false } │
909
+ │ workflow-helper显示: 🎉 工作流执行完成! │
910
+ └──────────────────────────────────────────────────┘
911
+ ```
912
+
913
+ ### 4.2 用户操作步骤
914
+
915
+ ```bash
916
+ # 终端1: 启动协调器
917
+ cd tools/workflow-coordinator
918
+ node src/index.js start requirements-analysis
919
+
920
+ # 输出:
921
+ # ✅ 工作流解析完成: 自动化需求分析和架构设计流程
922
+ # ✅ HTTP服务已启动: http://localhost:3001
923
+ # ⏳ 等待Claude Code连接...
924
+
925
+ # 终端2: Claude Code
926
+ # 打开Claude Code,切换到项目目录,执行:
927
+ /workflow-helper
928
+ *start-workflow requirements-analysis
929
+
930
+ # 协调器会自动驱动整个流程:
931
+ # ✅ 步骤 1/6: Analyst 需求分析 (预计15-25分钟)
932
+ # → 自动进入下一步骤...
933
+ # ✅ 步骤 2/6: Architect 架构分析 (预计10-20分钟)
934
+ # → 自动进入下一步骤...
935
+ # ✅ 步骤 3/6: PM 创建 PRD (预计20-30分钟)
936
+ # → 自动进入下一步骤...
937
+ # ✅ 步骤 4/6: PM 拆分史诗 (预计变动)
938
+ # → 自动进入下一步骤...
939
+ # ✅ 步骤 5/6: Architect 架构设计 (预计30-40分钟)
940
+ # → 自动进入下一步骤...
941
+ # ✅ 步骤 6/6: 生成完成报告
942
+ # 🎉 工作流执行完成!
943
+ ```
944
+
945
+ ---
946
+
947
+ ## 5. 技术架构
948
+
949
+ ### 5.1 协调器技术栈
950
+
951
+ **编程语言**: Node.js (JavaScript)
952
+
953
+ **核心依赖**:
954
+ ```json
955
+ {
956
+ "dependencies": {
957
+ "express": "^4.18.0", // HTTP服务器
958
+ "js-yaml": "^4.1.0", // YAML解析
959
+ "fs-extra": "^11.0.0", // 文件系统增强
960
+ "chalk": "^5.0.0", // 彩色输出
961
+ "dotenv": "^16.0.0" // 环境变量
962
+ },
963
+ "devDependencies": {
964
+ "jest": "^29.0.0", // 测试
965
+ "nodemon": "^3.0.0" // 开发热重载
966
+ }
967
+ }
968
+ ```
969
+
970
+ ### 5.2 Claude Code集成
971
+
972
+ **方式1: workflow-helper智能体**
973
+ - 新增智能体定义文件
974
+ - 使用 fetch API 调用协调器
975
+ - 自动切换智能体和执行命令
976
+
977
+ **方式2: MCP工具(可选)**
978
+ - 开发MCP Server
979
+ - 提供工具: `start_workflow`, `report_complete`
980
+ - Claude Code通过MCP协议调用
981
+
982
+ ---
983
+
984
+ ## 6. 开发计划
985
+
986
+ ### 6.1 阶段1: 协调器MVP (2-3周)
987
+
988
+ **目标**: 实现基础的协调器功能
989
+
990
+ **任务**:
991
+ 1. 工作流YAML解析
992
+ 2. HTTP服务器和API端点
993
+ 3. 步骤流程控制逻辑
994
+ 4. 状态持久化
995
+
996
+ **验收**:
997
+ - ✅ 能解析现有工作流YAML
998
+ - ✅ HTTP API正常工作
999
+ - ✅ 能正确返回下一步指令
1000
+
1001
+ ---
1002
+
1003
+ ### 6.2 阶段2: Claude Code集成 (2-3周)
1004
+
1005
+ **目标**: 实现workflow-helper智能体
1006
+
1007
+ **任务**:
1008
+ 1. 创建workflow-helper智能体定义
1009
+ 2. 实现HTTP API调用逻辑
1010
+ 3. 实现智能体切换和命令执行
1011
+ 4. 实现步骤结果收集和报告
1012
+
1013
+ **验收**:
1014
+ - ✅ workflow-helper能调用协调器API
1015
+ - ✅ 能自动切换智能体
1016
+ - ✅ 能报告步骤完成
1017
+
1018
+ ---
1019
+
1020
+ ### 6.3 阶段3: 端到端测试 (1-2周)
1021
+
1022
+ **目标**: 完整执行需求分析工作流
1023
+
1024
+ **任务**:
1025
+ 1. 端到端集成测试
1026
+ 2. 错误处理和重试机制
1027
+ 3. 质量门控验证
1028
+ 4. 用户体验优化
1029
+
1030
+ **验收**:
1031
+ - ✅ 能完整执行requirements-analysis工作流
1032
+ - ✅ 全程自动化,无需人工干预
1033
+ - ✅ 生成所有预期文档
1034
+
1035
+ ---
1036
+
1037
+ ### 6.4 阶段4: 增强功能 (1-2周)
1038
+
1039
+ **目标**: 添加高级功能
1040
+
1041
+ **任务**:
1042
+ 1. MCP集成(可选)
1043
+ 2. 进度监控和可视化
1044
+ 3. 工作流恢复功能
1045
+ 4. 文档和示例
1046
+
1047
+ **验收**:
1048
+ - ✅ 支持中断恢复
1049
+ - ✅ 实时进度监控
1050
+ - ✅ 文档完善
1051
+
1052
+ ---
1053
+
1054
+ ## 7. 验收标准
1055
+
1056
+ ### 7.1 核心功能验收
1057
+
1058
+ #### 场景1: 完整执行需求分析工作流
1059
+
1060
+ **前置条件**:
1061
+ - 协调器已启动
1062
+ - Claude Code中workflow-helper已激活
1063
+ - docs/req.txt文件存在
1064
+
1065
+ **执行**:
1066
+ ```bash
1067
+ # 在Claude Code中:
1068
+ /workflow-helper
1069
+ *start-workflow requirements-analysis
1070
+ ```
1071
+
1072
+ **预期结果**:
1073
+ - ✅ 协调器成功启动并返回第一步指令
1074
+ - ✅ workflow-helper自动执行所有6个步骤
1075
+ - ✅ 步骤间无需人工确认,自动连续执行
1076
+ - ✅ 生成所有预期文档:
1077
+ - docs/requirements/requirements-analysis.md
1078
+ - docs/architecture/current-architecture-analysis.md
1079
+ - docs/prd/brownfield-iteration-prd.md
1080
+ - docs/epics/史诗-*.md
1081
+ - docs/architecture/iteration-backend-design.md
1082
+ - docs/architecture/db-migration-scripts.sql
1083
+ - ✅ 总耗时 ≤ 3小时
1084
+
1085
+ ---
1086
+
1087
+ #### 场景2: 工作流中断恢复
1088
+
1089
+ **执行**:
1090
+ 1. 启动工作流
1091
+ 2. 在步骤3完成后手动中止
1092
+ 3. 重新启动: `*resume-workflow`
1093
+
1094
+ **预期结果**:
1095
+ - ✅ 协调器能检测到未完成的工作流
1096
+ - ✅ 验证已完成步骤的输出完整性
1097
+ - ✅ 从步骤4继续执行
1098
+ - ✅ 成功完成剩余步骤
1099
+
1100
+ ---
1101
+
1102
+ #### 场景3: 步骤失败和重试
1103
+
1104
+ **执行**:
1105
+ 模拟步骤执行失败(如文件写入失败)
1106
+
1107
+ **预期结果**:
1108
+ - ✅ workflow-helper报告失败
1109
+ - ✅ 协调器决策重试
1110
+ - ✅ 自动重试(最多3次)
1111
+ - ✅ 重试成功后继续下一步
1112
+
1113
+ ---
1114
+
1115
+ ### 7.2 非功能验收
1116
+
1117
+ - ✅ 协调器启动时间 ≤ 3秒
1118
+ - ✅ API响应时间 ≤ 100ms
1119
+ - ✅ 状态保存时间 ≤ 50ms
1120
+ - ✅ HTTP服务稳定性: 无崩溃
1121
+ - ✅ 内存占用 ≤ 100MB
1122
+
1123
+ ---
1124
+
1125
+ ## 8. 风险和缓解
1126
+
1127
+ ### 8.1 技术风险
1128
+
1129
+ #### 风险1: Claude Code与协调器通信不稳定
1130
+
1131
+ **影响**: 步骤完成无法及时报告,工作流阻塞
1132
+
1133
+ **缓解措施**:
1134
+ 1. 实现HTTP + 文件系统双通道通信
1135
+ 2. 添加心跳机制
1136
+ 3. 超时自动重试
1137
+
1138
+ #### 风险2: 智能体切换失败
1139
+
1140
+ **影响**: 无法执行下一步
1141
+
1142
+ **缓解措施**:
1143
+ 1. 验证智能体是否存在
1144
+ 2. 提供降级方案(使用当前智能体)
1145
+ 3. 详细的错误日志
1146
+
1147
+ ---
1148
+
1149
+ ### 8.2 集成风险
1150
+
1151
+ #### 风险3: Claude Code API限制
1152
+
1153
+ **影响**: 无法实现某些功能
1154
+
1155
+ **缓解措施**:
1156
+ 1. 使用多种通信方式
1157
+ 2. 文件系统作为备用方案
1158
+ 3. 与Claude Code团队沟通
1159
+
1160
+ ---
1161
+
1162
+ ## 9. 后续计划
1163
+
1164
+ ### 9.1 短期(3个月内)
1165
+
1166
+ - ✅ 完成协调器MVP
1167
+ - ✅ 完成Claude Code集成
1168
+ - ✅ 支持requirements-analysis工作流
1169
+ - ✅ 支持story-development工作流
1170
+
1171
+ ### 9.2 中期(6个月内)
1172
+
1173
+ - 🔄 支持自定义工作流
1174
+ - 🔄 可视化进度监控
1175
+ - 🔄 Web界面管理
1176
+ - 🔄 多项目并行执行
1177
+
1178
+ ### 9.3 长期(1年内)
1179
+
1180
+ - 🔄 AI驱动的智能协调
1181
+ - 🔄 工作流模板市场
1182
+ - 🔄 团队协作功能
1183
+ - 🔄 云端托管服务
1184
+
1185
+ ---
1186
+
1187
+ ## 附录
1188
+
1189
+ ### A. API完整规范
1190
+
1191
+ 见第2.2节"通信协议设计"
1192
+
1193
+ ### B. workflow-helper智能体完整定义
1194
+
1195
+ 见第3.2节"F6: workflow-helper智能体"
1196
+
1197
+ ### C. 错误代码表
1198
+
1199
+ ```
1200
+ E1001: 工作流文件未找到
1201
+ E1002: 工作流定义格式错误
1202
+ E1003: 步骤执行失败
1203
+ E1004: 输出文件验证失败
1204
+ E1005: 协调器API调用失败
1205
+ E1006: 状态文件损坏
1206
+ E1007: 智能体切换失败
1207
+ ```
1208
+
1209
+ ---
1210
+
1211
+ **文档状态**: Draft
1212
+ **版本**: 2.0.0
1213
+ **最后更新**: 2025-11-13
1214
+ **下次审查**: 待定