maestro-flow 0.4.16 → 0.4.18

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 (105) hide show
  1. package/.agents/skills/maestro/SKILL.md +1 -1
  2. package/.agents/skills/maestro-analyze/SKILL.md +5 -0
  3. package/.agents/skills/maestro-blueprint/SKILL.md +5 -0
  4. package/.agents/skills/maestro-brainstorm/SKILL.md +5 -0
  5. package/.agents/skills/maestro-init/SKILL.md +1 -1
  6. package/.agents/skills/maestro-next/SKILL.md +219 -0
  7. package/.agents/skills/maestro-ralph-beta/SKILL.md +893 -0
  8. package/.agy/skills/maestro/SKILL.md +1 -1
  9. package/.agy/skills/maestro-analyze/SKILL.md +5 -0
  10. package/.agy/skills/maestro-blueprint/SKILL.md +5 -0
  11. package/.agy/skills/maestro-brainstorm/SKILL.md +5 -0
  12. package/.agy/skills/maestro-init/SKILL.md +1 -1
  13. package/.agy/skills/maestro-next/SKILL.md +215 -0
  14. package/.agy/skills/maestro-ralph-beta/SKILL.md +889 -0
  15. package/.claude/commands/maestro-analyze.md +5 -0
  16. package/.claude/commands/maestro-blueprint.md +5 -0
  17. package/.claude/commands/maestro-brainstorm.md +5 -0
  18. package/.claude/commands/maestro-init.md +1 -1
  19. package/.claude/commands/maestro-next.md +217 -0
  20. package/.claude/commands/maestro-ralph-beta.md +891 -0
  21. package/.claude/commands/maestro.md +1 -1
  22. package/.codex/skills/learn-decompose/SKILL.md +34 -3
  23. package/.codex/skills/learn-retro/SKILL.md +31 -1
  24. package/.codex/skills/learn-second-opinion/SKILL.md +34 -4
  25. package/.codex/skills/maestro-analyze/SKILL.md +44 -5
  26. package/.codex/skills/maestro-blueprint/SKILL.md +5 -0
  27. package/.codex/skills/maestro-brainstorm/SKILL.md +46 -0
  28. package/.codex/skills/maestro-execute/SKILL.md +61 -5
  29. package/.codex/skills/maestro-milestone-audit/SKILL.md +64 -13
  30. package/.codex/skills/maestro-milestone-complete/SKILL.md +12 -0
  31. package/.codex/skills/maestro-plan/SKILL.md +36 -1
  32. package/.codex/skills/maestro-player/SKILL.md +25 -6
  33. package/.codex/skills/maestro-ralph/SKILL.md +108 -81
  34. package/.codex/skills/maestro-ralph-beta/SKILL.md +891 -0
  35. package/.codex/skills/maestro-ralph-execute/SKILL.md +244 -0
  36. package/.codex/skills/maestro-roadmap/SKILL.md +35 -4
  37. package/.codex/skills/maestro-ui-codify/SKILL.md +38 -10
  38. package/.codex/skills/maestro-verify/SKILL.md +40 -5
  39. package/.codex/skills/manage-codebase-rebuild/SKILL.md +52 -5
  40. package/.codex/skills/manage-issue-discover/SKILL.md +106 -15
  41. package/.codex/skills/quality-auto-test/SKILL.md +70 -16
  42. package/.codex/skills/quality-debug/SKILL.md +139 -28
  43. package/.codex/skills/quality-refactor/SKILL.md +61 -11
  44. package/.codex/skills/quality-review/SKILL.md +45 -9
  45. package/.codex/skills/quality-test/SKILL.md +58 -3
  46. package/.codex/skills/security-audit/SKILL.md +38 -0
  47. package/.codex/skills/spec-map/SKILL.md +65 -8
  48. package/.codex/skills/team-coordinate/SKILL.md +28 -11
  49. package/.codex/skills/team-coordinate/specs/role-catalog.md +20 -0
  50. package/.codex/skills/team-lifecycle-v4/SKILL.md +23 -7
  51. package/.codex/skills/team-lifecycle-v4/instructions/agent-instruction.md +20 -0
  52. package/.codex/skills/team-quality-assurance/SKILL.md +40 -2
  53. package/.codex/skills/team-review/SKILL.md +42 -2
  54. package/.codex/skills/team-tech-debt/SKILL.md +45 -2
  55. package/.codex/skills/team-testing/SKILL.md +42 -2
  56. package/dashboard/dist-server/dashboard/src/server/wiki/search.d.ts +6 -4
  57. package/dashboard/dist-server/dashboard/src/server/wiki/search.js +50 -8
  58. package/dashboard/dist-server/dashboard/src/server/wiki/search.js.map +1 -1
  59. package/dashboard/dist-server/dashboard/src/server/wiki/virtual-wiki-adapters.d.ts +32 -0
  60. package/dashboard/dist-server/dashboard/src/server/wiki/virtual-wiki-adapters.js +294 -0
  61. package/dashboard/dist-server/dashboard/src/server/wiki/virtual-wiki-adapters.js.map +1 -1
  62. package/dashboard/dist-server/dashboard/src/server/wiki/wiki-indexer.d.ts +1 -0
  63. package/dashboard/dist-server/dashboard/src/server/wiki/wiki-indexer.js +35 -1
  64. package/dashboard/dist-server/dashboard/src/server/wiki/wiki-indexer.js.map +1 -1
  65. package/dashboard/dist-server/dashboard/src/server/wiki/wiki-indexer.test.js +235 -0
  66. package/dashboard/dist-server/dashboard/src/server/wiki/wiki-indexer.test.js.map +1 -1
  67. package/dist/src/commands/install-backend.d.ts.map +1 -1
  68. package/dist/src/commands/install-backend.js +23 -4
  69. package/dist/src/commands/install-backend.js.map +1 -1
  70. package/dist/src/commands/ralph.d.ts.map +1 -1
  71. package/dist/src/commands/ralph.js +3 -1
  72. package/dist/src/commands/ralph.js.map +1 -1
  73. package/dist/src/ralph/cmd-check.js +1 -1
  74. package/dist/src/ralph/cmd-check.js.map +1 -1
  75. package/dist/src/ralph/cmd-complete.js +1 -1
  76. package/dist/src/ralph/cmd-complete.js.map +1 -1
  77. package/dist/src/ralph/cmd-next.d.ts.map +1 -1
  78. package/dist/src/ralph/cmd-next.js +56 -5
  79. package/dist/src/ralph/cmd-next.js.map +1 -1
  80. package/dist/src/ralph/cmd-session.js +2 -2
  81. package/dist/src/ralph/cmd-session.js.map +1 -1
  82. package/dist/src/ralph/cmd-skills.d.ts +2 -0
  83. package/dist/src/ralph/cmd-skills.d.ts.map +1 -1
  84. package/dist/src/ralph/cmd-skills.js +11 -4
  85. package/dist/src/ralph/cmd-skills.js.map +1 -1
  86. package/dist/src/ralph/skill-scanner.d.ts +7 -2
  87. package/dist/src/ralph/skill-scanner.d.ts.map +1 -1
  88. package/dist/src/ralph/skill-scanner.js +39 -24
  89. package/dist/src/ralph/skill-scanner.js.map +1 -1
  90. package/dist/src/ralph/status-schema.d.ts +2 -0
  91. package/dist/src/ralph/status-schema.d.ts.map +1 -1
  92. package/dist/src/ralph/status-store.d.ts +8 -1
  93. package/dist/src/ralph/status-store.d.ts.map +1 -1
  94. package/dist/src/ralph/status-store.js +12 -2
  95. package/dist/src/ralph/status-store.js.map +1 -1
  96. package/dist/src/tools/store-knowhow.d.ts.map +1 -1
  97. package/dist/src/tools/store-knowhow.js +51 -64
  98. package/dist/src/tools/store-knowhow.js.map +1 -1
  99. package/dist/src/utils/update-notices.js +12 -0
  100. package/dist/src/utils/update-notices.js.map +1 -1
  101. package/package.json +1 -1
  102. package/templates/config.json +21 -33
  103. package/workflows/finish-work.md +119 -0
  104. package/workflows/init.md +11 -11
  105. package/workflows/milestone-complete.md +23 -1
@@ -0,0 +1,893 @@
1
+ ---
2
+ name: maestro-ralph-beta
3
+ description: Self-running loop controller for adaptive maestro workflow — build, tick, decide in one skill
4
+ argument-hint: "<intent> [-y] | continue | status"
5
+ allowed-tools:
6
+ - read_file
7
+ - write_file
8
+ - edit_file
9
+ - shell
10
+ - find_files
11
+ - search
12
+ - invoke_skill
13
+ - ask_user
14
+ ---
15
+ <!-- Open-standard mirror generated by scripts/build-agents-standard.mjs — do not edit; re-run after editing .claude/ source. -->
16
+
17
+ <purpose>
18
+ Closed-loop runner for the maestro workflow lifecycle.
19
+ Single skill — every invocation routes by session state, executes one tick, and self-invokes `invoke_skill("maestro-ralph-beta")` until all `completion_confirmed` or paused.
20
+
21
+ Entry points:
22
+ - **`/maestro-ralph-beta "intent"`** — New session: infer → decompose → build → tick
23
+ - **`/maestro-ralph-beta continue`** — Resume: locate session → tick
24
+ - **`/maestro-ralph-beta status`** — Display session progress
25
+
26
+ Tick kinds:
27
+ - **执行 step** (`step.decision == null`): `maestro ralph next` → inline → `maestro ralph complete` → self-invoke
28
+ - **decision step** (`step.decision != null`): inline evaluate → apply verdict → self-invoke
29
+
30
+ Session: `.workflow/.maestro/ralph-{YYYYMMDD-HHmmss}/status.json`
31
+ </purpose>
32
+
33
+ <context>
34
+ $ARGUMENTS — intent text, flags, or keywords.
35
+
36
+ **Parse:**
37
+ ```
38
+ -y flag → auto_confirm = true
39
+ .md/.txt path → input_doc (supplementary context only, NEVER substitutes lifecycle stages)
40
+ "status" → status mode
41
+ "continue" → resume mode
42
+ Remaining → intent (new session)
43
+ ```
44
+
45
+ **State files:**
46
+ - `.workflow/state.json` — artifact registry, milestones, phases
47
+ - `.workflow/roadmap.md` — milestone/phase structure
48
+ - `.workflow/.maestro/ralph-*/status.json` — ralph session state
49
+ </context>
50
+
51
+ <invariants>
52
+ 1. **Self-invocation = `invoke_skill("maestro-ralph-beta")`** — 每次 tick 末尾强制自调用;除非 router 命中终止条件
53
+ 2. **status.json 是唯一真源;写入权限分层**:
54
+ - **Step 级字段**(`step.completion_*`, `step.status` 执行 step running↔completed, `step.load.*`, `step.retried`,以及执行 step 的 `active_step_index` 占用/释放)→ 由 `maestro ralph next/complete/retry` CLI 写入
55
+ - **会话级结构**(`session.status`, `passed_gates`, `steps[]` 增删/reindex, `task_decomposition[*]`, `boundary_contract`, `context.*`, `scope_verdict`, `consec_exit2_count`, decision step 的 `status`/`retry_count`/`active_step_index` 占用与释放)→ 由 maestro-ralph-beta 写入
56
+ 3. **执行 step 通过 `maestro ralph next` 加载** — CLI 解析 frontmatter + `<required_reading>` + `<deferred_reading>`、读 required 全文、拼 prompt、写 `step.load.*` + `active_step_index` + `step.status="running"`
57
+ 4. **decision step 内联评估** — 不 handoff、不调 ralph next;按 `step.decision` 分派 A_DECISION_*
58
+ 5. **每个 step 必须 `completion_confirmed: true`** — 由 `maestro ralph complete N --status DONE|DONE_WITH_CONCERNS` 写入;STATUS 仅 `DONE | DONE_WITH_CONCERNS | NEEDS_RETRY | BLOCKED`
59
+ 6. **command_path 在 A_BUILD_STEPS 解析** — 通过 `maestro ralph skills --platform claude --json --quiet` 预校验(project 覆盖 global,只扫描 `.claude/commands/`);未命中标 `command_scope = "missing"`
60
+ 7. **required reading 由 CLI 加载** — 缺失 → 退出码 1(E007)→ pause session;ralph build 阶段不读 .md 内容
61
+ 8. **active_step_index 一致性由 CLI 维护** — 同一 session 同时最多一个 step 持有;E008/E009 直接退出
62
+ 9. **Decomposition is outcome-oriented** — sub-goals 为可观测交付,禁止 lifecycle 复刻;`/goal` 由用户输入
63
+ 10. **planning_mode governs arg granularity** — `unified` → skill args 无 `{phase}`;`independent` → 含 `{phase}`
64
+ 11. **task_decomposition 驱动 steps[] 动态生长** — `post-goal-audit` 按 unmet 子目标插入 scoped mini-loop;字段累加,既有字段不删不改
65
+ </invariants>
66
+
67
+ <router>
68
+
69
+ 每次进入 skill 先执行 router,按顺序匹配,先命中先用。术语:
70
+ - **active session** = `.workflow/.maestro/ralph-*/status.json` 中 `status ∈ {running, paused}` 的最新会话
71
+ - **live session** = active session 且 `status == "running"`
72
+ - **active_step** = `session.steps[session.active_step_index]`
73
+
74
+ ```
75
+ 1. intent == "status" → S_STATUS → END
76
+ 2. intent == "continue" AND active session exists → A_RESUME_SESSION → S_TICK_LOCATE
77
+ 3. intent non-empty AND intent ∉ {"continue","status"} AND active session exists
78
+ → S_FALLBACK → END
79
+ display "已有 active session {id};先 /maestro-ralph-beta continue 续跑或显式 abandon"
80
+ 4. live session AND active_step.status == "running" AND active_step.decision != null
81
+ → S_TICK_LOCATE → S_TICK_DECISION
82
+ 5. live session AND has pending step → S_TICK_LOCATE
83
+ 6. live session AND all completion_confirmed → S_COMPLETE → END
84
+ 7. active session AND session.status == "paused" AND no intent → S_FALLBACK → END
85
+ display "Session {id} paused;输入 /maestro-ralph-beta continue 显式恢复"
86
+ 8. no active session AND intent non-empty → S_BUILD_PHASE
87
+ 9. no active session AND no intent → S_FALLBACK → END
88
+ ```
89
+
90
+ </router>
91
+
92
+ <state_machine>
93
+
94
+ <states>
95
+ # Build phase (one-time per session)
96
+ S_RESOLVE_PHASE — 解析 phase + phase_is_new + D-007 milestone PERSIST: session.phase, session.phase_is_new, session.milestone
97
+ S_INFER — 推断 lifecycle_position PERSIST: session.lifecycle_position
98
+ S_RESOLVE_SCOPE — 读 macro analyze conclusions.scope_verdict PERSIST: session.scope_verdict, session.analyze_macro_id
99
+ S_QUALITY_MODE — 决定质量管线模式 PERSIST: session.quality_mode
100
+ S_PLANNING_MODE — 决定统一/独立规划模式 PERSIST: session.planning_mode
101
+ S_DECOMPOSE — 边界澄清、写执行准则+子目标清单 PERSIST: session.boundary_contract, .execution_criteria, .task_decomposition
102
+ S_BUILD_CHAIN — 构建步骤链 PERSIST: session.steps[]
103
+ S_CREATE_SESSION — 写 status.json PERSIST: session (全量)
104
+ S_CONFIRM — 用户确认 PERSIST: —
105
+
106
+ # Tick phase (per step)
107
+ S_TICK_LOCATE — 定位 session + 找 active step PERSIST: —
108
+ S_TICK — 分派执行 step 或 decision step PERSIST: step.status, active_step_index
109
+ S_TICK_EXEC — 执行 step:ralph next → inline → ralph complete PERSIST: via CLI
110
+ S_TICK_DECISION — decision step:内联评估 + 应用裁决 PERSIST: session.steps[], passed_gates, decisions.ndjson
111
+ S_HANDLE_FAIL — 处理执行失败 PERSIST: step.status, session.status
112
+
113
+ # Terminal
114
+ S_STATUS — 显示 session 进度 PERSIST: —
115
+ S_COMPLETE — 收尾 PERSIST: session.status = "completed"
116
+ S_FALLBACK — 引导用户输入或退出 PERSIST: —
117
+ </states>
118
+
119
+ <transitions>
120
+
121
+ # === Build phase ===
122
+
123
+ S_BUILD_PHASE (entry):
124
+ → S_RESOLVE_PHASE
125
+
126
+ S_RESOLVE_PHASE:
127
+ → S_INFER WHEN: phase resolved or null DO: A_RESOLVE_PHASE
128
+ → S_FALLBACK WHEN: ambiguous
129
+ GUARD: auto_confirm does NOT skip phase ambiguity
130
+
131
+ S_INFER:
132
+ → S_RESOLVE_SCOPE WHEN: position resolved DO: A_INFER_POSITION
133
+ → S_FALLBACK WHEN: cannot infer
134
+
135
+ S_RESOLVE_SCOPE:
136
+ → S_QUALITY_MODE DO: A_RESOLVE_SCOPE_VERDICT
137
+ GUARD: position ∈ {brainstorm, blueprint, init} → skip (scope_verdict = null)
138
+
139
+ S_QUALITY_MODE:
140
+ → S_PLANNING_MODE DO: A_DETERMINE_QUALITY_MODE
141
+
142
+ S_PLANNING_MODE:
143
+ → S_DECOMPOSE DO: A_DETERMINE_PLANNING_MODE
144
+ GUARD: lifecycle_position ∈ {brainstorm, blueprint, init, analyze-macro, roadmap} → skip (force independent)
145
+
146
+ S_DECOMPOSE:
147
+ → S_BUILD_CHAIN DO: A_DECOMPOSE_TASKS
148
+ GUARD: broad intent → MUST clarify boundary even if auto_confirm
149
+ GUARD: narrow intent → auto-derive, skip questions
150
+ GUARD: position ∈ {brainstorm, blueprint, init} → skip decomposition
151
+
152
+ S_BUILD_CHAIN:
153
+ → S_CREATE_SESSION DO: A_BUILD_STEPS
154
+
155
+ S_CREATE_SESSION:
156
+ → S_CONFIRM WHEN: not auto_confirm DO: A_CREATE_SESSION
157
+ → S_TICK_LOCATE WHEN: auto_confirm DO: A_CREATE_SESSION + invoke_skill("maestro-ralph-beta")
158
+
159
+ S_CONFIRM:
160
+ → S_TICK_LOCATE WHEN: user selects "Proceed" DO: invoke_skill("maestro-ralph-beta")
161
+ → S_BUILD_CHAIN WHEN: user selects "Edit"
162
+ → END WHEN: user selects "Cancel"
163
+
164
+ # === Tick phase ===
165
+
166
+ S_TICK_LOCATE: Entry: A_LOCATE_SESSION
167
+ → S_TICK WHEN: next_pending_step != null
168
+ → S_COMPLETE WHEN: next_pending_step == null
169
+ → S_FALLBACK WHEN: no active session
170
+
171
+ S_TICK:
172
+ → S_TICK_DECISION WHEN: next_pending_step.decision != null DO: A_CLAIM_DECISION
173
+ → S_TICK_EXEC WHEN: next_pending_step.decision == null DO: A_RESOLVE_ARGS
174
+
175
+ S_TICK_EXEC: Entry: A_EXEC_STEP
176
+ → S_TICK_LOCATE WHEN: ralph complete with DONE|DONE_WITH_CONCERNS DO: invoke_skill("maestro-ralph-beta")
177
+ → S_TICK_LOCATE WHEN: ralph next exit == 2 DO: invoke_skill("maestro-ralph-beta")
178
+ → S_HANDLE_FAIL WHEN: ralph next exit == 1 OR exit >= 3
179
+ → S_HANDLE_FAIL WHEN: ralph complete with NEEDS_RETRY|BLOCKED
180
+
181
+ S_TICK_DECISION: (gate 名取自 `step.decision`)
182
+ → S_TICK_APPLY WHEN: quality-gate (post-verify, post-business-test, post-review, post-test)
183
+ DO: A_DELEGATE_EVALUATE
184
+ → S_TICK_APPLY WHEN: goal-gate (post-goal-audit)
185
+ DO: A_GOAL_AUDIT_EVALUATE
186
+ → S_TICK_APPLY WHEN: scope-gate (post-analyze-scope)
187
+ DO: A_SCOPE_EVALUATE
188
+ → S_TICK_APPLY WHEN: structural (post-milestone, post-debug-escalate)
189
+ DO: A_STRUCTURAL_EVALUATE
190
+
191
+ S_TICK_APPLY:
192
+ → S_TICK_LOCATE WHEN: verdict == "proceed" DO: A_APPLY_PROCEED + invoke_skill("maestro-ralph-beta")
193
+ → S_TICK_LOCATE WHEN: post-goal-audit + unmet sub-goals DO: A_APPLY_GOAL_FIX + invoke_skill("maestro-ralph-beta")
194
+ → S_TICK_LOCATE WHEN: post-goal-audit + all sub-goals met DO: A_APPLY_GOAL_DONE + invoke_skill("maestro-ralph-beta")
195
+ → S_TICK_LOCATE WHEN: post-analyze-scope DO: A_APPLY_SCOPE_VERDICT + invoke_skill("maestro-ralph-beta")
196
+ → S_TICK_LOCATE WHEN: verdict == "fix" DO: A_APPLY_FIX + invoke_skill("maestro-ralph-beta")
197
+ → S_TICK_LOCATE WHEN: verdict == "escalate" DO: A_APPLY_ESCALATE + invoke_skill("maestro-ralph-beta")
198
+ → S_TICK_LOCATE WHEN: post-milestone + standard + next milestone DO: A_ADVANCE_MILESTONE + invoke_skill("maestro-ralph-beta")
199
+ → END WHEN: post-milestone + standard + no next milestone DO: mark completed
200
+ → END WHEN: post-milestone + adhoc DO: mark completed (adhoc self-contained)
201
+ → END WHEN: post-debug-escalate (always STOP) DO: A_PAUSE_ESCALATE
202
+ GUARD: retry_count >= max_retries → force escalate
203
+ GUARD: confidence_score < 60 AND proceed → override to fix
204
+ GUARD: confidence_score > 95 AND fix AND retry > 0 → suggest proceed
205
+ GUARD: auto_confirm → skip user prompt, apply adjusted verdict
206
+ GUARD: not auto_confirm → ask_user with override options
207
+
208
+ S_HANDLE_FAIL:
209
+ → S_TICK_LOCATE WHEN: auto + not retried DO: A_RETRY + invoke_skill("maestro-ralph-beta")
210
+ → END WHEN: auto + retried DO: A_PAUSE_SESSION
211
+ → S_TICK_LOCATE WHEN: interactive + user selects retry DO: A_RETRY + invoke_skill("maestro-ralph-beta")
212
+ → S_TICK_LOCATE WHEN: interactive + user selects skip DO: A_SKIP_STEP + invoke_skill("maestro-ralph-beta")
213
+ → END WHEN: interactive + user selects abort DO: A_PAUSE_SESSION
214
+
215
+ # === Terminal ===
216
+
217
+ S_STATUS:
218
+ → END DO: A_SHOW_STATUS
219
+
220
+ S_COMPLETE:
221
+ → END DO: A_COMPLETE_SESSION
222
+
223
+ S_FALLBACK:
224
+ → S_BUILD_PHASE WHEN: user provides intent (no active session) DO: ask_user
225
+ → S_TICK_LOCATE WHEN: user selects "continue active session" DO: A_RESUME_SESSION + invoke_skill("maestro-ralph-beta")
226
+ → END WHEN: user cancels OR no active session for resume
227
+
228
+ </transitions>
229
+
230
+ <actions>
231
+
232
+ ### A_SHOW_STATUS
233
+
234
+ 1. Find latest ralph session (by created_at)
235
+ 2. Display: Session, Status, Position, Progress, Current step
236
+ 3. List steps: [✓] completion_confirmed, [▸] current, [ ] pending, [◆] decision(`step.decision` 非空);执行 step 附 `command_scope`(global/project) + `command_path`
237
+ 4. If `task_decomposition` present (absent → skip):
238
+ ```
239
+ Sub-goals ({done}/{total}) source: {session_dir}/status.json#/task_decomposition
240
+ [x] G1 done_when={done_when} evidence={evidence} confirmed={completion_confirmed}
241
+ [ ] G2 done_when={done_when} evidence={evidence} confirmed=false ◀ unmet
242
+ ```
243
+
244
+ ### A_RESOLVE_PHASE
245
+
246
+ 产出 `phase` + `phase_is_new` + `milestone`(D-007 反查)。
247
+
248
+ **Priority:**
249
+
250
+ | Step | 行为 | phase_is_new |
251
+ |------|------|--------------|
252
+ | 1 | intent 匹配 `phase\s*(\d+)` → 取 state.json 对应 phase | false |
253
+ | 2 | intent 派生短语 → 在 `state.json.milestones[*].phase_slugs` / `artifacts[*].path` 查找 | false (匹配) / true (无匹配) |
254
+ | 3 | 未派生 → 取最新 in-progress artifact 的 phase | false |
255
+ | 4 | 仍无 → state.json 首个 incomplete phase | false |
256
+ | 5 | position 将是 brainstorm/blueprint/init/roadmap/analyze-macro → phase = null | n/a |
257
+ | 6 | 仍模糊 → `ask_user` | 由用户回答确定 |
258
+
259
+ **D-007 Phase→Milestone 反查**(数字 phase 已解析时):
260
+ ```
261
+ resolve_milestone(phase_number):
262
+ for ms in state.json.milestones:
263
+ if str(phase_number) in ms.phase_slugs: return ms.id
264
+ return state.json.current_milestone # fallback
265
+ ```
266
+ 写入 `session.milestone`。
267
+
268
+ **写入 session**: `phase`, `phase_is_new`, `milestone`。
269
+
270
+ **新派生 phase 时 milestone 处理**:
271
+ - state.json 当前 milestone 仍 active → 沿用,新增 phase
272
+ - intent 派生新 milestone 名 → 写入 session 仅作标签;`state.json.milestones` 由 `maestro-roadmap` / `maestro-milestone-release` 创建
273
+
274
+ ### A_INFER_POSITION
275
+
276
+ **Intent-based overrides** (按顺序匹配,先命中先用):
277
+
278
+ | Pattern | Position |
279
+ |---------|----------|
280
+ | brainstorm / 头脑风暴 / 探索 / ideate / 设计思路 | `brainstorm` |
281
+ | blueprint / 规格 / 正式文档 / spec-generate / 7-phase | `blueprint` |
282
+ | broad/medium intent 无数字 phase (重构/全面/重写/迁移/新功能 X) | `analyze-macro` |
283
+
284
+ **Bootstrap detection:**
285
+
286
+ | Condition | Position |
287
+ |-----------|----------|
288
+ | No `.workflow/` + no source files | `brainstorm` |
289
+ | No `.workflow/` + has source files | `init` |
290
+ | Has `.workflow/` but no state.json | `init` |
291
+ | Has state.json | → phase-aware artifact inference |
292
+
293
+ **Phase-aware artifact inference**(基于 `session.phase` + `session.phase_is_new`,artifact 按 `session.phase` 过滤):
294
+
295
+ | Condition | Position |
296
+ |-----------|----------|
297
+ | `phase_is_new == true` | `analyze` |
298
+ | no milestones AND no roadmap.md AND has analyze macro artifact | `roadmap` |
299
+ | no milestones AND no roadmap.md AND no analyze artifact | `analyze-macro` |
300
+ | `phase == null` | n/a |
301
+ | phase 已存在 + 无任何 artifact | `analyze` |
302
+ | phase 已存在 + 最新 artifact = analyze | `plan` |
303
+ | phase 已存在 + 最新 artifact = plan | `execute` |
304
+ | phase 已存在 + 最新 artifact = execute | `verify` |
305
+ | phase 已存在 + 最新 artifact = verify | → refine from result files |
306
+
307
+ **Refine from verify results:**
308
+
309
+ | Condition | Position |
310
+ |-----------|----------|
311
+ | verification.json: passed==false or gaps[] | `verify-failed` |
312
+ | passed==true, no review.json | `business-test` |
313
+ | review.json: verdict=="BLOCK" | `review-failed` |
314
+ | review.json: verdict!="BLOCK" | `test` |
315
+ | uat.md: all passed | `milestone-audit` |
316
+ | uat.md: has failures | `test-failed` |
317
+
318
+ ### A_RESOLVE_SCOPE_VERDICT
319
+
320
+ 仅当 `lifecycle_position ∈ {analyze-macro, roadmap, plan}` 且存在最新 analyze artifact 时执行。
321
+
322
+ 1. 定位最新 macro analyze artifact(`type=="analyze"` 且 `scope=="macro"`,按 created_at DESC)→ `session.analyze_macro_id = ANL-xxx`
323
+ 2. 读 `{artifact_path}/conclusions.json` 的 `scope_verdict` 字段(`large | medium | small`)
324
+ 3. 写入 `session.scope_verdict`;缺失 → `unknown`
325
+ 4. 路由建议:
326
+
327
+ | scope_verdict | 链路 |
328
+ |---------------|------|
329
+ | `large` | analyze-macro → roadmap → analyze → plan → execute → ... |
330
+ | `medium` / `small` | analyze-macro → plan --from analyze:{ANL_ID} → execute → ... |
331
+ | `unknown` | 默认 large;post-analyze-scope 节点再纠正 |
332
+
333
+ ### A_DETERMINE_QUALITY_MODE
334
+
335
+ 读 `session.quality_mode_override`(CLI `--quality`),无则按规则推断:
336
+
337
+ | Condition | Mode | Pipeline (verify 之后) |
338
+ |-----------|------|-------------------------|
339
+ | Has `specs/REQ-*.md` + 当前 phase 业务范围明确 | `full` | business-test → review → test-gen → test |
340
+ | Default | `standard` | review → test-gen (当 coverage<80%) → test |
341
+ | `--quality quick` | `quick` | review --tier quick |
342
+
343
+ 写入 `session.quality_mode`。
344
+
345
+ ### A_DETERMINE_PLANNING_MODE
346
+
347
+ **Auto-resolve rules (按优先级):**
348
+
349
+ | Condition | Mode |
350
+ |-----------|------|
351
+ | lifecycle_position ∈ {brainstorm, init, roadmap} | `independent` |
352
+ | `phase_is_new == true` | `independent` |
353
+ | intent 显式指定 phase 编号(如 "phase 2"、"P3") | `independent` |
354
+ | milestone 仅含 1 个 phase | `independent` |
355
+ | milestone 含多个 phase + `auto_confirm` | `unified` |
356
+ | milestone 含多个 phase + 非 `auto_confirm` | → ask_user |
357
+
358
+ **ask_user** (仅当 milestone 含 ≥2 phase 且非 auto_confirm):
359
+
360
+ ```
361
+ question: "当前里程碑含 {N} 个 phase,选择规划模式?"
362
+ options:
363
+ - label: "统一规划 (Recommended)"
364
+ description: "一次性分析+规划整个里程碑所有 phase,analyze/plan 走里程碑级,适合 phase 间关联紧密"
365
+ - label: "独立规划"
366
+ description: "逐个 phase 走完整生命周期(analyze→plan→execute→verify→...),适合 phase 间独立性高"
367
+ ```
368
+
369
+ 写入 `session.planning_mode`(`"unified"` 或 `"independent"`)。
370
+
371
+ ### A_DECOMPOSE_TASKS
372
+
373
+ **1. Classify intent breadth:**
374
+
375
+ | Pattern | Breadth | Clarify? |
376
+ |---------|---------|----------|
377
+ | 重构/全面/重写/重做/整体/迁移 · overhaul/migrate/rewrite/revamp | broad | MUST (ignores auto_confirm) |
378
+ | named single file/function/bug, "fix X", "add Y to Z" | narrow | skip — auto-derive |
379
+ | otherwise | medium | clarify unless auto_confirm |
380
+
381
+ **2. Clarify boundary** (broad/medium) — `ask_user`, ≤3 rounds, options pre-filled from intent + a quick Glob/Grep scan of the target module:
382
+
383
+ | Round | Question | Drives |
384
+ |-------|----------|--------|
385
+ | Scope | 哪些目录/文件/层在范围内?明确排除什么? | boundary_contract.in_scope / out_of_scope |
386
+ | Constraints | 必须向后兼容?公共 API 冻结?行为/性能预算?测试门槛? | boundary_contract.constraints + execution_criteria |
387
+ | Done | 什么可观测结果算"完成"?(如:测试全绿 + 行为零变更 + X 指标) | boundary_contract.definition_of_done |
388
+
389
+ narrow → derive defaults from intent + codebase, skip questions.
390
+
391
+ **3. Derive `execution_criteria`**: backward-compat、scope-freeze、test/coverage bar、fix-don't-hide、incremental commit。
392
+
393
+ **4. Derive `task_decomposition`** (子目标清单 — outcome-oriented, NOT lifecycle stages). Each entry:
394
+ ```json
395
+ { "id": "G1", "goal": "<deliverable>", "boundary": "<in/out note>",
396
+ "done_when": "<objectively checkable condition>",
397
+ "evidence": "verification.json|review.json|uat.md|<test path>",
398
+ "lifecycle": ["analyze","execute","verify"], "status": "pending" }
399
+ ```
400
+ `done_when` 必须客观可验证,且引用 ralph 已产出的 artifact;`lifecycle` 字段映射到产出 evidence 的生命周期 stage。
401
+
402
+ **5. Persist**: `boundary_contract`, `execution_criteria`, `task_decomposition`。每个 sub-goal 初始化 `status: "pending"` + `completion_confirmed: false`。
403
+
404
+ **6. Stage** the Goal Prompt (Appendix) for A_CREATE_SESSION to emit.
405
+
406
+ ### A_BUILD_STEPS
407
+
408
+ 从 `session.lifecycle_position` 生成 steps 到 `milestone-complete`。
409
+
410
+ | Stage | invoke_skill(independent) | invoke_skill(unified) | Decision after | quality_mode |
411
+ |-------|---------------------|-----------------|----------------|--------------|
412
+ | brainstorm | `maestro-brainstorm "{intent}"` | *(same)* | — | all |
413
+ | blueprint | `maestro-blueprint "{intent}"` | *(same)* | — | all |
414
+ | init | `maestro-init` | *(same)* | — | all |
415
+ | analyze-macro | `maestro-analyze "{intent}"` | *(same)* | `post-analyze-scope` | all |
416
+ | roadmap | `maestro-roadmap --from analyze:{analyze_macro_id}` | *(same)* | — | all |
417
+ | analyze | `maestro-analyze {phase}` | `maestro-analyze` | — | all |
418
+ | plan | `maestro-plan {phase}` *(scope=phase)* / `maestro-plan --from analyze:{analyze_macro_id}` *(scope=standalone)* / `maestro-plan --from blueprint:{blueprint_id}` *(scope=standalone)* | `maestro-plan` | — | all |
419
+ | execute | `maestro-execute {phase}` | `maestro-execute` | — | all |
420
+ | verify | `maestro-verify {phase}` | `maestro-verify` | `post-verify` | all |
421
+ | business-test | `quality-auto-test {phase}` | `quality-auto-test` | `post-business-test` | full only |
422
+ | review | `quality-review {phase}` | `quality-review` | `post-review` | all (quick: append `--tier quick`) |
423
+ | test-gen | `quality-auto-test {phase}` | `quality-auto-test` | — | full / standard if coverage<80% |
424
+ | test | `quality-test {phase}` | `quality-test` | `post-test` | full, standard |
425
+ | milestone-audit | `maestro-milestone-audit` | *(same)* | — | all |
426
+ | goal-audit | *(decision-only)* | *(same)* | `post-goal-audit` | all (only if decomposed) |
427
+ | milestone-complete | `maestro-milestone-complete` | *(same)* | `post-milestone` | all |
428
+
429
+ **Build rules (按顺序应用):**
430
+
431
+ 0. **planning_mode 选列**:`unified` → invoke_skill(unified) 列;`independent` → invoke_skill(independent) 列
432
+ 1. **起点**:从 `session.lifecycle_position` 开始
433
+ 2. **跳过已完成**:跳过当前 milestone+phase 下已有 completed artifact 的 stage(按 `session.phase` 过滤);unified 按 milestone 过滤
434
+ 3. **quality_mode 过滤**:按 `session.quality_mode` 排除不匹配 stage
435
+ 4. **决策节点**:每个 Decision after 非空的 stage 之后插入 `{ decision: "<gate>", retry_count: 0, max_retries: 2, command_scope: null, command_path: null }`
436
+ 5. **goal-audit 插入**:`task_decomposition` 存在时,在最后一个 evidence-producing stage(verify/review/test)之后、`milestone-complete` 之前插入 `decision:post-goal-audit`
437
+ 6. **终点硬约束**:chain 以 `milestone-complete` 结尾
438
+ 7. **goal_ref 传播**:`task_decomposition` 存在时,每个 step 按 `step.stage ∈ g.lifecycle` 匹配 `step.goal_ref = g.id`(多匹配取字典序最小);decision 节点不打 goal_ref
439
+ 8. **占位符**:independent 保留 `{phase}` `{intent}`;unified 不带 `{phase}`
440
+ 9. **command_path 解析**(执行 step):
441
+ - skill 名 = args 前的第一个 token
442
+ - `shell("maestro ralph skills --platform claude --json --quiet")` 拉取 global + project(project 覆盖 global),匹配 skill 名:
443
+ - 命中 → `command_scope = "global" | "project"`,`command_path = <绝对路径>`
444
+ - 未命中 → `command_scope = "missing"`, `command_path = null` → A_CREATE_SESSION raise E006
445
+ 10. **每个 step 初始化** `completion_confirmed: false`, `completion_status: null`, `completion_evidence: null`, `deferred_reads: []`, `load: null`
446
+ 11. **scope_verdict gating**(仅当 chain 起点 = `analyze-macro`):
447
+ - `scope_verdict ∈ {medium, small}` → 跳过 `roadmap` + `analyze` 两 stage;`plan` 选 standalone 列(`--from analyze:{analyze_macro_id}`),不带 `{phase}`
448
+ - `scope_verdict == large` → 保留 `roadmap` + `analyze`;`plan` 选 phase 列(`{phase}`)
449
+ - `scope_verdict == unknown` → 默认 large 路径;由 `post-analyze-scope` 决策节点在 macro analyze 完成后纠正(A_APPLY_SCOPE_VERDICT)
450
+ 12. **--from 自动注入**:
451
+ - `analyze_macro_id` 存在且当前 step 是 `roadmap` → args 改为 `--from analyze:{analyze_macro_id}`
452
+ - `analyze_macro_id` 存在且 `scope_verdict ∈ {medium, small}` 且当前 step 是 `plan` → args 改为 `--from analyze:{analyze_macro_id}`
453
+ - `blueprint_id` 存在 → 当前 step 是 `plan` → args 改为 `--from blueprint:{blueprint_id}`(优先级低于 phase 数字参数)
454
+ - 写入 `step.source_artifact_ref` 以便审计
455
+ 13. **Milestone-ref**:含 `{phase}` 占位符的 step → `step.milestone_id = session.milestone`
456
+ 14. **动态插入步骤**(A_APPLY_*)同样应用规则 7-13
457
+
458
+ ### A_CREATE_SESSION
459
+
460
+ 1. 校验所有 step 的 `command_scope != "missing"`;否则 raise E006 + 列出缺失 skill
461
+ 2. Write `.workflow/.maestro/ralph-{YYYYMMDD-HHmmss}/status.json`
462
+ 3. Display chain overview:每步显示 `{index}. {skill} [{command_scope}]`
463
+ 4. `task_decomposition` 存在 → display Goal Prompt block,继续进入 tick
464
+
465
+ ### A_LOCATE_SESSION
466
+
467
+ 1. If session_id provided → load `.workflow/.maestro/{session_id}/status.json`
468
+ 2. Else: scan `.workflow/.maestro/*/status.json`, filter `status ∈ {"running","paused"}`, sort DESC by created_at, take first
469
+ 3. Extract: session_id, source, steps[], phase, milestone, intent, auto_mode, context, cli_tool, active_step_index, status
470
+ 4. 预探测 `next_pending_step`(瞬态,不持久化):
471
+ - 若 `active_step_index != null` 且 `steps[active_step_index].status == "running"` → `steps[active_step_index]`
472
+ - 否则 `steps[]` 中 `status == "pending"` 的最小 index
473
+ - 都无 → `null`
474
+
475
+ ### A_RESUME_SESSION
476
+
477
+ 1. A_LOCATE_SESSION 加载 active session
478
+ 2. 清理 active_step_index:若 `active_step_index != null` 且 `steps[active_step_index].status ∈ {"completed","skipped","failed"}` → `active_step_index = null`;其余保留
479
+ 3. If `session.status == "paused"` → `session.status = "running"`
480
+ 4. `session.consec_exit2_count = 0`
481
+ 5. Display: `↻ Resume {session_id}`
482
+
483
+ ### A_CLAIM_DECISION
484
+
485
+ 1. 校验 `session.active_step_index ∈ {null, next_pending_step.index}`,否则 raise E008
486
+ 2. `session.active_step_index = next_pending_step.index`
487
+ 3. `steps[next_pending_step.index].status = "running"`
488
+ 4. Display: `[{index}/{total}] ◆ {step.decision} Retry: {retry}/{max}`
489
+
490
+ ### A_RESOLVE_ARGS
491
+
492
+ **Placeholder substitution:**
493
+
494
+ | Placeholder | Source |
495
+ |-------------|--------|
496
+ | `{phase}` | session.phase |
497
+ | `{milestone}` | session.milestone |
498
+ | `{intent}` | session.intent |
499
+ | `{description}` | session.intent (alias) |
500
+ | `{scratch_dir}` | session.context.scratch_dir or latest artifact path |
501
+ | `{plan_dir}` | session.context.plan_dir |
502
+ | `{analysis_dir}` | session.context.analysis_dir |
503
+ | `{issue_id}` | session.context.issue_id |
504
+ | `{milestone_num}` | session.context.milestone_num |
505
+
506
+ **Per-skill enrichment** (when args empty or minimal):
507
+
508
+ | Skill | Required context | Source |
509
+ |-------|-----------------|--------|
510
+ | maestro-brainstorm | topic | `"{intent}"` |
511
+ | maestro-roadmap | description | `"{intent}"` |
512
+ | maestro-analyze | phase or topic | `{phase}` or `"{intent}"` |
513
+ | maestro-plan | phase or --dir | `{phase}`, or `--dir {scratch_dir}` |
514
+ | maestro-execute | phase or --dir | `{phase}`, or `--dir {scratch_dir}` |
515
+ | quality-debug | gap context | Read previous step's error/gap |
516
+ | quality-* | phase | `{phase}` |
517
+
518
+ **Artifact dir resolution for --dir:**
519
+ ```
520
+ Read state.json → filter artifacts by milestone + phase
521
+ plan commands: latest type=="analyze" → --dir .workflow/scratch/{path}
522
+ execute commands: latest type=="plan" → --dir .workflow/scratch/{path}
523
+ ```
524
+
525
+ Write enriched args back to status.json.
526
+
527
+ ### A_EXEC_STEP
528
+
529
+ 1. **Load** — `shell("maestro ralph next")`
530
+ - exit 0 → `session.consec_exit2_count = 0`,按 stdout 内联执行(进入步骤 2)
531
+ - exit 2 → `session.consec_exit2_count += 1`;≥ 2 时抛 E010 → S_HANDLE_FAIL;否则 → S_TICK_LOCATE
532
+ - exit 1 → E007 → S_HANDLE_FAIL
533
+ - exit ≥ 3 → E008 → S_HANDLE_FAIL
534
+ 2. **Inline execution** — 按 stdout 执行;deferred_reading 按需 Read
535
+ 3. **Complete**:
536
+ - `shell("maestro ralph complete N --status DONE [--evidence <path>]")`
537
+ - `shell("maestro ralph complete N --status DONE_WITH_CONCERNS --concerns \"...\"")`
538
+ - `shell("maestro ralph retry N")`
539
+ - `shell("maestro ralph complete N --status BLOCKED --reason \"...\"")`
540
+ 4. **Propagate context signals** — `PHASE: N` / `scratch_dir: path` / `BLP-xxx` 写入 `status.json.context`
541
+
542
+ ### A_DELEGATE_EVALUATE
543
+
544
+ 1. Resolve artifact dir: `.workflow/scratch/{artifact.path}/` with fallback glob
545
+ 2. Parse decision metadata: `{ decision, retry_count, max_retries }`
546
+ 3. Map result files:
547
+ | Decision | Files |
548
+ |----------|-------|
549
+ | post-verify | verification.json |
550
+ | post-business-test | .tests/auto-test/report.json |
551
+ | post-review | review.json |
552
+ | post-test | uat.md, .tests/test-results.json |
553
+ 4. Check artifact for confidence section → include as signal
554
+ 5. Execute delegate (run_in_background, STOP, wait for callback):
555
+ ```
556
+ maestro delegate "PURPOSE: 评估 {decision} 质量门结果
557
+ TASK: 读取结果 | 分析状态 | 评估严重性 | 给出建议
558
+ EXPECTED: ---VERDICT--- STATUS/REASON/GAP_SUMMARY/CONFIDENCE(high|medium|low)/CONFIDENCE_SCORE(0-100)/WEAKEST_DIMENSION ---END---
559
+ CONSTRAINTS: 只评估 | 置信度<60% 倾向 fix | retry {n}/{max} 达上限必须 escalate"
560
+ --role analyze --mode analysis
561
+ ```
562
+ 6. On callback: parse verdict; if parse fails → fallback STATUS="fix"
563
+ 7. Confidence adjustment: <60 + proceed → fix; >95 + fix + retry>0 → suggest proceed
564
+ 8. **Decision log**: Append to `{session_dir}/decisions.ndjson`:
565
+ ```json
566
+ { "id": "DEC-{timestamp}", "timestamp": "{ISO}", "source": "ralph",
567
+ "node_id": "{step.decision}", "type": "quality-gate",
568
+ "verdict": "{adjusted_verdict}", "confidence_score": {N},
569
+ "close_call": {N>=50 && N<=70}, "summary": "{REASON}" }
570
+ ```
571
+
572
+ ### A_STRUCTURAL_EVALUATE
573
+
574
+ **post-milestone:**
575
+ 1. Read state.json → 取已完成 milestone 对象
576
+ 2. `milestone_obj.type` (default `"standard"`)
577
+ 3. `type == "standard"`:next milestone 存在 → insert lifecycle steps;否则 → END
578
+ 4. `type == "adhoc"`:END,`current_milestone = null`
579
+
580
+ **post-debug-escalate:** STOP → paused,display "请人工介入"
581
+
582
+ ### A_SCOPE_EVALUATE
583
+
584
+ 由 `post-analyze-scope` 触发。
585
+
586
+ 1. 定位刚完成的 macro analyze artifact → `analyze_macro_id`, `conclusions_path = {artifact_path}/conclusions.json`
587
+ 2. 读取 `conclusions.scope_verdict`(`large | medium | small`),缺失 → `unknown`
588
+ 3. 写入 `session.scope_verdict` + `session.analyze_macro_id`
589
+ 4. Append `{session_dir}/decisions.ndjson`:
590
+ ```json
591
+ { "id": "DEC-{timestamp}", "type": "scope-gate",
592
+ "source": "ralph", "node_id": "post-analyze-scope",
593
+ "verdict": "{scope_verdict}", "analyze_macro_id": "{ANL_ID}" }
594
+ ```
595
+ 5. → A_APPLY_SCOPE_VERDICT
596
+
597
+ ### A_GOAL_AUDIT_EVALUATE
598
+
599
+ 仅当 `task_decomposition` 存在。
600
+
601
+ 1. Read `session.task_decomposition`
602
+ 2. For each sub-goal `status != "done"`:resolve `evidence` artifact
603
+ 3. Delegate read-only audit (run_in_background, STOP, wait):
604
+ ```
605
+ maestro delegate "PURPOSE: 审计未完成子目标,判定 met / unmet
606
+ TASK:
607
+ 1. 读取 status.json.task_decomposition 中 status!=done 的子目标
608
+ 2. 打开 evidence 产物,对照 done_when 严格判定
609
+ 3. 输出 met / unmet,unmet 给出 gap + target_phase
610
+ CONTEXT:
611
+ status.json = {session_dir}/status.json
612
+ evidence = {evidence artifacts}
613
+ execution_criteria = {execution_criteria}
614
+ boundary_contract = {boundary_contract}
615
+ EXPECTED:
616
+ ---VERDICT---
617
+ STATUS=all_met|has_unmet
618
+ UNMET=[{id:G2,gap:'...',target_phase:execute}, ...]
619
+ CONFIDENCE_SCORE=0-100
620
+ ---END---
621
+ CONSTRAINTS:
622
+ - 只评估,不修改文件
623
+ - 严格按 done_when 判定;evidence 缺失 → unmet
624
+ - 不得建议超出 boundary_contract 的修改
625
+ "
626
+ --role analyze --mode analysis
627
+ ```
628
+ 4. On callback: 对每个 met 子目标,set `task_decomposition[i].status="done"` + `completion_confirmed=true` + `completed_at=now`
629
+ 5. Append `{session_dir}/decisions.ndjson` with `"type": "goal-gate"`, `unmet_count`, `unmet_ids`
630
+ 6. Verdict: `all_met` → A_APPLY_GOAL_DONE; `has_unmet` → A_APPLY_GOAL_FIX
631
+ GUARD: retry_count >= max_retries AND still unmet → A_APPLY_ESCALATE
632
+
633
+ > **A_APPLY_\* release 协议**(所有 A_APPLY_* 末尾统一应用):
634
+ > - 完成分支(proceed / goal-done / scope applied / structural advanced):`step.status = "completed"`, `step.completion_confirmed = true`, `session.active_step_index = null`
635
+ > - 重评分支(fix / escalate / goal-fix):`step.status = "pending"`, `step.completion_confirmed = false`, `session.active_step_index = null`, `step.retry_count += 1`
636
+
637
+ ### A_APPLY_PROCEED
638
+
639
+ 1. release 协议 — 完成分支
640
+ 2. Append decisions.ndjson with verdict
641
+ 3. Display: ◆ Decision: {type} → proceed ({reason})
642
+
643
+ ### A_APPLY_FIX
644
+
645
+ 1. Insert fix-loop commands after current step (Appendix: Fix-Loop Templates)
646
+ 2. release 协议 — 重评分支;reindex steps
647
+ 3. Display: ◆ Decision: {type} → fix, +{N} commands inserted
648
+
649
+ ### A_APPLY_ESCALATE
650
+
651
+ 1. Insert `[quality-debug "{gap_summary}", decision:post-debug-escalate]`
652
+ 2. release 协议 — 重评分支;reindex
653
+
654
+ ### A_APPLY_SCOPE_VERDICT
655
+
656
+ 由 `post-analyze-scope` 触发。
657
+
658
+ 1. 读 `session.scope_verdict`
659
+ 2. `large`:为后续 `roadmap` step 注入 `--from analyze:{analyze_macro_id}`;后续 `plan` step 选 phase 列
660
+ 3. `medium` / `small`:
661
+ - 删除 `goal-audit` 之前未完成的 `roadmap` + `analyze` (phase) step
662
+ - 下一个未完成的 `plan` step → `maestro-plan --from analyze:{analyze_macro_id}`,去掉 `{phase}`,`source_artifact_ref = analyze:{analyze_macro_id}`
663
+ - 后续 `execute` / `verify` 同 standalone scope
664
+ 4. `unknown`:非 auto_confirm → ask_user 二选一(large / medium-small);auto_confirm → 默认 large
665
+ 5. release 协议 — 完成分支;reindex
666
+ 6. Display: ◆ Scope verdict: {verdict} → {kept|collapsed to standalone via analyze:{ANL_ID}}
667
+
668
+ ### A_APPLY_GOAL_FIX
669
+
670
+ 1. 对每个 unmet 子目标 `G{n}`(按 `target_phase` 分组去重):在 `goal-audit` 节点前插入 scoped mini-loop(Appendix: post-goal-audit),每条 step `goal_ref: "G{n}"`
671
+ 2. 追加 `decision:post-goal-audit {retry+1}`
672
+ 3. release 协议 — 重评分支;reindex
673
+ 4. Display: ◆ Goal audit: {k} unmet → +{N} steps inserted (G{ids}), retry {r}/{max}
674
+
675
+ ### A_APPLY_GOAL_DONE
676
+
677
+ 1. 每个 `task_decomposition[*]` → `status="done"`, `completion_confirmed=true`, `completed_at=now`;顶层 `task_decomposition_all_done=true`
678
+ 2. release 协议 — 完成分支;proceed to `milestone-complete`
679
+ 3. Display: ◆ Goal audit: all met ✓
680
+
681
+ ### A_ADVANCE_MILESTONE
682
+
683
+ 1. Update session: milestone, phase, reset passed_gates
684
+ 2. Insert full lifecycle steps for next milestone
685
+ 3. release 协议 — 完成分支;reindex
686
+
687
+ ### A_RETRY
688
+
689
+ 1. `shell("maestro ralph retry N")`
690
+ 2. Display: `[{index}/{total}] ↻ {step.skill} retry`
691
+
692
+ ### A_SKIP_STEP
693
+
694
+ 手动编辑 status.json:`step.status = "skipped"`, `step.completion_confirmed = false`,若 `active_step_index == step.index` 则置 null。
695
+
696
+ ### A_PAUSE_SESSION
697
+
698
+ `session.status = "paused"` (CLI 通过 `ralph complete N --status BLOCKED` 自动写;手动场景直接编辑)
699
+ Display: `[{index}/{total}] ✗ {step.skill} 失败,会话已暂停。/maestro-ralph-beta continue 恢复。`
700
+
701
+ ### A_PAUSE_ESCALATE
702
+
703
+ 1. `session.status = "paused"`
704
+ 2. Display: ◆ 已达最大重试次数,debug 已执行。请人工介入。
705
+ 3. Display: /maestro-ralph-beta continue 恢复
706
+
707
+ ### A_COMPLETE_SESSION
708
+
709
+ 1. 校验:所有 step `completion_confirmed == true`(除 skipped);task_decomposition 存在时校验 `task_decomposition_all_done == true`
710
+ 2. 任一校验失败 → 不标 completed,回 S_TICK_LOCATE 或 pause
711
+ 3. `session.status = "completed"`, write status.json
712
+ 4. Display completion report:
713
+ ```
714
+ ============================================================
715
+ SESSION COMPLETE
716
+ ============================================================
717
+ Session: {session_id} [{source}]
718
+ Steps: {completed}/{total} confirmed: {confirmed}/{completed}
719
+
720
+ [✓] 0. maestro-plan 1 [global]
721
+ [✓] 1. maestro-execute 1 [project]
722
+ [✓] 2. maestro-verify 1 [global]
723
+ [✓] 3. ◆ post-verify [decision]
724
+ ...
725
+ ============================================================
726
+ ```
727
+ Icons: `✓` confirmed, `—` skipped, `✗` failed, `◆` decision
728
+
729
+ </actions>
730
+
731
+ </state_machine>
732
+
733
+ <appendix>
734
+
735
+ ### Session Schema
736
+
737
+ ```json
738
+ {
739
+ "session_id": "ralph-{YYYYMMDD-HHmmss}",
740
+ "source": "ralph", "status": "running",
741
+ "ralph_protocol_version": "2",
742
+ "active_step_index": null,
743
+ "intent": "", "lifecycle_position": "",
744
+ "phase": null, "phase_is_new": false,
745
+ "milestone": "", // D-007 反查结果
746
+ "auto_mode": false,
747
+ "quality_mode": "standard", // "full" | "standard" | "quick"
748
+ "planning_mode": "independent", // "unified" | "independent"
749
+ "scope_verdict": null, // "large" | "medium" | "small" | "unknown" | null
750
+ "analyze_macro_id": null, // "ANL-xxx"
751
+ "blueprint_id": null, // "BLP-xxx"
752
+ "cli_tool": "claude", "passed_gates": [],
753
+ "consec_exit2_count": 0,
754
+
755
+ "context": { "issue_id": null, "scratch_dir": null, "plan_dir": null,
756
+ "analysis_dir": null, "brainstorm_dir": null, "blueprint_dir": null },
757
+ "steps": [{
758
+ "index": 0,
759
+ "skill": "", // 执行 step 有值;decision 节点为空字符串/null
760
+ "args": "",
761
+ "stage": "", // brainstorm|blueprint|init|analyze-macro|roadmap|analyze|plan|execute|verify|...
762
+ "scope": null, // "phase"|"standalone"|"milestone"|null(plan 等需要)
763
+ "decision": null, // null = 执行 step;非 null = decision step (值为 gate 名)
764
+ "retry_count": 0, // decision step
765
+ "max_retries": 2, // decision step
766
+ "command_scope": "global|project|missing|null",
767
+ "command_path": "<absolute path> | null",
768
+ "milestone_id": null, // 仅含 {phase} 占位符的 step
769
+ "source_artifact_ref": null, // "analyze:ANL-xxx" | "blueprint:BLP-xxx" | null
770
+ "status": "pending|running|completed|skipped|failed",
771
+ "goal_ref": null,
772
+ "completion_confirmed": false,
773
+ "completion_status": null,
774
+ "completion_evidence": null,
775
+ "completed_at": null,
776
+ "deferred_reads": [],
777
+ "load": null // { loaded_at, required_files[], deferred_files[], resolve_version }
778
+ }],
779
+ "current_step": 0,
780
+
781
+ "boundary_contract": {
782
+ "in_scope": [], "out_of_scope": [], "constraints": [], "definition_of_done": ""
783
+ },
784
+ "execution_criteria": [],
785
+ "task_decomposition": [
786
+ { "id": "G1", "goal": "", "boundary": "", "done_when": "",
787
+ "evidence": "", "lifecycle": [], "status": "pending|done",
788
+ "completion_confirmed": false, "completed_at": null }
789
+ ],
790
+ "task_decomposition_all_done": false
791
+ }
792
+ ```
793
+
794
+ ### Fix-Loop Templates
795
+
796
+ 插入的执行 step 按 A_BUILD_STEPS 规则 9 解析 `command_path` + `command_scope`;`decision:*` 条目为 decision 节点。
797
+
798
+ **post-verify:**
799
+ ```
800
+ quality-debug "{gap_summary}"
801
+ maestro-plan --gaps {phase}
802
+ maestro-execute {phase}
803
+ maestro-verify {phase}
804
+ decision:post-verify {retry+1}
805
+ ```
806
+
807
+ **post-business-test:**
808
+ ```
809
+ quality-debug --from-business-test "{gap_summary}"
810
+ maestro-plan --gaps {phase}
811
+ maestro-execute {phase}
812
+ maestro-verify {phase}
813
+ decision:post-verify {retry: 0}
814
+ quality-auto-test {phase}
815
+ decision:post-business-test {retry+1}
816
+ ```
817
+
818
+ **post-review:**
819
+ ```
820
+ quality-debug "{gap_summary}"
821
+ maestro-plan --gaps {phase}
822
+ maestro-execute {phase}
823
+ quality-review {phase}
824
+ decision:post-review {retry+1}
825
+ ```
826
+
827
+ **post-test:**
828
+ ```
829
+ quality-debug --from-uat "{gap_summary}"
830
+ maestro-plan --gaps {phase}
831
+ maestro-execute {phase}
832
+ maestro-verify {phase}
833
+ decision:post-verify {retry: 0}
834
+ quality-auto-test {phase}
835
+ decision:post-business-test {retry: 0}
836
+ quality-review {phase}
837
+ decision:post-review {retry: 0}
838
+ quality-auto-test {phase}
839
+ quality-test {phase}
840
+ decision:post-test {retry+1}
841
+ ```
842
+
843
+ **post-goal-audit:** (per unmet sub-goal group)
844
+ ```
845
+ # for each unmet sub-goal G{n}, scoped to target_phase:
846
+ maestro-plan --gaps {target_phase} "G{n}: {gap}" [goal_ref: G{n}]
847
+ maestro-execute {target_phase} [goal_ref: G{n}]
848
+ maestro-verify {target_phase} [goal_ref: G{n}]
849
+ # after all unmet groups inserted:
850
+ decision:post-goal-audit {retry+1}
851
+ ```
852
+
853
+ ### Goal Prompt Template
854
+
855
+ decomposition 产出后,链路概览之后逐字显示:
856
+
857
+ ```
858
+ 📋 任务分解完成。可随时复制以下 /goal 设定终止条件:
859
+
860
+ /goal 直到 {session_dir}/status.json 的 task_decomposition[*] 与 steps[*] 全部 completion_confirmed=true 才停。每轮以 status.json 为唯一行动手册,通过 /maestro-ralph-beta 推进 tick;decision 节点由 ralph 内联评估。禁止手动执行 skill 或修改 boundary_contract.out_of_scope。
861
+ ```
862
+
863
+ ### Error Codes
864
+
865
+ | Code | Severity | Description | Recovery |
866
+ |------|----------|-------------|----------|
867
+ | E001 | error | No intent and no running session | Prompt for intent |
868
+ | E002 | error | Cannot infer lifecycle position | Show raw state, ask |
869
+ | E003 | error | Artifact dir not found for decision | Show glob, ask |
870
+ | E004 | error | Delegate verdict parse failed | Fallback: "fix" |
871
+ | E005 | error | Delegate execution failed | Fallback: "fix" |
872
+ | E006 | error | command_scope == "missing" for one or more steps | List missing skills, abort build |
873
+ | E007 | error | required_reading 引用文件缺失 | `ralph next` 拒绝;CLI stderr 列出缺失路径 |
874
+ | E008 | error | `ralph complete` idx ≠ active_step_index | 编辑 status.json 修正一致性 |
875
+ | E009 | error | `ralph complete` step.status ≠ running | 重复 complete 或非法跳跃;编辑 status.json |
876
+ | E010 | error | status.json schema 损坏 OR A_EXEC_STEP exit=2 熔断(连续 ≥2 次空转) | `ralph check` 显示损坏字段;熔断需人工核对 next_pending_step 与 router 路由是否一致 |
877
+ | W001 | warning | Decision expanded chain | Auto-handled |
878
+ | W002 | warning | Max retries, escalating | Auto-handled |
879
+ | W003 | warning | Multiple running sessions | Use latest, warn |
880
+ | W004 | warning | Low delegate confidence | Show warning |
881
+ | W005 | warning | active_step_index 指向已 completed step | `ralph next` 自动清理后继续 |
882
+ | W007 | warning | step.skill ≠ command .md frontmatter.name | 提示但不阻塞 |
883
+
884
+ ### Success Criteria
885
+
886
+ - [ ] Tick 末尾自调用 `invoke_skill("maestro-ralph-beta")`,直到全部 `completion_confirmed` 或 paused
887
+ - [ ] 同一 session 同时仅一个 step 持 `active_step_index`;切换前必经 release
888
+ - [ ] Decision step 全程不调 `maestro ralph next` / `complete`,由 maestro-ralph-beta 内联评估并 release
889
+ - [ ] `task_decomposition` 存在时,chain 含 `decision:post-goal-audit`,且最终 `task_decomposition_all_done == true` 才允许 S_COMPLETE
890
+ - [ ] Chain 以 `milestone-complete` 结尾;A_APPLY_* 修改 steps[] 后均 reindex
891
+ - [ ] 连续 2 次 `ralph next` exit=2 → E010 pause(防 router 错路由空转)
892
+
893
+ </appendix>