ralphflow-dsh 2.3.1 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +47 -21
  2. package/graphs/codewiki/format.md +362 -0
  3. package/graphs/codewiki/graph.yaml +39 -0
  4. package/graphs/codewiki/nodes/assemble.md +24 -0
  5. package/graphs/codewiki/nodes/core-pages.md +17 -0
  6. package/graphs/codewiki/nodes/module-pages.md +18 -0
  7. package/graphs/codewiki/nodes/operations-pages.md +18 -0
  8. package/graphs/codewiki/nodes/survey.md +22 -0
  9. package/lib/asset-path.d.ts +59 -0
  10. package/lib/asset-path.js +181 -0
  11. package/lib/assets.d.ts +42 -0
  12. package/lib/assets.js +86 -0
  13. package/lib/client/phase.d.ts +29 -0
  14. package/lib/client/phase.js +86 -0
  15. package/lib/client/selection.d.ts +28 -0
  16. package/lib/client/selection.js +9 -0
  17. package/lib/client/status-source.d.ts +3 -1
  18. package/lib/client/status-source.js +3 -2
  19. package/lib/client/status.js +49 -13
  20. package/lib/client/viewer.d.ts +18 -0
  21. package/lib/client/viewer.js +540 -0
  22. package/lib/client.js +1159 -64
  23. package/lib/engine.d.ts +111 -47
  24. package/lib/engine.js +473 -320
  25. package/lib/facade.d.ts +175 -0
  26. package/lib/facade.js +553 -0
  27. package/lib/graph/agent-registry.d.ts +4 -0
  28. package/lib/graph/agent-registry.js +20 -0
  29. package/lib/graph/asset.d.ts +47 -0
  30. package/lib/graph/asset.js +276 -0
  31. package/lib/graph/assets.d.ts +47 -0
  32. package/lib/graph/assets.js +224 -0
  33. package/lib/graph/branches.d.ts +9 -0
  34. package/lib/graph/branches.js +13 -0
  35. package/lib/graph/check.d.ts +23 -0
  36. package/lib/graph/check.js +46 -0
  37. package/lib/graph/engine.d.ts +55 -0
  38. package/lib/graph/engine.js +2002 -0
  39. package/lib/graph/report.d.ts +9 -0
  40. package/lib/graph/report.js +117 -0
  41. package/lib/graph/state.d.ts +244 -0
  42. package/lib/graph/state.js +358 -0
  43. package/lib/graph/workspace.d.ts +68 -0
  44. package/lib/graph/workspace.js +262 -0
  45. package/lib/index.js +150 -47
  46. package/lib/owner.d.ts +34 -0
  47. package/lib/owner.js +49 -0
  48. package/lib/paths.d.ts +12 -0
  49. package/lib/paths.js +44 -0
  50. package/lib/pause.d.ts +12 -0
  51. package/lib/pause.js +19 -0
  52. package/lib/skills.d.ts +17 -30
  53. package/lib/skills.js +85 -21
  54. package/lib/status-contract.d.ts +114 -1
  55. package/lib/status-contract.js +106 -4
  56. package/lib/status-service.d.ts +5 -1
  57. package/lib/status-service.js +8 -1
  58. package/lib/tools.d.ts +14 -6
  59. package/lib/tools.js +88 -60
  60. package/lib/unfinished.d.ts +11 -0
  61. package/lib/unfinished.js +18 -0
  62. package/lib/verifier-preset.d.ts +40 -0
  63. package/lib/verifier-preset.js +126 -0
  64. package/lib/verify.d.ts +63 -9
  65. package/lib/verify.js +282 -72
  66. package/package.json +50 -38
  67. package/skills/ralphflow-create/SKILL.md +32 -0
  68. package/skills/ralphflow-create/graph-authoring.md +85 -0
  69. package/skills/ralphflow-create/matt/LICENSE +21 -0
  70. package/skills/ralphflow-create/matt/SHA256SUMS +6 -0
  71. package/skills/ralphflow-create/matt/SKILL-MECHANICS.md +22 -0
  72. package/skills/ralphflow-create/matt/SOURCE.md +12 -0
  73. package/skills/ralphflow-create/matt/grilling.md +30 -0
  74. package/skills/ralphflow-create/matt/to-spec.md +75 -0
  75. package/skills/ralphflow-create/matt/to-tickets.md +105 -0
  76. package/skills/ralphflow-create/matt/writing-for-agents.md +81 -0
  77. package/skills/ralphflow-create/ralphflow-authoring.md +31 -0
  78. package/skills/ralphflow-create/testing-workflow.md +60 -0
  79. package/{references → skills/ralphflow-create}/workflow-authoring.md +25 -5
  80. package/workflows/create-graph/steps/graph.md +17 -0
  81. package/workflows/create-graph/workflow.yaml +77 -0
  82. package/workflows/loop/workflow.yaml +23 -0
  83. package/lib/create.d.ts +0 -2
  84. package/lib/create.js +0 -17
  85. package/workflows/loop.yaml +0 -45
  86. /package/workflows/{spec.yaml → spec/workflow.yaml} +0 -0
package/lib/engine.js CHANGED
@@ -9,25 +9,27 @@
9
9
  * 交卷了吗(do_submitted)/ 判定落地了吗(verdicts)/ 有在飞委派吗(delegations)/ 暂停了吗(paused)
10
10
  */
11
11
  import fs from "node:fs";
12
+ import { normalizeUnfinished } from "./unfinished.js";
12
13
  import path from "node:path";
13
- import os from "node:os";
14
14
  import { fileURLToPath } from "node:url";
15
15
  import yaml from "js-yaml";
16
+ import { userRalphFlowDir } from "./paths.js";
17
+ import { FLOW_ENTRY_FILE, assetCandidates, assetReferenceSection, assetRootOf, discoverAssetsIn, placementSection, } from "./asset-path.js";
18
+ import { pauseLabel } from "./pause.js";
19
+ import { OWNER_HEARTBEAT_REFRESH_MS, ownerAlive, ownerRecheckMs, runtimeId, stampOwner } from "./owner.js";
16
20
  import { MAX_VOTERS, decideVotingOutcome, formatVotingFailureReason, formatVotingInfraReason, formatVotingPassReason, voterProgressLine, voterStatusLabel, } from "./voting.js";
17
21
  // 纯函数层(聚合优先级与三份文案)的唯一实现在 voting.ts;这里只把常量与展示标签转出去,
18
22
  // 让 `lib/engine.js` 仍是「引擎 + 方言」的单一入口(verify.ts / 测试都从它取类型)。
19
23
  export { MAX_VOTERS };
20
24
  export { formatVotingFailureReason, formatVotingPassReason, formatVotingInfraReason, voterProgressLine, voterStatusLabel };
21
25
  /**
22
- * 工作区内的运行时根目录。**工作区 dot-dir**(§1.8):与 opencode `.opencode/ralph-flow/`、
23
- * claude `.claude/ralph-flow/` 形状一致;全局命名空间 `~/.dsh/ralph-flow/` 由
24
- * {@link RALPH_FLOW_NAME} 拼出,两个作用域里的插件命名空间都叫 `ralph-flow`。
26
+ * 项目内的运行时根目录。**项目根 dot-dir**(§1.8):项目根 = 最近的含 `.git` 的祖先目录,
27
+ * 与原生 Skill 的 `<projectRoot>/.dsh/skills` 用同一条规则;用户级命名空间
28
+ * `<DSH_HOME>/ralph-flow/` 由 `paths.ts` 解析。
25
29
  *
26
- * 注意:这里是**工作区相对路径**(含 `/`),`path.join(workspace, RALPH_FLOW_DIR)` 仍成立。
30
+ * 注意:这里是**项目根相对路径**(含 `/`),`path.join(projectRoot, RALPH_FLOW_DIR)` 仍成立。
27
31
  */
28
32
  export const RALPH_FLOW_DIR = ".dsh/ralph-flow";
29
- /** 插件命名空间名(全局 `~/.dsh/<name>/...`)——与工作区内 `.dsh/<name>/` 对称 */
30
- export const RALPH_FLOW_NAME = "ralph-flow";
31
33
  /** 每实例产出目录的目录名(§1.7,与 opencode 同名) */
32
34
  const ARTIFACTS_DIRNAME = "artifacts";
33
35
  /**
@@ -208,8 +210,8 @@ export function stepHasCheck(step) {
208
210
  /**
209
211
  * 本步是否配置了**任何**对抗性检查:单 `check` 或多验证者投票(`check_voting`)。
210
212
  *
211
- * 这是「本步是否需要独立验证」的**唯一判据**(取代原先只看 `check` 的写法):
212
- * 两者都不写 → 跳过对抗性验证(manual 步骤 = 纯人工审查)。
213
+ * 这是「本步是否需要独立验证」的**唯一判据**:单 `check` 与 `check_voting` 任一存在
214
+ * 就委派验证者;两者都不写 → 跳过对抗性验证(manual 步骤 = 纯人工审查)。
213
215
  */
214
216
  export function stepHasVerification(step) {
215
217
  return stepHasCheck(step) || voterCountOf(step) > 0;
@@ -350,7 +352,9 @@ function composeDesc(callDesc, subDesc) {
350
352
  * · 调用点 `reset: true` → **首个展开后子步骤** 的 `reset: true` + `reset_from_call`
351
353
  * (进入子工作流 = 进入它的第一个步骤;来源标记记着调用点 id,措辞才说得出是谁标的);
352
354
  * · 调用点 `do` → 每个子步骤的 {@link StepDef.task}(**最内层优先**:内层调用点已经下沉出
353
- * `task` 的子步骤不被覆盖,于是外层值只作继承、由更内层的那句说了算)。
355
+ * `task` 的子步骤不被覆盖,于是外层值只作继承、由更内层的那句说了算);
356
+ * · 子资产入口 → 每个子步骤的 {@link StepDef.assetPath}(**保留更内层已带的路径**,否则父级
357
+ * 参考根会盖掉子工作流自己的目录)。
354
358
  *
355
359
  * `callTask` 是**调用点这一层**生效的任务:调用点自己写了 `do` 就是它,没写就是外层继承下来的
356
360
  * 值(`loadWorkflow` 的 `ctx.inheritedTask`);两者都没有 = `undefined`(提示词回落父级任务)。
@@ -369,6 +373,8 @@ function prefixSubWorkflowSteps(sub, callId, callDesc, callReset, callTask) {
369
373
  on_pass: onPass,
370
374
  // 缺省 on_fail = 自身(展开后就是带前缀的那个 id,语义不变)
371
375
  on_fail: s.on_fail ? pre + s.on_fail : undefined,
376
+ // 子工作流的入口路径 = 它自己的参考根。嵌套时 s.assetPath 已有值(更内层),保留它。
377
+ assetPath: s.assetPath ?? sub.assetPath,
372
378
  };
373
379
  // 调用点的 `do` 下沉:这段子工作流「要做什么」= 提示词「## 任务」的内容。
374
380
  // **最内层优先、外层继承**:`s.task` 已经有值 = 更内层的调用点已经下沉过了(那次展开
@@ -447,46 +453,17 @@ function callPointKeyWarning(callId, key, subName) {
447
453
  return head(`调用点只认 \`id\` / \`desc\` / \`do\` / \`input\` / \`output\` / \`workflow\` / \`on_pass\` / \`on_fail\` / \`max_fail_count\` / \`reset\`(外加工作流级 \`manual_step\` 列表里的调用点 id = 整段子工作流跑完后停门),其余键一律忽略。`);
448
454
  }
449
455
  }
450
- // ─── 孤儿委派的判据:属主运行时是否还活着 ────────────────────────────────────
451
- //
452
- // 「孤儿委派」= 发起这笔验证的**运行时已经不在了**(进程退出 / 宿主重启),判定永远
453
- // 回不来,所以 `restore()` 必须兜住它(暂停 check_infra 等用户定夺,不隐式继续)。
454
- //
455
- // 反面同样重要:属主**还活着**的委派绝不是孤儿。这里曾经无条件清空所有 `delegations`
456
- // —— 于是**别的会话**碰一下 ralphflow(哪怕是 `/ralphflow-list` 这种只读的:新建引擎
457
- // → restore)就会把正在飞的验证连根拔掉并暂停实例,验证白烧、用户被迫手动 resume
458
- // (实测两次,state.json 里 15:59:45 / 16:18:24 的 orphan_delegation_recovered)。
459
- //
460
- // 判活必须跨进程、跨 sandbox 都成立 —— 只有文件系统是共享的,所以用**心跳**:
461
- // 属主在等在飞判定期间按周期刷新 `delegations[i].heartbeat_at`,别的运行时(别的会话、
462
- // 别的 sandbox、插件重载后的新实例)看到心跳还新鲜就绝不碰它;心跳停了才是真孤儿。
463
- //
464
- // 判据与「谁在调用 restore」无关,所以同一进程里多少会话、跨多少沙箱、重载多少次,
465
- // 都不会互相踩;而真正死掉的属主留下的委派照样兜得住(TTL 之后由下一个 restore 触发点,
466
- // 或用户显式 /ralphflow-continue 兜住)。
467
- /** 在飞委派的心跳周期:属主每隔这么久把 `heartbeat_at` 刷新一次 */
468
- export const DELEGATION_HEARTBEAT_REFRESH_MS = 5_000;
456
+ // 属主判活见 `owner.ts`:心跳是**实例级**的,委派不再单独记一份。
457
+ // 这样 DO 阶段(没有委派)与验证阶段共用同一个事实,恢复逻辑也只有一条。
469
458
  /**
470
- * 心跳多久没刷就算属主失联(= 真孤儿)。
459
+ * 回合收尾检查的阈值。只在「这一轮没干活」时才算数 —— 模型每轮都在动手就是在推进,
460
+ * 不该被次数掐断(opencode 版同形:`MAX_DO_REINJECT` 只在 `!hasToolUse` 时生效)。
471
461
  *
472
- * 取 12 倍刷新周期:既容忍属主事件循环偶发卡顿(一次两次没刷上不算死),又让崩溃留下的
473
- * 孤儿在一个 TTL 之内被兜住 —— 崩溃恢复没有缩水,只是判据从「pid 还在吗」换成「心跳还在吗」。
462
+ * `STALL` 只累计**连续空回合**:一次提醒之后模型一个工具都没调用,又停了一次。连续这么多次,
463
+ * 多半是在等人或卡住了,先暂停让用户处理。有动作的回合把连续计数清零;没有累计总预算 —
464
+ * 干活的循环不设天花板,单次停顿也不会因为「历史提醒多」而被立刻暂停。
474
465
  */
475
- export const DELEGATION_HEARTBEAT_TTL_MS = 60_000;
476
- /** 本进程的运行时 id(**只作诊断**,不参与判活;pid 在跨沙箱场景里没有可比性) */
477
- let cachedRuntimeId;
478
- export function runtimeId() {
479
- if (cachedRuntimeId === undefined) {
480
- cachedRuntimeId = `${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
481
- }
482
- return cachedRuntimeId;
483
- }
484
- /** 一笔委派是否仍有存活属主 —— `restore()` 的唯一判据(导出供测试直接取证)。 */
485
- // ralphflow:orphan-liveness
486
- export function delegationOwnerAlive(d) {
487
- return typeof d.heartbeat_at === "number" && Number.isFinite(d.heartbeat_at)
488
- && Date.now() - d.heartbeat_at <= DELEGATION_HEARTBEAT_TTL_MS;
489
- }
466
+ export const SUBMIT_REMINDER_STALL_LIMIT = 2;
490
467
  /**
491
468
  * §1.4 每步耗时与重试次数:**全部从 `history` 的 `ts` 与 `fail_counts` 派生**
492
469
  * (不新增落盘字段)。纯函数,便于用合成 history 直接验证。
@@ -494,10 +471,8 @@ export function delegationOwnerAlive(d) {
494
471
  * 耗时区间 = 属于某步的**第一条**历史事件 → 下一条属于其它步骤的事件(或 `endTs`);
495
472
  * 同一被反复进入的步骤(返工/回退)累计总时长。
496
473
  *
497
- * ⚠️ 这里曾经有一个只在「步骤切换」时才结算的实现:最后一步的耗时被算成
498
- * `endTs - 该步最后一条事件`,而最后一条事件(`complete`)与 `endTs` 只差几毫秒
499
- * —— 于是**每一步都显示 `耗时 0s`**(实测:6m22s 的一轮报告成 0s,历史上每一份
500
- * 归档报告都是 0s)。区间起点必须是该步的**首条**事件,不是末条。
474
+ * 区间起点必须是该步的**首条**事件:取末条事件时,最后一步只剩 `complete` 与
475
+ * `endTs` 之间几毫秒,报告会显示 `耗时 0s`。
501
476
  *
502
477
  * 重试次数 = `max(fail_counts[step], 该步 verdict_failed 条数)`:
503
478
  * 通过时 `clearFailCount` 会把该步计数清零、恢复暂停时也会清零,所以单看
@@ -548,7 +523,7 @@ export function stepStats(history, failCounts, endTs) {
548
523
  *
549
524
  * 这些是「引擎只在运行时才暴露、甚至永远不暴露」的问题:
550
525
  * · 不可达步骤静默不执行;
551
- * · 没有可达步骤能到 `done` → 工作流永远不完成(旧版 doctor 还报 ✅,运行时无限循环);
526
+ * · 没有可达步骤能到 `done` → 工作流永远不完成;
552
527
  * · 未解析的 `{{...}}` 原样进入提示词;
553
528
  * · 非 manual 步没写 check → 该步**跳过对抗性验证**、直接推进(必须让作者知道)。
554
529
  */
@@ -658,7 +633,7 @@ export function makeArtifactsDirName(task, instId) {
658
633
  return slug ? `${slug}-${suffix}` : String(instId);
659
634
  }
660
635
  /**
661
- * 内置工作流文件(不落盘,只存在于插件目录;lib/engine.js → ../workflows/<name>.yaml)。
636
+ * 内置工作流资产(不落盘,只存在于插件目录;lib/engine.js → ../workflows/<name>/workflow.yaml)。
662
637
  *
663
638
  * 取模块目录**必须**用 `fileURLToPath`:`new URL(import.meta.url).pathname` 不做百分号解码,
664
639
  * Windows 上还给出 `/C:/…`(盘符前多一个 `/`,`path.resolve` 之后盘符变成一个**字面目录名**)。
@@ -671,8 +646,8 @@ export function makeArtifactsDirName(task, instId) {
671
646
  export function builtinWorkflowPath(name) {
672
647
  const here = path.dirname(fileURLToPath(import.meta.url));
673
648
  const candidates = [
674
- path.resolve(here, "..", "workflows", `${name}.yaml`),
675
- path.resolve(here, "..", "..", "workflows", `${name}.yaml`),
649
+ ...assetCandidates(path.resolve(here, "..", "workflows"), name, FLOW_ENTRY_FILE),
650
+ ...assetCandidates(path.resolve(here, "..", "..", "workflows"), name, FLOW_ENTRY_FILE),
676
651
  ];
677
652
  return candidates.find((p) => { try {
678
653
  return fs.statSync(p).isFile();
@@ -681,38 +656,26 @@ export function builtinWorkflowPath(name) {
681
656
  return false;
682
657
  } });
683
658
  }
684
- /** 全局工作流目录:`<DSH_HOME|~/.dsh>/ralph-flow/workflows` */
659
+ /** 用户级工作流目录:`<DSH_HOME|~/.dsh>/ralph-flow/workflows` */
685
660
  export function globalWorkflowsDirOf() {
686
- const configured = process.env.DSH_HOME;
687
- const dshHome = configured && path.isAbsolute(configured) ? path.resolve(configured) : path.join(os.homedir(), ".dsh");
688
- return path.join(dshHome, RALPH_FLOW_NAME, "workflows");
661
+ return userRalphFlowDir("workflows");
689
662
  }
690
663
  /**
691
- * 只读某个工作区(+ 全局目录 + 内置)里**全部工作流的名字与描述** —— 不建引擎、不建任何目录。
664
+ * 只读某个项目根(+ 用户级目录 + 内置)里**全部工作流的名字与描述** —— 不建引擎、不建任何目录。
692
665
  *
693
666
  * 动态快捷命令 `/ralphflow-<名字>` 在插件加载时登记,而引擎是按工作区**惰性**创建的
694
- * (首个工具调用才建)。只靠引擎的话,用户在新工作区里第一次打开会话时,自己建的工作流
667
+ * (首个工具调用才建)。只靠引擎的话,用户在新项目里第一次打开会话时,自己建的工作流
695
668
  * 还没有快捷命令。这个函数让登记可以在 `session/created` 时廉价完成(纯读目录)。
696
669
  *
697
670
  * **必须包含内置工作流**(`loop`/`spec`)——它们不落盘,只存在于插件目录,漏掉就会让
698
- * `/ralphflow-loop`、`/ralphflow-spec` 消失。工作区里的同名文件遮蔽内置(有意行为)。
671
+ * `/ralphflow-loop`、`/ralphflow-spec` 消失。项目根里的同名文件遮蔽内置(有意行为)。
699
672
  */
700
673
  export function listWorkflowsIn(workspace) {
701
- const found = new Map(); // name → 文件路径(工作区优先,其次全局,最后内置)
674
+ const found = new Map(); // name → 入口文件路径(项目根优先,其次用户级,最后内置)
702
675
  for (const dir of [path.join(workspace, RALPH_FLOW_DIR, "workflows"), globalWorkflowsDirOf()]) {
703
- let files = [];
704
- try {
705
- files = fs.readdirSync(dir);
706
- }
707
- catch {
708
- continue;
709
- }
710
- for (const f of files) {
711
- if (!/\.ya?ml$/i.test(f))
712
- continue;
713
- const name = f.replace(/\.ya?ml$/i, "");
676
+ for (const [name, file] of discoverAssetsIn(dir, FLOW_ENTRY_FILE)) {
714
677
  if (!found.has(name))
715
- found.set(name, path.join(dir, f));
678
+ found.set(name, file);
716
679
  }
717
680
  }
718
681
  for (const name of BUILTIN_WORKFLOWS) {
@@ -739,7 +702,7 @@ export function createEngine(projectDir, ports) {
739
702
  const workflowsDir = path.join(root, "workflows");
740
703
  const reportsDir = path.join(root, "reports");
741
704
  const artifactsDir = path.join(root, ARTIFACTS_DIRNAME);
742
- // 全局工作流目录仍是 `~/.dsh/ralph-flow/workflows`(插件命名空间在全局与工作区同名)
705
+ // 用户级工作流目录:`<DSH_HOME|~/.dsh>/ralph-flow/workflows`(与项目根同名命名空间)
743
706
  const globalWorkflowsDir = globalWorkflowsDirOf();
744
707
  /**
745
708
  * 实例 → 在飞取消信号集合(取消/重开/暂停时中止验证者,不白烧 token)。
@@ -779,75 +742,61 @@ export function createEngine(projectDir, ports) {
779
742
  aborts.delete(instId);
780
743
  return n;
781
744
  }
782
- // ─── 在飞委派的心跳(跨 sandbox 的判活机制,见 delegationOwnerAlive)──────────
745
+ // ─── 属主心跳(跨进程判活,见 owner.ts)────────────────────────────────────
783
746
  //
784
- // 属主在等判定期间每 DELEGATION_HEARTBEAT_REFRESH_MS 把 `state.json` 里的
785
- // `heartbeat_at` 刷一次。别处(别的会话 / 别的沙箱进程 / 重载后的新实例)据此判断
786
- // 「这笔委派还有人在等判定」还是「属主已经不在了」。跨进程唯一共享的是文件系统,
787
- // 所以心跳写在实例的 state.json 里,不引入第二个事实源。
788
- /** 定时器:key = `instId\0runId` */
789
- const heartbeats = new Map();
790
- const beatKey = (instId, runId) => `${instId}\u0000${runId}`;
747
+ // 只由**正在驱动实例**的运行时刷新:DO 中 / 验证中。暂停、审查门、等待人工处理不需要
748
+ // 属主 —— 它们本来就该由任何 host 接管,也绝不能因为属主没了被误判成中断。
749
+ /** 本进程正在驱动的实例(心跳的刷新范围)。 */
750
+ const driving = new Set();
751
+ let drivingTimer;
752
+ /** 这个实例当前是否需要一个属主(决定心跳是否继续)。 */
753
+ function needsOwner(s) {
754
+ return s.active && !s.paused && (!s.do_submitted || s.delegations.length > 0);
755
+ }
791
756
  /**
792
- * 让一笔在飞委派保持「活着」。每次刷新前**重读 state**:委派没了(判定落地/作废/取消/
793
- * 推进)或实例没了(已销毁)就自行停表 —— 绝不在实例销毁后把目录写回来。
757
+ * 开始/继续驱动一个实例。定时器每次**重读 state**:实例结束、暂停、到了审查门,或已被
758
+ * 另一个运行时接管,就自行移除 —— 绝不在实例销毁后把目录写回来。
794
759
  */
795
- function startHeartbeat(instId, runId) {
796
- const key = beatKey(instId, runId);
797
- if (heartbeats.has(key))
760
+ function startDriving(instId) {
761
+ driving.add(instId);
762
+ if (drivingTimer)
798
763
  return;
799
- const timer = setInterval(() => {
800
- // 心跳与「判定落账」写的是**同一份 state.json**(读-改-写)。本进程内这两段都是
801
- // 同步块(readFileSync/writeFileSync),不会交错;共用实例锁是**按构造的护栏**:
802
- // 多验证者投票时 N 份心跳 + N 笔判定同时活跃,将来任何一处引入 await(异步落盘、
803
- // 重试)都不会退化成互相覆盖(判定被旧快照写回去 = 票凭空消失、卡在「验证中」)。
804
- void withStateLock(instId, () => {
805
- try {
806
- const fresh = readState(instId);
807
- const d = fresh?.delegations.find((x) => x.run_id === runId);
808
- if (!fresh || !fresh.active || !d) {
809
- stopHeartbeat(instId, runId);
810
- return;
764
+ drivingTimer = setInterval(() => {
765
+ for (const id of [...driving]) {
766
+ // 心跳与判定落账写同一份 state.json;共用实例锁,避免读-改-写互相覆盖。
767
+ void withStateLock(id, () => {
768
+ try {
769
+ const fresh = readState(id);
770
+ if (!fresh || !needsOwner(fresh) || (fresh.owner_runtime && fresh.owner_runtime !== runtimeId())) {
771
+ driving.delete(id);
772
+ return;
773
+ }
774
+ fresh.owner_runtime = runtimeId();
775
+ fresh.owner_heartbeat_at = Date.now();
776
+ writeState(fresh, id);
811
777
  }
812
- d.heartbeat_at = Date.now();
813
- writeState(fresh, instId);
814
- }
815
- catch (e) {
816
- log("warn", "delegation_heartbeat_failed", { instId, runId, error: msg(e) });
817
- }
818
- });
819
- }, DELEGATION_HEARTBEAT_REFRESH_MS);
820
- // 心跳不该拖住进程退出
821
- timer.unref?.();
822
- heartbeats.set(key, timer);
823
- }
824
- function stopHeartbeat(instId, runId) {
825
- const key = beatKey(instId, runId);
826
- const t = heartbeats.get(key);
827
- if (t) {
828
- clearInterval(t);
829
- heartbeats.delete(key);
830
- }
831
- }
832
- /** 把某实例下所有在飞委派的心跳停掉(兜底清理:判定落地、孤儿恢复、取消…) */
833
- function stopHeartbeatsOf(instId, delegations) {
834
- for (const d of delegations)
835
- stopHeartbeat(instId, d.run_id);
778
+ catch (e) {
779
+ log("warn", "owner_heartbeat_failed", { instId: id, error: msg(e) });
780
+ }
781
+ });
782
+ }
783
+ }, OWNER_HEARTBEAT_REFRESH_MS);
784
+ drivingTimer.unref?.();
836
785
  }
837
- // ─── 单根:一个引擎只服务一个工作区 ────────────────────────────────────────
786
+ // ─── 单根:一个引擎只服务一个项目根 ────────────────────────────────────────
838
787
  //
839
788
  // 这里曾有一个「全局实例索引」(`~/.dsh/ralphflow-instances-index.json`)把 instId
840
789
  // 映射到工作区,好让**一个**引擎服务多个工作区。那是 dsh 版独有的复杂度,也正是
841
- // 「写入看会话工作区、读取看进程 cwd」这类缺陷的来源:引擎的 `projectDir` 是 dsh
842
- // 进程的 cwd,而实例资产落在会话工作区,真实 GUI 里两者必然不同(实测 `dsh web`
843
- // 的 cwd = `/home/yj`,会话工作区 = `/home/yj/ralph-flow-dsh`)—— 于是自定义工作流
790
+ // 「写入看会话目录、读取看进程 cwd」这类缺陷的来源:引擎的 `projectDir` 曾是 dsh
791
+ // 进程的 cwd,而实例资产落在会话目录,真实 GUI 里两者必然不同(实测 `dsh web`
792
+ // 的 cwd = `/home/yj`,会话的项目根 = `/home/yj/ralph-flow-dsh`)—— 于是自定义工作流
844
793
  // 加载不到、历史列表永远是空的、doctor 看不见残留。
845
794
  //
846
- // 现在引擎**按工作区实例化**(见 `index.ts` 的 `engineFor`),这正是 opencode 版的
795
+ // 现在引擎**按项目根实例化**(见 `index.ts` 的 `engineFor`),这正是 opencode 版的
847
796
  // 形状(它的插件是「每个项目目录一个实例」,见其 `engine.ts:9`)。所有路径只有一根,
848
- // 索引、`workspaceOf()` 的回落、跨工作区联合扫描一并删除。
797
+ // 索引、`workspaceOf()` 的回落、跨项目根联合扫描一并删除。
849
798
  /**
850
- * 每实例产出目录(§1.7):`<workspace>/.dsh/ralph-flow/artifacts/<artifacts_dir_name>/`。
799
+ * 每实例产出目录(§1.7):`<项目根>/.dsh/ralph-flow/artifacts/<artifacts_dir_name>/`。
851
800
  *
852
801
  * 目录名来自 `state.artifacts_dir_name`(缺省回退 `instId`,兼容老 `state.json`)。
853
802
  * 注意:销毁流程必须**先**解析出这个路径,再删实例目录(不变量 3)。
@@ -1004,8 +953,7 @@ export function createEngine(projectDir, ports) {
1004
953
  }
1005
954
  // 内置工作流**有意不落盘**(对齐 opencode/claude 的 ensureProjectWorkflows):
1006
955
  // loadWorkflow 会回落到插件目录,所以内置始终解析到**随插件发布的最新版本**。
1007
- // 播种副本会遮蔽插件目录、并在插件升级后变成陈旧副本——实测踩过:工作区里那份
1008
- // 7 步 spec 副本把新版 4 步内置整个挡住了,改了内置却"没生效"。
956
+ // 工作区里的同名副本会遮蔽插件目录,并在插件升级后变成陈旧副本;
1009
957
  // 用户要定制,就在本目录放同名文件(遮蔽是有意的,也是唯一的定制入口)。
1010
958
  }
1011
959
  // ─── 工作流加载与校验(坏文件 fail-fast 说人话)────────────────────────────
@@ -1018,32 +966,23 @@ export function createEngine(projectDir, ports) {
1018
966
  * 不写就继承父级任务 —— 与 `reset` 一样是「零新概念:同一个键、同一个意思,只是层级不同」)。
1019
967
  */
1020
968
  const CALL_POINT_KEYS = new Set(["id", "desc", "do", "input", "output", "workflow", "on_pass", "on_fail", "max_fail_count", "reset"]);
1021
- const KNOWN_WF_KEYS = new Set(["description", "manual_step", "adversarial_check", "auto_reset", "steps"]);
969
+ const KNOWN_WF_KEYS = new Set(["kind", "description", "manual_step", "adversarial_check", "auto_reset", "steps"]);
1022
970
  function knownWorkflowDirs() {
1023
- // 单根:本工作区的工作流目录 + 全局目录(内置工作流不落盘,由 builtinWorkflowPath 回落)
971
+ // 单根:本项目根的工作流目录 + 用户级目录(内置工作流不落盘,由 builtinWorkflowPath 回落)
1024
972
  return [workflowsDir, globalWorkflowsDir];
1025
973
  }
1026
974
  function workflowPaths(name) {
1027
- const out = [];
1028
- for (const dir of knownWorkflowDirs()) {
1029
- out.push(path.join(dir, `${name}.yaml`), path.join(dir, `${name}.yml`));
1030
- }
1031
- return out;
975
+ return knownWorkflowDirs().flatMap((dir) => assetCandidates(dir, name, FLOW_ENTRY_FILE));
1032
976
  }
1033
977
  function listWorkflows() {
1034
978
  const names = new Set(BUILTIN_WORKFLOWS);
1035
979
  for (const dir of knownWorkflowDirs()) {
1036
- try {
1037
- for (const f of fs.readdirSync(dir)) {
1038
- if (/\.ya?ml$/i.test(f))
1039
- names.add(f.replace(/\.ya?ml$/i, ""));
1040
- }
1041
- }
1042
- catch { }
980
+ for (const name of discoverAssetsIn(dir, FLOW_ENTRY_FILE).keys())
981
+ names.add(name);
1043
982
  }
1044
983
  return [...names].sort().map((n) => {
1045
984
  const { def, problems, warnings } = loadWorkflow(n);
1046
- return { name: n, desc: def?.description ?? "", invalid: !def, problems, warnings };
985
+ return { name: n, desc: def?.description ?? "", invalid: !def, problems, warnings, steps: def?.steps.length ?? 0 };
1047
986
  });
1048
987
  }
1049
988
  /**
@@ -1104,7 +1043,7 @@ export function createEngine(projectDir, ports) {
1104
1043
  }
1105
1044
  }
1106
1045
  if (raw === undefined) {
1107
- problems.push(`未找到工作流 "${name}"。把 YAML 放到 ${workflowsDir}/<name>.yaml 即可被识别。`);
1046
+ problems.push(`未找到工作流 "${name}"。把资产放到 ${workflowsDir}/<name>/workflow.yaml(目录形态;单文件 ${workflowsDir}/<name>.yaml 也识别)即可被加载。`);
1108
1047
  return { def: null, problems, warnings };
1109
1048
  }
1110
1049
  raw = raw.replace(/^\uFEFF/, "");
@@ -1124,15 +1063,24 @@ export function createEngine(projectDir, ports) {
1124
1063
  if (!KNOWN_WF_KEYS.has(k))
1125
1064
  warnings.push(`顶层键 \`${k}\` 本版本未支持,已忽略。`);
1126
1065
  }
1066
+ // ── kind / 目录一致性(design §2.1;目录分派在加载器,这里兜住直接按名字加载的路径)──
1067
+ if (Object.prototype.hasOwnProperty.call(doc, "nodes")) {
1068
+ problems.push(`${usedPath} 含有 \`nodes\`:Graph 资产只放 graphs/ 目录,且必须用 Graph 校验器加载。`);
1069
+ return { def: null, problems, warnings };
1070
+ }
1071
+ if (doc.kind !== undefined && doc.kind !== null && doc.kind !== "flow") {
1072
+ problems.push(`${usedPath} 的 \`kind\` 是 ${describeValueKind(doc.kind)}:workflows/ 目录只接受 Flow 资产(\`kind: flow\` 或省略)。Graph 资产请放到 graphs/。`);
1073
+ return { def: null, problems, warnings };
1074
+ }
1127
1075
  const stepsRaw = doc.steps;
1128
1076
  if (!Array.isArray(stepsRaw) || stepsRaw.length === 0) {
1129
1077
  problems.push(`${usedPath} 缺少非空的 steps 列表。`);
1130
1078
  return { def: null, problems, warnings };
1131
1079
  }
1132
1080
  // ── adversarial_check 容错(design §8 Q13 口径:自己不兑现的键一律 warn+ignore)──
1133
- // 公开契约只允许 `model` 一个字段。其余字段(含已删除的 agent / system_prompt /
1134
- // timeout_ms)与「整个值不是对象」都在**加载期**告警并忽略:不拒收、不静默、
1135
- // 不改作别的含义。告警必须在这里出现,不能拖到验证阶段。
1081
+ // 公开契约只允许 `model` 一个字段。其余字段(agent / system_prompt / timeout_ms)
1082
+ // 与「整个值不是对象」都在**加载期**告警并忽略:不拒收、不静默、不改作别的含义。
1083
+ // 告警必须在这里出现,不能拖到验证阶段。
1136
1084
  //
1137
1085
  // 解析提前到步骤之前:**展开子工作流时要拿它当「逐字段继承」的父级模型**
1138
1086
  // (opencode 的 `adversarial_check` 沿调用链继承,见 sinkVerificationModel)。
@@ -1222,13 +1170,13 @@ export function createEngine(projectDir, ports) {
1222
1170
  if (!KNOWN_STEP_KEYS.has(k))
1223
1171
  warnings.push(`步骤 \`${s.id}\` 的键 \`${k}\` 本版本未支持,已忽略。`);
1224
1172
  }
1225
- // ── 步骤级 `manual_step` 已删除(只保留工作流级列表)──────────────────
1226
- // 两种写法在本引擎里曾语义相同、纯冗余;但 opencode/pi 只认**工作流级列表**,
1227
- // 步骤级写法在那边只是「不认识的步骤键」→ 警告忽略 → **人工审查门静默消失**。
1228
- // 静默跳过审查门比报错严重得多,故这里不论值是什么(true/false/null)都硬错误,
1229
- // 并在文案里直接给出正确写法。键存在与否用 hasOwnProperty 判(`manual_step:` 空值也算写了)。
1173
+ // ── 步骤级 `manual_step` 是加载期硬错误(人工门只认工作流级列表)──────────
1174
+ // opencode/pi 只认**工作流级列表**;步骤级写法在那边只是「不认识的步骤键」→
1175
+ // 警告忽略 → **人工审查门静默消失**。静默跳过审查门比报错严重得多,故这里
1176
+ // 不论值是什么(true/false/null)都硬错误,并在文案里直接给出正确写法。
1177
+ // 键存在与否用 hasOwnProperty 判(`manual_step:` 空值也算写了)。
1230
1178
  if (Object.prototype.hasOwnProperty.call(s, "manual_step")) {
1231
- problems.push(`步骤 \`${s.id}\` 写了步骤级 \`manual_step\`:该写法已删除,不论值是什么(true/false/空值)都不再有效。`
1179
+ problems.push(`步骤 \`${s.id}\` 写了步骤级 \`manual_step\`:这个键不是本版本的写法,不论值是什么(true/false/空值)都无效。`
1232
1180
  + `正确写法是把该步 id 列进工作流级 \`manual_step:\` 列表(顶层,与 \`steps\` 同级),即 \`manual_step: [${s.id}]\`(或写成 \`manual_step:\` 下的列表项 \`- ${s.id}\`)。`
1233
1181
  + `步骤级写法在 opencode 那边只是「不认识的步骤键」,会被忽略——人工审查门静默消失,因此这里硬错误而不是告警忽略。`);
1234
1182
  }
@@ -1244,7 +1192,7 @@ export function createEngine(projectDir, ports) {
1244
1192
  problems.push(`步骤 \`${s.id}\` 写了 \`workflow\` 但没有给出要调用的工作流名(必须是非空字符串,例如 \`workflow: analyze\`)。调用点以 \`workflow:\` 声明委托(此时 \`do\` 可省略;写了就是这段子工作流的任务)。`);
1245
1193
  }
1246
1194
  else if (/[\\/]/.test(subName)) {
1247
- problems.push(`步骤 \`${s.id}\` 的 \`workflow: ${subName}\` 含路径分隔符:\`workflow\` 只能是工作流**名**(对应 \`${workflowsDir}/<名字>.yaml\`、全局目录或内置同名文件),不能是路径。`);
1195
+ problems.push(`步骤 \`${s.id}\` 的 \`workflow: ${subName}\` 含路径分隔符:\`workflow\` 只能是工作流**名**(对应目录 \`${workflowsDir}/<名字>/workflow.yaml\`、全局目录或内置同名资产),不能是路径。`);
1248
1196
  }
1249
1197
  if (s.id.includes(SUBWORKFLOW_ID_SEP)) {
1250
1198
  problems.push(`调用点 \`${s.id}\` 的 id 含 \`${SUBWORKFLOW_ID_SEP}\`:展开后步骤 id 是 \`调用点id${SUBWORKFLOW_ID_SEP}子步骤id\`,调用点 id 含分隔符会与展开结果撞名。请把 id 改成不含 \`${SUBWORKFLOW_ID_SEP}\` 的名字。`);
@@ -1520,7 +1468,7 @@ export function createEngine(projectDir, ports) {
1520
1468
  if (problems.length > 0)
1521
1469
  return { def: null, problems, warnings };
1522
1470
  // manual_step 方言:**只有工作流级(顶层)一种写法**,列表与逗号字符串都接受(对齐 opencode)。
1523
- // 步骤级 `manual_step` 已删除 = 上面的加载期硬错误——绝不静默放过(审查门会静默消失)。
1471
+ // 步骤级 `manual_step` 由上面的加载期硬错误拦下(审查门不能静默消失)。
1524
1472
  const manual = [];
1525
1473
  if (Array.isArray(doc.manual_step)) {
1526
1474
  manual.push(...doc.manual_step
@@ -1568,6 +1516,7 @@ export function createEngine(projectDir, ports) {
1568
1516
  warnings.push(...lintWorkflow(steps, manualSet, autoReset));
1569
1517
  const def = {
1570
1518
  name,
1519
+ assetPath: usedPath,
1571
1520
  description: typeof doc.description === "string" ? doc.description : "",
1572
1521
  manual_step: [...manualSet],
1573
1522
  // 只保留公开契约里的 `model`;其余字段已在上面告警忽略,绝不带进定义。
@@ -1595,6 +1544,10 @@ export function createEngine(projectDir, ports) {
1595
1544
  const s = JSON.parse(fs.readFileSync(statePath(instId), "utf-8"));
1596
1545
  if (!s || typeof s !== "object")
1597
1546
  return null;
1547
+ // 一个 instances/ 目录装两类实例(design §3.1):Flow 引擎只读自己这一类。
1548
+ // Graph 状态由 graph/state.ts 读;这里返回 null 让 listInstances/uiStatus 自然跳过。
1549
+ if (s.kind === "graph")
1550
+ return null;
1598
1551
  s.delegations ??= [];
1599
1552
  s.verdicts ??= [];
1600
1553
  s.history ??= [];
@@ -1828,7 +1781,6 @@ export function createEngine(projectDir, ports) {
1828
1781
  }
1829
1782
  state.do_submitted = false;
1830
1783
  state.verdicts = [];
1831
- stopHeartbeatsOf(instId, state.delegations);
1832
1784
  state.delegations = [];
1833
1785
  state.last_submit_summary = undefined;
1834
1786
  pushHistory(state, "gate_reopened", reason, step.id);
@@ -1836,13 +1788,20 @@ export function createEngine(projectDir, ports) {
1836
1788
  writeState(state, instId);
1837
1789
  }
1838
1790
  // ─── 交卷与验证(三时刻①②)────────────────────────────────────────────────
1791
+ /**
1792
+ * 本步引用资源的入口文件:子工作流展开时步骤自己带路径(子资产目录),普通步骤落在所在
1793
+ * 工作流上。DO 与 CHECK(单票/投票)都从这里取**同一个值** —— 执行者与验证者拿到同一个
1794
+ * 参考根,子工作流的资源才不会错用调用点的目录。
1795
+ */
1796
+ function assetPathOfStep(wf, step) {
1797
+ return step.assetPath ?? wf.assetPath;
1798
+ }
1839
1799
  /**
1840
1800
  * DO prompt:宣告本步任务(交卷 = 调用 ralphflow_submit 工具,dsh 原生方式)。
1841
1801
  *
1842
- * §1.7:每个 DO 提示词**各注入一节**「产出目录」(工作区相对路径),写明**过程文档**与
1843
- * **产物**的落点边界(过程文档裸文件名 → 该目录;明确路径 → 按写的路径;工作目录只放产物、
1844
- * 不留副本)。`## 交付物` 一节随后补一句「落点由产出目录决定」,保证**拼装后**两节不打架 ——
1845
- * 仅靠「各文件单独看没错」会漏掉这种跨节矛盾(loop 曾经的 `+ summary.md` 正是如此)。
1802
+ * 落点按**概念**划:过程记录进 `artifacts/<dir>/`,交付物落工作目录或 `output` 写明的
1803
+ * 路径。文案只有一份(`placementSection`),DO 与 CHECK 共用;`## 交付物` 只放 `output`
1804
+ * 原文,落点由「## 落点」一节说,两节拼装后自洽。
1846
1805
  *
1847
1806
  * 「## 任务」= {@link effectiveTaskOf}:子工作流调用点写了 `do` 时,这里给的是**那段子工作流
1848
1807
  * 要做什么**(加载期下沉到 `step.task`);否则仍是发起会话的任务描述(向后兼容)。
@@ -1851,14 +1810,19 @@ export function createEngine(projectDir, ports) {
1851
1810
  * 写进 DO 提示词,而不是只写进交接稿 —— 交接稿是「换上下文成功」才有的东西,而原因是
1852
1811
  * 换方向这件事本身的一部分:替换失败时 DO 照样带着原因落地(没有 `keep_session` 这类逃生口)。
1853
1812
  * 那一段同时点明**下游旧产出仍在盘上、基于旧方向**(回退不删除、不作废任何已有产出)。
1813
+ *
1814
+ * `continuation` = 上一轮进度交卷留下的清单。提醒与 continue 都把它作为**本轮清单**注入,
1815
+ * 并在「交卷方式」里把完成条件写成「清单做完或被阻塞」—— 这样 start / continue / 提醒
1816
+ * 三个入口拿到的是同一份任务书,轮长不再由入口决定(旧版提醒只有回顾短卡,实测同一模型
1817
+ * 在完整 DO 下做 93/140 次工具调用,在短卡下只做 3 次)。
1854
1818
  */
1855
- function doPrompt(instId, wf, state, step, rework, rewind) {
1819
+ function doPrompt(instId, wf, state, step, rework, rewind, continuation) {
1856
1820
  const idx = wf.steps.findIndex((s) => s.id === step.id) + 1;
1857
1821
  const rel = artifactsRelDirOf(instId);
1858
1822
  const hasCheck = stepHasVerification(step);
1859
1823
  const voters = voterCountOf(step);
1824
+ const assetRef = assetReferenceSection(assetRootOf(assetPathOfStep(wf, step)));
1860
1825
  // 本步是不是审查门:无检查依据 + 门 = 纯人工审查,交卷后停在门等用户放行(不是「自动进入下一步」)。
1861
- const gate = isGate(wf, step);
1862
1826
  const parts = [
1863
1827
  `[ralphflow] 工作流 \`${wf.name}\` · 步骤 ${idx}/${wf.steps.length}:**${step.id}**${step.desc ? ` — ${step.desc}` : ""}`,
1864
1828
  "",
@@ -1867,28 +1831,24 @@ export function createEngine(projectDir, ports) {
1867
1831
  "",
1868
1832
  `## 输入`,
1869
1833
  String(step.input).trim(),
1870
- "先读取本步所需输入;重置后从指定文件恢复需求、决定与验证依据。文件中的完成声明是待核对的记录,以当前产出与证据为准。",
1834
+ "读本步声明的输入;重置后从这里恢复需求与决定。输入里的完成声明是记录,以产出与证据为准。",
1871
1835
  "",
1836
+ ...(assetRef ? [assetRef, ""] : []),
1872
1837
  ...(hasCheck ? [
1873
1838
  "## 本步验收依据(供自查)",
1874
1839
  ...(voters > 0 ? step.check_voting.map((v, i) => `${i + 1}. ${v.check.trim()}`) : [step.check.trim()]),
1875
- "以下执行要求应交付满足这些判据的产出;独立判定由验证者负责。",
1876
1840
  "",
1877
1841
  ] : []),
1878
1842
  `## 本步要做什么`,
1879
1843
  (step.do || step.desc || step.id).trim(),
1880
1844
  "",
1881
- `## 产出目录`,
1882
- `\`${rel}/\` —— 本步的**过程文档**(清单、方案、报告、摘要、草稿等)只落这里:\`do\`/\`output\` 里写**裸文件名**的(如 \`summary.md\`)落到这个目录;写了**明确路径**的(如 \`docs/x.md\`)按写的路径来。`,
1883
- "",
1884
- `工作目录只放本步的**产物**(代码、资源、可执行文件);过程文档除「写了明确路径」外不进工作目录,同一份过程文档只写一处、不要留副本(例如产出目录已有 \`summary.md\`、工作目录根又出现一份,那是落点错误)。`,
1845
+ placementSection(rel),
1885
1846
  ];
1886
- // 「交付物」与「产出目录」必须拼装后自洽:`output` 说的是**产出什么**,落点由上面
1887
- // 「产出目录」一节决定。少了这句,`output` 里写进过程文档名(如 loop 曾经的
1888
- // `+ summary.md(执行摘要)`)就会被读成「和代码并列的工作目录交付物」,
1889
- // 与紧邻的「产出目录」直接打架 —— 模型两边都写、并行维护、开始漂移。
1890
1847
  if (step.output) {
1891
- parts.push("", `## 交付物`, String(step.output).trim(), "", `(这一节说的是本步**产出什么**;它们落在**哪里**由「产出目录」一节决定 —— 过程文档写裸文件名就落产出目录,不因为列在这一节就改写进工作目录。)`);
1848
+ parts.push("", `## 交付物`, String(step.output).trim());
1849
+ }
1850
+ if (continuation && continuation.items.length > 0) {
1851
+ parts.push("", `## 本轮清单(上一轮记下的 ${continuation.count} 项未完成)`, ...continuation.items.map((item, index) => `${index + 1}. ${item}`), "", "本轮的目标是把这份清单做完;以清单完成作为本轮的完成条件。");
1892
1852
  }
1893
1853
  if (rework) {
1894
1854
  parts.push("", "## 上一轮验证未通过(反馈)", rework.trim(), "反馈用于定位与安排修复;完成条件仍是当前步的完整要求。修复这些问题后,继续核对其它要求与实际产出,全部满足后再交卷。");
@@ -1897,19 +1857,11 @@ export function createEngine(projectDir, ports) {
1897
1857
  // 回退原因**自成一段**:不依赖交接稿、不依赖历史 —— 接手这一步的模型一定能看到它。
1898
1858
  const at = wf.steps.findIndex((s) => s.id === step.id);
1899
1859
  const downstream = wf.steps.slice(at + 1).map((s) => `\`${s.id}\``);
1900
- parts.push("", `## 用户回退了这一步(\`/ralphflow-rewind\`:从 \`${rewind.from}\` 回到 \`${step.id}\`)`, "", "用户给出的回退原因(原文):", "", rewind.reason, "", "请按这个原因**换方向重做本步**,不要沿原方向继续。", "", downstream.length > 0
1901
- ? `⚠️ **下游旧产出仍在盘上、且基于旧方向**:${downstream.join("、")} 的既有产出没有被删除、也不会自动作废,它们可能与本步的新方向不一致。交卷时请写清哪些下游旧产出需要随之重做或作废,供后续步骤与独立验证者判断。`
1860
+ parts.push("", `## 用户回退了这一步(\`/ralphflow-rewind\`:从 \`${rewind.from}\` 回到 \`${step.id}\`)`, "", "用户给出的回退原因(原文):", "", rewind.reason, "", "请按这个原因**换方向重做本步**。", "", downstream.length > 0
1861
+ ? `⚠️ **下游旧产出仍在盘上、且基于旧方向**:${downstream.join("、")} 的既有产出仍在盘上、可能已过时,与本步的新方向不一致。交卷时请写清哪些下游旧产出需要随之重做或作废,供后续步骤与独立验证者判断。`
1902
1862
  : "⚠️ **本步是工作流顺序上的最后一步**:它自己的既有产出仍在盘上、基于旧方向,重做时以新方向为准;交卷时请说明旧产出里哪些已不再适用。");
1903
1863
  }
1904
- const afterSubmit = hasCheck
1905
- ? (voters > 0
1906
- ? `${voters} 个独立验证者**并行**取证,各自只查一条检查依据,**全过才放行**。`
1907
- : "独立验证者取证判定。")
1908
- : "本步未配置 check / check_voting,跳过对抗性验证。";
1909
- const nextAction = gate
1910
- ? `${hasCheck ? "通过后" : "交卷即"}停在审查门,等用户 \`/ralphflow-continue\` 放行。`
1911
- : (hasCheck ? "由引擎自动推进或投递失败依据。" : "交卷后由引擎自动推进。");
1912
- parts.push("", "## 交卷方式", "1. 对照本步要求核验交付物。将跨步需要的用户决定、验证方法与结果写入本步已有过程文档;需要用户补充信息时说明阻塞项,等信息齐全再完成本步。", "2. 面向用户简短说明本步交付内容及自查结果,然后**调用 `ralphflow_submit` 工具交卷**。验证者看不到 summary 参数:需要验收的证据应能从文件或命令结果独立取得。", `交卷后:${afterSubmit}${nextAction}`, ...(hasCheck ? ["独立验证期间不需要用户做任何操作;可用 `/ralphflow-status` 查进度或 `/ralphflow-cancel` 中止。保持已交付产出稳定,新增修改等返工或用户指令后再做;不要给任何时长预估。"] : []), "交卷工具会结束当前回合,随后等待引擎或用户的下一条指令。通知与状态入口由插件展示,不需要重复播报。");
1864
+ parts.push("", "## 交卷", `完成条件逐条满足、每条都有可复核的证据(文件位置、命令与结果),把 \`unfinished\` 留空,调用 \`ralphflow_submit\`。`, "确实被阻塞时(只算缺用户决定、缺外部输入、环境不可用),把还没完成的事项写进 `unfinished`;引擎会把清单还给你接着做。", "需要用户决定时调用 `ask_user_question`;把用户决定、验证方法与结果写进本步过程记录,计划与完成分开写。", "先向用户简短说明本步交付与自查结果,再交卷;交卷后引擎接手,用 `/ralphflow-status` 看进度。");
1913
1865
  return parts.join("\n");
1914
1866
  }
1915
1867
  /**
@@ -1966,13 +1918,12 @@ export function createEngine(projectDir, ports) {
1966
1918
  const startedAt = Date.now();
1967
1919
  state.delegations.push({
1968
1920
  run_id: runId, check_index: checkIndex, attempt, ts: new Date().toISOString(),
1969
- // 属主运行时(诊断)+ 心跳起点(判活的唯一依据):心跳只要还在刷新,别的会话 /
1970
- // 别的沙箱进程 / 重载后的新实例就不得把这笔在飞委派当孤儿清掉。
1971
- owner_runtime: runtimeId(), heartbeat_at: Date.now(),
1972
1921
  });
1922
+ // 验证中也需要属主:实例心跳继续刷,别的 host 才知道这笔判定还有人在等。
1923
+ stampOwner(state);
1924
+ startDriving(instId);
1973
1925
  pushHistory(state, "verify_start", `check_index=${checkIndex},attempt=${attempt}`, step.id);
1974
1926
  writeState(state, instId);
1975
- startHeartbeat(instId, runId);
1976
1927
  log("info", "verify_start", { instId, step: step.id, checkIndex, attempt });
1977
1928
  // 阶段播报:验证是**异步**的(委派独立子代理,不阻塞主会话回合)。
1978
1929
  // 这段静默窗口必须讲清三件事:正在发生什么 / 要不要你操作 / 去哪看进度。
@@ -1981,7 +1932,7 @@ export function createEngine(projectDir, ports) {
1981
1932
  // (见 verify.ts:生命周期跟随宿主原生能力)—— 猜一个「通常 1–5 分钟」就是编。
1982
1933
  // 能诚实说的只有「它在读文件、跑命令取证,你(用户)看得到」。
1983
1934
  notify(state, attempt > 1 ? [
1984
- `🔍 步骤 \`${step.id}\` 验证发生基础设施故障,正在**自动重新验证一次**(不计失败次数)。`,
1935
+ `🔍 步骤 \`${step.id}\` 验证发生基础设施故障,正在**自动重新验证一次**(不计返工次数)。`,
1985
1936
  "无需操作;重试仍故障会暂停,等你修复后继续。",
1986
1937
  ].join("\n") : [
1987
1938
  `🔍 步骤 \`${step.id}\` 已交卷,独立验证者(独立会话,看不到本对话)正在取证判定。`,
@@ -1999,6 +1950,7 @@ export function createEngine(projectDir, ports) {
1999
1950
  try {
2000
1951
  verdict = await ports.verify({
2001
1952
  instId, step, workflow: wf, userTask: effectiveTaskOf(step, state.user_task),
1953
+ assetPath: assetPathOfStep(wf, step),
2002
1954
  ownerSession: state.owner_session, checkIndex, artifactsRelDir: artifactsRelDirOf(instId),
2003
1955
  // 验证模型优先级链(对齐 opencode resolveVerifierModel):
2004
1956
  // 步骤 check_model > 全局 adversarial_check.model > 发起会话当前模型
@@ -2035,11 +1987,9 @@ export function createEngine(projectDir, ports) {
2035
1987
  : fresh.current_step !== step.id ? "step_changed"
2036
1988
  : "run_superseded";
2037
1989
  log("warn", "verdict_discarded", { instId, reason: why, status: verdict.status, step: step.id, runId });
2038
- stopHeartbeat(instId, runId); // 本笔已作废:心跳没有任何意义了
2039
1990
  dropAbort(instId, controller); // 取消句柄同样作废,避免集合里堆积死句柄
2040
1991
  return;
2041
1992
  }
2042
- stopHeartbeat(instId, runId);
2043
1993
  fresh.delegations = fresh.delegations.filter((d) => d.run_id !== runId);
2044
1994
  fresh.verdicts.push(verdict);
2045
1995
  dropAbort(instId, controller);
@@ -2066,7 +2016,7 @@ export function createEngine(projectDir, ports) {
2066
2016
  // · **全部终态才聚合**:任何单票完成都不碰状态机(多票同时落账会互相覆盖读-改-写);
2067
2017
  // · 聚合优先级 `failed > infra > 全过`(`decideVotingOutcome`)——工作问题绝不被故障遮蔽;
2068
2018
  // · infra **自动重试一次**,只重跑故障票(已通过的保留);重试仍 infra 且无 failed →
2069
- // `check_infra` 暂停(不计失败次数),`/ralphflow-continue` 只重跑未通过的票;
2019
+ // `check_infra` 暂停(不计返工次数),`/ralphflow-continue` 只重跑未通过的票;
2070
2020
  // · 跨轮(DO 返工后重新交卷)**全部重投**:上一轮的票一律不复用(工作已经变了)。
2071
2021
  //
2072
2022
  // 进度不另立文件:每票状态就是 `state.json` 的 `verdicts[]`(终态)+ `delegations[]`(在飞)
@@ -2094,6 +2044,7 @@ export function createEngine(projectDir, ports) {
2094
2044
  try {
2095
2045
  verdict = await ports.verify({
2096
2046
  instId, step, workflow: wf, userTask: effectiveTaskOf(step, state.user_task),
2047
+ assetPath: assetPathOfStep(wf, step),
2097
2048
  ownerSession: state.owner_session, checkIndex: index,
2098
2049
  // 该票的专属检查依据 + 序号:verify.ts 据此生成「你是 N 个之一」的投票提示词。
2099
2050
  voter: { index: index + 1, count, check: entry.check },
@@ -2135,10 +2086,8 @@ export function createEngine(projectDir, ports) {
2135
2086
  : fresh.current_step !== step.id ? "step_changed"
2136
2087
  : "run_superseded";
2137
2088
  log("warn", "verdict_discarded", { instId, reason: why, status: verdict.status, step: step.id, runId, voter: index + 1 });
2138
- stopHeartbeat(instId, runId); // 本笔已作废:心跳没有任何意义了
2139
2089
  return { roundComplete: false };
2140
2090
  }
2141
- stopHeartbeat(instId, runId);
2142
2091
  fresh.delegations = fresh.delegations.filter((d) => d.run_id !== runId);
2143
2092
  fresh.verdicts.push(verdict);
2144
2093
  // 每票一条轨迹。**刻意不用 `verdict_*` 事件名**:报告里的「失败轮数」按 `verdict_failed`
@@ -2193,7 +2142,7 @@ export function createEngine(projectDir, ports) {
2193
2142
  void launchVotingRound(instId, fresh, wf, step, retry, attempt + 1);
2194
2143
  return;
2195
2144
  }
2196
- // 重试仍失败 → 基础设施故障暂停(不计失败次数);continue 只重跑未通过的票。
2145
+ // 重试仍失败 → 基础设施故障暂停(不计返工次数);continue 只重跑未通过的票。
2197
2146
  const reason = formatVotingInfraReason(asVotes, entries, count);
2198
2147
  pushHistory(fresh, "verdict_infra", reason.slice(0, 300), step.id);
2199
2148
  applyRoundOutcome(instId, fresh, wf, step, { kind: "infra", reason }, startedAt);
@@ -2218,16 +2167,14 @@ export function createEngine(projectDir, ports) {
2218
2167
  const runId = `v-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}-${index}`;
2219
2168
  state.delegations.push({
2220
2169
  run_id: runId, check_index: index, attempt, ts: stamp,
2221
- // 属主运行时(诊断)+ 心跳起点(判活的唯一依据):N 票各有独立心跳,
2222
- // 只要还有一笔在刷,别的会话 / 别的沙箱进程就不得把在飞委派当孤儿清掉。
2223
- owner_runtime: runtimeId(), heartbeat_at: Date.now(),
2224
2170
  });
2225
2171
  return { runId, index, controller };
2226
2172
  });
2173
+ // 投票也是「验证中」:属主心跳继续,别让别的 host 把这一轮当孤儿。
2174
+ stampOwner(state);
2175
+ startDriving(instId);
2227
2176
  pushHistory(state, "verify_start", `voters=${indices.map((i) => i + 1).join(",")}/${count}${attempt > 1 ? "(infra 自动重试)" : ""}`, step.id);
2228
2177
  writeState(state, instId);
2229
- for (const r of runs)
2230
- startHeartbeat(instId, r.runId);
2231
2178
  log("info", "verify_start", { instId, step: step.id, voters: indices, count, attempt });
2232
2179
  // 阶段播报:与单 check 同一套「正在发生什么 / 要不要你操作 / 去哪看进度」,
2233
2180
  // 只把「一个验证者」换成「N 个验证者并行」这层事实。**依旧绝不给时长预估**。
@@ -2300,7 +2247,6 @@ export function createEngine(projectDir, ports) {
2300
2247
  }
2301
2248
  state.do_submitted = false;
2302
2249
  state.verdicts = [];
2303
- stopHeartbeatsOf(instId, state.delegations);
2304
2250
  state.delegations = [];
2305
2251
  if (target.id !== step.id) {
2306
2252
  state.current_step = target.id;
@@ -2352,7 +2298,6 @@ export function createEngine(projectDir, ports) {
2352
2298
  state.current_step = next.id;
2353
2299
  state.do_submitted = false;
2354
2300
  state.verdicts = [];
2355
- stopHeartbeatsOf(instId, state.delegations);
2356
2301
  state.delegations = [];
2357
2302
  state.last_submit_summary = undefined;
2358
2303
  // 不在这里清 fail_counts:通过时已 `clearFailCount`(该步失败史了结)。
@@ -2495,7 +2440,7 @@ export function createEngine(projectDir, ports) {
2495
2440
  }
2496
2441
  catch { /* 读不到就退回通用说法 */ }
2497
2442
  return {
2498
- text: `[ralphflow] 你执行了 \`/ralphflow-reset\`,但**这次重置没有生效**:${why}。\n\n重置只换干净上下文(失败计数原样保留),且只能落在**当前步 DO 阶段的空闲窗口**里 —— 否则会打断在飞验证、把已有判定变成孤儿。用 \`/ralphflow-status\` 看进度;等本步失败返工、或进入下一步的 DO 之后,再执行一次 \`/ralphflow-reset\`。`,
2443
+ text: `[ralphflow] 你执行了 \`/ralphflow-reset\`,但**这次重置没有生效**:${why}。\n\n重置只换干净上下文(返工计数原样保留),且只能落在**当前步 DO 阶段的空闲窗口**里 —— 否则会打断在飞验证、把已有判定变成孤儿。用 \`/ralphflow-status\` 看进度;等本步返工、或进入下一步的 DO 之后,再执行一次 \`/ralphflow-reset\`。`,
2499
2444
  summary: `⚠️ /ralphflow-reset 未生效:${why}`,
2500
2445
  };
2501
2446
  }
@@ -2541,7 +2486,7 @@ export function createEngine(projectDir, ports) {
2541
2486
  notice: trigger === "manual"
2542
2487
  ? {
2543
2488
  summary: `♻️ 已按 /ralphflow-reset 重置上下文,重投步骤 ${step.id} 的 DO`,
2544
- text: `[ralphflow] 用户执行了 \`/ralphflow-reset\`:当前步(\`${step.id}\`)的上下文已整段替换为一条交接稿,本步 DO 随即重投。此前对话已移出模型上下文;**失败计数原样保留**(重置只换干净上下文,不赦免失败)。本行是给用户看的可见告知——替换节点在 Chat 里不显示,模型上下文里也没有这条告知。`,
2489
+ text: `[ralphflow] 用户执行了 \`/ralphflow-reset\`:当前步(\`${step.id}\`)的上下文已整段替换为一条交接稿,本步 DO 随即重投。此前对话已移出模型上下文;**返工计数原样保留**(重置只换干净上下文,不赦免失败)。本行是给用户看的可见告知——替换节点在 Chat 里不显示,模型上下文里也没有这条告知。`,
2545
2490
  }
2546
2491
  : trigger === "rewind"
2547
2492
  ? {
@@ -2583,6 +2528,8 @@ export function createEngine(projectDir, ports) {
2583
2528
  * 重置绝不被说成「本步标了 `reset: true`」(作者没标)。
2584
2529
  */
2585
2530
  function deliverStepDo(state, instId, wf, step, summary, rework, opts) {
2531
+ // 新的 DO 开始 = 实例重新需要属主(可能刚从审查门/暂停回来,心跳曾被定时器丢弃)。
2532
+ startDriving(instId);
2586
2533
  const text = doPrompt(instId, wf, state, step, rework, opts?.rewind);
2587
2534
  const sid = state.owner_session;
2588
2535
  const trigger = opts?.rewind ? "rewind" : opts?.manual ? "manual" : resetCauseOf(wf, step);
@@ -2614,14 +2561,14 @@ export function createEngine(projectDir, ports) {
2614
2561
  const stillLive = () => {
2615
2562
  try {
2616
2563
  const cur = readState(instId);
2617
- return !!cur && cur.active === true && cur.current_step === step.id && cur.do_submitted === false;
2564
+ return !!cur && cur.active === true && cur.current_step === step.id && cur.do_submitted === false && cur.paused === false;
2618
2565
  }
2619
2566
  catch {
2620
2567
  return false;
2621
2568
  }
2622
2569
  };
2623
2570
  req.canProceed = stillLive; // 载体在 append 之前同步复查一次(关掉「等窗口期间被取消」的竞态)
2624
- // 从这一刻起「本步 DO 还没送达」——期间 turn-stopping 的「忘了交卷」提醒必须闭嘴
2571
+ // 从这一刻起「本步 DO 还没送达」——期间 turn-stopping 的回合收尾提醒必须闭嘴
2625
2572
  pendingDoDelivery.add(instId);
2626
2573
  publishStatus();
2627
2574
  const releasePending = () => { pendingDoDelivery.delete(instId); publishStatus(); };
@@ -2669,7 +2616,7 @@ export function createEngine(projectDir, ports) {
2669
2616
  return stepStats(state.history, state.fail_counts, endTs);
2670
2617
  }
2671
2618
  /**
2672
- * 归档最终报告到 `<workspace>/.dsh/ralph-flow/reports/<instId>.md`。
2619
+ * 归档最终报告到 `<项目根>/.dsh/ralph-flow/reports/<instId>.md`。
2673
2620
  *
2674
2621
  * 返回**绝对路径**;写失败返回 `null`(**绝不吞掉失败**):调用方
2675
2622
  * {@link destroyInstance} 依赖这个 `null` 决定「不销毁实例」——宁可留一个
@@ -2705,7 +2652,7 @@ export function createEngine(projectDir, ports) {
2705
2652
  "## 步骤耗时与重试",
2706
2653
  "",
2707
2654
  ...(stats.length > 0
2708
- ? stats.map((d) => `- \`${d.step}\`:耗时 ${formatDuration(d.ms)} · 失败 ${d.retries} 轮`)
2655
+ ? stats.map((d) => `- \`${d.step}\`:耗时 ${formatDuration(d.ms)} · 返工 ${d.retries} 轮`)
2709
2656
  : ["- (无步骤记录)"]),
2710
2657
  "",
2711
2658
  "## 轨迹",
@@ -2734,10 +2681,8 @@ export function createEngine(projectDir, ports) {
2734
2681
  * 否则部分删除失败(Windows EBUSY 等)会留下一个「列表里看不到、磁盘上还在」的幽灵;
2735
2682
  * 反过来先除名,实例在任何失败下都不会复活成幽灵。
2736
2683
  *
2737
- * **路径必须在除名之前解析并固定**(曾经的缺陷):早期 `instanceDir()` / `statePath()` 都经
2738
- * `workspaceOf(instId) = registry[instId] ?? projectDir`,先除名会让它们回落到引擎的
2739
- * `projectDir`,跨工作区时删除静默打空(报告有了、目录还在)。索引已随「引擎按工作区
2740
- * 实例化」一并删除,路径现在由单根目录直接给出;「先解析、后动手」的顺序仍保留。
2684
+ * **路径必须在除名之前解析并固定**:实例目录与状态路径都从单根目录直接给出;
2685
+ * 先除名再解析路径会让删除落到错误的工作区,留下「报告有了、目录还在」。
2741
2686
  *
2742
2687
  * 返回 `{ reportPath, instanceDirRemoved }`;归档失败返回 `null` 且**不销毁**
2743
2688
  * (见不变量 3 与边界 2)。`state` 缺省从磁盘读;调用方(complete/cancel)传内存里的 state,
@@ -2813,10 +2758,7 @@ export function createEngine(projectDir, ports) {
2813
2758
  if (mine) {
2814
2759
  return { ok: false, text: `当前会话已有活跃实例 \`${mine.id}\`(${mine.state.workflow_name} · ${mine.state.current_step})。用 \`/ralphflow-continue\` 继续,或 \`/ralphflow-cancel\` 取消。` };
2815
2760
  }
2816
- try {
2817
- ensureLayout();
2818
- }
2819
- catch { }
2761
+ ensureLayout();
2820
2762
  const { def: wf, problems, warnings } = loadWorkflow(workflowName.trim());
2821
2763
  if (!wf)
2822
2764
  return { ok: false, text: `工作流 \`${workflowName}\` 无法启动:\n${problems.map((p) => `- ${p}`).join("\n")}` };
@@ -2832,8 +2774,10 @@ export function createEngine(projectDir, ports) {
2832
2774
  delegations: [], verdicts: [], history: [], started_at: now, updated_at: now,
2833
2775
  artifacts_dir_name: artifactsDirName,
2834
2776
  };
2777
+ stampOwner(state);
2835
2778
  pushHistory(state, "start", `workflow=${wf.name}`, first.id);
2836
2779
  writeState(state, instId);
2780
+ startDriving(instId);
2837
2781
  // 执行日志:启动 + 首步 step_start(首步也给 step_start,机器才能只靠该事件枚举步骤)
2838
2782
  logEvent(instId, "info", "start", { workflow: wf.name, step: first.id });
2839
2783
  logEvent(instId, "info", "step_start", { step: first.id, index: 1 });
@@ -2907,7 +2851,41 @@ export function createEngine(projectDir, ports) {
2907
2851
  * 返回 ToolResult:把「已受理 / 不能重复交卷 / 没有活跃实例」直接回给模型,
2908
2852
  * 而不是像文本标记那样静默失败。
2909
2853
  */
2910
- function onSubmit(sessionId, summary) {
2854
+ /** 进度记录的 detail 形状;`lastCheckpointOf` 按同一形状读回条数(两个函数放在一起,改一处就够)。 */
2855
+ function checkpointDetail(items) {
2856
+ return `未完成 ${items.length} 项:${items.join(";")}`;
2857
+ }
2858
+ /**
2859
+ * 本步最近的「报进度」(`submit_incomplete`):本轮仍是 DO 阶段、且最后一条记录之后
2860
+ * 没有重新进入本步(step_start / 返工 / 恢复 / 已交卷)。只用来换催促的口径,不参与判定。
2861
+ *
2862
+ * 同时带回**条目原文**:上下文被压缩后,光说「还有 3 项」等于没说 —— 催促消息必须
2863
+ * 能独立恢复出"到底还剩什么"。
2864
+ */
2865
+ function lastCheckpointOf(state, stepId) {
2866
+ const boundaries = new Set(["step_start", "rework_rewind", "resume", "do_submitted"]);
2867
+ let from = -1;
2868
+ let entry = -1;
2869
+ for (let i = 0; i < state.history.length; i++) {
2870
+ const h = state.history[i];
2871
+ if (h.step !== stepId)
2872
+ continue;
2873
+ if (boundaries.has(h.event))
2874
+ from = i;
2875
+ if (h.event === "submit_incomplete")
2876
+ entry = i;
2877
+ }
2878
+ if (entry <= from)
2879
+ return null;
2880
+ const detail = state.history[entry]?.detail ?? "";
2881
+ const count = Number(/^未完成 (\d+) 项/.exec(detail)?.[1] ?? 0);
2882
+ if (count <= 0)
2883
+ return null;
2884
+ const raw = detail.replace(/^未完成 \d+ 项:/, "");
2885
+ const items = raw ? raw.split(";").map((item) => item.trim()).filter(Boolean) : [];
2886
+ return { count, items };
2887
+ }
2888
+ function onSubmit(sessionId, summary, unfinished) {
2911
2889
  const info = activeInstanceOfSession(sessionId);
2912
2890
  if (!info) {
2913
2891
  const others = listInstances().filter((i) => i.state.active);
@@ -2920,7 +2898,7 @@ export function createEngine(projectDir, ports) {
2920
2898
  }
2921
2899
  const { id: instId, state } = info;
2922
2900
  if (state.paused) {
2923
- return { ok: false, text: `实例 \`${instId}\` 处于暂停状态(${state.pause_reason}),交卷未被受理。先按提示处理,再用 \`/ralphflow-continue\` 恢复。` };
2901
+ return { ok: false, text: `实例 \`${instId}\` 处于暂停状态(${pauseLabel(state.pause_reason)}),交卷未被受理。先按提示处理,再用 \`/ralphflow-continue\` 恢复。` };
2924
2902
  }
2925
2903
  const { def: wf } = loadWorkflow(state.workflow_name);
2926
2904
  if (!wf) {
@@ -2930,6 +2908,24 @@ export function createEngine(projectDir, ports) {
2930
2908
  const step = stepOf(wf, state.current_step);
2931
2909
  if (!step)
2932
2910
  return { ok: false, text: `实例状态损坏:当前步骤 \`${state.current_step}\` 不在工作流里。用 \`/ralphflow-cancel\` 结束。` };
2911
+ // 未完成项非空 = 本轮进度记录,**不是**完成声明:不设 do_submitted、不委派验证者、不占返工预算。
2912
+ // 这一条是「没做完就先交卷」的机械闸门:模型自己知道还剩什么,把它的自述变成引擎可执行的判断。
2913
+ const remaining = normalizeUnfinished(unfinished);
2914
+ if (!state.do_submitted && remaining.length > 0) {
2915
+ pushHistory(state, "submit_incomplete", checkpointDetail(remaining), step.id);
2916
+ writeState(state, instId);
2917
+ logEvent(instId, "info", "submit_incomplete", { step: step.id, count: remaining.length });
2918
+ // 进度记录也是一次动作(见 noteAction 的注释):宿主把 ralphflow_submit 排除在
2919
+ // 「在干活」之外,引擎在这里补记自己受理过的那一次。
2920
+ try {
2921
+ ports.noteAction?.(sessionId, Date.now());
2922
+ }
2923
+ catch { }
2924
+ return {
2925
+ ok: true,
2926
+ text: `已记下这轮进度:本步还有 ${remaining.length} 项没完成。\n\n${remaining.map((item) => `- ${item}`).join("\n")}\n\n继续做这些;做完后再交卷。\n需要我决定的事:调用 \`ask_user_question\`。`,
2927
+ };
2928
+ }
2933
2929
  const text = (summary ?? noteTextFor(sessionId) ?? "").slice(-4000).trim();
2934
2930
  if (state.do_submitted) {
2935
2931
  // 本步已交卷。区分「门上改稿重交」与「重复交卷」:
@@ -2974,9 +2970,7 @@ export function createEngine(projectDir, ports) {
2974
2970
  }
2975
2971
  writeState(state, instId);
2976
2972
  void launchVerification(instId, state, wf, step);
2977
- return { ok: true, text: voterCountOf(step) > 0
2978
- ? `🔍 已受理重新交卷,正在重新委派 ${voterCountOf(step)} 个独立验证者并行检查步骤 \`${step.id}\`(全过才放行)。`
2979
- : `🔍 已受理重新交卷,正在重新委派独立验证者检查步骤 \`${step.id}\`。` };
2973
+ return { ok: true, text: "🔍 已受理重新交卷,本轮结束;不要重复交卷。" };
2980
2974
  }
2981
2975
  state.do_submitted = true;
2982
2976
  state.last_submit_summary = text;
@@ -2993,9 +2987,7 @@ export function createEngine(projectDir, ports) {
2993
2987
  }
2994
2988
  writeState(state, instId);
2995
2989
  void launchVerification(instId, state, wf, step);
2996
- return { ok: true, text: voterCountOf(step) > 0
2997
- ? `🔍 交卷已受理,${voterCountOf(step)} 个独立验证者(独立会话)正在并行取证判定,全过才放行。等它们返回即可,不要重复交卷。`
2998
- : `🔍 交卷已受理,独立验证者(独立会话)正在取证判定。等它返回即可,不要重复交卷。` };
2990
+ return { ok: true, text: "🔍 交卷已受理,本轮结束;不要重复交卷。" };
2999
2991
  }
3000
2992
  // ─── 交卷上下文捕获(**只**服务审查门重交去重;不落盘、不触发任何状态迁移)──────
3001
2993
  /**
@@ -3021,24 +3013,18 @@ export function createEngine(projectDir, ports) {
3021
3013
  function noteTextFor(sessionId) {
3022
3014
  return lastText.get(sessionId);
3023
3015
  }
3024
- // ─── DO 阶段「忘了交卷」兜底(原生 agent/turn-stopping 驱动)─────────────────
3025
- /**
3026
- * 回合即将关闭时的判定:该不该提醒模型交卷。
3027
- *
3028
- * 文本标记时代这件事是静默的(模型忘了写标记 → 什么都没发生)。
3029
- * 这里由原生 `agent/turn-stopping`(serial、可 await)在回合关闭前发问:
3030
- * 有活跃实例、本步未交卷、未暂停、无在飞委派 → 模型干完了却没交卷。
3031
- *
3032
- * 提醒次数从 history 派生(不新增状态字段,宪法 §10.4);达到上限则暂停等用户,
3033
- * 绝不死循环催促。
3034
- *
3035
- * **次数按「本次进入该步」起算**:`step_start` 就是那条边界(回退也会记一条)。
3036
- * 若统计整段 history,回退到一个已经用光提醒预算的步骤会**立刻** `no_submit` 暂停 ——
3037
- * 用户刚换了方向,工作流却一步没跑就停下。同理,返工(`rework_rewind` 换步、
3038
- * `do_submitted` 开启本步新一轮)与 `/ralphflow-continue` 恢复(`resume` 后重投 DO)
3039
- * 也都是新一轮的边界;只有**同一轮里**的提醒才累积。
3040
- */
3041
- function submitReminderCount(state, stepId) {
3016
+ // ─── 回合收尾检查(原生 agent/turn-stopping 驱动)──────────────────────────
3017
+ //
3018
+ // 它问的是「还有没有剩余事项」,不是「你怎么还没交卷」:
3019
+ // 没有剩余 → 交卷;还有剩余 → 接着做;在等用户 → 直说。
3020
+ // 目标驱动(goal-round-driver)判定「做完没做完」的方式也是模型自报,没有独立评估器;
3021
+ // 我们不需要接它 —— 交卷之后由独立验证者判定,比自报更强。
3022
+ function reminderStateOf(state, stepId, lastActionAt) {
3023
+ // **次数按「本次进入该步」起算**:`step_start` 就是那条边界(回退也会记一条)。
3024
+ // 若统计整段 history,回退到一个已经连续空过两次的步骤会**立刻** `no_submit` 暂停 ——
3025
+ // 用户刚换了方向,工作流却一步没跑就停下。同理,返工(`rework_rewind` 换步、
3026
+ // `do_submitted` 开启本步新一轮)与 `/ralphflow-continue` 恢复(`resume` 后重投 DO)
3027
+ // 也都是新一轮的边界;只有**同一轮里**的提醒才累积。
3042
3028
  const boundaries = new Set(["step_start", "rework_rewind", "do_submitted", "resume"]);
3043
3029
  let from = -1;
3044
3030
  for (let i = 0; i < state.history.length; i++) {
@@ -3046,20 +3032,61 @@ export function createEngine(projectDir, ports) {
3046
3032
  if (h.step === stepId && boundaries.has(h.event))
3047
3033
  from = i;
3048
3034
  }
3049
- let n = 0;
3035
+ // 连续空回合(从 history 派生,不新增落盘字段):`submit_reminder` 加一,
3036
+ // 一条有动作的 `submit_activity` 清零。只关心「最近连续几次没干活」,
3037
+ // 不关心历史总次数 —— 总次数会把干活的轮也算进去,反而让单次停顿被误暂停。
3038
+ let stalls = 0;
3039
+ let last = -1;
3050
3040
  for (let i = from + 1; i < state.history.length; i++) {
3051
3041
  const h = state.history[i];
3052
- if (h.event === "submit_reminder" && h.step === stepId)
3053
- n++;
3042
+ if (h.step !== stepId)
3043
+ continue;
3044
+ if (h.event === "submit_activity") {
3045
+ stalls = 0;
3046
+ last = i;
3047
+ }
3048
+ else if (h.event === "submit_reminder") {
3049
+ stalls++;
3050
+ last = i;
3051
+ }
3054
3052
  }
3055
- return n;
3053
+ const anchor = last >= 0 ? state.history[last].ts : from >= 0 ? state.history[from].ts : undefined;
3054
+ const anchorMs = anchor ? Date.parse(anchor) : Number.NaN;
3055
+ const worked = lastActionAt !== undefined && Number.isFinite(anchorMs) && lastActionAt > anchorMs;
3056
+ return { stalls, worked };
3057
+ }
3058
+ /** 把 history 里的 rewind detail(`from → step:reason`)还原成 doPrompt 需要的形状。 */
3059
+ function rewindOf(detail) {
3060
+ const cut = detail.indexOf(":");
3061
+ const head = cut >= 0 ? detail.slice(0, cut) : detail;
3062
+ const reason = cut >= 0 ? detail.slice(cut + 1).trim() : "";
3063
+ const arrow = head.indexOf(" → ");
3064
+ return { from: arrow >= 0 ? head.slice(0, arrow).trim() : head.trim(), reason };
3065
+ }
3066
+ /**
3067
+ * 无 `check` / `check_voting` 时,提醒与 continue 要如实写明的「跳过验证」说明。
3068
+ * DO 本身不写(`rewind` 契约:DO 只讲任务);但「模型每一轮都会重新读到的通道」
3069
+ * 必须说清,否则它会误以为交卷后会启动验证者。
3070
+ */
3071
+ function verificationNoteOf(wf, step) {
3072
+ if (stepHasVerification(step))
3073
+ return "";
3074
+ return `\n\n## 验证方式\n本步不配置对抗性检查:${isGate(wf, step) ? "交卷后停在审查门等用户放行(跳过对抗性验证)。" : "交卷后跳过对抗性验证。"}`;
3056
3075
  }
3076
+ /**
3077
+ * 回合收尾检查:**每一轮都投递同一份 doPrompt**。
3078
+ *
3079
+ * 旧实现给提醒单独写了一份「回顾 + 催办」的短卡,省 token;实测同一模型在完整 DO 下
3080
+ * 做 93/140 次工具调用,在短卡下只做 3 次 —— 轮长由入口决定,不是任务决定的。
3081
+ * 现在 start(工具结果)、continue(重投)、提醒(turn-stopping)都走 doPrompt:
3082
+ * 任务、验收依据、产出目录、交付物、交卷方式逐字相同,只有「本轮清单」和开头一行状态不同。
3083
+ */
3057
3084
  function remindToSubmit(sessionId) {
3058
3085
  const info = activeInstanceOfSession(sessionId);
3059
3086
  if (!info)
3060
3087
  return { remind: false };
3061
3088
  const { id: instId, state } = info;
3062
- // 本步的 DO 还没送达(`reset: true` 的步骤要等空闲窗口做完替换才投递):此刻催交卷是**错的**
3089
+ // 本步的 DO 还没送达(`reset: true` 的步骤要等空闲窗口做完替换才投递):此刻提醒是**错的**
3063
3090
  // —— 模型还不知道这一步存在。不拦的话,两轮提醒后会把实例暂停(pause_reason=no_submit),
3064
3091
  // 而 DO 随后落在一个已暂停的实例上(第二轮验证者 2/4 实测)。
3065
3092
  if (pendingDoDelivery.has(instId))
@@ -3070,38 +3097,80 @@ export function createEngine(projectDir, ports) {
3070
3097
  const step = wf ? stepOf(wf, state.current_step) : undefined;
3071
3098
  if (!wf || !step)
3072
3099
  return { remind: false };
3073
- const max = 2;
3074
- const used = submitReminderCount(state, step.id);
3075
- if (used >= max) {
3076
- // 反复提醒仍不交卷 → 停下来让用户处理,不再自动催(避免死循环)
3100
+ const { stalls, worked } = reminderStateOf(state, step.id, ports.lastActionAt?.(sessionId));
3101
+ // 连续空回合到上限才暂停:模型中途干过活,连续计数就被打破,
3102
+ // 不该因为「历史上有过两次空回合」在它回来干活的这一轮把它停掉。
3103
+ const stalledOut = !worked && stalls >= SUBMIT_REMINDER_STALL_LIMIT;
3104
+ if (stalledOut) {
3105
+ // 不是交卷次数上限,也不是「提醒总次数到顶」:只是连续几个回合一个工具都没调用。
3106
+ const emptyRounds = stalls + 1;
3107
+ const why = `连续 ${emptyRounds} 个回合没有调用任何工具`;
3077
3108
  state.paused = true;
3078
3109
  state.pause_reason = "no_submit";
3079
- pushHistory(state, "reminder_exhausted", `${used} 次提醒后仍未交卷`, step.id);
3080
- logPause(instId, state, "no_submit", { used, max });
3110
+ pushHistory(state, "reminder_exhausted", why, step.id);
3111
+ logPause(instId, state, "no_submit", { emptyRounds });
3081
3112
  writeState(state, instId);
3082
- log("warn", "submit_reminder_exhausted", { instId, step: step.id, used });
3113
+ log("warn", "submit_reminder_exhausted", { instId, step: step.id, emptyRounds });
3083
3114
  return {
3084
3115
  remind: false,
3085
- summary: `⏸ 步骤 ${step.id} 反复未交卷,已暂停等你处理`,
3086
- message: `⏸ 步骤 \`${step.id}\` 已提醒 ${used} 次仍未收到交卷,已暂停等你处理。\n\n如果工作其实做完了:先用 \`/ralphflow-continue\` 恢复,再让模型调用 \`ralphflow_submit\` 交卷。\n如果它卡住了:说明情况或 \`/ralphflow-cancel\` 结束。`,
3116
+ summary: `⏸ 步骤 ${step.id} 已暂停:${why}`,
3117
+ message: `⏸ 步骤 \`${step.id}\` 已暂停等你处理。\n\n${why}。\n\n- \`/ralphflow-continue\` 会清零连续计数,然后重新投递本步任务书。\n- \`ralphflow_submit\` 没有次数上限;这里暂停只因为连续没有动作。\n- 它其实做完了:continue 后让它交卷(\`unfinished\` 留空)。\n- 它在等你:先回复它要的信息,再 continue。\n- 它卡住了:\`/ralphflow-cancel\` 结束。`,
3087
3118
  };
3088
3119
  }
3089
- pushHistory(state, "submit_reminder", `第 ${used + 1} 次`, step.id);
3120
+ // 上次提醒之后有工具调用 = 模型在干活:不累计空回合,只记一条「有动作」的提醒。
3121
+ pushHistory(state, worked ? "submit_activity" : "submit_reminder", worked ? "有动作" : `第 ${stalls + 1}/${SUBMIT_REMINDER_STALL_LIMIT} 次连续无工具回合`, step.id);
3090
3122
  writeState(state, instId);
3091
- const n = used + 1;
3092
- // 诚实标注:无检查依据的步骤本就不验证,不能说「独立验证不会自动开始」(那是另一回事);
3093
- // 门步还要说清「停在审查门等用户放行」,不能写成「直接继续」(与 doPrompt 同一口径)。
3094
- const noSubmitReason = stepHasVerification(step)
3095
- ? "独立验证不会自动开始"
3096
- : isGate(wf, step)
3097
- ? "本步是纯人工审查门(未配置 `check` / `check_voting`):交卷后**跳过对抗性验证**,停在审查门等用户放行"
3098
- : "工作流不会推进(本步未配置 `check` / `check_voting`,交卷后跳过对抗性验证直接继续)";
3123
+ const head = worked
3124
+ ? `[ralphflow] 提醒:本轮继续,本步(\`${step.id}\`)还没结束。`
3125
+ : `[ralphflow] 提醒(第 ${stalls + 1}/${SUBMIT_REMINDER_STALL_LIMIT} 次连续无工具回合):本步(\`${step.id}\`)还没结束,上一轮没有调用任何工具。需要用户决定就调用 \`ask_user_question\`;否则继续做本轮清单。`;
3126
+ // 每一轮都拿同一份任务书:start 的工具结果、continue 的重投、这里的提醒都走 doPrompt。
3127
+ // 旧 stepRecap 是「催办 + 回顾」;实测同一模型在完整 DO 下做 93/140 次工具调用,
3128
+ // 在回顾下只做 3 次 —— 轮长由入口决定,不是任务决定的。统一成完整 DO 才能让每轮同形。
3129
+ const checkpoint = lastCheckpointOf(state, step.id);
3130
+ const failed = state.verdicts.filter((verdict) => verdict.step_id === step.id && verdict.status === "failed");
3131
+ const rework = failed.length > 0
3132
+ ? failed.map((verdict) => `- ${verdict.reason.trim() || "(未给出原因)"}`).join("\n")
3133
+ : undefined;
3134
+ const rewindEvent = [...state.history].reverse().find((h) => h.event === "rewind" && h.step === step.id);
3135
+ const brief = doPrompt(instId, wf, state, step, rework, rewindEvent ? rewindOf(rewindEvent.detail ?? "") : undefined, checkpoint ?? undefined);
3136
+ // 无 check / check_voting 的步骤:提醒要如实写明跳过验证。
3137
+ // DO 本身不写(`rewind` 契约要求 DO 只讲任务);提醒是模型每轮重新读到的通道,
3138
+ // 不能让它误以为交卷后会启动验证者。
3139
+ const verificationNote = verificationNoteOf(wf, step);
3099
3140
  return {
3100
3141
  remind: true,
3101
- summary: `⚠️ 步骤 ${step.id} 尚未交卷(第 ${n}/${max} 次提醒)`,
3102
- message: `[ralphflow] 提醒(第 ${n}/${max} 次):本步(\`${step.id}\`)还没交卷,${noSubmitReason}。\n\n如果任务已完成,请调用 \`ralphflow_submit\` 工具交卷;如果还没做完,继续做。\n如果你正在等用户回答或需要用户介入,请直接说明,不必交卷。`,
3142
+ summary: worked
3143
+ ? `▶️ 步骤 ${step.id} 还没结束:本轮任务书`
3144
+ : `▶️ 步骤 ${step.id} 还没结束:本轮任务书(连续 ${stalls + 1} 个回合没有工具调用)`,
3145
+ message: `${head}\n\n${brief}${verificationNote}`,
3103
3146
  };
3104
3147
  }
3148
+ /**
3149
+ * 用户点停止按钮(宿主把当前回合 cancel 成 `turn/end { kind:"aborted", reason:{kind:"user"} }`):
3150
+ * 把实例转成 `paused(user_stop)`。
3151
+ *
3152
+ * 只在 **DO 阶段**生效:已交卷 = 验证在飞 / 停在审查门,停止回合不该打断验证。
3153
+ * 暂停是**意图**,先落盘、再由调用方释放所有权(心跳/锁),顺序不能反 —— 先放所有权
3154
+ * 会让别的 host 把"在飞 + 无主"误判成中断。
3155
+ */
3156
+ function pauseForUserStop(sessionId) {
3157
+ const info = activeInstanceOfSession(sessionId);
3158
+ if (!info)
3159
+ return { ok: false, text: "当前会话没有活跃的 Flow 实例,不需要暂停。" };
3160
+ const { id: instId, state } = info;
3161
+ if (state.paused)
3162
+ return { ok: false, text: `实例 \`${instId}\` 已经暂停。` };
3163
+ if (state.do_submitted) {
3164
+ return { ok: false, text: `步骤 \`${state.current_step}\` 已交卷;停止回合不会打断验证或审查门。` };
3165
+ }
3166
+ state.paused = true;
3167
+ state.pause_reason = "user_stop";
3168
+ pushHistory(state, "pause", `step=${state.current_step}`, state.current_step);
3169
+ logPause(instId, state, "user_stop", { step: state.current_step });
3170
+ writeState(state, instId);
3171
+ notify(state, `⏸ 已暂停:你停止了运行。用 \`/ralphflow-continue\` 继续步骤 \`${state.current_step}\`,或 \`/ralphflow-cancel\` 结束。`, "⏸ 已暂停:你停止了运行");
3172
+ return { ok: true, text: `实例 \`${instId}\` 已暂停(你停止了运行)。` };
3173
+ }
3105
3174
  /**
3106
3175
  * 三时刻③:推进的唯一人工入口(fail-closed)。
3107
3176
  *
@@ -3156,21 +3225,32 @@ export function createEngine(projectDir, ports) {
3156
3225
  const step = stepOf(wf, state.current_step);
3157
3226
  if (!step)
3158
3227
  return { ok: false, text: `实例状态损坏:当前步骤 \`${state.current_step}\` 不在工作流里。用 \`/ralphflow-cancel\` 结束。` };
3228
+ // 属主已失联、但复查还没落盘:用户显式 continue 就是最快的恢复入口,按中断处理。
3229
+ if (!state.paused && needsOwner(state) && !ownerAlive(state)) {
3230
+ state.paused = true;
3231
+ state.pause_reason = "host_restarted";
3232
+ state.delegations = [];
3233
+ pushHistory(state, "interrupted", "owner_heartbeat_stale", state.current_step);
3234
+ writeState(state, instId);
3235
+ }
3159
3236
  // ① 暂停中 → 解除暂停
3160
3237
  if (state.paused) {
3161
3238
  const reason = state.pause_reason;
3162
3239
  // 投票步的 `check_infra` 恢复:**已通过的票保留**,只重跑未出终态的票
3163
3240
  // (照抄 opencode §5.3「continue 把 infra_failed 重置为 pending,passed 不动」)。
3164
3241
  // 其它情形(max_failures / no_submit / 非投票步)保持原语义:清空判定重新验证。
3165
- const resumeVoting = voterCountOf(step) > 0 && reason === "check_infra" && state.do_submitted;
3242
+ // `host_restarted` 与 `check_infra` 同形:已通过的票是盘上的事实,保留;只重跑没出终态的票。
3243
+ const resumeVoting = voterCountOf(step) > 0 && (reason === "check_infra" || reason === "host_restarted") && state.do_submitted;
3166
3244
  const keptVerdicts = resumeVoting
3167
3245
  ? state.verdicts.filter((v) => verdictBelongsToStep(v, step.id) && v.status === "passed")
3168
3246
  : [];
3169
3247
  state.paused = false;
3170
3248
  state.pause_reason = undefined;
3171
3249
  state.verdicts = keptVerdicts;
3172
- stopHeartbeatsOf(instId, state.delegations);
3173
3250
  state.delegations = [];
3251
+ // 恢复 = 本运行时重新成为属主:心跳立刻刷新,别让别的 host 的复查把刚恢复的实例再判死。
3252
+ stampOwner(state);
3253
+ startDriving(instId);
3174
3254
  // 重置当前步失败计数:这是投递给模型的机制说明(tools.ts / SHARED_MECHANISM)明确承诺的
3175
3255
  // 「重置失败计数并重试」。不清零的话,max_failures 恢复后只要再失败一次就立刻二次暂停,
3176
3256
  // 用户永远拿不到「修好→重试」的机会。
@@ -3185,8 +3265,8 @@ export function createEngine(projectDir, ports) {
3185
3265
  return {
3186
3266
  ok: true,
3187
3267
  text: atGate
3188
- ? `▶️ 已解除暂停(原因:${reason})。步骤 \`${step.id}\` 未配置 \`check\`/\`check_voting\`,已跳过对抗性验证,停在审查门等你放行。`
3189
- : `▶️ 已解除暂停(原因:${reason})。步骤 \`${step.id}\` 未配置 \`check\`/\`check_voting\`,已跳过对抗性验证,直接进入下一步。`,
3268
+ ? `▶️ 已解除暂停(原因:${pauseLabel(reason)})。步骤 \`${step.id}\` 未配置 \`check\`/\`check_voting\`,已跳过对抗性验证,停在审查门等你放行。`
3269
+ : `▶️ 已解除暂停(原因:${pauseLabel(reason)})。步骤 \`${step.id}\` 未配置 \`check\`/\`check_voting\`,已跳过对抗性验证,直接进入下一步。`,
3190
3270
  };
3191
3271
  }
3192
3272
  if (resumeVoting) {
@@ -3196,27 +3276,27 @@ export function createEngine(projectDir, ports) {
3196
3276
  // 防御性:全部票都已在手却停在 check_infra(不该发生)→ 按已通过处理,绝不死循环。
3197
3277
  const votes = keptVerdicts.map((v) => ({ index: v.check_index, status: v.status, reason: v.reason }));
3198
3278
  applyRoundOutcome(instId, state, wf, step, { kind: "passed", reason: formatVotingPassReason(votes, step.check_voting ?? [], voterCountOf(step)) }, Date.now());
3199
- return { ok: true, text: `▶️ 已解除暂停(原因:${reason}):步骤 \`${step.id}\` 的判定已全部通过,已推进。` };
3279
+ return { ok: true, text: `▶️ 已解除暂停(原因:${pauseLabel(reason)}):步骤 \`${step.id}\` 的判定已全部通过,已推进。` };
3200
3280
  }
3201
3281
  // 重试预算随用户 continue **重置**(新的一次赦免):再故障仍会自动重试一次。
3202
3282
  void launchVotingRound(instId, state, wf, step, pending, 1);
3203
- return { ok: true, text: `▶️ 已解除暂停(原因:${reason}):保留已通过的 ${done.size} 票,正在重新验证其余 ${pending.length} 票(基础设施故障不计失败)。` };
3283
+ return { ok: true, text: `▶️ 已解除暂停(原因:${pauseLabel(reason)}):保留已通过的 ${done.size} 票,正在重新验证其余 ${pending.length} 票(基础设施故障不计失败)。` };
3204
3284
  }
3205
3285
  void launchVerification(instId, state, wf, step);
3206
- return { ok: true, text: `▶️ 已解除暂停(原因:${reason}),正在重新委派独立验证者检查步骤 \`${step.id}\`。` };
3286
+ return { ok: true, text: `▶️ 已解除暂停(原因:${pauseLabel(reason)}),正在重新委派独立验证者检查步骤 \`${step.id}\`。` };
3207
3287
  }
3208
- deliverDirective(state, doPrompt(instId, wf, state, step), `▶️ 步骤 ${step.id} 继续执行`);
3209
- return { ok: true, text: `▶️ 已解除暂停(原因:${reason}),已让模型继续步骤 \`${step.id}\`。` };
3288
+ const checkpoint = lastCheckpointOf(state, step.id);
3289
+ deliverDirective(state, doPrompt(instId, wf, state, step, undefined, undefined, checkpoint ?? undefined) + verificationNoteOf(wf, step), `▶️ 步骤 ${step.id} 继续执行`);
3290
+ return { ok: true, text: `▶️ 已解除暂停(原因:${pauseLabel(reason)}),已让模型继续步骤 \`${step.id}\`。` };
3210
3291
  }
3211
3292
  // ② 有在飞委派 → 不重复推进(防重复委派)
3212
3293
  if (state.delegations.length > 0) {
3213
- if (state.delegations.some(delegationOwnerAlive)) {
3294
+ if (ownerAlive(state)) {
3214
3295
  return { ok: false, text: `🔍 步骤 \`${step.id}\` 的独立验证者仍在取证判定中,现在不需要你操作——它跑完会自动唤醒本会话并继续。\n\n想了解进度用 \`/ralphflow-status\`;想中止用 \`/ralphflow-cancel\`。` };
3215
3296
  }
3216
3297
  // 心跳全停了 = 属主已失联(进程崩溃/被重启),判定永远回不来。绝不把用户卡在一个
3217
3298
  // 永远不会结束的「验证中」幽灵状态:按孤儿兜底,并**立刻重新委派**(用户显式动作,
3218
3299
  // 不必等下一个 restore 触发点)。投票步同样只重跑未通过的票。
3219
- stopHeartbeatsOf(instId, state.delegations);
3220
3300
  state.delegations = [];
3221
3301
  pushHistory(state, "orphan_delegation_recovered", "via=continue");
3222
3302
  log("warn", "orphan_delegation_recovered", { instId, via: "continue" });
@@ -3309,7 +3389,7 @@ export function createEngine(projectDir, ports) {
3309
3389
  if (state.paused) {
3310
3390
  return {
3311
3391
  ok: false,
3312
- text: `实例 \`${instId}\` 处于暂停状态(${state.pause_reason ?? "未知原因"}),**拒绝重置**。\n\n重置只换干净上下文、**不赦免失败**(失败计数原样保留),也不会解除暂停。请先运行 \`/ralphflow-continue\` 恢复(它会解除暂停、重置失败计数并重试);恢复后若仍想要干净的上下文,再执行 \`/ralphflow-reset\`。`,
3392
+ text: `实例 \`${instId}\` 处于暂停状态(${pauseLabel(state.pause_reason)}),**拒绝重置**。\n\n重置只换干净上下文、**不赦免失败**(返工计数原样保留),也不会解除暂停。请先运行 \`/ralphflow-continue\` 恢复(它会解除暂停、重置失败计数并重试);恢复后若仍想要干净的上下文,再执行 \`/ralphflow-reset\`。`,
3313
3393
  };
3314
3394
  }
3315
3395
  // ③ 只在 DO 阶段:已交卷 = 验证在飞 / 停在审查门,重置会打断它、把判定变成孤儿。
@@ -3437,7 +3517,6 @@ export function createEngine(projectDir, ports) {
3437
3517
  // 在飞验证者一律中止(正常路径下 `do_submitted === false` ⇒ 无在飞委派;这里是硬护栏:
3438
3518
  // 清掉 delegations 而不中止,判定回来时会变成无人认领的孤儿)
3439
3519
  abortInstance(instId);
3440
- stopHeartbeatsOf(instId, state.delegations);
3441
3520
  state.delegations = [];
3442
3521
  state.verdicts = [];
3443
3522
  state.current_step = target.id;
@@ -3449,6 +3528,7 @@ export function createEngine(projectDir, ports) {
3449
3528
  state.pause_reason = undefined;
3450
3529
  state.fail_counts = {};
3451
3530
  state.fail_count = 0;
3531
+ stampOwner(state);
3452
3532
  pushHistory(state, "rewind", `${from} → ${target.id}:${reasonText}`, target.id);
3453
3533
  pushHistory(state, "step_start", target.desc ?? "", target.id);
3454
3534
  log("info", "rewind", { instId, from, to: target.id, reason: reasonText });
@@ -3473,8 +3553,7 @@ export function createEngine(projectDir, ports) {
3473
3553
  abortInstance(instId);
3474
3554
  state.active = false;
3475
3555
  state.paused = false;
3476
- state.pause_reason = "user_cancelled";
3477
- stopHeartbeatsOf(instId, state.delegations);
3556
+ state.pause_reason = undefined;
3478
3557
  state.delegations = [];
3479
3558
  pushHistory(state, "cancelled", reason);
3480
3559
  logEvent(instId, "info", "cancelled", { step: state.current_step, reason: reason ?? null });
@@ -3585,10 +3664,10 @@ export function createEngine(projectDir, ports) {
3585
3664
  function renderInstance(info, sessionId) {
3586
3665
  const { id, state } = info;
3587
3666
  const facts = [
3588
- state.active ? (state.paused ? `⏸ 暂停(${state.pause_reason})` : state.delegations.length > 0 ? "🔍 验证中" : state.do_submitted ? "🙋 待放行" : "▶️ 执行中") : "✅ 已结束",
3667
+ state.active ? (state.paused ? (state.pause_reason === "host_restarted" ? "⏸ 已中断(属主运行时失联)" : `⏸ 暂停(${pauseLabel(state.pause_reason)})`) : state.delegations.length > 0 ? "🔍 验证中" : state.do_submitted ? "🙋 待放行" : "▶️ 执行中") : "✅ 已结束",
3589
3668
  `工作流 \`${state.workflow_name}\``,
3590
3669
  `步骤 \`${state.current_step}\``,
3591
- `失败 ${state.fail_count} 轮`,
3670
+ `返工 ${state.fail_count} 轮`,
3592
3671
  ];
3593
3672
  const ownerText = !state.owner_session
3594
3673
  ? "无(无属主:`/ralphflow-continue` 会自动接管)"
@@ -3630,15 +3709,19 @@ export function createEngine(projectDir, ports) {
3630
3709
  return `工作流已结束,历史在报告里:${rel};要再跑一次用 \`/ralphflow-start <工作流> <任务>\`。`;
3631
3710
  }
3632
3711
  if (s.paused) {
3712
+ if (s.pause_reason === "host_restarted")
3713
+ return "**已中断**:驱动这个实例的运行时不在了(宿主重启或进程退出)。状态、判定与产出都保留;用 `/ralphflow-continue` 继续,或 `/ralphflow-cancel` 结束。";
3714
+ if (s.pause_reason === "user_stop")
3715
+ return "**等你继续**:你停止了运行。用 `/ralphflow-continue` 从当前步继续,或 `/ralphflow-cancel` 结束。";
3633
3716
  if (s.pause_reason === "max_failures")
3634
3717
  return "**等你定夺**:修好问题后 `/ralphflow-continue` 重新验证,或 `/ralphflow-cancel` 结束。";
3635
3718
  if (s.pause_reason === "no_submit")
3636
- return "**等你处理**:模型反复未交卷。先 `/ralphflow-continue` 恢复,再让它调用 `ralphflow_submit`;或 `/ralphflow-cancel` 结束。";
3637
- return "**暂停中**:处理后 `/ralphflow-continue` 恢复(基础设施问题不计失败)。";
3719
+ return "**等你处理**:本步反复停下且没有动作,已暂停。先 `/ralphflow-continue` 恢复,再让它交卷;或 `/ralphflow-cancel` 结束。";
3720
+ return `**暂停中**(${pauseLabel(s.pause_reason)}):处理后 \`/ralphflow-continue\` 恢复(基础设施问题不计失败)。`;
3638
3721
  }
3639
3722
  if (s.delegations.length > 0) {
3640
3723
  // 心跳停了 = 属主没了:绝不显示成一个永远不会结束的「验证中」(读路径只如实说,不写状态)
3641
- if (!s.delegations.some(delegationOwnerAlive)) {
3724
+ if (!ownerAlive(s)) {
3642
3725
  return "**验证已中断**:验证属主已失联(那个运行时已经不在了),判定回不来。`/ralphflow-continue` 会按孤儿兜底并重新委派验证;想结束就用 `/ralphflow-cancel`。";
3643
3726
  }
3644
3727
  return "**无需操作**:独立验证者正在取证判定,跑完会自动唤醒本会话继续。可用 `/ralphflow-status` 看进度,`/ralphflow-cancel` 中止。";
@@ -3657,7 +3740,7 @@ export function createEngine(projectDir, ports) {
3657
3740
  if (!s.active)
3658
3741
  return "已结束";
3659
3742
  if (s.paused)
3660
- return `暂停(${s.pause_reason})`;
3743
+ return s.pause_reason === "host_restarted" ? "已中断(属主运行时失联)" : `暂停(${pauseLabel(s.pause_reason)})`;
3661
3744
  if (s.delegations.length > 0)
3662
3745
  return "验证中";
3663
3746
  if (s.do_submitted)
@@ -3760,6 +3843,9 @@ export function createEngine(projectDir, ports) {
3760
3843
  issues.push(`实例 \`${id}\` 的 state.json 损坏(${msg(err)})—— 该实例无法恢复,确认无需保留后可删除整个目录`);
3761
3844
  continue;
3762
3845
  }
3846
+ // Graph 实例完成后**有意保留**(design §3.3):不是「已结束但未销毁」的异常。
3847
+ if (parsed.kind === "graph")
3848
+ continue;
3763
3849
  if (parsed.active === false) {
3764
3850
  issues.push(`实例 \`${id}\` 已结束但目录未被销毁(可能是报告归档失败)。先确认报告是否已生成,再决定是否删除该目录`);
3765
3851
  }
@@ -3773,6 +3859,20 @@ export function createEngine(projectDir, ports) {
3773
3859
  for (const { state } of listInstances())
3774
3860
  if (state.artifacts_dir_name)
3775
3861
  claimed.add(state.artifacts_dir_name);
3862
+ // Graph 实例与 Flow 共用 artifacts/;它们的产出目录同样不是孤儿(kind 只作数据读取)。
3863
+ try {
3864
+ for (const entry of fs.readdirSync(instancesDir, { withFileTypes: true })) {
3865
+ if (!entry.isDirectory())
3866
+ continue;
3867
+ try {
3868
+ const parsed = JSON.parse(fs.readFileSync(path.join(instancesDir, entry.name, "state.json"), "utf-8"));
3869
+ if (parsed.kind === "graph" && typeof parsed.artifacts_dir_name === "string")
3870
+ claimed.add(parsed.artifacts_dir_name);
3871
+ }
3872
+ catch { }
3873
+ }
3874
+ }
3875
+ catch { }
3776
3876
  for (const h of listHistory())
3777
3877
  if (h.artifactsDirName)
3778
3878
  claimed.add(h.artifactsDirName);
@@ -3819,7 +3919,7 @@ export function createEngine(projectDir, ports) {
3819
3919
  if (!s.active)
3820
3920
  flags.push("已结束");
3821
3921
  else if (s.paused)
3822
- flags.push(`暂停(${s.pause_reason})`);
3922
+ flags.push(phaseLabel(s));
3823
3923
  else if (s.delegations.length > 0)
3824
3924
  flags.push("验证中");
3825
3925
  else if (s.do_submitted)
@@ -3849,36 +3949,86 @@ export function createEngine(projectDir, ports) {
3849
3949
  return { ok: true, text: lines.join("\n") };
3850
3950
  }
3851
3951
  /**
3852
- * 插件加载/进程重启:孤儿委派 fail-safe(不隐式继续、不隐式通过)。
3952
+ * 插件加载/进程重启:只处理「需要属主却没有属主」的实例(不隐式继续、不隐式通过)。
3853
3953
  *
3854
- * **只兜真正的孤儿**:委派的心跳已经停了(属主运行时崩溃/被重启 → 判定永远回不来)→
3855
- * 暂停 check_infra 等用户定夺。心跳还新鲜的委派一律原样留着、一个字节都不动 ——
3856
- * 别的会话、别的 sandbox 进程、重载后的新实例碰 ralphflow 都不得影响在飞的验证。
3954
+ * 判据是**实例心跳**(`owner.ts`):
3955
+ * · 心跳过了 TTL 或缺失 → 属主确实死了,立刻标中断;
3956
+ * · 心跳还新鲜 → 可能是另一个活着的 host,也可能是**快速重启**(最后一下心跳必然新鲜)。
3957
+ * 等一个刷新窗口再复查:心跳往前走了 = 活着;没走 = 死了。既不误伤另一个 host,
3958
+ * 也不用等满 TTL。
3857
3959
  *
3858
- * 老 `state.json` 里的委派没有心跳字段(来源不可考)→ 按孤儿兜底,安全网不缩水。
3859
- * 判据细节见 {@link delegationOwnerAlive}。
3960
+ * 审查门/暂停不需要属主,一律不动。
3860
3961
  */
3861
3962
  function restore() {
3862
3963
  for (const { id, state } of listInstances()) {
3863
- if (!state.active)
3964
+ if (!needsOwner(state))
3864
3965
  continue;
3865
- if (state.delegations.length === 0)
3866
- continue;
3867
- if (state.delegations.some(delegationOwnerAlive)) {
3868
- // 心跳还新鲜(属主还在等判定)→ 判定会回来,绝不打断。
3869
- log("info", "orphan_recovery_skipped_live", { instId: id, delegations: state.delegations.length });
3966
+ if (!ownerAlive(state)) {
3967
+ markOwnerLost(id);
3870
3968
  continue;
3871
3969
  }
3872
- stopHeartbeatsOf(id, state.delegations);
3873
- state.delegations = [];
3874
- state.paused = true;
3875
- state.pause_reason = "check_infra";
3876
- pushHistory(state, "orphan_delegation_recovered");
3877
- logPause(id, state, "check_infra", { detail: "orphan_delegation_recovered" });
3878
- writeState(state, id);
3879
- log("warn", "orphan_delegation_recovered", { instId: id });
3970
+ // 心跳的属主就是本进程(例如同进程里另一个 facade 正在驱动它):我们知道自己活着,
3971
+ // 不必再复查,更不会把它判死。
3972
+ if (state.owner_runtime === runtimeId())
3973
+ continue;
3974
+ scheduleOwnerRecheck(id, state.owner_heartbeat_at ?? 0);
3880
3975
  }
3881
3976
  }
3977
+ /**
3978
+ * 把「属主已失联」落盘:暂停(host_restarted),并清掉不可能回来的在飞委派。
3979
+ * **同步**写:restore() 在 facade 创建时调用,调用方读完状态就要看到结果;
3980
+ * 这个实例不在本运行时的 driving 集合里,没有同实例的并发写要排队。
3981
+ */
3982
+ function markOwnerLost(instId) {
3983
+ markOwnerLostLocked(instId);
3984
+ }
3985
+ /**
3986
+ * 已在实例锁内的版本。`beatAt` 是**快速复查**用的观察点:复查时心跳还没过 TTL,
3987
+ * 不能再用 `ownerAlive` 挡;判据换成「心跳是否越过复查前看到的那一下」。
3988
+ */
3989
+ function markOwnerLostLocked(instId, beatAt) {
3990
+ try {
3991
+ const fresh = readState(instId);
3992
+ if (!fresh || !needsOwner(fresh))
3993
+ return;
3994
+ if (beatAt !== undefined ? (fresh.owner_heartbeat_at ?? 0) > beatAt : ownerAlive(fresh))
3995
+ return;
3996
+ fresh.delegations = [];
3997
+ fresh.paused = true;
3998
+ fresh.pause_reason = "host_restarted";
3999
+ pushHistory(fresh, "interrupted", "owner_heartbeat_stale");
4000
+ logPause(instId, fresh, "host_restarted", { detail: "owner_heartbeat_stale" });
4001
+ writeState(fresh, instId);
4002
+ notify(fresh, "⏸ 已中断:驱动这个实例的运行时不在了(宿主重启或进程退出)。状态与产出都保留;用 `/ralphflow-continue` 继续当前步骤。", "⏸ 已中断:属主运行时失联");
4003
+ log("warn", "owner_lost", { instId });
4004
+ }
4005
+ catch (e) {
4006
+ log("warn", "owner_lost_check_failed", { instId, error: msg(e) });
4007
+ }
4008
+ }
4009
+ /**
4010
+ * 快速复查:等一个刷新窗口,心跳还没有往前走,才判属主已死。
4011
+ * 定时器 unref;实例被继续/暂停/结束时条件自然不成立,复查是空操作。
4012
+ */
4013
+ function scheduleOwnerRecheck(instId, beatAt) {
4014
+ const delay = ownerRecheckMs();
4015
+ if (delay <= 0)
4016
+ return;
4017
+ const timer = setTimeout(() => {
4018
+ void withStateLock(instId, () => {
4019
+ try {
4020
+ const fresh = readState(instId);
4021
+ if (!fresh || !needsOwner(fresh))
4022
+ return;
4023
+ markOwnerLostLocked(instId, beatAt);
4024
+ }
4025
+ catch (e) {
4026
+ log("warn", "owner_recheck_failed", { instId, error: msg(e) });
4027
+ }
4028
+ });
4029
+ }, delay);
4030
+ timer.unref?.();
4031
+ }
3882
4032
  /** Read-only UI projection; never persists derived phase or advances an instance. */
3883
4033
  function uiStatus(sessionId) {
3884
4034
  let info = listInstances().find((i) => i.state.owner_session === sessionId);
@@ -3906,14 +4056,17 @@ export function createEngine(projectDir, ports) {
3906
4056
  : state.do_submitted && step && wf && atOpenGate(wf, state, step) ? "gate"
3907
4057
  : state.do_submitted ? "switching" : "executing";
3908
4058
  const total = step ? Math.max(voterCountOf(step), stepHasVerification(step) ? 1 : 0) : 0;
4059
+ // 每一票带上**它自己**的检查依据:状态弹层要能看出验证者在查什么,而不只是「通过/未通过」。
4060
+ const criterionOf = (index) => (step?.check ?? step?.check_voting?.[index]?.check)?.trim() || undefined;
3909
4061
  const votes = state.do_submitted ? Array.from({ length: total }, (_, index) => {
3910
4062
  const verdict = state.verdicts.find((v) => verdictBelongsToStep(v, state.current_step) && (total === 1 || v.check_index === index));
3911
4063
  const running = state.delegations.some((d) => total === 1 || d.check_index === index);
3912
- return { index: index + 1, status: verdict?.status ?? (running ? "running" : "pending"), reason: verdict?.reason.slice(0, 500) ?? "" };
4064
+ const check = criterionOf(index);
4065
+ return { index: index + 1, status: verdict?.status ?? (running ? "running" : "pending"), reason: verdict?.reason.slice(0, 500) ?? "", ...(check ? { check } : {}) };
3913
4066
  }) : [];
3914
4067
  const hint = stage === "unavailable" ? "状态或报告不可用,请用 /ralphflow-doctor 检查。" : stage === "switching" ? "正在切换步骤或准备本步上下文。" : stage === "executing" ? "执行阶段,等待本步交卷。"
3915
4068
  : (nextActionHint(state, id, step) ?? "").replace(/\*\*/g, "");
3916
- return { status: { id, workflow: state.workflow_name, task: state.user_task.slice(0, 2000), step: state.current_step,
4069
+ return { status: { id, kind: "flow", workflow: state.workflow_name, task: state.user_task.slice(0, 2000), step: state.current_step,
3917
4070
  stage, hint, failures: state.fail_count, maxFailures: step?.max_fail_count ?? 0, updatedAt: state.updated_at, report: null,
3918
4071
  steps: (wf?.steps ?? []).map((s) => ({ id: s.id, description: s.desc ?? "", current: s.id === state.current_step, failures: failCountOf(state, s.id) })),
3919
4072
  votes, recent: state.history.slice(-5).map((h) => ({ step: h.step ?? "", event: h.event, detail: h.detail ?? "" })),
@@ -3932,7 +4085,7 @@ export function createEngine(projectDir, ports) {
3932
4085
  }
3933
4086
  if (!report.parsed || report.id !== ref.runId || report.statusLabel !== (ref.ended === "done" ? "完成" : "取消"))
3934
4087
  return null;
3935
- return { id: ref.runId, workflow: report.workflow ?? "Ralph Flow", task: report.task ?? "", step: "",
4088
+ return { id: ref.runId, kind: "flow", workflow: report.workflow ?? "Ralph Flow", task: report.task ?? "", step: "",
3936
4089
  stage: ref.ended, hint: "运行已结束,报告与产出已归档。", failures: 0, maxFailures: 0,
3937
4090
  updatedAt: report.endedAt ?? "", report: report.relPath, steps: [], votes: [], recent: [] };
3938
4091
  }
@@ -3941,7 +4094,7 @@ export function createEngine(projectDir, ports) {
3941
4094
  ensureLayout, listWorkflows, loadWorkflow,
3942
4095
  readState, listInstances, listHistory, instanceDir,
3943
4096
  artifactsDirOf, artifactsRelDirOf, reportRelPathOf, destroyInstance,
3944
- start, onSubmit, noteAssistantText, remindToSubmit, continueInstance, resetCurrent, rewindTo, cancelInstance, statusOf, listAll, restore, diagnose,
4097
+ start, onSubmit, noteAssistantText, remindToSubmit, pauseForUserStop, continueInstance, resetCurrent, rewindTo, cancelInstance, statusOf, listAll, restore, diagnose,
3945
4098
  activeInstanceOfSession, uiStatus, uiReport,
3946
4099
  };
3947
4100
  }
@@ -3974,4 +4127,4 @@ function normalizeVerdict(v, stepId, checkIndex) {
3974
4127
  ...(raw.agent_id !== undefined ? { agent_id: String(raw.agent_id) } : {}),
3975
4128
  };
3976
4129
  }
3977
- export const BUILTIN_WORKFLOWS = ["loop", "spec"];
4130
+ export const BUILTIN_WORKFLOWS = ["loop", "spec", "create-graph"];