maestro-flow 0.5.44 → 0.5.46

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 (126) hide show
  1. package/.agents/agents/ralph-executor.md +93 -0
  2. package/.agents/skills/maestro-ralph-cli/SKILL.md +21 -16
  3. package/.agents/skills/maestro-ralph-v2/SKILL.md +923 -0
  4. package/.agents/skills/odyssey-debug/SKILL.md +338 -253
  5. package/.agents/skills/odyssey-improve/SKILL.md +367 -281
  6. package/.agents/skills/odyssey-planex/SKILL.md +490 -420
  7. package/.agents/skills/odyssey-review-test-fix/SKILL.md +336 -251
  8. package/.agents/skills/odyssey-ui/SKILL.md +332 -247
  9. package/.agy/agents/ralph-executor.md +91 -0
  10. package/.agy/skills/maestro-ralph-cli/SKILL.md +21 -16
  11. package/.agy/skills/maestro-ralph-v2/SKILL.md +935 -0
  12. package/.agy/skills/odyssey-debug/SKILL.md +338 -253
  13. package/.agy/skills/odyssey-improve/SKILL.md +367 -281
  14. package/.agy/skills/odyssey-planex/SKILL.md +490 -420
  15. package/.agy/skills/odyssey-review-test-fix/SKILL.md +336 -251
  16. package/.agy/skills/odyssey-ui/SKILL.md +332 -247
  17. package/.claude/agents/ralph-executor.md +91 -0
  18. package/.claude/commands/maestro-ralph-cli.md +21 -16
  19. package/.claude/commands/maestro-ralph-v2.md +921 -0
  20. package/.claude/commands/odyssey-debug.md +352 -267
  21. package/.claude/commands/odyssey-improve.md +381 -295
  22. package/.claude/commands/odyssey-planex.md +504 -434
  23. package/.claude/commands/odyssey-review-test-fix.md +350 -265
  24. package/.claude/commands/odyssey-ui.md +346 -261
  25. package/.codex/skills/maestro-next/SKILL.md +1 -1
  26. package/dashboard/dist-server/dashboard/src/server/wiki/embedding.js +3 -3
  27. package/dashboard/dist-server/dashboard/src/server/wiki/embedding.js.map +1 -1
  28. package/dashboard/dist-server/dashboard/src/server/wiki/wiki-indexer.js +4 -4
  29. package/dashboard/dist-server/dashboard/src/server/wiki/wiki-indexer.js.map +1 -1
  30. package/dashboard/dist-server/src/graph/kg/db/queries.d.ts +6 -0
  31. package/dashboard/dist-server/src/graph/kg/db/queries.js +141 -19
  32. package/dashboard/dist-server/src/graph/kg/db/queries.js.map +1 -1
  33. package/dashboard/dist-server/src/graph/kg/extraction/code/svelte-extractor.js +1 -1
  34. package/dashboard/dist-server/src/graph/kg/extraction/code/svelte-extractor.js.map +1 -1
  35. package/dashboard/dist-server/src/graph/kg/extraction/code/tree-sitter.js +2 -2
  36. package/dashboard/dist-server/src/graph/kg/extraction/code/tree-sitter.js.map +1 -1
  37. package/dashboard/dist-server/src/graph/kg/extraction/code/vue-extractor.js +1 -1
  38. package/dashboard/dist-server/src/graph/kg/extraction/code/vue-extractor.js.map +1 -1
  39. package/dashboard/dist-server/src/graph/kg/extraction/code/wasm-stability.js +1 -1
  40. package/dashboard/dist-server/src/graph/kg/extraction/code/wasm-stability.js.map +1 -1
  41. package/dashboard/dist-server/src/graph/kg/extraction/orchestrator.js +2 -2
  42. package/dashboard/dist-server/src/graph/kg/extraction/orchestrator.js.map +1 -1
  43. package/dashboard/dist-server/src/graph/kg/surface/hook-injector.js +1 -1
  44. package/dashboard/dist-server/src/graph/kg/surface/hook-injector.js.map +1 -1
  45. package/dashboard/dist-server/src/hooks/keyword-spec-injector.js +35 -0
  46. package/dashboard/dist-server/src/hooks/keyword-spec-injector.js.map +1 -1
  47. package/dashboard/dist-server/src/hooks/spec-analytics.d.ts +1 -0
  48. package/dashboard/dist-server/src/hooks/spec-analytics.js.map +1 -1
  49. package/dashboard/dist-server/src/hooks/wiki-search-bridge.d.ts +32 -0
  50. package/dashboard/dist-server/src/hooks/wiki-search-bridge.js +71 -0
  51. package/dashboard/dist-server/src/hooks/wiki-search-bridge.js.map +1 -0
  52. package/dist/src/agents/api-explore/agent-loop.d.ts +15 -2
  53. package/dist/src/agents/api-explore/agent-loop.d.ts.map +1 -1
  54. package/dist/src/agents/api-explore/agent-loop.js +6 -5
  55. package/dist/src/agents/api-explore/agent-loop.js.map +1 -1
  56. package/dist/src/agents/api-explore/config.d.ts +56 -0
  57. package/dist/src/agents/api-explore/config.d.ts.map +1 -1
  58. package/dist/src/agents/api-explore/config.js +34 -0
  59. package/dist/src/agents/api-explore/config.js.map +1 -1
  60. package/dist/src/agents/api-explore/llm.d.ts +5 -1
  61. package/dist/src/agents/api-explore/llm.d.ts.map +1 -1
  62. package/dist/src/agents/api-explore/llm.js +10 -8
  63. package/dist/src/agents/api-explore/llm.js.map +1 -1
  64. package/dist/src/agents/api-explore/moa-cache.d.ts +12 -0
  65. package/dist/src/agents/api-explore/moa-cache.d.ts.map +1 -0
  66. package/dist/src/agents/api-explore/moa-cache.js +50 -0
  67. package/dist/src/agents/api-explore/moa-cache.js.map +1 -0
  68. package/dist/src/agents/api-explore/moa-loop.d.ts +49 -0
  69. package/dist/src/agents/api-explore/moa-loop.d.ts.map +1 -0
  70. package/dist/src/agents/api-explore/moa-loop.js +43 -0
  71. package/dist/src/agents/api-explore/moa-loop.js.map +1 -0
  72. package/dist/src/agents/api-explore/moa-pipeline.d.ts +43 -0
  73. package/dist/src/agents/api-explore/moa-pipeline.d.ts.map +1 -0
  74. package/dist/src/agents/api-explore/moa-pipeline.js +276 -0
  75. package/dist/src/agents/api-explore/moa-pipeline.js.map +1 -0
  76. package/dist/src/agents/api-explore/runner.d.ts +3 -0
  77. package/dist/src/agents/api-explore/runner.d.ts.map +1 -1
  78. package/dist/src/agents/api-explore/runner.js +24 -7
  79. package/dist/src/agents/api-explore/runner.js.map +1 -1
  80. package/dist/src/agents/api-explore/session.d.ts +15 -0
  81. package/dist/src/agents/api-explore/session.d.ts.map +1 -1
  82. package/dist/src/agents/api-explore/session.js.map +1 -1
  83. package/dist/src/cli.js +1 -0
  84. package/dist/src/cli.js.map +1 -1
  85. package/dist/src/commands/explore.d.ts.map +1 -1
  86. package/dist/src/commands/explore.js +16 -1
  87. package/dist/src/commands/explore.js.map +1 -1
  88. package/dist/src/commands/moa.d.ts +3 -0
  89. package/dist/src/commands/moa.d.ts.map +1 -0
  90. package/dist/src/commands/moa.js +202 -0
  91. package/dist/src/commands/moa.js.map +1 -0
  92. package/dist/src/graph/kg/db/queries.d.ts +6 -0
  93. package/dist/src/graph/kg/db/queries.d.ts.map +1 -1
  94. package/dist/src/graph/kg/db/queries.js +141 -19
  95. package/dist/src/graph/kg/db/queries.js.map +1 -1
  96. package/dist/src/graph/kg/extraction/code/svelte-extractor.js +1 -1
  97. package/dist/src/graph/kg/extraction/code/svelte-extractor.js.map +1 -1
  98. package/dist/src/graph/kg/extraction/code/tree-sitter.js +2 -2
  99. package/dist/src/graph/kg/extraction/code/tree-sitter.js.map +1 -1
  100. package/dist/src/graph/kg/extraction/code/vue-extractor.js +1 -1
  101. package/dist/src/graph/kg/extraction/code/vue-extractor.js.map +1 -1
  102. package/dist/src/graph/kg/extraction/code/wasm-stability.js +1 -1
  103. package/dist/src/graph/kg/extraction/code/wasm-stability.js.map +1 -1
  104. package/dist/src/graph/kg/extraction/orchestrator.js +2 -2
  105. package/dist/src/graph/kg/extraction/orchestrator.js.map +1 -1
  106. package/dist/src/graph/kg/surface/hook-injector.js +1 -1
  107. package/dist/src/graph/kg/surface/hook-injector.js.map +1 -1
  108. package/dist/src/hooks/keyword-spec-injector.d.ts.map +1 -1
  109. package/dist/src/hooks/keyword-spec-injector.js +35 -0
  110. package/dist/src/hooks/keyword-spec-injector.js.map +1 -1
  111. package/dist/src/hooks/spec-analytics.d.ts +1 -0
  112. package/dist/src/hooks/spec-analytics.d.ts.map +1 -1
  113. package/dist/src/hooks/spec-analytics.js.map +1 -1
  114. package/dist/src/hooks/wiki-search-bridge.d.ts +33 -0
  115. package/dist/src/hooks/wiki-search-bridge.d.ts.map +1 -0
  116. package/dist/src/hooks/wiki-search-bridge.js +71 -0
  117. package/dist/src/hooks/wiki-search-bridge.js.map +1 -0
  118. package/dist/src/utils/update-notices.js +12 -0
  119. package/dist/src/utils/update-notices.js.map +1 -1
  120. package/package.json +1 -1
  121. package/.agents/skills/maestro-ralph-agent/SKILL.md +0 -697
  122. package/.agents/skills/maestro-ralph-agent-execute/SKILL.md +0 -461
  123. package/.agy/skills/maestro-ralph-agent/SKILL.md +0 -696
  124. package/.agy/skills/maestro-ralph-agent-execute/SKILL.md +0 -457
  125. package/.claude/commands/maestro-ralph-agent-execute.md +0 -459
  126. package/.claude/commands/maestro-ralph-agent.md +0 -695
@@ -0,0 +1,935 @@
1
+ ---
2
+ name: maestro-ralph-v2
3
+ description: Adaptive lifecycle orchestrator — compose, dispatch ralph-executor agent, evaluate decision, loop
4
+ argument-hint: <intent> [-y] [--amend [change]] [--roadmap] | status | continue
5
+ allowed-tools:
6
+ - ask_question
7
+ - define_subagent
8
+ - grep_search
9
+ - invoke_subagent
10
+ - manage_subagents
11
+ - replace_file_content
12
+ - run_command
13
+ - send_message
14
+ - view_file
15
+ - write_to_file
16
+ agy-subagents:
17
+ - ralph-executor
18
+ ---
19
+
20
+ ## Sub-Agent Registration (Antigravity)
21
+
22
+ Before any `invoke_subagent` call below, register each sub-agent type once per session by reading the system_prompt from `<agy-agents-dir>/<name>.md` and passing it to `define_subagent`. The `<agy-agents-dir>` is:
23
+ - global install: `~/.gemini/antigravity-cli/agents/`
24
+ - workspace install: `<project>/.agents/agents/`
25
+
26
+ - `define_subagent(name="ralph-executor", description="<from agents/ralph-executor.md frontmatter>", system_prompt=<contents of agents/ralph-executor.md body>, enable_write_tools=true, enable_mcp_tools=true, enable_subagent_tools=false)`
27
+
28
+ **ConversationId tracking**: `invoke_subagent` returns a ConversationId per spawned instance. Subsequent `send_message(Recipient=<ConversationId>, Message=...)` calls require that ConversationId — never use the role name as the recipient.
29
+
30
+ ---
31
+ <purpose>
32
+ Adaptive lifecycle orchestrator: locate step → resolve args → load context → dispatch invoke_subagent(ralph-executor) per step (agent 调 `ralph next` + 执行) → extract signals → drift check → ralph complete → evaluate decision → next step → loop.
33
+
34
+ Session: `.workflow/.maestro/ralph-v2-{YYYYMMDD-HHmmss}/status.json`
35
+ </purpose>
36
+
37
+ <deferred_reading>
38
+ - [ralph-amend-goal.md](~/.maestro/workflows/ralph-amend-goal.md) — read when `--amend` flag active for goal amendment flow
39
+ </deferred_reading>
40
+
41
+ <context>
42
+ $ARGUMENTS — intent text, flags, or keywords.
43
+
44
+ **Parse:**
45
+ ```
46
+ -y flag → auto_confirm = true
47
+ --roadmap → wants_roadmap = true
48
+ --amend / -a → amend_mode = true
49
+ .md/.txt path → input_doc
50
+ status|continue → route keyword
51
+ Remaining → intent (amend_mode 时为 change_request)
52
+ ```
53
+
54
+ **State files**:
55
+ - `.workflow/state.json` — artifact registry
56
+ - `.workflow/.maestro/ralph-v2-*/status.json` — session state
57
+ </context>
58
+
59
+ <invariants>
60
+ 1. **Ralph-v2 owns the full loop** — locate step → resolve args → load context → dispatch agent → wait for send_message → receive → extract signals → drift → complete,全部在本命令内完成
61
+ 2. **One agent per step** — 每个执行 step 派发一个 named executor agent,agent 通过 send_message 回传结果,主流程解析结果后决定下一步
62
+ 3. **Agent is a thin wrapper** — executor agent 调 `ralph next` 获取 skill prompt 并执行,通过 send_message 回传输出;arg resolution、context loading、signal extraction、drift analysis、ralph complete 均由主流程完成
63
+ 4. **Dual dispatch model** — 执行 Agent 与评估 Agent 使用不同派发模式:
64
+ - **执行 Agent**(A_STEP_DISPATCH):`invoke_subagent([{ TypeName: "<TypeName>", Role: "exe-xxx", Prompt: "<Prompt>", Workspace: "inherit" }])` — named mailbox teammate,支持内部多 agent 编排,通过 `send_message({to: "main"})` 回传结果
65
+ - **评估 Agent**(A_AGENT_EVALUATE / A_AGENT_GOAL_AUDIT / A_AGENT_REGROUND):`invoke_subagent()` 不传 `name` — 同步阻塞,直接返回结果(评估 agent 只读不需要多 agent)
66
+ - `agent_exec_name` 既用于 display/日志,也作为执行 Agent 的 `name` 参数
67
+ 5. **主流程调 `ralph complete`** — 每个 step 完成后由主流程调 `maestro ralph complete`,非 agent 上报
68
+ 6. **Decision evaluation inline** — decision 节点不 handoff,通过 Agent 或 CLI delegate 在本循环内评估
69
+ 7. **CLI delegation for evaluation only** — CLI delegate(`maestro delegate --mode analysis`)仅限评估环节;执行仍通过 executor Agent 完成
70
+ 8. **Decision delegates read-only** — 评估 Agent 通过 prompt 中的 CONSTRAINTS 约束为只读
71
+ 9. **执行 step 通过 `maestro ralph next` CLI 加载并内联执行**(由 execute Agent 完成)
72
+ 10. **status.json 是唯一真源** — 不生成 markdown 清单或侧文件
73
+ 11. **每个 step 必须 `completion_confirmed: true`** — 由 `maestro ralph complete N --status DONE`(或 DONE_WITH_CONCERNS)写入;CLI 是唯一合法写入路径
74
+ 12. **command_path 在 A_BUILD_STEPS 解析** — 通过 `maestro ralph skills --platform agy --json --quiet` 预校验
75
+ 13. **执行 step 加载契约** — 由 `maestro ralph next` CLI 在执行期完成
76
+ 14. **Decomposition is outcome-oriented** — sub-goals 为可观测交付,禁止 lifecycle 复刻
77
+ 15. **planning_mode governs arg granularity** — `unified` → skill args 无 `{phase}`;`independent` → 含 `{phase}`
78
+ 16. **task_decomposition 驱动 steps[] 动态生长** — `post-goal-audit` 按 unmet 子目标插入 scoped mini-loop
79
+ 17. **Invariant violation = BLOCK** — 违反上述任一 invariant 即阻断当前操作
80
+ 18. **Evaluate fallback 必须标记** — 评估 Agent 解析 verdict 失败时 fallback 为 "fix",MUST 在 decisions.ndjson 记录 `"parse_failed": true, "confidence_score": 0`
81
+ 19. **auto_confirm 单一来源** — `auto_confirm` 仅由用户 `-y` 标志设定
82
+ 20. **分解契约单一所有者** — `boundary_contract` / `task_decomposition` 由 session 创建者拥有
83
+ 21. **控制权优先级(范式治理)** — FSM 独占 session 生命周期 + step 排序 + retry/fix/escalate + cross-step decision 节点
84
+ </invariants>
85
+
86
+ <state_machine>
87
+
88
+ Chain-building states + 执行循环 states:
89
+
90
+ <states>
91
+ S_PARSE_ROUTE — 解析参数、路由入口
92
+ S_STATUS — 显示 session 进度
93
+ S_CONTINUE — 恢复执行
94
+ S_RESOLVE_PHASE — 解析 phase + phase_is_new + milestone PERSIST: session.phase, session.phase_is_new, session.milestone
95
+ S_INFER — 推断 lifecycle_position PERSIST: session.lifecycle_position, session.wants_roadmap
96
+ S_RESOLVE_SCOPE — 读 macro analyze conclusions.scope_verdict PERSIST: session.scope_verdict, session.analyze_macro_id
97
+ S_QUALITY_MODE — 决定质量管线模式 PERSIST: session.quality_mode
98
+ S_PLANNING_MODE — 决定统一/独立规划模式 PERSIST: session.planning_mode
99
+ S_DECOMPOSE — 边界澄清 + 执行准则 + 子目标清单 PERSIST: session.boundary_contract, .execution_criteria, .task_decomposition
100
+ S_BUILD_CHAIN — 构建步骤链(build rules 0-14) PERSIST: session.steps[]
101
+ S_CREATE_SESSION — 写 status.json PERSIST: session (全量)
102
+ S_CONFIRM — 用户确认
103
+
104
+ S_STEP_LOCATE — 找下一个 pending step PERSIST: —
105
+ S_STEP_RESOLVE — 解析占位符 + 丰富参数 PERSIST: step.args (enriched)
106
+ S_STEP_DISPATCH — 组装上下文 + 派发 named executor agent PERSIST: step.agent_exec_name, step.status = "running"
107
+ S_STEP_WAIT_MSG — 等待 executor 的 send_message 回传 PERSIST: —
108
+ S_STEP_ANALYZE — 提取信号 + 组装 completion 参数 PERSIST: —
109
+ S_STEP_DRIFT — 产物 vs 目标偏离分析 PERSIST: step.drift_score
110
+ S_STEP_COMPLETE — 调 `ralph complete` 上报 PERSIST: step.completion_*
111
+ S_DECISION_EVAL — 启动分析 Agent 评估质量门 PERSIST: —
112
+ S_APPLY_VERDICT — 应用裁决 PERSIST: session.steps[]
113
+ S_SESSION_DONE — 所有 step 完成 PERSIST: session.status
114
+ S_HANDLE_FAIL — 处理失败 PERSIST: step.status
115
+ S_AMEND_GOAL — 修改 running session 目标 PERSIST: session.task_decomposition, .boundary_contract, .goal_changelog, .steps[]
116
+ S_FALLBACK — 请求用户输入 PERSIST: —
117
+ </states>
118
+
119
+ <transitions>
120
+
121
+ S_PARSE_ROUTE:
122
+ → S_STATUS WHEN: intent == "status"
123
+ → S_CONTINUE WHEN: intent == "continue"
124
+ → S_AMEND_GOAL WHEN: amend_mode == true AND running session exists
125
+ → S_FALLBACK WHEN: amend_mode == true AND no running session
126
+ → S_DECISION_EVAL WHEN: running session with decision step in "running" status
127
+ → S_RESOLVE_PHASE WHEN: intent is non-empty
128
+ → S_FALLBACK WHEN: no intent AND no running session
129
+
130
+ S_STATUS:
131
+ → END DO: A_SHOW_STATUS
132
+
133
+ S_CONTINUE:
134
+ → S_STEP_LOCATE WHEN: running session found
135
+ → S_FALLBACK WHEN: no running session
136
+
137
+ S_AMEND_GOAL:
138
+ → S_STEP_LOCATE WHEN: change applied + user confirmed DO: A_AMEND_GOAL
139
+ → END WHEN: user cancels
140
+ GUARD: RISK_LEVEL=high → auto_confirm 无效
141
+
142
+ S_CREATE_SESSION:
143
+ → S_CONFIRM WHEN: not auto_confirm
144
+ → S_STEP_LOCATE WHEN: auto_confirm
145
+
146
+ S_CONFIRM:
147
+ → S_STEP_LOCATE WHEN: user confirms
148
+ → S_BUILD_CHAIN WHEN: user edits
149
+ → END WHEN: user cancels
150
+
151
+ S_STEP_LOCATE:
152
+ → S_STEP_RESOLVE WHEN: pending execution step found (step.decision == null)
153
+ → S_DECISION_EVAL WHEN: pending decision step found (step.decision != null)
154
+ → S_SESSION_DONE WHEN: no pending steps (all completed/skipped)
155
+ → S_HANDLE_FAIL WHEN: has failed step and no pending
156
+ → S_FALLBACK WHEN: no running session
157
+
158
+ S_STEP_RESOLVE:
159
+ → S_STEP_DISPATCH DO: A_STEP_RESOLVE_ARGS
160
+
161
+ S_STEP_DISPATCH:
162
+ → S_STEP_WAIT_MSG WHEN: executor dispatched DO: A_STEP_DISPATCH
163
+
164
+ S_STEP_WAIT_MSG:
165
+ → S_STEP_ANALYZE WHEN: received agent-message with EXECUTOR_OUTPUT DO: A_STEP_RECEIVE
166
+ → S_HANDLE_FAIL WHEN: received agent-message with status=ERROR DO: A_STEP_RECEIVE
167
+ → S_HANDLE_FAIL WHEN: executor idle without send_message(崩溃检测) DO: mark BLOCKED
168
+
169
+ S_STEP_ANALYZE:
170
+ → S_STEP_DRIFT WHEN: STATUS == DONE|DONE_WITH_CONCERNS DO: A_STEP_EXTRACT
171
+ → S_HANDLE_FAIL WHEN: STATUS == NEEDS_RETRY|BLOCKED DO: A_STEP_EXTRACT
172
+
173
+ S_STEP_DRIFT:
174
+ → S_STEP_COMPLETE WHEN: ALIGNED|MINOR_DRIFT DO: A_STEP_DRIFT_ANALYZE
175
+ → S_STEP_DISPATCH WHEN: MAJOR_DRIFT + not retried DO: A_STEP_DRIFT_ANALYZE (ralph retry + re-execute)
176
+ → S_STEP_COMPLETE WHEN: MAJOR_DRIFT + retried DO: A_STEP_DRIFT_ANALYZE (DONE_WITH_CONCERNS)
177
+
178
+ S_STEP_COMPLETE:
179
+ → S_STEP_LOCATE DO: A_STEP_COMPLETE (loop to next step)
180
+
181
+ S_DECISION_EVAL: (decision 节点 == `step.decision` 非空)
182
+ → S_APPLY_VERDICT WHEN: quality-gate (post-execute, post-business-test, post-review, post-test, post-frontend-verify)
183
+ DO: A_AGENT_EVALUATE
184
+ → S_APPLY_VERDICT WHEN: goal-gate (post-goal-audit)
185
+ DO: A_AGENT_GOAL_AUDIT
186
+ → S_APPLY_VERDICT WHEN: scope-gate (post-analyze-scope)
187
+ DO: A_SCOPE_EVALUATE
188
+ → S_APPLY_VERDICT WHEN: reground-gate (post-reground)
189
+ DO: A_AGENT_REGROUND
190
+ → S_APPLY_VERDICT WHEN: structural (post-milestone, post-debug-escalate)
191
+ DO: A_STRUCTURAL_EVALUATE
192
+
193
+ S_APPLY_VERDICT:
194
+ → S_STEP_LOCATE WHEN: verdict == "proceed" DO: A_APPLY_PROCEED
195
+ → S_STEP_LOCATE WHEN: post-goal-audit + has_unmet DO: A_APPLY_GOAL_FIX
196
+ → S_STEP_LOCATE WHEN: post-goal-audit + all_met + INTENT_ALIGNED=true DO: A_APPLY_GOAL_DONE
197
+ → END WHEN: post-goal-audit + all_met + INTENT_ALIGNED=false DO: A_REGROUND_HALT
198
+ → S_STEP_LOCATE WHEN: post-analyze-scope DO: A_APPLY_SCOPE_VERDICT
199
+ → S_STEP_LOCATE WHEN: verdict == "fix" DO: A_APPLY_FIX
200
+ → S_STEP_LOCATE WHEN: verdict == "escalate" DO: A_APPLY_ESCALATE
201
+ → S_STEP_LOCATE WHEN: post-milestone + standard + next milestone DO: A_ADVANCE_MILESTONE
202
+ → END WHEN: post-milestone + standard + no next milestone
203
+ → END WHEN: post-milestone + adhoc DO: mark completed (set current_milestone = null)
204
+ → END WHEN: post-debug-escalate DO: A_PAUSE_ESCALATE
205
+ → END WHEN: post-reground + drifted + confidence >= 60 DO: A_REGROUND_HALT
206
+ → S_STEP_LOCATE WHEN: post-reground + aligned DO: A_APPLY_PROCEED
207
+ → S_STEP_LOCATE WHEN: post-reground + drifted + confidence < 60 DO: A_APPLY_PROCEED (标 LOW CONFIDENCE)
208
+ GUARD: retry_count >= max_retries → force escalate
209
+ GUARD: confidence_score < 60 AND proceed → override to fix
210
+ GUARD: confidence_score > 95 AND fix AND retry > 0 → suggest proceed
211
+ GUARD: auto_confirm → skip user prompt, apply adjusted verdict
212
+ GUARD: not auto_confirm → ask_question with override options
213
+ GUARD: post-reground + drifted + confidence >= 60 → A_REGROUND_HALT(auto_confirm 不跳过)
214
+
215
+ S_HANDLE_FAIL:
216
+ → S_STEP_LOCATE WHEN: auto + not retried DO: A_RETRY
217
+ → END WHEN: auto + retried DO: A_PAUSE_SESSION
218
+ → S_STEP_LOCATE WHEN: interactive + retry
219
+ → S_STEP_LOCATE WHEN: interactive + skip
220
+ → END WHEN: interactive + abort
221
+
222
+ S_SESSION_DONE:
223
+ → END DO: A_COMPLETE_SESSION
224
+
225
+ </transitions>
226
+
227
+ <actions>
228
+
229
+ ### A_CREATE_SESSION
230
+ 1. `session_id` format: `ralph-v2-{YYYYMMDD-HHmmss}`
231
+ 2. Additional fields: `execution_mode: "agent"`,无 `cli_tool` 字段
232
+ 3. Each step: `agent_exec_name: null`(执行 Agent 名称标识)
233
+ 4. Step mode/role/rule assigned per stage (see Stage Mapping table)
234
+
235
+ ### A_STEP_RESOLVE_ARGS
236
+
237
+ 解析占位符 + 丰富参数。在 `ralph next` 之前执行。
238
+
239
+ **1. Placeholder substitution:**
240
+
241
+ | Placeholder | Source |
242
+ |-------------|--------|
243
+ | `{phase}` | session.phase |
244
+ | `{milestone}` | session.milestone |
245
+ | `{intent}` | session.intent |
246
+ | `{description}` | session.intent (alias) |
247
+ | `{scratch_dir}` | session.context.scratch_dir or latest artifact path |
248
+ | `{plan_dir}` | session.context.plan_dir |
249
+ | `{analysis_dir}` | session.context.analysis_dir |
250
+ | `{issue_id}` | session.context.issue_id |
251
+ | `{milestone_num}` | session.context.milestone_num |
252
+
253
+ **2. Per-skill enrichment** (when args empty or minimal):
254
+
255
+ | Skill | Required context | Source |
256
+ |-------|-----------------|--------|
257
+ | maestro-brainstorm | topic | `"{intent}"` |
258
+ | maestro-roadmap | description | `"{intent}"` |
259
+ | maestro-analyze | phase or topic | `{phase}` or `"{intent}"` |
260
+ | maestro-plan | phase, --from, or --dir | see --from auto-injection below |
261
+ | maestro-execute | phase or --dir | see --from auto-injection below |
262
+ | quality-debug | gap context | Read previous step's error/gap |
263
+ | quality-* | phase | `{phase}` |
264
+
265
+ **3. --from auto-injection (phase-level artifact chaining):**
266
+
267
+ ```
268
+ Read state.json.artifacts(含 milestone_history 内归档 artifacts)
269
+ → filter by milestone={session.milestone} + phase={session.phase} + status=="completed"
270
+
271
+ plan step(含 {phase} 占位符,args 无 --from 且无 --dir):
272
+ 1. 查同 phase+milestone 最新 completed type=="analyze" artifact → id = ANL-xxx
273
+ 2. 命中 → args 追加 --from analyze:{id}
274
+ 3. 写 step.source_artifact_ref = "analyze:{id}"
275
+
276
+ execute step(含 {phase} 占位符,args 无 --dir):
277
+ 1. 查同 phase+milestone 最新 completed type=="plan" artifact → id = PLN-xxx, path = scratch/...
278
+ 2. 命中 → args 追加 --dir .workflow/scratch/{path}
279
+ 3. 写 step.source_artifact_ref = "plan:{id}"
280
+ ```
281
+
282
+ 兜底:查询无结果 → 不注入,由命令自身 discovery 逻辑处理。已有 `--from` 或 `--dir` 的 step 不覆盖。
283
+
284
+ **4. Goal context injection:**
285
+
286
+ 当 `step.goal_ref` 非空且 `session.task_decomposition` 存在时:
287
+ ```
288
+ goal = session.task_decomposition.find(g => g.id == step.goal_ref)
289
+ if goal:
290
+ goal_snippet = { id: goal.id, goal: goal.goal, done_when: goal.done_when,
291
+ boundary: goal.boundary, evidence: goal.evidence }
292
+ → 传递给 A_STEP_DISPATCH 注入 agent prompt
293
+ ```
294
+
295
+ **5. Write** enriched args + source_artifact_ref back to status.json.
296
+
297
+ ### A_STEP_DISPATCH
298
+
299
+ 加载前序产出 + 组装上下文 + 派发 executor agent 执行单步。Agent 内部调 `maestro ralph next` 获取 skill prompt 并执行。
300
+
301
+ **1. Load previous step context:**
302
+
303
+ - 读前一 completed step 的 `completion_summary` + `completion_caveats` + `completion_decisions` + `completion_deferred`
304
+ - 按 `session.context` 中的路径逐个 Read,提取与当前 step 相关的内容:
305
+
306
+ | 当前 stage | 加载什么 | Source |
307
+ |-----------|---------|--------|
308
+ | plan | analysis conclusions + scope_verdict | `{context.analysis_dir}/conclusions.json` |
309
+ | execute | task list + wave assignments | `{context.plan_dir}/TASK-*.json` |
310
+ | review | changed files + verification results | `{context.scratch_dir}/verification.json` |
311
+ | test | review findings | `review.json` |
312
+ | debug | error traces + failing test details | 前一 step 的 `completion_evidence` |
313
+ | brainstorm | grill report | `{context.grill_id}` report |
314
+
315
+ - Explore if needed — 产物指向代码位置但缺少上下文 → `maestro explore` 补充(仅 execute/debug/test 且有文件路径引用时)
316
+ - Accumulated signals — 遍历 ALL completed steps → 聚合 caveats + deferred
317
+
318
+ **2. Goal context pre-injection:**
319
+
320
+ - GUARD: `ralph_protocol_version >= "2"` → skip(session_anchor 已含 goal context)
321
+ - WHEN `ralph_protocol_version < "2"` 或缺失 AND `step.goal_ref` 非空 → 组装 `<goal_context>` 块注入 prompt:
322
+ ```
323
+ <goal_context>
324
+ Sub-goal: {goal.id} — {goal.goal}
325
+ Done when: {goal.done_when}
326
+ Boundary: {goal.boundary}
327
+ Evidence target: {goal.evidence}
328
+ Execution criteria: {session.execution_criteria joined by '; '}
329
+ </goal_context>
330
+ ```
331
+
332
+ **3. Resolve agent name:** `{stage_prefix}-{session_id_short}-{HHmmss}`
333
+
334
+ | Stage | Prefix |
335
+ |-------|--------|
336
+ | grill | `grl` |
337
+ | brainstorm | `brn` |
338
+ | analyze-macro | `anm` |
339
+ | analyze | `ana` |
340
+ | plan | `pln` |
341
+ | execute | `exe` |
342
+ | review | `rev` |
343
+ | test | `tst` |
344
+ | debug | `dbg` |
345
+ | Other | `run` |
346
+
347
+ **4. Dispatch(named mailbox executor):**
348
+
349
+ > 执行 Agent 使用 `name` 参数派发为 named mailbox teammate,支持内部多 agent 编排。executor 通过 `send_message({to: "main"})` 回传执行结果。`resolved_agent_name` 同时用于 display 和 Agent `name` 参数。
350
+
351
+ ```
352
+ invoke_subagent({
353
+ name: "{resolved_agent_name}",
354
+ subagent_type: "ralph-executor",
355
+ description: "执行 step {index}: {step.skill}",
356
+ prompt: `Session: {session_id}
357
+ Agent name: {resolved_agent_name}
358
+
359
+ {goal_context 块,仅 protocol < 2 时}
360
+
361
+ {loaded_step_context}
362
+ `
363
+ })
364
+ ```
365
+
366
+ 5. Write `step.agent_exec_name` to status.json
367
+ 6. Display: `[{index}/{total}] ⟶ {step.skill} → {resolved_agent_name}`
368
+ 7. invoke_subagent() 立即返回(named teammate 异步启动)→ 进入 S_STEP_WAIT_MSG 等待 executor 的 send_message
369
+
370
+ ### A_STEP_RECEIVE
371
+
372
+ 从 executor 的 `agent-message` 中提取执行输出。
373
+
374
+ 1. 接收到 `<agent-message from="{resolved_agent_name}">` 后,提取 message 内容
375
+ 2. 解析 `EXECUTOR_OUTPUT` 格式:
376
+ - `status: DONE` → agent_output = message 内容,继续 S_STEP_ANALYZE
377
+ - `status: DONE_WITH_CONCERNS` → agent_output = message 内容,继续 S_STEP_ANALYZE
378
+ - `status: ERROR` → STATUS=BLOCKED,转 S_HANDLE_FAIL
379
+ 3. idle_notification 处理(区分正常等待与崩溃):
380
+ - 首次收到 `idle_notification`:executor 可能在等待 worker 回传,正常现象,继续等待
381
+ - 连续收到 2 次 `idle_notification` 且中间无 `agent-message`:向 executor 发送 `send_message({to: "{resolved_agent_name}", message: "请回报执行状态"})` 询问
382
+ - 询问后仍只收到 `idle_notification` 无 `agent-message`:STATUS=BLOCKED,转 S_HANDLE_FAIL
383
+ 4. `agent_output` = 提取的 message 内容
384
+
385
+ ### A_STEP_EXTRACT
386
+
387
+ 从 agent 返回的执行输出中提取结构化信号,用于 completion 参数组装。
388
+
389
+ **1. Stage-specific signal extraction:**
390
+
391
+ | Stage | 提取什么 | 写入字段 |
392
+ |-------|---------|---------|
393
+ | analyze | `conclusions.json` scope_verdict + key_findings | `--summary`, context.analysis_dir |
394
+ | plan | TASK-*.json 数量 + 主要模块 + 波次 | `--summary`, context.plan_dir |
395
+ | execute | 修改文件数 + verification passed/failed | `--summary`, `--evidence`, context.scratch_dir |
396
+ | review | verdict + findings 数量 + severity | `--summary`, `--decisions` |
397
+ | test | pass/fail 统计 | `--summary`, `--evidence` |
398
+ | debug | root cause + 修复内容 | `--summary`, `--decisions` |
399
+ | grill | 核心质疑点数量 | `--summary`, `--caveats`, context.grill_id |
400
+ | brainstorm | 候选方案数 + 推荐方案 | `--summary`, `--decisions`, context.brainstorm_dir |
401
+
402
+ **2. Artifact scanning** — Use Glob 查找执行期间新增/修改的产物:
403
+
404
+ | Pattern | Signal |
405
+ |---------|--------|
406
+ | `conclusions.json` | `analysis_dir` |
407
+ | `TASK-*.json` | `plan_dir` |
408
+ | `verification.json` | `scratch_dir` |
409
+ | `review.json` | review stage |
410
+ | `test-results.json`, `uat.md` | test stage |
411
+ | `grill-report.md` | `grill_id` |
412
+ | `.brainstorming/*` | `brainstorm_dir` |
413
+
414
+ **3. Output text signal extraction** — 从执行输出文本中提取:
415
+
416
+ | Signal pattern | 写入 |
417
+ |----------------|------|
418
+ | `ANL-xxx` (artifact ID) | `session.analyze_macro_id` |
419
+ | `PLN-xxx` (artifact ID) | `context.plan_dir` |
420
+ | `BLP-xxx` (artifact ID) | `session.blueprint_id` |
421
+ | `scratch_dir:` 或 `.workflow/scratch/` 路径 | `context.scratch_dir` |
422
+ | `plan_dir:` 路径 | `context.plan_dir` |
423
+ | `PHASE: N` | `session.context.phase` |
424
+
425
+ **4. STATUS determination:**
426
+
427
+ | 条件 | STATUS |
428
+ |------|--------|
429
+ | Skill 正常完成 + 有产物 | `DONE` |
430
+ | 完成但有 warnings/concerns | `DONE_WITH_CONCERNS` |
431
+ | 执行出错但可重试(临时错误、网络问题) | `NEEDS_RETRY` |
432
+ | 执行出错且无法重试(schema 错误、command_path 不可达) | `BLOCKED` |
433
+ | Agent 返回 null(崩溃/超时) | `BLOCKED` |
434
+
435
+ **5. Compose completion params:**
436
+
437
+ | Param | 规则 | 组装方法 |
438
+ |-------|------|---------|
439
+ | `--summary` | MUST。动词开头,≤100 字 | `"<动词><做了什么>,<量化结果>"` |
440
+ | `--decisions` | SHOULD。每条一个架构/技术决策 | 从执行中做出的非显而易见的选择 |
441
+ | `--caveats` | SHOULD。后续 step 须知 | 发现但不属于本步解决的问题 |
442
+ | `--deferred` | SHOULD。推迟工作项 | 被主动推迟的项 |
443
+ | `--evidence` | SHOULD。验证产物路径 | 指向验证结果文件 |
444
+ | `--concerns` | COND。仅 DONE_WITH_CONCERNS 时 | CAVEATS 内容同时映射为 --concerns |
445
+
446
+ ### A_STEP_DRIFT_ANALYZE
447
+
448
+ 产物 vs 目标偏离分析。A_STEP_EXTRACT 后、A_STEP_COMPLETE 前执行。
449
+
450
+ **1. 收集对照基准:**
451
+
452
+ | 基准来源 | 取值 |
453
+ |---------|------|
454
+ | `step.goal_ref` → goal.done_when | 子目标完成条件 |
455
+ | `session.boundary_contract.definition_of_done` | 全局验收标准 |
456
+ | `session.execution_criteria` | 执行准则 |
457
+ | `session.intent` | 原始意图 |
458
+
459
+ **2. 对比评分:**
460
+
461
+ | 维度 | 检查 |
462
+ |------|------|
463
+ | 覆盖度 | 产物是否覆盖 goal.done_when 每个条件 |
464
+ | 方向性 | decisions 是否与 intent/boundary 一致 |
465
+ | 完整性 | 预期产物类型是否齐全 |
466
+
467
+ **drift_score:**
468
+ - `ALIGNED` — 全部维度通过
469
+ - `MINOR_DRIFT` — 小缺口,不影响后续
470
+ - `MAJOR_DRIFT` — 方向性偏离或关键产物缺失
471
+
472
+ **3. 修正动作:**
473
+
474
+ | drift_score | 动作 |
475
+ |-------------|------|
476
+ | ALIGNED | 正常进入 S_STEP_COMPLETE |
477
+ | MINOR_DRIFT | 偏离项追加到 caveats,正常 complete |
478
+ | MAJOR_DRIFT + 未重试 | `run_command("maestro ralph retry {index}")` → 回到 S_STEP_DISPATCH 重执行(drift_correction 作修正上下文注入 prompt) |
479
+ | MAJOR_DRIFT + 已重试 | 以 DONE_WITH_CONCERNS complete |
480
+
481
+ **4. 写入:** `step.drift_score`, `step.drift_correction`
482
+
483
+ ### A_STEP_COMPLETE
484
+
485
+ 调 `ralph complete` 上报 + 传播上下文信号 + 循环。
486
+
487
+ 1. 使用 A_STEP_EXTRACT 组装的参数调用 `ralph complete`:
488
+ ```
489
+ run_command("maestro ralph complete {index} --status DONE --summary \"{SUMMARY}\" [--evidence ...] [--decisions ...] [--caveats ...] [--deferred ...]")
490
+ ```
491
+ DONE_WITH_CONCERNS 时 caveats 同时映射 `--concerns`。BLOCKED 时用 `--reason`。
492
+
493
+ 2. **Context signals propagation** — 将关键信号写入 `status.json.context`:
494
+
495
+ | Signal | 写入字段 |
496
+ |--------|---------|
497
+ | `analysis_dir` | `context.analysis_dir` |
498
+ | `plan_dir` | `context.plan_dir` |
499
+ | `scratch_dir` | `context.scratch_dir` |
500
+ | `grill_id` | `context.grill_id` |
501
+ | `brainstorm_dir` | `context.brainstorm_dir` |
502
+ | `blueprint_dir` | `context.blueprint_dir` |
503
+ | `ANL-xxx` | `session.analyze_macro_id` |
504
+ | `BLP-xxx` | `session.blueprint_id` |
505
+ | `phase` | `session.context.phase` |
506
+
507
+ 3. Display: `[{index}/{total}] ✓ {step.skill} → {SUMMARY}`
508
+ 4. Loop back to S_STEP_LOCATE
509
+
510
+ ### A_AGENT_EVALUATE
511
+
512
+ 通过 Agent 和/或 CLI delegate 评估质量门。评估模式由 `step.evaluate_via` 决定。
513
+
514
+ **1. Common setup:**
515
+
516
+ 1. Resolve artifact dir: `.workflow/scratch/{artifact.path}/` with fallback glob
517
+ 2. Parse decision metadata: `{ decision, retry_count, max_retries, evaluate_via }`
518
+ 3. Map result files:
519
+
520
+ | Decision | Files |
521
+ |----------|-------|
522
+ | post-execute | verification.json |
523
+ | post-business-test | .tests/auto-test/report.json |
524
+ | post-review | review.json |
525
+ | post-test | uat.md, .tests/test-results.json |
526
+ | post-frontend-verify | e2e-results.json |
527
+
528
+ 4. `evaluate_via` 默认值:`"agent"`(未设置时)
529
+
530
+ **2. Dispatch by mode:**
531
+
532
+ **Mode: `agent`(默认)** — 同步 Agent 评估:
533
+
534
+ ```
535
+ invoke_subagent({
536
+ description: "评估 {decision} 质量门(同步评估 Agent,不传 name)",
537
+ prompt: "PURPOSE: 评估 {decision} 质量门结果
538
+ TASK: 读取以下结果文件 | 分析状态 | 评估严重性 | 给出建议
539
+ FILES: {result_file_paths}
540
+ SESSION: {session_dir}/status.json
541
+ EXPECTED: 输出以下格式:
542
+ ---VERDICT---
543
+ STATUS: PASS|FAIL|PARTIAL|BLOCKED
544
+ REASON: <一句话原因>
545
+ GAP_SUMMARY: <差距摘要>
546
+ CONFIDENCE: high|medium|low
547
+ CONFIDENCE_SCORE: 0-100
548
+ WEAKEST_DIMENSION: <最弱维度>
549
+ ---END---
550
+ CONSTRAINTS: 只评估不修改文件 | 置信度<60%倾向 fix | retry {n}/{max} 达上限必须 escalate"
551
+ })
552
+ ```
553
+
554
+ **Mode: `cli`** — CLI delegate 评估(异步后台):
555
+
556
+ ```
557
+ run_command({
558
+ command: `maestro delegate "PURPOSE: 评估 ${decision} 质量门结果\nTASK: 读取 ${result_file_paths} | 分析状态 | 评估严重性\nEXPECTED: ---VERDICT--- 格式(STATUS/REASON/GAP_SUMMARY/CONFIDENCE_SCORE)\nCONSTRAINTS: 只评估不修改文件" --mode analysis --rule analysis-review-code-quality`,
559
+ run_in_background: true
560
+ })
561
+ ```
562
+ 等待 delegate 完成 → `maestro delegate output {exec_id}` 获取结果 → 解析 `---VERDICT---`
563
+
564
+ **Mode: `dual`** — Agent + CLI 并行评估,交叉验证:
565
+
566
+ 1. 先派发 CLI delegate(`run_in_background: true`)
567
+ 2. 同时派发同步 Agent(阻塞等待)
568
+ 3. Agent 返回后,检查 CLI delegate 状态(`maestro delegate status {exec_id}`)
569
+ 4. 合并裁决:
570
+
571
+ | Agent 结果 | CLI 结果 | 合并策略 |
572
+ |-----------|---------|---------|
573
+ | 两者一致 | — | 采用共识,confidence_score 取较高值 |
574
+ | Agent=PASS, CLI=FAIL | — | 降级为 PARTIAL,confidence_score 取平均值 |
575
+ | Agent=FAIL, CLI=PASS | — | 维持 FAIL(保守策略) |
576
+ | CLI 未返回 | — | 使用 Agent 结果,标 `"cli_pending": true` |
577
+
578
+ **3. Verdict parse + adjustment(所有模式通用):**
579
+
580
+ 5. Parse `---VERDICT---` block — STATUS must match strict enum `PASS|FAIL|PARTIAL|BLOCKED`; parse failure → fallback STATUS="fix", `parse_failed: true`, `confidence_score: 0` (invariant 18)
581
+ 6. Confidence adjustment: <60 + proceed → fix; >95 + fix + retry>0 → suggest proceed
582
+ 7. **Decision log**: Append to `{session_dir}/decisions.ndjson`:
583
+ ```json
584
+ { "id": "DEC-{timestamp}", "timestamp": "{ISO}", "source": "ralph-v2",
585
+ "node_id": "{step.decision}", "type": "quality-gate",
586
+ "evaluate_via": "{mode}", "cli_exec_id": "{exec_id|null}",
587
+ "verdict": "{adjusted_verdict}", "confidence_score": {N},
588
+ "parse_failed": false,
589
+ "close_call": {N>=50 && N<=70}, "summary": "{REASON}" }
590
+ ```
591
+
592
+ ### A_AGENT_GOAL_AUDIT
593
+
594
+ 通过 Agent 和/或 CLI delegate 审计子目标完成情况。支持 `evaluate_via` 三种模式(同 A_AGENT_EVALUATE)。
595
+
596
+ 1. Read `session.task_decomposition` from status.json
597
+ 2. Dispatch audit(按 `evaluate_via` 模式,默认 `agent`):
598
+ ```
599
+ invoke_subagent({
600
+ description: "审计子目标完成情况(同步评估 Agent,不传 name)",
601
+ prompt: "PURPOSE: 审计未完成子目标,判定 met / unmet
602
+ TASK:
603
+ 1. 读取 {session_dir}/status.json 中 task_decomposition 的 status!=done 子目标
604
+ 2. 打开 evidence 产物,对照 done_when 严格判定
605
+ 3. 输出 met / unmet,unmet 给出 gap + target_phase
606
+ 4. 对照 intent + definition_of_done 判定意图保真
607
+ CONTEXT:
608
+ status.json = {session_dir}/status.json
609
+ intent = {session.intent}
610
+ definition_of_done = {boundary_contract.definition_of_done}
611
+ execution_criteria = {execution_criteria}
612
+ boundary_contract = {boundary_contract}
613
+ EXPECTED:
614
+ ---VERDICT---
615
+ STATUS: all_met|has_unmet
616
+ INTENT_ALIGNED: true|false
617
+ UNMET: [{id:G2,gap:'...',target_phase:execute}, ...]
618
+ CONFIDENCE_SCORE: 0-100
619
+ ---END---
620
+ CONSTRAINTS: 只评估不修改文件 | 严格按 done_when 判定 | evidence 缺失→unmet"
621
+ })
622
+ ```
623
+ 3. On return: parse verdict, update task_decomposition status
624
+ 4. Append `{session_dir}/decisions.ndjson`:`{ "type": "goal-gate", "evaluate_via": "{mode}", "unmet_count": N, "unmet_ids": [...] }`
625
+ 5. Verdict routing: `all_met` + `INTENT_ALIGNED=true` → A_APPLY_GOAL_DONE;`all_met` + `INTENT_ALIGNED=false` → A_REGROUND_HALT;`has_unmet` → A_APPLY_GOAL_FIX
626
+ GUARD: retry_count >= max_retries AND still unmet → A_APPLY_ESCALATE
627
+
628
+ ### A_AGENT_REGROUND
629
+
630
+ 通过 Agent 和/或 CLI delegate 执行意图保真检查。支持 `evaluate_via` 三种模式(同 A_AGENT_EVALUATE)。
631
+
632
+ 1. Read status.json:intent, boundary_contract, completed steps, done goals
633
+ 2. Dispatch reground(按 `evaluate_via` 模式,默认 `agent`):
634
+ ```
635
+ invoke_subagent({
636
+ description: "意图保真检查(同步评估 Agent,不传 name)",
637
+ prompt: "PURPOSE: 意图保真检查 — 对照 intent 验证累积执行是否漂移
638
+ TASK:
639
+ 1. 读取 intent + boundary_contract.definition_of_done
640
+ 2. 读取已完成 steps 的 completion_evidence + 已 done 子目标
641
+ 3. 判定累积产出是否仍服务 intent
642
+ 4. 输出 aligned / drifted + drift_description + corrective_action
643
+ CONTEXT:
644
+ status.json = {session_dir}/status.json
645
+ intent = {session.intent}
646
+ definition_of_done = {boundary_contract.definition_of_done}
647
+ in_scope = {boundary_contract.in_scope}
648
+ out_of_scope = {boundary_contract.out_of_scope}
649
+ goal_changelog = {session.goal_changelog ?? []}
650
+ EXPECTED:
651
+ ---VERDICT---
652
+ STATUS: aligned|drifted
653
+ DRIFT_DESCRIPTION: <空或具体描述>
654
+ CORRECTIVE_ACTION: <空或建议>
655
+ CONFIDENCE_SCORE: 0-100
656
+ ---END---
657
+ CONSTRAINTS: 只评估不修改文件 | aligned 阈值≥80% | 单个 step 触碰 out_of_scope→直接 drifted"
658
+ })
659
+ ```
660
+ 3. On return: parse verdict
661
+ 4. Append `{session_dir}/decisions.ndjson`
662
+ 5. Verdict routing:aligned → A_APPLY_PROCEED;drifted + confidence >= 60 → A_REGROUND_HALT;drifted + confidence < 60 → A_APPLY_PROCEED (LOW CONFIDENCE)
663
+
664
+ ### A_SCOPE_EVALUATE
665
+
666
+ 仅由 `post-analyze-scope` 决策节点触发。
667
+
668
+ 1. 定位刚完成的 macro analyze artifact → `analyze_macro_id`, `conclusions_path`
669
+ 2. 读取 `conclusions.scope_verdict`(`large | medium | small`),缺失 → `unknown`
670
+ 3. 写入 `session.scope_verdict` + `session.analyze_macro_id`
671
+ 4. Append `{session_dir}/decisions.ndjson`:`{ "type": "scope-gate", "source": "ralph-v2", "verdict": "{scope_verdict}", "analyze_macro_id": "{ANL_ID}" }`
672
+
673
+ ### A_STRUCTURAL_EVALUATE
674
+
675
+ **post-milestone:**
676
+ 1. Read state.json → resolve milestone type(default `"standard"`)
677
+ 2. Standard milestone:next milestone exists → insert lifecycle steps / complete
678
+ 3. Adhoc milestone(`type == "adhoc"`):always END,set `current_milestone = null`
679
+
680
+ **post-debug-escalate:** always → A_PAUSE_ESCALATE
681
+
682
+ ### A_SHOW_STATUS
683
+
684
+ 1. Find latest `ralph-v2-*` session(by created_at)
685
+ 2. Display: Session, Status, Position, Progress, Current step
686
+ 3. List steps: [✓] confirmed, [▸] current, [ ] pending, [◆] decision;执行 step 附 `command_scope` + `command_path`
687
+ 4. If `task_decomposition` present → 显示 sub-goals 进度(done/total)
688
+
689
+ ### A_APPLY_PROCEED / A_APPLY_FIX / A_APPLY_ESCALATE
690
+
691
+ - **A_APPLY_PROCEED**: Mark decision completed, write status.json
692
+ - **A_APPLY_FIX**: Insert fix-loop steps after current step(见 Fix-Loop Templates),reindex,increment retry_count
693
+ - **A_APPLY_ESCALATE**: Insert `[quality-debug "{gap_summary}", decision:post-debug-escalate]`,reindex
694
+
695
+ ### A_APPLY_SCOPE_VERDICT
696
+
697
+ 依据 `session.scope_verdict` + `session.wants_roadmap` 重塑下游链路:
698
+
699
+ 1. 路径 A(`large` 且 `wants_roadmap`):保持 roadmap+analyze,`plan` 选 phase 列
700
+ 2. 路径 B(`medium`/`small`,或 `large` 非 `wants_roadmap`):删除未完成的 `roadmap` + `analyze` step,`plan` 改为 `--from analyze:{ANL_ID}`
701
+ 3. 路径 C(`unknown`):非 auto_confirm → ask_question;auto_confirm → 默认路径 B
702
+ 4. Reindex steps,标 decision completed
703
+
704
+ ### A_APPLY_GOAL_FIX / A_APPLY_GOAL_DONE
705
+
706
+ - **A_APPLY_GOAL_FIX**: 对每个 unmet 子目标插入 scoped mini-loop(plan --gaps + execute),`goal_ref` 标注,重新追加 `decision:post-goal-audit {retry+1}`
707
+ - **A_APPLY_GOAL_DONE**: set `task_decomposition[*].status="done"`, `completion_confirmed=true`, `task_decomposition_all_done=true`
708
+
709
+ ### A_ADVANCE_MILESTONE
710
+
711
+ 1. Update session: milestone, phase, reset passed_gates
712
+ 2. Insert full lifecycle steps for next milestone
713
+ 3. Reindex, write status.json
714
+
715
+ ### A_REGROUND_HALT / A_PAUSE_ESCALATE
716
+
717
+ - **A_REGROUND_HALT**: set `session.status = "paused"`,display drift warning + 恢复选项。auto_confirm 不跳过
718
+ - **A_PAUSE_ESCALATE**: set session paused,display "请人工介入",suggest continue
719
+
720
+ ### A_AMEND_GOAL
721
+
722
+ 运行中 session 的目标热修改。详细流程由 `<deferred_reading>` 加载 `ralph-amend-goal.md`。
723
+
724
+ | Phase | 行为 | 产出 |
725
+ |-------|------|------|
726
+ | 1. 快照 | 读 `task_decomposition` + `boundary_contract` + 已完成 steps 的 `completion_summary` | Display: 目标列表 + 进度 |
727
+ | 2. 解析 | `change_request` 非空 → 直接用;为空 → ask_question(修改/新增/移除/调整边界) | `change_type` + `change_request` |
728
+ | 3. Mini Grill | Agent 评估影响 | RISK_LEVEL + AFFECTED_GOALS + INVALIDATED_STEPS + NEW_GAPS |
729
+ | 4. 确认 | ask_question:应用并继续 / 仅改目标 / 取消 | 用户选择 |
730
+ | 5. 应用 | 归档旧目标(`superseded`)→ 写入新目标(`origin: CHG-xxx`)→ 重建链路 → write status.json | re-dispatch |
731
+
732
+ **Phase 3 Agent prompt:**
733
+ ```
734
+ invoke_subagent({
735
+ description: "Amend impact analysis(同步评估 Agent,不传 name)",
736
+ prompt: "PURPOSE: 评估目标修改对 running session 的影响
737
+ TASK:
738
+ 1. 读取 {session_dir}/status.json 的 task_decomposition + boundary_contract + 已完成 steps
739
+ 2. 分析 change_request 对既有目标/步骤的影响
740
+ 3. 判定 RISK_LEVEL (low/medium/high)
741
+ 4. 列出 AFFECTED_GOALS / INVALIDATED_STEPS / NEW_GAPS
742
+ CONTEXT:
743
+ change_request = {change_request}
744
+ change_type = {change_type}
745
+ session = {session_dir}/status.json
746
+ EXPECTED:
747
+ ---AMEND-VERDICT---
748
+ RISK_LEVEL: low|medium|high
749
+ AFFECTED_GOALS: [G1, G2, ...]
750
+ INVALIDATED_STEPS: [step indices]
751
+ NEW_GAPS: [gap descriptions]
752
+ RECOMMENDATION: <建议>
753
+ ---END---
754
+ CONSTRAINTS: 只评估不修改文件"
755
+ })
756
+ ```
757
+
758
+ GUARD: `RISK_LEVEL == high` → ask_question 不跳过(auto_confirm 无效)
759
+ GUARD: 已完成(`status: "done"`)的目标不可 supersede(skip + warn)
760
+ 旧目标标 `superseded`(`superseded_by` + `superseded_at`),新目标标 `origin: "CHG-xxx"`。`goal_changelog` 含完整 `before/after` + `impact_assessment`。
761
+
762
+ ### A_RETRY / A_PAUSE_SESSION / A_COMPLETE_SESSION
763
+
764
+ - **A_RETRY**: `run_command("maestro ralph retry {index}")` — CLI 设 `step.retried = true`, `step.status = "pending"`, 清 `active_step_index`
765
+ - **A_PAUSE_SESSION**: `ralph complete N --status BLOCKED --reason "..."` — CLI 写 `session.status = "paused"`
766
+ - **A_COMPLETE_SESSION**: 校验所有 step `completion_confirmed == true` + `task_decomposition_all_done == true`(若存在),通过后写 `session.status = "completed"`。完成后向所有 idle executor 发送 shutdown_request 清理:
767
+ ```
768
+ 遍历 steps[].agent_exec_name → send_message({to: name, message: {type: "shutdown_request"}})
769
+ ```
770
+
771
+ </actions>
772
+
773
+ </state_machine>
774
+
775
+ <appendix>
776
+
777
+ ### Stage Mapping
778
+
779
+ 执行 Agent 始终拥有完整工具集(read + write),由 skill 自身约束行为。Decision 评估 Agent 通过 prompt 中的 CONSTRAINTS 约束为只读。
780
+
781
+ | Stage | Skill (independent) | Skill (unified) | Decision after | quality_mode |
782
+ |-------|---------------------|-----------------|----------------|--------------|
783
+ | grill | `maestro-grill "{intent}"` | *(same)* | — | all |
784
+ | brainstorm | `maestro-brainstorm "{intent}"` | *(same)* | — | all |
785
+ | blueprint | `maestro-blueprint "{intent}"` | *(same)* | — | all |
786
+ | init | `maestro-init` | *(same)* | — | all |
787
+ | spec-setup | `spec-setup` | *(same)* | — | all |
788
+ | analyze-macro | `maestro-analyze "{intent}"` | *(same)* | `post-analyze-scope` | all |
789
+ | roadmap | `maestro-roadmap --from analyze:{id}` | *(same)* | — | all |
790
+ | analyze | `maestro-analyze {phase}` | `maestro-analyze` | — | all |
791
+ | plan | `maestro-plan {phase}` | `maestro-plan` | — | all |
792
+ | execute | `maestro-execute {phase}` | `maestro-execute` | `post-execute` | all |
793
+ | business-test | `quality-auto-test {phase}` | `quality-auto-test` | `post-business-test` | full only |
794
+ | review | `quality-review {phase}` | `quality-review` | `post-review` | all |
795
+ | test-gen | `quality-auto-test {phase}` | `quality-auto-test` | — | full / standard |
796
+ | test | `quality-test {phase}` | `quality-test` | `post-test` | full, standard |
797
+ | frontend-verify | `quality-test {phase} --frontend-verify` | `quality-test --frontend-verify` | `post-frontend-verify` | all (UI only) |
798
+ | milestone-audit | `maestro-milestone-audit` | *(same)* | — | all |
799
+ | goal-audit | *(decision-only)* | *(same)* | `post-goal-audit` | all |
800
+ | milestone-complete | `maestro-milestone-complete` | *(same)* | `post-milestone` | all |
801
+
802
+ Build rules 0-14 全部适用,包括 spec-setup 预检(rule 0.5)、grill auto_confirm 透传(rule 3.5)、frontend-verify UI 门控(rule 3.6)、re-grounding 插入(rule 5.5)等。
803
+
804
+ ### Session Schema
805
+
806
+ ```json
807
+ {
808
+ "session_id": "ralph-v2-{YYYYMMDD-HHmmss}",
809
+ "source": "ralph", "status": "running",
810
+ "execution_mode": "agent",
811
+ "ralph_protocol_version": "2",
812
+ "active_step_index": null,
813
+ "active_agent_name": null,
814
+ "intent": "", "lifecycle_position": "",
815
+ "phase": null, "phase_is_new": false,
816
+ "milestone": "",
817
+ "auto_mode": false,
818
+ "decomposition_owner": "ralph",
819
+
820
+ "quality_mode": "standard",
821
+ "planning_mode": "independent",
822
+ "scope_verdict": null,
823
+ "wants_roadmap": false,
824
+ "analyze_macro_id": null,
825
+ "blueprint_id": null,
826
+ "passed_gates": [],
827
+ "context": { "issue_id": null, "scratch_dir": null, "plan_dir": null,
828
+ "analysis_dir": null, "brainstorm_dir": null, "blueprint_dir": null },
829
+ "steps": [{
830
+ "index": 0,
831
+ "skill": "",
832
+ "args": "",
833
+ "stage": "",
834
+ "scope": null,
835
+ "decision": null,
836
+ "evaluate_via": "agent|cli|dual",
837
+ "retry_count": 0,
838
+ "max_retries": 2,
839
+ "command_scope": "global|project|missing|null",
840
+ "command_path": "<absolute path> | null",
841
+ "milestone_id": null,
842
+ "source_artifact_ref": null,
843
+ "status": "pending|running|completed|skipped|failed",
844
+ "goal_ref": null,
845
+ "completion_confirmed": false,
846
+ "completion_status": null,
847
+ "completion_evidence": null,
848
+ "completion_summary": null,
849
+ "completion_decisions": null,
850
+ "completion_caveats": null,
851
+ "completion_deferred": null,
852
+ "completed_at": null,
853
+ "deferred_reads": [],
854
+ "load": null,
855
+ "agent_exec_name": null,
856
+ "artifacts_produced": [],
857
+ "drift_score": null,
858
+ "drift_correction": null
859
+ }],
860
+ "waves": [], "current_step": 0,
861
+
862
+ "boundary_contract": {
863
+ "in_scope": [], "out_of_scope": [], "constraints": [], "definition_of_done": ""
864
+ },
865
+ "execution_criteria": [],
866
+ "task_decomposition": [
867
+ { "id": "G1", "goal": "", "boundary": "", "done_when": "",
868
+ "evidence": "", "lifecycle": [], "status": "pending|done|superseded",
869
+ "completion_confirmed": false, "completed_at": null,
870
+ "superseded_by": null, "superseded_at": null, "origin": null }
871
+ ],
872
+ "task_decomposition_all_done": false,
873
+
874
+ "goal_changelog": [
875
+ { "id": "CHG-001", "timestamp": "{ISO}",
876
+ "change_type": "modify|add|remove|boundary",
877
+ "reason": "",
878
+ "impact_assessment": { "risk_level": "low|medium|high",
879
+ "invalidated_steps": [], "new_steps_inserted": 0 },
880
+ "before": { "goals": [{"id":"G1","goal":"...","done_when":"..."}] },
881
+ "after": { "goals": [{"id":"G1v2","goal":"...","done_when":"..."}] } }
882
+ ]
883
+ }
884
+ ```
885
+
886
+ ### Fix-Loop Templates
887
+
888
+ 6 套 fix-loop templates(post-execute / post-business-test / post-review / post-test / post-frontend-verify / post-goal-audit)。插入的 step 通过 A_STEP_DISPATCH 派发 executor agent 逐步执行,由主流程调 `ralph complete` 上报。
889
+
890
+ ### Error Codes
891
+
892
+ E001–E006, W001–W004 适用。Agent 新增:
893
+
894
+ | Code | Severity | Description | Recovery |
895
+ |------|----------|-------------|----------|
896
+ | E014 | error | Agent execution failed (Agent returned null) | Retry once, then BLOCKED |
897
+ | E016 | error | Evaluation Agent verdict parse failed | Fallback fix + parse_failed: true |
898
+
899
+ ### Success Criteria
900
+
901
+ - [ ] ralph-v2 owns full step loop: locate → resolve → dispatch → wait → receive → extract → drift → complete → next
902
+ - [ ] One agent per step — `invoke_subagent([{ TypeName: "ralph-executor", Role: "<Role>", Prompt: "<Prompt>", Workspace: "inherit" }])` 每步派发一个 named executor
903
+ - [ ] Executor 内调 `maestro ralph next` 获取 skill prompt 并执行,支持内部多 agent 编排
904
+ - [ ] Executor 通过 `send_message({to: "main"})` 回传 `EXECUTOR_OUTPUT` 格式结果
905
+ - [ ] 主流程调 `maestro ralph complete` 上报(非 agent 上报)
906
+ - [ ] 主流程负责 arg resolution、context loading、signal extraction、drift analysis
907
+ - [ ] A_STEP_RECEIVE 从 executor 的 agent-message 中提取执行输出
908
+ - [ ] Executor 崩溃(idle 无 send_message)→ 询问 2 次后 STATUS=BLOCKED,转 S_HANDLE_FAIL
909
+ - [ ] Dual dispatch: 执行 Agent 传 `name`(async + send_message),评估 Agent 不传 `name`(sync)或 CLI delegate
910
+ - [ ] Decision evaluation 支持三种模式:agent(同步)、cli(CLI delegate)、dual(并行交叉验证)
911
+ - [ ] `evaluate_via` 字段控制评估模式,默认 `"agent"`
912
+ - [ ] dual 模式合并策略:一致取共识、分歧保守降级、CLI 未返回用 Agent 结果
913
+ - [ ] Verdict 解析保持 `---VERDICT---` 格式,parse 失败 → fallback fix + parse_failed: true
914
+ - [ ] decisions.ndjson 追加:source 字段为 `"ralph-v2"`
915
+ - [ ] Session schema: `execution_mode: "agent"`,`agent_exec_name`(执行 Agent name + display),含 `artifacts_produced`
916
+ - [ ] Chain building(S_RESOLVE_PHASE through S_BUILD_CHAIN)自包含执行
917
+ - [ ] A_STEP_DISPATCH 含前序产出加载(滑动窗口 5 step + accumulated signals + stage-specific artifacts)
918
+ - [ ] `agent_exec_name` 含 stage prefix(grl/brn/anm/ana/pln/exe/rev/tst/dbg)——同时用于 Agent name 参数和 display
919
+ - [ ] `--summary` 在 DONE/DONE_WITH_CONCERNS 时为 MUST(动词开头,≤100 字)
920
+ - [ ] CAVEATS 在 DONE_WITH_CONCERNS 时同时映射 --concerns
921
+ - [ ] A_STEP_EXTRACT 从 executor 输出提取 artifact IDs、path signals、phase signals
922
+ - [ ] A_STEP_DRIFT_ANALYZE:ALIGNED/MINOR_DRIFT → complete;MAJOR_DRIFT+未重试 → retry;MAJOR_DRIFT+已重试 → DONE_WITH_CONCERNS
923
+ - [ ] A_STEP_COMPLETE 将 context signals 写入 status.json.context
924
+ - [ ] A_AMEND_GOAL:完整 5 步流程 + deferred_reading ralph-amend-goal.md + Agent mini grill 含完整 prompt
925
+ - [ ] 旧目标标 superseded(superseded_by + superseded_at),新目标 origin: "CHG-xxx"
926
+ - [ ] goal_changelog 含完整 before/after + impact_assessment
927
+ - [ ] blueprint_id session 字段支持 --from blueprint:{BLP_ID} 路径
928
+ - [ ] spec-setup 预检(build rule 0.5)
929
+ - [ ] post-milestone adhoc 分支:mark completed + set current_milestone = null
930
+ - [ ] post-reground + drifted + confidence < 60 → A_APPLY_PROCEED (LOW CONFIDENCE)
931
+ - [ ] Fix-loop 插入的 step 通过 A_STEP_DISPATCH 逐步执行
932
+ - [ ] re-grounding 3-step 插入规则(build rule 5.5)不变
933
+ - [ ] A_REGROUND_HALT 漂移熔断(auto_confirm 不跳过)不变
934
+
935
+ </appendix>