ralphflow-dsh 0.1.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 (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +196 -0
  3. package/lib/actions.d.ts +37 -0
  4. package/lib/actions.js +55 -0
  5. package/lib/check-voting.d.ts +54 -0
  6. package/lib/check-voting.js +289 -0
  7. package/lib/check.d.ts +64 -0
  8. package/lib/check.js +329 -0
  9. package/lib/client/CommandCard.d.ts +24 -0
  10. package/lib/client/CommandCard.js +69 -0
  11. package/lib/client/HeaderAction.d.ts +39 -0
  12. package/lib/client/HeaderAction.js +509 -0
  13. package/lib/client/RunCard.d.ts +27 -0
  14. package/lib/client/RunCard.js +375 -0
  15. package/lib/client/client.d.ts +3 -0
  16. package/lib/client/client.js +275 -0
  17. package/lib/client/definition.d.ts +126 -0
  18. package/lib/client/definition.js +259 -0
  19. package/lib/client/hidden-runs.d.ts +6 -0
  20. package/lib/client/hidden-runs.js +52 -0
  21. package/lib/client/http-state.d.ts +67 -0
  22. package/lib/client/http-state.js +81 -0
  23. package/lib/client/markdown.d.ts +26 -0
  24. package/lib/client/markdown.js +174 -0
  25. package/lib/client/notify-watch.d.ts +38 -0
  26. package/lib/client/notify-watch.js +98 -0
  27. package/lib/client/notify.d.ts +21 -0
  28. package/lib/client/notify.js +168 -0
  29. package/lib/client/snapshots.d.ts +8 -0
  30. package/lib/client/snapshots.js +101 -0
  31. package/lib/client.js +2361 -0
  32. package/lib/commands.d.ts +41 -0
  33. package/lib/commands.js +223 -0
  34. package/lib/create.d.ts +14 -0
  35. package/lib/create.js +98 -0
  36. package/lib/deps.d.ts +17 -0
  37. package/lib/deps.js +19 -0
  38. package/lib/done-detect.d.ts +2 -0
  39. package/lib/done-detect.js +28 -0
  40. package/lib/driver.d.ts +32 -0
  41. package/lib/driver.js +248 -0
  42. package/lib/engine.d.ts +306 -0
  43. package/lib/engine.js +2851 -0
  44. package/lib/events.d.ts +35 -0
  45. package/lib/events.js +52 -0
  46. package/lib/index.d.ts +11 -0
  47. package/lib/index.js +201 -0
  48. package/lib/jobs.d.ts +56 -0
  49. package/lib/jobs.js +355 -0
  50. package/lib/mutex.d.ts +9 -0
  51. package/lib/mutex.js +21 -0
  52. package/lib/session-hygiene.d.ts +25 -0
  53. package/lib/session-hygiene.js +205 -0
  54. package/lib/tools.d.ts +24 -0
  55. package/lib/tools.js +716 -0
  56. package/lib/voting-progress.d.ts +37 -0
  57. package/lib/voting-progress.js +89 -0
  58. package/package.json +73 -0
  59. package/workflows/loop.yaml +27 -0
  60. package/workflows/spec.yaml +105 -0
package/lib/engine.js ADDED
@@ -0,0 +1,2851 @@
1
+ /**
2
+ * Ralph Flow Engine for opencode.
3
+ *
4
+ * The WORKFLOW LOGIC (prompt building, the check-result state machine, workflow
5
+ * loading, lint/doctor) mirrors the Claude Code plugin's mcp-server/server.mjs
6
+ * so the two stay behavior-compatible; see SYNC.md.
7
+ *
8
+ * The RUNTIME PLUMBING is opencode-native, NOT a mirror. opencode runs one
9
+ * plugin instance per project directory (shared memory, events carry the
10
+ * sessionID), so the Claude version's multi-PROCESS coordination is unnecessary
11
+ * and was actively harmful here:
12
+ * - No shared mutable "bound instance": every instance-scoped function takes an
13
+ * explicit `instId` (like the original opencode plugin passed `directory`),
14
+ * so there is nothing to serialize and no in-memory state lock.
15
+ * - No cross-process file lock: a single process needs none; operations on one
16
+ * instance are naturally serialized by opencode's per-session turn model.
17
+ * - Ownership is just `session_id` stored in the instance's state.json — no
18
+ * owner-session file, no pid/ppid liveness inference.
19
+ *
20
+ * Multi-instance is kept for parity: state lives under
21
+ * .opencode/ralph-flow/instances/<instance-id>/, so different sessions can run
22
+ * their own workflow in the same project.
23
+ */
24
+ import fs from "fs";
25
+ import path from "path";
26
+ import { fileURLToPath } from "url";
27
+ import yaml from "js-yaml";
28
+ /**
29
+ * Strip UTF-8 BOM (Byte Order Mark) from file content.
30
+ * Windows Notepad and some editors add BOM to UTF-8 files.
31
+ * js-yaml and JSON.parse don't handle BOM, causing parse failures.
32
+ */
33
+ export function stripBom(text) {
34
+ return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
35
+ }
36
+ // ─── Constants ────────────────────────────────────────────────────────────────
37
+ export const RALPH_FLOW_DIR = "ralph-flow";
38
+ const INSTANCES_DIRNAME = "instances";
39
+ const REPORTS_DIRNAME = "reports";
40
+ const STATE_FILENAME = "state.json";
41
+ const STACK_FILENAME = "state-stack.json";
42
+ // Mirrors the Claude version's .adversarial-pid: holds the CHECK session id
43
+ // instead of a child-process pid (the opencode check runs as an SDK session,
44
+ // not a subprocess).
45
+ const ADVERSARIAL_SESSION_FILENAME = ".adversarial-session";
46
+ /**
47
+ * popState 的「栈文件损坏」哨兵:与 null(栈为空=真正顶层)严格区分。
48
+ * 收到哨兵绝不能走「顶层完成→销毁实例」分支——父帧可能仍在,误判会连本带
49
+ * 息丢掉父工作流的剩余步骤。
50
+ */
51
+ const STACK_CORRUPTED = Symbol("ralphflow:stack-corrupted");
52
+ export const MANUAL_STEP_MARKER = ".manual-step-active";
53
+ export const MANUAL_GATE_MARKER = ".manual-gate";
54
+ export const DONE_TAG_MARKER = ".done-tag-detected";
55
+ export const REINJECT_WARNED_MARKER = ".reinject-warned";
56
+ // 同一 DO 阶段被 idle 催促(无工具调用)达到此上限后,driver 停止自动驱动并
57
+ // 把控制权交给用户(用户可 /ralphflow-continue 确认完成进入验证)。
58
+ export const MAX_DO_REINJECT = 5;
59
+ const MAX_STEP_RECORDS = 1000;
60
+ export const MAX_NESTING_DEPTH = 5;
61
+ export const MAX_VOTERS = 5;
62
+ export const VOTING_PROGRESS_FILENAME = ".check-voting-progress.json";
63
+ const MAX_WORKFLOW_FILE_SIZE = 1024 * 1024; // 1 MB
64
+ const isWin = process.platform === "win32";
65
+ export function createEngine(projectDir, platform) {
66
+ // No in-memory or cross-process lock: every op takes an explicit instId, so
67
+ // there is no shared mutable state to guard, and one plugin process + the
68
+ // per-session turn model serialize instance operations naturally.
69
+ // ─── Atomic File I/O ────────────────────────────────────────────────────────
70
+ function atomicWriteJson(filePath, data) {
71
+ atomicWriteText(filePath, JSON.stringify(data, null, 2));
72
+ }
73
+ function atomicWriteText(filePath, text) {
74
+ const dir = path.dirname(filePath);
75
+ if (!fs.existsSync(dir))
76
+ fs.mkdirSync(dir, { recursive: true });
77
+ const tmp = filePath + ".tmp." + process.pid;
78
+ fs.writeFileSync(tmp, text);
79
+ try {
80
+ fs.renameSync(tmp, filePath);
81
+ }
82
+ catch (e) {
83
+ // Windows can throw EPERM/EEXIST when renaming over an existing file that
84
+ // is momentarily open (antivirus, indexer). Retry once after a short spin.
85
+ if (isWin && (e.code === "EPERM" || e.code === "EEXIST" || e.code === "EACCES")) {
86
+ try {
87
+ fs.unlinkSync(filePath);
88
+ }
89
+ catch { }
90
+ fs.renameSync(tmp, filePath);
91
+ }
92
+ else {
93
+ try {
94
+ fs.unlinkSync(tmp);
95
+ }
96
+ catch { }
97
+ throw e;
98
+ }
99
+ }
100
+ }
101
+ // ─── Instance Infrastructure ────────────────────────────────────────────────
102
+ function getRalphFlowDir() {
103
+ return path.join(projectDir, RALPH_FLOW_DIR);
104
+ }
105
+ // Diagnostic sink. The Claude version writes these to console.error, which is
106
+ // harmless there (a separate MCP-server process — Claude Code captures its
107
+ // stderr). In opencode the plugin runs IN the TUI process, so ANY console
108
+ // output corrupts the display. Route everything to a file instead. (Every
109
+ // user-facing problem is already surfaced through the `problems` array /
110
+ // tool responses, so nothing important is hidden by this.)
111
+ function diag(...args) {
112
+ try {
113
+ const dir = path.join(getRalphFlowDir(), "logs");
114
+ if (!fs.existsSync(dir))
115
+ fs.mkdirSync(dir, { recursive: true });
116
+ fs.appendFileSync(path.join(dir, "plugin-diag.log"), `[${new Date().toISOString()}] ${args.map((a) => (a instanceof Error ? a.message : String(a))).join(" ")}\n`);
117
+ }
118
+ catch { }
119
+ }
120
+ function getInstancesRoot() {
121
+ return path.join(getRalphFlowDir(), INSTANCES_DIRNAME);
122
+ }
123
+ function getReportsDir() {
124
+ return path.join(getRalphFlowDir(), REPORTS_DIRNAME);
125
+ }
126
+ // Per-instance artifacts directory. Lives OUTSIDE instances/<id>/ because the
127
+ // instance dir is deleted on completion/cancel (destroyInstance) — artifacts
128
+ // are workflow deliverables that must survive the workflow and stay isolated
129
+ // between parallel instances.
130
+ const ARTIFACTS_DIRNAME = "artifacts";
131
+ const ARTIFACTS_NAME_FILENAME = "artifacts-dir";
132
+ /** Final report file path for an instance (may not exist). */
133
+ function getReportPath(instId) {
134
+ return path.join(getReportsDir(), `${instId}-final-report.md`);
135
+ }
136
+ /** Whether a final report exists for the instance. */
137
+ function reportExists(instId) {
138
+ try {
139
+ return fs.statSync(getReportPath(instId)).isFile();
140
+ }
141
+ catch {
142
+ return false;
143
+ }
144
+ }
145
+ // OpenSpec-style human-readable dir name: short task summary + instance-id
146
+ // suffix so parallel instances of the same task never collide.
147
+ function makeArtifactsDirName(task, instId) {
148
+ // Truncate by code point (Array.from), not UTF-16 unit: a plain slice() can
149
+ // cut an emoji in half, leaving a lone surrogate that round-trips through
150
+ // the utf-8 name file as U+FFFD — the prompt and the file would then name
151
+ // two different directories. Dash-trim runs after the cut for the same
152
+ // reason (the cut itself can expose a trailing dash).
153
+ const slug = Array.from(String(task || "").trim()
154
+ .replace(/\s+/g, "-")
155
+ .replace(/[\\/:*?"'`<>|.$&(){}[\];!#~^]/g, "")).slice(0, 30).join("").replace(/^-+|-+$/g, "");
156
+ // Windows 保留设备名(CON/PRN/NUL/COM1…)作目录名会命中设备而非目录
157
+ const safeSlug = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(slug) ? `${slug}-dir` : slug;
158
+ const suffix = String(instId).split("-").pop() || "0";
159
+ return safeSlug ? `${safeSlug}-${suffix}` : String(instId);
160
+ }
161
+ // The name is fixed at workflow start and read back from the instance dir —
162
+ // sub-workflow pushes rewrite state.json (including user_task), so the name
163
+ // cannot be re-derived from state later.
164
+ function writeArtifactsDirName(instId, task) {
165
+ atomicWriteText(instPath(ARTIFACTS_NAME_FILENAME, instId), makeArtifactsDirName(task, instId));
166
+ }
167
+ function getArtifactsDirName(instId) {
168
+ try {
169
+ const v = stripBom(fs.readFileSync(instPath(ARTIFACTS_NAME_FILENAME, instId), "utf-8")).trim();
170
+ // A hand-edited name file must not be able to walk out of the artifacts
171
+ // root (this path is joined and later mkdir'd/rmdir'd).
172
+ if (v && !v.includes("/") && !v.includes("\\") && !v.includes(".."))
173
+ return v;
174
+ }
175
+ catch { }
176
+ return reqInst(instId);
177
+ }
178
+ function getArtifactsDir(instId) {
179
+ return path.join(getRalphFlowDir(), ARTIFACTS_DIRNAME, getArtifactsDirName(instId));
180
+ }
181
+ // Project-relative form with forward slashes, embeddable in DO/CHECK prompts
182
+ // (both the session and the adversarial checker run with cwd = projectDir).
183
+ function getArtifactsRelDir(instId) {
184
+ return `${RALPH_FLOW_DIR}/${ARTIFACTS_DIRNAME}/${getArtifactsDirName(instId)}`;
185
+ }
186
+ // Internal escape hatch only: {{artifacts_dir}} in step text still resolves,
187
+ // but workflow authors never need it — every DO/CHECK prompt carries a 产出目录
188
+ // section pointing at the same path.
189
+ const ARTIFACTS_TOKEN = "{{artifacts_dir}}";
190
+ function renderStepText(instId, text) {
191
+ if (typeof text !== "string" || !text.includes(ARTIFACTS_TOKEN))
192
+ return text;
193
+ return text.split(ARTIFACTS_TOKEN).join(getArtifactsRelDir(instId));
194
+ }
195
+ /** 长文本截断(DO/CHECK prompt 的 token 成本控制);截断处明确标注不藏拙 */
196
+ function truncateText(text, max) {
197
+ if (!text || text.length <= max)
198
+ return text;
199
+ return `${text.slice(0, max)}\n\n…(内容过长已截断,完整内容见工作流定义/任务记录)`;
200
+ }
201
+ // Extra read-access dirs for the adversarial checker, declared explicitly at
202
+ // ralphflow_start for tasks whose source material lives outside the project
203
+ // dir. Stored as an instance file so sub-workflow state pushes can't drop them.
204
+ const EXTRA_DIRS_FILENAME = "extra-dirs";
205
+ function writeExtraDirs(instId, dirs) {
206
+ if (Array.isArray(dirs) && dirs.length > 0) {
207
+ atomicWriteJson(instPath(EXTRA_DIRS_FILENAME, instId), dirs);
208
+ }
209
+ }
210
+ function readExtraDirs(instId) {
211
+ try {
212
+ const v = JSON.parse(stripBom(fs.readFileSync(instPath(EXTRA_DIRS_FILENAME, instId), "utf-8")));
213
+ if (Array.isArray(v))
214
+ return v.filter((d) => typeof d === "string");
215
+ }
216
+ catch { }
217
+ return [];
218
+ }
219
+ function getInstanceDir(instId) {
220
+ return path.join(getInstancesRoot(), instId);
221
+ }
222
+ /** Every instance-scoped helper requires an explicit instId. */
223
+ function reqInst(instId) {
224
+ if (!instId)
225
+ throw new Error("instId is required");
226
+ return instId;
227
+ }
228
+ function instPath(name, instId) {
229
+ return path.join(getInstanceDir(reqInst(instId)), name);
230
+ }
231
+ function isValidInstanceId(id) {
232
+ return typeof id === "string" && /^[a-z0-9][a-z0-9-]{0,80}$/.test(id);
233
+ }
234
+ function generateInstanceId(workflowName) {
235
+ const base = String(workflowName).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 24) || "wf";
236
+ const d = new Date();
237
+ const pad = (n) => String(n).padStart(2, "0");
238
+ const ts = `${String(d.getFullYear()).slice(2)}${pad(d.getMonth() + 1)}${pad(d.getDate())}${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
239
+ // 同一秒内并发 start(脚本/双开)会撞 id——撞上就重试,随机段兜底加长
240
+ for (let attempt = 0; attempt < 5; attempt++) {
241
+ const rand = Math.random().toString(36).slice(2, attempt < 3 ? 6 : 10).padEnd(attempt < 3 ? 6 : 10, "0");
242
+ const candidate = `${base}-${ts}-${rand}`;
243
+ try {
244
+ if (!fs.existsSync(getInstanceDir(candidate)))
245
+ return candidate;
246
+ }
247
+ catch {
248
+ return candidate;
249
+ }
250
+ }
251
+ return `${base}-${ts}-${Date.now().toString(36)}`;
252
+ }
253
+ /** The owning session id is stored in the instance's state.json. */
254
+ function readOwnerSession(instId) {
255
+ const s = readState(instId);
256
+ return s?.session_id || null;
257
+ }
258
+ /** Claim ownership by writing session_id into the state (no-op if gone). */
259
+ function claimOwnership(instId, sessionId) {
260
+ if (!sessionId)
261
+ return;
262
+ const s = readState(instId);
263
+ if (!s || !s.active)
264
+ return;
265
+ if (s.session_id === sessionId)
266
+ return;
267
+ writeState({ ...s, session_id: sessionId }, instId);
268
+ clearMarker(".orphan-notified", instId);
269
+ }
270
+ // ─── State Management (per instance) ────────────────────────────────────────
271
+ function getStateFile(instId) {
272
+ return instPath(STATE_FILENAME, instId);
273
+ }
274
+ /**
275
+ * A live instance is one whose state.json still exists. Writers below check
276
+ * this before writing so no code path can resurrect a destroyed instance
277
+ * directory (e.g. a cross-session cancel racing an in-flight check).
278
+ */
279
+ function instanceExists(instId) {
280
+ try {
281
+ return fs.existsSync(getStateFile(instId));
282
+ }
283
+ catch {
284
+ return false;
285
+ }
286
+ }
287
+ function isValidState(s) {
288
+ return s && typeof s === "object"
289
+ && typeof s.active === "boolean"
290
+ && typeof s.workflow_name === "string" && s.workflow_name.length > 0
291
+ && typeof s.current_step === "string" && s.current_step.length > 0
292
+ && typeof s.current_phase === "string"
293
+ && typeof s.fail_count === "number" && s.fail_count >= 0
294
+ && typeof s.paused === "boolean"
295
+ && (s.pause_reason === undefined || s.pause_reason === null || typeof s.pause_reason === "string");
296
+ }
297
+ function readState(instId) {
298
+ try {
299
+ const stateFile = getStateFile(instId);
300
+ if (fs.existsSync(stateFile)) {
301
+ try {
302
+ const parsed = JSON.parse(stripBom(fs.readFileSync(stateFile, "utf-8")));
303
+ if (!isValidState(parsed)) {
304
+ diag("[ralph-flow] State file has invalid schema, backing up");
305
+ try {
306
+ fs.renameSync(stateFile, stateFile + ".invalid." + Date.now());
307
+ }
308
+ catch { }
309
+ return null;
310
+ }
311
+ return parsed;
312
+ }
313
+ catch (parseErr) {
314
+ // 仅真正的 JSON 语法损坏才改名隔离;瞬时 I/O 错误(权限抖动、NFS
315
+ // stale handle)不该触发「读即改名」把活实例误杀。
316
+ if (parseErr instanceof SyntaxError) {
317
+ diag("[ralph-flow] State file corrupted, backing up:", parseErr.message);
318
+ try {
319
+ fs.renameSync(stateFile, stateFile + ".corrupted." + Date.now());
320
+ }
321
+ catch { }
322
+ }
323
+ else {
324
+ diag("[ralph-flow] Transient error reading state:", parseErr.message);
325
+ }
326
+ return null;
327
+ }
328
+ }
329
+ }
330
+ catch (e) {
331
+ diag("[ralph-flow] Error reading state:", e.message);
332
+ }
333
+ return null;
334
+ }
335
+ function writeState(state, instId) {
336
+ try {
337
+ const id = reqInst(instId);
338
+ // Preserve the owning session_id when the caller's state object omits it.
339
+ // Pure-logic transitions (sub-workflow entry, check routing) build fresh
340
+ // state objects without session_id; without this they would orphan the
341
+ // instance. An explicit session_id in `state` still wins (ownership claim).
342
+ // Preserve existing session_id only when the caller's state does not
343
+ // mention the key at all. An explicit session_id (even null, to clear
344
+ // ownership) must win — otherwise the comment is lying to callers.
345
+ const session_id = Object.prototype.hasOwnProperty.call(state, "session_id")
346
+ ? state.session_id
347
+ : readState(id)?.session_id;
348
+ atomicWriteJson(getStateFile(id), { ...state, session_id, instance_id: id });
349
+ }
350
+ catch (e) {
351
+ diag("[ralph-flow] Error writing state:", e.message);
352
+ }
353
+ }
354
+ function writeMarker(name, content, instId) {
355
+ try {
356
+ const id = reqInst(instId);
357
+ if (!instanceExists(id))
358
+ return; // never resurrect a destroyed instance
359
+ atomicWriteText(path.join(getInstanceDir(id), name), content);
360
+ }
361
+ catch { }
362
+ }
363
+ function clearMarker(name, instId) {
364
+ try {
365
+ const marker = instPath(name, instId);
366
+ if (fs.existsSync(marker))
367
+ fs.unlinkSync(marker);
368
+ }
369
+ catch { }
370
+ }
371
+ function markerExists(name, instId) {
372
+ try {
373
+ return fs.existsSync(instPath(name, instId));
374
+ }
375
+ catch {
376
+ return false;
377
+ }
378
+ }
379
+ function writeManualStepMarker(instId) { writeMarker(MANUAL_STEP_MARKER, "active", instId); }
380
+ function clearManualStepMarker(instId) { clearMarker(MANUAL_STEP_MARKER, instId); }
381
+ function clearManualGate(instId) { clearMarker(MANUAL_GATE_MARKER, instId); }
382
+ // 催促计数归零 = 新一轮 DO 的开始,顺带清掉"已警告过催促上限"的标记,
383
+ // 这样新一轮再次超限时用户还能再看到一次警告(而不是永久静默)。
384
+ function clearReinjectCounter(instId) {
385
+ clearMarker(".do-reinject-count", instId);
386
+ clearMarker(REINJECT_WARNED_MARKER, instId);
387
+ }
388
+ function clearDoPromptCache(instId) { clearMarker(".do-prompt-cache", instId); }
389
+ function clearDoneTagDetected(instId) { clearMarker(DONE_TAG_MARKER, instId); }
390
+ /**
391
+ * 读取当前 DO 阶段的催促计数(driver 写入 .do-reinject-count,格式
392
+ * "stepId:phase count")。传入 stepId/phase 时校验 key——旧步骤的计数在
393
+ * 新步骤下视为 0(与 driver 的 getReinjectCount 语义一致)。
394
+ */
395
+ function readReinjectCount(instId, stepId, phase) {
396
+ try {
397
+ const content = stripBom(fs.readFileSync(instPath(".do-reinject-count", reqInst(instId)), "utf-8")).trim();
398
+ const [key, count] = content.split(" ");
399
+ if (stepId && phase && key !== `${stepId}:${phase}`)
400
+ return 0;
401
+ return parseInt(count, 10) || 0;
402
+ }
403
+ catch {
404
+ return 0;
405
+ }
406
+ }
407
+ function writeDoPromptCache(prompt, instId) {
408
+ try {
409
+ const id = reqInst(instId);
410
+ if (!instanceExists(id))
411
+ return;
412
+ atomicWriteText(instPath(".do-prompt-cache", id), prompt);
413
+ }
414
+ catch { }
415
+ }
416
+ function readDoPromptCache(instId) {
417
+ try {
418
+ return stripBom(fs.readFileSync(instPath(".do-prompt-cache", reqInst(instId)), "utf-8")).trim();
419
+ }
420
+ catch {
421
+ return "";
422
+ }
423
+ }
424
+ /**
425
+ * The canonical "you are still in DO, here is the task, here is how you finish"
426
+ * nudge. The driver injects it on an idle keep-alive; ralphflow_continue returns
427
+ * it when there is no gate/pause/attach to act on. Those are the same situation
428
+ * — the step isn't done — so they must say the same thing, from one place.
429
+ */
430
+ function buildDoNudge(instId, stepId) {
431
+ const cached = readDoPromptCache(instId);
432
+ return `继续执行步骤 \`${stepId}\` 的任务。${cached ? `\n\n${cached}` : ""}\n\n当所有要求满足后,在单独一行输出 \`<promise>done</promise>\`。`;
433
+ }
434
+ /**
435
+ * Set the driver dedup markers after a tool response that already contains
436
+ * the current DO prompt: .last-phase-report suppresses a duplicate full phase
437
+ * report, .post-tool-active suppresses the immediate keep-alive for this turn.
438
+ * Later idles still keep-alive normally.
439
+ */
440
+ function markPromptDelivered(stepId, instId) {
441
+ try {
442
+ const id = reqInst(instId);
443
+ if (!instanceExists(id))
444
+ return;
445
+ atomicWriteText(instPath(".last-phase-report", id), `do:${stepId}`);
446
+ atomicWriteText(instPath(".post-tool-active", id), Date.now().toString());
447
+ }
448
+ catch { }
449
+ }
450
+ // ─── Adversarial-check session file (cross-session cancel support) ──────────
451
+ //
452
+ // 每个验证者一个独立登记文件 `.verifier-<id>.live`(内容=登记时间戳 ms)。
453
+ // 聚合文件(旧 `.adversarial-session`,JSON 数组)只读兼容、不再新写——多票
454
+ // 并行时对同一文件的 read-modify-write 会互相覆盖丢登记,独立文件天然无竞态
455
+ // (voters 在实例互斥锁内运行,登记处绝不能再拿锁)。
456
+ const VERIFIER_LIVE_PREFIX = ".verifier-";
457
+ const VERIFIER_LIVE_SUFFIX = ".live";
458
+ function sanitizeVerifierFileId(id) {
459
+ return id.replace(/[^a-zA-Z0-9._-]/g, "_");
460
+ }
461
+ function verifierLivePath(checkSessionId, instId) {
462
+ return path.join(getInstanceDir(instId), `${VERIFIER_LIVE_PREFIX}${sanitizeVerifierFileId(checkSessionId)}${VERIFIER_LIVE_SUFFIX}`);
463
+ }
464
+ function readAdversarialSessions(instId) {
465
+ try {
466
+ const id = reqInst(instId);
467
+ const dir = getInstanceDir(id);
468
+ if (!fs.existsSync(dir))
469
+ return [];
470
+ const out = new Set();
471
+ try {
472
+ for (const f of fs.readdirSync(dir)) {
473
+ if (f.startsWith(VERIFIER_LIVE_PREFIX) && f.endsWith(VERIFIER_LIVE_SUFFIX)) {
474
+ out.add(f.slice(VERIFIER_LIVE_PREFIX.length, f.length - VERIFIER_LIVE_SUFFIX.length));
475
+ }
476
+ }
477
+ }
478
+ catch { }
479
+ // 旧聚合格式只读兼容(不再新写)
480
+ try {
481
+ const legacy = path.join(dir, ADVERSARIAL_SESSION_FILENAME);
482
+ if (fs.existsSync(legacy)) {
483
+ const v = stripBom(fs.readFileSync(legacy, "utf-8")).trim();
484
+ if (v) {
485
+ try {
486
+ const parsed = JSON.parse(v);
487
+ if (Array.isArray(parsed))
488
+ parsed.forEach((x) => typeof x === "string" && x && out.add(x));
489
+ else if (typeof parsed === "string" && parsed)
490
+ out.add(parsed);
491
+ }
492
+ catch {
493
+ out.add(v); // legacy 单值裸 id
494
+ }
495
+ }
496
+ }
497
+ }
498
+ catch { }
499
+ return [...out];
500
+ }
501
+ catch {
502
+ return [];
503
+ }
504
+ }
505
+ function writeAdversarialSession(checkSessionId, instId) {
506
+ try {
507
+ const id = reqInst(instId);
508
+ if (!instanceExists(id))
509
+ return;
510
+ atomicWriteText(verifierLivePath(checkSessionId, id), String(Date.now()));
511
+ }
512
+ catch { }
513
+ }
514
+ function removeAdversarialSession(checkSessionId, instId) {
515
+ try {
516
+ const id = reqInst(instId);
517
+ // 新格式:删独立 live 文件;旧聚合文件里的条目:尽力清一次(已无并发写入者)
518
+ try {
519
+ fs.unlinkSync(verifierLivePath(checkSessionId, id));
520
+ }
521
+ catch { }
522
+ try {
523
+ const legacy = instPath(ADVERSARIAL_SESSION_FILENAME, id);
524
+ if (fs.existsSync(legacy)) {
525
+ const raw = stripBom(fs.readFileSync(legacy, "utf-8")).trim();
526
+ if (raw) {
527
+ let next = null;
528
+ try {
529
+ const parsed = JSON.parse(raw);
530
+ if (Array.isArray(parsed))
531
+ next = parsed.filter((x) => x !== checkSessionId);
532
+ else if (typeof parsed === "string" && parsed === checkSessionId)
533
+ next = [];
534
+ }
535
+ catch {
536
+ if (raw === checkSessionId)
537
+ next = []; // legacy 单值裸 id
538
+ }
539
+ if (next !== null)
540
+ atomicWriteText(legacy, JSON.stringify(next));
541
+ }
542
+ }
543
+ }
544
+ catch { }
545
+ }
546
+ catch { }
547
+ }
548
+ /**
549
+ * 清理孤儿登记:进程在验证进行中被 kill -9 时 finally 不执行,live 文件残留,
550
+ * continue/status 会永远认为「验证进行中」而死等。验证者 id/文件的年龄超过
551
+ * timeout_ms + 宽限(默认 5 分钟)即视为孤儿移除。返回剩余(活)登记数。
552
+ */
553
+ function pruneStaleAdversarialSessions(instId, graceMs = 5 * 60_000) {
554
+ try {
555
+ const id = reqInst(instId);
556
+ const dir = getInstanceDir(id);
557
+ if (!fs.existsSync(dir))
558
+ return 0;
559
+ let timeoutMs = DEFAULT_ADVERSARIAL_TIMEOUT_MS;
560
+ try {
561
+ const st = readState(id);
562
+ const wf = st ? loadWorkflow(st.workflow_name) : null;
563
+ if (wf)
564
+ timeoutMs = getEffectiveAdversarialCheck(id, wf)?.timeout_ms || DEFAULT_ADVERSARIAL_TIMEOUT_MS;
565
+ }
566
+ catch { }
567
+ const deadline = Date.now() - timeoutMs - graceMs;
568
+ let removed = 0;
569
+ for (const f of fs.readdirSync(dir)) {
570
+ if (!f.startsWith(VERIFIER_LIVE_PREFIX) || !f.endsWith(VERIFIER_LIVE_SUFFIX))
571
+ continue;
572
+ const full = path.join(dir, f);
573
+ try {
574
+ if (fs.statSync(full).mtimeMs < deadline) {
575
+ fs.unlinkSync(full);
576
+ removed++;
577
+ }
578
+ }
579
+ catch { }
580
+ }
581
+ // 旧聚合文件:整体 mtime 判断
582
+ try {
583
+ const legacy = path.join(dir, ADVERSARIAL_SESSION_FILENAME);
584
+ if (fs.existsSync(legacy) && fs.statSync(legacy).mtimeMs < deadline) {
585
+ fs.unlinkSync(legacy);
586
+ removed++;
587
+ }
588
+ }
589
+ catch { }
590
+ if (removed > 0)
591
+ logEvent(id, "warn", "stale_verifier_pruned", { removed, timeout_ms: timeoutMs });
592
+ return readAdversarialSessions(id).length;
593
+ }
594
+ catch {
595
+ return 0;
596
+ }
597
+ }
598
+ function clearAdversarialSession(instId) {
599
+ try {
600
+ const id = reqInst(instId);
601
+ const dir = getInstanceDir(id);
602
+ try {
603
+ for (const f of fs.readdirSync(dir)) {
604
+ if (f.startsWith(VERIFIER_LIVE_PREFIX) && f.endsWith(VERIFIER_LIVE_SUFFIX)) {
605
+ try {
606
+ fs.unlinkSync(path.join(dir, f));
607
+ }
608
+ catch { }
609
+ }
610
+ }
611
+ }
612
+ catch { }
613
+ clearMarker(ADVERSARIAL_SESSION_FILENAME, id);
614
+ }
615
+ catch { }
616
+ }
617
+ function readAdversarialSession(instId) {
618
+ const arr = readAdversarialSessions(instId);
619
+ return arr.length > 0 ? arr[0] : null;
620
+ }
621
+ // ─── Instance listing / resolution ──────────────────────────────────────────
622
+ function listInstances() {
623
+ const result = [];
624
+ const root = getInstancesRoot();
625
+ if (!fs.existsSync(root))
626
+ return result;
627
+ let entries;
628
+ try {
629
+ entries = fs.readdirSync(root, { withFileTypes: true });
630
+ }
631
+ catch {
632
+ return result;
633
+ }
634
+ for (const entry of entries) {
635
+ if (!entry.isDirectory())
636
+ continue;
637
+ const id = entry.name;
638
+ if (!isValidInstanceId(id))
639
+ continue;
640
+ const state = readState(id);
641
+ if (!state || !state.active)
642
+ continue;
643
+ let lastActivity = null;
644
+ try {
645
+ lastActivity = fs.statSync(getStateFile(id)).mtime;
646
+ }
647
+ catch { }
648
+ result.push({
649
+ id,
650
+ state,
651
+ owner: state.session_id || null,
652
+ manualGate: markerExists(MANUAL_GATE_MARKER, id),
653
+ doneTag: markerExists(DONE_TAG_MARKER, id),
654
+ lastActivity,
655
+ });
656
+ }
657
+ return result;
658
+ }
659
+ function instanceStatusLabel(info) {
660
+ const s = info.state;
661
+ if (s.paused) {
662
+ if (s.pause_reason === "max_failures")
663
+ return "⏸ 已暂停(达到最大失败次数)";
664
+ if (s.pause_reason === "config_error")
665
+ return "⏸ 已暂停(工作流配置错误)";
666
+ if (s.pause_reason === "check_error")
667
+ return "⏸ 已暂停(验证未能运行,continue 重新验证)";
668
+ return `⏸ 已暂停(${s.pause_reason || "未知原因"})`;
669
+ }
670
+ if (s.current_phase === "check")
671
+ return "🔍 验证中";
672
+ if (info.manualGate)
673
+ return "⏸ 等待手动审查";
674
+ if (info.doneTag)
675
+ return "✅ DO 完成,待验证";
676
+ return "🔨 执行中";
677
+ }
678
+ function formatLastActivity(date) {
679
+ if (!date)
680
+ return "未知";
681
+ const diffMs = Date.now() - date.getTime();
682
+ const mins = Math.floor(diffMs / 60000);
683
+ if (mins < 1)
684
+ return "刚刚";
685
+ if (mins < 60)
686
+ return `${mins} 分钟前`;
687
+ const hours = Math.floor(mins / 60);
688
+ if (hours < 24)
689
+ return `${hours} 小时前`;
690
+ return `${Math.floor(hours / 24)} 天前`;
691
+ }
692
+ function formatInstanceList(instances, actionHint) {
693
+ const lines = [`## 工作流实例(${instances.length} 个)`, ""];
694
+ for (const info of instances) {
695
+ const task = (info.state.user_task || "").replace(/\s+/g, " ").slice(0, 60);
696
+ lines.push(`### \`${info.id}\``);
697
+ lines.push(`- **工作流**: ${info.state.workflow_name}`);
698
+ if (task)
699
+ lines.push(`- **任务**: ${task}${(info.state.user_task || "").length > 60 ? "…" : ""}`);
700
+ lines.push(`- **步骤**: ${info.state.current_step}(${info.state.current_phase})`);
701
+ lines.push(`- **状态**: ${instanceStatusLabel(info)}`);
702
+ lines.push(`- **属主会话**: ${info.owner ? `\`${info.owner.slice(0, 8)}\`` : "无"}`);
703
+ lines.push(`- **最后活动**: ${formatLastActivity(info.lastActivity)}`);
704
+ lines.push("");
705
+ }
706
+ if (actionHint)
707
+ lines.push(actionHint);
708
+ return lines.join("\n");
709
+ }
710
+ /**
711
+ * Resolve which instance a tool call from `sessionId` targets.
712
+ * `attached` is true when the call takes over an instance owned by a
713
+ * different (or no) session — the caller uses it to pick attach semantics.
714
+ * There is no liveness probe: opencode can't cheaply tell whether a session
715
+ * is still open, so ownership is advisory and takeover is always allowed
716
+ * (explicitly, or implicitly when a single instance exists).
717
+ */
718
+ function resolveInstance(explicitId, sessionId) {
719
+ const instances = listInstances();
720
+ // 1. Explicit id (unique prefix allowed).
721
+ if (explicitId) {
722
+ const wanted = String(explicitId).trim();
723
+ const matches = instances.filter((i) => i.id === wanted);
724
+ const prefixMatches = matches.length > 0 ? matches : instances.filter((i) => i.id.startsWith(wanted));
725
+ if (prefixMatches.length === 1) {
726
+ const inst = prefixMatches[0];
727
+ return { ok: true, id: inst.id, attached: inst.owner !== sessionId };
728
+ }
729
+ if (prefixMatches.length === 0) {
730
+ return {
731
+ ok: false,
732
+ text: instances.length === 0
733
+ ? `没有找到实例 "${wanted}"。当前没有活跃的工作流实例。`
734
+ : `没有找到匹配 "${wanted}" 的实例。\n\n${formatInstanceList(instances)}`,
735
+ };
736
+ }
737
+ return { ok: false, text: `前缀 "${wanted}" 匹配到 ${prefixMatches.length} 个实例,请提供更长的前缀:\n\n${formatInstanceList(prefixMatches)}` };
738
+ }
739
+ // 2. An instance already owned by this session.
740
+ if (sessionId) {
741
+ const mine = instances.filter((i) => i.owner === sessionId);
742
+ if (mine.length >= 1) {
743
+ mine.sort((a, b) => (b.lastActivity?.getTime() || 0) - (a.lastActivity?.getTime() || 0));
744
+ return { ok: true, id: mine[0].id, attached: false };
745
+ }
746
+ }
747
+ // 3. No instance owned by this session.
748
+ if (instances.length === 0) {
749
+ return { ok: false, text: "没有活跃的工作流。使用 /ralphflow-start 启动一个。" };
750
+ }
751
+ // Exactly one instance in the project → attach to it.
752
+ if (instances.length === 1) {
753
+ return { ok: true, id: instances[0].id, attached: instances[0].owner !== sessionId };
754
+ }
755
+ return { ok: false, text: formatInstanceList(instances, "存在多个实例,请显式指定要操作的实例:调用工具时传入 `instance: \"<实例ID>\"`(支持唯一前缀)。") };
756
+ }
757
+ /** Claim an instance for a session (writes session_id into its state). */
758
+ function bindInstance(instId, sessionId) {
759
+ claimOwnership(instId, sessionId);
760
+ }
761
+ // ─── Instance destruction (complete / cancel) ───────────────────────────────
762
+ function archiveReport(instId, workflowName, status, records) {
763
+ try {
764
+ const reportsDir = getReportsDir();
765
+ if (!fs.existsSync(reportsDir))
766
+ fs.mkdirSync(reportsDir, { recursive: true });
767
+ const reportPath = path.join(reportsDir, `${instId}-final-report.md`);
768
+ let artifactsNote = "";
769
+ try {
770
+ const artifactsDir = getArtifactsDir(instId);
771
+ if (fs.readdirSync(artifactsDir).length > 0) {
772
+ artifactsNote = `\n\n产出目录:\`${getArtifactsRelDir(instId)}/\`\n`;
773
+ }
774
+ }
775
+ catch { }
776
+ // Archive the execution log alongside the report: destroyInstance removes
777
+ // the instance dir right after this returns, and without a copy the whole
778
+ // audit trail (model_source, check verdicts, infra errors) dies with it.
779
+ let logNote = "";
780
+ try {
781
+ const logFile = path.join(getLogDir(instId), "execution.log");
782
+ if (fs.existsSync(logFile)) {
783
+ fs.copyFileSync(logFile, path.join(reportsDir, `${instId}-execution.log`));
784
+ logNote = `\n\n执行日志:\`${RALPH_FLOW_DIR}/${REPORTS_DIRNAME}/${instId}-execution.log\`\n`;
785
+ }
786
+ }
787
+ catch (e) {
788
+ diag("[ralph-flow] Execution log archiving failed:", e.message);
789
+ }
790
+ atomicWriteText(reportPath, buildReportText(workflowName, status, records || []) + artifactsNote + logNote);
791
+ return reportPath;
792
+ }
793
+ catch (e) {
794
+ diag("[ralph-flow] Report generation failed:", e.message);
795
+ return null;
796
+ }
797
+ }
798
+ /**
799
+ * Destroy an instance: abort any running adversarial check, archive the final
800
+ * report, remove the instance directory. Returns the archived report path,
801
+ * or null when archiving failed — in which case NOTHING is deleted and the
802
+ * full scene (state.json, step-records.json, execution.log) survives for a
803
+ * later retry. Callers must treat null as "not destroyed" and surface the
804
+ * failure honestly instead of claiming success.
805
+ */
806
+ function destroyInstance(instId, status) {
807
+ let workflowName = instId;
808
+ const state = readState(instId);
809
+ if (state)
810
+ workflowName = state.workflow_name;
811
+ const records = loadStepRecords(instId);
812
+ // Abort a check running in this process.
813
+ try {
814
+ platform.abortActiveCheck?.(instId);
815
+ }
816
+ catch { }
817
+ const reportPath = archiveReport(instId, workflowName, status, records);
818
+ if (!reportPath) {
819
+ // 归档失败 → 拒绝销毁:报告没落地就删目录 = 报告+审计日志(step-records/
820
+ // execution.log)全部丢失且用户零感知。保留完整现场,由调用方置暂停并
821
+ // 如实告知,修复磁盘/权限后重试本操作即可。
822
+ diag("[ralph-flow] destroyInstance aborted: report archiving failed; instance kept intact:", instId);
823
+ return null;
824
+ }
825
+ // Resolve before the instance dir goes away — the artifacts-dir name file
826
+ // lives inside it.
827
+ const artifactsDir = getArtifactsDir(instId);
828
+ // 归档索引:历史第一次成为系统可回答的问题(「以前跑过什么」)。报告正文
829
+ // 留在 reports/ 的 md 里,这里只记一行指针——UI 历史 tab / 检索的数据源。
830
+ // 必须在实例目录删除前解析 artifacts 名(它就住在实例目录里)。
831
+ try {
832
+ const historyFile = path.join(getRalphFlowDir(), "history.jsonl");
833
+ const entry = {
834
+ instId,
835
+ workflow: workflowName,
836
+ task: state?.user_task ?? "",
837
+ status,
838
+ endedAt: new Date().toISOString(),
839
+ reportPath,
840
+ artifactsRelDir: fs.existsSync(artifactsDir) ? getArtifactsRelDir(instId) : undefined,
841
+ };
842
+ fs.appendFileSync(historyFile, JSON.stringify(entry) + "\n");
843
+ }
844
+ catch (e) {
845
+ diag("[ralph-flow] History index append failed:", e.message);
846
+ }
847
+ // Delete state.json first: even if the recursive removal partially fails
848
+ // (Windows EBUSY on files still held open), the instance is de-listed and
849
+ // can't act as a ghost.
850
+ try {
851
+ fs.unlinkSync(getStateFile(instId));
852
+ }
853
+ catch { }
854
+ try {
855
+ fs.rmSync(getInstanceDir(instId), { recursive: true, force: true });
856
+ }
857
+ catch (e) {
858
+ diag("[ralph-flow] Error removing instance dir:", e.message);
859
+ }
860
+ // A workflow that produced nothing leaves no folder behind — rmdir refuses
861
+ // non-empty dirs, so real deliverables always outlive the instance.
862
+ try {
863
+ fs.rmdirSync(artifactsDir);
864
+ }
865
+ catch { }
866
+ return reportPath;
867
+ }
868
+ // ─── Workflow Loader ────────────────────────────────────────────────────────
869
+ function getPluginWorkflowsDir() {
870
+ const __filename = fileURLToPath(import.meta.url);
871
+ return path.join(path.dirname(__filename), "..", "workflows");
872
+ }
873
+ function getProjectWorkflowsDir() {
874
+ return path.join(getRalphFlowDir(), "workflows");
875
+ }
876
+ // Global user workflows, available across ALL projects and surviving plugin
877
+ // updates (built-ins live inside the managed npm package, which is
878
+ // overwritten on update and not user-editable when installed online). Lives
879
+ // under dsh's own global home (honors $DSH_HOME, default ~/.dsh), so users
880
+ // find it next to their other dsh config — same shape as the opencode
881
+ // plugin's ~/.config/opencode/ralph-flow/workflows, just dsh-rooted.
882
+ function getGlobalConfigHome() {
883
+ const env = process.env.DSH_HOME;
884
+ if (env && path.isAbsolute(env))
885
+ return env;
886
+ const home = process.env.HOME || process.env.USERPROFILE || "";
887
+ if (!home)
888
+ return null;
889
+ return path.join(home, ".dsh");
890
+ }
891
+ function getGlobalWorkflowsDir() {
892
+ const cfg = getGlobalConfigHome();
893
+ return cfg ? path.join(cfg, RALPH_FLOW_DIR, "workflows") : null;
894
+ }
895
+ function parseWorkflowFile(filePath, workflowName, problems) {
896
+ // Validation failures are collected into `problems` (when provided) so tool
897
+ // responses can tell the user WHY a workflow is unusable.
898
+ const problem = (msg) => { if (Array.isArray(problems))
899
+ problems.push(msg); };
900
+ const skipStep = (msg) => { diag(`[ralph-flow] ${msg}`); problem(msg); };
901
+ try {
902
+ const stats = fs.statSync(filePath);
903
+ if (stats.size > MAX_WORKFLOW_FILE_SIZE) {
904
+ diag(`[ralph-flow] Workflow file ${filePath} exceeds ${MAX_WORKFLOW_FILE_SIZE} bytes, skipped`);
905
+ problem(`工作流文件超过 ${MAX_WORKFLOW_FILE_SIZE} 字节上限`);
906
+ return null;
907
+ }
908
+ const content = stripBom(fs.readFileSync(filePath, "utf-8"));
909
+ const parsed = yaml.load(content);
910
+ if (!parsed || typeof parsed !== "object") {
911
+ problem("YAML 内容不是对象");
912
+ return null;
913
+ }
914
+ if (!Array.isArray(parsed.steps) || parsed.steps.length === 0) {
915
+ problem("缺少非空的 steps 数组");
916
+ return null;
917
+ }
918
+ const validSteps = [];
919
+ for (let i = 0; i < parsed.steps.length; i++) {
920
+ const step = parsed.steps[i];
921
+ if (!step || typeof step !== "object") {
922
+ skipStep(`Step ${i} in ${workflowName}: not an object, skipped`);
923
+ continue;
924
+ }
925
+ if (!step.id || typeof step.id !== "string") {
926
+ skipStep(`Step ${i} in ${workflowName}: missing/invalid 'id', skipped`);
927
+ continue;
928
+ }
929
+ if (!step.desc || typeof step.desc !== "string") {
930
+ skipStep(`Step "${step.id}" in ${workflowName}: missing/invalid 'desc', skipped`);
931
+ continue;
932
+ }
933
+ if (!step.on_pass || typeof step.on_pass !== "string") {
934
+ skipStep(`Step "${step.id}" in ${workflowName}: missing/invalid 'on_pass', skipped`);
935
+ continue;
936
+ }
937
+ if (!step.on_fail || typeof step.on_fail !== "string") {
938
+ skipStep(`Step "${step.id}" in ${workflowName}: missing/invalid 'on_fail', skipped`);
939
+ continue;
940
+ }
941
+ if (typeof step.max_fail_count !== "number" || step.max_fail_count < 1) {
942
+ skipStep(`Step "${step.id}" in ${workflowName}: missing/invalid 'max_fail_count', skipped`);
943
+ continue;
944
+ }
945
+ if (step.reset !== undefined && typeof step.reset !== "boolean") {
946
+ skipStep(`Step "${step.id}" in ${workflowName}: 'reset' must be a boolean, skipped`);
947
+ continue;
948
+ }
949
+ // Validate input/output fields (they become the 输入说明/输出要求 sections of the DO/CHECK prompts)
950
+ if (!step.input || typeof step.input !== "string") {
951
+ skipStep(`Step "${step.id}" in ${workflowName}: missing/invalid 'input' field, skipped`);
952
+ continue;
953
+ }
954
+ if (!step.output || typeof step.output !== "string") {
955
+ skipStep(`Step "${step.id}" in ${workflowName}: missing/invalid 'output' field, skipped`);
956
+ continue;
957
+ }
958
+ if (step.workflow) {
959
+ if (typeof step.workflow !== "string") {
960
+ skipStep(`Step "${step.id}" in ${workflowName}: invalid 'workflow', skipped`);
961
+ continue;
962
+ }
963
+ validSteps.push(step);
964
+ continue;
965
+ }
966
+ // check 与 check_voting 互斥(§3.4 规则 1):互斥优先于类型检查——即使
967
+ // check 类型错,只要两字段都在就按互斥硬错,不让配置错误被静默 skip 掩盖。
968
+ const hasCheck = step.check !== undefined && step.check !== null;
969
+ const hasVoting = step.check_voting !== undefined && step.check_voting !== null;
970
+ if (hasCheck && hasVoting) {
971
+ problem(`步骤 "${step.id}" 的 'check' 与 'check_voting' 互斥,不能同时写(二选一)`);
972
+ return null;
973
+ }
974
+ // check_voting 校验(§3.4 规则 2):非法 → 硬错。长度 1-MAX_VOTERS(5),用户写几个就几个。
975
+ if (hasVoting) {
976
+ if (!Array.isArray(step.check_voting) || step.check_voting.length === 0) {
977
+ problem(`步骤 "${step.id}" 的 'check_voting' 必须是 1-${MAX_VOTERS} 个验证者的数组`);
978
+ return null;
979
+ }
980
+ if (step.check_voting.length > MAX_VOTERS) {
981
+ problem(`步骤 "${step.id}" 的 'check_voting' 超过上限 ${MAX_VOTERS} 个验证者`);
982
+ return null;
983
+ }
984
+ for (let vi = 0; vi < step.check_voting.length; vi++) {
985
+ const entry = step.check_voting[vi];
986
+ if (!entry || typeof entry !== "object" || typeof entry.check !== "string" || !entry.check.trim()) {
987
+ problem(`步骤 "${step.id}" 的 check_voting[${vi}] 缺少非空的 'check' 字段`);
988
+ return null;
989
+ }
990
+ const em = entry.model;
991
+ if (em !== undefined && em !== null && !resolveCheckModel(em)) {
992
+ problem(`步骤 "${step.id}" 的 check_voting[${vi}] 'model' 格式非法(应为 provider/model 或 {providerID, modelID})`);
993
+ return null;
994
+ }
995
+ const et = entry.timeout_ms;
996
+ if (et !== undefined && (typeof et !== "number" || et <= 0)) {
997
+ problem(`步骤 "${step.id}" 的 check_voting[${vi}] 'timeout_ms' 必须是正数`);
998
+ return null;
999
+ }
1000
+ }
1001
+ if (step.check_model !== undefined && step.check_model !== null) {
1002
+ problem(`步骤 "${step.id}" 同时写了 'check_voting' 与 'check_model':check_model 仅单 check 场景生效,此处无意义`);
1003
+ return null;
1004
+ }
1005
+ validSteps.push(step);
1006
+ continue;
1007
+ }
1008
+ if (!step.do || typeof step.do !== "string") {
1009
+ skipStep(`Step "${step.id}" in ${workflowName}: missing/invalid 'do', skipped`);
1010
+ continue;
1011
+ }
1012
+ // 单 check 路径:check 可缺(与 opencode 版一致)——缺则标 no_check 保留,
1013
+ // DO 完成后直通 on_pass(driver skipCheck),不静默丢弃步骤。
1014
+ if (!hasCheck) {
1015
+ validSteps.push({ ...step, no_check: true });
1016
+ continue;
1017
+ }
1018
+ if (typeof step.check !== "string") {
1019
+ skipStep(`Step "${step.id}" in ${workflowName}: missing/invalid 'check', skipped`);
1020
+ continue;
1021
+ }
1022
+ validSteps.push(step);
1023
+ }
1024
+ if (validSteps.length === 0) {
1025
+ problem("没有任何有效步骤");
1026
+ return null;
1027
+ }
1028
+ // Duplicate step ids make on_pass/on_fail ambiguous (getStep returns the
1029
+ // first match, and the id Set silently collapses the rest) — a hard
1030
+ // error, not a silent merge.
1031
+ const dupIds = [...new Set(validSteps.map((s) => s.id).filter((id, i, arr) => arr.indexOf(id) !== i))];
1032
+ if (dupIds.length > 0) {
1033
+ problem(`步骤 id 重复:${dupIds.map((id) => `"${id}"`).join("、")}(每个步骤的 id 必须唯一)`);
1034
+ return null;
1035
+ }
1036
+ // Validate on_pass/on_fail references
1037
+ const stepIds = new Set(validSteps.map((s) => s.id));
1038
+ for (const step of validSteps) {
1039
+ if (step.on_pass !== "done" && !stepIds.has(step.on_pass)) {
1040
+ diag(`[ralph-flow] Step "${step.id}" on_pass references unknown step "${step.on_pass}"`);
1041
+ problem(`步骤 "${step.id}" 的 on_pass 引用了不存在的步骤 "${step.on_pass}"`);
1042
+ return null;
1043
+ }
1044
+ if (!stepIds.has(step.on_fail)) {
1045
+ diag(`[ralph-flow] Step "${step.id}" on_fail references unknown step "${step.on_fail}"`);
1046
+ problem(`步骤 "${step.id}" 的 on_fail 引用了不存在的步骤 "${step.on_fail}"`);
1047
+ return null;
1048
+ }
1049
+ }
1050
+ const auto_reset = typeof parsed.auto_reset === "boolean" ? parsed.auto_reset : (parsed.auto_reset !== undefined ? (problem("'auto_reset' 必须为 boolean(true/false)"), false) : false);
1051
+ const manual_step = Array.isArray(parsed.manual_step)
1052
+ ? parsed.manual_step.filter((s) => typeof s === "string" && s.trim()).map((s) => s.trim())
1053
+ : typeof parsed.manual_step === "string"
1054
+ ? parsed.manual_step.split(",").map((s) => s.trim()).filter(Boolean)
1055
+ : [];
1056
+ // A typo'd manual_step entry would silently drop a human review gate the
1057
+ // user is counting on — the workflow would run fully automated past the
1058
+ // point that was supposed to stop for review. Hard error, not a warning.
1059
+ const unknownManual = manual_step.filter((id) => !stepIds.has(id));
1060
+ if (unknownManual.length > 0) {
1061
+ diag(`[ralph-flow] manual_step in ${workflowName} references unknown step(s): ${unknownManual.join(", ")}`);
1062
+ problem(`manual_step 引用了不存在的步骤:${unknownManual.map((s) => `"${s}"`).join("、")}`);
1063
+ return null;
1064
+ }
1065
+ // The manual review gate is driven by a step's DO phase (the driver stops
1066
+ // when DO completes and waits for approval). Sub-workflow (composite) steps
1067
+ // have no DO phase — the idle driver skips them entirely — so marking one
1068
+ // manual is silently inert: the gate the user is counting on never fires.
1069
+ // Reject it so the mistake surfaces at load time instead of at runtime.
1070
+ const compositeStepIds = new Set(validSteps.filter((s) => isSubWorkflowStep(s)).map((s) => s.id));
1071
+ const compositeManual = manual_step.filter((id) => compositeStepIds.has(id));
1072
+ if (compositeManual.length > 0) {
1073
+ diag(`[ralph-flow] manual_step in ${workflowName} references composite/sub-workflow step(s): ${compositeManual.join(", ")}`);
1074
+ problem(`manual_step 不能用于子工作流(复合)步骤:${compositeManual.map((s) => `"${s}"`).join("、")}。手动审查门只作用于带 do/check 的最小步骤——若要在子工作流后停下审查,请把 manual_step 标在该子工作流内部最后一个普通步骤上。`);
1075
+ return null;
1076
+ }
1077
+ const adv = parsed.adversarial_check;
1078
+ let adversarial_check = undefined;
1079
+ if (adv && typeof adv === "object") {
1080
+ // Both formats are native here: string model (Claude Code style) is
1081
+ // passed through and resolved by the host; object {providerID, modelID}
1082
+ // is the opencode SDK's own shape. The object form requires BOTH ids as
1083
+ // non-empty strings — a half-specified object (e.g. modelID only, or a
1084
+ // numeric providerID) would otherwise reach the SDK as garbage and
1085
+ // surface as an opaque request failure; drop it here and let the
1086
+ // linter warn (mirrors how the bare-string form is handled).
1087
+ let model = undefined;
1088
+ if (typeof adv.model === "string" && adv.model.trim()) {
1089
+ model = adv.model.trim();
1090
+ }
1091
+ else if (adv.model && typeof adv.model === "object") {
1092
+ const pid = adv.model.providerID;
1093
+ const mid = adv.model.modelID;
1094
+ if (typeof pid === "string" && pid.trim() && typeof mid === "string" && mid.trim()) {
1095
+ model = { providerID: pid.trim(), modelID: mid.trim() };
1096
+ }
1097
+ }
1098
+ const system_prompt = typeof adv.system_prompt === "string" && adv.system_prompt.trim() ? adv.system_prompt.trim() : undefined;
1099
+ const agent = typeof adv.agent === "string" && adv.agent.trim() ? adv.agent.trim() : undefined;
1100
+ let timeout_ms = undefined;
1101
+ if (typeof adv.timeout_ms === "number" && adv.timeout_ms > 0) {
1102
+ timeout_ms = Math.min(adv.timeout_ms, 3600000); // Cap at 1 hour
1103
+ }
1104
+ adversarial_check = { model, agent, system_prompt, timeout_ms };
1105
+ }
1106
+ return {
1107
+ name: workflowName,
1108
+ description: parsed.description || validSteps[0].desc || workflowName,
1109
+ manual_step,
1110
+ steps: validSteps,
1111
+ adversarial_check,
1112
+ auto_reset,
1113
+ };
1114
+ }
1115
+ catch (e) {
1116
+ diag(`[ralph-flow] Error parsing workflow ${filePath}:`, e.message);
1117
+ problem(`解析失败:${e.message}`);
1118
+ return null;
1119
+ }
1120
+ }
1121
+ function isValidWorkflowName(name) {
1122
+ // Reject names with path separators, traversal sequences, or special chars
1123
+ return typeof name === "string" && name.length > 0 && name.length < 100
1124
+ && !/[\/\\]/.test(name) && !name.includes("..") && !name.startsWith(".");
1125
+ }
1126
+ function loadWorkflow(workflowName, problems) {
1127
+ if (!isValidWorkflowName(workflowName))
1128
+ return null;
1129
+ const globalDir = getGlobalWorkflowsDir();
1130
+ // Resolution order: project > global user > plugin built-in. A same-named
1131
+ // workflow at an earlier tier shadows the later ones.
1132
+ const searchPaths = [
1133
+ path.join(getProjectWorkflowsDir(), `${workflowName}.yaml`),
1134
+ path.join(getProjectWorkflowsDir(), `${workflowName}.yml`),
1135
+ ...(globalDir ? [
1136
+ path.join(globalDir, `${workflowName}.yaml`),
1137
+ path.join(globalDir, `${workflowName}.yml`),
1138
+ ] : []),
1139
+ path.join(getPluginWorkflowsDir(), `${workflowName}.yaml`),
1140
+ path.join(getPluginWorkflowsDir(), `${workflowName}.yml`),
1141
+ ];
1142
+ for (const p of searchPaths) {
1143
+ if (fs.existsSync(p)) {
1144
+ const result = parseWorkflowFile(p, workflowName, problems);
1145
+ if (result)
1146
+ return result;
1147
+ }
1148
+ }
1149
+ return null;
1150
+ }
1151
+ function listWorkflows() {
1152
+ const workflows = new Map();
1153
+ const scanDir = (dir) => {
1154
+ if (!fs.existsSync(dir))
1155
+ return;
1156
+ try {
1157
+ for (const file of fs.readdirSync(dir)) {
1158
+ if (file.endsWith(".yaml") || file.endsWith(".yml")) {
1159
+ try {
1160
+ const filePath = path.join(dir, file);
1161
+ const stats = fs.statSync(filePath);
1162
+ if (stats.size > MAX_WORKFLOW_FILE_SIZE) {
1163
+ diag(`[ralph-flow] Workflow file ${filePath} exceeds ${MAX_WORKFLOW_FILE_SIZE} bytes, skipped`);
1164
+ continue;
1165
+ }
1166
+ const content = stripBom(fs.readFileSync(filePath, "utf-8"));
1167
+ const parsed = yaml.load(content);
1168
+ // Not workflow-shaped at all (stray yaml) — skip silently, as before.
1169
+ if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.steps) || parsed.steps.length === 0)
1170
+ continue;
1171
+ const name = file.replace(/\.(yaml|yml)$/, "");
1172
+ // Run the FULL validation so the list agrees with what
1173
+ // ralphflow_start will accept — a file that fails loadWorkflow must
1174
+ // not be listed as launchable, it gets flagged instead.
1175
+ const problems = [];
1176
+ const wf = parseWorkflowFile(filePath, name, problems);
1177
+ const existing = workflows.get(name);
1178
+ if (wf) {
1179
+ // First valid candidate in resolution order wins; a valid later
1180
+ // candidate replaces an invalid earlier one — loadWorkflow falls
1181
+ // through invalid files the same way.
1182
+ if (!existing || existing.invalid) {
1183
+ workflows.set(name, { name, desc: wf.description });
1184
+ }
1185
+ }
1186
+ else if (!existing) {
1187
+ workflows.set(name, {
1188
+ name,
1189
+ desc: `⚠️ 定义无效,无法启动:${problems[0] || "解析失败"}`,
1190
+ invalid: true,
1191
+ });
1192
+ }
1193
+ }
1194
+ catch (e) {
1195
+ diag(`[ralph-flow] Error reading workflow ${file}:`, e.message);
1196
+ }
1197
+ }
1198
+ }
1199
+ }
1200
+ catch (e) {
1201
+ diag(`[ralph-flow] Error scanning dir ${dir}:`, e.message);
1202
+ }
1203
+ };
1204
+ // Scan project → global → plugin — the first VALID writer wins, so a valid
1205
+ // project workflow shadows a same-named global one which shadows a built-in,
1206
+ // while an invalid one falls through. Matches loadWorkflow's resolution
1207
+ // order exactly, so list and execution agree.
1208
+ scanDir(getProjectWorkflowsDir());
1209
+ const globalDir = getGlobalWorkflowsDir();
1210
+ if (globalDir)
1211
+ scanDir(globalDir);
1212
+ scanDir(getPluginWorkflowsDir());
1213
+ return Array.from(workflows.values());
1214
+ }
1215
+ // ─── Workflow Doctor ────────────────────────────────────────────────────────
1216
+ //
1217
+ // Deep diagnosis behind the ralphflow_doctor tool. Reuses parseWorkflowFile so
1218
+ // its verdicts always agree with what ralphflow_start actually accepts, then
1219
+ // layers lints for problems the engine only surfaces at runtime (or never).
1220
+ /**
1221
+ * Lint a workflow that already passed full validation. Returns human-readable
1222
+ * warning strings — things that won't stop ralphflow_start but will bite later.
1223
+ * `rawParsed` is the untouched yaml.load result (parseWorkflowFile drops fields
1224
+ * the lints need to see).
1225
+ */
1226
+ function lintWorkflow(wf, rawParsed, fromBuiltin = false) {
1227
+ const warnings = [];
1228
+ // Unreachable steps: execution enters at steps[0] and only moves along
1229
+ // on_pass/on_fail edges, so anything outside that closure never runs.
1230
+ const byId = new Map(wf.steps.map((s) => [s.id, s]));
1231
+ const reachable = new Set();
1232
+ const queue = [wf.steps[0].id];
1233
+ while (queue.length > 0) {
1234
+ const id = queue.pop();
1235
+ if (reachable.has(id))
1236
+ continue;
1237
+ reachable.add(id);
1238
+ const s = byId.get(id);
1239
+ if (!s)
1240
+ continue;
1241
+ if (s.on_pass !== "done")
1242
+ queue.push(s.on_pass);
1243
+ queue.push(s.on_fail);
1244
+ }
1245
+ const unreachable = wf.steps.filter((s) => !reachable.has(s.id)).map((s) => s.id);
1246
+ if (unreachable.length > 0) {
1247
+ warnings.push(`步骤 ${unreachable.map((s) => `"${s}"`).join("、")} 从入口(steps 的第一项)沿 on_pass/on_fail 不可达,永远不会执行`);
1248
+ }
1249
+ // A workflow none of whose reachable steps can reach "done" never finishes.
1250
+ if (!wf.steps.some((s) => reachable.has(s.id) && s.on_pass === "done")) {
1251
+ warnings.push(`没有任何可达步骤的 on_pass 为 "done",工作流永远无法正常完成`);
1252
+ }
1253
+ // Template tokens: the engine resolves exactly one token, {{artifacts_dir}}
1254
+ // (byte-exact — even extra spaces inside the braces break it). Anything else
1255
+ // reaches the DO/CHECK prompt unresolved.
1256
+ for (const s of wf.steps) {
1257
+ for (const field of ["desc", "do", "check", "input", "output"]) {
1258
+ const text = s[field];
1259
+ if (typeof text !== "string")
1260
+ continue;
1261
+ for (const m of text.matchAll(/\{\{[^{}]*\}\}/g)) {
1262
+ if (m[0] !== ARTIFACTS_TOKEN) {
1263
+ warnings.push(`步骤 "${s.id}" 的 ${field} 含模板变量 ${m[0]},引擎不会解析(唯一支持的记号是 ${ARTIFACTS_TOKEN},花括号内不能有空格;产出目录本就会自动注入到提示词,通常不需要任何记号)`);
1264
+ }
1265
+ }
1266
+ }
1267
+ }
1268
+ // Sub-workflow references resolve lazily at runtime — a broken one passes
1269
+ // validation and then fails the workflow mid-run.
1270
+ for (const s of wf.steps) {
1271
+ if (!isSubWorkflowStep(s))
1272
+ continue;
1273
+ const subProblems = [];
1274
+ if (!loadWorkflow(s.workflow, subProblems)) {
1275
+ warnings.push(`步骤 "${s.id}" 引用的子工作流 "${s.workflow}" 无法加载(${subProblems[0] || "未找到定义文件"})— 校验能通过,但运行到该步时工作流会失败`);
1276
+ }
1277
+ }
1278
+ const cycle = findSubWorkflowCycle(wf.name);
1279
+ if (cycle) {
1280
+ warnings.push(`子工作流引用成环:${cycle.join(" → ")}。运行时会在嵌套深度 ${MAX_NESTING_DEPTH} 处报错暂停`);
1281
+ }
1282
+ // adversarial_check fields the opencode engine clamps.
1283
+ const adv = rawParsed && typeof rawParsed === "object" ? rawParsed.adversarial_check : undefined;
1284
+ if (adv && typeof adv === "object") {
1285
+ if (typeof adv.timeout_ms === "number" && adv.timeout_ms > 3600000) {
1286
+ warnings.push(`adversarial_check.timeout_ms(${adv.timeout_ms})超过 1 小时上限,会被截断为 3600000`);
1287
+ }
1288
+ if (typeof adv.model === "string" && adv.model.includes("/") === false && adv.model.trim()) {
1289
+ warnings.push(`adversarial_check.model 是字符串("${adv.model}")——opencode 需要能被解析的模型标识(如 "anthropic/claude-sonnet-4-5" 或对象 {providerID, modelID}),无法解析时将回退到 ralph-check agent 的默认模型`);
1290
+ }
1291
+ if (adv.model && typeof adv.model === "object") {
1292
+ const pidOk = typeof adv.model.providerID === "string" && adv.model.providerID.trim();
1293
+ const midOk = typeof adv.model.modelID === "string" && adv.model.modelID.trim();
1294
+ if (!pidOk || !midOk) {
1295
+ const missing = !pidOk && !midOk ? "providerID 和 modelID" : !pidOk ? "providerID" : "modelID";
1296
+ warnings.push(`adversarial_check.model 是对象但缺少有效的 ${missing}(需要 {providerID, modelID} 两个非空字符串)——该配置被忽略,回退到 ralph-check agent 的默认模型`);
1297
+ }
1298
+ }
1299
+ }
1300
+ // check_voting 条目的 lint(设计 §3.5;硬错误已在 parseWorkflowFile 拦截,
1301
+ // 这里只报已通过校验但仍可优化的配置)。
1302
+ if (rawParsed && typeof rawParsed === "object" && Array.isArray(rawParsed.steps)) {
1303
+ for (const s of rawParsed.steps) {
1304
+ if (!s || typeof s !== "object" || !Array.isArray(s.check_voting))
1305
+ continue;
1306
+ const sid = typeof s.id === "string" ? s.id : "(?)";
1307
+ if (s.check_voting.length === 1 && !(s.check_voting[0] && s.check_voting[0].model)) {
1308
+ warnings.push(`步骤 "${sid}" 的 check_voting 只有 1 个验证者且未指定 model——等同单验证者,建议直接用 check 或配多视角/多模型`);
1309
+ }
1310
+ if (s.check_voting.length === 1 && s.check) {
1311
+ warnings.push(`步骤 "${sid}" 同时写了 check 与 check_voting`);
1312
+ }
1313
+ if (s.check_model !== undefined && s.check_voting) {
1314
+ warnings.push(`步骤 "${sid}" 同时写了 'check_voting' 与 'check_model':check_model 仅单 check 场景生效`);
1315
+ }
1316
+ for (let vi = 0; vi < s.check_voting.length; vi++) {
1317
+ const entry = s.check_voting[vi];
1318
+ if (!entry || typeof entry !== "object")
1319
+ continue;
1320
+ if (entry.model && typeof entry.model === "string" && !entry.model.includes("/")) {
1321
+ warnings.push(`步骤 "${sid}" 的 check_voting[${vi}].model 是字符串("${entry.model}")——无法解析时将回退到 ralph-check agent 的默认模型`);
1322
+ }
1323
+ if (entry.model && typeof entry.model === "object") {
1324
+ const pidOk = typeof entry.model.providerID === "string" && entry.model.providerID.trim();
1325
+ const midOk = typeof entry.model.modelID === "string" && entry.model.modelID.trim();
1326
+ if (!pidOk || !midOk) {
1327
+ warnings.push(`步骤 "${sid}" 的 check_voting[${vi}].model 是对象但缺少有效的 providerID/modelID——该配置被忽略,回退到默认模型`);
1328
+ }
1329
+ }
1330
+ }
1331
+ }
1332
+ }
1333
+ // reset / auto_reset 提示。内置工作流跳过:标 reset 是插件设计决定,
1334
+ // 不该对用户显示"成本较高"的警告。
1335
+ if (!fromBuiltin && wf.steps.length > 0 && wf.steps[0].reset === true) {
1336
+ warnings.push(`首步 "${wf.steps[0].id}" 标了 reset:启动时已是新会话不触发;但进入该步的每次转换都触发——包括失败重试(on_fail 回本步)和后续步骤 on_fail 回首步。单步骤 loop 会频繁重置,token 成本较高`);
1337
+ }
1338
+ if (!fromBuiltin && wf.auto_reset === true) {
1339
+ const allOnFailSelf = wf.steps.every((s) => s.on_fail === s.id);
1340
+ if (allOnFailSelf) {
1341
+ warnings.push(`auto_reset: true 且所有步骤的 on_fail 都指向自身(纯线性流)——每次失败重试也会换新会话,token 成本较高`);
1342
+ }
1343
+ }
1344
+ return warnings;
1345
+ }
1346
+ /**
1347
+ * DFS through sub-workflow references looking for a cycle starting at `name`.
1348
+ * Returns the cycle path (["a", "b", "a"]) or null. `clean` memoizes names
1349
+ * proven cycle-free so shared sub-workflows aren't re-walked.
1350
+ */
1351
+ function findSubWorkflowCycle(name, stack = [], clean = new Set()) {
1352
+ if (clean.has(name))
1353
+ return null;
1354
+ const idx = stack.indexOf(name);
1355
+ if (idx >= 0)
1356
+ return [...stack.slice(idx), name];
1357
+ const wf = loadWorkflow(name);
1358
+ if (wf) {
1359
+ for (const s of wf.steps) {
1360
+ if (!isSubWorkflowStep(s))
1361
+ continue;
1362
+ const cycle = findSubWorkflowCycle(s.workflow, [...stack, name], clean);
1363
+ if (cycle)
1364
+ return cycle;
1365
+ }
1366
+ }
1367
+ clean.add(name);
1368
+ return null;
1369
+ }
1370
+ /**
1371
+ * Diagnose every workflow file in all search dirs. Returns per-name entries
1372
+ * in loadWorkflow's exact resolution order (project, global user, plugin
1373
+ * built-in) so "which file actually runs" is derivable, plus yaml files that
1374
+ * aren't workflow-shaped at all.
1375
+ */
1376
+ function diagnoseWorkflowFiles() {
1377
+ const globalDir = getGlobalWorkflowsDir();
1378
+ const sources = [
1379
+ { source: "project", label: "项目自定义", dir: getProjectWorkflowsDir() },
1380
+ ...(globalDir ? [{ source: "global", label: "全局用户", dir: globalDir }] : []),
1381
+ { source: "plugin", label: "插件内置", dir: getPluginWorkflowsDir() },
1382
+ ];
1383
+ const byName = new Map(); // name -> candidate[] in resolution order
1384
+ const strays = []; // yaml files that aren't workflow definitions
1385
+ for (const { source, label, dir } of sources) {
1386
+ if (!fs.existsSync(dir))
1387
+ continue;
1388
+ let files;
1389
+ try {
1390
+ files = fs.readdirSync(dir);
1391
+ }
1392
+ catch {
1393
+ continue;
1394
+ }
1395
+ // .yaml before .yml within a dir, matching loadWorkflow's searchPaths.
1396
+ files = files.filter((f) => f.endsWith(".yaml") || f.endsWith(".yml"))
1397
+ .sort((a, b) => (a.endsWith(".yaml") ? 0 : 1) - (b.endsWith(".yaml") ? 0 : 1) || a.localeCompare(b));
1398
+ for (const file of files) {
1399
+ const filePath = path.join(dir, file);
1400
+ const name = file.replace(/\.(yaml|yml)$/, "");
1401
+ const relPath = source === "project"
1402
+ ? `${RALPH_FLOW_DIR}/workflows/${file}`
1403
+ : source === "global"
1404
+ ? `~/.dsh/${RALPH_FLOW_DIR}/workflows/${file}`
1405
+ : `<插件目录>/workflows/${file}`;
1406
+ const candidate = { source, sourceLabel: label, file, filePath, relPath, name };
1407
+ try {
1408
+ if (fs.statSync(filePath).size > MAX_WORKFLOW_FILE_SIZE) {
1409
+ candidate.verdict = "invalid";
1410
+ candidate.problems = [`工作流文件超过 ${MAX_WORKFLOW_FILE_SIZE} 字节上限`];
1411
+ pushCandidate(byName, candidate);
1412
+ continue;
1413
+ }
1414
+ let rawParsed;
1415
+ try {
1416
+ rawParsed = yaml.load(stripBom(fs.readFileSync(filePath, "utf-8")));
1417
+ }
1418
+ catch (e) {
1419
+ candidate.verdict = "invalid";
1420
+ candidate.problems = [`YAML 解析失败:${e.message.split("\n")[0]}`];
1421
+ pushCandidate(byName, candidate);
1422
+ continue;
1423
+ }
1424
+ if (!rawParsed || typeof rawParsed !== "object" || !("steps" in rawParsed)) {
1425
+ // Not workflow-shaped: probably a stray yaml, but the user may have
1426
+ // MEANT it as a workflow — surface it instead of skipping silently.
1427
+ candidate.verdict = "stray";
1428
+ strays.push(candidate);
1429
+ continue;
1430
+ }
1431
+ const problems = [];
1432
+ const wf = parseWorkflowFile(filePath, name, problems);
1433
+ if (wf) {
1434
+ candidate.verdict = "valid";
1435
+ candidate.desc = wf.description;
1436
+ // Soft problems (skipped steps) that didn't invalidate the file are
1437
+ // exactly the silent-drop trap — merge them with the lints.
1438
+ candidate.warnings = [
1439
+ ...problems.map((p) => `${p}(该步骤已被静默丢弃,工作流其余部分照常运行)`),
1440
+ ...lintWorkflow(wf, rawParsed, source === "plugin"),
1441
+ ];
1442
+ }
1443
+ else {
1444
+ candidate.verdict = "invalid";
1445
+ candidate.problems = problems.length > 0 ? problems : ["解析失败"];
1446
+ }
1447
+ pushCandidate(byName, candidate);
1448
+ }
1449
+ catch (e) {
1450
+ candidate.verdict = "invalid";
1451
+ candidate.problems = [`读取失败:${e.message}`];
1452
+ pushCandidate(byName, candidate);
1453
+ }
1454
+ }
1455
+ }
1456
+ return { byName, strays };
1457
+ }
1458
+ function pushCandidate(byName, candidate) {
1459
+ if (!byName.has(candidate.name))
1460
+ byName.set(candidate.name, []);
1461
+ byName.get(candidate.name).push(candidate);
1462
+ }
1463
+ /** Instance-dir health: state.json missing or corrupt makes an instance invisible to every tool. */
1464
+ function diagnoseInstances() {
1465
+ const issues = [];
1466
+ const root = getInstancesRoot();
1467
+ if (!fs.existsSync(root))
1468
+ return issues;
1469
+ let entries;
1470
+ try {
1471
+ entries = fs.readdirSync(root, { withFileTypes: true });
1472
+ }
1473
+ catch {
1474
+ return issues;
1475
+ }
1476
+ for (const entry of entries) {
1477
+ if (!entry.isDirectory())
1478
+ continue;
1479
+ const stateFile = path.join(root, entry.name, "state.json");
1480
+ if (!fs.existsSync(stateFile)) {
1481
+ // 有隔离备份(.invalid/.corrupted)说明 state 曾被读时改名保护过——
1482
+ // 提示用户备份可抢救,绝不能引导「直接删除整个目录」连备份一起销毁。
1483
+ let backups = [];
1484
+ try {
1485
+ backups = fs.readdirSync(path.join(root, entry.name))
1486
+ .filter((f) => f.startsWith("state.json.invalid.") || f.startsWith("state.json.corrupted."));
1487
+ }
1488
+ catch { }
1489
+ issues.push(backups.length > 0
1490
+ ? `实例 \`${entry.name}\` 的 state.json 已被隔离为 ${backups.join("、")} — 实例对所有工具不可见。目录内有最后状态备份可人工抢救;确认无需保留后再删除整个目录`
1491
+ : `实例目录 \`instances/${entry.name}/\` 缺少 state.json — 所有工具都看不到它。若是残留目录可直接删除`);
1492
+ continue;
1493
+ }
1494
+ try {
1495
+ const parsed = JSON.parse(stripBom(fs.readFileSync(stateFile, "utf-8")));
1496
+ if (!parsed || typeof parsed !== "object")
1497
+ throw new Error("not an object");
1498
+ }
1499
+ catch (e) {
1500
+ issues.push(`实例 \`${entry.name}\` 的 state.json 损坏(${e.message.split("\n")[0]})— 该实例无法恢复,确认无需保留后可删除整个目录`);
1501
+ }
1502
+ }
1503
+ return issues;
1504
+ }
1505
+ function buildDoctorReport() {
1506
+ const { byName, strays } = diagnoseWorkflowFiles();
1507
+ const instanceIssues = diagnoseInstances();
1508
+ const sections = [];
1509
+ let launchable = 0, withWarnings = 0, broken = 0;
1510
+ const detailLines = [];
1511
+ const names = Array.from(byName.keys()).sort((a, b) => a.localeCompare(b));
1512
+ for (const name of names) {
1513
+ const candidates = byName.get(name);
1514
+ const effective = candidates.find((c) => c.verdict === "valid") || null;
1515
+ const lines = [`### ${name}`];
1516
+ if (effective) {
1517
+ launchable++;
1518
+ const shadowed = candidates.filter((c) => c !== effective);
1519
+ let sourceNote = `${effective.relPath}(${effective.sourceLabel}`;
1520
+ // A valid candidate LATER in resolution order is shadowed by this one.
1521
+ const shadowedValid = shadowed.find((c) => c.verdict === "valid" && candidates.indexOf(c) > candidates.indexOf(effective));
1522
+ if (shadowedValid) {
1523
+ sourceNote += `,遮蔽了同名${shadowedValid.sourceLabel} ${shadowedValid.relPath}`;
1524
+ }
1525
+ sourceNote += ")";
1526
+ lines.push(`- 生效文件:${sourceNote}`);
1527
+ // An invalid candidate EARLIER in resolution order means the user's file
1528
+ // is being silently skipped in favor of this one — worth shouting about.
1529
+ const brokenBefore = candidates.slice(0, candidates.indexOf(effective)).filter((c) => c.verdict === "invalid");
1530
+ for (const b of brokenBefore) {
1531
+ broken++;
1532
+ lines.push(`- ❌ ${b.relPath} 定义无效,已回退到上面的生效文件(启动的不是你这份!)`);
1533
+ for (const p of b.problems || [])
1534
+ lines.push(` - ${p}`);
1535
+ }
1536
+ if ((effective.warnings || []).length > 0) {
1537
+ withWarnings++;
1538
+ lines.push(`- ✅ 可启动,但有 ${effective.warnings.length} 条警告:`);
1539
+ for (const w of effective.warnings)
1540
+ lines.push(` - ⚠️ ${w}`);
1541
+ }
1542
+ else {
1543
+ lines.push(`- ✅ 可启动,无警告`);
1544
+ }
1545
+ // Invalid candidates AFTER the effective one are harmless (never reached)
1546
+ // — mention them only so the user knows the file exists and is dead.
1547
+ const deadAfter = candidates.slice(candidates.indexOf(effective) + 1).filter((c) => c.verdict === "invalid");
1548
+ for (const d of deadAfter) {
1549
+ lines.push(`- ℹ️ ${d.relPath} 定义无效,但已被上面的生效文件遮蔽,不影响使用(问题:${(d.problems || [])[0]})`);
1550
+ }
1551
+ }
1552
+ else {
1553
+ broken += candidates.length;
1554
+ lines.push(`- ❌ 无法启动(没有任何有效定义)`);
1555
+ for (const c of candidates) {
1556
+ lines.push(`- 文件 ${c.relPath}:`);
1557
+ for (const p of c.problems || [])
1558
+ lines.push(` - ${p}`);
1559
+ }
1560
+ }
1561
+ detailLines.push(lines.join("\n"));
1562
+ }
1563
+ sections.push(`# Ralph Flow 工作流诊断\n\n## 概览\n\n- 可启动工作流:**${launchable}** 个${withWarnings > 0 ? `(其中 ${withWarnings} 个有警告)` : ""}\n- 有问题的定义文件:**${broken}** 个\n- 非工作流 YAML:**${strays.length}** 个\n- 实例目录异常:**${instanceIssues.length}** 个`);
1564
+ if (detailLines.length > 0) {
1565
+ sections.push(`## 工作流详情\n\n${detailLines.join("\n\n")}`);
1566
+ }
1567
+ else {
1568
+ sections.push(`## 工作流详情\n\n三个目录(工作区 ${RALPH_FLOW_DIR}/workflows/、全局 ~/.dsh/${RALPH_FLOW_DIR}/workflows/、插件内置 workflows/)里都没有找到自定义工作流定义文件。内置的 \`loop\`、\`spec\` 开箱即用;要自定义,可复制插件内置 workflows/*.yaml 为模板,改好后放到上述任一目录。`);
1569
+ }
1570
+ if (strays.length > 0) {
1571
+ sections.push(`## 被忽略的 YAML 文件\n\n以下文件不是工作流定义(缺少 steps 数组),list/start 都会忽略它们。若本意是工作流,需要补上 steps:\n\n${strays.map((s) => `- ${s.relPath}`).join("\n")}`);
1572
+ }
1573
+ if (instanceIssues.length > 0) {
1574
+ sections.push(`## 实例目录异常\n\n${instanceIssues.map((i) => `- ⚠️ ${i}`).join("\n")}`);
1575
+ }
1576
+ const projectDirExists = fs.existsSync(getProjectWorkflowsDir());
1577
+ const hasProjectWorkflow = names.some((n) => byName.get(n).some((c) => c.source === "project"));
1578
+ const hasGlobalWorkflow = names.some((n) => byName.get(n).some((c) => c.source === "global"));
1579
+ if (!hasProjectWorkflow && !hasGlobalWorkflow) {
1580
+ const dirNote = projectDirExists ? "" : `(\`${RALPH_FLOW_DIR}/workflows/\` 目录尚未创建)`;
1581
+ sections.push(`## 提示\n\n还没有自定义工作流${dirNote}。内置工作流开箱即用;要定制自己的流程,可复制内置 workflows/*.yaml 为模板修改,放到工作区 \`${RALPH_FLOW_DIR}/workflows/\`(只对本工作区生效)或全局 \`~/.dsh/${RALPH_FLOW_DIR}/workflows/\`(所有项目可用,且插件更新不会覆盖)。用 /ralphflow-doctor 校验定义。`);
1582
+ }
1583
+ return sections.join("\n\n");
1584
+ }
1585
+ // ─── Step Helpers ───────────────────────────────────────────────────────────
1586
+ function getStep(workflow, stepId) {
1587
+ return workflow.steps.find((s) => s.id === stepId) || null;
1588
+ }
1589
+ function buildDoPrompt(instId, step, userTask, retryContext, retryCount) {
1590
+ const sections = [];
1591
+ const isRetry = retryContext || (retryCount && retryCount > 0);
1592
+ if (userTask)
1593
+ sections.push(`## 用户需求\n\n${truncateText(userTask, 4000)}`);
1594
+ if (retryContext)
1595
+ sections.push(`## 上次失败原因\n\n${truncateText(retryContext, 4000)}`);
1596
+ if (retryCount && retryCount > 0) {
1597
+ sections.push(`## 重试信息\n\n这是第 **${retryCount}** 次重试,最大重试次数为 **${step.max_fail_count}** 次。`);
1598
+ }
1599
+ if (sections.length > 0)
1600
+ sections.push("---");
1601
+ try {
1602
+ fs.mkdirSync(getArtifactsDir(instId), { recursive: true });
1603
+ }
1604
+ catch { }
1605
+ sections.push(`## 当前任务
1606
+
1607
+ **步骤**:${step.id}
1608
+ **描述**:${step.desc}
1609
+
1610
+ **任务**:${truncateText(renderStepText(instId, step.do), 8000)}
1611
+
1612
+ **输入说明**:${truncateText(renderStepText(instId, step.input), 2000)}
1613
+
1614
+ **输出要求**:${truncateText(renderStepText(instId, step.output), 2000)}
1615
+
1616
+ **产出目录**:\`${getArtifactsRelDir(instId)}/\` — 本工作流的文档产出(清单、方案、报告等)统一放在此目录。步骤中提到的文档文件名(如 summary.md)若未写路径,即指此目录下的文件;明确写了其他路径的除外。`);
1617
+ if (isRetry) {
1618
+ sections.push(`---
1619
+
1620
+ ## 执行指令
1621
+
1622
+ 上次执行未通过,原因见上方。请执行以下操作:
1623
+
1624
+ 1. **针对上述失败原因进行修复**,不要重复之前未通过的做法
1625
+ 2. 完成实际工作(修改代码、创建文件、执行命令等)
1626
+ 3. 所有任务要求和输出要求都满足后,在回复的**最后一行**单独输出 \`<promise>done</promise>\`
1627
+
1628
+ 不要只描述你打算怎么做,直接去做。不要在工作未完成时输出 done 标记。`);
1629
+ }
1630
+ else {
1631
+ sections.push(`---
1632
+
1633
+ ## 执行指令
1634
+
1635
+ 请执行上述任务。完成实际工作(修改代码、创建文件、执行命令等),不要只做分析或规划。
1636
+ ${step.no_check ? "\n本步骤没有配置独立验证(no-check),完成后直接进入下一步。\n" : ""}
1637
+ 所有任务要求和输出要求都满足后,在回复的**最后一行**单独输出 \`<promise>done</promise>\`。
1638
+
1639
+ 如果遇到无法解决的问题,说明具体问题,不要输出 done 标记。`);
1640
+ }
1641
+ const prompt = sections.join("\n\n");
1642
+ // Cache the do prompt: the driver re-injects it in keep-alives and phase reports
1643
+ writeDoPromptCache(prompt, instId);
1644
+ return prompt;
1645
+ }
1646
+ function buildCheckPrompt(instId, step, userTask) {
1647
+ const sections = [];
1648
+ if (userTask)
1649
+ sections.push(`## 用户需求\n\n${truncateText(userTask, 4000)}`);
1650
+ sections.push(`## Do 阶段任务
1651
+
1652
+ **步骤**:${step.id}
1653
+ **任务描述**:${truncateText(renderStepText(instId, step.do), 8000)}
1654
+ **输入**:${truncateText(renderStepText(instId, step.input), 2000)}
1655
+ **预期输出**:${truncateText(renderStepText(instId, step.output), 2000)}
1656
+ **产出目录**:\`${getArtifactsRelDir(instId)}/\` — 检查依据中未写路径的文档文件名即指此目录下的文件`);
1657
+ if (sections.length > 0)
1658
+ sections.push("---");
1659
+ sections.push(`## 检查依据
1660
+
1661
+ ${truncateText(renderStepText(instId, step.check || ""), 8000)}
1662
+
1663
+ ---
1664
+
1665
+ 请基于上述信息,自主探索项目验证任务完成情况。基于你自己的探索结果判断,不要依赖任何外部提供的"实现总结"。
1666
+
1667
+ 检查完成后输出:
1668
+ - 通过:先说明通过原因,最后一行输出 \`<promise-check>true</promise-check>\`
1669
+ - 不通过:先说明失败原因,最后一行输出 \`<promise-check>false</promise-check>\`
1670
+
1671
+ 标签必须独占最后一行。`);
1672
+ return sections.join("\n\n");
1673
+ }
1674
+ /**
1675
+ * 多验证者投票的单票 prompt:共享段(用户需求/DO 任务/产出目录)+ 该票专属
1676
+ * 检查依据 + "你是 N 个验证者之一,只查自己视角"约束(设计 §8.4)。
1677
+ */
1678
+ function buildVotingCheckPrompt(instId, step, userTask, entry, index, count) {
1679
+ const sections = [];
1680
+ if (userTask)
1681
+ sections.push(`## 用户需求\n\n${truncateText(userTask, 4000)}`);
1682
+ sections.push(`## Do 阶段任务
1683
+
1684
+ **步骤**:${step.id}
1685
+ **任务描述**:${truncateText(renderStepText(instId, step.do), 8000)}
1686
+ **输入**:${truncateText(renderStepText(instId, step.input), 2000)}
1687
+ **预期输出**:${truncateText(renderStepText(instId, step.output), 2000)}
1688
+ **产出目录**:\`${getArtifactsRelDir(instId)}/\` — 检查依据中未写路径的文档文件名即指此目录下的文件`);
1689
+ sections.push(`## 你的检查依据(专属视角)
1690
+
1691
+ ${truncateText(renderStepText(instId, entry.check), 8000)}`);
1692
+ sections.push(`## 你是 ${count} 个验证者之一
1693
+
1694
+ - 你**只负责你自己的检查依据**(上方"检查依据"段),不要试图覆盖其他验证者的视角
1695
+ - 其他验证者正在并行检查其他方面,各有独立会话
1696
+ - 你的结论不受任何其他验证者影响,也不要等待或引用它们`);
1697
+ sections.push(`请基于上述信息,自主探索项目验证任务完成情况。基于你自己的探索结果判断,不要依赖任何外部提供的"实现总结"。
1698
+
1699
+ 检查完成后输出:
1700
+ - 通过:先说明通过原因,最后一行输出 \`<promise-check>true</promise-check>\`
1701
+ - 不通过:先说明失败原因,最后一行输出 \`<promise-check>false</promise-check>\`
1702
+
1703
+ 标签必须独占最后一行。`);
1704
+ return sections.join("\n\n---\n\n");
1705
+ }
1706
+ function buildSubWorkflowUserTask(instId, step, parentUserTask) {
1707
+ const parts = [];
1708
+ if (step.inputs && typeof step.inputs === "object" && !Array.isArray(step.inputs)) {
1709
+ for (const [key, value] of Object.entries(step.inputs)) {
1710
+ parts.push(`${key}: ${renderStepText(instId, String(value))}`);
1711
+ }
1712
+ }
1713
+ if (parentUserTask) {
1714
+ if (parts.length > 0)
1715
+ parts.push("");
1716
+ parts.push(`原始需求:${parentUserTask}`);
1717
+ }
1718
+ return parts.join("\n");
1719
+ }
1720
+ /**
1721
+ * Recursively resolve a sub-workflow entry point.
1722
+ * If the sub-workflow's first step is itself a sub-workflow, push intermediate states and recurse.
1723
+ * Returns { text, error? } where text is the do prompt for the deepest normal step.
1724
+ */
1725
+ function resolveSubWorkflowEntry(instId, subWorkflowName, parentUserTask, parentStep, maxDepth, retryContext, retryCount) {
1726
+ const depth = getStackDepth(instId);
1727
+ if (depth >= (maxDepth || MAX_NESTING_DEPTH)) {
1728
+ return { text: `嵌套深度超过限制(${depth}/${maxDepth || MAX_NESTING_DEPTH})。可能存在循环引用。`, error: true };
1729
+ }
1730
+ const subProblems = [];
1731
+ const subWorkflow = loadWorkflow(subWorkflowName, subProblems);
1732
+ if (!subWorkflow) {
1733
+ return {
1734
+ text: subProblems.length > 0
1735
+ ? `子工作流 "${subWorkflowName}" 定义无效:\n${subProblems.map((p) => `- ${p}`).join("\n")}`
1736
+ : `子工作流 "${subWorkflowName}" 未找到。`,
1737
+ error: true,
1738
+ };
1739
+ }
1740
+ const firstStep = subWorkflow.steps[0];
1741
+ if (!firstStep) {
1742
+ return { text: `子工作流 "${subWorkflowName}" 没有步骤。`, error: true };
1743
+ }
1744
+ const subUserTask = buildSubWorkflowUserTask(instId, parentStep, parentUserTask);
1745
+ if (isSubWorkflowStep(firstStep)) {
1746
+ // Push intermediate state and recurse
1747
+ const intermediateState = {
1748
+ active: true, workflow_name: subWorkflowName, current_step: firstStep.id,
1749
+ current_phase: "do", fail_count: 0, user_task: subUserTask, paused: false,
1750
+ };
1751
+ pushState(intermediateState, instId);
1752
+ const result = resolveSubWorkflowEntry(instId, firstStep.workflow, subUserTask, firstStep, maxDepth, retryContext, retryCount);
1753
+ if (result.error) {
1754
+ popState(instId); // undo the push on error
1755
+ }
1756
+ return result;
1757
+ }
1758
+ // Normal first step — write state and return do prompt
1759
+ writeState({
1760
+ active: true, workflow_name: subWorkflowName, current_step: firstStep.id,
1761
+ current_phase: "do", fail_count: 0, user_task: subUserTask, paused: false,
1762
+ }, instId);
1763
+ // If the sub-workflow's first step is manual, arm the marker for the driver
1764
+ if (subWorkflow.manual_step && subWorkflow.manual_step.includes(firstStep.id)) {
1765
+ writeManualStepMarker(instId);
1766
+ }
1767
+ else {
1768
+ clearManualStepMarker(instId);
1769
+ }
1770
+ recordStepStart(instId, firstStep.id, "do");
1771
+ logEvent(instId, "info", "step_start", { step: firstStep.id, phase: "do" });
1772
+ return { text: buildDoPrompt(instId, firstStep, subUserTask, retryContext, retryCount) };
1773
+ }
1774
+ // ─── State Stack (for sub-workflows, per instance) ──────────────────────────
1775
+ function getStackFile(instId) {
1776
+ return instPath(STACK_FILENAME, instId);
1777
+ }
1778
+ function pushState(state, instId) {
1779
+ try {
1780
+ const stackFile = getStackFile(instId);
1781
+ let stack = [];
1782
+ if (fs.existsSync(stackFile)) {
1783
+ try {
1784
+ const parsed = JSON.parse(stripBom(fs.readFileSync(stackFile, "utf-8")));
1785
+ if (Array.isArray(parsed))
1786
+ stack = parsed;
1787
+ else
1788
+ diag("[ralph-flow] Stack file is not an array, starting fresh");
1789
+ }
1790
+ catch (parseErr) {
1791
+ diag("[ralph-flow] Stack file corrupted, backing up and starting fresh:", parseErr.message);
1792
+ try {
1793
+ fs.renameSync(stackFile, stackFile + ".corrupted." + Date.now());
1794
+ }
1795
+ catch { }
1796
+ }
1797
+ }
1798
+ // 栈帧是父状态的快照,不含运行时所有权(session_id)。session_id 若入帧,
1799
+ // 子工作流完成/失败回父时会把「进入子工作流前」的旧 session 写回状态——
1800
+ // reset 门换会话(claimOwnership)后所有权被旧值覆盖,实例被已废弃的旧
1801
+ // 会话独占,新会话的空闲驱动对非属主实例静默,父工作流无人驱动(表现为
1802
+ // "子工作流完成了回不到父工作流":状态回父了但卡死不动)。
1803
+ const frame = { ...state };
1804
+ delete frame.session_id;
1805
+ stack.push(frame);
1806
+ atomicWriteJson(stackFile, stack);
1807
+ }
1808
+ catch (e) {
1809
+ diag("[ralph-flow] Error pushing state:", e.message);
1810
+ }
1811
+ }
1812
+ function popState(instId) {
1813
+ try {
1814
+ const stackFile = getStackFile(instId);
1815
+ if (!fs.existsSync(stackFile))
1816
+ return null;
1817
+ let stack;
1818
+ try {
1819
+ stack = JSON.parse(stripBom(fs.readFileSync(stackFile, "utf-8")));
1820
+ }
1821
+ catch (parseErr) {
1822
+ diag("[ralph-flow] Stack file corrupted, backing up:", parseErr.message);
1823
+ try {
1824
+ fs.renameSync(stackFile, stackFile + ".corrupted." + Date.now());
1825
+ }
1826
+ catch { }
1827
+ return STACK_CORRUPTED;
1828
+ }
1829
+ if (!Array.isArray(stack)) {
1830
+ diag("[ralph-flow] Stack file is not an array, backing up");
1831
+ try {
1832
+ fs.renameSync(stackFile, stackFile + ".corrupted." + Date.now());
1833
+ }
1834
+ catch { }
1835
+ return STACK_CORRUPTED;
1836
+ }
1837
+ if (stack.length === 0)
1838
+ return null;
1839
+ const parentState = stack.pop();
1840
+ // 防御:旧版本(修复前)写入的栈文件可能带 session_id,弹出时一并剥离,
1841
+ // 保证任何回父路径 writeState({...parentState}) 都不会覆盖当前所有权。
1842
+ delete parentState.session_id;
1843
+ atomicWriteJson(stackFile, stack);
1844
+ return parentState;
1845
+ }
1846
+ catch (e) {
1847
+ diag("[ralph-flow] Error popping state:", e.message);
1848
+ return STACK_CORRUPTED;
1849
+ }
1850
+ }
1851
+ function getStackDepth(instId) {
1852
+ try {
1853
+ const stackFile = getStackFile(instId);
1854
+ if (!fs.existsSync(stackFile))
1855
+ return 0;
1856
+ let stack;
1857
+ try {
1858
+ stack = JSON.parse(stripBom(fs.readFileSync(stackFile, "utf-8")));
1859
+ }
1860
+ catch {
1861
+ // 损坏时按最大深度对待:阻止继续嵌套进入子工作流(再 push 会把唯一
1862
+ // 的现场证据改名清掉),而不是装作深度为 0 放行。
1863
+ return MAX_NESTING_DEPTH;
1864
+ }
1865
+ return Array.isArray(stack) ? stack.length : MAX_NESTING_DEPTH;
1866
+ }
1867
+ catch {
1868
+ return 0;
1869
+ }
1870
+ }
1871
+ /** 弹出损坏栈帧后的统一处置:暂停 + 如实告知(备份文件名带回提示) */
1872
+ function pauseForCorruptedStack(instId, state, context) {
1873
+ writeState({ ...state, paused: true, pause_reason: "config_error", last_failure_reason: `子工作流状态栈损坏(${context})。` }, instId);
1874
+ logEvent(instId, "error", "state_stack_corrupted", { context });
1875
+ return {
1876
+ text: `## ⚠️ 无法安全完成:子工作流状态栈损坏\n\n本实例的子工作流状态栈文件损坏,无法确认是否存在父工作流——为避免误判「顶层完成」把实例连同剩余步骤一起销毁,已暂停并保留现场。\n\n- 备份保留在实例目录内(\`stack.json.corrupted.*\`),可人工抢救。\n- 若确认没有未完成的父工作流:运行 \`/ralphflow-cancel\` 结束;若可能有:修复后运行 \`/ralphflow-continue\`。`,
1877
+ paused: true,
1878
+ };
1879
+ }
1880
+ /** Read the whole ancestor-state stack without mutating it (index 0 = outermost parent). */
1881
+ function readStateStack(instId) {
1882
+ try {
1883
+ const stackFile = getStackFile(instId);
1884
+ if (!fs.existsSync(stackFile))
1885
+ return [];
1886
+ const parsed = JSON.parse(stripBom(fs.readFileSync(stackFile, "utf-8")));
1887
+ if (!Array.isArray(parsed))
1888
+ return [];
1889
+ return parsed.filter((s) => !!s && typeof s === "object" && typeof s.workflow_name === "string");
1890
+ }
1891
+ catch {
1892
+ return [];
1893
+ }
1894
+ }
1895
+ /**
1896
+ * Java-style field-level inheritance for the verifier config along the
1897
+ * sub-workflow chain: the current workflow's own adversarial_check wins for
1898
+ * every field that is present AND usable; each missing/unusable field falls
1899
+ * back to the nearest ancestor that defines it, then to the built-in
1900
+ * defaults in check.ts. A sub-workflow that only overrides `model` still
1901
+ * inherits its parent's `timeout_ms`, and an unresolvable `model` (bare
1902
+ * name, half-specified object) does NOT shadow the parent's valid one.
1903
+ */
1904
+ function getEffectiveAdversarialCheck(instId, workflow) {
1905
+ // Chain ordered nearest-first: current workflow, then parents innermost → outermost.
1906
+ const chain = [];
1907
+ if (workflow.adversarial_check)
1908
+ chain.push(workflow.adversarial_check);
1909
+ const stack = readStateStack(instId);
1910
+ for (let i = stack.length - 1; i >= 0; i--) {
1911
+ const wf = loadWorkflow(stack[i].workflow_name);
1912
+ if (wf?.adversarial_check)
1913
+ chain.push(wf.adversarial_check);
1914
+ }
1915
+ if (chain.length === 0)
1916
+ return undefined;
1917
+ const pick = (valid) => {
1918
+ for (const cfg of chain) {
1919
+ const v = valid(cfg);
1920
+ if (v !== undefined)
1921
+ return v;
1922
+ }
1923
+ return undefined;
1924
+ };
1925
+ const model = pick((c) => (resolveCheckModel(c.model) ? c.model : undefined));
1926
+ const agent = pick((c) => (typeof c.agent === "string" && c.agent.trim() ? c.agent : undefined));
1927
+ const system_prompt = pick((c) => (typeof c.system_prompt === "string" && c.system_prompt.trim() ? c.system_prompt : undefined));
1928
+ const timeout_ms = pick((c) => (typeof c.timeout_ms === "number" && c.timeout_ms > 0 ? c.timeout_ms : undefined));
1929
+ if (model === undefined && agent === undefined && system_prompt === undefined && timeout_ms === undefined)
1930
+ return undefined;
1931
+ return { model, agent, system_prompt, timeout_ms };
1932
+ }
1933
+ // ─── Log Helpers ────────────────────────────────────────────────────────────
1934
+ function getLogDir(instId) {
1935
+ // Fall back to the global logs dir after the instance dir was destroyed
1936
+ // (e.g. a cancel during a check) — never resurrect a deleted dir.
1937
+ if (!instId || !fs.existsSync(getInstanceDir(instId)))
1938
+ return path.join(getRalphFlowDir(), "logs");
1939
+ return path.join(getInstanceDir(instId), "logs");
1940
+ }
1941
+ function ensureLogDir(instId) {
1942
+ const logDir = getLogDir(instId);
1943
+ if (!fs.existsSync(logDir))
1944
+ fs.mkdirSync(logDir, { recursive: true });
1945
+ }
1946
+ const MAX_LOG_SIZE_BYTES = 10 * 1024 * 1024; // 10 MB
1947
+ const MAX_LOG_ROTATIONS = 3;
1948
+ function rotateLogIfNeeded(instId) {
1949
+ try {
1950
+ const logFile = path.join(getLogDir(instId), "execution.log");
1951
+ if (!fs.existsSync(logFile))
1952
+ return;
1953
+ const stats = fs.statSync(logFile);
1954
+ if (stats.size < MAX_LOG_SIZE_BYTES)
1955
+ return;
1956
+ // Rotate: .3 → delete, .2 → .3, .1 → .2, current → .1
1957
+ for (let i = MAX_LOG_ROTATIONS; i >= 1; i--) {
1958
+ const older = `${logFile}.${i}`;
1959
+ if (i === MAX_LOG_ROTATIONS) {
1960
+ if (fs.existsSync(older))
1961
+ fs.unlinkSync(older);
1962
+ }
1963
+ else {
1964
+ if (fs.existsSync(older))
1965
+ fs.renameSync(older, `${logFile}.${i + 1}`);
1966
+ }
1967
+ }
1968
+ fs.renameSync(logFile, `${logFile}.1`);
1969
+ }
1970
+ catch (e) {
1971
+ diag("[ralph-flow] Log rotation failed:", e.message);
1972
+ }
1973
+ }
1974
+ function logEvent(instId, level, event, extra) {
1975
+ try {
1976
+ ensureLogDir(instId);
1977
+ rotateLogIfNeeded(instId);
1978
+ const entry = { ts: new Date().toISOString(), level, event, ...extra };
1979
+ fs.appendFileSync(path.join(getLogDir(instId), "execution.log"), JSON.stringify(entry) + "\n");
1980
+ }
1981
+ catch (e) {
1982
+ diag(`[ralph-flow] Log failed (${event}):`, e.message);
1983
+ }
1984
+ }
1985
+ /**
1986
+ * 从执行日志提取全部 UI 事件帧(按发生顺序)。用途:continue 接管中断实例时
1987
+ * 把历史帧重放进新会话——新会话的 chat 里没有任何本实例的卡片(帧都发到了
1988
+ * 旧会话),不重放的话用户面对的是文字墙而不是可导航的档案。
1989
+ * 保证首条 run-start 帧始终在列(client 折叠器只有它才能建节点)。
1990
+ */
1991
+ function readUiEventFrames(instId, max = 200) {
1992
+ try {
1993
+ const logFile = path.join(getLogDir(instId), "execution.log");
1994
+ if (!fs.existsSync(logFile))
1995
+ return [];
1996
+ const lines = fs.readFileSync(logFile, "utf-8").split("\n").filter(Boolean);
1997
+ const frames = [];
1998
+ for (const line of lines) {
1999
+ try {
2000
+ const e = JSON.parse(line);
2001
+ if (typeof e.event !== "string" || !e.event.startsWith("ui_event_tool-ralphflow/"))
2002
+ continue;
2003
+ const data = { ...e };
2004
+ delete data.ts;
2005
+ delete data.level;
2006
+ delete data.event;
2007
+ frames.push({ type: String(e.event).slice("ui_event_".length), data });
2008
+ }
2009
+ catch { }
2010
+ }
2011
+ if (frames.length <= max)
2012
+ return frames;
2013
+ // 截断保底:run-start(建卡必需)+ 最近 max-1 条
2014
+ const tail = frames.slice(-(max - 1));
2015
+ if (tail.some((f) => f.type === "tool-ralphflow/run-start"))
2016
+ return tail;
2017
+ const firstStart = frames.find((f) => f.type === "tool-ralphflow/run-start");
2018
+ return firstStart ? [firstStart, ...tail] : tail;
2019
+ }
2020
+ catch {
2021
+ return [];
2022
+ }
2023
+ }
2024
+ // ─── HTTP 状态通道数据(/ralphflow/instances 的数据源)────────────────────
2025
+ /**
2026
+ * 全部活跃实例的富状态快照(供 HTTP 路由 / 轮询 UI 消费)。字段刻意对齐
2027
+ * client 端 RunSummary/折叠器所需:steps/current/voters/verdicts/gate/
2028
+ * lastCheck/stopReason/elapsed。不再走 session.append 后这是唯一实时面。
2029
+ */
2030
+ function snapshotAllInstances() {
2031
+ const out = [];
2032
+ const instances = listInstances();
2033
+ for (const inst of instances) {
2034
+ const st = inst.state;
2035
+ const detail = {
2036
+ runId: inst.id,
2037
+ workflow: st.workflow_name,
2038
+ task: st.user_task,
2039
+ current: { step: st.current_step, phase: st.current_phase, failCount: st.fail_count ?? 0 },
2040
+ owner: st.session_id ?? null,
2041
+ paused: !!st.paused,
2042
+ pauseReason: st.pause_reason ?? undefined,
2043
+ lastFailureReason: st.last_failure_reason ?? undefined,
2044
+ startedAt: inst.lastActivity ? inst.lastActivity.toISOString() : undefined,
2045
+ gate: markerExists(MANUAL_GATE_MARKER, inst.id) ? {
2046
+ step: st.current_step,
2047
+ title: st.current_step,
2048
+ reason: st.paused ? (st.pause_reason ?? "") : "审查门",
2049
+ taskExcerpt: undefined,
2050
+ } : undefined,
2051
+ };
2052
+ // 工作流步骤全列表(MiniPipeline / 步骤条的数据源)
2053
+ try {
2054
+ const wf = loadWorkflow(st.workflow_name);
2055
+ if (wf) {
2056
+ detail.steps = wf.steps.map((s) => ({ id: s.id, desc: s.desc }));
2057
+ const gstep = getStep(wf, st.current_step);
2058
+ if (gstep && !isSubWorkflowStep(gstep)) {
2059
+ detail.gate = markerExists(MANUAL_GATE_MARKER, inst.id)
2060
+ ? { step: gstep.id, title: gstep.desc, reason: st.pause_reason ?? "", taskExcerpt: (gstep.do || "").trim().slice(0, 300) }
2061
+ : detail.gate;
2062
+ }
2063
+ }
2064
+ }
2065
+ catch { }
2066
+ // 验证者活体 + 票(check 相位)
2067
+ if (st.current_phase === "check" && !st.paused) {
2068
+ try {
2069
+ const progress = readVotingProgressFile(inst.id);
2070
+ if (progress) {
2071
+ detail.voters = progress.entries.length;
2072
+ detail.voterProgress = progress.entries.map((e) => ({
2073
+ voter: e.index + 1,
2074
+ status: e.status,
2075
+ model: e.model ?? null,
2076
+ check: (e.check || "").slice(0, 80),
2077
+ startedAt: e.startedAt,
2078
+ reason: e.reason ? e.reason.slice(0, 200) : undefined,
2079
+ }));
2080
+ }
2081
+ else {
2082
+ const wf2 = loadWorkflow(st.workflow_name);
2083
+ const step2 = wf2 ? getStep(wf2, st.current_step) : null;
2084
+ detail.voters = Array.isArray(step2?.check_voting)
2085
+ ? step2.check_voting.length
2086
+ : 1;
2087
+ }
2088
+ }
2089
+ catch { }
2090
+ }
2091
+ // 超时终点感:本轮 CHECK 的超时上限与起点(UI 画剩余时间进度条)
2092
+ if (st.current_phase === "check" && !st.paused) {
2093
+ try {
2094
+ const wf = loadWorkflow(st.workflow_name);
2095
+ const step = wf ? getStep(wf, st.current_step) : null;
2096
+ if (wf && step && !isSubWorkflowStep(step)) {
2097
+ const s = step;
2098
+ let timeoutMs;
2099
+ if (Array.isArray(s.check_voting) && s.check_voting.length > 0) {
2100
+ timeoutMs = s.check_voting[0]?.timeout_ms ?? getEffectiveAdversarialCheck(inst.id, wf)?.timeout_ms ?? DEFAULT_ADVERSARIAL_TIMEOUT_MS;
2101
+ }
2102
+ else {
2103
+ timeoutMs = getEffectiveAdversarialCheck(inst.id, wf)?.timeout_ms ?? DEFAULT_ADVERSARIAL_TIMEOUT_MS;
2104
+ }
2105
+ if (typeof timeoutMs === "number" && timeoutMs > 0)
2106
+ detail.timeoutMs = timeoutMs;
2107
+ const checkStart = stepStartTime(inst.id, st.current_step, "check");
2108
+ if (checkStart)
2109
+ detail.checkStartedAt = Date.parse(checkStart);
2110
+ else if (inst.lastActivity)
2111
+ detail.checkStartedAt = inst.lastActivity.getTime();
2112
+ }
2113
+ }
2114
+ catch { }
2115
+ }
2116
+ out.push(detail);
2117
+ }
2118
+ return out;
2119
+ }
2120
+ function readVotingProgressFile(instId) {
2121
+ try {
2122
+ const file = path.join(getInstanceDir(instId), ".check-voting-progress.json");
2123
+ if (!fs.existsSync(file))
2124
+ return null;
2125
+ const raw = JSON.parse(fs.readFileSync(file, "utf-8"));
2126
+ if (!raw || !Array.isArray(raw.entries))
2127
+ return null;
2128
+ return {
2129
+ entries: raw.entries
2130
+ .filter((e) => e && typeof e === "object")
2131
+ .map((e) => ({
2132
+ index: typeof e.index === "number" ? e.index : 0,
2133
+ check: typeof e.check === "string" ? e.check : "",
2134
+ model: typeof e.model === "string" ? e.model : null,
2135
+ status: typeof e.status === "string" ? e.status : "pending",
2136
+ // 票飞行起点(running 时写入)与判定理由——UI「该票已跑 Xs」与详情面板
2137
+ ...(typeof e.startedAt === "number" && e.startedAt > 0 ? { startedAt: e.startedAt } : {}),
2138
+ ...(typeof e.reason === "string" && e.reason ? { reason: e.reason } : {}),
2139
+ })),
2140
+ };
2141
+ }
2142
+ catch {
2143
+ return null;
2144
+ }
2145
+ }
2146
+ /** 归档历史索引(history.jsonl 全量读) */
2147
+ function readHistory(limit = 100) {
2148
+ try {
2149
+ const file = path.join(getRalphFlowDir(), "history.jsonl");
2150
+ if (!fs.existsSync(file))
2151
+ return [];
2152
+ const lines = fs.readFileSync(file, "utf-8").split("\n").filter(Boolean);
2153
+ const out = [];
2154
+ for (const line of lines.slice(-limit)) {
2155
+ try {
2156
+ out.push(JSON.parse(line));
2157
+ }
2158
+ catch { }
2159
+ }
2160
+ return out;
2161
+ }
2162
+ catch {
2163
+ return [];
2164
+ }
2165
+ }
2166
+ /**
2167
+ * 实例销毁后的终态帧审计落点:追加到归档副本 reports/<instId>-execution.log。
2168
+ * 实例目录被 destroyInstance 删除后 logEvent 会兜底写全局 logs——终态帧会
2169
+ * 从该实例的归档记录里消失。这里显式补写归档副本,保证报告+终态事件审计
2170
+ * 完整(与 destroyInstance 拷贝的日志副本同文件,实现拼接续写)。
2171
+ */
2172
+ function appendArchivedUiEvent(instId, type, data) {
2173
+ try {
2174
+ const copy = path.join(getReportsDir(), `${instId}-execution.log`);
2175
+ if (!fs.existsSync(copy))
2176
+ return;
2177
+ const entry = { ts: new Date().toISOString(), level: "info", event: `ui_event_${type}`, ...data };
2178
+ fs.appendFileSync(copy, JSON.stringify(entry) + "\n");
2179
+ }
2180
+ catch { }
2181
+ }
2182
+ // ─── Step Records Persistence (per instance) ────────────────────────────────
2183
+ const STEP_RECORDS_FILENAME = "step-records.json";
2184
+ function getStepRecordsFile(instId) {
2185
+ return path.join(getLogDir(instId), STEP_RECORDS_FILENAME);
2186
+ }
2187
+ function loadStepRecords(instId) {
2188
+ try {
2189
+ const file = getStepRecordsFile(instId);
2190
+ if (fs.existsSync(file)) {
2191
+ try {
2192
+ const parsed = JSON.parse(stripBom(fs.readFileSync(file, "utf-8")));
2193
+ if (Array.isArray(parsed))
2194
+ return parsed;
2195
+ diag("[ralph-flow] Step records file is not an array, resetting");
2196
+ }
2197
+ catch (parseErr) {
2198
+ diag("[ralph-flow] Step records file corrupted, backing up:", parseErr.message);
2199
+ try {
2200
+ fs.renameSync(file, file + ".corrupted." + Date.now());
2201
+ }
2202
+ catch { }
2203
+ }
2204
+ }
2205
+ }
2206
+ catch (e) {
2207
+ diag("[ralph-flow] Error loading step records:", e.message);
2208
+ }
2209
+ return [];
2210
+ }
2211
+ function saveStepRecords(instId, records) {
2212
+ try {
2213
+ ensureLogDir(instId);
2214
+ atomicWriteJson(getStepRecordsFile(instId), records);
2215
+ }
2216
+ catch (e) {
2217
+ diag("[ralph-flow] Error saving step records:", e.message);
2218
+ }
2219
+ }
2220
+ // ─── Report Generation ──────────────────────────────────────────────────────
2221
+ function formatDuration(startTime, endTime) {
2222
+ const durationMs = Math.max(0, new Date(endTime).getTime() - new Date(startTime).getTime());
2223
+ const minutes = Math.floor(durationMs / 60000);
2224
+ const seconds = Math.floor((durationMs % 60000) / 1000);
2225
+ return minutes > 0 ? `${minutes}m${seconds}s` : `${seconds}s`;
2226
+ }
2227
+ function buildReportText(workflowName, status, stepRecords) {
2228
+ const totalFailures = stepRecords.reduce((sum, s) => sum + (s.failCount || 0), 0);
2229
+ const startTime = stepRecords.length > 0 ? stepRecords[0].startTime : new Date().toISOString();
2230
+ const endTime = stepRecords.length > 0 ? stepRecords[stepRecords.length - 1].endTime || new Date().toISOString() : new Date().toISOString();
2231
+ const statusCn = { completed: "已完成", cancelled: "已取消", paused: "已暂停" };
2232
+ const lines = [
2233
+ "# 工作流执行报告", "",
2234
+ "## 执行摘要", "",
2235
+ `- **工作流**: ${workflowName}`,
2236
+ `- **状态**: ${statusCn[status] || status}`,
2237
+ `- **总步骤数**: ${stepRecords.length}`,
2238
+ `- **失败次数**: ${totalFailures}`,
2239
+ `- **总耗时**: ${formatDuration(startTime, endTime)}`,
2240
+ "", "## 步骤执行情况", "",
2241
+ ];
2242
+ for (let i = 0; i < stepRecords.length; i++) {
2243
+ const step = stepRecords[i];
2244
+ const icon = step.status === "passed" ? "✓" : "✗";
2245
+ lines.push(`### ${i + 1}. ${step.stepId} (${step.phase}) ${icon}`);
2246
+ lines.push(`- 状态:${step.status === "passed" ? "通过" : "失败"}`);
2247
+ if (step.failCount > 0)
2248
+ lines.push(`- 失败次数:${step.failCount}`);
2249
+ if (step.reason)
2250
+ lines.push(`- ${step.status === "passed" ? "通过原因" : "失败原因"}:${step.reason}`);
2251
+ if (step.startTime && step.endTime)
2252
+ lines.push(`- 耗时:${formatDuration(step.startTime, step.endTime)}`);
2253
+ lines.push("");
2254
+ }
2255
+ return lines.join("\n");
2256
+ }
2257
+ // ─── Check Result Parsing ───────────────────────────────────────────────────
2258
+ /**
2259
+ * Match the check verdict tag: last line first, then a small tail window.
2260
+ * 验证者偶尔在标签后补尾随文字/空行——只认物理最后一行会把实际通过的判定
2261
+ * 误读为失败(白烧一整轮 DO 返工)。与 done-detect 的尾部兜底策略对齐,
2262
+ * 窗口限制在末尾 4 行内避免正文中间的标签被误匹配。
2263
+ */
2264
+ function matchCheckTag(responseText) {
2265
+ const lines = responseText.trim().split("\n");
2266
+ const tagRe = /<promise-check>\s*(true|false)\s*<\/promise-check>/i;
2267
+ const windowStart = Math.max(0, lines.length - 4);
2268
+ for (let i = lines.length - 1; i >= windowStart; i--) {
2269
+ const m = lines[i].trim().match(tagRe);
2270
+ if (m)
2271
+ return m;
2272
+ }
2273
+ return null;
2274
+ }
2275
+ function parseCheckResult(responseText) {
2276
+ const match = matchCheckTag(responseText);
2277
+ if (!match)
2278
+ return false;
2279
+ return match[1].toLowerCase() === "true";
2280
+ }
2281
+ function getAdversarialCheckReason(responseText) {
2282
+ const lines = responseText.trim().split("\n");
2283
+ const tagRe = /<promise-check>\s*(true|false)\s*<\/promise-check>/i;
2284
+ // 标签所在行(含)之后的内容不算理由;找不到标签时沿用旧语义去掉末行
2285
+ let cut = lines.length - 1;
2286
+ for (let i = lines.length - 1; i >= Math.max(0, lines.length - 4); i--) {
2287
+ if (tagRe.test(lines[i])) {
2288
+ cut = i;
2289
+ break;
2290
+ }
2291
+ }
2292
+ const reason = lines.slice(0, cut).join("\n").trim();
2293
+ return reason.length > 20000 ? reason.substring(0, 20000) + "..." : reason;
2294
+ }
2295
+ // ─── Workflow Advancement Logic (shared by done handler) ────────────────────
2296
+ function handleCheckPassed(instId, state, workflow, step, checkResult, skipped = false) {
2297
+ // Note: manual steps no longer pause after the check — the manual review gate
2298
+ // now sits BEFORE the check (the driver stops the session when the DO phase of
2299
+ // a manual step completes; the user's ralphflow_continue call is the approval
2300
+ // that starts the check). Once the check passes, the workflow advances.
2301
+ // skipped=true 表示该步骤未配置独立验证(no-check 直通)——标题必须如实
2302
+ // 标注「跳过对抗性验证」,不能谎称跑过独立 CHECK。
2303
+ const passHeader = skipped ? "## 步骤已通过(跳过对抗性验证)" : "## 检查结果:通过 ✓";
2304
+ if (step.on_pass === "done") {
2305
+ const parentState = popState(instId);
2306
+ if (parentState === STACK_CORRUPTED) {
2307
+ return pauseForCorruptedStack(instId, { ...state, current_phase: "check" }, `${state.workflow_name}/${state.current_step} 完成时`);
2308
+ }
2309
+ if (parentState) {
2310
+ const parentWorkflow = loadWorkflow(parentState.workflow_name);
2311
+ if (parentWorkflow) {
2312
+ const parentStep = getStep(parentWorkflow, parentState.current_step);
2313
+ if (parentStep) {
2314
+ // Sub-workflow completed — advance to parent step's on_pass target
2315
+ const grandparentResult = handleCheckPassed(instId, { ...parentState, current_phase: "do", fail_count: 0, last_failure_reason: undefined, paused: false, pause_reason: undefined }, parentWorkflow, parentStep, { reason: `子工作流 "${state.workflow_name}" 已完成。` });
2316
+ // Only record parent step's check as passed if transition succeeded and
2317
+ // the instance still exists (a completed workflow already destroyed it)
2318
+ if (!grandparentResult.paused && !grandparentResult.completed) {
2319
+ addStepRecord(instId, parentState.current_step, "check", "passed", parentState.fail_count || 0, `子工作流 "${state.workflow_name}" 已完成。`, parentState.workflow_name);
2320
+ }
2321
+ logEvent(instId, "info", "sub_workflow_end", { workflow: state.workflow_name, parent_workflow: parentState.workflow_name, parent_step: parentState.current_step });
2322
+ return {
2323
+ text: `${passHeader}\n\n${checkResult.reason || "检查通过。"}\n\n---\n\n## 子工作流 "${state.workflow_name}" 已完成!\n\n---\n\n${grandparentResult.text}`,
2324
+ paused: grandparentResult.paused,
2325
+ completed: grandparentResult.completed,
2326
+ // Propagate a sub-workflow entry from the recursive advance (e.g.
2327
+ // this sub-workflow's completion routed the parent into ANOTHER
2328
+ // composite step) so the driver's reset gate sees it.
2329
+ enteredCompositeStepId: grandparentResult.enteredCompositeStepId,
2330
+ };
2331
+ }
2332
+ }
2333
+ // Parent workflow not found — push parent state back and pause so user can fix and resume
2334
+ pushState({ ...parentState, paused: true, pause_reason: "config_error", last_failure_reason: `父工作流 "${parentState.workflow_name}" 加载失败。` }, instId);
2335
+ writeState({ ...parentState, paused: true, pause_reason: "config_error", last_failure_reason: `父工作流 "${parentState.workflow_name}" 加载失败。` }, instId);
2336
+ logEvent(instId, "warn", "parent_workflow_not_found", { workflow: state.workflow_name, parent_workflow: parentState.workflow_name });
2337
+ return {
2338
+ text: `${passHeader}\n\n${checkResult.reason || "检查通过。"}\n\n---\n\n子工作流 "${state.workflow_name}" 已完成,但父工作流 "${parentState.workflow_name}" 加载失败。工作流已暂停 — 请修复工作流 YAML 后调用 \`/ralphflow-continue\` 恢复。`,
2339
+ paused: true,
2340
+ };
2341
+ }
2342
+ // No parent — this is the top-level workflow, complete it.
2343
+ // Archive the report and destroy the instance directory.
2344
+ const reportPath = destroyInstance(instId, "completed");
2345
+ if (!reportPath) {
2346
+ // 报告归档失败时 destroyInstance 已拒绝销毁:实例连同 step-records/
2347
+ // execution.log 完整保留。置为专用 archive_failed 暂停(不是 check_error
2348
+ // ——那会让 continue 重跑一整轮验证白烧 token),continue 只重试归档。
2349
+ writeState({ ...state, paused: true, pause_reason: "archive_failed", last_failure_reason: "最终报告归档失败(磁盘满/权限不足?)。" }, instId);
2350
+ logEvent(instId, "error", "complete_archive_failed", { workflow: state.workflow_name });
2351
+ return {
2352
+ text: `${passHeader}\n\n---\n\n## ⚠️ 工作流已完成,但报告归档失败\n\n所有步骤均已通过,但最终报告写入失败(磁盘满或权限不足)。实例与执行记录已完整保留,本次不视为完成。\n\n👉 排查磁盘/权限后运行 \`/ralphflow-continue\` 重试归档(不会重新验证);或 \`/ralphflow-cancel\` 放弃归档直接结束。`,
2353
+ paused: true,
2354
+ };
2355
+ }
2356
+ logEvent(instId, "info", "workflow_end", { workflow: state.workflow_name });
2357
+ return {
2358
+ text: `${passHeader}\n\n${checkResult.reason || "检查通过。"}\n\n---\n\n## 🎉 工作流完成!\n\n所有步骤已验证通过,无需再操作。${reportPath ? `\n\n执行报告:${path.relative(projectDir, reportPath)}` : ""}`,
2359
+ completed: true,
2360
+ };
2361
+ }
2362
+ const nextStep = getStep(workflow, step.on_pass);
2363
+ if (!nextStep) {
2364
+ logEvent(instId, "error", "next_step_not_found", { step: state.current_step, on_pass: step.on_pass });
2365
+ writeState({ ...state, paused: true, pause_reason: "config_error", last_failure_reason: `下一步 "${step.on_pass}" 在工作流定义中未找到。` }, instId);
2366
+ return { text: `${passHeader}\n\n下一步 "${step.on_pass}" 在工作流定义中未找到。\n\n## 工作流已暂停\n\n工作流配置错误。请修复工作流定义,然后调用 \`/ralphflow-continue\` 恢复。`, paused: true };
2367
+ }
2368
+ if (isSubWorkflowStep(nextStep)) {
2369
+ recordStepStart(instId, nextStep.id, "do");
2370
+ logEvent(instId, "info", "step_start", { step: nextStep.id, phase: "do" });
2371
+ // Write parent's next step state before entering sub-workflow.
2372
+ // This ensures the state file reflects the correct parent step after sub-workflow completes
2373
+ const nextState = { ...state, current_step: nextStep.id, current_phase: "do", fail_count: 0, last_failure_reason: undefined, paused: false, pause_reason: undefined };
2374
+ writeState(nextState, instId);
2375
+ pushState({ ...state, current_step: nextStep.id, current_phase: "do", fail_count: 0, paused: false, pause_reason: undefined }, instId);
2376
+ const subResult = resolveSubWorkflowEntry(instId, nextStep.workflow, state.user_task, nextStep);
2377
+ if (subResult.error) {
2378
+ popState(instId);
2379
+ writeState({ ...state, paused: true, pause_reason: "config_error", last_failure_reason: subResult.text }, instId);
2380
+ return { text: subResult.text, paused: true };
2381
+ }
2382
+ return {
2383
+ text: `${passHeader}\n\n${checkResult.reason || "检查通过。"}\n\n---\n\n## 进入子工作流:${nextStep.id}\n\n---\n\n${subResult.text}`,
2384
+ enteredCompositeStepId: nextStep.id,
2385
+ };
2386
+ }
2387
+ const nextState = { ...state, current_step: nextStep.id, current_phase: "do", fail_count: 0, last_failure_reason: undefined, paused: false, pause_reason: undefined };
2388
+ writeState(nextState, instId);
2389
+ recordStepStart(instId, nextStep.id, "do");
2390
+ logEvent(instId, "info", "step_start", { step: nextStep.id, phase: "do" });
2391
+ return {
2392
+ text: `${passHeader}\n\n${checkResult.reason || "检查通过。"}\n\n---\n\n下一步:**${nextStep.id}** - ${nextStep.desc}\n\n---\n\n${buildDoPrompt(instId, nextStep, state.user_task)}`,
2393
+ };
2394
+ }
2395
+ function handleCheckFailed(instId, state, workflow, step, checkResult) {
2396
+ const newFailCount = state.fail_count + 1;
2397
+ logEvent(instId, "warn", "fail_count_increment", { step: state.current_step, fail_count: newFailCount });
2398
+ if (newFailCount >= step.max_fail_count) {
2399
+ const parentState = popState(instId);
2400
+ if (parentState === STACK_CORRUPTED) {
2401
+ return pauseForCorruptedStack(instId, { ...state, fail_count: newFailCount, current_phase: "check" }, `${state.workflow_name}/${state.current_step} 失败达上限时`);
2402
+ }
2403
+ if (parentState) {
2404
+ const parentFailCount = parentState.fail_count + 1;
2405
+ // Check if parent step's max_fail_count is exceeded
2406
+ const parentWorkflow = loadWorkflow(parentState.workflow_name);
2407
+ const parentStep = parentWorkflow ? getStep(parentWorkflow, parentState.current_step) : null;
2408
+ if (parentStep && parentFailCount >= parentStep.max_fail_count) {
2409
+ // Parent step also exceeded max failures — pause parent workflow
2410
+ // Push parent state back to stack so resume/cancel can restore nesting
2411
+ pushState({ ...parentState, current_phase: "do", fail_count: parentFailCount, paused: true, pause_reason: "max_failures", last_failure_reason: checkResult.reason }, instId);
2412
+ writeState({ ...parentState, current_phase: "do", fail_count: parentFailCount, paused: true, pause_reason: "max_failures", last_failure_reason: checkResult.reason }, instId);
2413
+ logEvent(instId, "warn", "workflow_paused", { workflow: parentState.workflow_name, step: parentState.current_step, fail_count: parentFailCount });
2414
+ return {
2415
+ text: `## 检查结果:失败 ✗ (${newFailCount}/${step.max_fail_count})\n\n${checkResult.reason || "检查失败。"}\n\n---\n\n## 工作流已暂停\n\n子工作流失败且父步骤最大失败次数 (${parentFailCount}/${parentStep.max_fail_count}) 已达。请修复问题,然后调用 \`/ralphflow-continue\` 恢复。`,
2416
+ paused: true,
2417
+ };
2418
+ }
2419
+ // Parent step not at max — follow parent's on_fail
2420
+ if (!parentWorkflow || !parentStep) {
2421
+ // Push parent state back so resume can restore the stack
2422
+ pushState({ ...parentState, fail_count: parentFailCount, paused: true, pause_reason: "config_error", last_failure_reason: `父工作流 "${parentState.workflow_name}" 或步骤 "${parentState.current_step}" 未找到。` }, instId);
2423
+ writeState({ ...parentState, fail_count: parentFailCount, paused: true, pause_reason: "config_error", last_failure_reason: `父工作流 "${parentState.workflow_name}" 或步骤 "${parentState.current_step}" 未找到。` }, instId);
2424
+ logEvent(instId, "error", "parent_workflow_or_step_not_found", { workflow: parentState.workflow_name, step: parentState.current_step });
2425
+ return {
2426
+ text: `## 检查结果:失败 ✗ (${newFailCount}/${step.max_fail_count})\n\n${checkResult.reason || "检查失败。"}\n\n---\n\n父工作流或步骤未找到。工作流已暂停。`,
2427
+ paused: true,
2428
+ };
2429
+ }
2430
+ const failStep = getStep(parentWorkflow, parentStep.on_fail);
2431
+ if (failStep) {
2432
+ if (isSubWorkflowStep(failStep)) {
2433
+ recordStepStart(instId, failStep.id, "do");
2434
+ logEvent(instId, "info", "step_start", { step: failStep.id, phase: "do" });
2435
+ pushState({ ...parentState, current_step: failStep.id, current_phase: "do", fail_count: parentFailCount, last_failure_reason: checkResult.reason }, instId);
2436
+ const subResult = resolveSubWorkflowEntry(instId, failStep.workflow, parentState.user_task, failStep, MAX_NESTING_DEPTH, checkResult.reason, parentFailCount);
2437
+ if (subResult.error) {
2438
+ popState(instId);
2439
+ writeState({ ...parentState, fail_count: parentFailCount, paused: true, pause_reason: "config_error", last_failure_reason: subResult.text }, instId);
2440
+ return { text: subResult.text, paused: true };
2441
+ }
2442
+ return {
2443
+ text: `## 检查结果:失败 ✗ (${newFailCount}/${step.max_fail_count})\n\n${checkResult.reason || "检查失败。"}\n\n---\n\n子工作流失败。使用父步骤重试:**${failStep.id}**\n\n---\n\n${subResult.text}`,
2444
+ enteredCompositeStepId: failStep.id,
2445
+ };
2446
+ }
2447
+ const retryState = { ...parentState, current_step: failStep.id, current_phase: "do", fail_count: parentFailCount, last_failure_reason: checkResult.reason };
2448
+ writeState(retryState, instId);
2449
+ recordStepStart(instId, failStep.id, "do");
2450
+ logEvent(instId, "info", "step_start", { step: failStep.id, phase: "do" });
2451
+ return {
2452
+ text: `## 检查结果:失败 ✗ (${newFailCount}/${step.max_fail_count})\n\n${checkResult.reason || "检查失败。"}\n\n---\n\n子工作流失败。使用父步骤重试:**${failStep.id}** - ${failStep.desc}\n\n---\n\n${buildDoPrompt(instId, failStep, parentState.user_task, checkResult.reason, parentFailCount)}`,
2453
+ };
2454
+ }
2455
+ // on_fail step not found — pause, but push parent state back so resume can restore stack
2456
+ pushState({ ...parentState, fail_count: parentFailCount, paused: true, pause_reason: "config_error", last_failure_reason: `父步骤 on_fail "${parentStep.on_fail}" 未找到。` }, instId);
2457
+ writeState({ ...parentState, fail_count: parentFailCount, paused: true, pause_reason: "config_error", last_failure_reason: `父步骤 on_fail "${parentStep.on_fail}" 未找到。` }, instId);
2458
+ return {
2459
+ text: `## 检查结果:失败 ✗ (${newFailCount}/${step.max_fail_count})\n\n${checkResult.reason || "检查失败。"}\n\n---\n\n父步骤 on_fail "${parentStep.on_fail}" 未找到。工作流已暂停。`,
2460
+ paused: true,
2461
+ };
2462
+ }
2463
+ clearManualStepMarker(instId);
2464
+ const pausedState = { ...state, fail_count: newFailCount, paused: true, pause_reason: "max_failures", last_failure_reason: checkResult.reason };
2465
+ writeState(pausedState, instId);
2466
+ logEvent(instId, "warn", "workflow_paused", { workflow: state.workflow_name, step: state.current_step, fail_count: newFailCount });
2467
+ return {
2468
+ text: `## 检查结果:失败 ✗ (${newFailCount}/${step.max_fail_count})\n\n${checkResult.reason || "检查失败。"}\n\n---\n\n## ⏸ 工作流已暂停 · 🙋 轮到你了\n\n步骤 \`${state.current_step}\` 连续失败已达上限(${newFailCount}/${step.max_fail_count}),停下等你介入:\n\n- 🔧 看上面的失败原因,动手修一修,然后运行 \`/ralphflow-continue\` 重试(失败计数会清零)\n- 🗑️ 或运行 \`/ralphflow-cancel\` 放弃\n\n已完成的工作都保留,模型不会自动继续。`,
2469
+ paused: true,
2470
+ };
2471
+ }
2472
+ const failStep = getStep(workflow, step.on_fail);
2473
+ if (!failStep) {
2474
+ const pausedState = { ...state, fail_count: newFailCount, paused: true, pause_reason: "config_error", last_failure_reason: `失败步骤 "${step.on_fail}" 在工作流定义中未找到。` };
2475
+ writeState(pausedState, instId);
2476
+ logEvent(instId, "error", "fail_step_not_found", { step: state.current_step, on_fail: step.on_fail });
2477
+ return {
2478
+ text: `## 检查结果:失败 ✗ (${newFailCount}/${step.max_fail_count})\n\n失败步骤 "${step.on_fail}" 在工作流定义中未找到。\n\n---\n\n## 工作流已暂停\n\n工作流配置错误。请修复工作流定义,然后调用 \`/ralphflow-continue\` 恢复。`,
2479
+ paused: true,
2480
+ };
2481
+ }
2482
+ if (isSubWorkflowStep(failStep)) {
2483
+ recordStepStart(instId, failStep.id, "do");
2484
+ logEvent(instId, "info", "step_start", { step: failStep.id, phase: "do" });
2485
+ // Always use newFailCount (never reset on routing to different step)
2486
+ pushState({ ...state, current_step: failStep.id, current_phase: "do", fail_count: newFailCount, last_failure_reason: checkResult.reason }, instId);
2487
+ const subResult = resolveSubWorkflowEntry(instId, failStep.workflow, state.user_task, failStep, MAX_NESTING_DEPTH, checkResult.reason, newFailCount);
2488
+ if (subResult.error) {
2489
+ popState(instId);
2490
+ writeState({ ...state, fail_count: newFailCount, paused: true, pause_reason: "config_error", last_failure_reason: subResult.text }, instId);
2491
+ return { text: subResult.text, paused: true };
2492
+ }
2493
+ return {
2494
+ text: `## 检查结果:失败 ✗ (${newFailCount}/${step.max_fail_count})\n\n${checkResult.reason || "检查失败。"}\n\n---\n\n使用子工作流重试:**${failStep.id}**\n\n---\n\n${subResult.text}`,
2495
+ enteredCompositeStepId: failStep.id,
2496
+ };
2497
+ }
2498
+ // Always use newFailCount (never reset on routing to different step)
2499
+ const retryState = { ...state, current_step: failStep.id, current_phase: "do", fail_count: newFailCount, last_failure_reason: checkResult.reason };
2500
+ writeState(retryState, instId);
2501
+ recordStepStart(instId, failStep.id, "do");
2502
+ logEvent(instId, "info", "step_start", { step: failStep.id, phase: "do" });
2503
+ return {
2504
+ text: `## 检查结果:失败 ✗ (${newFailCount}/${step.max_fail_count})\n\n${checkResult.reason || "检查失败。"}\n\n---\n\n重试:**${failStep.id}** - ${failStep.desc}\n\n---\n\n${buildDoPrompt(instId, failStep, state.user_task, checkResult.reason, newFailCount)}`,
2505
+ };
2506
+ }
2507
+ // ─── Step Records (per instance, file-backed) ───────────────────────────────
2508
+ // Ephemeral start times keyed by instId:stepId:phase (only used to compute a
2509
+ // record's duration when addStepRecord fires). Not shared state that any op
2510
+ // reads across an await, so no lock is needed.
2511
+ const stepStartTimes = new Map();
2512
+ function recordStepStart(instId, stepId, phase) {
2513
+ stepStartTimes.set(`${instId}:${stepId}:${phase}`, new Date().toISOString());
2514
+ }
2515
+ /** 读取某步骤某相位的开始时刻(ISO)。进程重启后内存态丢失返回 undefined,
2516
+ * 调用方(HTTP 快照)回退到实例 lastActivity。 */
2517
+ function stepStartTime(instId, stepId, phase) {
2518
+ return stepStartTimes.get(`${instId}:${stepId}:${phase}`);
2519
+ }
2520
+ function addStepRecord(instId, stepId, phase, status, failCount, reason, workflowName) {
2521
+ const now = new Date().toISOString();
2522
+ const key = `${instId}:${stepId}:${phase}`;
2523
+ const startTime = stepStartTimes.get(key) || now;
2524
+ stepStartTimes.delete(key);
2525
+ const records = loadStepRecords(instId);
2526
+ records.push({ stepId, phase, status, failCount: failCount || 0, startTime, endTime: now, reason, workflowName });
2527
+ saveStepRecords(instId, records.length > MAX_STEP_RECORDS ? records.slice(-MAX_STEP_RECORDS) : records);
2528
+ }
2529
+ /**
2530
+ * 在 `workflowName` 指定的工作流里,返回历史执行记录中通过独立 CHECK 的
2531
+ * 步骤 id 列表(去重、保留插入顺序)。用于 `/ralphflow-rewind`:只能回退
2532
+ * 到这些已通过验证的步骤。仅统计 `phase==="check" && status==="passed"`,
2533
+ * 且该步骤必须在目标工作流的 steps 中存在。
2534
+ *
2535
+ * 跨子工作流栈帧同名步骤的隔离:记录带 `workflowName`(2.7.1 起写入)时
2536
+ * 要求与目标工作流同名——子工作流里 `build` 的 check-passed 不会让父工作流
2537
+ * 从未执行过的同名 `build` 变成可回退目标。无该字段的旧记录回退到仅按
2538
+ * stepId 过滤(升级前的历史不丢,代价是旧记录仍可能把同名子步骤算进来)。
2539
+ */
2540
+ function passedStepIds(instId, workflowName) {
2541
+ const wf = loadWorkflow(workflowName);
2542
+ if (!wf)
2543
+ return [];
2544
+ const stepIds = new Set(wf.steps.map((s) => s.id));
2545
+ const records = loadStepRecords(instId);
2546
+ const passed = new Set();
2547
+ for (const r of records) {
2548
+ if (r.phase !== "check" || r.status !== "passed" || !stepIds.has(r.stepId))
2549
+ continue;
2550
+ if (r.workflowName && r.workflowName !== workflowName)
2551
+ continue;
2552
+ passed.add(r.stepId);
2553
+ }
2554
+ return [...passed];
2555
+ }
2556
+ // ─── Legacy single-workflow layout migration ────────────────────────────────
2557
+ const LEGACY_STATE_FILENAME = "ralph-flow.local.md";
2558
+ /** Parse the pre-2.0 markdown-frontmatter state file. */
2559
+ function parseLegacyState(content) {
2560
+ const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
2561
+ if (!match)
2562
+ return null;
2563
+ const state = {
2564
+ active: false, workflow_name: "", current_step: "", current_phase: "do",
2565
+ fail_count: 0, user_task: "", paused: false,
2566
+ };
2567
+ let inFailureReason = false;
2568
+ let failureReasonLines = [];
2569
+ for (const line of match[1].split(/\r?\n/)) {
2570
+ if (inFailureReason) {
2571
+ if (line.startsWith(" ")) {
2572
+ failureReasonLines.push(line.substring(2));
2573
+ continue;
2574
+ }
2575
+ state.last_failure_reason = failureReasonLines.join("\n").trim() || undefined;
2576
+ inFailureReason = false;
2577
+ }
2578
+ const [key, ...valueParts] = line.split(":");
2579
+ const value = valueParts.join(":").trim();
2580
+ switch (key.trim()) {
2581
+ case "active":
2582
+ state.active = value === "true";
2583
+ break;
2584
+ case "workflow_name":
2585
+ state.workflow_name = value;
2586
+ break;
2587
+ case "current_step":
2588
+ state.current_step = value;
2589
+ break;
2590
+ case "current_phase":
2591
+ state.current_phase = value === "check" ? "check" : "do";
2592
+ break;
2593
+ case "fail_count":
2594
+ state.fail_count = parseInt(value) || 0;
2595
+ break;
2596
+ case "user_task":
2597
+ state.user_task = value.replace(/\\n/g, "\n").replace(/\\r/g, "\r");
2598
+ break;
2599
+ case "paused":
2600
+ state.paused = value === "true";
2601
+ break;
2602
+ case "session_id":
2603
+ if (value)
2604
+ state.session_id = value;
2605
+ break;
2606
+ case "last_failure_reason":
2607
+ if (value === "") {
2608
+ inFailureReason = true;
2609
+ failureReasonLines = [];
2610
+ }
2611
+ else
2612
+ state.last_failure_reason = value;
2613
+ break;
2614
+ }
2615
+ }
2616
+ if (inFailureReason && failureReasonLines.length > 0) {
2617
+ state.last_failure_reason = failureReasonLines.join("\n").trim() || undefined;
2618
+ }
2619
+ return state;
2620
+ }
2621
+ /**
2622
+ * Pre-2.0 plugin versions kept ONE workflow per project directly under
2623
+ * .opencode/ralph-flow/ (ralph-flow.local.md + state-stack.json). The current
2624
+ * code only scans instances/<id>/, so an interrupted legacy workflow would
2625
+ * silently become invisible after an upgrade. Move it into the instances
2626
+ * layout at startup. The state-file rename is the atomic claim, so concurrent
2627
+ * processes in the same project migrate it exactly once.
2628
+ */
2629
+ function migrateLegacyInstance() {
2630
+ try {
2631
+ const dir = getRalphFlowDir();
2632
+ const legacyState = path.join(dir, LEGACY_STATE_FILENAME);
2633
+ if (!fs.existsSync(legacyState))
2634
+ return;
2635
+ let state = null;
2636
+ try {
2637
+ state = parseLegacyState(stripBom(fs.readFileSync(legacyState, "utf-8")));
2638
+ }
2639
+ catch { }
2640
+ if (!state || state.active !== true || !state.workflow_name || !state.current_step) {
2641
+ // Not a resumable workflow — park it so it is never re-parsed again
2642
+ try {
2643
+ fs.renameSync(legacyState, legacyState + ".pre-migration-backup");
2644
+ }
2645
+ catch { }
2646
+ return;
2647
+ }
2648
+ const instId = generateInstanceId(state.workflow_name);
2649
+ const instDir = getInstanceDir(instId);
2650
+ fs.mkdirSync(instDir, { recursive: true });
2651
+ // Atomic claim: exactly one concurrent process wins this rename
2652
+ try {
2653
+ fs.renameSync(legacyState, path.join(instDir, LEGACY_STATE_FILENAME + ".migrated"));
2654
+ }
2655
+ catch {
2656
+ try {
2657
+ fs.rmSync(instDir, { recursive: true, force: true });
2658
+ }
2659
+ catch { }
2660
+ return; // another process already migrated it
2661
+ }
2662
+ // Write the new-format state; the legacy session_id carries over as the
2663
+ // owning session (it may be closed — a new session takes over via continue).
2664
+ atomicWriteJson(path.join(instDir, STATE_FILENAME), { ...state, instance_id: instId });
2665
+ // Move the sub-workflow stack along (missing is fine).
2666
+ try {
2667
+ fs.renameSync(path.join(dir, STACK_FILENAME), path.join(instDir, STACK_FILENAME));
2668
+ }
2669
+ catch { }
2670
+ logEvent(instId, "info", "legacy_instance_migrated", { instance: instId, workflow: state.workflow_name, step: state.current_step, phase: state.current_phase });
2671
+ diag(`[ralph-flow] Migrated legacy workflow state to instance ${instId}`);
2672
+ }
2673
+ catch (e) {
2674
+ diag("[ralph-flow] Legacy migration failed:", e.message);
2675
+ }
2676
+ }
2677
+ function ensureProjectWorkflows() {
2678
+ // Ensure the project AND global user workflow dirs exist as places for the
2679
+ // user to drop *custom* workflows. Built-in workflows are intentionally NOT
2680
+ // copied into either: loadWorkflow falls back to the plugin dir, so
2681
+ // built-ins always resolve to the latest shipped version. Seeding copies
2682
+ // would shadow the plugin dir and go stale on plugin updates. The global
2683
+ // dir matters most for online installs, where the plugin package itself is
2684
+ // a managed, non-editable location.
2685
+ for (const dir of [getProjectWorkflowsDir(), getGlobalWorkflowsDir()]) {
2686
+ if (!dir)
2687
+ continue;
2688
+ try {
2689
+ if (!fs.existsSync(dir))
2690
+ fs.mkdirSync(dir, { recursive: true });
2691
+ }
2692
+ catch (e) {
2693
+ diag("[ralph-flow] Error initializing workflows dir:", dir, e.message);
2694
+ }
2695
+ }
2696
+ }
2697
+ return {
2698
+ projectDir,
2699
+ // paths
2700
+ getRalphFlowDir, getInstancesRoot, getReportsDir, getInstanceDir, instPath,
2701
+ getArtifactsDir, getArtifactsRelDir, getPluginWorkflowsDir, getProjectWorkflowsDir,
2702
+ getGlobalWorkflowsDir, getGlobalConfigHome,
2703
+ // instance infra
2704
+ generateInstanceId, isValidInstanceId, instanceExists,
2705
+ writeArtifactsDirName, writeExtraDirs, readExtraDirs,
2706
+ readOwnerSession, claimOwnership,
2707
+ listInstances, resolveInstance, bindInstance, destroyInstance,
2708
+ instanceStatusLabel, formatInstanceList, formatLastActivity,
2709
+ // state + markers
2710
+ readState, writeState, isValidState,
2711
+ writeMarker, clearMarker, markerExists,
2712
+ writeManualStepMarker, clearManualStepMarker, clearManualGate,
2713
+ clearReinjectCounter, readReinjectCount, clearDoPromptCache, clearDoneTagDetected,
2714
+ writeDoPromptCache, readDoPromptCache, buildDoNudge, markPromptDelivered,
2715
+ writeAdversarialSession, clearAdversarialSession, readAdversarialSession,
2716
+ readAdversarialSessions, removeAdversarialSession, pruneStaleAdversarialSessions,
2717
+ // workflows
2718
+ parseWorkflowFile, loadWorkflow, listWorkflows, lintWorkflow, buildDoctorReport,
2719
+ // steps + prompts
2720
+ getStep, buildDoPrompt, buildCheckPrompt, buildVotingCheckPrompt, buildSubWorkflowUserTask,
2721
+ resolveSubWorkflowEntry, renderStepText,
2722
+ // stack
2723
+ pushState, popState, getStackDepth, readStateStack,
2724
+ getEffectiveAdversarialCheck,
2725
+ // logs + records
2726
+ logEvent, recordStepStart, stepStartTime, addStepRecord, loadStepRecords, passedStepIds,
2727
+ readUiEventFrames, snapshotAllInstances, readHistory, appendArchivedUiEvent,
2728
+ // reports
2729
+ buildReportText, archiveReport, getReportPath, reportExists,
2730
+ // check parsing
2731
+ matchCheckTag, parseCheckResult, getAdversarialCheckReason,
2732
+ // transitions
2733
+ handleCheckPassed, handleCheckFailed,
2734
+ shouldResetOnTransition,
2735
+ // startup
2736
+ migrateLegacyInstance, ensureProjectWorkflows,
2737
+ };
2738
+ }
2739
+ export function isSubWorkflowStep(step) {
2740
+ return "workflow" in step && typeof step.workflow === "string";
2741
+ }
2742
+ /**
2743
+ * 判断从 sourceStepId 转换到 targetStepId 时是否应触发上下文重置。
2744
+ * 标了 reset 的步骤任何方式进入都触发(含同步骤重试——失败原因经
2745
+ * retryContext 文本通道注入,不丢现场);auto_reset = 全部步骤标 reset。
2746
+ */
2747
+ export function shouldResetOnTransition(workflow, sourceStepId, targetStepId) {
2748
+ if (workflow.auto_reset === true)
2749
+ return true;
2750
+ const step = workflow.steps.find((s) => s.id === targetStepId);
2751
+ return step?.reset === true;
2752
+ }
2753
+ /**
2754
+ * Resolve the yaml adversarial_check.model field into the SDK's
2755
+ * {providerID, modelID} shape. Shared by the engine's inheritance walk
2756
+ * (usability test) and check.ts (actual SDK call) so the two can never
2757
+ * drift: a model this cannot resolve is treated as absent.
2758
+ */
2759
+ export function resolveCheckModel(model) {
2760
+ if (!model)
2761
+ return undefined;
2762
+ if (typeof model === "object") {
2763
+ if (typeof model.providerID === "string" && model.providerID.trim()
2764
+ && typeof model.modelID === "string" && model.modelID.trim()) {
2765
+ return { providerID: model.providerID.trim(), modelID: model.modelID.trim() };
2766
+ }
2767
+ return undefined;
2768
+ }
2769
+ // String form "provider/model" (Claude Code yaml compatibility); a bare name
2770
+ // without provider cannot be resolved here — fall back to the agent default.
2771
+ const idx = model.indexOf("/");
2772
+ if (idx > 0)
2773
+ return { providerID: model.slice(0, idx), modelID: model.slice(idx + 1) };
2774
+ return undefined;
2775
+ }
2776
+ /**
2777
+ * 验证者模型优先级链(设计 §7):
2778
+ * 条目 model(最强) > 步骤 check_model(仅单 check 场景) > effective(workflow+祖先链)
2779
+ * 之后的 agent 配置 / owner session / 全局默认由 check.ts 的既有 fallback 链处理。
2780
+ */
2781
+ export function resolveVerifierModel(entryModel, stepModel, effective) {
2782
+ return resolveCheckModel(entryModel ?? stepModel ?? effective?.model);
2783
+ }
2784
+ // ─── Adversarial check defaults (shared with check.ts) ──────────────────────
2785
+ export const DEFAULT_ADVERSARIAL_SYSTEM_PROMPT = `你是一个严格、独立的检查者。根据"检查依据"判断 DO 阶段声称完成的工作是否真的完成。
2786
+
2787
+ ## 铁律
2788
+
2789
+ **你不能修改任何文件。无例外。** 你的 \`edit\` 权限已被硬性拒绝。bash 可以跑任意验证命令——命令产生的副作用(临时文件、缓存、构建产物)不算"你修改了文件";但主动改源码/测试/配置都让本次验证作废。违规即失败,没有"仅此一次"。
2790
+
2791
+ ## 不要相信 DO 阶段的报告
2792
+
2793
+ DO 的实现总结可能不完整、不准确、过于乐观。**你必须独立验证一切**:读真实代码、跑真实命令、看真实输出。无法独立验证的依据项 → 不通过。
2794
+
2795
+ ## 理性化——这些念头冒出来时
2796
+
2797
+ | 脑里冒出的想法 | 现实 |
2798
+ |---|---|
2799
+ | "测试挂了,顺手修一下再跑" | 污染证据,本次验证作废 |
2800
+ | "DO 报告说做完了" | 不信报告。看代码、跑测试,自己判断 |
2801
+ | "改的是无关文件" | 任何主动改动都让验证不可信 |
2802
+ | "看着对,应该通过" | 通过必须有执行证据,禁止"看着对" |
2803
+ | "对结论不确定" | 任何疑问 → 不通过,没有例外 |
2804
+
2805
+ ## 输出格式(精炼,结构化)
2806
+
2807
+ **判定**:最后一行输出标签:
2808
+ - 通过 → \`<promise-check>true</promise-check>\`
2809
+ - 不通过 → \`<promise-check>false</promise-check>\`
2810
+
2811
+ **证据与原因,每条一行,最多 10 行**,位置前缀按情况选用:
2812
+ - 具体代码问题:\`[文件:行号] 问题一句话\`
2813
+ - 模块级问题:\`[模块名] 问题一句话\`
2814
+ - 架构级/跨文件问题:直接写问题一句话,不加前缀
2815
+
2816
+ 示例:
2817
+ - \`[auth.service.ts:47] JWT 密钥硬编码\`
2818
+ - \`[payment] 与 auth 共享全局可变状态,耦合过高\`
2819
+ - \`缺少统一错误处理层,各模块异常处理散落\`
2820
+
2821
+ 不要复述检查依据原文,不要写结论性空话。证据为准。标签独占最后一行。`;
2822
+ export const DEFAULT_ADVERSARIAL_TIMEOUT_MS = 900_000;
2823
+ // ─── Verifier permissions: edit hard-deny + bash open + prompt discipline ────
2824
+ //
2825
+ // Design choice: we don't gate the verifier's bash with an allow-list. Three
2826
+ // reasons grounded in how opencode's own built-in "don't touch code" agents are
2827
+ // configured (see `opencode agent list`):
2828
+ //
2829
+ // 1. The `plan` agent — whose job is also "read/think, don't ship code" — uses
2830
+ // exactly `edit *: deny` (plus a narrow hole for its scratchpad) and leaves
2831
+ // bash fully open. That's opencode's own canonical answer to the same
2832
+ // dilemma.
2833
+ // 2. The `explore` agent doesn't even deny edit — it leans entirely on its
2834
+ // system prompt. So "no mutation" doesn't require a bash allow-list to
2835
+ // hold; it can be enforced by prompt alone.
2836
+ // 3. A bash allow-list can't actually prevent mutation anyway: `npm test`
2837
+ // (which any sane allow-list must permit) can run arbitrary scripts that
2838
+ // rewrite src/. The list gates what the model types directly, not what
2839
+ // those commands do. So the "safety" it appears to provide is largely
2840
+ // theatrical, while it very really blocks pnpm/bun/mvn/mix/... — the
2841
+ // coverage gap that bit ralph-check users in practice.
2842
+ //
2843
+ // The hard constraint that actually holds is `edit: deny` — it blocks the
2844
+ // direct "open file and change it" path the model would take to "helpfully
2845
+ // fix" failing work. Bash side-effects (test writes, build artifacts) aren't
2846
+ // the verifier agreeing with itself, so they don't poison the verdict the way
2847
+ // a direct edit would. Behavioral fidelity we enforce via the system prompt
2848
+ // (see DEFAULT_ADVERSARIAL_SYSTEM_PROMPT), borrowing persuasion patterns
2849
+ // (authority / anti-rationalization table / "don't trust the report") from
2850
+ // superpowers' research — empirically a 33% → 72% compliance lift for
2851
+ // discipline prompts.