ralphflow-dsh 2.4.1 → 2.6.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.
package/lib/engine.js CHANGED
@@ -13,9 +13,10 @@ import { normalizeUnfinished } from "./unfinished.js";
13
13
  import path from "node:path";
14
14
  import { fileURLToPath } from "node:url";
15
15
  import yaml from "js-yaml";
16
- import { userRalphFlowDir } from "./paths.js";
16
+ import { RALPH_FLOW_DIR, assetSearchDirs, displayPath, headlessModeEnabled, resolveRalphFlowLayout, userRalphFlowDir, } from "./paths.js";
17
17
  import { FLOW_ENTRY_FILE, assetCandidates, assetReferenceSection, assetRootOf, discoverAssetsIn, placementSection, } from "./asset-path.js";
18
18
  import { pauseLabel } from "./pause.js";
19
+ import { TERMINAL_RECORD_SCHEMA_VERSION, removeTerminalRecord, writeTerminalRecord, } from "./terminal.js";
19
20
  import { OWNER_HEARTBEAT_REFRESH_MS, ownerAlive, ownerRecheckMs, runtimeId, stampOwner } from "./owner.js";
20
21
  import { MAX_VOTERS, decideVotingOutcome, formatVotingFailureReason, formatVotingInfraReason, formatVotingPassReason, voterProgressLine, voterStatusLabel, } from "./voting.js";
21
22
  // 纯函数层(聚合优先级与三份文案)的唯一实现在 voting.ts;这里只把常量与展示标签转出去,
@@ -23,13 +24,10 @@ import { MAX_VOTERS, decideVotingOutcome, formatVotingFailureReason, formatVotin
23
24
  export { MAX_VOTERS };
24
25
  export { formatVotingFailureReason, formatVotingPassReason, formatVotingInfraReason, voterProgressLine, voterStatusLabel };
25
26
  /**
26
- * 项目内的运行时根目录。**项目根 dot-dir**(§1.8):项目根 = 最近的含 `.git` 的祖先目录,
27
- * 与原生 Skill 的 `<projectRoot>/.dsh/skills` 用同一条规则;用户级命名空间
28
- * `<DSH_HOME>/ralph-flow/` 由 `paths.ts` 解析。
29
- *
30
- * 注意:这里是**项目根相对路径**(含 `/`),`path.join(projectRoot, RALPH_FLOW_DIR)` 仍成立。
27
+ * 项目内的运行时根目录名。定义在 `paths.ts`(运行态布局的唯一解析点),这里只转出,
28
+ * 让 `lib/engine.js` 仍是路径常量与引擎的既有入口。
31
29
  */
32
- export const RALPH_FLOW_DIR = ".dsh/ralph-flow";
30
+ export { RALPH_FLOW_DIR };
33
31
  /** 每实例产出目录的目录名(§1.7,与 opencode 同名) */
34
32
  const ARTIFACTS_DIRNAME = "artifacts";
35
33
  /**
@@ -227,28 +225,86 @@ export function expectedVerdicts(step) {
227
225
  return voters;
228
226
  return stepHasCheck(step) ? 1 : 0;
229
227
  }
230
- /** 本步进入前是否要重置上下文,以及**为什么**(`undefined` = 不重置)。 */
231
- export function resetCauseOf(wf, step) {
228
+ /**
229
+ * 按轮重置的**固定阈值**:模型每自报未完成 3 次,引擎在下一轮 DO 投递前换一次干净上下文。
230
+ *
231
+ * 这是引擎默认行为,**不可配置**:作者不写任何字段就生效,也没有 YAML 键能改频率或按步关闭
232
+ * (旧频率字段已从方言删除;再写它只会拿到「未知步骤键」的通用告警并被忽略)。
233
+ * 要「每次进入都换」用静态门 `reset: true` / `auto_reset: true`。
234
+ *
235
+ * 现场依据:模型报「没做完」超过三次,多半是上下文脏了而不是任务变了 —— 换一次干净上下文就能
236
+ * 接着做很久。所以这是**默认行为**,与「没输出 `<promise>done</promise>` 默认催 5 遍」同一口径:
237
+ * 作者不必写任何东西,长循环步天然有机械出口。
238
+ *
239
+ * 与静态门**不互相遮蔽**(两个维度,各管各的):
240
+ * · **静态门**管「进入本步前换」(重试/返工时由它换);
241
+ * · **按轮门**管「本步攒够 3 次自报未完成再换」(长循环里由它换);
242
+ * · **同一次 DO 投递最多替换一次**:静态门已经换了,就把本次到期的按轮阈值记为已用
243
+ * (上下文已经干净,不重复换);静态门没触发时按轮门照常补上。
244
+ * 于是同一步可以同时拥有两种触发:返工时静态门换、长循环里按轮门换。
245
+ *
246
+ * 三条硬语义(与 `fail_counts` 那条线**完全分开**):
247
+ * · **唯一计数来源 = 模型自报未完成**(`submit_incomplete`)。CHECK 判定失败**不计入**,
248
+ * 它走 `fail_counts` / `max_fail_count`,两条线互不干扰;
249
+ * · **不赦免失败**:`fail_counts` / `max_fail_count` 的语义与判定顺序一个字节都不动;
250
+ * · 该步**验证通过时计数清零**;计数与「已换过的阈值」都持久化在 `state.json`,
251
+ * 跨 pause/resume 存活(见 `InstanceState.incomplete_counts` / `round_reset_marks`)。
252
+ *
253
+ * 计数到阈值后若替换失败(面不平衡 / 不在空闲窗口),阈值**不消耗** —— 下一轮投递照常重试。
254
+ * 首步的**初次进入**结构上仍然无法替换(DO 是 `ralphflow_start` 的返回值);第 3 次自报
255
+ * 未完成之后的下一轮投递正常触发。
256
+ */
257
+ export const ROUND_RESET_THRESHOLD = 3;
258
+ /**
259
+ * 本步这次 DO 投递要不要重置上下文、**为什么**,以及按轮门的到期阈值 —— 纯函数。
260
+ *
261
+ * 两个维度各答各的(**互不遮蔽**):
262
+ * · **静态门**:`reset: true`(含子工作流 `auto_reset` / 调用点下沉,来源分别是 step/auto/call)
263
+ * ∨ 工作流级 `auto_reset: true` —— 进入本步前换一次;
264
+ * · **按轮门**:模型自报未完成次数攒够了一个没换过的阈值(固定每
265
+ * {@link ROUND_RESET_THRESHOLD} 次)—— 同一轮循环里换一次。
266
+ *
267
+ * `opts.skipStatic` 给「同一轮的再投递」用(回合收尾提醒 / 解除暂停):那不是「进入本步」,
268
+ * 静态门不重复触发,但按轮门照常生效。
269
+ *
270
+ * 没有计数快照(`every` 省略:纯静态判定)时按轮门永远不会到期 —— 于是
271
+ * {@link stepWantsReset} 仍是纯粹的「作者声明了进入就换吗」。
272
+ */
273
+ export function resetCauseOf(wf, step, every, opts) {
274
+ // ── 维度一:静态门(进入本步前换)──
232
275
  // 子工作流 auto_reset 下沉出来的 `reset: true` 不是作者在本步标的 → 仍记 `"auto"`。
276
+ let staticCause;
233
277
  if (step.reset === true) {
234
- if (step.reset_from_auto === true)
235
- return "auto";
236
- if (typeof step.reset_from_call === "string" && step.reset_from_call !== "")
237
- return "call";
238
- return "step";
239
- }
240
- if (wf.auto_reset === true)
241
- return "auto";
242
- return undefined;
278
+ staticCause = step.reset_from_auto === true
279
+ ? "auto"
280
+ : (typeof step.reset_from_call === "string" && step.reset_from_call !== "" ? "call" : "step");
281
+ }
282
+ else if (wf.auto_reset === true) {
283
+ staticCause = "auto";
284
+ }
285
+ // ── 维度二:按轮门(本步攒够自报未完成再换)──
286
+ const everySeq = every ? Math.floor(every.count / ROUND_RESET_THRESHOLD) : 0;
287
+ const everyDue = everySeq > (every?.applied ?? 0);
288
+ if (staticCause !== undefined && opts?.skipStatic !== true) {
289
+ // 静态门先赢:**同一次投递只替换一次**。到期的按轮阈值一并交回(`everySeq`),
290
+ // 调用方在替换成功后把它记为已用 —— 否则下一轮会为同一个阈值再清一次。
291
+ return { trigger: staticCause, everySeq: everyDue ? everySeq : 0 };
292
+ }
293
+ if (everyDue)
294
+ return { trigger: "every", everySeq };
295
+ return { everySeq: 0 };
243
296
  }
244
297
  /**
245
- * 本步进入前是否要重置上下文(步骤级 `reset` ∨ 工作流级 `auto_reset`)。
298
+ * 本步是否声明了**静态**重置门(步骤级 `reset` ∨ 工作流级 `auto_reset`)。
246
299
  *
247
- * **唯一判据**:所有投递点(advance / 返工 / 手动 `/ralphflow-reset`)都走这一个谓词,
248
- * 不再有「这里看 reset、那里看 auto_reset」的分叉 —— 那正是两种豁免规则走样的来源。
300
+ * 这是「作者声明『进入就换』」的静态谓词:启动回执、措辞、迁移标记都用它。
301
+ *
302
+ * ⚠️ 这不是运行期的触发判据:真正决定「这次投递要不要换上下文」的只有一个地方 ——
303
+ * `deliverStepDo` 调 {@link resetCauseOf} 并传入按轮计数快照。这里不带计数,
304
+ * 所以按轮门恒不到期(它答的是「作者有没有声明进入就换」,不是「这一轮该不该换」)。
249
305
  */
250
306
  export function stepWantsReset(wf, step) {
251
- return resetCauseOf(wf, step) !== undefined;
307
+ return resetCauseOf(wf, step).trigger !== undefined;
252
308
  }
253
309
  /**
254
310
  * 本步**生效的任务**(DO 与 CHECK 提示词「## 任务」段的内容)—— 纯函数,只读 `StepDef` 与任务描述。
@@ -598,6 +654,8 @@ export function lintWorkflow(steps, manual, autoReset = false) {
598
654
  if (autoReset && steps.length > 0 && steps.every((s) => (s.on_fail ?? s.id) === s.id)) {
599
655
  warnings.push("`auto_reset: true` 且所有步骤的 `on_fail` 都指向自身(纯线性流):每次失败重试也会重置上下文,token 成本较高。");
600
656
  }
657
+ // 静态门与按轮门**互不遮蔽**(静态门管「进入本步前换」,按轮门管「本步攒够 3 次自报未完成
658
+ // 再换」)。同一步同时拥有两种触发是正常配置(返工由静态门换、长循环由按轮门换),不告警。
601
659
  return warnings;
602
660
  }
603
661
  /** 人类可读时长(报告用):`45s` / `3m12s` / `1h05m` */
@@ -670,9 +728,11 @@ export function globalWorkflowsDirOf() {
670
728
  * **必须包含内置工作流**(`loop`/`spec`)——它们不落盘,只存在于插件目录,漏掉就会让
671
729
  * `/ralphflow-loop`、`/ralphflow-spec` 消失。项目根里的同名文件遮蔽内置(有意行为)。
672
730
  */
673
- export function listWorkflowsIn(workspace) {
674
- const found = new Map(); // name → 入口文件路径(项目根优先,其次用户级,最后内置)
675
- for (const dir of [path.join(workspace, RALPH_FLOW_DIR, "workflows"), globalWorkflowsDirOf()]) {
731
+ export function listWorkflowsIn(workspace, runtime = {}) {
732
+ const found = new Map(); // name → 入口文件路径(项目根优先,其次用户级,最后内置;无头时只剩后两者)
733
+ // 无头运行的工作流来源隔离与引擎加载面同一条规则:只认用户级与内置。
734
+ const headless = headlessModeEnabled(runtime.ignoreWorkspaceWorkflows);
735
+ for (const dir of assetSearchDirs(workspace, "workflows", headless)) {
676
736
  for (const [name, file] of discoverAssetsIn(dir, FLOW_ENTRY_FILE)) {
677
737
  if (!found.has(name))
678
738
  found.set(name, file);
@@ -696,14 +756,21 @@ export function listWorkflowsIn(workspace) {
696
756
  return { name, desc };
697
757
  });
698
758
  }
699
- export function createEngine(projectDir, ports) {
700
- const root = path.join(projectDir, RALPH_FLOW_DIR);
701
- const instancesDir = path.join(root, "instances");
702
- const workflowsDir = path.join(root, "workflows");
703
- const reportsDir = path.join(root, "reports");
704
- const artifactsDir = path.join(root, ARTIFACTS_DIRNAME);
705
- // 用户级工作流目录:`<DSH_HOME|~/.dsh>/ralph-flow/workflows`(与项目根同名命名空间)
706
- const globalWorkflowsDir = globalWorkflowsDirOf();
759
+ export function createEngine(projectDir, ports, runtime = {}) {
760
+ // 运行态布局只有一处解析(外部状态目录 / 无头模式都在这里落定):Flow 与 Graph 共用同一份
761
+ // 根,报告、产出、实例目录绝不会一半在项目根、一半在外部目录。
762
+ const layout = resolveRalphFlowLayout(projectDir, runtime);
763
+ const root = layout.root;
764
+ const instancesDir = layout.instancesDir;
765
+ const workflowsDir = layout.workflowsDir;
766
+ const reportsDir = layout.reportsDir;
767
+ const artifactsDir = layout.artifactsDir;
768
+ /** 运行态在项目根之外:报告与提示词里的路径必须给绝对路径(工作区里读不到相对路径)。 */
769
+ const externalState = layout.external;
770
+ /** 无头运行:项目级资产不可信,人工审查门没人放行。 */
771
+ const headless = layout.headless;
772
+ /** 报告目录在人类可读文案里的写法(默认沿用工作区相对路径,外部化时给绝对路径)。 */
773
+ const reportsDirLabel = displayPath(projectDir, reportsDir, externalState);
707
774
  /**
708
775
  * 实例 → 在飞取消信号集合(取消/重开/暂停时中止验证者,不白烧 token)。
709
776
  *
@@ -813,13 +880,19 @@ export function createEngine(projectDir, ports) {
813
880
  /**
814
881
  * 产出目录的**工作区相对路径**(正斜杠,可嵌进 DO/CHECK 提示词)。
815
882
  * 验证者继承父会话工作区,所以这个路径对它同样可读。
883
+ *
884
+ * 外部化时运行态不在工作区里:这里改给**绝对路径**,否则执行者与验证者都会按工作区
885
+ * 解析出一个不存在的目录。
816
886
  */
817
- function artifactsRelDirOf(instId) {
818
- return `${RALPH_FLOW_DIR}/${ARTIFACTS_DIRNAME}/${artifactsDirNameOf(instId)}`;
887
+ function artifactsDisplayDirOf(instId) {
888
+ return displayPath(projectDir, path.join(artifactsDir, artifactsDirNameOf(instId)), externalState);
819
889
  }
820
- /** 报告的**工作区相对路径**(完成/取消消息、历史列表、状态查询共用同一份事实) */
821
- function reportRelPathOf(instId) {
822
- return `${RALPH_FLOW_DIR}/reports/${instId}.md`;
890
+ /**
891
+ * 报告的路径(完成/取消消息、历史列表、状态查询共用同一份事实)。
892
+ * 默认是工作区相对路径;外部化时给绝对路径,报告在项目根之外也指得准。
893
+ */
894
+ function reportPathOf(instId) {
895
+ return displayPath(projectDir, path.join(reportsDir, `${instId}.md`), externalState);
823
896
  }
824
897
  // ─── 执行日志(JSONL,docs/v2/execution-log-brief.md)───────────────────────
825
898
  //
@@ -945,7 +1018,12 @@ export function createEngine(projectDir, ports) {
945
1018
  }
946
1019
  }
947
1020
  function ensureLayout() {
948
- for (const p of [root, instancesDir, workflowsDir, reportsDir, artifactsDir]) {
1021
+ const dirs = [root, instancesDir, reportsDir, artifactsDir];
1022
+ // 项目资产目录只在默认布局下创建:外部化/无头运行时**绝不**在目标仓库里留下
1023
+ // `.dsh/ralph-flow/`(那是「零污染」契约,也是 git status 保持干净的前提)。
1024
+ if (!externalState && !headless)
1025
+ dirs.push(workflowsDir);
1026
+ for (const p of dirs) {
949
1027
  try {
950
1028
  fs.mkdirSync(p, { recursive: true });
951
1029
  }
@@ -968,8 +1046,14 @@ export function createEngine(projectDir, ports) {
968
1046
  const CALL_POINT_KEYS = new Set(["id", "desc", "do", "input", "output", "workflow", "on_pass", "on_fail", "max_fail_count", "reset"]);
969
1047
  const KNOWN_WF_KEYS = new Set(["kind", "description", "manual_step", "adversarial_check", "auto_reset", "steps"]);
970
1048
  function knownWorkflowDirs() {
971
- // 单根:本项目根的工作流目录 + 用户级目录(内置工作流不落盘,由 builtinWorkflowPath 回落)
972
- return [workflowsDir, globalWorkflowsDir];
1049
+ // 单根:本项目根的工作流目录 + 用户级目录(内置工作流不落盘,由 builtinWorkflowPath 回落)。
1050
+ // 无头运行只认用户级与内置:受管业务仓库里放同名文件不能覆盖工厂内置 Flow。
1051
+ return assetSearchDirs(projectDir, "workflows", headless);
1052
+ }
1053
+ /** 「工作流能放哪」的文案:无头模式不把作者引向被忽略的项目资产目录。 */
1054
+ function workflowPlacementText(name) {
1055
+ const dir = knownWorkflowDirs()[0];
1056
+ return `${dir}/${name}/workflow.yaml(目录形态;单文件 ${dir}/${name}.yaml 也识别)`;
973
1057
  }
974
1058
  function workflowPaths(name) {
975
1059
  return knownWorkflowDirs().flatMap((dir) => assetCandidates(dir, name, FLOW_ENTRY_FILE));
@@ -1043,7 +1127,7 @@ export function createEngine(projectDir, ports) {
1043
1127
  }
1044
1128
  }
1045
1129
  if (raw === undefined) {
1046
- problems.push(`未找到工作流 "${name}"。把资产放到 ${workflowsDir}/<name>/workflow.yaml(目录形态;单文件 ${workflowsDir}/<name>.yaml 也识别)即可被加载。`);
1130
+ problems.push(`未找到工作流 "${name}"。把资产放到 ${workflowPlacementText("<name>")} 即可被加载。`);
1047
1131
  return { def: null, problems, warnings };
1048
1132
  }
1049
1133
  raw = raw.replace(/^\uFEFF/, "");
@@ -1192,7 +1276,7 @@ export function createEngine(projectDir, ports) {
1192
1276
  problems.push(`步骤 \`${s.id}\` 写了 \`workflow\` 但没有给出要调用的工作流名(必须是非空字符串,例如 \`workflow: analyze\`)。调用点以 \`workflow:\` 声明委托(此时 \`do\` 可省略;写了就是这段子工作流的任务)。`);
1193
1277
  }
1194
1278
  else if (/[\\/]/.test(subName)) {
1195
- problems.push(`步骤 \`${s.id}\` 的 \`workflow: ${subName}\` 含路径分隔符:\`workflow\` 只能是工作流**名**(对应目录 \`${workflowsDir}/<名字>/workflow.yaml\`、全局目录或内置同名资产),不能是路径。`);
1279
+ problems.push(`步骤 \`${s.id}\` 的 \`workflow: ${subName}\` 含路径分隔符:\`workflow\` 只能是工作流**名**(对应目录 \`${knownWorkflowDirs()[0]}/<名字>/workflow.yaml\`${headless ? "、内置同名资产" : "、全局目录或内置同名资产"}),不能是路径。`);
1196
1280
  }
1197
1281
  if (s.id.includes(SUBWORKFLOW_ID_SEP)) {
1198
1282
  problems.push(`调用点 \`${s.id}\` 的 id 含 \`${SUBWORKFLOW_ID_SEP}\`:展开后步骤 id 是 \`调用点id${SUBWORKFLOW_ID_SEP}子步骤id\`,调用点 id 含分隔符会与展开结果撞名。请把 id 改成不含 \`${SUBWORKFLOW_ID_SEP}\` 的名字。`);
@@ -1507,6 +1591,15 @@ export function createEngine(projectDir, ports) {
1507
1591
  problems.push(`manual_step 引用了不存在的步骤:${unknownManual.map((m) => `\`${m}\``).join("、")}(审查门会静默失效,必须修正拼写或删掉)。`);
1508
1592
  return { def: null, problems, warnings };
1509
1593
  }
1594
+ // ── 无头运行:人工审查门没人放行 ────────────────────────────────────────────
1595
+ // 无头会话里没有人类可以执行 `/ralphflow-continue`,实例会停在一个永远等不到确认的
1596
+ // 审查门上(画面上看起来像「卡住」,没有任何错误)。因此加载期就拒绝整份定义,
1597
+ // 让启动失败得响亮而不是运行到一半静默停摆。
1598
+ if (headless && manualSet.size > 0) {
1599
+ problems.push(`工作流 \`${name}\` 声明了人工审查门(\`manual_step\`:${[...manualSet].map((m) => `\`${m}\``).join("、")}),但本次是无头运行:没有会话能执行 \`/ralphflow-continue\` 放行它。`
1600
+ + `无头运行只接受没有审查门的工作流:请删掉顶层 \`manual_step\`,让每一步由独立验证者的判定自动推进;需要人工审查的工作流放到交互式会话里运行。`);
1601
+ return { def: null, problems, warnings };
1602
+ }
1510
1603
  // 子工作流里的 `adversarial_check.model` 下沉到它各步的 `check_model`(对齐 opencode 的
1511
1604
  // 逐字段继承):**只在子层加载时**做,且只填「自己没填或填了但无效」的步骤 ——
1512
1605
  // 父级的 `adversarial_check` 是整份定义的兜底、不区分层次,帮不了子层。
@@ -1554,6 +1647,7 @@ export function createEngine(projectDir, ports) {
1554
1647
  // 向后兼容读取:老 state.json 只有标量 fail_count(无 fail_counts)。
1555
1648
  // 归入当前步的计数,避免升级后「失败轮数」凭空归零。
1556
1649
  s.fail_counts ??= {};
1650
+ s.incomplete_counts ??= {};
1557
1651
  if (typeof s.fail_counts[s.current_step] !== "number" && typeof s.fail_count === "number" && s.fail_count > 0) {
1558
1652
  s.fail_counts[s.current_step] = s.fail_count;
1559
1653
  }
@@ -1580,6 +1674,9 @@ export function createEngine(projectDir, ports) {
1580
1674
  fs.writeFileSync(tmp, JSON.stringify(persisted, null, 2), "utf-8");
1581
1675
  fs.renameSync(tmp, statePath(instId));
1582
1676
  statusErrors.delete(instId);
1677
+ // 终态记录与 state 同一次写:state 是唯一事实源,记录只由它推导。
1678
+ // 放在 rename 之后 —— 只有真正落盘的状态才能成为机器事实。sync 自身永不抛出。
1679
+ syncTerminalRecord(state, instId);
1583
1680
  }
1584
1681
  catch (e) {
1585
1682
  statusErrors.set(instId, "状态写盘失败,当前显示最后确认值。请检查工作区权限或磁盘空间。");
@@ -1587,6 +1684,55 @@ export function createEngine(projectDir, ports) {
1587
1684
  }
1588
1685
  publishStatus();
1589
1686
  }
1687
+ // ─── 结构化终态记录(reports/<instId>.json,契约见 terminal.ts)──────────────
1688
+ //
1689
+ // 两个写入点:暂停态由 `writeState` 统一同步(所有暂停入口都汇聚到它,不会漏),
1690
+ // 终态由 `destroyInstance` 在报告归档后写(只有那时才有 reportPath)。
1691
+ // 恢复运行后移除旧记录,避免一份过期的 `paused` 继续冒充真实状态。
1692
+ /** 把 `state` 的暂停事实投影成记录;`done` / `cancelled` 由 {@link destroyInstance} 调用。 */
1693
+ function writeTerminalRecordFor(state, instId, status, reportPath) {
1694
+ const record = {
1695
+ schemaVersion: TERMINAL_RECORD_SCHEMA_VERSION,
1696
+ instanceId: instId,
1697
+ workflow: state.workflow_name,
1698
+ status,
1699
+ // 引擎的每条暂停路径都会写原因;手改过的老 state 缺字段时如实写 null,不编造原因。
1700
+ pauseReason: status === "paused" ? (state.pause_reason ?? null) : null,
1701
+ reportPath,
1702
+ updatedAt: new Date().toISOString(),
1703
+ };
1704
+ try {
1705
+ writeTerminalRecord(reportsDir, instId, record);
1706
+ }
1707
+ catch (e) {
1708
+ // 终态记录是派生事实:写失败只告警,绝不阻塞状态推进或实例销毁。
1709
+ log("warn", "terminal_record_write_failed", { instId, status, error: msg(e) });
1710
+ }
1711
+ }
1712
+ /** 暂停中 → 落一份 `paused`;其它(运行中 / 恢复后 / 残留)→ 移除旧记录。 */
1713
+ function syncTerminalRecord(state, instId) {
1714
+ if (state.active && state.paused) {
1715
+ if (!state.pause_reason) {
1716
+ // 契约要求 `paused` 必带原因;引擎所有暂停路径都写了原因,缺字段只可能来自手改的
1717
+ // 老状态。与其写一份不合契约的记录,不如不写(宿主 fail-closed)并留下告警。
1718
+ log("warn", "terminal_record_pause_reason_missing", { instId });
1719
+ removeTerminalRecordBestEffort(instId);
1720
+ return;
1721
+ }
1722
+ writeTerminalRecordFor(state, instId, "paused", null);
1723
+ return;
1724
+ }
1725
+ removeTerminalRecordBestEffort(instId);
1726
+ }
1727
+ function removeTerminalRecordBestEffort(instId) {
1728
+ try {
1729
+ removeTerminalRecord(reportsDir, instId);
1730
+ }
1731
+ catch (e) {
1732
+ // 删不掉就说出来:一份过期的 paused 会让机器宿主误判真实终态。
1733
+ log("warn", "terminal_record_remove_failed", { instId, error: msg(e) });
1734
+ }
1735
+ }
1590
1736
  /** 某步当前的失败轮数(按步计数;缺省 0) */
1591
1737
  function failCountOf(state, stepId) {
1592
1738
  const id = stepId ?? state.current_step;
@@ -1607,6 +1753,70 @@ export function createEngine(projectDir, ports) {
1607
1753
  state.fail_counts[stepId] = 0;
1608
1754
  state.fail_count = failCountOf(state);
1609
1755
  }
1756
+ /** 某步当前的「模型自报未完成」次数(按步计数;缺省 0) */
1757
+ function incompleteCountOf(state, stepId) {
1758
+ const id = stepId ?? state.current_step;
1759
+ const n = state.incomplete_counts?.[id];
1760
+ return typeof n === "number" ? n : 0;
1761
+ }
1762
+ /**
1763
+ * 记一次「模型自报未完成」并返回该步累计次数。
1764
+ *
1765
+ * **唯一调用点**:onSubmit 的 `submit_incomplete` 分支。CHECK 判定失败绝不走这里 ——
1766
+ * 那一条线是 {@link bumpFailCount}(`fail_counts` / `max_fail_count`),两条线互不干扰。
1767
+ */
1768
+ function bumpIncompleteCount(state, stepId) {
1769
+ state.incomplete_counts ??= {};
1770
+ const n = incompleteCountOf(state, stepId) + 1;
1771
+ state.incomplete_counts[stepId] = n;
1772
+ return n;
1773
+ }
1774
+ /**
1775
+ * 该步的按轮计数清零(**验证通过**与**进入该步**两处调用)。
1776
+ *
1777
+ * 同时清 `round_reset_marks`:阈值序号是 `floor(count / 3)` 的记账,计数归零后它必须一起
1778
+ * 归零,否则下次进入该步时「已换过第 1 个阈值」的旧账会挡住新的一轮。
1779
+ */
1780
+ function clearIncompleteCount(state, stepId) {
1781
+ state.incomplete_counts ??= {};
1782
+ state.round_reset_marks ??= {};
1783
+ state.incomplete_counts[stepId] = 0;
1784
+ state.round_reset_marks[stepId] = 0;
1785
+ }
1786
+ /**
1787
+ * 本步的按轮计数快照(给 {@link resetCauseOf} 用)。
1788
+ *
1789
+ * 阈值是常量 {@link ROUND_RESET_THRESHOLD}:任何步骤都按同一个频率做按轮重置,没有按步开关。
1790
+ */
1791
+ function roundResetCounterOf(state, step) {
1792
+ return {
1793
+ count: incompleteCountOf(state, step.id),
1794
+ applied: state.round_reset_marks?.[step.id] ?? 0,
1795
+ };
1796
+ }
1797
+ /**
1798
+ * 记下「第 seq 个阈值已经换过」——**只在替换成功之后**调用(`deliverStepDo` 的 ok 分支)。
1799
+ *
1800
+ * 为什么重新读盘而不是写手里的 state:替换是异步的(等空闲窗口),这段时间里实例可能已经
1801
+ * 推进/取消;拿闭包快照写盘会把过期状态盖回去。读不到 / 已换步 / 已收摊就**不记**
1802
+ * (代价只是下一轮多重试一次替换,绝不会丢事实)。
1803
+ */
1804
+ function markRoundResetApplied(instId, stepId, seq) {
1805
+ try {
1806
+ const cur = readState(instId);
1807
+ if (!cur || cur.active !== true || cur.current_step !== stepId)
1808
+ return;
1809
+ cur.round_reset_marks ??= {};
1810
+ const prev = cur.round_reset_marks[stepId] ?? 0;
1811
+ if (seq <= prev)
1812
+ return;
1813
+ cur.round_reset_marks[stepId] = seq;
1814
+ writeState(cur, instId);
1815
+ }
1816
+ catch (e) {
1817
+ log("warn", "round_reset_mark_failed", { instId, step: stepId, seq, error: msg(e) });
1818
+ }
1819
+ }
1610
1820
  function pushHistory(state, event, detail, step) {
1611
1821
  state.history.push({ ts: new Date().toISOString(), event, detail, step: step ?? state.current_step });
1612
1822
  if (state.history.length > 200)
@@ -1650,7 +1860,8 @@ export function createEngine(projectDir, ports) {
1650
1860
  const startedAt = field("开始");
1651
1861
  const endedAt = field("结束");
1652
1862
  const artifactsRel = strip(field("产出目录"));
1653
- const artifactsDirName = artifactsRel ? artifactsRel.replace(/\/+$/, "").split("/").pop() : undefined;
1863
+ // 产出目录可能是工作区相对路径或绝对路径:只看最后一段目录名。
1864
+ const artifactsDirName = artifactsRel ? path.basename(artifactsRel.replace(/[\\/]+$/, "")) : undefined;
1654
1865
  const workflow = /^#\s*ralphflow 报告 ·\s*(.+)$/m.exec(text)?.[1]?.trim();
1655
1866
  const statusLabel = statusRaw.includes("完成") ? "完成" : statusRaw.includes("取消") ? "取消" : undefined;
1656
1867
  return {
@@ -1686,7 +1897,7 @@ export function createEngine(projectDir, ports) {
1686
1897
  text = fs.readFileSync(path.join(reportsDir, f), "utf-8");
1687
1898
  }
1688
1899
  catch { }
1689
- return parseReportHeader(`${RALPH_FLOW_DIR}/reports/${f}`, id, text);
1900
+ return parseReportHeader(reportPathOf(id), id, text);
1690
1901
  });
1691
1902
  const key = (h) => {
1692
1903
  const t = h.endedAt ? new Date(h.endedAt).getTime() : NaN;
@@ -1818,7 +2029,7 @@ export function createEngine(projectDir, ports) {
1818
2029
  */
1819
2030
  function doPrompt(instId, wf, state, step, rework, rewind, continuation) {
1820
2031
  const idx = wf.steps.findIndex((s) => s.id === step.id) + 1;
1821
- const rel = artifactsRelDirOf(instId);
2032
+ const rel = artifactsDisplayDirOf(instId);
1822
2033
  const hasCheck = stepHasVerification(step);
1823
2034
  const voters = voterCountOf(step);
1824
2035
  const assetRef = assetReferenceSection(assetRootOf(assetPathOfStep(wf, step)));
@@ -1890,6 +2101,8 @@ export function createEngine(projectDir, ports) {
1890
2101
  */
1891
2102
  function skipVerification(instId, state, wf, step) {
1892
2103
  noteCheckSkipped(instId, state, step);
2104
+ // 免验证步的「通过」= 交卷这一刻(没有验证者可等):按轮重置的计数在这里清零。
2105
+ clearIncompleteCount(state, step.id);
1893
2106
  writeState(state, instId);
1894
2107
  if (isGate(wf, step)) {
1895
2108
  // 停在审查门的两种打开方式都要留痕:这里是「无检查依据的纯人工审查」
@@ -1951,7 +2164,7 @@ export function createEngine(projectDir, ports) {
1951
2164
  verdict = await ports.verify({
1952
2165
  instId, step, workflow: wf, userTask: effectiveTaskOf(step, state.user_task),
1953
2166
  assetPath: assetPathOfStep(wf, step),
1954
- ownerSession: state.owner_session, checkIndex, artifactsRelDir: artifactsRelDirOf(instId),
2167
+ ownerSession: state.owner_session, checkIndex, artifactsRelDir: artifactsDisplayDirOf(instId),
1955
2168
  // 验证模型优先级链(对齐 opencode resolveVerifierModel):
1956
2169
  // 步骤 check_model > 全局 adversarial_check.model > 发起会话当前模型
1957
2170
  //(没有覆盖时不传 agentOptions,由宿主 resolveChildAgentOptions 继承父级)
@@ -2048,7 +2261,7 @@ export function createEngine(projectDir, ports) {
2048
2261
  ownerSession: state.owner_session, checkIndex: index,
2049
2262
  // 该票的专属检查依据 + 序号:verify.ts 据此生成「你是 N 个之一」的投票提示词。
2050
2263
  voter: { index: index + 1, count, check: entry.check },
2051
- artifactsRelDir: artifactsRelDirOf(instId),
2264
+ artifactsRelDir: artifactsDisplayDirOf(instId),
2052
2265
  // 模型优先级链(对齐 opencode):**该票 `model`** > 全局 `adversarial_check.model` >
2053
2266
  // 发起会话当前模型。(`check_voting` 与步骤 `check_model` 同写是加载期硬错误,
2054
2267
  // 所以这条链上没有 check_model 那一级。)
@@ -2248,6 +2461,10 @@ export function createEngine(projectDir, ports) {
2248
2461
  state.do_submitted = false;
2249
2462
  state.verdicts = [];
2250
2463
  state.delegations = [];
2464
+ // 返工理由一律进轨迹(**两条路径都写**):交接稿的「最近 3 轮未完成的原因」从这里取,
2465
+ // 换干净上下文后模型才不会重复试已被验证者排除的路。同步骤返工以前什么都不写,
2466
+ // 于是 reset 后的交接稿看不到「上一轮为什么没过」—— 补这一条就是为了那条通道。
2467
+ pushHistory(state, "rework", reason.slice(0, 300), step.id);
2251
2468
  if (target.id !== step.id) {
2252
2469
  state.current_step = target.id;
2253
2470
  pushHistory(state, "rework_rewind", `${step.id} → ${target.id}`, target.id);
@@ -2259,6 +2476,8 @@ export function createEngine(projectDir, ports) {
2259
2476
  }
2260
2477
  // 全 passed(且判定属于当前步)
2261
2478
  clearFailCount(state, step.id);
2479
+ // 该步验证通过 = 这一轮循环了结:按轮重置的自报未完成计数一并清零(下次进来从 0 起算)。
2480
+ clearIncompleteCount(state, step.id);
2262
2481
  if (isGate(wf, step) && allPassedVerified(state, step)) {
2263
2482
  // 审查门打开(有 check:验证通过后停门等放行)
2264
2483
  logEvent(instId, "info", "gate_opened", { step: step.id, kind: "verified", ms: Date.now() - startedAt });
@@ -2303,6 +2522,10 @@ export function createEngine(projectDir, ports) {
2303
2522
  // 不在这里清 fail_counts:通过时已 `clearFailCount`(该步失败史了结)。
2304
2523
  // 若用 on_fail 回退到一个「失败过但尚未通过」的步骤,它自己的计数应保留 ——
2305
2524
  // 这既避免把前一步的失败算到它头上,也让成环的 on_fail 仍能触及 max_fail_count。
2525
+ //
2526
+ // 按轮重置的计数不同:它是「同一轮循环里模型自报了几次没做完」,进入本步就是新一轮,
2527
+ // 必须从 0 起算(否则上一步留下的旧账会让新步第一次投递就换上下文)。
2528
+ clearIncompleteCount(state, next.id);
2306
2529
  pushHistory(state, "step_start", next.desc ?? "", next.id);
2307
2530
  logEvent(instId, "info", "step_start", { step: next.id });
2308
2531
  writeState(state, instId);
@@ -2326,7 +2549,7 @@ export function createEngine(projectDir, ports) {
2326
2549
  // 销毁顺序与失败分支都在 destroyInstance 里(不变量 2/3)。
2327
2550
  const destroyed = destroyInstance(instId, "done", state);
2328
2551
  if (destroyed) {
2329
- const rel = reportRelPathOf(instId);
2552
+ const rel = reportPathOf(instId);
2330
2553
  // 诚实播报:只有**复查确认**实例目录真没了,才说「已销毁」;否则如实说残留并指向 doctor。
2331
2554
  if (destroyed.instanceDirRemoved) {
2332
2555
  notify(state, `✅ 工作流 \`${wf.name}\` 完成,报告已归档到 \`${rel}\`。\n\n实例目录已销毁、产出目录保留;报告与产出是永久的,需要时按上面这个路径翻。`, `✅ 工作流 ${wf.name} 完成(报告 ${rel})`);
@@ -2358,7 +2581,7 @@ export function createEngine(projectDir, ports) {
2358
2581
  const instId = stateIds.get(state);
2359
2582
  const ended = state.history.some((h) => h.event === "cancelled") ? "cancelled" : "done";
2360
2583
  const uiRef = !state.active && instId && fs.existsSync(path.join(reportsDir, `${instId}.md`))
2361
- ? { v: 1, runId: instId, reportRef: reportRelPathOf(instId), ended } : undefined;
2584
+ ? { v: 1, runId: instId, reportRef: reportPathOf(instId), ended } : undefined;
2362
2585
  const ok = ports.deliverNotice(state.owner_session, text, summary, { dedupe: false, ...(uiRef ? { uiRef } : {}) });
2363
2586
  if (!ok)
2364
2587
  log("warn", "deliver_notice_failed", { instId: state.owner_session });
@@ -2374,7 +2597,7 @@ export function createEngine(projectDir, ports) {
2374
2597
  * `"call"` 支需要**调用点 id**(`step.reset_from_call`)才说得出「哪个调用点标的」——
2375
2598
  * 传不进 step 时退回不带 id 的说法,绝不编一个 id 出来。
2376
2599
  */
2377
- function resetSourceText(trigger, step) {
2600
+ function resetSourceText(trigger, step, every) {
2378
2601
  switch (trigger) {
2379
2602
  case "step": return "本步标了 `reset: true`";
2380
2603
  case "auto": return "本工作流标了 `auto_reset: true`(等价于每一步都标 reset)";
@@ -2384,6 +2607,12 @@ export function createEngine(projectDir, ports) {
2384
2607
  ? `调用点 \`${at}\` 上标了 \`reset: true\`(进入子工作流 = 首个展开后子步骤的重置)`
2385
2608
  : "子工作流调用点上标了 `reset: true`(进入子工作流 = 首个展开后子步骤的重置)";
2386
2609
  }
2610
+ // 按轮门的措辞必须说清「为什么是现在」:不是进入本步,而是模型自报未完成攒够了阈值。
2611
+ // 阈值是引擎固定的默认行为,**没有作者配置**——一律说「引擎默认每 3 次」。
2612
+ case "every": {
2613
+ const rounds = every?.count ?? 0;
2614
+ return `引擎默认每 ${ROUND_RESET_THRESHOLD} 次自报未完成换一次上下文:模型已自报未完成 ${rounds} 次,第 ${Math.max(1, Math.floor(rounds / ROUND_RESET_THRESHOLD))} 个阈值到了`;
2615
+ }
2387
2616
  case "manual": return "用户执行了 `/ralphflow-reset`";
2388
2617
  // 回退是**用户手里的换方向入口**:它不只是换上下文,还会把状态机拨回更早的步骤
2389
2618
  // 并带上原因。措辞必须说出是哪个命令做的,否则用户会以为这是自动门的机械动作。
@@ -2396,6 +2625,7 @@ export function createEngine(projectDir, ports) {
2396
2625
  case "step": return "标了 `reset: true`";
2397
2626
  case "auto": return "工作流级 `auto_reset: true`";
2398
2627
  case "call": return step?.reset_from_call ? `调用点 \`${step.reset_from_call}\` 标了 \`reset: true\`` : "调用点标了 `reset: true`";
2628
+ case "every": return `引擎默认每 ${ROUND_RESET_THRESHOLD} 次自报未完成已攒够阈值`;
2399
2629
  case "manual": return "用户执行了 `/ralphflow-reset`";
2400
2630
  case "rewind": return "用户执行了 `/ralphflow-rewind`";
2401
2631
  }
@@ -2415,9 +2645,9 @@ export function createEngine(projectDir, ports) {
2415
2645
  }
2416
2646
  }
2417
2647
  /**
2418
- * `/ralphflow-reset` 在空闲窗口复查时发现「实例已不在可重置状态」→ 一句给用户的实话。
2648
+ * 手动重置 / 回退在空闲窗口复查时发现「实例已不在可投递状态」→ 一句给用户的实话。
2419
2649
  *
2420
- * 为什么必须告知(分配置护栏 ③ 的边界):手动重置是**异步**落地的(要等空闲窗口),而
2650
+ * 为什么必须告知(分配置护栏 ③ 的边界):两者都是**异步**落地的(要等空闲窗口),而
2421
2651
  * 命令处理器当场就返回了 `{kind:"success"}`(零程序化卡片)。若被丢弃时静默 return,
2422
2652
  * 用户在最需要这个手动逃生口的时刻(模型在飞、回合以 `ralphflow_submit` 收尾)会
2423
2653
  * 「按了命令、什么都没发生」——命令说受理、结果无声作废(验证者 2/4 实测)。
@@ -2425,7 +2655,7 @@ export function createEngine(projectDir, ports) {
2425
2655
  * 具体原因**重新读盘**再分述(`stillLive()` 只回一个布尔,说不出是哪一条):读不到就退回
2426
2656
  * 通用说法,绝不编造。
2427
2657
  */
2428
- function manualResetDropNote(instId, stepId) {
2658
+ function resetDropReason(instId, stepId) {
2429
2659
  let why = "实例状态在这段空闲窗口里发生了变化";
2430
2660
  try {
2431
2661
  const cur = readState(instId);
@@ -2435,29 +2665,72 @@ export function createEngine(projectDir, ports) {
2435
2665
  why = "实例已结束或被取消";
2436
2666
  else if (cur.current_step !== stepId)
2437
2667
  why = `工作流已推进到步骤 \`${cur.current_step}\``;
2668
+ else if (cur.paused === true)
2669
+ why = `实例已暂停(${pauseLabel(cur.pause_reason)})`;
2438
2670
  else if (cur.do_submitted === true)
2439
2671
  why = `步骤 \`${stepId}\` 已经交卷(独立验证者正在取证,或已停在审查门)`;
2440
2672
  }
2441
2673
  catch { /* 读不到就退回通用说法 */ }
2674
+ return why;
2675
+ }
2676
+ /** `/ralphflow-reset` 的丢弃告知(与回退同形;措辞必须说得出是哪条命令)。 */
2677
+ function manualResetDropNote(instId, stepId) {
2678
+ const why = resetDropReason(instId, stepId);
2442
2679
  return {
2443
2680
  text: `[ralphflow] 你执行了 \`/ralphflow-reset\`,但**这次重置没有生效**:${why}。\n\n重置只换干净上下文(返工计数原样保留),且只能落在**当前步 DO 阶段的空闲窗口**里 —— 否则会打断在飞验证、把已有判定变成孤儿。用 \`/ralphflow-status\` 看进度;等本步返工、或进入下一步的 DO 之后,再执行一次 \`/ralphflow-reset\`。`,
2444
2681
  summary: `⚠️ /ralphflow-reset 未生效:${why}`,
2445
2682
  };
2446
2683
  }
2684
+ /**
2685
+ * `/ralphflow-rewind` 的丢弃告知:状态机已经拨到目标步,但换上下文 / 目标步 DO 没落地
2686
+ * (实例被取消、被暂停、或已推进到别的步骤)。绝不能静默 —— 用户会以为模型已经拿到
2687
+ * 新任务书,实际它仍在按旧方向跑。
2688
+ */
2689
+ function rewindDropNote(instId, stepId) {
2690
+ const why = resetDropReason(instId, stepId);
2691
+ return {
2692
+ text: `[ralphflow] 你执行了 \`/ralphflow-rewind\`,但**这次回退的换上下文与目标步 DO 没有落地**:${why}。\n\n用 \`/ralphflow-status\` 看当前进度;实例仍在运行时,等它回到 DO 阶段后再执行一次 \`/ralphflow-rewind\`;需要恢复暂停用 \`/ralphflow-continue\`。`,
2693
+ summary: `⚠️ /ralphflow-rewind 的换上下文与 DO 重投未落地:${why}`,
2694
+ };
2695
+ }
2696
+ /**
2697
+ * 交接稿的「最近 3 轮未完成的原因」段 —— 换干净上下文**之前**的那几轮为什么没做完。
2698
+ *
2699
+ * 数据只从已有的 `state.history` 取(`submit_incomplete` = 模型自报的未完成清单;
2700
+ * `rework` = 验证未通过时的返工理由),**不新增任何状态字段**;一条都没有时整段省略
2701
+ * (首次进入的步骤不该凭空多出一段空标题)。
2702
+ *
2703
+ * 为什么必须给:上下文一换,模型就再也看不到「上一轮试过什么、为什么被否」。只给任务书
2704
+ * 会让它重复走已被排除的路 —— 这正是「reset 后还是做不完」的常见原因。detail 截断到
2705
+ * 约 200 字符:交接稿会被自动压缩,写长了等于没写。
2706
+ */
2707
+ function recentUnfinishedSection(state, stepId) {
2708
+ const picked = state.history.filter((h) => h.step === stepId && (h.event === "submit_incomplete" || h.event === "rework"));
2709
+ if (picked.length === 0)
2710
+ return [];
2711
+ const lines = picked.slice(-3).map((h) => {
2712
+ const detail = String(h.detail ?? "").replace(/\s+/g, " ").trim().slice(0, 200);
2713
+ const body = h.event === "submit_incomplete" ? (detail || "(未留下未完成清单)") : `返工 · ${detail || "(验证者未给出理由)"}`;
2714
+ return `- ${h.ts}:${body}`;
2715
+ });
2716
+ return ["", "## 本步骤最近 3 轮未完成的原因", ...lines];
2717
+ }
2447
2718
  /**
2448
2719
  * 组装 reset 门的投递物:**交接稿**(模型可见,写小——会被 dsh 自动压缩总结掉)+
2449
2720
  * **可见告知**(append 来源,Chat 显示;随后被同一次替换遮蔽,模型看不到)。
2450
2721
  *
2451
2722
  * 交接稿只写**能现算**的四项(决定①:不含「已完成勾选」,因此不新增任何状态字段):
2452
- * 工作流名 / 第几步 / 产出目录 / 交互契约。任务描述不必写 —— 紧随其后的 DO 提示词
2453
- * 自带「## 任务」;**回退原因同样不进交接稿**(它在 DO 里自成一段:换上下文失败时
2454
- * DO 照样带着原因落地,交接稿写不写都不改变这一点)。
2723
+ * 工作流名 / 第几步 / 产出目录 / 交互契约;若该步有「最近 3 轮未完成」的记录,再附一段
2724
+ * {@link recentUnfinishedSection}(同样是现算的 history,不落新字段)。任务描述不必写 ——
2725
+ * 紧随其后的 DO 提示词自带「## 任务」;**回退原因同样不进交接稿**(它在 DO 里自成一段:
2726
+ * 换上下文失败时 DO 照样带着原因落地,交接稿写不写都不改变这一点)。
2455
2727
  *
2456
2728
  * `rewind` 只用于**可见告知**的措辞(说清是从哪一步退回本步的)。
2729
+ * `every` 只用于按轮门的措辞(第几次自报未完成触发的)。
2457
2730
  */
2458
- function resetRequestFor(instId, wf, step, trigger, rewind) {
2731
+ function resetRequestFor(state, instId, wf, step, trigger, rewind, every) {
2459
2732
  const idx = wf.steps.findIndex((s) => s.id === step.id) + 1;
2460
- const rel = artifactsRelDirOf(instId);
2733
+ const rel = artifactsDisplayDirOf(instId);
2461
2734
  const hasCheck = stepHasVerification(step);
2462
2735
  const voters = voterCountOf(step);
2463
2736
  const contract = hasCheck
@@ -2474,6 +2747,9 @@ export function createEngine(projectDir, ports) {
2474
2747
  `- 当前步骤:\`${step.id}\`${step.desc ? ` — ${step.desc}` : ""}`,
2475
2748
  `- 产出目录:\`${rel}/\``,
2476
2749
  `- 交互契约:${contract}`,
2750
+ // 「最近 3 轮未完成的原因」插在交互契约之后、收尾句之前:一条记录都没有时整段省略,
2751
+ // 于是首次进入的步骤交接稿与改造前**逐字相同**(回归基线)。
2752
+ ...recentUnfinishedSection(state, step.id),
2477
2753
  "",
2478
2754
  "请只依据本稿与紧随其后的本步 DO 提示行事(原始记录仍留在会话日志里,可复盘)。",
2479
2755
  ].join("\n");
@@ -2493,12 +2769,20 @@ export function createEngine(projectDir, ports) {
2493
2769
  summary: `↩️ 已按 /ralphflow-rewind 回退到步骤 ${step.id},重投其 DO`,
2494
2770
  text: `[ralphflow] 用户执行了 \`/ralphflow-rewind\`:工作流已${rewind?.from ? `从步骤 \`${rewind.from}\` ` : ""}回退到 \`${step.id}\`,**暂停与失败计数已清**、本轮判定与在飞验证已作废。属主会话上下文已整段替换为一条交接稿,本步 DO 随即重投——**用户给出的回退原因写在 DO 里**(自成一段;换上下文失败时 DO 照样带着原因落地)。⚠️ 下游旧产出仍在盘上、基于旧方向,不会自动作废。本行是给用户看的可见告知——替换节点在 Chat 里不显示,模型上下文里也没有这条告知。`,
2495
2771
  }
2496
- : {
2497
- summary: `♻️ 步骤 ${step.id} 开始前已重置上下文(${resetSourceShort(trigger, step)})`,
2498
- // 这条告知是给用户看的:替换消息本身在 Chat 里不显示,不告知就成了
2499
- // 「用户看到的 ≠ 模型看到的」且是静默的(决定②)。
2500
- text: `[ralphflow] 本步(\`${step.id}\`)开始前做了上下文重置(来源:${resetSourceText(trigger, step)}):此前对话已移出模型上下文,整段替换为一条交接稿(工作流 / 步骤 / 产出目录 / 交互契约)。本行是给用户看的可见告知——替换节点在 Chat 里不显示,模型上下文里也没有这条告知。`,
2501
- },
2772
+ : trigger === "every"
2773
+ ? {
2774
+ summary: `♻️ 步骤 ${step.id} 按轮重置上下文(模型已自报未完成 ${every?.count ?? 0} 次)`,
2775
+ // 这条告知必须说清「为什么是现在」:不是进入本步,而是同一轮循环里模型自报
2776
+ // 未完成攒够了阈值。也绝不能写成「本步标了 reset: true」(作者没标)。
2777
+ // 阈值是引擎固定的默认行为,措辞统一由 resetSourceText 给「引擎默认每 3 次」。
2778
+ text: `[ralphflow] ${resetSourceText(trigger, step, every)}:在下一轮任务书投递前换了一次干净上下文,整段替换为一条交接稿(工作流 / 步骤 / 产出目录 / 交互契约,以及最近 3 轮未完成的原因)。**返工计数与失败预算原样保留**(重置只换干净上下文,不赦免失败)。本行是给用户看的可见告知——替换节点在 Chat 里不显示,模型上下文里也没有这条告知。`,
2779
+ }
2780
+ : {
2781
+ summary: `♻️ 步骤 ${step.id} 开始前已重置上下文(${resetSourceShort(trigger, step)})`,
2782
+ // 这条告知是给用户看的:替换消息本身在 Chat 里不显示,不告知就成了
2783
+ // 「用户看到的 ≠ 模型看到的」且是静默的(决定②)。
2784
+ text: `[ralphflow] 本步(\`${step.id}\`)开始前做了上下文重置(来源:${resetSourceText(trigger, step)}):此前对话已移出模型上下文,整段替换为一条交接稿(工作流 / 步骤 / 产出目录 / 交互契约)。本行是给用户看的可见告知——替换节点在 Chat 里不显示,模型上下文里也没有这条告知。`,
2785
+ },
2502
2786
  };
2503
2787
  }
2504
2788
  /**
@@ -2511,39 +2795,84 @@ export function createEngine(projectDir, ports) {
2511
2795
  * (实测:`pause_reason=no_submit`,DO 反而落在已暂停的实例上)。
2512
2796
  */
2513
2797
  const pendingDoDelivery = new Set();
2798
+ /**
2799
+ * 上面那批里**由回退发起**的一段(`trigger === "rewind"`)。
2800
+ *
2801
+ * 只有回退会把 `current_step` 换掉:旧回合手里的任务书指向**上一步**,它在这段窗口里交的
2802
+ * 卷绝不能记到目标步上 —— `onSubmit` 据此拒收。手动重置不在此列:`current_step` 没变,
2803
+ * 同一个步骤的旧交卷仍然算数(交卷赢、异步重置被丢弃并如实告知),这是 reset-surface
2804
+ * 用例 17 钉住的既有语义。
2805
+ */
2806
+ const pendingRewindDelivery = new Set();
2514
2807
  /**
2515
2808
  * 投递某一步的 DO。**要重置上下文的步骤先做整段替换、再投递 DO**(顺序不可颠倒:
2516
2809
  * DO 若先落地就会被自己这次替换一并遮蔽掉)。
2517
2810
  *
2518
- * 触发来源四类,全走这一根接线(不再有第二条重置路径):
2811
+ * 触发来源五类,全走这一根接线(**这是重置判定的唯一判据点**,不再有第二条重置路径):
2519
2812
  * · 步骤级 `reset: true` / 工作流级 `auto_reset: true`(advance 与返工都经这里);
2813
+ * · 按轮门(`"every"`:模型自报未完成每攒够 3 次 → 换一次,同一阈值只换一次,固定不可配置);
2520
2814
  * · 手动 `/ralphflow-reset`(`opts.manual`:**无论该步有没有标 reset 都强制重置**);
2521
2815
  * · 用户 `/ralphflow-rewind`(`opts.rewind`:同样强制重置,并把**回退原因**带进 DO ——
2522
2816
  * 原因写进 DO 而不是只写交接稿:换上下文失败时 DO 照样带着原因落地)。
2523
2817
  *
2818
+ * `opts.round`:这次投递是**新的一轮**(回合收尾的提醒)→ 用 `deliverRound`(followup)
2819
+ * 而不是 `steer`。载体差别是宿主语义:`steer` 会把正在收尾的回合续上(「一轮 ≠ 一个回合」),
2820
+ * `followup` 让本回合正常结束、提醒成为下一回合的第一条消息。
2821
+ *
2822
+ * `opts.composeDo`:把 DO 正文包成调用方要投递的文本(提醒的前缀行、免验证说明等)。
2823
+ *
2524
2824
  * 替换是异步的(宿主的 `runMaintenance` 返回 Promise),所以这里用 promise 链保证顺序;
2525
2825
  * **失败绝不吞掉 DO** —— 照常投递,并把失败原因如实写进用户可见的播报行。
2526
2826
  *
2527
2827
  * 所有播报的「为什么重置」都经 {@link resetSourceText} 按来源分述 —— `auto_reset` 带出的
2528
2828
  * 重置绝不被说成「本步标了 `reset: true`」(作者没标)。
2829
+ *
2830
+ * 返回**将要投递的文本**(调用方需要回执原文时用;投递本身是脱手的)。
2529
2831
  */
2530
2832
  function deliverStepDo(state, instId, wf, step, summary, rework, opts) {
2531
2833
  // 新的 DO 开始 = 实例重新需要属主(可能刚从审查门/暂停回来,心跳曾被定时器丢弃)。
2532
2834
  startDriving(instId);
2533
- const text = doPrompt(instId, wf, state, step, rework, opts?.rewind);
2835
+ // 本轮清单(上一轮记下的未完成项)从 history 现算:它跨 reset 存活,正是换干净上下文后
2836
+ // 最该接着做的东西。没有(新步/已交卷)时 doPrompt 不写这一段。
2837
+ const baseDo = doPrompt(instId, wf, state, step, rework, opts?.rewind ?? opts?.rewindNote, lastCheckpointOf(state, step.id) ?? undefined);
2838
+ const text = opts?.composeDo ? opts.composeDo(baseDo) : baseDo;
2534
2839
  const sid = state.owner_session;
2535
- const trigger = opts?.rewind ? "rewind" : opts?.manual ? "manual" : resetCauseOf(wf, step);
2840
+ // 按轮门的计数快照(固定每 3 次自报未完成换一次)。
2841
+ const every = roundResetCounterOf(state, step);
2842
+ // **唯一判据点**:静态门 + 按轮门一起算。`sameVisit` 说明这次不是「进入本步」(回合收尾
2843
+ // 提醒 / 解除暂停后继续)→ 静态门不重复触发,但按轮门照常生效。手动 / 回退是强制替换,
2844
+ // 来源由命令决定,覆盖判定的 trigger;它们同样会把本次到期的按轮阈值记为已用。
2845
+ const decision = resetCauseOf(wf, step, every, { skipStatic: opts?.sameVisit === true });
2846
+ const trigger = opts?.rewind
2847
+ ? "rewind"
2848
+ : opts?.manual
2849
+ ? "manual"
2850
+ : decision.trigger;
2851
+ // 本次到期的按轮阈值序号:**只有真要替换时**才记账(不替换就绝不能消耗阈值)。
2852
+ // 静态门 / 手动 / 回退赢的时候它也 > 0 —— 同一次投递最多替换一次,上下文已经干净,
2853
+ // 下一轮不该为同一个阈值再换一次。
2854
+ const everySeq = trigger === undefined ? 0 : decision.everySeq;
2855
+ // 载体:本轮提醒走 followup(新回合),其余照旧走 steer(回合内唤醒)。
2856
+ // 两条都传 `dedupe:false`(引擎自驱的投递不去重:去重会吞掉真实迁移,见 deliverDirective 端口注释)。
2857
+ const send = (s, sm) => {
2858
+ if (opts?.round && typeof ports.deliverRound === "function") {
2859
+ if (!ports.deliverRound(sid, s, sm, { dedupe: false }))
2860
+ log("warn", "deliver_round_failed", { instId, step: step.id });
2861
+ return;
2862
+ }
2863
+ deliverDirective(state, s, sm);
2864
+ };
2536
2865
  if (trigger === undefined || !sid) {
2537
- deliverDirective(state, text, summary);
2538
- return;
2866
+ send(text, summary);
2867
+ return text;
2539
2868
  }
2540
2869
  if (typeof ports.resetSurface !== "function") {
2541
2870
  // 端口没装配:不假装做过(要重置的步骤也照常执行,只是没有重置)
2542
2871
  log("warn", "reset_surface_unavailable", { instId, step: step.id, trigger });
2543
- deliverDirective(state, text, `${summary}(⚠️ ${resetSourceText(trigger, step)},但本进程未装配重置端口:上下文未重置)`);
2544
- return;
2872
+ send(text, `${summary}(⚠️ ${resetSourceText(trigger, step, every)},但本进程未装配重置端口:上下文未重置)`);
2873
+ return text;
2545
2874
  }
2546
- const req = resetRequestFor(instId, wf, step, trigger, opts?.rewind);
2875
+ const req = resetRequestFor(state, instId, wf, step, trigger, opts?.rewind, every);
2547
2876
  // 替换之前先把**挂起的播报**补齐:它们因工具调用在飞而没能立刻 append,若拖到替换之后
2548
2877
  // 才落,就会站在交接稿后面,破坏「替换后表面 = 系统提示 + 交接稿 + DO」(判据 5)。
2549
2878
  // 此刻可见面必须配平(否则替换本身也会被判 unbalanced 放弃),所以这一步几乎总能落成。
@@ -2570,8 +2899,14 @@ export function createEngine(projectDir, ports) {
2570
2899
  req.canProceed = stillLive; // 载体在 append 之前同步复查一次(关掉「等窗口期间被取消」的竞态)
2571
2900
  // 从这一刻起「本步 DO 还没送达」——期间 turn-stopping 的回合收尾提醒必须闭嘴
2572
2901
  pendingDoDelivery.add(instId);
2902
+ if (trigger === "rewind")
2903
+ pendingRewindDelivery.add(instId);
2573
2904
  publishStatus();
2574
- const releasePending = () => { pendingDoDelivery.delete(instId); publishStatus(); };
2905
+ const releasePending = () => {
2906
+ pendingDoDelivery.delete(instId);
2907
+ pendingRewindDelivery.delete(instId);
2908
+ publishStatus();
2909
+ };
2575
2910
  void Promise.resolve()
2576
2911
  .then(() => ports.resetSurface(sid, req))
2577
2912
  .then((outcome) => {
@@ -2592,24 +2927,42 @@ export function createEngine(projectDir, ports) {
2592
2927
  logEvent(instId, "warn", "manual_reset_dropped", { step: step.id, reason });
2593
2928
  deliverNotice(state, note.text, note.summary);
2594
2929
  }
2930
+ // 回退**无论替换成败**都要告知:状态机已经拨到目标步,但模型没收到新任务书。
2931
+ // 静默会让用户以为回退生效(真机缺陷里 `replace` 为 0、用户却只看到命令受理)。
2932
+ if (trigger === "rewind") {
2933
+ const note = rewindDropNote(instId, step.id);
2934
+ logEvent(instId, "warn", "rewind_dropped", { step: step.id, reason });
2935
+ deliverNotice(state, note.text, note.summary);
2936
+ }
2595
2937
  return;
2596
2938
  }
2597
2939
  if (outcome.ok) {
2598
- log("info", "reset_surface_applied", { instId, step: step.id, trigger, shadowed: outcome.shadowed });
2599
- logEvent(instId, "info", "reset_surface", { step: step.id, trigger, shadowed: outcome.shadowed, handoffSeq: outcome.handoffSeq, noticeSeq: outcome.noticeSeq });
2600
- deliverDirective(state, text, summary);
2940
+ log("info", "reset_surface_applied", { instId, step: step.id, trigger, shadowed: outcome.shadowed, rounds: every?.count, threshold: everySeq });
2941
+ logEvent(instId, "info", "reset_surface", {
2942
+ step: step.id, trigger, shadowed: outcome.shadowed, handoffSeq: outcome.handoffSeq, noticeSeq: outcome.noticeSeq,
2943
+ // `rounds` / `threshold` 只在本次确实消耗了一个按轮阈值时才有意义 —— 包括
2944
+ // **静态门先赢、顺手把到期阈值记为已用**的情况(否则事后看日志会以为下一轮漏换)。
2945
+ // 它让 execution.log 能直接复盘「第 3、6 轮各换了一次」,不必再从别的事件反推。
2946
+ ...(everySeq > 0 ? { rounds: every?.count, threshold: everySeq } : {}),
2947
+ });
2948
+ // 阈值**换成了**才记账(同一阈值只换一次);换失败不记 → 下一轮自然重试。
2949
+ // 任何来源的替换都记:同一次投递最多换一次,上下文已经干净,按轮门不该再为它换一次。
2950
+ if (everySeq > 0)
2951
+ markRoundResetApplied(instId, step.id, everySeq);
2952
+ send(text, summary);
2601
2953
  return;
2602
2954
  }
2603
- log("warn", "reset_surface_skipped", { instId, step: step.id, trigger, reason: outcome.reason, detail: outcome.detail });
2604
- logEvent(instId, "warn", "reset_surface_skipped", { step: step.id, trigger, reason: outcome.reason ?? "unknown", detail: outcome.detail });
2605
- deliverDirective(state, text, `${summary}(⚠️ ${resetSourceText(trigger, step)},但本次上下文重置未生效:${resetFailureText(outcome)})`);
2955
+ log("warn", "reset_surface_skipped", { instId, step: step.id, trigger, reason: outcome.reason, detail: outcome.detail, rounds: every?.count });
2956
+ logEvent(instId, "warn", "reset_surface_skipped", { step: step.id, trigger, reason: outcome.reason ?? "unknown", detail: outcome.detail, ...(everySeq > 0 ? { rounds: every?.count, threshold: everySeq } : {}) });
2957
+ send(text, `${summary}(⚠️ ${resetSourceText(trigger, step, every)},但本次上下文重置未生效:${resetFailureText(outcome)})`);
2606
2958
  })
2607
2959
  .catch((e) => {
2608
2960
  releasePending();
2609
2961
  log("warn", "reset_surface_failed", { instId, step: step.id, trigger, error: e instanceof Error ? e.message : String(e) });
2610
2962
  if (stillLive())
2611
- deliverDirective(state, text, `${summary}(⚠️ ${resetSourceText(trigger, step)},但本次上下文重置未生效:宿主异常)`);
2963
+ send(text, `${summary}(⚠️ ${resetSourceText(trigger, step, every)},但本次上下文重置未生效:宿主异常)`);
2612
2964
  });
2965
+ return text;
2613
2966
  }
2614
2967
  // ─── 报告归档 ──────────────────────────────────────────────────────────────
2615
2968
  function stepStatsOf(state, endTs) {
@@ -2632,7 +2985,7 @@ export function createEngine(projectDir, ports) {
2632
2985
  const stats = stepStatsOf(state, endTs);
2633
2986
  const totalMs = Math.max(0, endTs - new Date(state.started_at).getTime());
2634
2987
  const totalFails = stats.reduce((a, s) => a + s.retries, 0);
2635
- const artifactsRel = artifactsRelDirOf(instId);
2988
+ const artifactsRel = artifactsDisplayDirOf(instId);
2636
2989
  const lines = [
2637
2990
  `# ralphflow 报告 · ${wf.name}`,
2638
2991
  "",
@@ -2647,7 +3000,7 @@ export function createEngine(projectDir, ports) {
2647
3000
  // §3.1:报告只新增**这一行**指路,其余内容逐字节不变(验收 2 用 diff 证明)。
2648
3001
  // 只在运行期日志确实存在时才写:日志压根没写出来时不指一个不存在的文件(诚实优先,
2649
3002
  // 也让「日志写失败」这件事在报告里表现为**少一行**而不是**假指路**)。
2650
- ...(fs.existsSync(logFileOf(instId)) ? [`- 执行日志:\`${RALPH_FLOW_DIR}/reports/${instId}-execution.log\``] : []),
3003
+ ...(fs.existsSync(logFileOf(instId)) ? [`- 执行日志:\`${displayPath(projectDir, archivedLogOf(instId), externalState)}\``] : []),
2651
3004
  "",
2652
3005
  "## 步骤耗时与重试",
2653
3006
  "",
@@ -2702,12 +3055,19 @@ export function createEngine(projectDir, ports) {
2702
3055
  // (这一步写 state 是安全的:实例目录本就存在且不打算删。)
2703
3056
  s.active = false;
2704
3057
  writeState(s, instId);
3058
+ // 上一步的 writeState 会移除旧记录;这里补写**真实的**终态(报告没归档 → reportPath
3059
+ // 为 null)。否则留在盘上的最后一份 `paused` 会冒充“当前仍暂停”,与 active=false 矛盾。
3060
+ writeTerminalRecordFor(s, instId, status, null);
2705
3061
  notify(s, `⚠️ 实例 \`${instId}\` 的报告归档失败,已**保留**实例目录与 \`state.json\`,未销毁。\n\n` +
2706
- `请检查工作区 \`${RALPH_FLOW_DIR}/reports/\` 是否可写(例如被同名文件占位)。\n` +
3062
+ `请检查报告目录 \`${reportsDirLabel}/\` 是否可写(例如被同名文件占位)。\n` +
2707
3063
  `报告不会自动补写;残留可用 \`/ralphflow-doctor\` 查看,确认无需保留后可手动删除该实例目录。`, `⚠️ 报告归档失败,实例 ${instId} 未销毁`);
2708
3064
  }
2709
3065
  return null;
2710
3066
  }
3067
+ // 1a) 结构化终态记录:报告路径只有归档成功后才存在,所以 done / cancelled 的机器事实
3068
+ // 在这里落(暂停态已在 writeState 里同步过)。写入失败只告警(见 writeTerminalRecordFor)。
3069
+ if (s)
3070
+ writeTerminalRecordFor(s, instId, status, reportPath);
2711
3071
  // 1b) 执行日志随报告一起归档(§3.1):先落 `destroy` 事件、再拷副本,归档的日志因此以
2712
3072
  // `destroy` 收尾(副本必须在删目录之前拷)。**日志归档失败只告警、不阻塞销毁** ——
2713
3073
  // 与第 1 步「报告归档失败即中止销毁」是有意的不对称:报告是主事实,日志是辅助证据。
@@ -2770,7 +3130,8 @@ export function createEngine(projectDir, ports) {
2770
3130
  const artifactsDirName = makeArtifactsDirName(task.trim(), instId);
2771
3131
  const state = {
2772
3132
  active: true, workflow_name: wf.name, current_step: first.id, user_task: task.trim(),
2773
- fail_counts: {}, fail_count: 0, paused: false, do_submitted: false, owner_session: sessionId,
3133
+ fail_counts: {}, fail_count: 0, incomplete_counts: {}, round_reset_marks: {},
3134
+ paused: false, do_submitted: false, owner_session: sessionId,
2774
3135
  delegations: [], verdicts: [], history: [], started_at: now, updated_at: now,
2775
3136
  artifacts_dir_name: artifactsDirName,
2776
3137
  };
@@ -2803,7 +3164,7 @@ export function createEngine(projectDir, ports) {
2803
3164
  // 措辞按**来源**分述(任务书硬要求):`auto_reset: true` / 调用点 `reset: true` 时作者
2804
3165
  // **没有**在这一步上标 `reset: true`,说「本步标了 `reset: true`」就是说错话。三支共用
2805
3166
  // 同一段结构性解释。
2806
- const firstResetCause = resetCauseOf(wf, first);
3167
+ const firstResetCause = resetCauseOf(wf, first).trigger;
2807
3168
  const firstResetStructure = "**工作流首步的初次进入无法做上下文重置**:首步的 DO 是启动工具的返回值,在工具调用内部替换会留下孤儿 tool/result(静默损坏会话)。**重试时会正常重置**(返工走空闲窗口)。";
2808
3169
  const firstStepResetNote = firstResetCause === "step"
2809
3170
  ? `⚠️ 本步标了 \`reset: true\`,但${firstResetStructure}`
@@ -2908,22 +3269,42 @@ export function createEngine(projectDir, ports) {
2908
3269
  const step = stepOf(wf, state.current_step);
2909
3270
  if (!step)
2910
3271
  return { ok: false, text: `实例状态损坏:当前步骤 \`${state.current_step}\` 不在工作流里。用 \`/ralphflow-cancel\` 结束。` };
3272
+ // 这条判断回答的是「模型交的是**上一份任务书**的卷」:回退已经把 `current_step` 拨到
3273
+ // 目标步,而旧回合还在按旧任务书干活。它在这段 DO 投递窗口里交的卷收下就会把旧步的
3274
+ // 成果记成目标步的交卷(真机缺陷:回退 c→a 后旧回合的 submit 直接推进到 b)。
3275
+ // 因此拒收本次交卷:不设 do_submitted、不推进、不烧验证;新 DO 到达后按新任务书重做。
3276
+ // 手动重置不在此列(`current_step` 没变,旧交卷仍算数,见 `pendingRewindDelivery`)。
3277
+ if (pendingRewindDelivery.has(instId)) {
3278
+ return {
3279
+ ok: false,
3280
+ text: `步骤 \`${step.id}\` 的 DO 正在投递(回退进行中),本次交卷未受理;**不要重试**,等本步 DO 到达后按新任务书重做。`,
3281
+ };
3282
+ }
2911
3283
  // 未完成项非空 = 本轮进度记录,**不是**完成声明:不设 do_submitted、不委派验证者、不占返工预算。
2912
3284
  // 这一条是「没做完就先交卷」的机械闸门:模型自己知道还剩什么,把它的自述变成引擎可执行的判断。
2913
3285
  const remaining = normalizeUnfinished(unfinished);
2914
3286
  if (!state.do_submitted && remaining.length > 0) {
3287
+ // 唯一计数来源:模型自报未完成(CHECK 判定失败走 fail_counts,两条线互不干扰)。
3288
+ const rounds = bumpIncompleteCount(state, step.id);
2915
3289
  pushHistory(state, "submit_incomplete", checkpointDetail(remaining), step.id);
2916
3290
  writeState(state, instId);
2917
- logEvent(instId, "info", "submit_incomplete", { step: step.id, count: remaining.length });
3291
+ logEvent(instId, "info", "submit_incomplete", { step: step.id, count: remaining.length, rounds });
2918
3292
  // 进度记录也是一次动作(见 noteAction 的注释):宿主把 ralphflow_submit 排除在
2919
3293
  // 「在干活」之外,引擎在这里补记自己受理过的那一次。
2920
3294
  try {
2921
3295
  ports.noteAction?.(sessionId, Date.now());
2922
3296
  }
2923
3297
  catch { }
3298
+ // 攒够阈值时**只说事实**:真正换上下文发生在下一次 DO 投递(deliverStepDo),这里不投递、
3299
+ // 不重置(结构机制只有一处)。说出来的目的是让模型理解下一轮为什么拿到的是交接稿。
3300
+ // 阈值是引擎固定的默认行为:每次满 3 次都说「引擎默认每 3 次」,没有作者配置可冒充。
3301
+ const atThreshold = rounds % ROUND_RESET_THRESHOLD === 0;
2924
3302
  return {
2925
3303
  ok: true,
2926
- text: `已记下这轮进度:本步还有 ${remaining.length} 项没完成。\n\n${remaining.map((item) => `- ${item}`).join("\n")}\n\n继续做这些;做完后再交卷。\n需要我决定的事:调用 \`ask_user_question\`。`,
3304
+ text: `已记下这轮进度:本步还有 ${remaining.length} 项没完成。\n\n${remaining.map((item) => `- ${item}`).join("\n")}\n\n继续做这些;做完后再交卷。\n需要我决定的事:调用 \`ask_user_question\`。`
3305
+ + (atThreshold
3306
+ ? `\n\n本步已第 ${rounds} 次报「没做完」(引擎默认每 ${ROUND_RESET_THRESHOLD} 次自报未完成换一次上下文):下一次投递本步任务书前会先换一次干净上下文,未完成清单会随任务书一起交回给你。`
3307
+ : ""),
2927
3308
  };
2928
3309
  }
2929
3310
  const text = (summary ?? noteTextFor(sessionId) ?? "").slice(-4000).trim();
@@ -3126,24 +3507,29 @@ export function createEngine(projectDir, ports) {
3126
3507
  // 每一轮都拿同一份任务书:start 的工具结果、continue 的重投、这里的提醒都走 doPrompt。
3127
3508
  // 旧 stepRecap 是「催办 + 回顾」;实测同一模型在完整 DO 下做 93/140 次工具调用,
3128
3509
  // 在回顾下只做 3 次 —— 轮长由入口决定,不是任务决定的。统一成完整 DO 才能让每轮同形。
3129
- const checkpoint = lastCheckpointOf(state, step.id);
3130
3510
  const failed = state.verdicts.filter((verdict) => verdict.step_id === step.id && verdict.status === "failed");
3131
3511
  const rework = failed.length > 0
3132
3512
  ? failed.map((verdict) => `- ${verdict.reason.trim() || "(未给出原因)"}`).join("\n")
3133
3513
  : undefined;
3134
3514
  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
3515
  // 无 check / check_voting 的步骤:提醒要如实写明跳过验证。
3137
3516
  // DO 本身不写(`rewind` 契约要求 DO 只讲任务);提醒是模型每轮重新读到的通道,
3138
3517
  // 不能让它误以为交卷后会启动验证者。
3139
3518
  const verificationNote = verificationNoteOf(wf, step);
3140
- return {
3141
- remind: true,
3142
- summary: worked
3143
- ? `▶️ 步骤 ${step.id} 还没结束:本轮任务书`
3144
- : `▶️ 步骤 ${step.id} 还没结束:本轮任务书(连续 ${stalls + 1} 个回合没有工具调用)`,
3145
- message: `${head}\n\n${brief}${verificationNote}`,
3146
- };
3519
+ const summary = worked
3520
+ ? `▶️ 步骤 ${step.id} 还没结束:本轮任务书`
3521
+ : `▶️ 步骤 ${step.id} 还没结束:本轮任务书(连续 ${stalls + 1} 个回合没有工具调用)`;
3522
+ // 提醒就是「下一轮 DO 投递」——**必须**走 deliverStepDo 这同一根接线(`opts.round` 让载体
3523
+ // 仍是 followup 的新回合),否则按轮门攒够阈值时这里就成了绕过重置判定的第二条路。
3524
+ // 回退原因只作为 DO 正文的一段(`rewindNote`),**不改变触发来源**:提醒不是回退动作,
3525
+ // 不能因为「这一步曾经被回退过」就每次提醒都强制重置。
3526
+ const message = deliverStepDo(state, instId, wf, step, summary, rework, {
3527
+ round: true,
3528
+ sameVisit: true,
3529
+ ...(rewindEvent ? { rewindNote: rewindOf(rewindEvent.detail ?? "") } : {}),
3530
+ composeDo: (doText) => `${head}\n\n${doText}${verificationNote}`,
3531
+ });
3532
+ return { remind: true, summary, message, delivered: true };
3147
3533
  }
3148
3534
  /**
3149
3535
  * 用户点停止按钮(宿主把当前回合 cancel 成 `turn/end { kind:"aborted", reason:{kind:"user"} }`):
@@ -3285,8 +3671,12 @@ export function createEngine(projectDir, ports) {
3285
3671
  void launchVerification(instId, state, wf, step);
3286
3672
  return { ok: true, text: `▶️ 已解除暂停(原因:${pauseLabel(reason)}),正在重新委派独立验证者检查步骤 \`${step.id}\`。` };
3287
3673
  }
3288
- const checkpoint = lastCheckpointOf(state, step.id);
3289
- deliverDirective(state, doPrompt(instId, wf, state, step, undefined, undefined, checkpoint ?? undefined) + verificationNoteOf(wf, step), `▶️ 步骤 ${step.id} 继续执行`);
3674
+ // 与推进/返工/提醒**同一根接线**:续跑重投也是「本步的又一轮」(`sameVisit`:静态重置门
3675
+ // 不重复触发,按轮门攒够阈值时照常先换上下文再投任务书)。
3676
+ deliverStepDo(state, instId, wf, step, `▶️ 步骤 ${step.id} 继续执行`, undefined, {
3677
+ sameVisit: true,
3678
+ composeDo: (doText) => doText + verificationNoteOf(wf, step),
3679
+ });
3290
3680
  return { ok: true, text: `▶️ 已解除暂停(原因:${pauseLabel(reason)}),已让模型继续步骤 \`${step.id}\`。` };
3291
3681
  }
3292
3682
  // ② 有在飞委派 → 不重复推进(防重复委派)
@@ -3323,7 +3713,7 @@ export function createEngine(projectDir, ports) {
3323
3713
  // 以为「已推进 = 现在开始干下一步」而在没有 DO 的情况下盲干(那部分工作也会被随后的重置遮蔽)。
3324
3714
  const afterGate = nextStepId(wf, step);
3325
3715
  const afterStep = afterGate === "done" ? undefined : stepOf(wf, afterGate);
3326
- const afterCause = afterStep ? resetCauseOf(wf, afterStep) : undefined;
3716
+ const afterCause = afterStep ? resetCauseOf(wf, afterStep).trigger : undefined;
3327
3717
  const deferredNote = afterCause && afterStep
3328
3718
  ? `\n\n⚠️ 下一步 \`${afterStep.id}\` 会触发上下文重置(${resetSourceShort(afterCause, afterStep)},重置门):它的 DO 提示会在**本回合结束后**送达(上下文重置只能在步骤边界的空闲窗口里做)。**本回合请勿开始该步的工作**,简短确认即可。`
3329
3719
  : "";
@@ -3417,14 +3807,18 @@ export function createEngine(projectDir, ports) {
3417
3807
  return { ok: true, text: `已按 /ralphflow-reset 排入上下文重置:步骤 \`${step.id}\` 的 DO 会在属主会话的空闲窗口完成整段替换后重投(失败计数保留,状态机不动)。` };
3418
3808
  }
3419
3809
  /**
3420
- * 回退(`/ralphflow-rewind <步骤> <原因>`):**reset 的动作 + 状态机倒退 + 带走原因**。
3810
+ * 回退(`/ralphflow-rewind <步骤> <原因>`):**先中止旧回合** + reset 的动作 + 状态机倒退 + 带走原因。
3421
3811
  *
3422
- * 机械动作 = 把 `current_step` 拨到目标步,清 `paused` / `pause_reason` / `fail_counts` /
3423
- * `do_submitted` / `verdicts` / `delegations`(并中止在飞验证者),记 `rewind` + `step_start`,
3424
- * 然后走**同一根** `deliverStepDo` 接线:整段替换上下文(强制,无论该步有没有标 `reset`)+
3425
- * 可见告知 + 重投目标步 DO(DO 里**自成一段**带着用户给出的原因)。
3812
+ * 机械动作 = 中止属主会话当前回合(`ports.interrupt`;这是「旧回合交的是上一份任务书的
3813
+ * 卷」的源头,必须先停)→ 把 `current_step` 拨到目标步,清 `paused` / `pause_reason` /
3814
+ * `fail_counts` / `do_submitted` / `verdicts` / `delegations`(并中止在飞验证者),记
3815
+ * `rewind` + `step_start` → 走**同一根** `deliverStepDo` 接线:整段替换上下文(强制,
3816
+ * 无论该步有没有标 `reset`)+ 可见告知 + 重投目标步 DO(DO 里**自成一段**带着用户给出的原因)。
3426
3817
  * 载体(`src/reset.ts`)一行都不用动 —— 这是策略层的事。
3427
3818
  *
3819
+ * 中止与投递之间的竞态由 `onSubmit` 的 `pendingDoDelivery` 判据兜底:旧回合若在这段
3820
+ * 窗口里交卷,会被拒收(不设 `do_submitted`、不推进、不烧验证)。
3821
+ *
3428
3822
  * **没有第二道门**:引擎对进度的全部认知就是 `current_step`,「已通过 CHECK 的步骤」是现算的
3429
3823
  * 派生量(`verdicts[]` / `history`),不是状态。所以「回退到某步」与「跳到某步」在机械上是
3430
3824
  * 同一件事,合法性判据只有一条:**按工作流定义顺序、当前步之前的步骤**。
@@ -3511,9 +3905,21 @@ export function createEngine(projectDir, ports) {
3511
3905
  text: `目标 \`${targetId}\` 在当前步 \`${state.current_step}\` **之后**(第 ${tgtIdx + 1}/${wf.steps.length} 步 vs 当前第 ${curIdx + 1} 步):回退只能去当前步**之前**的步骤。${earlierHint}`,
3512
3906
  };
3513
3907
  }
3514
- // ── 机械动作:reset 的动作 + 状态机倒退 + 带走原因 ───────────────────────────
3908
+ // ── 机械动作:先中止旧回合,再 reset 的动作 + 状态机倒退 + 带走原因 ─────────────
3515
3909
  const target = wf.steps[tgtIdx];
3516
3910
  const from = state.current_step;
3911
+ // ① 旧回合还在按旧任务书干活:先停掉它。否则它随后的 `ralphflow_submit` 会落到
3912
+ // 已经回退后的 `current_step` 上,把旧步的成果记成目标步的交卷(真机缺陷本体)。
3913
+ // 端口缺失/异常**绝不阻断回退**:只记 `interrupt_failed`,机械动作照常。
3914
+ try {
3915
+ if (typeof ports.interrupt === "function")
3916
+ ports.interrupt(sessionId);
3917
+ else
3918
+ log("warn", "interrupt_failed", { instId, reason: "unavailable" });
3919
+ }
3920
+ catch (e) {
3921
+ log("warn", "interrupt_failed", { instId, error: e instanceof Error ? e.message : String(e) });
3922
+ }
3517
3923
  // 在飞验证者一律中止(正常路径下 `do_submitted === false` ⇒ 无在飞委派;这里是硬护栏:
3518
3924
  // 清掉 delegations 而不中止,判定回来时会变成无人认领的孤儿)
3519
3925
  abortInstance(instId);
@@ -3528,6 +3934,9 @@ export function createEngine(projectDir, ports) {
3528
3934
  state.pause_reason = undefined;
3529
3935
  state.fail_counts = {};
3530
3936
  state.fail_count = 0;
3937
+ // 自报未完成计数是「这一轮循环里的轮数」:回退换方向后就地重新起算(与 fail_counts 同口径)。
3938
+ state.incomplete_counts = {};
3939
+ state.round_reset_marks = {};
3531
3940
  stampOwner(state);
3532
3941
  pushHistory(state, "rewind", `${from} → ${target.id}:${reasonText}`, target.id);
3533
3942
  pushHistory(state, "step_start", target.desc ?? "", target.id);
@@ -3560,7 +3969,7 @@ export function createEngine(projectDir, ports) {
3560
3969
  // 取消 = 与完成同一条销毁路径(归档报告 → 销毁实例目录 → 删空产出目录)。
3561
3970
  const destroyed = destroyInstance(instId, "cancelled", state);
3562
3971
  if (destroyed) {
3563
- const rel = reportRelPathOf(instId);
3972
+ const rel = reportPathOf(instId);
3564
3973
  const head = `🛑 实例 \`${instId}\` 已取消${reason ? `:${reason}` : ""}。报告已归档到 \`${rel}\`。`;
3565
3974
  if (destroyed.instanceDirRemoved) {
3566
3975
  notify(state, head, `🛑 ralphflow 实例已取消(报告 ${rel})`);
@@ -3589,7 +3998,7 @@ export function createEngine(projectDir, ports) {
3589
3998
  const all = listInstances();
3590
3999
  if (all.length > 0)
3591
4000
  return { ok: true, text: renderActiveOverview(all, sessionId) };
3592
- return { ok: true, text: `当前没有活跃实例。用 \`/ralphflow-start <工作流> <任务>\` 启动;已结束的运行:报告在 \`${RALPH_FLOW_DIR}/reports/\`。` };
4001
+ return { ok: true, text: `当前没有活跃实例。用 \`/ralphflow-start <工作流> <任务>\` 启动;已结束的运行:报告在 \`${reportsDirLabel}/\`。` };
3593
4002
  }
3594
4003
  const info = listInstances().find((i) => i.id === instanceRef || i.id.startsWith(instanceRef));
3595
4004
  if (info)
@@ -3613,7 +4022,7 @@ export function createEngine(projectDir, ports) {
3613
4022
  ].filter(Boolean).join("\n"),
3614
4023
  };
3615
4024
  }
3616
- return { ok: true, text: `找不到活跃实例 \`${instanceRef}\`,也没有与它匹配的历史报告。用 \`/ralphflow-list\` 查看活跃实例,或直接看 \`${RALPH_FLOW_DIR}/reports/\`。` };
4025
+ return { ok: true, text: `找不到活跃实例 \`${instanceRef}\`,也没有与它匹配的历史报告。用 \`/ralphflow-list\` 查看活跃实例,或直接看 \`${reportsDirLabel}/\`。` };
3617
4026
  }
3618
4027
  }
3619
4028
  /**
@@ -3705,7 +4114,7 @@ export function createEngine(projectDir, ports) {
3705
4114
  function nextActionHint(s, instId, step) {
3706
4115
  if (!s.active) {
3707
4116
  // 基本不可达:实例一旦结束就被销毁。保留但改为**指向精确报告路径**。
3708
- const rel = instId ? `\`${reportRelPathOf(instId)}\`` : "`" + RALPH_FLOW_DIR + "/reports/`";
4117
+ const rel = instId ? `\`${reportPathOf(instId)}\`` : "`" + reportsDirLabel + "/`";
3709
4118
  return `工作流已结束,历史在报告里:${rel};要再跑一次用 \`/ralphflow-start <工作流> <任务>\`。`;
3710
4119
  }
3711
4120
  if (s.paused) {
@@ -3805,7 +4214,7 @@ export function createEngine(projectDir, ports) {
3805
4214
  //
3806
4215
  // **数据面 `listHistory()` 仍然保留**:doctor 的孤儿产出体检与 status 的历史报告查找
3807
4216
  // 都靠它 —— 去掉的是「列表里这一节」,不是「读历史的能力」。
3808
- body.push("", `已结束的运行:报告在 \`${RALPH_FLOW_DIR}/reports/\`(不在此逐个列出;报告与产出永久保留,只能由你显式删除)。`);
4217
+ body.push("", `已结束的运行:报告在 \`${reportsDirLabel}/\`(不在此逐个列出;报告与产出永久保留,只能由你显式删除)。`);
3809
4218
  return { ok: true, text: head.concat(body).join("\n") };
3810
4219
  }
3811
4220
  /**
@@ -3816,6 +4225,7 @@ export function createEngine(projectDir, ports) {
3816
4225
  */
3817
4226
  function diagnoseInstanceDirs() {
3818
4227
  const issues = [];
4228
+ const instancesLabel = displayPath(projectDir, instancesDir, externalState);
3819
4229
  let entries = [];
3820
4230
  try {
3821
4231
  entries = fs.readdirSync(instancesDir, { withFileTypes: true });
@@ -3827,7 +4237,7 @@ export function createEngine(projectDir, ports) {
3827
4237
  if (!e.isDirectory())
3828
4238
  continue;
3829
4239
  const id = e.name;
3830
- const label = `instances/${id}/`;
4240
+ const label = `${instancesLabel}/${id}/`;
3831
4241
  const sp = path.join(instancesDir, id, "state.json");
3832
4242
  if (!fs.existsSync(sp)) {
3833
4243
  issues.push(`实例目录 \`${label}\` 缺少 state.json —— 所有工具都看不到它。若是残留目录可直接删除`);
@@ -3855,6 +4265,7 @@ export function createEngine(projectDir, ports) {
3855
4265
  /** 孤儿产出:`artifacts/<name>/` 既无对应报告、也无对应活跃实例(通常来自被手动清理的实例)。同样只报不删。 */
3856
4266
  function diagnoseOrphanArtifacts() {
3857
4267
  const issues = [];
4268
+ const artifactsLabel = displayPath(projectDir, artifactsDir, externalState);
3858
4269
  const claimed = new Set();
3859
4270
  for (const { state } of listInstances())
3860
4271
  if (state.artifacts_dir_name)
@@ -3886,7 +4297,7 @@ export function createEngine(projectDir, ports) {
3886
4297
  for (const e of entries) {
3887
4298
  if (!e.isDirectory() || claimed.has(e.name))
3888
4299
  continue;
3889
- issues.push(`产出目录 \`artifacts/${e.name}/\` 既无对应报告、也无对应实例目录(通常来自被手动清理的实例)—— 只报告,不删除`);
4300
+ issues.push(`产出目录 \`${artifactsLabel}/${e.name}/\` 既无对应报告、也无对应实例目录(通常来自被手动清理的实例)—— 只报告,不删除`);
3890
4301
  }
3891
4302
  return issues;
3892
4303
  }
@@ -4074,7 +4485,7 @@ export function createEngine(projectDir, ports) {
4074
4485
  }
4075
4486
  /** Resolve only an exact trusted report id, never a browser-supplied filesystem path. */
4076
4487
  function uiReport(ref) {
4077
- if (!/^[a-zA-Z0-9_-]+$/.test(ref.runId) || ref.reportRef !== reportRelPathOf(ref.runId))
4488
+ if (!/^[a-zA-Z0-9_-]+$/.test(ref.runId) || ref.reportRef !== reportPathOf(ref.runId))
4078
4489
  return null;
4079
4490
  let report;
4080
4491
  try {
@@ -4093,7 +4504,7 @@ export function createEngine(projectDir, ports) {
4093
4504
  root, instancesDir, workflowsDir, reportsDir, projectDir,
4094
4505
  ensureLayout, listWorkflows, loadWorkflow,
4095
4506
  readState, listInstances, listHistory, instanceDir,
4096
- artifactsDirOf, artifactsRelDirOf, reportRelPathOf, destroyInstance,
4507
+ artifactsDirOf, artifactsDisplayDirOf, reportPathOf, destroyInstance,
4097
4508
  start, onSubmit, noteAssistantText, remindToSubmit, pauseForUserStop, continueInstance, resetCurrent, rewindTo, cancelInstance, statusOf, listAll, restore, diagnose,
4098
4509
  activeInstanceOfSession, uiStatus, uiReport,
4099
4510
  };