dsh-workplan 1.8.18 → 1.10.6

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/host.js CHANGED
@@ -13,6 +13,7 @@ import { fileURLToPath } from 'node:url';
13
13
  */
14
14
  import { applyHardeningHeaders, cancelToolOutputSchema, createWorkplanRuntime, dispatchToolOutputSchema, plannerOutputSchema, statusToolOutputSchema, updateToolOutputSchema, } from './runtime.js';
15
15
  import { isRecord } from './plan.js';
16
+ import { autoResumeEnabledFrom } from './auto-resume.js';
16
17
  /*
17
18
  * [1.8.14] Identity of the modules this process actually loaded (N1).
18
19
  *
@@ -101,6 +102,7 @@ const PROMPT_SECTION = [
101
102
  */
102
103
  '5. 「完成」只有一个判据:计划里全部子任务都是 done,**且** deliveryReady=true(每个 done 项 verification="structured"、acceptance 非空且逐项 result="pass"、无缺失产物)。用户取消 ≠ 完成:取消只停止执行,未完成项仍然是未完成。`dsh_workplan_dispatch` 返回 ok:true / complete:true 只表示调用成功或状态全 done,必须再看 deliveryReady 与 完成 X/Y;只要 deliveryReady=false 或还有 pending/blocked,就禁止 present 交付物、禁止写“已完成/最终版/已交付”、禁止给收尾性最终答复,必须先再次调用 dsh_workplan_dispatch 续跑剩余项。',
103
104
  '6. 如果续跑被拒绝、受阻项无法恢复、证据补不齐、计划已取消但未完成,或用户要求先看中间结果:答复开头必须写「未完成:剩余 N 项(列出 ID)与原因」,正文只能按中间结果表述,不得包装成成品。取消不会给你交付许可。',
105
+ '7. 子任务有硬执行上限(默认 15 分钟/步)与整轮预算(默认 20 分钟):子 Agent 接近上限时应先把已完成内容落盘并在结论里列出路径。任何「达到执行上限」「本轮预算用尽」都不等于「什么都没做」:状态里的 error 会列出「声明产物已在盘上」,必须先用文件核对;若产物已覆盖验收标准,用 dsh_workplan_update 复核改判,只补缺失部分再续跑,禁止无视盘上产物把整步重跑。',
104
106
  '结果消息里每个完成项都带 verification 与 acceptance:`structured` 是子 Agent 逐条自检通过,`unverified` 是自述但未逐条确认,`failed` 是自检失败(已按受阻处理),`legacy` 是旧格式回传。只有 structured 且 acceptance 每项 pass 才算可交付;其余必须你自己核对产物,并用 dsh_workplan_update 的 verification/acceptance/artifacts 字段把核对结果写回(这些字段会持久化、刷新后仍生效),不要把“看着没问题”当成证据。',
105
107
  '子 Agent 通过 `needs` 提出的跨部门需求会列在结果消息的「跨部门待转达」里:由你逐条处理(补派、向用户确认或直接完成),不要忽略。',
106
108
  '长任务可以用 `dsh_workplan_dispatch({ mode: "async" })` 先开跑并立即答复用户,再用 `dsh_workplan_status` 查看进度;async 返回的是“已开跑”,不是“已完成”。',
@@ -253,7 +255,12 @@ function createCancelTool(runtime) {
253
255
  description: '取消当前会话尚未派发/正在等待派发的任务分解计划。仅取消计划记录,不伪造任何完成;'
254
256
  + '取消后计划在面板中显示为“已取消”,不会启动任何部门 Agent。'
255
257
  + '注意:取消不等于完成。取消后如仍有未完成项或证据缺口,present 仍会被拒绝,'
256
- + '答复必须按「未完成:剩余 N 项与原因」说明。',
258
+ + '答复必须按「未完成:剩余 N 项与原因」说明。'
259
+ + 'disposition="superseded" 是另一种处置:把交付责任转移给一个可验证的承接计划。'
260
+ + '运行时逐条复算(V1–V8):源计划必须已取消且未全 done、承接计划必须定义更晚且非终态、'
261
+ + '映射必须覆盖源计划全部子任务、每个映射目标必须有 done+structured 证据与全通过的验收、'
262
+ + '且本会话存在同时含两个 planId 的用户确认消息。任一不满足即拒绝并返回 SUPERSEDE_* 码,'
263
+ + '状态不变;被取代不等于完成。',
257
264
  parameters: {
258
265
  type: 'object',
259
266
  properties: {
@@ -263,7 +270,39 @@ function createCancelTool(runtime) {
263
270
  },
264
271
  reason: {
265
272
  type: 'string',
266
- description: '取消原因,会写入会话记录。',
273
+ description: '取消/取代原因,会写入会话记录。',
274
+ },
275
+ disposition: {
276
+ type: 'string',
277
+ enum: ['cancelled', 'superseded'],
278
+ description: '处置方式:cancelled=用户撤销(默认);superseded=责任已转移给承接计划。',
279
+ },
280
+ supersededBy: {
281
+ type: 'object',
282
+ description: 'disposition=superseded 时必填:承接计划与逐项覆盖映射。'
283
+ + '只给映射意图,requiredCount/coveredCount/coverage/digest 由运行时复算,不接受自报。',
284
+ properties: {
285
+ planId: {
286
+ type: 'string',
287
+ description: '承接计划的 planId(必须定义得过且未终止)。',
288
+ },
289
+ mapping: {
290
+ type: 'array',
291
+ description: '源计划每个定义子任务一条映射;from 必须恰好覆盖全部源项(各一次)。',
292
+ items: {
293
+ type: 'object',
294
+ properties: {
295
+ from: { type: 'string', description: '源计划子任务 ID。' },
296
+ to: { type: 'string', description: '承接计划子任务 ID。' },
297
+ basis: { type: 'string', description: '覆盖依据(为什么这两项是同一责任)。' },
298
+ },
299
+ required: ['from', 'to', 'basis'],
300
+ additionalProperties: false,
301
+ },
302
+ },
303
+ },
304
+ required: ['planId', 'mapping'],
305
+ additionalProperties: false,
267
306
  },
268
307
  },
269
308
  additionalProperties: false,
@@ -272,9 +311,18 @@ function createCancelTool(runtime) {
272
311
  schema: cancelToolOutputSchema(),
273
312
  render(_args, value) {
274
313
  const result = isRecord(value) ? value : {};
275
- if (!result.ok)
276
- return textContent(`取消失败:${String(result.error ?? '未知错误')}`);
314
+ if (!result.ok) {
315
+ return textContent(`处置失败${result.code ? `(${String(result.code)})` : ''}:`
316
+ + `${String(result.error ?? '未知错误')}`);
317
+ }
277
318
  const stats = isRecord(result.stats) ? result.stats : {};
319
+ if (result.phase === 'superseded') {
320
+ const by = isRecord(result.supersededBy) ? result.supersededBy : {};
321
+ return textContent(`计划 ${String(result.planId ?? '')} 已被取代:承接计划 ${String(by.planId ?? '')}`
322
+ + `(映射 ${Number(by.coveredCount ?? 0)}/${Number(by.requiredCount ?? 0)},digest 已复算)`
323
+ + `|源计划仍是 ${Number(stats.done ?? 0)}/${Number(stats.total ?? 0)}:被取代不等于完成,`
324
+ + '不得 present 源计划,只能使用承接计划通过交付就绪检查的产物。');
325
+ }
278
326
  const cancelledIncomplete = result.phase !== 'done';
279
327
  return textContent(`已取消计划 ${String(result.planId ?? '')}:${String(result.reason ?? '用户取消')}`
280
328
  + `(完成 ${Number(stats.done ?? 0)}/${Number(stats.total ?? 0)})`
@@ -291,6 +339,58 @@ function createCancelTool(runtime) {
291
339
  },
292
340
  };
293
341
  }
342
+ function createFollowupTool(runtime) {
343
+ return {
344
+ name: 'dsh_workplan_followup',
345
+ description: '把一条说明投递给本会话的某个**直接子会话**,让它继续跑一个正常回合。'
346
+ + '用途仅限:子任务被预算/超时中止、但产物已在盘上,且用户明确同意补发 follow-up 时,'
347
+ + '让子会话自己收尾,从而让它自己的 turn/end 变成 completed。'
348
+ + '它不写计划状态、不触发交付、也不改变界面判定;投递本身不等于完成。'
349
+ + '不是直接子会话(父会话 catalog 未登记)一律拒绝。',
350
+ parameters: {
351
+ type: 'object',
352
+ properties: {
353
+ sessionId: {
354
+ type: 'string',
355
+ description: '直接子会话 ID(父会话 subagent/catalog 中登记的那一个)。',
356
+ },
357
+ message: {
358
+ type: 'string',
359
+ description: '发给子会话的说明:确认已有产物、只补缺口、不要整步重跑;不要要求它伪造完成。',
360
+ },
361
+ },
362
+ required: ['sessionId', 'message'],
363
+ additionalProperties: false,
364
+ },
365
+ output: {
366
+ schema: {
367
+ type: 'object',
368
+ properties: {
369
+ ok: { type: 'boolean' },
370
+ sessionId: { type: 'string' },
371
+ messageId: { type: 'string' },
372
+ code: { type: 'string' },
373
+ error: { type: 'string' },
374
+ },
375
+ required: ['ok'],
376
+ additionalProperties: true,
377
+ },
378
+ render(_args, value) {
379
+ const result = isRecord(value) ? value : {};
380
+ if (!result.ok) {
381
+ return textContent(`follow-up 未投递:${String(result.error ?? result.code ?? '未知错误')}`);
382
+ }
383
+ return textContent(`已向子会话 ${String(result.sessionId ?? '')} 投递 follow-up`
384
+ + (result.messageId ? `(messageId ${String(result.messageId)})` : '')
385
+ + '。投递只代表消息被接收;界面状态要等该子会话自己的回合正常结束才会变化。');
386
+ },
387
+ },
388
+ async execute(args, exec) {
389
+ const parsed = asObject(args) ?? {};
390
+ return runtime.followupTool(exec.agent, parsed, exec.signal);
391
+ },
392
+ };
393
+ }
294
394
  function createStatusTool(runtime) {
295
395
  return {
296
396
  name: 'dsh_workplan_status',
@@ -444,6 +544,27 @@ function createDispatchTool(runtime) {
444
544
  * short of editing the source, so any machine with slower subagents hit the
445
545
  * wall on every plan. These knobs let operations tune it without a rebuild.
446
546
  */
547
+ /**
548
+ * [1.10.4] 布尔开关:配置项优先,其次环境变量。
549
+ *
550
+ * 与 `numericSetting` 不同,显式 `false` 必须能被表达,所以先判 boolean;
551
+ * 环境变量只接受 1/true/yes/on,大小写不敏感。未配置时返回 `false`。
552
+ *
553
+ * [1.10.6] 注意:`autoResume` 已改用 `autoResumeEnabledFrom`(默认开启,
554
+ * 且 `0/false/no/off` 可以显式关闭)。本函数保留给「默认关闭」语义的开关。
555
+ */
556
+ function booleanSetting(configValue, envName) {
557
+ if (typeof configValue === 'boolean')
558
+ return configValue;
559
+ const raw = typeof process !== 'undefined' ? process.env?.[envName] : undefined;
560
+ if (raw === undefined || raw === '')
561
+ return false;
562
+ return /^(1|true|yes|on)$/i.test(String(raw).trim());
563
+ }
564
+ /** [1.10.6] 原样读取环境变量,供三态解析使用(未设置返回 undefined)。 */
565
+ function settingEnv(envName) {
566
+ return typeof process !== 'undefined' ? process.env?.[envName] : undefined;
567
+ }
447
568
  function numericSetting(configValue, envName) {
448
569
  if (configValue !== undefined && configValue !== null && configValue !== '') {
449
570
  const numeric = Number(configValue);
@@ -492,6 +613,13 @@ export function apply(ctx, config = {}) {
492
613
  idleTimeoutMs: numericSetting(config.idleTimeoutMs, 'DSH_WORKPLAN_IDLE_TIMEOUT_MS'),
493
614
  totalTimeoutMs: numericSetting(config.totalTimeoutMs, 'DSH_WORKPLAN_TOTAL_TIMEOUT_MS'),
494
615
  maxResumes: numericSetting(config.maxResumes, 'DSH_WORKPLAN_MAX_RESUMES'),
616
+ /*
617
+ * [1.10.6] 三态解析:显式配置 > 显式环境变量 > 默认开启。
618
+ * 旧实现用 `booleanSetting(..., false)`,未配置即等于关闭,于是「预算到点
619
+ * 自动续跑」这个能力在用户机器上从来没打开过(1h57m 空窗的直接原因)。
620
+ */
621
+ autoResume: autoResumeEnabledFrom(config.autoResume, settingEnv('DSH_WORKPLAN_AUTO_RESUME')),
622
+ autoResumeMaxAttempts: numericSetting(config.autoResumeMaxAttempts, 'DSH_WORKPLAN_AUTO_RESUME_MAX'),
495
623
  });
496
624
  ctx.effect(() => ctx.systemPrompt.section({
497
625
  name: 'dsh-workplan',
@@ -501,6 +629,7 @@ export function apply(ctx, config = {}) {
501
629
  ctx.effect(() => ctx.tools.register(createUpdateTool(runtime)));
502
630
  ctx.effect(() => ctx.tools.register(createCancelTool(runtime)));
503
631
  ctx.effect(() => ctx.tools.register(createStatusTool(runtime)));
632
+ ctx.effect(() => ctx.tools.register(createFollowupTool(runtime)));
504
633
  ctx.effect(() => ctx.tools.register(createDispatchTool(runtime)));
505
634
  /*
506
635
  * Plan mode produces a plan for review, not department execution. Denying
@@ -573,7 +702,7 @@ export function apply(ctx, config = {}) {
573
702
  }
574
703
  export const meta = {
575
704
  name,
576
- version: '1.8.18',
705
+ version: '1.10.6',
577
706
  promptOrder: PROMPT_ORDER,
578
707
  routes: ['/dsh-workplan/plans', '/dsh-workplan/vendor/chart.umd.js'],
579
708
  };
package/lib/plan.js CHANGED
@@ -7,7 +7,55 @@
7
7
  * runtime and by unit tests.
8
8
  */
9
9
  import { randomUUID } from 'node:crypto';
10
+ import { isMappingDigest, verifyMappingDigest } from './supersede-digest.js';
10
11
  export const PLAN_VERSION = 1;
12
+ /**
13
+ * [1.9.0] 处置终态:cancelled(用户撤销)与 superseded(责任已转移)。
14
+ *
15
+ * 两者都是终态:记录与计数原样保留,永不算完成,也永不被自动选为
16
+ * `present` 的判定对象;只有「本回合结构化点名」时才判定(cancelled 仍硬拦)。
17
+ * 规则依据:_rerun_20261101/GATE_rule_design.md §3.1。
18
+ */
19
+ export const TERMINAL_PHASES = new Set(['cancelled', 'superseded']);
20
+ export function isTerminalPhase(phase) {
21
+ return typeof phase === 'string' && TERMINAL_PHASES.has(phase);
22
+ }
23
+ /**
24
+ * [1.9.2] `present` 拒绝码(P1 统一)。
25
+ *
26
+ * 规则出处:`_rerun_20261101/GATE_rule_design.md` §4.3(P1/P2 与
27
+ * `judgeEffective`)及 §4.4 真值表;最小修法出处:
28
+ * `_rerun_20261101/GATE_case_matrix.md` §3.2(T9 的唯一不一致格
29
+ * `C05.denyCode`)。
30
+ *
31
+ * T8 原文的 P1 把「全部 done 但证据缺口」和「还有子任务没做完」合并成
32
+ * 一个码值 `ACTIVE_NOT_READY`,于是 R2/G02 的 `EVIDENCE_GAP` 在未点名时
33
+ * 永远走不到。修法只拆一个维度:`remaining` 为空且 `blockers` 非空
34
+ * ⇒ `EVIDENCE_GAP`,其余仍是 `ACTIVE_NOT_READY`。这本来就是 1.8.19 的
35
+ * 既有语义(`remaining.length === 0` 有独立文案),不是新增语义。
36
+ *
37
+ * 码值是对外契约:测试、日志与后续 UI 按字面值断言。所有拒绝点只能引用
38
+ * 这里的常量或 `activeDenyCode()`,不得再手写字符串。
39
+ */
40
+ export const PRESENT_DENY_CODES = {
41
+ ACTIVE_NOT_READY: 'ACTIVE_NOT_READY',
42
+ EVIDENCE_GAP: 'EVIDENCE_GAP',
43
+ CANCELLED_NAMED: 'CANCELLED_NAMED',
44
+ SUPERSEDED_STALE: 'SUPERSEDED_STALE',
45
+ };
46
+ /**
47
+ * P1 的单一映射:active 计划未就绪时,只由交付就绪结果决定拒绝码。
48
+ *
49
+ * 调用点(`present` 的未完成分支、点名 active 计划的判定)必须走这个函数,
50
+ * 不要在分支里各写一份判断——T9 的 C05 不一致正是「规则一个码、实现另一个
51
+ * 码」造成的。终态计划不走这里:cancelled 是 `CANCELLED_NAMED`,superseded
52
+ * 按覆盖链给 `SUPERSEDED_STALE` / `ACTIVE_NOT_READY`。
53
+ */
54
+ export function activeDenyCode(readiness) {
55
+ return readiness.remaining.length === 0 && readiness.blockers.length > 0
56
+ ? PRESENT_DENY_CODES.EVIDENCE_GAP
57
+ : PRESENT_DENY_CODES.ACTIVE_NOT_READY;
58
+ }
11
59
  export const MAX_STAGES = 6;
12
60
  export const MAX_SUBTASKS = 15;
13
61
  export const MAX_CONCURRENT = 5;
@@ -1233,7 +1281,27 @@ export function parseResultMessage(message) {
1233
1281
  return null;
1234
1282
  }
1235
1283
  }
1236
- export function buildCancelMessage(planId, reason = '用户取消') {
1284
+ /*
1285
+ * [1.9.2] `workplan-cancel` 信封是 cancelled / superseded 的**唯一写入出口**。
1286
+ *
1287
+ * 规则出处:`_rerun_20261101/GATE_rule_design.md` §6.1(字段 schema)、§7.2
1288
+ * 第 7 条(写入 durable 记录后 replay 仍为 superseded)。写侧任何地方都不得
1289
+ * 自己拼这段 JSON:一旦有第二条拼装路径,`disposition`/`supersededBy` 的字段
1290
+ * 形状就会分叉,replay 与 present 的读侧判定随之失效(正是本子任务要杜绝的
1291
+ * 「绕过」)。
1292
+ *
1293
+ * 语义边界:本函数只负责把**运行时已经核验过**的处置结果写成信封;V1–V8
1294
+ * 核验与 digest 复算在 `src/supersede.ts`(唯一写入者)。因此这里对 superseded
1295
+ * 再做一次防线:`supersededBy.mapping` 与 `digest` 必须能逐字复算,否则抛错、
1296
+ * 不写日志、不改状态(fail-closed)。
1297
+ */
1298
+ export function buildCancelMessage(planId, reason = '用户取消', terminal = null) {
1299
+ const disposition = terminal?.disposition ?? 'cancelled';
1300
+ if (disposition === 'superseded')
1301
+ return buildSupersededMessage(planId, reason, terminal);
1302
+ if (disposition !== 'cancelled') {
1303
+ throw new Error(`buildCancelMessage: 非法处置 disposition=${String(disposition)}`);
1304
+ }
1237
1305
  const summary = `【任务已取消】${truncate(String(reason || '用户取消'), 120)}`;
1238
1306
  const payload = {
1239
1307
  kind: 'workplan-cancel',
@@ -1266,6 +1334,59 @@ export function buildCancelMessage(planId, reason = '用户取消') {
1266
1334
  summary,
1267
1335
  });
1268
1336
  }
1337
+ /**
1338
+ * [1.9.2] `disposition:'superseded'` 的信封正文(由 `buildCancelMessage` 独占调用)。
1339
+ *
1340
+ * 与 cancelled 共用同一个 `kind:'workplan-cancel'`:旧版本解析器只校验 `kind`
1341
+ * (`parseCancelMessage`),新增字段被忽略后按 cancelled 读——不可派发、不可
1342
+ * 交付,属安全降级(规则文档 §10.3)。这也是「不得新增第二种信封 kind」的原因:
1343
+ * 换 kind 会让旧回放彻底读不到这条处置记录。
1344
+ */
1345
+ function buildSupersededMessage(planId, reason, terminal) {
1346
+ const by = terminal?.supersededBy;
1347
+ const verifiable = isRecord(by)
1348
+ && typeof by.planId === 'string'
1349
+ && by.planId !== ''
1350
+ && Array.isArray(by.mapping)
1351
+ && by.mapping.length > 0
1352
+ && isMappingDigest(by.digest)
1353
+ && verifyMappingDigest(by.mapping, by.digest);
1354
+ if (!verifiable) {
1355
+ throw new Error('buildCancelMessage: superseded 信封必须带可复算的 supersededBy.planId/mapping/digest');
1356
+ }
1357
+ const text = String(reason || '责任已转移');
1358
+ const supersededAt = Number.isFinite(Number(terminal?.supersededAt)) ? Number(terminal.supersededAt) : Date.now();
1359
+ const requiredCount = Number(by.requiredCount ?? 0);
1360
+ const coveredCount = Number(by.coveredCount ?? 0);
1361
+ const summary = `【计划已被取代】${truncate(text, 120)}|承接:${by.planId}`
1362
+ + `(映射 ${coveredCount}/${requiredCount})`;
1363
+ const payload = {
1364
+ kind: 'workplan-cancel',
1365
+ version: PLAN_VERSION,
1366
+ planId,
1367
+ reason: text,
1368
+ cancelledAt: supersededAt,
1369
+ disposition: 'superseded',
1370
+ supersededAt,
1371
+ supersededBy: by,
1372
+ };
1373
+ const lines = [
1374
+ summary,
1375
+ '',
1376
+ '这次任务分解的责任已转移给一个可验证的承接计划。被取代不等于完成:',
1377
+ '原计划的记录与计数原样保留,未完成项永远不会因为这次转移而变成完成。',
1378
+ '交付时只能使用承接计划通过交付就绪检查的产物;原计划不作为完成证据。',
1379
+ '',
1380
+ CANCEL_MARKER_BEGIN,
1381
+ JSON.stringify(payload),
1382
+ CANCEL_MARKER_END,
1383
+ ];
1384
+ return makeUserMessage(lines.join('\n'), {
1385
+ kind: 'workplan-cancel',
1386
+ form: 'notice',
1387
+ summary,
1388
+ });
1389
+ }
1269
1390
  export function parseCancelMessage(message) {
1270
1391
  const body = extractBetween(messageText(message), CANCEL_MARKER_BEGIN, CANCEL_MARKER_END);
1271
1392
  if (!body)
@@ -1549,11 +1670,13 @@ export function applyResultStatuses(statuses, result) {
1549
1670
  continue;
1550
1671
  /*
1551
1672
  * A manually re-adjudicated status (durable `workplan-update`) must not be
1552
- * rolled back by an older result snapshot. Only comparable revisions are
1553
- * ordered; legacy entries without `revision` keep the old "last wins" rule.
1673
+ * rolled back by an older result snapshot — and the *same* snapshot must not
1674
+ * be applied twice. 1.9.1 skipped only `entry.revision < current.revision`,
1675
+ * so an equal revision was re-applied and bumped every row by one revision
1676
+ * on each replay (T1 实测:T1–T7 各 +1)。
1554
1677
  */
1555
1678
  if (Number.isInteger(entry.revision) && Number.isInteger(current.revision)
1556
- && Number(entry.revision) < Number(current.revision))
1679
+ && Number(entry.revision) <= Number(current.revision))
1557
1680
  continue;
1558
1681
  try {
1559
1682
  next = applyStatus(next, entry.subtaskId, {
@@ -1622,8 +1745,19 @@ export function applyStatus(statuses, subtaskId, patch) {
1622
1745
  next.finishedAt = patch.finishedAt;
1623
1746
  if (patch.summary !== undefined)
1624
1747
  next.summary = truncate(String(patch.summary), 3000);
1625
- if (patch.error !== undefined)
1748
+ if (patch.error !== undefined) {
1749
+ /*
1750
+ * [1.10.0] 显式清空 `error` 也属于一次「失败记录退场」:先留档再清空。
1751
+ *
1752
+ * 回放路径(`applyResultStatuses`)对 done 行传的是 `error: null`,如果这里
1753
+ * 只是把它抹掉,事故记录里「为什么这一行曾经没做完」就再也查不到了。
1754
+ */
1755
+ if (patch.error === null && typeof current.error === 'string' && current.error.trim() !== '') {
1756
+ next.lastError = current.error;
1757
+ next.lastErrorAt = Date.now();
1758
+ }
1626
1759
  next.error = patch.error === null ? null : truncate(String(patch.error), 2000);
1760
+ }
1627
1761
  if (patch.verification !== undefined) {
1628
1762
  if (!VERIFICATIONS.includes(patch.verification)) {
1629
1763
  throw new PlanError(`非法 verification:${String(patch.verification)}`, 'INVALID_VERIFICATION');
@@ -1648,6 +1782,20 @@ export function applyStatus(statuses, subtaskId, patch) {
1648
1782
  }
1649
1783
  if (patch.needs !== undefined)
1650
1784
  next.needs = readEvidenceNeeds(patch.needs);
1785
+ /*
1786
+ * [1.10.6] The files a retry refused to touch.
1787
+ *
1788
+ * A ceiling timeout can be retried once, but only when the artifacts the first
1789
+ * attempt landed are unchanged. When they did change, `runtime.ts` records
1790
+ * their refs here instead of overwriting them, so "why was there no retry"
1791
+ * stays answerable from the plan record alone.
1792
+ */
1793
+ if (patch.artifactConflict !== undefined) {
1794
+ next.artifactConflict = (Array.isArray(patch.artifactConflict) ? patch.artifactConflict : [])
1795
+ .slice(0, 8)
1796
+ .map((ref) => truncate(String(ref ?? ''), 300))
1797
+ .filter((ref) => ref !== '');
1798
+ }
1651
1799
  if (patch.blockedBy !== undefined) {
1652
1800
  next.blockedBy = (Array.isArray(patch.blockedBy) ? patch.blockedBy : [])
1653
1801
  .slice(0, 10)
@@ -1668,6 +1816,46 @@ export function applyStatus(statuses, subtaskId, patch) {
1668
1816
  next.progress = 100;
1669
1817
  if (next.finishedAt === null)
1670
1818
  next.finishedAt = Date.now();
1819
+ /*
1820
+ * [1.10.0] R-01:「完成」与「失败原因」不能同时成立。
1821
+ *
1822
+ * 1.9.1 及以前,done 分支根本不碰 `error`,而改判路径对非 blocked 传的是
1823
+ * `undefined`,被上面 1816 行解释成「保留旧值」。于是「预算用尽,等待续跑」
1824
+ * 这类上一轮的失败文本会永久留在一个 status=done 的行上,界面再无条件把它
1825
+ * 渲染成「卡住原因」——同一行同时写着「已完成」和「卡住了」,就是这次
1826
+ * 事故的同屏矛盾。
1827
+ *
1828
+ * 旧文本不丢弃,迁入 `lastError` 供审计;`error` 只描述「当前这一行为什么
1829
+ * 没做完」,完成的行没有这种原因。
1830
+ */
1831
+ if (typeof next.error === 'string' && next.error.trim() !== '') {
1832
+ next.lastError = next.error;
1833
+ next.lastErrorAt = Date.now();
1834
+ }
1835
+ /*
1836
+ * [1.10.2] 写侧补漏:显式传 `error` 的 done 也必须清空。
1837
+ *
1838
+ * 1.10.0/1.10.1 只在 `patch.error` 为 `undefined`/`null` 时清空,因此
1839
+ * `applyStatus(rows, id, { status: 'done', error: '...' })`(以及把子会话
1840
+ * result 原样回放的 `applyResultStatuses`)仍能把「完成 + 失败文本」写进
1841
+ * 持久化记录。读侧 `normaliseStatusEntry` 会在下发的载荷里清洗,界面看不到,
1842
+ * 但只要有任何消费者直接读 `record.statuses`(审计、导出、后续新增字段),
1843
+ * 这个不变量就又破了。这里与读侧使用同一条规则:旧文本只进 `lastError`。
1844
+ */
1845
+ next.error = null;
1846
+ next.completedBy = ['child', 'agent', 'system'].includes(patch.completedBy)
1847
+ ? patch.completedBy
1848
+ : (next.completedBy ?? next.updatedBy ?? 'system');
1849
+ if (next.attemptOutcome !== undefined && next.attemptOutcome !== null
1850
+ && next.attemptOutcome !== 'completed' && next.attemptOutcome !== 'manual') {
1851
+ next.priorOutcome = next.attemptOutcome;
1852
+ }
1853
+ next.attemptOutcome = patch.attemptOutcome
1854
+ ?? (next.completedBy === 'agent' ? 'manual' : 'completed');
1855
+ next.attemptEndedAt = patch.attemptEndedAt ?? Date.now();
1856
+ // [1.10.6] A finished row cannot also be "we refused to overwrite it".
1857
+ if (patch.artifactConflict === undefined)
1858
+ next.artifactConflict = undefined;
1671
1859
  }
1672
1860
  if (patch.status === 'pending') {
1673
1861
  /*
@@ -1700,10 +1888,16 @@ export function applyStatus(statuses, subtaskId, patch) {
1700
1888
  next.needs = undefined;
1701
1889
  if (patch.blockedBy === undefined)
1702
1890
  next.blockedBy = undefined;
1891
+ // [1.10.6] A conflict belongs to one attempt; a reset starts a new one.
1892
+ if (patch.artifactConflict === undefined)
1893
+ next.artifactConflict = undefined;
1703
1894
  }
1704
1895
  if (patch.status === 'in_progress') {
1705
1896
  if (next.startedAt === null)
1706
1897
  next.startedAt = Date.now();
1898
+ // [1.10.6] The retry of a conflicting row is itself the new attempt.
1899
+ if (patch.artifactConflict === undefined)
1900
+ next.artifactConflict = undefined;
1707
1901
  /*
1708
1902
  * [1.5.2] 「正在做」不允许自称 100%。
1709
1903
  *
@@ -1756,6 +1950,21 @@ export function normaliseStatusEntry(entry) {
1756
1950
  const source = entry ?? {};
1757
1951
  const status = isSubtaskStatus(source.status) ? source.status : 'pending';
1758
1952
  const progress = status === 'done' ? 100 : status === 'pending' ? 0 : clampProgress(source.progress);
1953
+ /*
1954
+ * [1.10.0] R-01 读侧兜底:历史脏数据在载荷层就要干净。
1955
+ *
1956
+ * 1.9.1 写下的记录里,被人工改判为 done 的行仍带着上一轮的失败文本。只修写
1957
+ * 入口不会让已经落盘的记录自愈,而状态只存在于会话事件日志里、不会重写,
1958
+ * 所以必须在每次派生载荷时把「done + error」拆成「done + lastError」,
1959
+ * 否则用户刷新一次就又能看到「已完成 + 卡住原因」。
1960
+ */
1961
+ const legacyError = typeof source.error === 'string' && source.error.trim() !== ''
1962
+ ? source.error
1963
+ : null;
1964
+ const error = status === 'done' ? null : legacyError;
1965
+ const lastError = status === 'done'
1966
+ ? (typeof source.lastError === 'string' && source.lastError !== '' ? source.lastError : legacyError)
1967
+ : (typeof source.lastError === 'string' ? source.lastError : null);
1759
1968
  return {
1760
1969
  ...source,
1761
1970
  subtaskId: stringOr(source.subtaskId, ''),
@@ -1769,7 +1978,8 @@ export function normaliseStatusEntry(entry) {
1769
1978
  startedAt: status === 'pending' ? null : numberOrNull(source.startedAt),
1770
1979
  finishedAt: status === 'pending' ? null : numberOrNull(source.finishedAt),
1771
1980
  summary: stringOr(source.summary, ''),
1772
- error: typeof source.error === 'string' ? source.error : null,
1981
+ error,
1982
+ ...(lastError ? { lastError } : {}),
1773
1983
  };
1774
1984
  }
1775
1985
  /**
@@ -1801,7 +2011,7 @@ export function normaliseStatuses(statuses) {
1801
2011
  * therefore never drag the plan's percentage up to where the cards say it is
1802
2012
  * finished — that was the “100% 但 11/12” contradiction users saw.
1803
2013
  */
1804
- export function deriveAggregates(statuses) {
2014
+ export function deriveAggregates(statuses, expectedTotal) {
1805
2015
  const departments = new Map();
1806
2016
  let done = 0;
1807
2017
  let blocked = 0;
@@ -1840,7 +2050,20 @@ export function deriveAggregates(statuses) {
1840
2050
  department.inProgress += 1;
1841
2051
  departments.set(item.department, department);
1842
2052
  }
1843
- const total = statuses.length;
2053
+ /*
2054
+ * [1.10.0] R-07:分母必须来自「计划定义」,不能是「实际有几行状态」。
2055
+ *
2056
+ * 1.9.1 的 `total = statuses.length`,而 I1 又只是拿它和自身比较(同义反复),
2057
+ * 于是构造出「定义 13 项、只写 5 行状态」就得到 5/5 = 100%(T3 反例 C16)。
2058
+ * 现在调用方把定义条数传进来:缺的行按 pending 计入总数,既不会把分母缩小,
2059
+ * 也不会凭空造出几行明细。
2060
+ */
2061
+ const defined = Number.isInteger(expectedTotal) && Number(expectedTotal) > 0
2062
+ ? Number(expectedTotal)
2063
+ : 0;
2064
+ const total = Math.max(statuses.length, defined);
2065
+ const missing = Math.max(0, total - statuses.length);
2066
+ pending += missing;
1844
2067
  const allDone = total > 0 && done === total;
1845
2068
  /*
1846
2069
  * [1.5.2] 加权进度在「未全部完成」时不得四舍五入成 100。
@@ -1870,9 +2093,9 @@ export function deriveAggregates(statuses) {
1870
2093
  * values share one array instance, so `stats`, `departments` and `statuses` in
1871
2094
  * a single payload cannot disagree.
1872
2095
  */
1873
- export function derivePlanSnapshot(raw) {
2096
+ export function derivePlanSnapshot(raw, expectedTotal) {
1874
2097
  const statuses = normaliseStatuses(raw);
1875
- const { stats, departments } = deriveAggregates(statuses);
2098
+ const { stats, departments } = deriveAggregates(statuses, expectedTotal);
1876
2099
  return { statuses, stats, departments };
1877
2100
  }
1878
2101
  /**
@@ -1899,8 +2122,23 @@ export function computeStats(statuses) {
1899
2122
  export function aggregateInvariantViolations(snapshot, phase) {
1900
2123
  const violations = [];
1901
2124
  const { statuses, stats, departments } = snapshot;
1902
- if (stats.total !== statuses.length) {
1903
- violations.push(`I1 stats.total=${stats.total} 与 statuses.length=${statuses.length} 不一致`);
2125
+ /*
2126
+ * [1.10.0] I1 改为「不得小于」,并新增 I12/I13。
2127
+ *
2128
+ * 旧 I1 是 `stats.total === statuses.length`——与产生它的表达式同义反复,
2129
+ * 永远成立,等于没检查(T3 实测 C16)。现在分母允许大于明细行数(缺行按
2130
+ * pending 计入),真正要禁止的是「分母比明细还小」这种把 100% 造出来的情形。
2131
+ * I12 封住本次事故的同屏矛盾:done 行不允许带 error。
2132
+ * I13 封住反过来的一侧:全部 done 却写着 progress<100。
2133
+ */
2134
+ if (stats.total < statuses.length) {
2135
+ violations.push(`I1 stats.total=${stats.total} 小于 statuses.length=${statuses.length}`);
2136
+ }
2137
+ if (stats.total > 0 && stats.done === stats.total && stats.progress !== 100) {
2138
+ violations.push(`I13 全部 ${stats.total} 项已 done,但 stats.progress=${stats.progress}`);
2139
+ }
2140
+ if (stats.done < stats.total && stats.progress >= 100) {
2141
+ violations.push(`I13 仅 ${stats.done}/${stats.total} 项 done,但 stats.progress=100`);
1904
2142
  }
1905
2143
  const counted = stats.done + stats.blocked + stats.inProgress + stats.pending;
1906
2144
  if (counted !== stats.total) {
@@ -1937,6 +2175,10 @@ export function aggregateInvariantViolations(snapshot, phase) {
1937
2175
  if (item.status === 'done' && item.progress !== 100) {
1938
2176
  violations.push(`I6 ${item.subtaskId} 是 done 但 progress=${item.progress}`);
1939
2177
  }
2178
+ /* [1.10.0] I12:「完成」与「卡住原因」不能同屏。 */
2179
+ if (item.status === 'done' && typeof item.error === 'string' && item.error.trim() !== '') {
2180
+ violations.push(`I12 ${item.subtaskId} 是 done 但仍带 error=${item.error.slice(0, 80)}`);
2181
+ }
1940
2182
  }
1941
2183
  const sums = { total: 0, done: 0, blocked: 0, inProgress: 0 };
1942
2184
  for (const department of departments) {
@@ -2052,6 +2294,12 @@ export function planPhase(statuses, _resultSeen = false) {
2052
2294
  * 它们携带状态列表里没有的信息(预算暂停、用户取消)。
2053
2295
  */
2054
2296
  export function reconcilePhase(phase, statuses) {
2297
+ /*
2298
+ * [1.9.0] 终态优先:superseded 的记录即使状态全部 done,也不得被对账成
2299
+ * done(T8 §5.5 C6)。cancelled 保持 1.8.19 的既有对账语义不变。
2300
+ */
2301
+ if (phase === 'superseded')
2302
+ return phase;
2055
2303
  const derived = planPhase(statuses);
2056
2304
  if (derived === 'done')
2057
2305
  return 'done';
@@ -2118,6 +2366,18 @@ export function deliveryReadiness(snapshot, options = {}) {
2118
2366
  }
2119
2367
  const done = Number(snapshot?.stats?.done ?? 0);
2120
2368
  const total = Number(snapshot?.stats?.total ?? 0);
2369
+ /*
2370
+ * [1.10.1] DF-05(P0):分母对账必须同时作用在交付门上。
2371
+ *
2372
+ * 1.10.0 把 `stats.total` 改成了计划定义条数,但 `deliveryReadiness` 仍然只遍历
2373
+ * 实际存在的状态行——于是「定义 13 项、只写 5 行且全 done」会得到
2374
+ * `done=5 / total=13` 却 **ready=true**,present 门禁可放行只做了 5/13 的计划
2375
+ * (T10 实测 `[done=5,total=13,ready=True]`)。缺失的行就是没做完,必须算阻塞。
2376
+ */
2377
+ const missingRows = total - statuses.length;
2378
+ if (total > 0 && missingRows > 0) {
2379
+ blockers.push(`状态明细缺少 ${missingRows} 行(计划定义 ${total} 项,实际只写 ${statuses.length} 行):缺失项按未完成计`);
2380
+ }
2121
2381
  if (phase === 'cancelled' && (remaining.length > 0 || blockers.length > 0)) {
2122
2382
  blockers.unshift(`计划已取消但只完成 ${done}/${total}:取消只停止执行,不等于完成`);
2123
2383
  }
@@ -2345,6 +2605,28 @@ export function buildChildPrompt({ plan, subtask, stage, dependencyResults, cwd,
2345
2605
  '请针对上面这个原因调整做法,不要重复相同的失败路径;如果仍然无法完成,第一行输出 `BLOCKED: 原因` 并说明缺少什么。',
2346
2606
  ].join('\n')
2347
2607
  : '';
2608
+ /*
2609
+ * [1.8.19] A retried subtask must not pretend the prior attempt never existed.
2610
+ *
2611
+ * The timeout/budget paths record the declared outputs that already landed on
2612
+ * disk (`artifacts[].exists === true`). Feeding them back into the next
2613
+ * attempt turns a 15-minute restart into "check what is there and finish",
2614
+ * which is the difference between a recoverable ceiling and silent rework.
2615
+ */
2616
+ const previousStatus = Array.isArray(statuses)
2617
+ ? statuses.find((item) => item && item.subtaskId === subtask?.id)
2618
+ : null;
2619
+ const landedArtifacts = (Array.isArray(previousStatus?.artifacts) ? previousStatus.artifacts : [])
2620
+ .filter((item) => item && item.exists === true && typeof item.ref === 'string')
2621
+ .map((item) => String(item.ref));
2622
+ const resumeHint = landedArtifacts.length > 0
2623
+ ? [
2624
+ '',
2625
+ '上一次这一子任务被中止,但以下声明产物已经在盘上(先用 read/grep 核对,不要重写):',
2626
+ ...landedArtifacts.slice(0, 8).map((ref) => `- ${ref}`),
2627
+ '已经覆盖验收标准的部分保持原样,只补缺失部分;结尾按契约给出证据块。',
2628
+ ].join('\n')
2629
+ : '';
2348
2630
  /*
2349
2631
  * [1.8.12] 提示词整体过一遍 session-reference 消毒。
2350
2632
  *
@@ -2377,6 +2659,7 @@ export function buildChildPrompt({ plan, subtask, stage, dependencyResults, cwd,
2377
2659
  dependencies,
2378
2660
  ...(team ? ['', '兄弟部门进展(同一计划内的其他子任务;不要直接联系它们,需要协作请写进 needs 由主 Agent 转达):', team] : []),
2379
2661
  ...(failure ? [failure] : []),
2662
+ ...(resumeHint ? [resumeHint] : []),
2380
2663
  '',
2381
2664
  '执行要求:',
2382
2665
  '- 只完成本子任务,不擅自扩大范围;不要派生新的 Agent。',