ralphflow-dsh 2.3.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +47 -21
  2. package/graphs/codewiki/format.md +362 -0
  3. package/graphs/codewiki/graph.yaml +39 -0
  4. package/graphs/codewiki/nodes/assemble.md +24 -0
  5. package/graphs/codewiki/nodes/core-pages.md +17 -0
  6. package/graphs/codewiki/nodes/module-pages.md +18 -0
  7. package/graphs/codewiki/nodes/operations-pages.md +18 -0
  8. package/graphs/codewiki/nodes/survey.md +22 -0
  9. package/lib/asset-path.d.ts +59 -0
  10. package/lib/asset-path.js +181 -0
  11. package/lib/assets.d.ts +42 -0
  12. package/lib/assets.js +86 -0
  13. package/lib/client/phase.d.ts +29 -0
  14. package/lib/client/phase.js +86 -0
  15. package/lib/client/selection.d.ts +28 -0
  16. package/lib/client/selection.js +9 -0
  17. package/lib/client/status-source.d.ts +3 -1
  18. package/lib/client/status-source.js +3 -2
  19. package/lib/client/status.js +49 -13
  20. package/lib/client/viewer.d.ts +18 -0
  21. package/lib/client/viewer.js +540 -0
  22. package/lib/client.js +1159 -64
  23. package/lib/engine.d.ts +111 -47
  24. package/lib/engine.js +482 -334
  25. package/lib/facade.d.ts +175 -0
  26. package/lib/facade.js +553 -0
  27. package/lib/graph/agent-registry.d.ts +4 -0
  28. package/lib/graph/agent-registry.js +20 -0
  29. package/lib/graph/asset.d.ts +47 -0
  30. package/lib/graph/asset.js +276 -0
  31. package/lib/graph/assets.d.ts +47 -0
  32. package/lib/graph/assets.js +224 -0
  33. package/lib/graph/branches.d.ts +9 -0
  34. package/lib/graph/branches.js +13 -0
  35. package/lib/graph/check.d.ts +23 -0
  36. package/lib/graph/check.js +46 -0
  37. package/lib/graph/engine.d.ts +55 -0
  38. package/lib/graph/engine.js +2002 -0
  39. package/lib/graph/report.d.ts +9 -0
  40. package/lib/graph/report.js +117 -0
  41. package/lib/graph/state.d.ts +244 -0
  42. package/lib/graph/state.js +358 -0
  43. package/lib/graph/workspace.d.ts +68 -0
  44. package/lib/graph/workspace.js +262 -0
  45. package/lib/index.js +150 -47
  46. package/lib/owner.d.ts +34 -0
  47. package/lib/owner.js +49 -0
  48. package/lib/paths.d.ts +12 -0
  49. package/lib/paths.js +44 -0
  50. package/lib/pause.d.ts +12 -0
  51. package/lib/pause.js +19 -0
  52. package/lib/skills.d.ts +18 -31
  53. package/lib/skills.js +88 -44
  54. package/lib/status-contract.d.ts +114 -1
  55. package/lib/status-contract.js +106 -4
  56. package/lib/status-service.d.ts +5 -1
  57. package/lib/status-service.js +8 -1
  58. package/lib/tools.d.ts +14 -6
  59. package/lib/tools.js +90 -62
  60. package/lib/unfinished.d.ts +11 -0
  61. package/lib/unfinished.js +18 -0
  62. package/lib/verifier-preset.d.ts +40 -0
  63. package/lib/verifier-preset.js +126 -0
  64. package/lib/verify.d.ts +64 -10
  65. package/lib/verify.js +287 -77
  66. package/package.json +51 -38
  67. package/skills/ralphflow-create/SKILL.md +32 -0
  68. package/skills/ralphflow-create/graph-authoring.md +85 -0
  69. package/skills/ralphflow-create/matt/LICENSE +21 -0
  70. package/skills/ralphflow-create/matt/SHA256SUMS +6 -0
  71. package/skills/ralphflow-create/matt/SKILL-MECHANICS.md +22 -0
  72. package/skills/ralphflow-create/matt/SOURCE.md +12 -0
  73. package/skills/ralphflow-create/matt/grilling.md +30 -0
  74. package/skills/ralphflow-create/matt/to-spec.md +75 -0
  75. package/skills/ralphflow-create/matt/to-tickets.md +105 -0
  76. package/skills/ralphflow-create/matt/writing-for-agents.md +81 -0
  77. package/skills/ralphflow-create/ralphflow-authoring.md +31 -0
  78. package/skills/ralphflow-create/testing-workflow.md +60 -0
  79. package/skills/ralphflow-create/workflow-authoring.md +137 -0
  80. package/workflows/create-graph/steps/graph.md +17 -0
  81. package/workflows/create-graph/workflow.yaml +77 -0
  82. package/workflows/loop/workflow.yaml +23 -0
  83. package/workflows/spec/workflow.yaml +105 -0
  84. package/lib/create.d.ts +0 -10
  85. package/lib/create.js +0 -147
  86. package/workflows/loop.yaml +0 -45
  87. package/workflows/spec.yaml +0 -110
@@ -0,0 +1,2002 @@
1
+ /**
2
+ * Graph 执行引擎:DAG 调度器 + 节点 attempt + CHECK(经 Flow 的独立验证者)+ 人工审查门 +
3
+ * Git worktree / integration。门面按 `kind` 路由到这里;Flow 引擎一个字节都不经过本文件。
4
+ *
5
+ * 宪法对齐:
6
+ * - 唯一写入者:本模块是 Graph 实例 `state.json` 的唯一写入者;门面只路由。
7
+ * - 不存派生量:state 只有 attempts/submissions/verdicts/acceptances/todos/integration/
8
+ * worktrees;节点状态、当前节点、等待原因由 `graph/state.ts` 现算。
9
+ * - T1:CHECK 只走 `ports.verify`(`src/verify.ts`);节点 agent 看不到验证者会话,验证者
10
+ * 看不到执行者自述。
11
+ * - T2:节点释放、返工、快进顺序由本调度器决定;节点在自己的分支上合并集成分支,
12
+ * 引擎按节点分支验收,只前进集成分支引用。
13
+ */
14
+ import fs from "node:fs";
15
+ import { normalizeUnfinished } from "../unfinished.js";
16
+ import path from "node:path";
17
+ import { createHash, randomUUID } from "node:crypto";
18
+ import { defineTool } from "@deepseek-ai/dsh-tools";
19
+ import { pauseLabel } from "../pause.js";
20
+ import { OWNER_HEARTBEAT_REFRESH_MS, ownerAlive, ownerRecheckMs, runtimeId, stampOwner } from "../owner.js";
21
+ import { RALPH_FLOW_DIR, SUBMIT_REMINDER_STALL_LIMIT, makeArtifactsDirName, } from "../engine.js";
22
+ import { graphAssetHash, } from "./asset.js";
23
+ import { checkDefinition, checkVersion } from "./check.js";
24
+ import { assetReferenceSection, assetRootOf } from "../asset-path.js";
25
+ import { graphWorkspaceDir, listGraphWorkflows, loadGraphWorkflow, } from "./assets.js";
26
+ import { acceptanceOfNode, attemptsOfNode, graphArtifactsDirOf, graphArtifactsRootOf, graphInstanceDirOf, graphInstancesDirOf, graphNodeArtifactDirOf, graphReportsDirOf, graphRootOf, graphStatePathOf, isGraphTerminal, latestAttemptOfNode, listGraphStates, nodeNameOf, nodeReleased, nodeStatusOf, projectionOf, pushGraphHistory, readGraphState, verdictOfAttempt, waitingTodoOfNode, writeGraphState, } from "./state.js";
27
+ import { buildGraphReport } from "./report.js";
28
+ import { registerGraphAgent, unregisterGraphAgent } from "./agent-registry.js";
29
+ import { advanceIntegration, branchTip, captureWorkspaceChanges, ensureIntegrationBranch, ensureNodeWorktree, integrationBranchFor, nodeBranchFor, nodeReadyForIntegration, nodeWorktreePathOf, removeCleanWorktree, resolveProject, workspaceRelative, worktreeRootOf, } from "./workspace.js";
30
+ const MAX_CHECK_REWORKS = 2;
31
+ /** 「合入集成分支」失败的重试上限:并行节点临近交卷时的竞态,重做一次很便宜。 */
32
+ const MAX_INTEGRATION_RETRIES = 5;
33
+ const MAX_LOG_SIZE_BYTES = 10 * 1024 * 1024;
34
+ const MAX_LOG_ROTATIONS = 3;
35
+ const logLabel = (level) => level;
36
+ function msg(error) {
37
+ return error instanceof Error ? error.message : String(error);
38
+ }
39
+ function now() {
40
+ return new Date().toISOString();
41
+ }
42
+ function sha256File(file) {
43
+ const content = fs.readFileSync(file);
44
+ return { sha256: createHash("sha256").update(content).digest("hex"), size: content.byteLength };
45
+ }
46
+ function uniqueId(asset) {
47
+ const slug = asset.id.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 16) || "graph";
48
+ return `${slug}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
49
+ }
50
+ function relOrAbsolute(workspace, absolute) {
51
+ return workspaceRelative(workspace, absolute) ?? absolute;
52
+ }
53
+ function syntheticStep(node, criteria) {
54
+ return { id: node.id, do: node.do, check: criteria, desc: node.name ?? node.id };
55
+ }
56
+ function syntheticWorkflow(asset) {
57
+ return { name: asset.id, description: asset.description, steps: [], warnings: [] };
58
+ }
59
+ /** 简易审批语义:人话里的“批准/放行”与“改稿要求”。与参考实现同一套词表。 */
60
+ const APPROVAL_TEXT = /(?:^|[^a-z])(?:approve|approved|approval)(?:$|[^a-z])|批准|放行|同意(?:放行|交付|通过)|通过(?:这个|这|该|此)?(?:版本|产物|交付)/i;
61
+ const NEGATED_APPROVAL_TEXT = /(?:not|never|don['’]?t|do not|no)\s+(?:approve|approved|approval)|(?:不|未|没有|暂不)\s*(?:批准|放行|通过)/i;
62
+ const REVISION_TEXT = /改|修改|调整|补充|增加|加上|加入|加一个|添加|重写|返工|更新|修正|删掉|删除|移除|revise|rework|modify|change|rewrite|update|edit|add|remove|adjust/i;
63
+ function classifyManualResponse(text) {
64
+ const approval = APPROVAL_TEXT.test(text) && !NEGATED_APPROVAL_TEXT.test(text);
65
+ const revisionText = text.replace(/(?:no|without)\s+(?:further\s+)?changes?(?:\s+(?:needed|required))?|无需(?:修改|改动)|没有(?:修改|改动)|不用改/gi, " ");
66
+ const revision = REVISION_TEXT.test(revisionText);
67
+ if (approval && revision)
68
+ return { kind: "clarify", reason: "conflicting_intent" };
69
+ if (approval)
70
+ return { kind: "approve" };
71
+ if (revision)
72
+ return { kind: "revise" };
73
+ return { kind: "clarify", reason: "not_explicit" };
74
+ }
75
+ export function createGraphEngine(options) {
76
+ const { ctx, ports, workspace } = options;
77
+ const root = graphRootOf(workspace);
78
+ const graphsDir = graphWorkspaceDir(workspace);
79
+ const instancesDir = graphInstancesDirOf(workspace);
80
+ const reportsDir = graphReportsDirOf(workspace);
81
+ const artifactsRoot = graphArtifactsRootOf(workspace);
82
+ const runs = new Map();
83
+ const agentBindings = new Map();
84
+ const log = (level, event, data) => {
85
+ try {
86
+ ports.log?.(level, event, data);
87
+ }
88
+ catch { }
89
+ };
90
+ function ensureLayout() {
91
+ for (const dir of [root, graphsDir, instancesDir, reportsDir, artifactsRoot]) {
92
+ try {
93
+ fs.mkdirSync(dir, { recursive: true });
94
+ }
95
+ catch { }
96
+ }
97
+ }
98
+ function instanceDir(instId) {
99
+ return graphInstanceDirOf(workspace, instId);
100
+ }
101
+ function logFileOf(instId) {
102
+ return path.join(instanceDir(instId), "execution.log");
103
+ }
104
+ function archivedLogOf(instId) {
105
+ return path.join(reportsDir, `${instId}-execution.log`);
106
+ }
107
+ function rotateLog(file) {
108
+ let size = 0;
109
+ try {
110
+ size = fs.statSync(file).size;
111
+ }
112
+ catch {
113
+ return;
114
+ }
115
+ if (size < MAX_LOG_SIZE_BYTES)
116
+ return;
117
+ try {
118
+ fs.rmSync(`${file}.${MAX_LOG_ROTATIONS}`, { force: true });
119
+ }
120
+ catch { }
121
+ for (let index = MAX_LOG_ROTATIONS - 1; index >= 1; index--) {
122
+ try {
123
+ fs.renameSync(`${file}.${index}`, `${file}.${index + 1}`);
124
+ }
125
+ catch { }
126
+ }
127
+ try {
128
+ fs.renameSync(file, `${file}.1`);
129
+ }
130
+ catch { }
131
+ }
132
+ function logEvent(instId, level, event, extra) {
133
+ try {
134
+ if (!fs.existsSync(instanceDir(instId)))
135
+ return;
136
+ const file = logFileOf(instId);
137
+ rotateLog(file);
138
+ const payload = extra ? { ...extra } : {};
139
+ delete payload.instId;
140
+ fs.appendFileSync(file, `${JSON.stringify({ ts: now(), level, event, instId, ...payload })}\n`, "utf-8");
141
+ }
142
+ catch (error) {
143
+ log("warn", "execution_log_write_failed", { instId, event, error: msg(error) });
144
+ }
145
+ }
146
+ function archiveExecutionLog(instId) {
147
+ const source = logFileOf(instId);
148
+ try {
149
+ if (!fs.existsSync(source))
150
+ return null;
151
+ fs.mkdirSync(reportsDir, { recursive: true });
152
+ const target = archivedLogOf(instId);
153
+ fs.copyFileSync(source, target);
154
+ return target;
155
+ }
156
+ catch (error) {
157
+ log("warn", "execution_log_archive_failed", { instId, error: msg(error) });
158
+ return null;
159
+ }
160
+ }
161
+ function writeReport(run) {
162
+ const reportPath = path.join(reportsDir, `${run.instId}.md`);
163
+ try {
164
+ fs.mkdirSync(reportsDir, { recursive: true });
165
+ const artifactsRelDir = `${RALPH_FLOW_DIR}/artifacts/${run.state.artifacts_dir_name}/nodes`;
166
+ const content = buildGraphReport(run.state, {
167
+ instanceId: run.instId,
168
+ workspace,
169
+ statePath: graphStatePathOf(workspace, run.instId),
170
+ reportPath,
171
+ artifactsRelDir,
172
+ });
173
+ const tmp = path.join(reportsDir, `.${run.instId}.${process.pid}.tmp`);
174
+ fs.writeFileSync(tmp, content, "utf-8");
175
+ fs.renameSync(tmp, reportPath);
176
+ return reportPath;
177
+ }
178
+ catch (error) {
179
+ log("warn", "report_write_failed", { instId: run.instId, error: msg(error) });
180
+ return null;
181
+ }
182
+ }
183
+ function persist(run) {
184
+ try {
185
+ writeGraphState(workspace, run.state, run.instId);
186
+ ports.statusChanged?.();
187
+ }
188
+ catch (error) {
189
+ log("error", "graph_state_write_failed", { instId: run.instId, error: msg(error) });
190
+ }
191
+ }
192
+ /**
193
+ * 属主心跳:只刷新本运行时拥有的 `running` run。暂停/等待/结束后不再刷 ——
194
+ * 那几个状态本来就该由任何 host 接管,也不该因为属主没了被判成中断。
195
+ */
196
+ let ownerBeat;
197
+ function ensureOwnerBeat() {
198
+ if (ownerBeat)
199
+ return;
200
+ ownerBeat = setInterval(() => {
201
+ for (const run of runs.values()) {
202
+ if (run.state.active !== true || run.state.graph.status !== "running")
203
+ continue;
204
+ if (run.state.owner_runtime !== runtimeId())
205
+ continue;
206
+ run.state.owner_heartbeat_at = Date.now();
207
+ persist(run);
208
+ }
209
+ }, OWNER_HEARTBEAT_REFRESH_MS);
210
+ ownerBeat.unref?.();
211
+ }
212
+ ensureOwnerBeat();
213
+ function history(run, event, detail, nodeId, level = "info") {
214
+ pushGraphHistory(run.state, event, detail, nodeId);
215
+ logEvent(run.instId, level, event, { ...(detail ? { detail } : {}), ...(nodeId ? { node: nodeId } : {}) });
216
+ }
217
+ function setStatus(run, status, pauseReason) {
218
+ run.state.graph.status = status;
219
+ if (pauseReason)
220
+ run.state.graph.pause_reason = pauseReason;
221
+ else
222
+ delete run.state.graph.pause_reason;
223
+ run.state.active = !isGraphTerminal(status);
224
+ persist(run);
225
+ }
226
+ function notify(run, text, summary, directive = false) {
227
+ const session = run.state.owner_session;
228
+ if (!session)
229
+ return;
230
+ if (directive)
231
+ ports.deliverDirective(session, text, summary, { dedupe: false });
232
+ else
233
+ ports.deliverNotice(session, text, summary, { dedupe: false });
234
+ }
235
+ // ── 资产发现 ────────────────────────────────────────────────────────────────
236
+ function listWorkflows() {
237
+ return listGraphWorkflows(workspace);
238
+ }
239
+ function loadWorkflow(name) {
240
+ return loadGraphWorkflow(workspace, name);
241
+ }
242
+ function readState(instId) {
243
+ return readGraphState(workspace, instId);
244
+ }
245
+ function listStates() {
246
+ return listGraphStates(workspace);
247
+ }
248
+ function activeInstanceOfSession(sessionId) {
249
+ return listStates().filter((entry) => entry.state.active && entry.state.owner_session === sessionId).at(-1);
250
+ }
251
+ function activeMainAttemptOfSession(sessionId) {
252
+ for (const run of runs.values()) {
253
+ if (run.state.owner_session !== sessionId || run.state.graph.status !== "running")
254
+ continue;
255
+ for (const node of run.state.graph.asset.nodes) {
256
+ if (node.execution !== "main")
257
+ continue;
258
+ const attempt = latestAttemptOfNode(run.state, node.id);
259
+ if (attempt?.status === "running")
260
+ return { run, attempt, node };
261
+ }
262
+ }
263
+ return undefined;
264
+ }
265
+ function waitingTodosOfSession(sessionId) {
266
+ const out = [];
267
+ for (const run of runs.values()) {
268
+ if (run.state.owner_session !== sessionId)
269
+ continue;
270
+ for (const todo of run.state.graph.human_todos)
271
+ if (todo.status === "waiting")
272
+ out.push({ run, todo });
273
+ }
274
+ if (out.length === 0) {
275
+ for (const entry of listStates()) {
276
+ if (entry.state.owner_session !== sessionId)
277
+ continue;
278
+ for (const todo of entry.state.graph.human_todos)
279
+ if (todo.status === "waiting")
280
+ out.push({ run: { instId: entry.id, state: entry.state }, todo });
281
+ }
282
+ }
283
+ return out;
284
+ }
285
+ // ── 启动 ────────────────────────────────────────────────────────────────────
286
+ async function start(workflowName, task, sessionId) {
287
+ if (!workflowName?.trim())
288
+ return { ok: false, text: "缺少工作流名。用法:`ralphflow_start(workflow, task, inputs)` 或 `/ralphflow-start <工作流> <任务>`。" };
289
+ const mine = activeInstanceOfSession(sessionId);
290
+ if (mine)
291
+ return { ok: false, text: `当前会话已有活跃 Graph 实例 \`${mine.id}\`(${mine.state.workflow_name})。用 \`/ralphflow-continue\` 继续,或 \`/ralphflow-cancel\` 取消。` };
292
+ const loaded = loadWorkflow(workflowName.trim());
293
+ if (!loaded.def) {
294
+ return { ok: false, text: `Graph 工作流 \`${workflowName}\` 无法启动:\n${loaded.problems.map((problem) => `- ${problem}`).join("\n")}` };
295
+ }
296
+ const asset = loaded.def;
297
+ const taskText = task.trim() || asset.name;
298
+ const instId = uniqueId(asset);
299
+ const artifactsDirName = makeArtifactsDirName(taskText, instId);
300
+ const startedAt = now();
301
+ // 测试夹具:Graph 的产品路径始终走 Git;只有测试脚本会把这个环境变量设为 1。
302
+ const artifactFixture = process.env.RALPHFLOW_GRAPH_ARTIFACT === "1";
303
+ let project = { mode: "artifact" };
304
+ let integration;
305
+ if (!artifactFixture) {
306
+ try {
307
+ const snapshot = await resolveProject(workspace);
308
+ if (!snapshot.clean) {
309
+ return { ok: false, text: "Graph 从 HEAD 建隔离 worktree,当前工作区有未提交改动。先让用户选择 commit 或 stash;工作区干净后重新调用 ralphflow_start;启动成功即完成。" };
310
+ }
311
+ project = { mode: "git", root: snapshot.root, baseline: snapshot.baseline };
312
+ const integrationBranch = integrationBranchFor(instId);
313
+ const current = await ensureIntegrationBranch(snapshot.root, integrationBranch, snapshot.baseline);
314
+ integration = { branch: integrationBranch, baseline: snapshot.baseline, current_commit: current };
315
+ }
316
+ catch (error) {
317
+ return { ok: false, text: `Graph 实例无法启动:${msg(error)}` };
318
+ }
319
+ }
320
+ const state = {
321
+ kind: "graph",
322
+ active: true,
323
+ workflow_name: workflowName.trim(),
324
+ user_task: taskText,
325
+ owner_session: sessionId,
326
+ artifacts_dir_name: artifactsDirName,
327
+ started_at: startedAt,
328
+ updated_at: startedAt,
329
+ graph: {
330
+ asset,
331
+ asset_hash: graphAssetHash(asset),
332
+ ...(loaded.path ? { asset_path: loaded.path } : {}),
333
+ status: "running",
334
+ project,
335
+ ...(integration ? { integration } : {}),
336
+ attempts: [],
337
+ verdicts: [],
338
+ acceptances: [],
339
+ human_todos: [],
340
+ worktrees: [],
341
+ rework_counts: {},
342
+ integration_retries: {},
343
+ fault_retries: {},
344
+ },
345
+ history: [],
346
+ };
347
+ const run = {
348
+ instId,
349
+ state,
350
+ artifactRoot: path.join(artifactsRoot, artifactsDirName),
351
+ ...(project.root ? { projectRoot: project.root } : {}),
352
+ submitWaiters: new Map(),
353
+ reviewWaiters: new Map(),
354
+ active: new Map(),
355
+ agents: new Map(),
356
+ abort: new AbortController(),
357
+ wake: null,
358
+ respondTools: new Map(),
359
+ mainBusy: false,
360
+ schedulerActive: false,
361
+ schedulerRestart: false,
362
+ acceptTail: Promise.resolve(),
363
+ };
364
+ runs.set(instId, run);
365
+ ensureLayout();
366
+ fs.mkdirSync(run.artifactRoot, { recursive: true });
367
+ // running 期间由本运行时持有属主心跳(暂停/结束自动停止刷新,见 owner.ts)。
368
+ stampOwner(state);
369
+ pushGraphHistory(state, "start", `workflow=${workflowName} asset=${asset.id}`);
370
+ logEvent(instId, "info", "start", { workflow: workflowName, nodes: asset.nodes.length, mode: project.mode });
371
+ persist(run);
372
+ const receipt = [
373
+ `🚀 已启动 Graph 工作流 **${asset.name}**(实例 \`${instId}\`,${asset.nodes.length} 个节点)。`,
374
+ "",
375
+ `节点:${asset.nodes.map((node) => `\`${node.id}\``).join("、")}`,
376
+ project.mode === "git"
377
+ ? `Git 工作区:集成分支 \`${integration?.branch}\`,基线 \`${integration?.baseline.slice(0, 12)}…\`;每个节点在自己的 worktree 与分支上运行,主会话的 HEAD 不动。`
378
+ : "Artifact 测试工作区:节点直接在当前工作区运行(仅测试夹具)。",
379
+ "",
380
+ "引擎会自动调度就绪节点;节点完成后经独立 CHECK(若配置)与人工门(若在 manual_step)。用 `/ralphflow-status` 看进度。",
381
+ ...(loaded.warnings.length > 0 ? ["", "⚠️ 资产告警:", ...loaded.warnings.map((warning) => `- ${warning}`)] : []),
382
+ ].join("\n");
383
+ notify(run, receipt, `🚀 Graph 已启动:${asset.name}(${instId})`);
384
+ startScheduler(run, (error) => {
385
+ log("error", "graph_scheduler_failed", { instId, error: msg(error) });
386
+ if (run.state.graph.status === "running") {
387
+ setStatus(run, "failed", "scheduler_failure");
388
+ finalize(run);
389
+ }
390
+ });
391
+ return { ok: true, text: receipt };
392
+ }
393
+ // ── 调度 ────────────────────────────────────────────────────────────────────
394
+ function wake(run) {
395
+ const resolve = run.wake;
396
+ run.wake = null;
397
+ resolve?.();
398
+ }
399
+ function waitForWake(run) {
400
+ return new Promise((resolve) => { run.wake = resolve; });
401
+ }
402
+ function startScheduler(run, onError) {
403
+ if (run.schedulerActive) {
404
+ // 旧调度器可能正因 paused 退出(或还在等在飞节点收尾)。记一笔:它退出时若实例已经
405
+ // 回到 running,就自动重启 —— 否则「暂停 → 立刻 continue」会落在一个没人再驱动的
406
+ // 实例上(schedulerActive 还是 true,新的 startScheduler 被吞掉)。
407
+ run.schedulerRestart = true;
408
+ return;
409
+ }
410
+ run.schedulerActive = true;
411
+ run.scheduler = runScheduler(run).catch(onError).finally(() => {
412
+ run.schedulerActive = false;
413
+ if (run.schedulerRestart && run.state.graph.status === "running") {
414
+ run.schedulerRestart = false;
415
+ startScheduler(run, onError);
416
+ }
417
+ });
418
+ }
419
+ function allReleased(run) {
420
+ return run.state.graph.asset.nodes.every((node) => nodeReleased(run.state, node));
421
+ }
422
+ function canLaunch(run, node) {
423
+ if (run.state.graph.status !== "running")
424
+ return false;
425
+ if (acceptanceOfNode(run.state, node.id))
426
+ return false;
427
+ if (waitingTodoOfNode(run.state, node.id))
428
+ return false;
429
+ if (run.active.has(node.id))
430
+ return false;
431
+ const latest = latestAttemptOfNode(run.state, node.id);
432
+ if (latest && (latest.status === "submitted" || latest.status === "running"))
433
+ return false;
434
+ if (run.state.graph.project.mode === "git" && latest?.status === "submitted" && verdictOfAttempt(run.state, latest.id)?.status === "passed") {
435
+ return false; // 等合入,不重做 DO
436
+ }
437
+ return node.dependsOn.every((dependency) => {
438
+ const source = run.state.graph.asset.nodes.find((candidate) => candidate.id === dependency);
439
+ return source ? nodeReleased(run.state, source) : false;
440
+ });
441
+ }
442
+ async function runScheduler(run) {
443
+ const limit = Number.MAX_SAFE_INTEGER;
444
+ while (run.state.graph.status === "running") {
445
+ let launched = false;
446
+ for (const node of run.state.graph.asset.nodes) {
447
+ if (run.active.size >= limit)
448
+ break;
449
+ if (node.execution === "main" && run.mainBusy)
450
+ continue;
451
+ if (!canLaunch(run, node))
452
+ continue;
453
+ launched = true;
454
+ const task = runNode(run, node)
455
+ .catch((error) => onNodeError(run, node, error))
456
+ .finally(() => {
457
+ run.active.delete(node.id);
458
+ wake(run);
459
+ });
460
+ run.active.set(node.id, task);
461
+ }
462
+ if (run.active.size > 0) {
463
+ await Promise.race([...run.active.values(), waitForWake(run)]);
464
+ continue;
465
+ }
466
+ if (allReleased(run)) {
467
+ completeRun(run);
468
+ return;
469
+ }
470
+ // 没有在飞、也没有可启动的节点:要么在等人(人工门/暂停),要么失败。
471
+ const waiting = run.state.graph.human_todos.some((todo) => todo.status === "waiting");
472
+ if (waiting) {
473
+ setStatus(run, "waiting", "human_todo");
474
+ notify(run, "Graph 实例在等待你处理人工门。回答后用 /ralphflow-continue 或 ralphflow_respond。", "⏸ Graph 等待人工处理");
475
+ return;
476
+ }
477
+ const failedNodes = run.state.graph.asset.nodes.filter((node) => nodeStatusOf(run.state, node) === "failed");
478
+ if (failedNodes.length > 0) {
479
+ setStatus(run, "failed", "node_failed");
480
+ finalize(run);
481
+ return;
482
+ }
483
+ setStatus(run, "paused", "no_schedulable_node");
484
+ notify(run, "Graph 实例没有可调度节点了(依赖未满足或有节点等待重试)。检查状态后用 /ralphflow-continue 继续。", "⏸ Graph 无法继续");
485
+ return;
486
+ }
487
+ wake(run);
488
+ }
489
+ function completeRun(run) {
490
+ if (run.state.graph.status !== "running")
491
+ return;
492
+ setStatus(run, "completed");
493
+ history(run, "complete", `${run.state.graph.asset.nodes.length} 个节点已释放`);
494
+ finalize(run);
495
+ }
496
+ function finalize(run) {
497
+ archiveExecutionLog(run.instId);
498
+ const report = writeReport(run);
499
+ persist(run);
500
+ const status = run.state.graph.status;
501
+ const label = status === "completed" ? "完成" : status === "cancelled" ? "取消" : status === "failed" ? "失败" : status;
502
+ const reportLine = report ? `报告:\`${relOrAbsolute(workspace, report)}\`` : "报告写入失败,状态记录仍在 `instances/` 里。";
503
+ notify(run, `Graph 实例 \`${run.instId}\` ${label}。${reportLine}`, `${status === "completed" ? "✅" : status === "cancelled" ? "⏹" : "❌"} Graph ${label}:${run.state.graph.asset.name}`);
504
+ log(status === "failed" ? "warn" : "info", status === "completed" ? "graph_complete" : status === "cancelled" ? "graph_cancelled" : "graph_failed", { instId: run.instId });
505
+ run.agents.clear();
506
+ }
507
+ async function onNodeError(run, node, error) {
508
+ if (run.state.graph.status === "cancelled")
509
+ return;
510
+ const message = msg(error);
511
+ const attempt = latestAttemptOfNode(run.state, node.id);
512
+ if (attempt && attempt.status === "running") {
513
+ attempt.status = "failed";
514
+ attempt.finished_at = now();
515
+ attempt.failure = { kind: "runtime_failure", message };
516
+ }
517
+ history(run, "node_failed", message, node.id, "warn");
518
+ if (run.state.graph.status === "running") {
519
+ setStatus(run, "paused", "node_failure");
520
+ notify(run, `节点 \`${node.id}\` 执行失败:${message}\n用 /ralphflow-continue 重试(会开新 attempt),或 /ralphflow-cancel 结束。`, `⏸ Graph 节点失败:${nodeNameOf(run.state, node)}`);
521
+ }
522
+ }
523
+ // ── 单个节点 ────────────────────────────────────────────────────────────────
524
+ async function runNode(run, node) {
525
+ if (node.execution === "main") {
526
+ await withMainLock(run, () => runNodeLoop(run, node));
527
+ }
528
+ else {
529
+ await runNodeLoop(run, node);
530
+ }
531
+ }
532
+ async function withMainLock(run, task) {
533
+ while (run.mainBusy && run.state.graph.status === "running")
534
+ await new Promise((resolve) => setTimeout(resolve, 100));
535
+ run.mainBusy = true;
536
+ try {
537
+ await task();
538
+ }
539
+ finally {
540
+ run.mainBusy = false;
541
+ }
542
+ }
543
+ async function runNodeLoop(run, node) {
544
+ const check = node.check ? checkDefinition(node.check.criteria) : checkDefinition(null);
545
+ let reworkReason = "";
546
+ let manualReason = "";
547
+ for (;;) {
548
+ if (run.state.graph.status !== "running")
549
+ return;
550
+ const attempt = newAttempt(run, node, { reworkReason, manualReason });
551
+ if (run.state.graph.project.mode === "git" && node.execution === "background") {
552
+ await prepareAttemptWorkspace(run, node, attempt);
553
+ }
554
+ history(run, "node_start", `attempt=${attempt.id}`, node.id);
555
+ try {
556
+ await executeAttempt(run, node, attempt);
557
+ }
558
+ catch (error) {
559
+ if (run.abort.signal.aborted || run.state.graph.status !== "running") {
560
+ // 暂停(用户停止回合)时 attempt 已被标为 interrupted —— 不要改写成 cancelled,
561
+ // 否则 continue 看不到"被打断、要重试"这件事。
562
+ if (attempt.status === "running") {
563
+ attempt.status = "cancelled";
564
+ attempt.finished_at = now();
565
+ }
566
+ persist(run);
567
+ return;
568
+ }
569
+ throw error;
570
+ }
571
+ if (run.abort.signal.aborted || run.state.graph.status !== "running")
572
+ return;
573
+ if (attempt.status !== "submitted") {
574
+ throw new Error(`节点 \`${node.id}\` 的 agent 在没有提交产物的情况下结束了回合(缺 ralphflow_submit)。`);
575
+ }
576
+ // CHECK
577
+ let verdict = null;
578
+ if (node.check) {
579
+ verdict = await runCheck(run, node, attempt, check);
580
+ if (run.abort.signal.aborted || run.state.graph.status !== "running")
581
+ return;
582
+ if (!verdict)
583
+ return;
584
+ if (verdict.status === "infra") {
585
+ setStatus(run, "paused", "check_infra");
586
+ history(run, "pause", `check_infra node=${node.id}`, node.id, "warn");
587
+ notify(run, `节点 \`${node.id}\` 的独立 CHECK 基础设施故障:${verdict.reason}\n用 /ralphflow-continue 重试验证。`, "⏸ 独立 CHECK 基础设施故障");
588
+ return;
589
+ }
590
+ if (verdict.status === "failed") {
591
+ const used = run.state.graph.rework_counts[node.id] ?? 0;
592
+ if (used >= MAX_CHECK_REWORKS) {
593
+ setStatus(run, "paused", "rework_limit");
594
+ history(run, "pause", `rework_limit node=${node.id} used=${used}`, node.id, "warn");
595
+ notify(run, `节点 \`${node.id}\` 的独立 CHECK 连续 ${used} 次未通过:${verdict.reason}\n修正资产或产物后用 /ralphflow-continue 再试。`, "⏸ CHECK 返工达到上限");
596
+ return;
597
+ }
598
+ run.state.graph.rework_counts[node.id] = used + 1;
599
+ reworkReason = verdict.reason;
600
+ attempt.status = "rejected";
601
+ attempt.finished_at = now();
602
+ persist(run);
603
+ history(run, "node_rework", verdict.reason, node.id, "warn");
604
+ continue;
605
+ }
606
+ }
607
+ // 人工门
608
+ if (run.abort.signal.aborted || run.state.graph.status !== "running")
609
+ return;
610
+ if (run.state.graph.asset.manual_step.includes(node.id)) {
611
+ const review = await reviewNode(run, node, attempt);
612
+ if (run.abort.signal.aborted || run.state.graph.status !== "running")
613
+ return;
614
+ if (!review)
615
+ return;
616
+ if (review.decision === "revise") {
617
+ manualReason = review.feedback;
618
+ attempt.status = "rejected";
619
+ attempt.finished_at = now();
620
+ persist(run);
621
+ history(run, "manual_revise", review.feedback, node.id, "warn");
622
+ continue;
623
+ }
624
+ }
625
+ // 接纳:只做快进;节点没把集成分支合进来就退回它自己
626
+ if (run.abort.signal.aborted || run.state.graph.status !== "running")
627
+ return;
628
+ const accepted = await acceptAttempt(run, node, attempt, check.mode);
629
+ if (accepted.ok)
630
+ return;
631
+ const mergeTries = run.state.graph.integration_retries[node.id] ?? 0;
632
+ if (mergeTries >= MAX_INTEGRATION_RETRIES) {
633
+ setStatus(run, "paused", "rework_limit");
634
+ history(run, "pause", `rework_limit node=${node.id} used=${mergeTries}`, node.id, "warn");
635
+ notify(run, `节点 \`${node.id}\` 连续 ${mergeTries} 次没有把集成分支合进自己的分支:${accepted.reason}\n修正后用 /ralphflow-continue 再试。`, "⏸ 合入重试达到上限");
636
+ return;
637
+ }
638
+ run.state.graph.integration_retries[node.id] = mergeTries + 1;
639
+ reworkReason = accepted.reason;
640
+ attempt.status = "rejected";
641
+ attempt.finished_at = now();
642
+ persist(run);
643
+ history(run, "node_rework", accepted.reason, node.id, "warn");
644
+ continue;
645
+ }
646
+ }
647
+ async function prepareAttemptWorkspace(run, node, attempt) {
648
+ if (run.state.graph.project.mode === "artifact")
649
+ return;
650
+ const projectRoot = run.state.graph.project.root;
651
+ const integration = run.state.graph.integration;
652
+ if (!projectRoot || !integration)
653
+ throw new Error("Git 模式缺少 project root 或集成分支记录。");
654
+ const recorded = run.state.graph.worktrees.find((item) => item.node_id === node.id);
655
+ // 已有 worktree 沿用**它创建时的集成分支头**:并行/返工期间集成线可能已前进,
656
+ // 节点要在交卷前把新头合进来(它的分支会包含两者)。
657
+ const baseline = recorded?.baseline ?? integration.current_commit;
658
+ const branch = recorded?.branch ?? nodeBranchFor(run.instId, node.id);
659
+ const worktreePath = nodeWorktreePathOf(workspace, run.instId, node.id);
660
+ const existing = await ensureNodeWorktree(projectRoot, worktreePath, branch, baseline);
661
+ attempt.workspace = { path: existing.path, baseline };
662
+ if (!recorded) {
663
+ run.state.graph.worktrees.push({ node_id: node.id, path: existing.path, branch, baseline, created_at: now() });
664
+ }
665
+ persist(run);
666
+ }
667
+ function newAttempt(run, node, reasons) {
668
+ const seq = attemptsOfNode(run.state, node.id).length + 1;
669
+ const attempt = {
670
+ id: randomUUID(),
671
+ node_id: node.id,
672
+ seq,
673
+ status: "running",
674
+ started_at: now(),
675
+ ...(reasons.reworkReason ? { rework_reason: reasons.reworkReason } : {}),
676
+ ...(reasons.manualReason ? { manual_rework_reason: reasons.manualReason } : {}),
677
+ };
678
+ run.state.graph.attempts.push(attempt);
679
+ persist(run);
680
+ return attempt;
681
+ }
682
+ // ── DO:背景节点 / 主会话节点 ──────────────────────────────────────────────
683
+ async function executeAttempt(run, node, attempt) {
684
+ if (node.execution === "main") {
685
+ await executeMainAttempt(run, node, attempt);
686
+ }
687
+ else {
688
+ await executeBackgroundAttempt(run, node, attempt);
689
+ }
690
+ }
691
+ function inputRefs(run, node) {
692
+ const refs = [];
693
+ for (const reference of node.inputs) {
694
+ const source = run.state.graph.asset.nodes.find((candidate) => candidate.id === reference.fromNode);
695
+ if (!source)
696
+ continue;
697
+ const sourceAttempts = attemptsOfNode(run.state, reference.fromNode);
698
+ const accepted = sourceAttempts.find((candidate) => candidate.artifact?.accepted)
699
+ ?? sourceAttempts.filter((candidate) => verdictOfAttempt(run.state, candidate.id)?.status === "passed").at(-1)
700
+ ?? sourceAttempts.at(-1);
701
+ if (!accepted?.artifact)
702
+ continue;
703
+ // 子 agent 的 cwd 是 worktree;产物在运行根下,必须给绝对路径。
704
+ refs.push({ label: `node:${reference.fromNode}/${reference.artifact}`, path: accepted.artifact.path });
705
+ }
706
+ return refs;
707
+ }
708
+ function doPrompt(run, node, attempt, rework, manual = "") {
709
+ const artifactPath = path.join(graphNodeArtifactDirOf(workspace, run.state, node.id, attempt.id), node.artifact);
710
+ const lines = [
711
+ `# Graph 节点执行 · ${node.id}`,
712
+ "",
713
+ `实例:\`${run.instId}\` 节点:\`${node.id}\`${node.name ? `(${node.name})` : ""} 尝试:\`${attempt.id}\``,
714
+ "",
715
+ "## 任务",
716
+ node.do,
717
+ "",
718
+ ];
719
+ const refs = inputRefs(run, node);
720
+ if (refs.length > 0) {
721
+ lines.push("## 只读材料(用原生 read 读取;路径已由引擎解析)", ...refs.map((ref) => `- ${ref.label}:${ref.path}`), "");
722
+ }
723
+ lines.push("## 交付", `用 \`ralphflow_artifact_write\` 写入节点产物 \`${node.artifact}\`(内容作为 content 参数;不要猜文件路径)。`, `产物逻辑路径:\`${workspaceRelative(workspace, artifactPath) ?? artifactPath}\``, "");
724
+ if (run.state.graph.project.mode === "git" && attempt.workspace?.path) {
725
+ const baseline = attempt.workspace.baseline;
726
+ const integration = run.state.graph.integration;
727
+ lines.push("## 工作区", `工作区:\`${attempt.workspace.path}\`(独立 worktree,分支 \`${nodeBranchFor(run.instId, node.id)}\`)。直接用 read/write/edit/bash 改代码,用 git 提交。`, `基线:\`${baseline}\``, integration
728
+ ? `交卷前:有代码改动的节点先提交,再把集成分支 \`${integration.branch}\` 合进你的分支(冲突在你这轮解决),跑与改动相关的测试,工作树不要留未提交的跟踪改动;没合集成线会被退回。没有代码改动的节点(HEAD 仍在基线)只交产物即可:空分支由引擎快进到集成 tip,没有内容要合。`
729
+ : "", "只改本节点需要的文件;不要动其它节点的 worktree 和主工作树。", "");
730
+ }
731
+ else {
732
+ lines.push("## 工作区", `项目工作区:\`${workspace}\`(主会话节点;直接读写)。`, "");
733
+ }
734
+ const assetRef = assetReferenceSection(assetRootOf(run.state.graph.asset_path));
735
+ if (assetRef)
736
+ lines.push(assetRef, "");
737
+ if (rework) {
738
+ lines.push("## 上一轮 CHECK 未通过(只修本节点)", rework, "");
739
+ }
740
+ if (manual) {
741
+ lines.push("## 人工审查要求修改(只修本节点)", manual, "");
742
+ }
743
+ if (attempt.manual_rework_reason) {
744
+ lines.push("## 人工审查要求改稿", attempt.manual_rework_reason, "");
745
+ }
746
+ lines.push("## 完成条件", "产物内容与工作区改动都完成后,调用一次 `ralphflow_submit`。没有 submit 的回合不算完成;CHECK 与人工门由引擎机械执行。");
747
+ return lines.join("\n");
748
+ }
749
+ /**
750
+ * 催促消息里的**自包含节点卡**。
751
+ *
752
+ * 长程节点 / 上下文压缩后,模型可能已经看不到原始节点 DO;只说「节点还没结束」等于让它猜。
753
+ * 这里带恢复方向必需的事实(任务 / 只读材料 / 交付 / 工作区 / 返工原因),
754
+ * 不重复「完成条件」那类长文 —— 催促是低频的(≤2 次空回合 / 20 次总上限)。
755
+ */
756
+ function nodeRecap(run, node, attempt) {
757
+ const artifactPath = path.join(graphNodeArtifactDirOf(workspace, run.state, node.id, attempt.id), node.artifact);
758
+ const refs = inputRefs(run, node);
759
+ const assetRoot = assetRootOf(run.state.graph.asset_path);
760
+ const lines = [
761
+ "## 本节点回顾(上下文可能已被压缩,以这里为准)",
762
+ `- 实例:\`${run.instId}\` 节点:\`${node.id}\`${node.name ? `(${node.name})` : ""} 尝试:\`${attempt.id}\``,
763
+ `- 任务:${node.do}`,
764
+ ...(refs.length > 0 ? ["- 只读材料(用原生 read 读取):", ...refs.map((ref) => ` - ${ref.label}:${ref.path}`)] : []),
765
+ `- 交付:用 \`ralphflow_artifact_write\` 写入节点产物 \`${node.artifact}\`(内容作为 content 参数;不要猜文件路径)。`,
766
+ `- 产物逻辑路径:\`${workspaceRelative(workspace, artifactPath) ?? artifactPath}\``,
767
+ ...(run.state.graph.project.mode === "git" && attempt.workspace?.path
768
+ ? [`- 工作区:\`${attempt.workspace.path}\`(独立 worktree;直接 read/write/edit/bash)`, `- 基线:\`${attempt.workspace.baseline}\``]
769
+ : [`- 工作区:\`${workspace}\`(主会话节点;直接读写)`]),
770
+ ...(assetRoot ? [`- 资产目录:\`${assetRoot}\``] : []),
771
+ ...(attempt.rework_reason ? [`- 上一轮 CHECK 未通过(只修本节点):${attempt.rework_reason}`] : []),
772
+ ...(attempt.manual_rework_reason ? [`- 人工审查要求改稿:${attempt.manual_rework_reason}`] : []),
773
+ ];
774
+ return lines.join("\n");
775
+ }
776
+ function agentOptionsFor(parent, node) {
777
+ const base = { ...(parent.options ?? {}) };
778
+ delete base.reasoningEffort;
779
+ return base;
780
+ }
781
+ /**
782
+ * 把节点 agent 登记进宿主的「子智能体」发现事实。
783
+ *
784
+ * 节点 agent 走 `ctx.agents.create`(不经 subagent 服务),宿主不会自己写
785
+ * `subagent/descriptor` 或父会话的 `subagent/catalog`;但它确实是 owner 会话的
786
+ * 直接子会话(origin=subagent + parentSession)。补上这两条事实后,顶部的子智能体
787
+ * 监控能看到它,打开会话时也能通过宿主对 subagent 地址的校验
788
+ * (one-shot:跑完即止,不可续)。
789
+ */
790
+ function announceChildAgent(parent, child, label) {
791
+ try {
792
+ const parentSession = parent.session;
793
+ const childSession = child.session;
794
+ const header = child.session?.header;
795
+ const childId = child.id;
796
+ if (typeof childId !== "string")
797
+ return;
798
+ // 宿主的 subagent 地址校验从**子会话自己的日志**折出 descriptor;只写父会话的
799
+ // catalog 会让 UI 看得到条目、却打不开历史(subagent descriptor is corrupt)。
800
+ // version 与 DSH 的 SUBAGENT_DESCRIPTOR_VERSION 对齐(当前 3);升级 DSH 时同步。
801
+ childSession?.append?.("subagent/descriptor", {
802
+ version: 3,
803
+ mode: "one-shot",
804
+ provider: "ralphflow-graph",
805
+ label,
806
+ });
807
+ parentSession?.append?.("subagent/catalog", {
808
+ version: 0,
809
+ childId,
810
+ childCreatedAt: typeof header?.createdAt === "number" ? header.createdAt : Date.now(),
811
+ mode: "one-shot",
812
+ label,
813
+ });
814
+ }
815
+ catch (error) {
816
+ log("warn", "graph_catalog_announce_failed", { error: msg(error) });
817
+ }
818
+ }
819
+ async function executeBackgroundAttempt(run, node, attempt) {
820
+ const parent = run.state.owner_session ? ctx.agents.get(run.state.owner_session) : undefined;
821
+ if (!parent)
822
+ throw new Error("发起会话不可用(owner_session 找不到 Agent),无法创建节点 agent。");
823
+ const cwd = node.execution === "background"
824
+ ? (run.state.graph.project.mode === "git" ? assertWorktree(run, node, attempt) : workspace)
825
+ : workspace;
826
+ const workerId = `ralphflow-graph-${randomUUID()}`;
827
+ attempt.worker_id = workerId;
828
+ persist(run);
829
+ const handle = await ctx.agents.create({
830
+ sessionId: workerId,
831
+ parentAgent: parent,
832
+ meta: { cwd, parentSession: parent.id, origin: "subagent", delegationDepth: 1 },
833
+ agentOptions: agentOptionsFor(parent, node),
834
+ setup: (scope) => {
835
+ installNativeTools(scope, parent);
836
+ registerScopedTool(scope, artifactWriteTool(run, node, attempt));
837
+ restrictToSubmit(scope);
838
+ },
839
+ });
840
+ run.agents.set(attempt.id, handle);
841
+ // create 与注册之间可能刚好被暂停:此时 attempt 已被标 interrupted,别再启动回合。
842
+ if (run.state.graph.status !== "running") {
843
+ run.agents.delete(attempt.id);
844
+ try {
845
+ await handle.dispose();
846
+ }
847
+ catch { }
848
+ return;
849
+ }
850
+ announceChildAgent(parent, handle.agent, `Graph 节点 ${node.id}`);
851
+ agentBindings.set(workerId, { instId: run.instId, nodeId: node.id, attemptId: attempt.id, workerId });
852
+ registerGraphAgent(workerId, workspace);
853
+ attempt.session_id = workerId;
854
+ persist(run);
855
+ // 节点要在自己的 worktree 里 commit、把集成分支合进来。worktree 的 Git 元数据在主仓库
856
+ // `.git` 下,`workspace-write` 的边界是会话 cwd、够不到它 —— 所以这里给的是与 Claude Code
857
+ // 子 agent 同级的权限,隔离交给 worktree 目录与提示词,而不是靠截断 git。
858
+ setSandbox(handle.agent, "danger-full-access");
859
+ let thrown;
860
+ try {
861
+ handle.agent.followup({
862
+ id: randomUUID(),
863
+ role: "user",
864
+ content: [{ type: "text", text: doPrompt(run, node, attempt, attempt.rework_reason ?? "", attempt.manual_rework_reason ?? "") }],
865
+ source: { kind: "ralphflow" },
866
+ });
867
+ await handle.agent.whenIdle();
868
+ }
869
+ catch (error) {
870
+ thrown = error;
871
+ }
872
+ finally {
873
+ agentBindings.delete(workerId);
874
+ unregisterGraphAgent(workerId);
875
+ run.agents.delete(attempt.id);
876
+ try {
877
+ await handle.dispose();
878
+ }
879
+ catch { }
880
+ const current = run.state.graph.attempts.find((item) => item.id === attempt.id);
881
+ if (current && current.status === "running") {
882
+ current.status = "failed";
883
+ current.failure = thrown
884
+ ? { kind: "runtime_failure", message: msg(thrown) }
885
+ : { kind: "missing_submission", message: "节点 agent 结束了回合但没有调用 ralphflow_submit。" };
886
+ persist(run);
887
+ }
888
+ }
889
+ if (thrown)
890
+ throw thrown;
891
+ }
892
+ async function executeMainAttempt(run, node, attempt) {
893
+ const sessionId = run.state.owner_session;
894
+ if (!sessionId)
895
+ throw new Error("Graph 主执行节点没有 owner_session。");
896
+ const agent = ctx.agents.get(sessionId);
897
+ if (!agent)
898
+ throw new Error("发起会话不在线,无法执行 execution: main 节点。");
899
+ attempt.worker_id = sessionId;
900
+ attempt.session_id = sessionId;
901
+ agentBindings.set(sessionId, { instId: run.instId, nodeId: node.id, attemptId: attempt.id, workerId: sessionId });
902
+ persist(run);
903
+ const disposers = [];
904
+ const agentCtx = agent.ctx;
905
+ const scopedTools = agentCtx?.get("tools");
906
+ if (!scopedTools)
907
+ throw new Error("宿主没有给主会话提供 agent-scoped tools,无法挂节点产物/应答工具。");
908
+ disposers.push(scopedTools.register(artifactWriteTool(run, node, attempt)));
909
+ syncRespondTool(run, sessionId);
910
+ const waited = waitForSubmit(run, attempt);
911
+ try {
912
+ const delivered = ports.deliverDirective(sessionId, doPrompt(run, node, attempt, attempt.rework_reason ?? "", attempt.manual_rework_reason ?? ""), `🧩 Graph 主执行节点:${nodeNameOf(run.state, node)}`, { dedupe: false });
913
+ if (!delivered)
914
+ throw new Error("无法把节点 DO 投递给主会话(会话可能离线)。");
915
+ await waited;
916
+ }
917
+ finally {
918
+ for (const dispose of disposers) {
919
+ try {
920
+ dispose();
921
+ }
922
+ catch { }
923
+ }
924
+ if (agentBindings.get(sessionId)?.attemptId === attempt.id)
925
+ agentBindings.delete(sessionId);
926
+ run.submitWaiters.delete(attempt.id);
927
+ }
928
+ }
929
+ function assertWorktree(run, node, attempt) {
930
+ if (!attempt.workspace?.path)
931
+ throw new Error(`节点 \`${node.id}\` 没有准备 Git worktree。`);
932
+ return attempt.workspace.path;
933
+ }
934
+ function waitForSubmit(run, attempt) {
935
+ return new Promise((resolve, reject) => {
936
+ run.submitWaiters.set(attempt.id, { resolve, reject });
937
+ run.abort.signal.addEventListener("abort", () => reject(new Error("run aborted")), { once: true });
938
+ });
939
+ }
940
+ function installNativeTools(scope, parent) {
941
+ const names = ["read", "write", "edit", "grep", "glob", "bash", "read_image", "skill"];
942
+ const parentTools = parent.ctx?.get("tools");
943
+ const pluginTools = ctx.tools;
944
+ const register = scope.tools.register.bind(scope.tools);
945
+ for (const name of names) {
946
+ let definition;
947
+ try {
948
+ definition = parentTools?.get(name, parent);
949
+ }
950
+ catch { }
951
+ if (!definition) {
952
+ try {
953
+ definition = pluginTools.get(name);
954
+ }
955
+ catch { }
956
+ }
957
+ if (definition) {
958
+ try {
959
+ register(definition);
960
+ }
961
+ catch { }
962
+ }
963
+ }
964
+ }
965
+ function registerScopedTool(scope, definition) {
966
+ try {
967
+ scope.tools.register(definition);
968
+ }
969
+ catch (error) {
970
+ log("warn", "graph_scoped_tool_register_failed", { error: msg(error) });
971
+ }
972
+ }
973
+ function restrictToSubmit(scope) {
974
+ try {
975
+ scope.tools.restrict({ allow: ["ralphflow_submit"] });
976
+ }
977
+ catch (error) {
978
+ log("warn", "graph_tool_restrict_failed", { error: msg(error) });
979
+ }
980
+ }
981
+ function setSandbox(agent, mode) {
982
+ const session = agent.session;
983
+ if (typeof session.append !== "function") {
984
+ throw new Error("宿主会话不支持 sandbox/mode 事件,节点无法获得写 Git 的权限。");
985
+ }
986
+ session.append("sandbox/mode", { mode });
987
+ }
988
+ function artifactWriteTool(run, node, attempt) {
989
+ return defineTool({
990
+ name: "ralphflow_artifact_write",
991
+ description: "写入本节点的声明产物。内容作为 content 传入;文件路径由引擎决定,不要自己猜。",
992
+ parameters: { content: { type: "string", required: true, description: "节点产物的完整内容(Markdown/JSON 均可)。" } },
993
+ output: { schema: { type: "string" }, render: (_args, value) => [{ type: "text", text: value }] },
994
+ async execute(args, exec) {
995
+ if (!exec?.agent)
996
+ return "找不到当前节点 agent,产物未写入。";
997
+ const binding = agentBindings.get(exec.agent.id ?? "");
998
+ if (!binding || binding.attemptId !== attempt.id || binding.nodeId !== node.id) {
999
+ return "当前 agent 没有绑定到这个节点 attempt,产物未写入。";
1000
+ }
1001
+ const content = args?.content;
1002
+ if (typeof content !== "string" || content.length === 0)
1003
+ return "content 必须是非空字符串,产物未写入。";
1004
+ const dir = graphNodeArtifactDirOf(workspace, run.state, node.id, attempt.id);
1005
+ const file = path.join(dir, node.artifact);
1006
+ fs.mkdirSync(path.dirname(file), { recursive: true });
1007
+ fs.writeFileSync(file, content, "utf-8");
1008
+ const digest = createHash("sha256").update(content).digest("hex");
1009
+ attempt.artifact = { path: file, rel: workspaceRelative(workspace, file) ?? file, sha256: digest, size: Buffer.byteLength(content), accepted: false };
1010
+ persist(run);
1011
+ logEvent(run.instId, "info", "artifact_written", { node: node.id, attempt: attempt.id, path: file, bytes: Buffer.byteLength(content) });
1012
+ return `已写入节点产物 \`${node.artifact}\`(${Buffer.byteLength(content)} bytes,sha256 ${digest.slice(0, 12)}…)。`;
1013
+ },
1014
+ });
1015
+ }
1016
+ /** 主会话的 ralphflow_submit 分派:先看有没有绑定到 Graph 节点 attempt。 */
1017
+ async function submitFromAgent(agent, summary, unfinished) {
1018
+ const agentId = agent?.id;
1019
+ if (agentId) {
1020
+ const binding = agentBindings.get(agentId);
1021
+ if (binding)
1022
+ return submitAttempt(binding.instId, binding.nodeId, binding.attemptId, summary, unfinished);
1023
+ }
1024
+ const sessionId = agent?.session?.id;
1025
+ if (!sessionId)
1026
+ return null;
1027
+ const main = activeMainAttemptOfSession(sessionId);
1028
+ if (main)
1029
+ return submitAttempt(main.run.instId, main.node.id, main.attempt.id, summary, unfinished);
1030
+ return null;
1031
+ }
1032
+ async function submitAttempt(instId, nodeId, attemptId, summary, unfinished) {
1033
+ const run = runs.get(instId) ?? restoreRun(instId);
1034
+ if (!run)
1035
+ return { ok: false, text: `Graph 实例 \`${instId}\` 不在内存中(宿主可能已重启);用 /ralphflow-continue 恢复后再交卷。` };
1036
+ const attempt = run.state.graph.attempts.find((item) => item.id === attemptId);
1037
+ if (!attempt || attempt.node_id !== nodeId)
1038
+ return { ok: false, text: "找不到这个节点 attempt,交卷未受理。" };
1039
+ if (run.state.graph.status !== "running")
1040
+ return { ok: false, text: `实例 \`${instId}\` 当前是 ${run.state.graph.status},交卷未受理。` };
1041
+ if (attempt.status !== "running")
1042
+ return { ok: false, text: `attempt 当前是 ${attempt.status},不能重复交卷。` };
1043
+ // 未完成项非空 = 交卷是进度,不是完成声明:CHECK 不启动,attempt 留在 running 让节点 agent 接着做。
1044
+ const remaining = normalizeUnfinished(unfinished);
1045
+ if (remaining.length > 0) {
1046
+ logEvent(instId, "info", "submit_incomplete", { node: nodeId, attempt: attemptId, count: remaining.length });
1047
+ const node = run.state.graph.asset.nodes.find((item) => item.id === nodeId);
1048
+ return {
1049
+ ok: false,
1050
+ text: `交卷未受理:你列出了 ${remaining.length} 项未完成。\n\n${remaining.map((item) => `- ${item}`).join("\n")}\n\n继续做完这些再交卷;没有剩余事项时 \`unfinished\` 留空。`,
1051
+ };
1052
+ }
1053
+ if (!attempt.artifact)
1054
+ return { ok: false, text: "还没有写节点产物:先调用 `ralphflow_artifact_write` 写入声明的 artifact,再交卷。" };
1055
+ try {
1056
+ const stat = sha256File(attempt.artifact.path);
1057
+ if (stat.sha256 !== attempt.artifact.sha256) {
1058
+ return { ok: false, text: "产物文件在写入后发生了变化,交卷未受理;请重新调用 ralphflow_artifact_write。" };
1059
+ }
1060
+ }
1061
+ catch {
1062
+ return { ok: false, text: "声明的产物文件不存在,交卷未受理;请先写产物。" };
1063
+ }
1064
+ attempt.status = "submitted";
1065
+ attempt.submission = { at: now(), ...(summary?.trim() ? { summary: summary.trim().slice(-4000) } : {}) };
1066
+ attempt.finished_at = now();
1067
+ // Git 模式:捕获工作区变更,供独立验证者取证。
1068
+ if (run.state.graph.project.mode === "git" && attempt.workspace?.path) {
1069
+ try {
1070
+ const changes = await captureWorkspaceChanges(attempt.workspace.path, attempt.workspace.baseline ?? run.state.graph.integration?.baseline ?? "", graphNodeArtifactDirOf(workspace, run.state, nodeId, attemptId));
1071
+ attemptsOfNode(run.state, nodeId).find((item) => item.id === attemptId).workspace_changes = {
1072
+ path: changes.path, sha256: changes.sha256, files: changes.files,
1073
+ };
1074
+ }
1075
+ catch (error) {
1076
+ // 同步捕获失败不阻塞交卷:CHECK 仍可读 worktree;把原因写进日志。
1077
+ logEvent(instId, "warn", "workspace_changes_failed", { node: nodeId, attempt: attemptId, error: msg(error) });
1078
+ }
1079
+ }
1080
+ persist(run);
1081
+ history(run, "do_submitted", `attempt=${attemptId}`, nodeId);
1082
+ run.submitWaiters.get(attempt.id)?.resolve({ summary });
1083
+ const submittedNode = run.state.graph.asset.nodes.find((node) => node.id === nodeId);
1084
+ notify(run, `节点 \`${nodeId}\` 已交卷,引擎开始 CHECK/人工门。`, `📥 Graph 节点交卷:${submittedNode ? nodeNameOf(run.state, submittedNode) : nodeId}`);
1085
+ return { ok: true, text: `交卷已受理:节点 \`${nodeId}\`。接下来由引擎执行独立 CHECK(若有)与人工门(若配置);不需要再调用 submit。` };
1086
+ }
1087
+ // ── CHECK ──────────────────────────────────────────────────────────────────
1088
+ async function runCheck(run, node, attempt, check) {
1089
+ if (!attempt.artifact)
1090
+ return null;
1091
+ const artifactPath = attempt.artifact.path;
1092
+ const relArtifact = attempt.artifact.rel ?? workspaceRelative(workspace, artifactPath) ?? artifactPath;
1093
+ const graphScope = {
1094
+ nodeId: node.id,
1095
+ attemptId: attempt.id,
1096
+ doInstruction: node.do,
1097
+ artifact: { path: relArtifact, sha256: attempt.artifact.sha256, size: attempt.artifact.size },
1098
+ inputs: inputRefs(run, node),
1099
+ ...(attempt.workspace?.path ? { workspacePath: attempt.workspace.path } : {}),
1100
+ ...(attempt.workspace_changes?.path ? { workspaceChangesPath: workspaceRelative(workspace, attempt.workspace_changes.path) ?? attempt.workspace_changes.path } : {}),
1101
+ criteriaText: check.criteriaText,
1102
+ criteria: check.criteria,
1103
+ checkMode: "custom",
1104
+ checkVersion: checkVersion(check) ?? "custom",
1105
+ };
1106
+ const request = {
1107
+ instId: run.instId,
1108
+ step: syntheticStep(node, check.criteriaText),
1109
+ workflow: syntheticWorkflow(run.state.graph.asset),
1110
+ userTask: run.state.user_task,
1111
+ assetPath: run.state.graph.asset_path,
1112
+ ...(run.state.owner_session ? { ownerSession: run.state.owner_session } : {}),
1113
+ checkIndex: 0,
1114
+ artifactsRelDir: `${RALPH_FLOW_DIR}/artifacts/${run.state.artifacts_dir_name}/nodes/${node.id}/${attempt.id}`,
1115
+ signal: run.abort.signal,
1116
+ logEvent: (level, event, extra) => logEvent(run.instId, level, event, { ...(extra ?? {}), node: node.id, attempt: attempt.id }),
1117
+ graph: graphScope,
1118
+ };
1119
+ history(run, "verify_start", `attempt=${attempt.id}`, node.id);
1120
+ let verdict;
1121
+ try {
1122
+ verdict = await ports.verify(request);
1123
+ }
1124
+ catch (error) {
1125
+ verdict = { check_index: 0, step_id: node.id, node_id: node.id, attempt_id: attempt.id, ts: now(), status: "infra", reason: `验证委派失败:${msg(error)}` };
1126
+ }
1127
+ if (!verdict || (verdict.status !== "passed" && verdict.status !== "failed" && verdict.status !== "infra")) {
1128
+ verdict = { check_index: 0, step_id: node.id, node_id: node.id, attempt_id: attempt.id, ts: now(), status: "infra", reason: "验证者返回了无法识别的判定(fail-closed)。" };
1129
+ }
1130
+ // infra 自动重试一次(与 Flow 的既有语义一致;不消耗返工预算)。
1131
+ if (verdict.status === "infra" && !run.abort.signal.aborted) {
1132
+ history(run, "verify_infra_retry", verdict.reason, node.id, "warn");
1133
+ try {
1134
+ const retry = await ports.verify(request);
1135
+ if (retry && (retry.status === "passed" || retry.status === "failed" || retry.status === "infra"))
1136
+ verdict = retry;
1137
+ }
1138
+ catch { }
1139
+ }
1140
+ const record = {
1141
+ node_id: node.id,
1142
+ attempt_id: attempt.id,
1143
+ status: verdict.status,
1144
+ reason: verdict.reason,
1145
+ ...(verdict.evidence ? { evidence: verdict.evidence } : {}),
1146
+ ...(verdict.agent_id ? { agent_id: verdict.agent_id } : {}),
1147
+ ts: verdict.ts,
1148
+ check_index: 0,
1149
+ check_mode: graphScope.checkMode,
1150
+ check_version: graphScope.checkVersion,
1151
+ };
1152
+ run.state.graph.verdicts.push(record);
1153
+ persist(run);
1154
+ history(run, `verdict_${record.status}`, record.reason, node.id, record.status === "failed" ? "warn" : "info");
1155
+ return record;
1156
+ }
1157
+ // ── 人工门 ──────────────────────────────────────────────────────────────────
1158
+ async function reviewNode(run, node, attempt) {
1159
+ if (!attempt.artifact)
1160
+ throw new Error("人工门需要节点产物,但 attempt 没有 artifact。");
1161
+ const artifact = { path: workspaceRelative(workspace, attempt.artifact.path) ?? attempt.artifact.path, sha256: attempt.artifact.sha256, size: attempt.artifact.size };
1162
+ const todo = {
1163
+ id: `graph-review-${randomUUID()}`,
1164
+ kind: "manual_review",
1165
+ status: "waiting",
1166
+ node_id: node.id,
1167
+ attempt_id: attempt.id,
1168
+ question: `节点「${nodeNameOf(run.state, node)}」已通过独立 CHECK(或未配置 CHECK),等待你审查产物后明确放行或要求改稿。`,
1169
+ artifact,
1170
+ created_at: now(),
1171
+ };
1172
+ run.state.graph.human_todos.push(todo);
1173
+ persist(run);
1174
+ syncRespondTool(run, run.state.owner_session);
1175
+ history(run, "gate_opened", `todo=${todo.id}`, node.id);
1176
+ notify(run, `节点 \`${node.id}\` 等待你审查:\n产物:\`${artifact.path}\`(sha256 ${artifact.sha256.slice(0, 12)}…)\n明确回复“批准此版本”放行,或说明要改什么。用 \`ralphflow_respond\` 把决定交给引擎。`, `🛑 Graph 人工门:${nodeNameOf(run.state, node)}`);
1177
+ const decision = await waitForReview(run, todo);
1178
+ if (!decision)
1179
+ return null;
1180
+ // 复核产物版本:等待期间被改写 → 门失效。
1181
+ try {
1182
+ const stat = sha256File(attempt.artifact.path);
1183
+ if (stat.sha256 !== todo.artifact.sha256) {
1184
+ todo.status = "stale";
1185
+ todo.answered_at = now();
1186
+ persist(run);
1187
+ history(run, "gate_stale", "artifact changed while waiting", node.id, "warn");
1188
+ notify(run, `节点 \`${node.id}\` 的产物在人工门等待期间被改写,本次放行作废;引擎会重新验证。`, "⚠️ Graph 人工门失效");
1189
+ return null;
1190
+ }
1191
+ }
1192
+ catch {
1193
+ todo.status = "stale";
1194
+ todo.answered_at = now();
1195
+ persist(run);
1196
+ return null;
1197
+ }
1198
+ if (decision.decision === "approve") {
1199
+ todo.status = "approved";
1200
+ todo.answered_at = now();
1201
+ attempt.artifact.accepted = false;
1202
+ if (run.state.graph.status === "waiting")
1203
+ setStatus(run, "running");
1204
+ persist(run);
1205
+ history(run, "gate_released", `todo=${todo.id}`, node.id);
1206
+ return decision;
1207
+ }
1208
+ todo.status = "revise";
1209
+ todo.feedback = decision.feedback;
1210
+ todo.answered_at = now();
1211
+ setStatus(run, "running");
1212
+ persist(run);
1213
+ history(run, "gate_revise", decision.feedback, node.id, "warn");
1214
+ return decision;
1215
+ }
1216
+ function waitForReview(run, todo) {
1217
+ return new Promise((resolve) => {
1218
+ run.reviewWaiters.set(todo.id, {
1219
+ resolve: (value) => {
1220
+ run.reviewWaiters.delete(todo.id);
1221
+ resolve(value);
1222
+ },
1223
+ reject: () => {
1224
+ run.reviewWaiters.delete(todo.id);
1225
+ resolve(null);
1226
+ },
1227
+ });
1228
+ run.abort.signal.addEventListener("abort", () => {
1229
+ const waiter = run.reviewWaiters.get(todo.id);
1230
+ if (waiter) {
1231
+ run.reviewWaiters.delete(todo.id);
1232
+ resolve(null);
1233
+ }
1234
+ }, { once: true });
1235
+ });
1236
+ }
1237
+ function syncRespondTool(run, sessionId) {
1238
+ if (!sessionId)
1239
+ return;
1240
+ const waiting = waitingTodosOfSession(sessionId);
1241
+ const existing = run.respondTools.get(sessionId);
1242
+ if (waiting.length === 0) {
1243
+ if (existing) {
1244
+ try {
1245
+ existing();
1246
+ }
1247
+ catch { }
1248
+ run.respondTools.delete(sessionId);
1249
+ }
1250
+ return;
1251
+ }
1252
+ if (existing)
1253
+ return;
1254
+ const agent = ctx.agents.get(sessionId);
1255
+ const tools = agent?.ctx?.get("tools");
1256
+ if (!tools || !agent)
1257
+ return;
1258
+ const dispose = tools.register(defineTool({
1259
+ name: "ralphflow_respond",
1260
+ description: "回答当前 Graph 人工待办:用户明确批准产物时提交批准,要求改稿时提交用户的修改要求。只在有 Graph 人工待办时可见。",
1261
+ parameters: {
1262
+ text: { type: "string", required: true, description: "用户的原话:批准此版本,或要改什么。" },
1263
+ todoId: { type: "string", description: "可选:明确点名待办 ID(多个待办时用)。" },
1264
+ },
1265
+ output: { schema: { type: "string" }, render: (_args, value) => [{ type: "text", text: value }] },
1266
+ async execute(args, exec) {
1267
+ const text = String(args?.text ?? "");
1268
+ const todoId = args?.todoId;
1269
+ return respondToTodo(exec?.agent, text, typeof todoId === "string" ? todoId : undefined);
1270
+ },
1271
+ }));
1272
+ run.respondTools.set(sessionId, dispose);
1273
+ }
1274
+ function respondToTodo(agent, text, todoId) {
1275
+ const sessionId = agent?.session?.id;
1276
+ if (!sessionId)
1277
+ return "找不到当前会话,无法提交回答。";
1278
+ const candidates = waitingTodosOfSession(sessionId);
1279
+ if (candidates.length === 0)
1280
+ return "当前会话没有等待中的 Graph 人工待办。";
1281
+ let selected;
1282
+ if (todoId)
1283
+ selected = candidates.find((candidate) => candidate.todo.id === todoId);
1284
+ else if (candidates.length === 1)
1285
+ selected = candidates[0];
1286
+ else {
1287
+ return `当前有 ${candidates.length} 个等待中的 Graph 待办,请点名 todoId:\n${candidates.map((candidate) => `- \`${candidate.todo.id}\` · 节点 \`${candidate.todo.node_id}\``).join("\n")}`;
1288
+ }
1289
+ if (!selected)
1290
+ return `没有找到待办 \`${todoId}\`;当前等待中:${candidates.map((candidate) => `\`${candidate.todo.id}\``).join("、")}。`;
1291
+ const { todo } = selected;
1292
+ const classified = classifyManualResponse(text);
1293
+ if (classified.kind === "clarify") {
1294
+ return classified.reason === "conflicting_intent"
1295
+ ? "你的回复同时包含“批准”和“改稿要求”,引擎不猜。请明确回复“批准此版本”,或只写要改什么。"
1296
+ : "请明确回复“批准此版本”放行,或说明要改什么(引擎不会把含糊回复当成批准)。";
1297
+ }
1298
+ const run = runs.get(selected.run.instId) ?? restoreRun(selected.run.instId);
1299
+ if (!run)
1300
+ return `实例 \`${selected.run.instId}\` 已不在内存中;用 /ralphflow-continue 恢复后再回答。`;
1301
+ const waiter = run.reviewWaiters.get(todo.id);
1302
+ if (!waiter)
1303
+ return "这个待办已经失效(可能已被取消或过期)。";
1304
+ if (run.state.graph.status === "paused") {
1305
+ // 暂停中允许先记录,恢复时再送达;简化:直接送达(人工门本身就是恢复点)。
1306
+ setStatus(run, "running");
1307
+ }
1308
+ waiter.resolve({ decision: classified.kind === "approve" ? "approve" : "revise", feedback: text.trim() });
1309
+ return classified.kind === "approve"
1310
+ ? `已把“批准”交给引擎:节点 \`${todo.node_id}\` 的产物将进入接纳流程。`
1311
+ : `已把改稿要求交给引擎:节点 \`${todo.node_id}\` 会开新 attempt。`;
1312
+ }
1313
+ /**
1314
+ * 接纳必须**串行**:集成分支每个 run 只有一条,并行节点依次快进。
1315
+ * 但验收本身是机械的:节点分支已经包含集成分支头,就前进引用;否则退回节点。
1316
+ */
1317
+ /** 显式 continue 后的接纳失败:把 attempt 标成 rejected,调度器会开新 attempt 重做这一步。 */
1318
+ function rejectIfNotFastForward(run, node, attempt, result) {
1319
+ if (!result || result.ok)
1320
+ return;
1321
+ attempt.status = "rejected";
1322
+ attempt.finished_at = now();
1323
+ run.state.graph.integration_retries[node.id] = 0;
1324
+ persist(run);
1325
+ history(run, "node_rework", result.reason, node.id, "warn");
1326
+ }
1327
+ async function acceptAttempt(run, node, attempt, checkMode) {
1328
+ const previous = run.acceptTail;
1329
+ let release;
1330
+ run.acceptTail = new Promise((resolve) => { release = resolve; });
1331
+ await previous;
1332
+ try {
1333
+ // 排队期间 run 可能已被暂停:别往暂停的 run 里写接纳记录。
1334
+ if (run.state.graph.status !== "running")
1335
+ return { ok: true };
1336
+ return await acceptAttemptLocked(run, node, attempt, checkMode);
1337
+ }
1338
+ finally {
1339
+ release();
1340
+ }
1341
+ }
1342
+ async function acceptAttemptLocked(run, node, attempt, checkMode) {
1343
+ if (!attempt.artifact)
1344
+ throw new Error("接纳需要节点产物。");
1345
+ const artifact = attempt.artifact;
1346
+ let integration;
1347
+ if (run.state.graph.project.mode === "git" && attempt.workspace?.path) {
1348
+ const accepted = await fastForwardIntegration(run, node, attempt);
1349
+ if (!accepted.ok)
1350
+ return accepted;
1351
+ integration = accepted.integration;
1352
+ }
1353
+ artifact.accepted = true;
1354
+ const acceptance = {
1355
+ node_id: node.id,
1356
+ attempt_id: attempt.id,
1357
+ accepted_at: now(),
1358
+ artifact_sha256: artifact.sha256,
1359
+ check_mode: checkMode,
1360
+ manual_approval: run.state.graph.asset.manual_step.includes(node.id),
1361
+ ...(integration ? { integration } : {}),
1362
+ };
1363
+ run.state.graph.acceptances.push(acceptance);
1364
+ attempt.artifact = { ...artifact, accepted: true };
1365
+ run.state.graph.rework_counts[node.id] = 0;
1366
+ run.state.graph.integration_retries[node.id] = 0;
1367
+ persist(run);
1368
+ history(run, "node_accepted", `attempt=${attempt.id}${integration ? ` commit=${integration.commit}` : ""}`, node.id);
1369
+ notify(run, `节点 \`${node.id}\` 已${integration ? `合入 \`${integration.branch}\`(${integration.commit.slice(0, 12)}…)` : "完成"}。`, `✅ Graph 节点完成:${nodeNameOf(run.state, node)}`);
1370
+ wake(run);
1371
+ return { ok: true };
1372
+ }
1373
+ /**
1374
+ * 快进集成分支。节点分支必须已经包含集成分支头 —— 那是节点自己「合入集成分支」的结果;
1375
+ * 不包含就退回节点,不在这里替它合并。
1376
+ */
1377
+ async function fastForwardIntegration(run, node, attempt) {
1378
+ const projectRoot = run.state.graph.project.root;
1379
+ const integration = run.state.graph.integration;
1380
+ if (!projectRoot || !integration)
1381
+ throw new Error("Git 模式缺少 project root 或集成分支记录。");
1382
+ if (!attempt.workspace?.path)
1383
+ throw new Error("节点缺少 worktree。");
1384
+ const previous = (await branchTip(projectRoot, integration.branch)) ?? integration.current_commit;
1385
+ if (previous !== integration.current_commit)
1386
+ integration.current_commit = previous;
1387
+ const base = attempt.workspace.baseline ?? integration.baseline;
1388
+ // 验收看状态里记录的节点分支:worktree 的游离 HEAD 不是合入对象。
1389
+ const worktree = run.state.graph.worktrees.find((item) => item.node_id === node.id);
1390
+ if (!worktree?.branch) {
1391
+ throw new Error(`节点 \`${node.id}\` 缺少 worktree 分支记录,无法验收;检查 state.json 的 worktrees。`);
1392
+ }
1393
+ const nodeBranch = worktree.branch;
1394
+ const readiness = await nodeReadyForIntegration({
1395
+ worktreePath: attempt.workspace.path,
1396
+ nodeBranch,
1397
+ baseline: base,
1398
+ integrationBranch: integration.branch,
1399
+ integrationTip: previous,
1400
+ });
1401
+ if (!readiness.ok)
1402
+ return { ok: false, reason: readiness.reason };
1403
+ if (readiness.aligned)
1404
+ history(run, "node_branch_aligned", `${nodeBranch} -> ${readiness.head}`, node.id);
1405
+ const commit = readiness.head;
1406
+ if (commit !== previous) {
1407
+ await advanceIntegration(projectRoot, integration.branch, previous, commit);
1408
+ history(run, "integration_advanced", `${previous} -> ${commit}`, node.id);
1409
+ }
1410
+ integration.current_commit = commit;
1411
+ return {
1412
+ ok: true,
1413
+ integration: { branch: integration.branch, previous_commit: previous, commit, base_commit: base },
1414
+ };
1415
+ }
1416
+ // ── 生命周期 ────────────────────────────────────────────────────────────────
1417
+ /** 恢复实例时确保集成分支存在(新实例在 start 里建;缺分支的保留实例在这里补齐)。 */
1418
+ async function ensureIntegrationBranchFor(run) {
1419
+ const projectRoot = run.state.graph.project.root;
1420
+ const integration = run.state.graph.integration;
1421
+ if (!projectRoot || !integration)
1422
+ return;
1423
+ const tip = await ensureIntegrationBranch(projectRoot, integration.branch, integration.current_commit);
1424
+ integration.current_commit = tip;
1425
+ }
1426
+ function restoreRun(instId) {
1427
+ if (runs.has(instId))
1428
+ return runs.get(instId);
1429
+ const state = readGraphState(workspace, instId);
1430
+ if (!state)
1431
+ return null;
1432
+ const run = {
1433
+ instId,
1434
+ state,
1435
+ artifactRoot: path.join(artifactsRoot, state.artifacts_dir_name),
1436
+ ...(state.graph.project.root ? { projectRoot: state.graph.project.root } : {}),
1437
+ submitWaiters: new Map(),
1438
+ reviewWaiters: new Map(),
1439
+ active: new Map(),
1440
+ agents: new Map(),
1441
+ abort: new AbortController(),
1442
+ wake: null,
1443
+ respondTools: new Map(),
1444
+ mainBusy: false,
1445
+ schedulerActive: false,
1446
+ schedulerRestart: false,
1447
+ acceptTail: Promise.resolve(),
1448
+ };
1449
+ runs.set(instId, run);
1450
+ return run;
1451
+ }
1452
+ /**
1453
+ * 宿主重开:只处理「running 但没有属主」的实例,**不自动推进**。
1454
+ *
1455
+ * 判据是实例心跳(`owner.ts`):过 TTL/缺失 → 立刻标中断;还新鲜 → 可能是另一个活着的
1456
+ * host,也可能是快速重启,等一个刷新窗口看心跳是否继续往前走来判定。审查门/暂停不动。
1457
+ * 心跳仍是「另一个 dsh 还活着」的唯一凭据;只看引擎启动会误伤它。
1458
+ */
1459
+ function restore() {
1460
+ for (const { id, state } of listStates()) {
1461
+ if (!state.active || state.graph.status !== "running")
1462
+ continue;
1463
+ if (!ownerAlive(state)) {
1464
+ const run = runs.get(id) ?? restoreRun(id);
1465
+ if (run)
1466
+ markInterrupted(run);
1467
+ continue;
1468
+ }
1469
+ // 心跳的属主就是本进程:我们知道自己活着,不必再复查。
1470
+ if (state.owner_runtime === runtimeId())
1471
+ continue;
1472
+ scheduleOwnerRecheck(id, state.owner_heartbeat_at ?? 0);
1473
+ }
1474
+ }
1475
+ /** 把「属主已失联」落盘为 interrupted(不自动继续)。 */
1476
+ function markInterrupted(run) {
1477
+ if (run.state.graph.status !== "running")
1478
+ return;
1479
+ run.state.graph.status = "interrupted";
1480
+ run.state.active = true;
1481
+ run.state.graph.pause_reason = "host_restarted";
1482
+ for (const attempt of run.state.graph.attempts) {
1483
+ if (attempt.status === "running") {
1484
+ attempt.status = "interrupted";
1485
+ attempt.interrupted_at = now();
1486
+ attempt.finished_at = now();
1487
+ attempt.failure = { kind: "interrupted", message: "驱动这个实例的运行时不在了。" };
1488
+ }
1489
+ }
1490
+ history(run, "interrupted", "owner runtime lost; resume with /ralphflow-continue");
1491
+ persist(run);
1492
+ notify(run, `⏸ Graph 已中断:驱动这个实例的运行时不在了(宿主重启或进程退出)。状态、判定与产物都保留;用 /ralphflow-continue 继续。`, "⏸ Graph 已中断:属主运行时失联");
1493
+ log("info", "graph_interrupted_restored", { instId: run.instId });
1494
+ }
1495
+ /**
1496
+ * 快速复查:等一个刷新窗口,心跳还没有往前走,才判属主已死。
1497
+ * 定时器 unref;实例被继续/暂停/结束时条件自然不成立,复查是空操作。
1498
+ */
1499
+ function scheduleOwnerRecheck(instId, beatAt) {
1500
+ const delay = ownerRecheckMs();
1501
+ if (delay <= 0)
1502
+ return;
1503
+ const timer = setTimeout(() => {
1504
+ try {
1505
+ const state = readGraphState(workspace, instId);
1506
+ if (!state || !state.active || state.graph.status !== "running")
1507
+ return;
1508
+ if ((state.owner_heartbeat_at ?? 0) > beatAt)
1509
+ return; // 另一个活着的属主刚刷过
1510
+ const run = runs.get(instId) ?? restoreRun(instId);
1511
+ if (run)
1512
+ markInterrupted(run);
1513
+ }
1514
+ catch (error) {
1515
+ log("warn", "graph_owner_recheck_failed", { instId, error: msg(error) });
1516
+ }
1517
+ }, delay);
1518
+ timer.unref?.();
1519
+ }
1520
+ async function continueInstance(sessionId, instanceRef) {
1521
+ const target = findInstance(sessionId, instanceRef);
1522
+ if (!target)
1523
+ return { ok: false, text: "找不到可继续的 Graph 实例。" };
1524
+ const run = runs.get(target.id) ?? restoreRun(target.id);
1525
+ if (!run)
1526
+ return { ok: false, text: `Graph 实例 \`${target.id}\` 的状态不可读,无法继续。` };
1527
+ if (run.state.owner_session && run.state.owner_session !== sessionId && !instanceRef) {
1528
+ return { ok: false, text: `实例 \`${target.id}\` 属于会话 \`${run.state.owner_session}\`;要接管请显式给实例 ID。` };
1529
+ }
1530
+ if (run.state.graph.status === "completed" || run.state.graph.status === "cancelled") {
1531
+ return { ok: false, text: `实例 \`${target.id}\` 已${run.state.graph.status === "completed" ? "完成" : "取消"},不能继续。` };
1532
+ }
1533
+ if (run.state.graph.human_todos.some((todo) => todo.status === "waiting")) {
1534
+ return { ok: false, text: `实例 \`${target.id}\` 正在等待人工审查;请先明确批准或要求改稿(ralphflow_respond),不能代答。` };
1535
+ }
1536
+ // 属主已失联、但复查还没落盘:显式 continue 就是最快的恢复入口,别用"正在运行"挡住用户。
1537
+ if (run.state.graph.status === "running" && !ownerAlive(run.state))
1538
+ markInterrupted(run);
1539
+ if (run.state.graph.status === "running") {
1540
+ return { ok: true, text: `实例 \`${target.id}\` 正在运行,无需继续。` };
1541
+ }
1542
+ const prev = run.state.graph.status;
1543
+ const prevReason = run.state.graph.pause_reason;
1544
+ // 显式给实例 ID 的 continue 是接管:属主随当前会话,否则后续节点 agent 会被投递到
1545
+ // 已关闭的旧会话。
1546
+ if (instanceRef || !run.state.owner_session)
1547
+ run.state.owner_session = sessionId;
1548
+ // 恢复 = 本运行时重新持有属主;先写心跳再由 setStatus 一并落盘。
1549
+ stampOwner(run.state);
1550
+ try {
1551
+ await ensureIntegrationBranchFor(run);
1552
+ }
1553
+ catch (error) {
1554
+ return { ok: false, text: `实例 \`${target.id}\` 的集成分支无法就绪:${msg(error)}` };
1555
+ }
1556
+ setStatus(run, "running");
1557
+ history(run, "resume", `from=${prev}${prevReason ? ` reason=${prevReason}` : ""}`);
1558
+ // 主节点还在跑:DO 只投递过一次,暂停期间回合已经结束,恢复时必须补一条继续指令,
1559
+ // 否则模型会一直停在那里(no_submit 暂停就是这种形态)。
1560
+ const mainNode = run.state.graph.asset.nodes.find((item) => item.execution === "main");
1561
+ const mainAttempt = mainNode ? latestAttemptOfNode(run.state, mainNode.id) : undefined;
1562
+ if (mainNode && mainAttempt?.status === "running") {
1563
+ notify(run, `[ralphflow] Graph 实例已恢复:节点 \`${mainNode.id}\` 的 attempt 还在进行。产物写好后,调用 \`ralphflow_submit\` 结束本轮;还有没完成的事项就写进 \`unfinished\`,没有就留空。`, `▶️ Graph 已恢复:节点 ${nodeNameOf(run.state, mainNode)} 继续执行`, true);
1564
+ }
1565
+ // 已经通过 CHECK/人工门但还没合入的节点:只重试合入,不重做 DO。
1566
+ for (const node of run.state.graph.asset.nodes) {
1567
+ if (acceptanceOfNode(run.state, node.id))
1568
+ continue;
1569
+ const attempt = latestAttemptOfNode(run.state, node.id);
1570
+ if (!attempt)
1571
+ continue;
1572
+ if (attempt.status === "interrupted") {
1573
+ attempt.status = "failed";
1574
+ // 保留中断的真实原因:用户暂停写的是「你停止了运行」,宿主重启写的是「运行时不在了」。
1575
+ if (attempt.failure?.kind !== "interrupted") {
1576
+ attempt.failure = { kind: "interrupted", message: "宿主重启中断了这次 attempt。" };
1577
+ }
1578
+ persist(run);
1579
+ continue;
1580
+ }
1581
+ if (attempt.status !== "submitted")
1582
+ continue;
1583
+ const check = node.check ? checkDefinition(node.check.criteria) : checkDefinition(null);
1584
+ const verdict = node.check ? verdictOfAttempt(run.state, attempt.id) : undefined;
1585
+ if (node.check && (!verdict || verdict.status === "infra" || verdict.status === "failed")) {
1586
+ // 暂停时没有完成判定(infra/中断)或判定未通过:显式 continue 是用户对重试的授权,
1587
+ // 给这一节点一次新的返工预算,然后让调度器开新 attempt(不偷偷把失败算成通过)。
1588
+ attempt.status = "rejected";
1589
+ attempt.finished_at = now();
1590
+ run.state.graph.rework_counts[node.id] = 0;
1591
+ persist(run);
1592
+ history(run, "node_retry_requested", verdict ? `previous=${verdict.status}` : "no verdict", node.id);
1593
+ continue;
1594
+ }
1595
+ if (run.state.graph.asset.manual_step.includes(node.id)) {
1596
+ const approved = run.state.graph.human_todos.some((todo) => todo.node_id === node.id && todo.status === "approved");
1597
+ if (approved) {
1598
+ await rejectIfNotFastForward(run, node, attempt, await acceptAttempt(run, node, attempt, check.mode));
1599
+ continue;
1600
+ }
1601
+ if (!waitingTodoOfNode(run.state, node.id)) {
1602
+ void reviewNode(run, node, attempt).then(async (decision) => {
1603
+ if (!decision)
1604
+ return;
1605
+ if (decision.decision === "approve") {
1606
+ const accepted = await acceptAttempt(run, node, attempt, check.mode).catch((error) => { onNodeError(run, node, error); return null; });
1607
+ if (accepted)
1608
+ rejectIfNotFastForward(run, node, attempt, accepted);
1609
+ }
1610
+ });
1611
+ }
1612
+ continue;
1613
+ }
1614
+ if (!node.check || verdict?.status === "passed") {
1615
+ await rejectIfNotFastForward(run, node, attempt, await acceptAttempt(run, node, attempt, check.mode));
1616
+ }
1617
+ }
1618
+ if (allReleased(run)) {
1619
+ completeRun(run);
1620
+ return { ok: true, text: `实例 \`${target.id}\` 的节点已全部释放,本次继续后完成。` };
1621
+ }
1622
+ startScheduler(run, (error) => onNodeError(run, run.state.graph.asset.nodes[0], error));
1623
+ return { ok: true, text: `已恢复 Graph 实例 \`${target.id}\`(${prev} → running),调度器会继续就绪节点。` };
1624
+ }
1625
+ /**
1626
+ * 用户要求暂停(停止按钮,或输入区的暂停按钮)。
1627
+ *
1628
+ * 只要有**任一节点 attempt 在飞**就暂停:Graph 的常态是后台节点,主会话只是调度入口,
1629
+ * 不能因为主回合空闲就拒绝暂停。在飞 attempt 标 `interrupted`(continue 按既有
1630
+ * interrupted 路径重试),后台 agent 直接 dispose,主回合的 submit 等待解开。
1631
+ *
1632
+ * 已交卷/验证中/没有在飞节点时不暂停:验证不该被停止键打断(与 Flow 同一条纪律)。
1633
+ * 先落盘暂停、再中断 agent,避免另一个 host 看到"在飞 + 无主"。
1634
+ */
1635
+ function pauseForUserStop(sessionId) {
1636
+ const target = activeInstanceOfSession(sessionId);
1637
+ if (!target)
1638
+ return { ok: false, text: "当前会话没有活跃的 Graph 实例,不需要暂停。" };
1639
+ const run = runs.get(target.id) ?? restoreRun(target.id);
1640
+ if (!run)
1641
+ return { ok: false, text: `Graph 实例 \`${target.id}\` 的状态不可读,无法暂停。` };
1642
+ if (run.state.graph.status !== "running") {
1643
+ return { ok: false, text: `Graph 实例 \`${target.id}\` 当前是 ${run.state.graph.status},不在执行中。` };
1644
+ }
1645
+ const running = run.state.graph.attempts.filter((attempt) => attempt.status === "running");
1646
+ if (running.length === 0) {
1647
+ return { ok: false, text: "当前没有正在执行的节点(可能在验证或等待),停止回合不按暂停处理。" };
1648
+ }
1649
+ const disposers = [];
1650
+ for (const attempt of running) {
1651
+ attempt.status = "interrupted";
1652
+ attempt.interrupted_at = now();
1653
+ attempt.finished_at = now();
1654
+ attempt.failure = { kind: "interrupted", message: "你停止了运行。" };
1655
+ const handle = run.agents.get(attempt.id);
1656
+ if (handle) {
1657
+ run.agents.delete(attempt.id);
1658
+ if (typeof handle.dispose === "function")
1659
+ disposers.push(() => handle.dispose());
1660
+ }
1661
+ run.submitWaiters.get(attempt.id)?.reject(new Error("paused by user"));
1662
+ run.submitWaiters.delete(attempt.id);
1663
+ }
1664
+ const nodes = [...new Set(running.map((attempt) => attempt.node_id))];
1665
+ history(run, "pause", `user_stop ${nodes.map((id) => `node=${id}`).join(" ")}`, running[0].node_id);
1666
+ setStatus(run, "paused", "user_stop");
1667
+ for (const dispose of disposers) {
1668
+ void dispose().catch(() => undefined);
1669
+ }
1670
+ notify(run, `⏸ Graph 已暂停(你停止了运行);${running.length} 个在飞节点已中断,不再启动新节点。用 /ralphflow-continue 继续。`, "⏸ Graph 已暂停:你停止了运行");
1671
+ return { ok: true, text: `Graph 实例 \`${target.id}\` 已暂停(你停止了运行)。` };
1672
+ }
1673
+ async function cancelInstance(sessionId, instanceRef, reason) {
1674
+ const target = findInstance(sessionId, instanceRef);
1675
+ if (!target)
1676
+ return { ok: false, text: "找不到要取消的 Graph 实例。" };
1677
+ const run = runs.get(target.id) ?? restoreRun(target.id);
1678
+ if (!run)
1679
+ return { ok: false, text: "状态不可读,无法取消。" };
1680
+ if (run.state.graph.status === "completed" || run.state.graph.status === "cancelled") {
1681
+ return { ok: false, text: `实例 \`${target.id}\` 已${run.state.graph.status === "completed" ? "完成" : "取消"}。` };
1682
+ }
1683
+ run.abort.abort();
1684
+ for (const waiter of run.submitWaiters.values())
1685
+ waiter.reject(new Error("run cancelled"));
1686
+ run.submitWaiters.clear();
1687
+ for (const waiter of run.reviewWaiters.values())
1688
+ waiter.reject(new Error("run cancelled"));
1689
+ run.reviewWaiters.clear();
1690
+ for (const todo of run.state.graph.human_todos) {
1691
+ if (todo.status === "waiting") {
1692
+ todo.status = "cancelled";
1693
+ todo.answered_at = now();
1694
+ }
1695
+ }
1696
+ for (const attempt of run.state.graph.attempts) {
1697
+ if (attempt.status === "running") {
1698
+ attempt.status = "cancelled";
1699
+ attempt.finished_at = now();
1700
+ }
1701
+ }
1702
+ setStatus(run, "cancelled", reason ? `user: ${reason}` : "user_cancelled");
1703
+ history(run, "cancelled", reason ?? "user_cancelled");
1704
+ for (const dispose of run.respondTools.values()) {
1705
+ try {
1706
+ dispose();
1707
+ }
1708
+ catch { }
1709
+ }
1710
+ run.respondTools.clear();
1711
+ for (const handle of run.agents.values()) {
1712
+ try {
1713
+ await handle.dispose();
1714
+ }
1715
+ catch { }
1716
+ }
1717
+ run.agents.clear();
1718
+ finalize(run);
1719
+ return { ok: true, text: `已取消 Graph 实例 \`${target.id}\`;报告已归档,状态、日志、产物与 worktree 保留供复核。worktree 要在复核后删除时,执行 /ralphflow-cleanup 只清理其中干净的那部分。` };
1720
+ }
1721
+ function findInstance(sessionId, instanceRef) {
1722
+ const all = listStates();
1723
+ if (instanceRef) {
1724
+ const exact = all.find((entry) => entry.id === instanceRef);
1725
+ if (exact)
1726
+ return exact;
1727
+ const prefixed = all.filter((entry) => entry.id.startsWith(instanceRef));
1728
+ return prefixed.length === 1 ? prefixed[0] : undefined;
1729
+ }
1730
+ return all.filter((entry) => entry.state.owner_session === sessionId).at(-1);
1731
+ }
1732
+ async function cleanupInstance(instanceRef) {
1733
+ const all = listStates();
1734
+ const target = instanceRef
1735
+ ? all.find((entry) => entry.id === instanceRef) ?? all.find((entry) => entry.id.startsWith(instanceRef))
1736
+ : all.filter((entry) => isGraphTerminal(entry.state.graph.status)).at(-1);
1737
+ if (!target)
1738
+ return { ok: false, text: "找不到可清理的 Graph 实例。" };
1739
+ const { id, state } = target;
1740
+ if (state.active && !isGraphTerminal(state.graph.status)) {
1741
+ return { ok: false, text: `实例 \`${id}\` 还在 ${state.graph.status};只清理已结束实例的干净 worktree。` };
1742
+ }
1743
+ if (state.graph.project.mode !== "git")
1744
+ return { ok: true, text: `Graph 实例 \`${id}\` 使用 artifact 测试工作区,没有 worktree 需要清理。` };
1745
+ const projectRoot = state.graph.project.root;
1746
+ if (!projectRoot)
1747
+ return { ok: false, text: `实例 \`${id}\` 没有 project root 记录,无法清理。` };
1748
+ const removed = [];
1749
+ const kept = [];
1750
+ const keepReason = (reason) => {
1751
+ switch (reason) {
1752
+ case "worktree_has_changes": return "有未提交或未跟踪的改动";
1753
+ case "not_registered": return "不在 git worktree 注册表里";
1754
+ case "unreadable": return "无法读取工作树状态";
1755
+ default: return reason ?? "未删除";
1756
+ }
1757
+ };
1758
+ for (const worktree of state.graph.worktrees) {
1759
+ const result = await removeCleanWorktree(projectRoot, worktree.path);
1760
+ if (result.removed)
1761
+ removed.push(worktree.node_id);
1762
+ else
1763
+ kept.push(`${worktree.node_id}(${keepReason(result.reason)})`);
1764
+ }
1765
+ // 保留的 worktree 连同它的 git 注册与目录原样留下;只在目录确实为空时收掉 worktrees 根。
1766
+ // 不递归删除:否则会把刚判定“保留”的目录一起抹掉,注册表还会留下 prunable。
1767
+ const worktreesRoot = worktreeRootOf(workspace, id);
1768
+ try {
1769
+ if (fs.existsSync(worktreesRoot) && fs.readdirSync(worktreesRoot).length === 0)
1770
+ fs.rmdirSync(worktreesRoot);
1771
+ }
1772
+ catch { }
1773
+ logEvent(id, "info", "cleanup", { removed, kept });
1774
+ return {
1775
+ ok: true,
1776
+ text: `已清理 Graph 实例 \`${id}\` 的干净 worktree:${removed.length > 0 ? removed.join("、") : "(无)"}。${kept.length > 0 ? `保留(路径与 git worktree 注册均未动):${kept.join(";")}。` : ""}state、artifacts、reports 一律未动。`,
1777
+ };
1778
+ }
1779
+ // ── 状态 / 诊断 ──────────────────────────────────────────────────────────────
1780
+ function formatProjection(projection) {
1781
+ const lines = [
1782
+ `## Graph 实例 \`${projection.id}\` — ${projection.workflow}`,
1783
+ "",
1784
+ `- 状态:**${projection.phase}**(${projection.status})`,
1785
+ `- 节点:${projection.counts.completed}/${projection.counts.total} 完成 · ${projection.counts.running} 在飞 · ${projection.counts.waiting} 等待 · ${projection.counts.blocked} 阻塞`,
1786
+ ...(projection.current ? [`- 当前节点:\`${projection.current.nodeId}\`(${projection.current.name})· ${projection.current.status}`] : []),
1787
+ ...(projection.nextAction ? [`- 下一步:${projection.nextAction.message}`] : []),
1788
+ ...(projection.integration ? [`- 集成分支:\`${projection.integration.branch}\` @ \`${projection.integration.currentCommit.slice(0, 12)}…\`(已接纳 ${projection.integration.accepted})`] : []),
1789
+ `- 交付:已交付 ${projection.delivery.delivered} · 未接纳 ${projection.delivery.unaccepted} · 未验证 ${projection.delivery.unverified} · 未完成 ${projection.delivery.unfinished}`,
1790
+ `- 报告:${projection.report ? `\`${projection.report}\`` : "(运行中,结束后归档)"}`,
1791
+ "",
1792
+ "### 节点",
1793
+ "",
1794
+ ...projection.nodes.map((node) => `- ${node.current ? "▶" : " "} \`${node.id}\` ${node.name} — **${node.label}**;尝试 ${node.attempts};CHECK ${node.check.mode}/${node.check.status}${node.check.reworks > 0 ? ` · 返工 ${node.check.reworks}` : ""}${node.artifact ? `;产物 \`${node.artifact.path}\`` : ""}`),
1795
+ "",
1796
+ "### 最近轨迹",
1797
+ "",
1798
+ ...(listStates().find((entry) => entry.id === projection.id)?.state.history.slice(-6).map((entry) => `- \`${entry.ts}\` **${entry.event}**${entry.step ? ` [${entry.step}]` : ""}${entry.detail ? ` — ${entry.detail}` : ""}`) ?? []),
1799
+ ];
1800
+ return lines.join("\n");
1801
+ }
1802
+ /** 让当前会话的 Graph 人工待办在(重开的)会话作用域里重新可见。 */
1803
+ function syncSession(sessionId) {
1804
+ const active = activeInstanceOfSession(sessionId);
1805
+ if (active) {
1806
+ const run = runs.get(active.id) ?? restoreRun(active.id);
1807
+ if (run)
1808
+ syncRespondTool(run, sessionId);
1809
+ return;
1810
+ }
1811
+ const retained = listStates().filter((entry) => entry.state.owner_session === sessionId).at(-1);
1812
+ if (!retained)
1813
+ return;
1814
+ const run = runs.get(retained.id) ?? restoreRun(retained.id);
1815
+ if (run)
1816
+ syncRespondTool(run, sessionId);
1817
+ }
1818
+ function statusOf(sessionId, instanceRef) {
1819
+ syncSession(sessionId);
1820
+ if (instanceRef) {
1821
+ const target = findInstance(sessionId, instanceRef);
1822
+ if (!target)
1823
+ return { ok: false, text: `没有找到 Graph 实例 \`${instanceRef}\`。` };
1824
+ return { ok: true, text: formatProjection(projectionOf(target.state, target.id)) };
1825
+ }
1826
+ const active = activeInstanceOfSession(sessionId);
1827
+ const retained = listStates().filter((entry) => entry.state.owner_session === sessionId).at(-1);
1828
+ const chosen = active ?? retained;
1829
+ if (!chosen)
1830
+ return { ok: false, text: "当前会话没有 Graph 实例。" };
1831
+ return { ok: true, text: formatProjection(projectionOf(chosen.state, chosen.id)) };
1832
+ }
1833
+ function listAll() {
1834
+ const workflows = listWorkflows();
1835
+ const states = listStates();
1836
+ const lines = ["## Graph 工作流", ""];
1837
+ if (workflows.length === 0)
1838
+ lines.push("(没有 Graph 工作流)");
1839
+ for (const workflow of workflows) {
1840
+ lines.push(`${workflow.invalid ? "❌" : "✅"} **${workflow.name}**(${workflow.nodes} 节点)${workflow.desc ? `:${workflow.desc}` : ""}`);
1841
+ for (const problem of workflow.problems)
1842
+ lines.push(` - ${problem}`);
1843
+ for (const warning of workflow.warnings)
1844
+ lines.push(` - ⚠️ ${warning}`);
1845
+ }
1846
+ lines.push("", "## Graph 实例", "");
1847
+ if (states.length === 0)
1848
+ lines.push("(暂无 Graph 实例)");
1849
+ for (const { id, state } of states) {
1850
+ const projection = projectionOf(state, id);
1851
+ lines.push(`- \`${id}\` — ${state.workflow_name} · ${projection.phase} · ${projection.counts.completed}/${projection.counts.total}`);
1852
+ }
1853
+ return { ok: true, text: lines.join("\n") };
1854
+ }
1855
+ function diagnose() {
1856
+ const lines = ["## Graph 工作流诊断", ""];
1857
+ const workflows = listWorkflows();
1858
+ if (workflows.length === 0)
1859
+ lines.push("(没有 Graph 工作流)");
1860
+ for (const workflow of workflows) {
1861
+ if (workflow.invalid) {
1862
+ lines.push(`- ❌ **${workflow.name}**:定义无效`);
1863
+ for (const problem of workflow.problems)
1864
+ lines.push(` - ${problem}`);
1865
+ }
1866
+ else {
1867
+ lines.push(`- ✅ **${workflow.name}**:${workflow.desc || "(无描述)"}`);
1868
+ for (const warning of workflow.warnings)
1869
+ lines.push(` - ⚠️ ${warning}`);
1870
+ }
1871
+ lines.push("");
1872
+ }
1873
+ lines.push("## Graph 实例诊断", "");
1874
+ const states = listStates();
1875
+ if (states.length === 0)
1876
+ lines.push("(暂无 Graph 实例)");
1877
+ for (const { id, state } of states) {
1878
+ const projection = projectionOf(state, id);
1879
+ if (state.active) {
1880
+ lines.push(`- \`${id}\` — ${state.workflow_name} · ${projection.phase}${state.graph.pause_reason ? `(${pauseLabel(state.graph.pause_reason)})` : ""}`);
1881
+ }
1882
+ else {
1883
+ lines.push(`- \`${id}\` — ${state.workflow_name} · 已结束(${state.graph.status},状态保留供复核)`);
1884
+ }
1885
+ }
1886
+ lines.push("", "结论:所有 ❌ 项即阻塞项,修复后重跑本命令直至全部 ✅。");
1887
+ return { ok: true, text: lines.join("\n") };
1888
+ }
1889
+ /**
1890
+ * 主执行节点的回合收尾检查(宿主 `agent/turn-stopping` 调用)。
1891
+ *
1892
+ * 判定与 Flow 同一条:有动作的重置连续计数;连续空回合到上限就暂停整个 run。
1893
+ * 暂停后主节点的 attempt 仍在等交卷 —— 恢复时由 {@link continueInstance} 重新投递继续指令,
1894
+ * 否则模型会停在原地(DO 只投递过一次)。
1895
+ */
1896
+ function reminderStateOf(run, nodeId, lastActionAt) {
1897
+ // 边界:这个节点的 attempt 起点;用户 `/ralphflow-continue` 之后重新计数。
1898
+ let from = -1;
1899
+ for (let i = 0; i < run.state.history.length; i++) {
1900
+ const h = run.state.history[i];
1901
+ if (h.step === nodeId && h.event === "node_start")
1902
+ from = i;
1903
+ else if (h.event === "resume" && from >= 0)
1904
+ from = i;
1905
+ }
1906
+ let stalls = 0;
1907
+ let last = -1;
1908
+ for (let i = from + 1; i < run.state.history.length; i++) {
1909
+ const h = run.state.history[i];
1910
+ if (h.step !== nodeId)
1911
+ continue;
1912
+ if (h.event === "submit_activity") {
1913
+ stalls = 0;
1914
+ last = i;
1915
+ }
1916
+ else if (h.event === "submit_reminder") {
1917
+ stalls++;
1918
+ last = i;
1919
+ }
1920
+ }
1921
+ const anchor = last >= 0 ? run.state.history[last].ts : from >= 0 ? run.state.history[from].ts : undefined;
1922
+ const anchorMs = anchor ? Date.parse(anchor) : Number.NaN;
1923
+ const worked = lastActionAt !== undefined && Number.isFinite(anchorMs) && lastActionAt > anchorMs;
1924
+ return { stalls, worked };
1925
+ }
1926
+ function remindToSubmit(sessionId) {
1927
+ const main = activeMainAttemptOfSession(sessionId);
1928
+ if (!main)
1929
+ return { remind: false };
1930
+ const { run, node, attempt } = main;
1931
+ if (run.state.graph.status !== "running")
1932
+ return { remind: false };
1933
+ const { stalls, worked } = reminderStateOf(run, node.id, ports.lastActionAt?.(sessionId));
1934
+ // 与 Flow 同一条:只有连续空回合到上限才暂停(干着活不被次数掐停)。
1935
+ const stalledOut = !worked && stalls >= SUBMIT_REMINDER_STALL_LIMIT;
1936
+ if (stalledOut) {
1937
+ const emptyRounds = stalls + 1;
1938
+ const why = `连续 ${emptyRounds} 个回合没有调用任何工具`;
1939
+ // 先记轨迹再改状态:setStatus 会 persist,顺序反了磁盘上就少了这条暂停原因。
1940
+ history(run, "reminder_exhausted", why, node.id, "warn");
1941
+ setStatus(run, "paused", "no_submit");
1942
+ logEvent(run.instId, "warn", "submit_reminder_exhausted", { node: node.id, emptyRounds });
1943
+ return {
1944
+ remind: false,
1945
+ summary: `⏸ Graph 节点 ${node.id} 已暂停:${why}`,
1946
+ message: `⏸ Graph 主执行节点 \`${node.id}\` 已暂停等你处理。\n\n${why}。\n\n- \`/ralphflow-continue\` 会清零连续计数,然后重新投递继续指令。\n- \`ralphflow_submit\` 没有次数上限;这里暂停只因为连续没有动作。\n- 它其实做完了:continue 后让它写产物并交卷。\n- 它在等你:先回复它要的信息,再 continue。\n- 它卡住了:\`/ralphflow-cancel\` 结束。`,
1947
+ };
1948
+ }
1949
+ history(run, worked ? "submit_activity" : "submit_reminder", worked ? "有动作" : `第 ${stalls + 1}/${SUBMIT_REMINDER_STALL_LIMIT} 次连续无工具回合`, node.id);
1950
+ persist(run);
1951
+ const head = worked
1952
+ ? `[ralphflow] 提醒:本轮继续,Graph 节点 \`${node.id}\` 还没结束。`
1953
+ : `[ralphflow] 提醒(第 ${stalls + 1}/${SUBMIT_REMINDER_STALL_LIMIT} 次连续无工具回合):本轮继续,Graph 节点 \`${node.id}\` 还没结束,上一轮没有调用任何工具。需要用户决定就调用 \`ask_user_question\`;否则继续做本轮清单。`;
1954
+ return {
1955
+ remind: true,
1956
+ summary: worked
1957
+ ? `▶️ Graph 节点 ${node.id} 还没结束:本轮任务书`
1958
+ : `▶️ Graph 节点 ${node.id} 还没结束:本轮任务书(连续 ${stalls + 1} 个回合没有工具调用)`,
1959
+ message: `${head}\n\n${nodeRecap(run, node, attempt)}\n\n本轮清单做完再交卷;确实被阻塞时,把还没完成的事项逐条写进 \`unfinished\`(交卷会被退回)。\n需要用户决定:调用 \`ask_user_question\`。其余情况继续做本轮清单。`,
1960
+ };
1961
+ }
1962
+ function uiStatus(sessionId) {
1963
+ const active = activeInstanceOfSession(sessionId);
1964
+ const retained = listStates().filter((entry) => entry.state.owner_session === sessionId).at(-1);
1965
+ const chosen = active ?? retained;
1966
+ if (!chosen)
1967
+ return { projection: null, error: null };
1968
+ return { projection: projectionOf(chosen.state, chosen.id), error: null };
1969
+ }
1970
+ const graphEngineFace = {
1971
+ kind: "graph",
1972
+ root,
1973
+ graphsDir,
1974
+ instancesDir,
1975
+ reportsDir,
1976
+ projectDir: workspace,
1977
+ ensureLayout,
1978
+ listWorkflows,
1979
+ loadWorkflow,
1980
+ readState,
1981
+ listStates,
1982
+ instanceDir,
1983
+ artifactsDirOf: (state) => graphArtifactsDirOf(workspace, state),
1984
+ start,
1985
+ submitFromAgent,
1986
+ continueInstance,
1987
+ pauseForUserStop,
1988
+ cancelInstance,
1989
+ cleanupInstance,
1990
+ statusOf,
1991
+ listAll,
1992
+ diagnose,
1993
+ restore,
1994
+ respond: respondToTodo,
1995
+ remindToSubmit,
1996
+ uiStatus,
1997
+ activeInstanceOfSession,
1998
+ syncSession,
1999
+ projectionOf: (state, id) => projectionOf(state, id),
2000
+ };
2001
+ return graphEngineFace;
2002
+ }