dsh-workplan 1.8.4 → 1.8.18

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/runtime.js CHANGED
@@ -14,8 +14,30 @@
14
14
  import { randomUUID } from 'node:crypto';
15
15
  import { existsSync } from 'node:fs';
16
16
  import { isAbsolute, resolve } from 'node:path';
17
- import { MAX_CONCURRENT, PlanError, aggregateInvariantViolations, applyStatus, attachPlanMeta, buildChildPrompt, buildCancelMessage, buildDegradedMessage, buildPlanMessage, buildPlannerPrompt, buildResultMessage, createStatuses, derivePlanSnapshot, extractJson, flattenSubtasks, isRecord, isSocialMessage, isStatusQuestion, isVagueContinuation, markDependentsBlocked, messageText, readySubtasks, MAX_PLAN_RESUMES, canResumePlan, resetBlockedStatuses, parseCancelMessage, parseResultMessage, parseWorkplanMessage, planPhase, reconcilePhase, truncate, validatePlan, applyResultStatuses, adjudicateResult, MAX_CONVERSATION_CHARS, parseUpdateMessage, buildUpdateMessage, } from './plan.js';
17
+ import { MAX_CONCURRENT, PlanError, aggregateInvariantViolations, applyStatus, attachPlanMeta, buildChildPrompt, buildCancelMessage, buildDegradedMessage, buildPlanMessage, buildPlannerPrompt, buildResultMessage, buildStopSteerText, createStatuses, deliveryReadiness, derivePlanSnapshot, extractJson, flattenSubtasks, isRecord, isSocialMessage, isStatusQuestion, isVagueContinuation, makeUserMessage, markDependentsBlocked, messageText, readySubtasks, MAX_PLAN_RESUMES, canResumePlan, resetBlockedStatuses, parseCancelMessage, parseResultMessage, parseWorkplanMessage, planPhase, reconcilePhase, truncate, validatePlan, applyResultStatuses, adjudicateResult, MAX_CONVERSATION_CHARS, parseUpdateMessage, buildUpdateMessage, } from './plan.js';
18
18
  import { createProgressWatchdog, describeError } from './watchdog.js';
19
+ /**
20
+ * [1.8.18] How many subtasks the plan *defines*.
21
+ *
22
+ * `deliveryReadiness` counts the derived statuses, and `ready` requires
23
+ * `total > 0`, so a plan with `stages: []` can never be ready. Such a plan is
24
+ * not a delivery object at all: normal planning rejects it (`validatePlan`),
25
+ * and it can only reach replay from a malformed historical message. Judging it
26
+ * as "0/0 unfinished forever" was U6 (T5 P13): present was refused with the
27
+ * false copy "0 个子任务虽都已 done".
28
+ *
29
+ * A malformed plan that reaches this function still counts as deliverable
30
+ * (`MAX_SAFE_INTEGER`); plans failing reconstruction earlier are dropped by
31
+ * `sessionPlanRecords` — a known fail-open boundary (T5 A9), not closed here.
32
+ */
33
+ function definedSubtaskCount(plan) {
34
+ try {
35
+ return flattenSubtasks(plan).length;
36
+ }
37
+ catch {
38
+ return Number.MAX_SAFE_INTEGER;
39
+ }
40
+ }
19
41
  export const PLANNER_TIMEOUT_MS = 120000;
20
42
  /**
21
43
  * Absolute ceiling for one child execution.
@@ -287,7 +309,7 @@ async function disposeActivation(activation, record, subtaskId, guard) {
287
309
  catch (error) {
288
310
  if (!guard?.timedOut) {
289
311
  record.errors = [
290
- ...record.errors,
312
+ ...(record.errors ?? []),
291
313
  `${subtaskId} dispose: ${truncate(String(error?.message ?? error), 300)}`,
292
314
  ].slice(-20);
293
315
  }
@@ -338,7 +360,7 @@ function writeSubtaskStatus(record, subtaskId, patch, guard) {
338
360
  function recordSubtaskError(record, subtaskId, message, guard) {
339
361
  if (guard.timedOut)
340
362
  return;
341
- record.errors = [...record.errors, `${subtaskId}: ${truncate(message, 500)}`].slice(-20);
363
+ record.errors = [...(record.errors ?? []), `${subtaskId}: ${truncate(message, 500)}`].slice(-20);
342
364
  }
343
365
  /**
344
366
  * Resolve one artifact reference against the round's working directory.
@@ -383,6 +405,82 @@ export function checkArtifacts(artifacts, cwd, artifactExists = existsSync) {
383
405
  });
384
406
  return { artifacts: checked, missingArtifacts };
385
407
  }
408
+ /**
409
+ * [1.8.5] 被中断时,先说清「东西到底写出来没有」。
410
+ *
411
+ * 事故(2026-10-30):一个子 Agent 在 21:34:52 写完了 38KB 交付物,两秒后被
412
+ * 外部中断;插件只留下「结束状态为 aborted」,产物存在与否完全不进判定,主
413
+ * Agent 只能把它当彻底失败,下游 6 个任务跟着停摆。
414
+ *
415
+ * 这里不改变任何判定语义(中断依然记为失败、依然不自动重试),只在报错里
416
+ * 附上一句可核实的事实:该步声明的产物里有哪几个已经在盘上。看到这句话的人
417
+ * 才知道下一步该去核对、改判,而不是白等一次重试。
418
+ */
419
+ export function probeInterruptedArtifacts(output, subtask, cwd, artifactExists = existsSync) {
420
+ const candidates = new Set();
421
+ const collect = (text) => {
422
+ if (typeof text !== 'string' || !text)
423
+ return;
424
+ // 文件名可能带中文(本次事故就是「T6_人性博弈推演_20261030.md」这种),
425
+ // 所以字符集必须放行 CJK,否则真正的产物会被当成没写。
426
+ for (const hit of text.matchAll(/[\w\u4e00-\u9fff@.\/-]+\.(?:md|csv|json|html|txt|ts|js|py|ya?ml)/g)) {
427
+ const ref = hit[0].replace(/^\.\//, '');
428
+ // 太短的多半是扩展名碎片(如 “.md”),不足以定位文件。
429
+ if (ref.length > 3)
430
+ candidates.add(ref);
431
+ }
432
+ };
433
+ collect(output);
434
+ for (const item of Array.isArray(subtask?.outputs) ? subtask.outputs : [])
435
+ collect(item);
436
+ const landed = [];
437
+ for (const ref of candidates) {
438
+ const target = resolveArtifactPath(ref, cwd);
439
+ if (!target)
440
+ continue;
441
+ let exists = false;
442
+ try {
443
+ exists = artifactExists(target) === true;
444
+ }
445
+ catch {
446
+ exists = false;
447
+ }
448
+ if (exists)
449
+ landed.push(ref);
450
+ if (landed.length >= 6)
451
+ break;
452
+ }
453
+ return landed;
454
+ }
455
+ /**
456
+ * [1.8.6] Turn "the child was interrupted" into evidence the plan can hold.
457
+ *
458
+ * 1.8.5 only put the landed files into the error string. That helped a human
459
+ * read the message, but the plan still recorded `blocked` with no
460
+ * `artifacts` / `missingArtifacts`, so the dispatcher had nothing to check and
461
+ * cascaded every dependent into `blocked`: one interrupted child still killed
462
+ * its whole downstream. This records the same finding in the status fields the
463
+ * scheduler already understands.
464
+ *
465
+ * It deliberately does NOT change the verdict: an interrupted task stays
466
+ * `blocked` (no auto-retry, no auto-adjudication). It only stops the cascade
467
+ * and leaves the main Agent a factual basis to re-adjudicate.
468
+ */
469
+ export function probeInterruptedEvidence(output, subtask, cwd, artifactExists = existsSync) {
470
+ const landed = probeInterruptedArtifacts(output, subtask, cwd, artifactExists);
471
+ const declared = [];
472
+ for (const item of Array.isArray(subtask?.outputs) ? subtask.outputs : []) {
473
+ for (const hit of String(item).matchAll(/[\w\u4e00-\u9fff@.\/-]+\.(?:md|csv|json|html|txt|ts|js|py|ya?ml)/g)) {
474
+ const ref = hit[0].replace(/^\.\//, '');
475
+ if (ref.length > 3 && !declared.includes(ref))
476
+ declared.push(ref);
477
+ }
478
+ }
479
+ const refs = [...new Set([...declared, ...landed])];
480
+ const artifacts = refs.map((ref) => ({ kind: 'file', ref, exists: landed.includes(ref) }));
481
+ const missingArtifacts = declared.filter((ref) => !landed.includes(ref));
482
+ return { artifacts, missingArtifacts };
483
+ }
386
484
  /**
387
485
  * Turn one child output into a status verdict.
388
486
  *
@@ -441,6 +539,15 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
441
539
  const { parentSignal, deadline, modelSelection, conversationContext = '', child, guard } = options;
442
540
  let lastError = null;
443
541
  let lastFailure = null;
542
+ /*
543
+ * [1.8.6] The interrupt has to outlive the thrown error.
544
+ *
545
+ * `interruptedFlag` travels back to the dispatcher (it must not cascade this
546
+ * task's dependents); `interruptedEvidence` is what gets written into the
547
+ * blocked status so the main Agent can re-adjudicate on facts.
548
+ */
549
+ let interruptedFlag = false;
550
+ let interruptedEvidence = null;
444
551
  try {
445
552
  if (!writeSubtaskStatus(record, subtask.id, {
446
553
  status: 'in_progress',
@@ -451,6 +558,7 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
451
558
  for (let attempt = 1; attempt <= 2; attempt += 1) {
452
559
  if (guard.timedOut)
453
560
  return;
561
+ interruptedEvidence = null;
454
562
  if (parentSignal.aborted)
455
563
  throw abortError();
456
564
  if (Date.now() >= deadline)
@@ -548,7 +656,25 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
548
656
  return;
549
657
  const output = resultText(result);
550
658
  if (result.stopReason !== 'completed') {
551
- throw new PlanError(`子 Agent 结束状态为 ${result.stopReason}${result.diagnostic ? `:${result.diagnostic}` : ''}`, 'CHILD_NOT_COMPLETED');
659
+ /*
660
+ * [1.8.5] 中断必须自己说出「接下来怎么办」。
661
+ *
662
+ * 2026-10-30 事故:T6 在被外部中断前 2 秒已写出 38KB 交付物,插件只留下
663
+ * 「子 Agent 结束状态为 aborted」,主 Agent 无从知道产物其实已经在盘上,
664
+ * 于是把它当彻底失败处理,并把 6 个下游一起判死。中断类失败要显式提示
665
+ * 「先核对已写出的产物」,并给出据实改判与续跑这两条出口。
666
+ */
667
+ const interrupted = result.stopReason === 'aborted';
668
+ const landed = interrupted ? probeInterruptedArtifacts(output, subtask, options.cwd, options.artifactExists) : [];
669
+ if (interrupted) {
670
+ interruptedFlag = true;
671
+ interruptedEvidence = probeInterruptedEvidence(output, subtask, options.cwd, options.artifactExists);
672
+ }
673
+ throw new PlanError(`子 Agent 结束状态为 ${result.stopReason}${result.diagnostic ? `:${result.diagnostic}` : ''}${interrupted
674
+ ? `(子 Agent 在完成前被中断:先核对该步声明的产物是否已写出${landed.length > 0
675
+ ? `——已核到 ${landed.length} 个文件确实在盘上:${landed.join('、')}`
676
+ : ''};据实改判,再决定是否续跑)`
677
+ : ''}`, 'CHILD_NOT_COMPLETED');
552
678
  }
553
679
  if (!output)
554
680
  throw new PlanError('子 Agent 没有返回文本结果', 'EMPTY_CHILD_OUTPUT');
@@ -587,7 +713,7 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
587
713
  const retry = !isAbort && shouldRetryAttempt(error, attempt, remaining, idleTimeoutMs);
588
714
  if (retry) {
589
715
  record.errors = [
590
- ...record.errors,
716
+ ...(record.errors ?? []),
591
717
  `${subtask.id}: 第 ${attempt} 次执行失败(${lastFailure.code}),已带上失败原因重试`,
592
718
  ].slice(-20);
593
719
  writeSubtaskStatus(record, subtask.id, { progress: 15 }, guard);
@@ -595,7 +721,7 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
595
721
  }
596
722
  if (!isAbort && remaining <= idleTimeoutMs && error?.code !== 'CHILD_TIMEOUT') {
597
723
  record.errors = [
598
- ...record.errors,
724
+ ...(record.errors ?? []),
599
725
  `${subtask.id}: 剩余预算不足(${Math.max(0, Math.round(remaining / 1000))}s),未重试`,
600
726
  ].slice(-20);
601
727
  }
@@ -615,8 +741,18 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
615
741
  finishedAt: Date.now(),
616
742
  error: truncate(message, 2000),
617
743
  summary: truncate(`未完成:${message}`, 3000),
744
+ // [1.8.6] A blocked status that carries no evidence is what made the
745
+ // dispatcher treat "interrupted, file on disk" exactly like "produced
746
+ // nothing". Record what was actually found.
747
+ ...(interruptedEvidence && interruptedEvidence.artifacts.length > 0
748
+ ? { artifacts: interruptedEvidence.artifacts }
749
+ : {}),
750
+ ...(interruptedEvidence && interruptedEvidence.missingArtifacts.length > 0
751
+ ? { missingArtifacts: interruptedEvidence.missingArtifacts }
752
+ : {}),
618
753
  }, guard);
619
754
  recordSubtaskError(record, subtask.id, message, guard);
755
+ return interruptedFlag ? { interrupted: true } : undefined;
620
756
  }
621
757
  catch (error) {
622
758
  const message = describeError(error);
@@ -665,12 +801,12 @@ async function runSubtask(ctx, record, stage, subtask, options) {
665
801
  error: message,
666
802
  summary: truncate(`未完成:${message}`, 3000),
667
803
  });
668
- record.errors = [...record.errors, `${subtask.id}: ${message}`].slice(-20);
804
+ record.errors = [...(record.errors ?? []), `${subtask.id}: ${message}`].slice(-20);
669
805
  record.updatedAt = Date.now();
670
806
  }
671
807
  catch (error) {
672
808
  record.errors = [
673
- ...record.errors,
809
+ ...(record.errors ?? []),
674
810
  `${subtask.id}: 超时状态写入失败:${truncate(String(error?.message ?? error), 500)}`,
675
811
  ].slice(-20);
676
812
  }
@@ -685,7 +821,9 @@ async function runSubtask(ctx, record, stage, subtask, options) {
685
821
  timer.unref?.();
686
822
  });
687
823
  try {
688
- await Promise.race([
824
+ // [1.8.6] The outcome (`{interrupted:true}`) has to reach the dispatcher;
825
+ // swallowing it here is why an interrupted child looked like any failure.
826
+ return await Promise.race([
689
827
  executeSubtask(ctx, record, stage, subtask, {
690
828
  ...options,
691
829
  child,
@@ -748,6 +886,15 @@ export function modelStatusLines(statuses) {
748
886
  summary: truncate(item.summary ?? item.error ?? '', 2000),
749
887
  error: item.error ?? null,
750
888
  verification: item.verification ?? null,
889
+ // [1.8.13] The model must see *which* acceptance item failed, not just the
890
+ // verdict; it cannot repair a gap it cannot name.
891
+ acceptance: Array.isArray(item.acceptance)
892
+ ? item.acceptance.slice(0, 8).map((entry) => ({
893
+ criterion: truncate(String(entry?.criterion ?? ''), 200),
894
+ result: String(entry?.result ?? ''),
895
+ evidence: truncate(String(entry?.evidence ?? ''), 300),
896
+ }))
897
+ : [],
751
898
  revision: Number(item.revision ?? 0),
752
899
  updatedBy: item.updatedBy ?? null,
753
900
  missingArtifacts: Array.isArray(item.missingArtifacts) ? item.missingArtifacts : [],
@@ -770,6 +917,49 @@ export function buildRoundResult(record, sessionId, limits) {
770
917
  resumeAvailable: canResumePlan(record, limits.maxResumes).resume,
771
918
  });
772
919
  }
920
+ /**
921
+ * [1.8.6] Explain why a `pending` task cannot run, instead of calling it blocked.
922
+ *
923
+ * A single generic sentence made three different situations indistinguishable:
924
+ * a budget pause (nothing ran yet), an upstream whose declared file is missing
925
+ * (the work may well be done), and a genuinely failed upstream. The main Agent
926
+ * read all three as "7 卡住了" and had to re-derive the cause by hand.
927
+ */
928
+ function describePendingCause(plan, statuses, id) {
929
+ const byId = new Map(statuses.map((item) => [item.subtaskId, item]));
930
+ const entry = flattenSubtasks(plan).find((candidate) => candidate.subtask.id === id);
931
+ if (!entry)
932
+ return '计划里找不到该步骤';
933
+ const declared = Array.isArray(entry.subtask.dependsOn) ? entry.subtask.dependsOn : [];
934
+ if (declared.length === 0)
935
+ return '没有上游依赖,但本轮未被调度到';
936
+ const bad = declared.filter((dep) => {
937
+ const state = byId.get(dep);
938
+ if (!state || state.status !== 'done')
939
+ return true;
940
+ if (Array.isArray(state.missingArtifacts) && state.missingArtifacts.length > 0)
941
+ return true;
942
+ if (state.verification === 'legacy')
943
+ return true;
944
+ return false;
945
+ });
946
+ if (bad.length === 0)
947
+ return '上游都已就绪,但本轮未被调度到';
948
+ return bad.map((dep) => {
949
+ const state = byId.get(dep);
950
+ if (!state)
951
+ return `上游 ${dep} 缺失`;
952
+ if (state.status !== 'done') {
953
+ return `上游 ${dep} 状态为 ${state.status}${state.error ? `(${String(state.error).slice(0, 80)})` : ''}`;
954
+ }
955
+ if (Array.isArray(state.missingArtifacts) && state.missingArtifacts.length > 0) {
956
+ return `上游 ${dep} 的声明产物缺失:${state.missingArtifacts.join('、')}`;
957
+ }
958
+ if (state.verification === 'legacy')
959
+ return `上游 ${dep} 完成但未提供结构化证据`;
960
+ return `上游 ${dep} 不可用`;
961
+ }).join(';');
962
+ }
773
963
  export async function dispatchPlan(ctx, record, options) {
774
964
  const { agent, signal, modelSelection, cwd, conversationContext = '' } = options;
775
965
  const deadline = Date.now() + (options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS);
@@ -825,6 +1015,16 @@ export async function dispatchPlan(ctx, record, options) {
825
1015
  record.updatedAt = record.dispatchedAt;
826
1016
  try {
827
1017
  let guard = 0;
1018
+ /*
1019
+ * [1.8.6] Interrupted tasks are not cascaded.
1020
+ *
1021
+ * The 2026-10-30 incident: one child was interrupted after it had already
1022
+ * written its deliverable; the dispatcher blocked its 6 dependents. Those
1023
+ * children were never given a chance, and the plan looked like a 7-task
1024
+ * failure. Keep the interrupted task itself `blocked` (its verdict must not
1025
+ * be rewritten automatically), but leave dependents `pending` and say why.
1026
+ */
1027
+ const interruptedIds = new Set();
828
1028
  while (true) {
829
1029
  guard += 1;
830
1030
  if (guard > 200)
@@ -846,12 +1046,22 @@ export async function dispatchPlan(ctx, record, options) {
846
1046
  }
847
1047
  : {});
848
1048
  if (ready.length === 0) {
1049
+ /*
1050
+ * [1.8.6] "Nothing is ready" is not the same thing as "everything
1051
+ * failed".
1052
+ *
1053
+ * The old code rewrote every remaining `pending` task to `blocked` with
1054
+ * one generic line ("依赖未完成或上游受阻"). A budget pause, a missing
1055
+ * artifact and a genuinely failed upstream all produced that same
1056
+ * status, the plan turned `blocked`, and a resume was billed against
1057
+ * the failure budget. Keep them `pending`, and record the actual cause.
1058
+ */
849
1059
  const pending = record.statuses.filter((item) => item.status === 'pending');
850
- for (const item of pending) {
851
- record.statuses = applyStatus(record.statuses, item.subtaskId, {
852
- status: 'blocked',
853
- error: '依赖未完成或上游受阻',
854
- });
1060
+ if (pending.length > 0) {
1061
+ const reasons = pending.map((item) => `${item.subtaskId}:${describePendingCause(record.plan, record.statuses, item.subtaskId)}`);
1062
+ const message = `本轮结束,仍有 ${pending.length} 项保持 pending(不是失败,也未级联成 blocked):${reasons.slice(0, 6).join(';')}`;
1063
+ record.error = message;
1064
+ record.errors = [...(record.errors ?? []), message].slice(-20);
855
1065
  }
856
1066
  break;
857
1067
  }
@@ -863,7 +1073,7 @@ export async function dispatchPlan(ctx, record, options) {
863
1073
  .find((candidate) => candidate.subtask.id === item.id);
864
1074
  if (!entry)
865
1075
  return;
866
- await runSubtask(ctx, record, entry.stage, entry.subtask, {
1076
+ const outcome = await runSubtask(ctx, record, entry.stage, entry.subtask, {
867
1077
  agent,
868
1078
  parentSignal: childController.signal,
869
1079
  deadline,
@@ -875,6 +1085,10 @@ export async function dispatchPlan(ctx, record, options) {
875
1085
  strictEvidence: options.strictEvidence,
876
1086
  artifactExists: options.artifactExists,
877
1087
  });
1088
+ // [1.8.6] Remember which failures were interrupts, so the cascade below
1089
+ // can leave their dependents pending instead of blaming them.
1090
+ if (outcome && outcome.interrupted)
1091
+ interruptedIds.add(item.id);
878
1092
  });
879
1093
  const blocked = record.statuses
880
1094
  .filter((item) => item.status === 'blocked')
@@ -886,6 +1100,19 @@ export async function dispatchPlan(ctx, record, options) {
886
1100
  * had to re-read the whole plan to guess what to repair.
887
1101
  */
888
1102
  const upstream = record.statuses.find((item) => item.subtaskId === id);
1103
+ /*
1104
+ * [1.8.6] An interrupted task blocked itself, not its dependents.
1105
+ *
1106
+ * Recording the interruption in `errors` (instead of silently skipping)
1107
+ * keeps the reason visible in the result message, and `continue` leaves
1108
+ * the dependents `pending` so a re-dispatch can still run them once the
1109
+ * main Agent re-adjudicates the interrupted step.
1110
+ */
1111
+ if (interruptedIds.has(id)) {
1112
+ record.errors = [...(record.errors ?? []),
1113
+ `${id}: 被中断但产物已核对(见 artifacts),未自动级联下游;请据实改判或续跑`].slice(-20);
1114
+ continue;
1115
+ }
889
1116
  const cause = upstream
890
1117
  ? {
891
1118
  reason: upstream.error,
@@ -900,7 +1127,17 @@ export async function dispatchPlan(ctx, record, options) {
900
1127
  */
901
1128
  record.updatedAt = Date.now();
902
1129
  }
903
- record.phase = planPhase(record.statuses);
1130
+ /*
1131
+ * [1.8.6] Do not let a pending tail masquerade as a failure.
1132
+ *
1133
+ * `planPhase` turns any `blocked` row into `blocked`; with D8's fix a round
1134
+ * can end with real blocked rows *and* untouched pending rows. Keep
1135
+ * `blocked` for real failures, and report `paused` when only pending work
1136
+ * is left, so a resume is not billed against the failure budget.
1137
+ */
1138
+ const hasBlocked = record.statuses.some((item) => item.status === 'blocked');
1139
+ const hasPending = record.statuses.some((item) => item.status === 'pending');
1140
+ record.phase = hasBlocked ? 'blocked' : (hasPending ? 'paused' : planPhase(record.statuses));
904
1141
  }
905
1142
  catch (error) {
906
1143
  const message = describeError(error);
@@ -962,7 +1199,7 @@ export async function dispatchPlan(ctx, record, options) {
962
1199
  */
963
1200
  record.errors = (record.errors ?? []).filter((line) => !/总执行超时/.test(String(line)));
964
1201
  if (!allDoneNow)
965
- record.errors = [...record.errors, record.error].slice(-20);
1202
+ record.errors = [...(record.errors ?? []), record.error].slice(-20);
966
1203
  }
967
1204
  else {
968
1205
  /*
@@ -1155,6 +1392,7 @@ function serialisePlan(record, session) {
1155
1392
  * 而不是等用户截图发现。附在 payload 上而不是抛错:展示层不应因自检而白屏。
1156
1393
  */
1157
1394
  const violations = aggregateInvariantViolations(snapshot, phase);
1395
+ const readiness = deliveryReadiness(snapshot, { phase: record.phase });
1158
1396
  return {
1159
1397
  sessionId: session.id,
1160
1398
  planId: record.planId ?? plan?.planId ?? null,
@@ -1171,6 +1409,17 @@ function serialisePlan(record, session) {
1171
1409
  plan,
1172
1410
  statuses,
1173
1411
  stats,
1412
+ /*
1413
+ * [1.8.13] Delivery readiness travels with the dashboard payload too.
1414
+ *
1415
+ * `phase` alone cannot express "all rows done but evidence missing, or a
1416
+ * cancelled plan is still incomplete"; a green 100% card next to a denied
1417
+ * present is exactly the contradiction this incident exposed. The UI can
1418
+ * now show the same verdict the gate uses.
1419
+ */
1420
+ deliveryReady: readiness.ready,
1421
+ deliveryBlockers: readiness.blockers.slice(0, 12),
1422
+ deliveryRemaining: readiness.remaining.slice(0, 20),
1174
1423
  /*
1175
1424
  * Liveness and resume bookkeeping. Without these the dashboard could not
1176
1425
  * tell a slow-but-alive child from a wedged one, and the model could not
@@ -1216,30 +1465,127 @@ function readToolArguments(value) {
1216
1465
  return null;
1217
1466
  }
1218
1467
  export function reconstructFromSession(session, targetPlanId) {
1219
- const start = Math.max(0, session.seq - MAX_HISTORY_EVENTS);
1220
- let plan = null;
1221
- let statuses = [];
1222
- let degraded = null;
1223
- let resultSeen = false;
1224
- // A round-budget pause must survive a page refresh; otherwise the replayed
1225
- // plan looks “executing” forever (nothing is running) and the card stops
1226
- // telling the user it can simply be dispatched again.
1227
- let resultPhase = '';
1228
- let cancelled = false;
1229
- let resumeCount = 0;
1230
1468
  /*
1231
- * Older plans stay dispatchable.
1469
+ * [1.8.10] 回放窗口必须包含目标计划的定义。
1232
1470
  *
1233
- * The replayed state used to be "whatever the newest plan message says", so a
1234
- * plan paused before a restart became unreachable the moment the next turn
1235
- * generated a new plan: the rebuild answered with the new plan and every
1236
- * dispatch of the old one failed with PLAN_ID_MISMATCH. Keep a snapshot per
1237
- * plan and let the caller ask for a specific one.
1471
+ * 会话事件超过 MAX_HISTORY_EVENTS(2000)后,窗口起点会越过早期的 plan
1472
+ * 消息。此时按 planId 重建旧计划得到 null,dispatch / status 都会退回
1473
+ * 内存里那个更新的计划,旧计划在卡片上消失,也无法再续跑。
1474
+ * 显式指定 planId 时向前扫到该计划的 plan 消息,把窗口起点前移。
1238
1475
  */
1239
- const finished = [];
1476
+ let start = Math.max(0, session.seq - MAX_HISTORY_EVENTS);
1477
+ if (targetPlanId) {
1478
+ for (let seq = start - 1; seq >= 0; seq -= 1) {
1479
+ let event;
1480
+ try {
1481
+ event = session.eventAt(seq);
1482
+ }
1483
+ catch {
1484
+ continue;
1485
+ }
1486
+ if (!event || event.type !== 'user/message')
1487
+ continue;
1488
+ const payload = parseWorkplanMessage(event.data);
1489
+ if (payload?.plan?.planId === targetPlanId) {
1490
+ start = seq;
1491
+ break;
1492
+ }
1493
+ }
1494
+ }
1495
+ /*
1496
+ * [1.8.15] Default replay keeps the "last defined plan" contract, but it
1497
+ * must still find that plan when its message predates the 2000-event window.
1498
+ *
1499
+ * T3 B4 measured the window failure on 1.8.14: on a >2000-event session the
1500
+ * window started after the plan message, the default replay returned null,
1501
+ * and `present` had no plan to judge — the delivery was silently allowed.
1502
+ * The scan reads backwards for the last `workplan` definition and moves the
1503
+ * window start to it.
1504
+ *
1505
+ * The "newest activity" variant was deliberately NOT adopted: the same
1506
+ * default answer also feeds `dispatch`, so an older plan that merely kept
1507
+ * receiving result/update messages would hijack a new task's default
1508
+ * dispatch target (the reason N5 in 1.8.14 left the contract alone). The
1509
+ * turn-scoped fixes (`planIdFromTurn`, the present gate) name the plan
1510
+ * explicitly instead of changing the default.
1511
+ */
1512
+ let defaultPlanId = null;
1513
+ if (!targetPlanId) {
1514
+ for (let seq = session.seq - 1; seq >= 0; seq -= 1) {
1515
+ let event;
1516
+ try {
1517
+ event = session.eventAt(seq);
1518
+ }
1519
+ catch {
1520
+ continue;
1521
+ }
1522
+ if (!event || event.type !== 'user/message')
1523
+ continue;
1524
+ const planMessage = parseWorkplanMessage(event.data);
1525
+ const planId = planMessage?.plan?.planId;
1526
+ if (typeof planId !== 'string' || planId === '')
1527
+ continue;
1528
+ defaultPlanId = planId;
1529
+ let planStart = seq;
1530
+ for (let back = seq - 1; back >= 0; back -= 1) {
1531
+ let prior;
1532
+ try {
1533
+ prior = session.eventAt(back);
1534
+ }
1535
+ catch {
1536
+ continue;
1537
+ }
1538
+ if (!prior || prior.type !== 'user/message')
1539
+ continue;
1540
+ if (parseWorkplanMessage(prior.data)?.plan?.planId === planId)
1541
+ planStart = back;
1542
+ }
1543
+ if (planStart < start)
1544
+ start = planStart;
1545
+ break;
1546
+ }
1547
+ }
1548
+ /*
1549
+ * [1.8.9] 回放按 planId 分账,不按会话「最后一个计划」分账。
1550
+ *
1551
+ * 旧实现只有一组 plan/statuses:中途出现第二个计划(这次事故里是「继续」被
1552
+ * 误判后生成的 wp-dd26f206)时,第一个计划的快照被冻结在当时,之后所有属于
1553
+ * 它的结果消息与人工改判都被丢弃——重启后卡片从 13/14 掉回 5/14,而会话
1554
+ * 日志里明明有 7/14 的结果消息和 6 条 done 改判。现在每个计划各一份快照,
1555
+ * 每条 durable 消息只写给 planId 指定的那个计划。
1556
+ */
1557
+ const snapshots = new Map();
1558
+ let currentId = null;
1559
+ let degraded = null;
1560
+ const ensure = (plan) => {
1561
+ let snap = snapshots.get(plan.planId);
1562
+ if (!snap) {
1563
+ snap = {
1564
+ plan,
1565
+ statuses: createStatuses(plan),
1566
+ resultPhase: '',
1567
+ resultSeen: false,
1568
+ resumeCount: 0,
1569
+ cancelled: false,
1570
+ errors: [],
1571
+ };
1572
+ snapshots.set(plan.planId, snap);
1573
+ }
1574
+ currentId = plan.planId;
1575
+ return snap;
1576
+ };
1240
1577
  /** [1.6.0] callId → 待确认的 update 写入;只有配对的 tool/result 才能定案。 */
1241
1578
  const pendingToolCalls = new Map();
1242
- const snapshot = () => ({ plan, statuses, resultPhase, resultSeen, resumeCount, cancelled });
1579
+ /**
1580
+ * [1.8.11] 已经由 durable `workplan-update` 消息应用过的人工改判。
1581
+ *
1582
+ * 一次 `dsh_workplan_update` 会写两份记录:一条 durable 用户消息(带
1583
+ * revision 与 updatedBy=agent)和一条 tool/result。回放原来两份都应用,
1584
+ * 第二次以 system 身份把 revision 再抬一级并覆盖 summary——人工改判的
1585
+ * 证据后缀就这么丢了。这里记下消息的 seq,配对的 tool/result 不再重复写。
1586
+ */
1587
+ const appliedUpdates = new Map();
1588
+ const updateKey = (planId, subtaskId) => `${planId}\u0000${subtaskId}`;
1243
1589
  for (let seq = start; seq < session.seq; seq += 1) {
1244
1590
  let event;
1245
1591
  try {
@@ -1254,36 +1600,42 @@ export function reconstructFromSession(session, targetPlanId) {
1254
1600
  const payload = parseWorkplanMessage(event.data);
1255
1601
  if (payload?.degraded) {
1256
1602
  degraded = payload;
1257
- plan = null;
1258
- statuses = [];
1259
- cancelled = false;
1603
+ currentId = null;
1260
1604
  }
1261
1605
  else if (payload?.plan) {
1262
- if (plan)
1263
- finished.push(snapshot());
1264
- plan = payload.plan;
1265
- statuses = createStatuses(plan);
1266
- cancelled = false;
1267
- /*
1268
- * A new plan must not inherit the previous plan's round phase.
1269
- *
1270
- * `resultPhase` outlived the old plan, so after a paused plan the next
1271
- * plan in the same session replayed as `paused` before its first
1272
- * dispatch — the card claimed the new plan was out of budget when it had
1273
- * not started. Only a result message for *this* plan may set it.
1274
- */
1275
- resultPhase = '';
1276
- resultSeen = false;
1277
- resumeCount = 0;
1606
+ ensure(payload.plan);
1278
1607
  }
1608
+ /*
1609
+ * Every result message is routed by its own planId. A result that arrives
1610
+ * after a newer plan was generated must still update the plan it names —
1611
+ * that was the 13/14 → 5/14 replay regression. A plan never inherits
1612
+ * another plan's round phase or resume counter (each snapshot owns them).
1613
+ */
1279
1614
  const result = parseResultMessage(event.data);
1280
- if (result && plan && result.planId === plan.planId) {
1281
- statuses = applyResultStatuses(statuses, result);
1282
- // Resume bookkeeping must survive a page refresh, otherwise the budget
1283
- // silently resets and a never-succeeding subtask can loop forever.
1284
- resumeCount = Number(result.resumeCount ?? resumeCount) || 0;
1285
- resultPhase = typeof result.phase === 'string' ? result.phase : '';
1286
- resultSeen = true;
1615
+ if (result && typeof result.planId === 'string') {
1616
+ const snap = snapshots.get(result.planId);
1617
+ if (snap) {
1618
+ snap.statuses = applyResultStatuses(snap.statuses, result);
1619
+ // Resume bookkeeping must survive a page refresh, otherwise the budget
1620
+ // silently resets and a never-succeeding subtask can loop forever.
1621
+ snap.resumeCount = Number(result.resumeCount ?? snap.resumeCount) || 0;
1622
+ snap.resultPhase = typeof result.phase === 'string' ? result.phase : '';
1623
+ snap.resultSeen = true;
1624
+ // [1.8.17] Keep the durable failure lines so a replayed record is
1625
+ // shaped like a live one (never `undefined`).
1626
+ if (Array.isArray(result.errors)) {
1627
+ snap.errors = snap.errors.concat(result.errors.map((line) => String(line))).slice(-20);
1628
+ }
1629
+ /*
1630
+ * [1.8.14] A cancel that lands while a dispatch is in flight writes no
1631
+ * separate cancel message (it aborts the dispatch instead), so the
1632
+ * only durable trace of that cancellation is `phase: 'cancelled'` in
1633
+ * the round result. Without this the plan reopens as "executing"
1634
+ * after a restart — the cancel is silently lost.
1635
+ */
1636
+ if (snap.resultPhase === 'cancelled')
1637
+ snap.cancelled = true;
1638
+ }
1287
1639
  }
1288
1640
  /*
1289
1641
  * [1.7.0] Manual re-adjudications replay in order.
@@ -1295,26 +1647,40 @@ export function reconstructFromSession(session, targetPlanId) {
1295
1647
  * newer one (see `applyResultStatuses`).
1296
1648
  */
1297
1649
  const update = parseUpdateMessage(event.data);
1298
- if (update && plan && update.planId === plan.planId && typeof update.subtaskId === 'string') {
1299
- try {
1300
- statuses = applyStatus(statuses, update.subtaskId, {
1301
- status: update.status,
1302
- progress: typeof update.progress === 'number' ? update.progress : undefined,
1303
- summary: typeof update.note === 'string' ? update.note : undefined,
1304
- revision: Number.isInteger(update.revision) ? update.revision : undefined,
1305
- updatedBy: 'agent',
1306
- });
1307
- }
1308
- catch {
1309
- // An invalid historical update is ignored; the rest still replays.
1650
+ if (update && typeof update.planId === 'string' && typeof update.subtaskId === 'string') {
1651
+ const snap = snapshots.get(update.planId);
1652
+ if (snap) {
1653
+ try {
1654
+ snap.statuses = applyStatus(snap.statuses, update.subtaskId, {
1655
+ status: update.status,
1656
+ progress: typeof update.progress === 'number' ? update.progress : undefined,
1657
+ summary: typeof update.note === 'string' ? update.note : undefined,
1658
+ // [1.8.13] Evidence written through the update tool must survive replay.
1659
+ verification: update.verification,
1660
+ acceptance: update.acceptance,
1661
+ artifacts: update.artifacts,
1662
+ missingArtifacts: update.missingArtifacts,
1663
+ revision: Number.isInteger(update.revision) ? update.revision : undefined,
1664
+ updatedBy: 'agent',
1665
+ });
1666
+ appliedUpdates.set(updateKey(update.planId, update.subtaskId), {
1667
+ seq: Number(event.seq ?? 0),
1668
+ status: String(update.status ?? ''),
1669
+ });
1670
+ }
1671
+ catch {
1672
+ // An invalid historical update is ignored; the rest still replays.
1673
+ }
1310
1674
  }
1311
1675
  }
1312
1676
  const cancel = parseCancelMessage(event.data);
1313
- if (cancel && plan && cancel.planId === plan.planId) {
1314
- cancelled = true;
1677
+ if (cancel && typeof cancel.planId === 'string') {
1678
+ const snap = snapshots.get(cancel.planId);
1679
+ if (snap)
1680
+ snap.cancelled = true;
1315
1681
  }
1316
1682
  }
1317
- else if (event.type === 'tool/call' && plan) {
1683
+ else if (event.type === 'tool/call') {
1318
1684
  /*
1319
1685
  * [1.6.0] 只登记,不下结论。
1320
1686
  *
@@ -1328,7 +1694,9 @@ export function reconstructFromSession(session, targetPlanId) {
1328
1694
  if (data?.name === 'dsh_workplan_update' && typeof data.callId === 'string') {
1329
1695
  const args = readToolArguments(data.arguments);
1330
1696
  if (args && typeof args.subtaskId === 'string' && typeof args.status === 'string') {
1331
- pendingToolCalls.set(data.callId, { args, planId: plan.planId });
1697
+ const planId = typeof args.planId === 'string' ? args.planId : currentId;
1698
+ if (planId)
1699
+ pendingToolCalls.set(data.callId, { args, planId, callSeq: Number(event.seq ?? 0) });
1332
1700
  }
1333
1701
  }
1334
1702
  }
@@ -1339,7 +1707,8 @@ export function reconstructFromSession(session, targetPlanId) {
1339
1707
  continue;
1340
1708
  const pending = pendingToolCalls.get(callId);
1341
1709
  pendingToolCalls.delete(callId);
1342
- if (!pending || !plan || pending.planId !== plan.planId) {
1710
+ const snap = pending && typeof pending.planId === 'string' ? snapshots.get(pending.planId) : null;
1711
+ if (!snap) {
1343
1712
  // 结果晚于新计划到达:旧计划的写入不污染新计划的状态表。
1344
1713
  }
1345
1714
  else if (message.isError === true) {
@@ -1347,22 +1716,46 @@ export function reconstructFromSession(session, targetPlanId) {
1347
1716
  }
1348
1717
  else {
1349
1718
  const args = pending.args;
1350
- try {
1351
- statuses = applyStatus(statuses, args.subtaskId, {
1352
- status: args.status,
1353
- progress: typeof args.progress === 'number' ? args.progress : undefined,
1354
- summary: typeof args.note === 'string' ? args.note : undefined,
1355
- });
1356
- }
1357
- catch {
1358
- // An invalid historical call is ignored; the live cache remains authoritative.
1719
+ /*
1720
+ * [1.8.11] 同一次改判已经由 durable 消息应用过时,配对结果不再写第二遍。
1721
+ * 判据是 seq 与状态都一致:durable 消息在本次调用之后到达且状态相同,
1722
+ * 才说明它是这次调用的记录;更早/更晚的人工改判仍按自己的顺序生效。
1723
+ */
1724
+ const applied = appliedUpdates.get(updateKey(pending.planId, args.subtaskId));
1725
+ const alreadyDurable = Boolean(applied)
1726
+ && applied.seq > Number(pending.callSeq ?? 0)
1727
+ && applied.status === String(args.status ?? '');
1728
+ if (!alreadyDurable) {
1729
+ try {
1730
+ snap.statuses = applyStatus(snap.statuses, args.subtaskId, {
1731
+ status: args.status,
1732
+ progress: typeof args.progress === 'number' ? args.progress : undefined,
1733
+ summary: typeof args.note === 'string' ? args.note : undefined,
1734
+ // [1.8.13] A tool/result fallback carries the same evidence fields.
1735
+ verification: args.verification,
1736
+ acceptance: args.acceptance,
1737
+ artifacts: args.artifacts,
1738
+ missingArtifacts: args.missingArtifacts,
1739
+ });
1740
+ }
1741
+ catch {
1742
+ // An invalid historical call is ignored; the live cache remains authoritative.
1743
+ }
1359
1744
  }
1360
1745
  }
1361
1746
  }
1362
1747
  }
1363
- if (!plan && !degraded)
1364
- return null;
1365
- if (degraded) {
1748
+ /*
1749
+ * [1.8.15] Prefer the explicitly named plan, then the plan that owns the
1750
+ * newest activity, then the last definition seen in the replay window.
1751
+ */
1752
+ const chosenId = targetPlanId ?? defaultPlanId ?? currentId;
1753
+ let chosen = chosenId ? snapshots.get(chosenId) ?? null : null;
1754
+ if (!chosen && currentId)
1755
+ chosen = snapshots.get(currentId) ?? null;
1756
+ if (!chosen) {
1757
+ if (!degraded)
1758
+ return null;
1366
1759
  return {
1367
1760
  plan: null,
1368
1761
  planId: degraded.planId ?? null,
@@ -1376,14 +1769,12 @@ export function reconstructFromSession(session, targetPlanId) {
1376
1769
  createdTurn: degraded.createdTurn ?? null,
1377
1770
  };
1378
1771
  }
1379
- if (!plan)
1380
- return null;
1381
- if (targetPlanId && plan.planId !== targetPlanId) {
1382
- const hit = finished.find((item) => item.plan?.planId === targetPlanId);
1383
- if (!hit)
1384
- return null;
1385
- ({ plan, statuses, resultPhase, resultSeen, resumeCount, cancelled } = hit);
1386
- }
1772
+ const plan = chosen.plan;
1773
+ const statuses = chosen.statuses;
1774
+ const resultPhase = chosen.resultPhase;
1775
+ const resultSeen = chosen.resultSeen;
1776
+ const resumeCount = chosen.resumeCount;
1777
+ const cancelled = chosen.cancelled;
1387
1778
  let phase = planPhase(statuses, resultSeen);
1388
1779
  if (resultPhase === 'paused' && statuses.some((item) => item.status !== 'done'))
1389
1780
  phase = 'paused';
@@ -1418,9 +1809,24 @@ export function reconstructFromSession(session, targetPlanId) {
1418
1809
  updatedAt: Date.now(),
1419
1810
  createdTurn: plan.createdTurn,
1420
1811
  resumeCount,
1812
+ /*
1813
+ * [1.8.17] A reconstructed record must carry every field the live dispatch
1814
+ * path spreads/pushes unconditionally. `errors` was the one that was
1815
+ * missing; its absence turned a recoverable child failure into a round
1816
+ * abort that marked the rest of the plan blocked.
1817
+ */
1818
+ errors: (chosen.errors ?? []).slice(-20),
1421
1819
  resumeLimit: MAX_PLAN_RESUMES,
1422
1820
  resumeAvailable: canResumePlan({ phase, statuses, resumeCount }, MAX_PLAN_RESUMES).resume,
1423
1821
  stale: stalePending,
1822
+ /*
1823
+ * [1.8.14] Two facts, one from the log: whether the plan is cancelled and
1824
+ * whether that cancellation is durably recorded. For replay they are the
1825
+ * same; the live `cancelPlan` uses `cancelRecorded` to make a second
1826
+ * cancel a no-op instead of appending a duplicate message (N8).
1827
+ */
1828
+ cancelled,
1829
+ cancelRecorded: cancelled,
1424
1830
  };
1425
1831
  }
1426
1832
  function liveSessions(ctx) {
@@ -1494,11 +1900,48 @@ function respondJson(res, status, payload) {
1494
1900
  res.end(body);
1495
1901
  }
1496
1902
  export function createWorkplanRuntime(ctx, options = {}) {
1497
- const state = { records: new Map() };
1903
+ /*
1904
+ * `activeTurns` maps a root session to the turn whose user message carried a
1905
+ * real task; the `agent/turn-stopping` gate only objects on those turns.
1906
+ */
1907
+ const state = { records: new Map(), activeTurns: new Map() };
1498
1908
  /*
1499
1909
  * Resolve the tunables once, at construction, so every code path (dispatch,
1500
1910
  * resume, cancel, the host's tool timeout) agrees on the same numbers.
1501
1911
  */
1912
+ const pluginVersion = typeof options.version === 'string' && options.version ? options.version : 'unknown';
1913
+ /*
1914
+ * [1.8.14] Build identity, captured once.
1915
+ *
1916
+ * `startedAt` is derived from `process.uptime()` so it is the real process
1917
+ * start, not the plugin's construction time; `uptimeMs` is computed live.
1918
+ * Tests construct the runtime without a `build` option, so every field is
1919
+ * optional and the answer degrades to `unknown` instead of failing.
1920
+ */
1921
+ const buildInfo = {
1922
+ pid: Number.isInteger(options.build?.pid) && Number(options.build?.pid) > 0
1923
+ ? Number(options.build.pid)
1924
+ : process.pid,
1925
+ startedAt: Number.isFinite(Number(options.build?.startedAt)) && Number(options.build?.startedAt) > 0
1926
+ ? Number(options.build.startedAt)
1927
+ : Math.round(Date.now() - process.uptime() * 1000),
1928
+ entryPath: typeof options.build?.entryPath === 'string' && options.build.entryPath
1929
+ ? options.build.entryPath
1930
+ : '',
1931
+ buildHash: typeof options.build?.buildHash === 'string' && options.build.buildHash
1932
+ ? options.build.buildHash
1933
+ : 'unknown',
1934
+ };
1935
+ function runtimeIdentity() {
1936
+ return {
1937
+ version: pluginVersion,
1938
+ pid: buildInfo.pid,
1939
+ startedAt: buildInfo.startedAt,
1940
+ uptimeMs: Math.max(0, Date.now() - buildInfo.startedAt),
1941
+ entryPath: buildInfo.entryPath,
1942
+ buildHash: buildInfo.buildHash,
1943
+ };
1944
+ }
1502
1945
  const limits = {
1503
1946
  childTimeoutMs: normaliseChildTimeout(options.childTimeoutMs),
1504
1947
  idleTimeoutMs: normaliseIdleTimeout(options.idleTimeoutMs),
@@ -1556,18 +1999,44 @@ export function createWorkplanRuntime(ctx, options = {}) {
1556
1999
  }
1557
2000
  }
1558
2001
  }
2002
+ /**
2003
+ * Point an edit or a cancellation at the plan the caller actually named.
2004
+ *
2005
+ * dispatch has always rebuilt an older plan out of the session log
2006
+ * (`needsRebuild` + `reconstructFromSession(session, requestedPlanId)`), but
2007
+ * update and cancel compared the id and threw PLAN_ID_MISMATCH — so the one
2008
+ * repair path for "the child wrote its artifact and was then interrupted"
2009
+ * (re-adjudicating that step) was closed on exactly the plans that needed it.
2010
+ * Align the three tools: a named plan that exists in the session log becomes
2011
+ * the target record. While a *different* plan is dispatching, refuse with a
2012
+ * reason instead of silently swapping the running record out from under it.
2013
+ */
2014
+ function adoptRequestedPlan(session, current, requestedPlanId) {
2015
+ if (!current?.plan || !requestedPlanId || current.plan.planId === requestedPlanId)
2016
+ return current;
2017
+ if (current.dispatchPromise) {
2018
+ throw new PlanError(`计划 ${requestedPlanId} 不是当前记录:${current.plan.planId} 正在执行,先等它结束或先取消它`, 'PLAN_ID_MISMATCH');
2019
+ }
2020
+ const rebuilt = reconstructFromSession(session, requestedPlanId);
2021
+ if (!rebuilt?.plan || rebuilt.plan.planId !== requestedPlanId) {
2022
+ throw new PlanError(`planId 与当前计划不匹配(当前 ${current.plan.planId},会话日志里也没有 ${requestedPlanId})`, 'PLAN_ID_MISMATCH');
2023
+ }
2024
+ rebuilt.resumeLimit = current.resumeLimit ?? rebuilt.resumeLimit;
2025
+ state.records.set(session.id, rebuilt);
2026
+ return rebuilt;
2027
+ }
1559
2028
  async function updateStatus(agent, args) {
1560
2029
  const session = agent?.session;
1561
2030
  if (!session)
1562
2031
  throw new PlanError('只能在会话内更新计划', 'NO_SESSION');
1563
2032
  if (!isRootSession(session))
1564
2033
  throw new PlanError('子 Agent 不能更新主计划', 'NOT_ROOT');
1565
- const record = state.records.get(session.id);
2034
+ let record = state.records.get(session.id);
2035
+ if (!record?.plan)
2036
+ record = reconstructFromSession(session, args?.planId);
2037
+ record = adoptRequestedPlan(session, record, args?.planId);
1566
2038
  if (!record?.plan)
1567
2039
  throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN');
1568
- if (args?.planId && record.plan.planId !== args.planId) {
1569
- throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH');
1570
- }
1571
2040
  const subtaskId = typeof args?.subtaskId === 'string' ? args.subtaskId : '';
1572
2041
  if (!subtaskId)
1573
2042
  throw new PlanError('缺少 subtaskId', 'MISSING_SUBTASK');
@@ -1622,11 +2091,31 @@ export function createWorkplanRuntime(ctx, options = {}) {
1622
2091
  };
1623
2092
  }
1624
2093
  const revision = Number(current?.revision ?? 0) + 1;
2094
+ /*
2095
+ * [1.8.13] A manual verdict can carry structured evidence.
2096
+ *
2097
+ * The tool used to accept only `status/progress/note/evidence`, so the
2098
+ * documented escape from the present gate ("先用 dsh_workplan_update 复核
2099
+ * 并补证据") did not exist: a done row stayed `verification: undefined`
2100
+ * and could never become deliverable. These four fields are now accepted,
2101
+ * sanitised by `applyStatus`, persisted in the durable update message and
2102
+ * replayed. Omitted fields keep their previous values.
2103
+ */
2104
+ const evidencePatch = {};
2105
+ if (args?.verification !== undefined)
2106
+ evidencePatch.verification = args.verification;
2107
+ if (args?.acceptance !== undefined)
2108
+ evidencePatch.acceptance = args.acceptance;
2109
+ if (args?.artifacts !== undefined)
2110
+ evidencePatch.artifacts = args.artifacts;
2111
+ if (args?.missingArtifacts !== undefined)
2112
+ evidencePatch.missingArtifacts = args.missingArtifacts;
1625
2113
  record.statuses = applyStatus(record.statuses, subtaskId, {
1626
2114
  status,
1627
2115
  progress: typeof args?.progress === 'number' ? args.progress : undefined,
1628
2116
  summary: summary || undefined,
1629
2117
  error: status === 'blocked' ? (summary || '由主 Agent 标记为受阻') : undefined,
2118
+ ...evidencePatch,
1630
2119
  revision,
1631
2120
  updatedBy: 'agent',
1632
2121
  });
@@ -1641,6 +2130,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
1641
2130
  * result. Appending one small message keeps the replay path honest.
1642
2131
  */
1643
2132
  try {
2133
+ const writtenRow = record.statuses.find((item) => item.subtaskId === subtaskId);
1644
2134
  session.append('user/message', buildUpdateMessage({
1645
2135
  planId: record.plan.planId,
1646
2136
  subtaskId,
@@ -1648,6 +2138,10 @@ export function createWorkplanRuntime(ctx, options = {}) {
1648
2138
  progress: typeof args?.progress === 'number' ? args.progress : undefined,
1649
2139
  note: summary || undefined,
1650
2140
  revision,
2141
+ verification: writtenRow?.verification,
2142
+ acceptance: writtenRow?.acceptance,
2143
+ artifacts: writtenRow?.artifacts,
2144
+ missingArtifacts: writtenRow?.missingArtifacts,
1651
2145
  }), { surfaceOp: 'append' });
1652
2146
  }
1653
2147
  catch (error) {
@@ -1666,6 +2160,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
1666
2160
  record.updatedAt = Date.now();
1667
2161
  const snapshot = derivePlanSnapshot(record.statuses);
1668
2162
  const written = snapshot.statuses.find((item) => item.subtaskId === subtaskId);
2163
+ const readiness = deliveryReadiness(snapshot, { phase: record.phase });
1669
2164
  return {
1670
2165
  ok: true,
1671
2166
  planId: record.plan.planId,
@@ -1674,6 +2169,16 @@ export function createWorkplanRuntime(ctx, options = {}) {
1674
2169
  revision: written?.revision ?? revision,
1675
2170
  updatedBy: written?.updatedBy ?? 'agent',
1676
2171
  stats: snapshot.stats,
2172
+ deliveryReady: readiness.ready,
2173
+ deliveryBlockers: readiness.blockers.slice(0, 12),
2174
+ deliveryRemaining: readiness.remaining.slice(0, 20),
2175
+ ...(readiness.ready
2176
+ ? { hint: '计划已全部 done 且证据通过,可以交付。' }
2177
+ : {
2178
+ hint: written?.status === 'done'
2179
+ ? '该子任务已是 done,但计划尚未通过交付就绪检查;若这项仍有证据缺口,请用 verification/acceptance 补齐或改回 blocked。'
2180
+ : '计划尚未通过交付就绪检查;继续推进剩余项,不要调用 present。',
2181
+ }),
1677
2182
  };
1678
2183
  }
1679
2184
  async function cancelPlan(agent, args) {
@@ -1684,12 +2189,10 @@ export function createWorkplanRuntime(ctx, options = {}) {
1684
2189
  throw new PlanError('子 Agent 不能取消主计划', 'NOT_ROOT');
1685
2190
  let record = state.records.get(session.id);
1686
2191
  if (!record?.plan)
1687
- record = reconstructFromSession(session);
2192
+ record = reconstructFromSession(session, args?.planId);
2193
+ record = adoptRequestedPlan(session, record, args?.planId);
1688
2194
  if (!record?.plan)
1689
2195
  throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN');
1690
- if (args?.planId && record.plan.planId !== args.planId) {
1691
- throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH');
1692
- }
1693
2196
  const reason = typeof args?.reason === 'string' && args.reason.trim()
1694
2197
  ? args.reason.trim()
1695
2198
  : '用户取消';
@@ -1716,6 +2219,56 @@ export function createWorkplanRuntime(ctx, options = {}) {
1716
2219
  stats: before.stats,
1717
2220
  };
1718
2221
  }
2222
+ /*
2223
+ * [1.8.14] N8: a second cancel used to append a second cancel message.
2224
+ *
2225
+ * Cancelling is idempotent by definition: once the cancellation is durably
2226
+ * recorded, repeating it must not grow the log — every duplicate is
2227
+ * replayed and shows up as another "取消" line in the transcript, which is
2228
+ * exactly the kind of "did it happen twice?" noise this incident was made
2229
+ * of.
2230
+ *
2231
+ * [1.8.15] The abort path was the exception that still duplicated: while
2232
+ * `dispatchPromise` was in flight the guard fell through every time, so two
2233
+ * cancels during one dispatch appended two messages (T4e F2). Once the
2234
+ * abort has been requested there is nothing left to stop, so the presence
2235
+ * of an in-flight promise is no longer a reason to append again.
2236
+ */
2237
+ if (record.phase === 'cancelled' && record.cancelRecorded === true
2238
+ && (!record.dispatchPromise || record.abortRequested === true)) {
2239
+ state.records.set(session.id, record);
2240
+ return {
2241
+ ok: true,
2242
+ planId: record.plan.planId,
2243
+ phase: 'cancelled',
2244
+ reason: typeof record.cancelReason === 'string' && record.cancelReason ? record.cancelReason : reason,
2245
+ alreadyCancelled: true,
2246
+ abortedRunning: false,
2247
+ cancelRecorded: true,
2248
+ stats: before.stats,
2249
+ };
2250
+ }
2251
+ const cancelMessage = buildCancelMessage(record.plan.planId, reason);
2252
+ /*
2253
+ * [1.8.14] N12: the durable cancel used to be the only append without a
2254
+ * try/catch. A failing append threw out of the tool after the in-memory
2255
+ * phase had already flipped to `cancelled`, leaving the UI saying
2256
+ * "已取消" while the log said nothing — the next restart silently undid it.
2257
+ * Record the failure and report `cancelRecorded: false` instead.
2258
+ */
2259
+ const appendCancelRecord = () => {
2260
+ try {
2261
+ session.append('user/message', cancelMessage, { surfaceOp: 'append' });
2262
+ record.cancelRecorded = true;
2263
+ record.cancelReason = reason;
2264
+ return true;
2265
+ }
2266
+ catch (error) {
2267
+ record.cancelRecorded = false;
2268
+ pushRecordError(record, `写入取消消息失败:${error instanceof Error ? error.message : String(error)}`);
2269
+ return false;
2270
+ }
2271
+ };
1719
2272
  if (record.dispatchPromise) {
1720
2273
  /*
1721
2274
  * Cancel must always work.
@@ -1731,32 +2284,47 @@ export function createWorkplanRuntime(ctx, options = {}) {
1731
2284
  record.updatedAt = Date.now();
1732
2285
  let aborted = false;
1733
2286
  try {
2287
+ /*
2288
+ * [1.8.15] Mark the abort before asking for it. The idempotency guard
2289
+ * above keys on this flag, so a second cancel that arrives while the
2290
+ * dispatch promise is still settling cannot append a second message.
2291
+ */
2292
+ record.abortRequested = true;
1734
2293
  record.abortDispatch?.(reason);
1735
2294
  aborted = true;
1736
2295
  }
1737
2296
  catch (error) {
1738
2297
  record.errors = [...(record.errors ?? []), `取消时中止执行失败:${String(error?.message ?? error)}`].slice(-20);
1739
2298
  }
2299
+ /*
2300
+ * [1.8.14] The abort path now writes the cancel durably too. 1.8.13
2301
+ * returned here without touching the log, so a later failed result write
2302
+ * left no trace of the cancellation at all and a restart reopened the
2303
+ * plan as "executing".
2304
+ */
2305
+ const recorded = appendCancelRecord();
2306
+ state.records.set(session.id, record);
1740
2307
  return {
1741
2308
  ok: true,
1742
2309
  planId: record.plan.planId,
1743
2310
  phase: 'cancelled',
1744
2311
  reason,
1745
2312
  abortedRunning: aborted,
2313
+ cancelRecorded: recorded,
1746
2314
  stats: derivePlanSnapshot(record.statuses).stats,
1747
2315
  };
1748
2316
  }
1749
2317
  record.phase = 'cancelled';
1750
2318
  record.error = `计划已取消:${reason}`;
1751
2319
  record.updatedAt = Date.now();
1752
- const message = buildCancelMessage(record.plan.planId, reason);
1753
- session.append('user/message', message, { surfaceOp: 'append' });
2320
+ const recorded = appendCancelRecord();
1754
2321
  state.records.set(session.id, record);
1755
2322
  return {
1756
2323
  ok: true,
1757
2324
  planId: record.plan.planId,
1758
2325
  phase: 'cancelled',
1759
2326
  reason,
2327
+ cancelRecorded: recorded,
1760
2328
  stats: derivePlanSnapshot(record.statuses).stats,
1761
2329
  };
1762
2330
  }
@@ -1776,6 +2344,12 @@ export function createWorkplanRuntime(ctx, options = {}) {
1776
2344
  }
1777
2345
  catch (error) {
1778
2346
  ctx.logger?.warn?.(`dsh-workplan: 写入结果消息失败:${error instanceof Error ? error.message : String(error)}`);
2347
+ /*
2348
+ * [1.8.14] N13: a failed result write is a real, user-visible failure —
2349
+ * the round summary is absent from the transcript and a restart can
2350
+ * disagree with the live phase. Log it durably, not only in the host log.
2351
+ */
2352
+ pushRecordError(record, `写入结果消息失败:${error instanceof Error ? error.message : String(error)}`);
1779
2353
  }
1780
2354
  }
1781
2355
  /*
@@ -1788,12 +2362,45 @@ export function createWorkplanRuntime(ctx, options = {}) {
1788
2362
  record.phase = reconcilePhase(record.phase, record.statuses);
1789
2363
  return record;
1790
2364
  }
2365
+ /*
2366
+ * [1.8.7] `ok` alone was read as "the plan is finished".
2367
+ *
2368
+ * The incident's tool result said `ok: true` while 3 of 13 subtasks had never
2369
+ * run; the rendered line added "已加入进行中的派发并等到结果", so the model
2370
+ * had no field telling it the round ended early. `complete`/`remaining` make
2371
+ * that state machine-readable instead of a sentence to interpret.
2372
+ */
2373
+ function completionFields(snapshot, phase) {
2374
+ const stats = snapshot?.stats ?? {};
2375
+ const total = Number(stats.total ?? 0);
2376
+ const done = Number(stats.done ?? 0);
2377
+ /*
2378
+ * [1.8.13] `complete` and `deliveryReady` are different facts.
2379
+ *
2380
+ * `complete` keeps its old meaning (every subtask done) so existing callers
2381
+ * do not break, but a dispatch answer that only said `complete:true` was
2382
+ * read as "finished" even when every row was legacy/empty-evidence. The
2383
+ * model now also sees whether the plan passed the delivery gate, plus the
2384
+ * exact gaps.
2385
+ */
2386
+ const readiness = deliveryReadiness(snapshot, { phase });
2387
+ return {
2388
+ complete: total > 0 && done >= total,
2389
+ remaining: Math.max(0, total - done),
2390
+ deliveryReady: readiness.ready,
2391
+ deliveryBlockers: readiness.blockers.slice(0, 12),
2392
+ deliveryRemaining: readiness.remaining.slice(0, 20),
2393
+ };
2394
+ }
1791
2395
  function dispatchSnapshotOf(record, extra = {}) {
1792
2396
  const snapshot = derivePlanSnapshot(record.statuses);
1793
2397
  return {
1794
2398
  ok: true,
2399
+ version: pluginVersion,
2400
+ runtime: runtimeIdentity(),
1795
2401
  planId: record.plan.planId,
1796
2402
  alreadyRunning: false,
2403
+ ...completionFields(snapshot, record.phase),
1797
2404
  ...extra,
1798
2405
  phase: record.phase,
1799
2406
  stats: snapshot.stats,
@@ -1820,18 +2427,30 @@ export function createWorkplanRuntime(ctx, options = {}) {
1820
2427
  record = rebuilt;
1821
2428
  }
1822
2429
  if (!record?.plan) {
2430
+ /*
2431
+ * [1.8.14] N1/§14.6 step 2: the identity of the loaded build must be
2432
+ * answerable even before a plan exists. 1.8.13 returned NO_PLAN with no
2433
+ * version here, so the documented restart check ("call status, confirm
2434
+ * the version") failed on a fresh session — the check itself was wrong,
2435
+ * not just the docs.
2436
+ */
1823
2437
  return {
1824
2438
  ok: false,
1825
2439
  code: 'NO_PLAN',
1826
2440
  running: false,
2441
+ version: pluginVersion,
2442
+ runtime: runtimeIdentity(),
1827
2443
  error: '当前会话没有可查看的计划',
1828
2444
  hint: '先让本轮生成计划并调用 dsh_workplan_dispatch。',
1829
2445
  };
1830
2446
  }
1831
2447
  const running = Boolean(record.dispatchPromise);
1832
2448
  const snapshot = derivePlanSnapshot(record.statuses);
2449
+ const readiness = deliveryReadiness(snapshot, { phase: record.phase });
1833
2450
  return {
1834
2451
  ok: true,
2452
+ version: pluginVersion,
2453
+ runtime: runtimeIdentity(),
1835
2454
  planId: record.plan.planId,
1836
2455
  running,
1837
2456
  phase: record.phase,
@@ -1840,9 +2459,16 @@ export function createWorkplanRuntime(ctx, options = {}) {
1840
2459
  statuses: modelStatusLines(snapshot.statuses),
1841
2460
  errors: (record.errors ?? []).slice(-10),
1842
2461
  resumeLimit: Number(record.resumeLimit ?? limits.maxResumes),
2462
+ deliveryReady: readiness.ready,
2463
+ deliveryBlockers: readiness.blockers.slice(0, 12),
2464
+ deliveryRemaining: readiness.remaining.slice(0, 20),
1843
2465
  ...(running
1844
2466
  ? { hint: '计划仍在执行:先向用户报告进度,不要声称完成;等结果消息出现后再逐项核对证据。' }
1845
- : { hint: '当前没有正在执行的派发。若仍有 pending/blocked,可再次调用 dsh_workplan_dispatch 续跑。' }),
2467
+ : readiness.ready
2468
+ ? { hint: '计划已全部 done 且证据通过,可以交付。' }
2469
+ : readiness.cancelled
2470
+ ? { hint: '计划已取消且未完成:不要 dispatch 或 present;答复按「未完成:剩余 N 项与原因」开头。' }
2471
+ : { hint: '当前没有正在执行的派发。计划尚未通过交付就绪检查:先 dispatch 续跑剩余项;若只剩已 done 项的证据缺口,用 dsh_workplan_update 补 verification/acceptance。不要调用 present。' }),
1846
2472
  };
1847
2473
  }
1848
2474
  async function dispatchTool(agent, args, signal) {
@@ -1889,6 +2515,31 @@ export function createWorkplanRuntime(ctx, options = {}) {
1889
2515
  if (args?.planId && record.plan.planId !== args.planId) {
1890
2516
  throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH');
1891
2517
  }
2518
+ /*
2519
+ * [1.8.15] Cancelled is terminal: dispatch must refuse, not resurrect.
2520
+ *
2521
+ * T4e F1/C16 proved the old path answered `ok: true` and really started
2522
+ * department Agents on a cancelled plan (`activationCalled: true`), and a
2523
+ * 2/2-done cancelled plan was silently rewritten to `phase: done`. Cancel
2524
+ * is the user's stop signal; the only honest answer is a refusal that says
2525
+ * how to continue deliberately (a new plan, or the main Agent takes over).
2526
+ */
2527
+ if (record.phase === 'cancelled' || record.cancelled === true) {
2528
+ const snapshot = derivePlanSnapshot(record.statuses);
2529
+ return {
2530
+ ok: false,
2531
+ planId: record.plan.planId,
2532
+ phase: 'cancelled',
2533
+ running: false,
2534
+ alreadyRunning: false,
2535
+ complete: false,
2536
+ remaining: Math.max(0, Number(snapshot.stats.total ?? 0) - Number(snapshot.stats.done ?? 0)),
2537
+ stats: snapshot.stats,
2538
+ code: 'PLAN_CANCELLED',
2539
+ error: '计划已取消:取消只停止执行,不会再启动任何部门 Agent',
2540
+ hint: '不要再次派发。如需继续这项工作,请向用户确认后重新生成计划;或由主 Agent 直接接手剩余项,并在答复中说明这是直接执行而非派发。',
2541
+ };
2542
+ }
1892
2543
  /*
1893
2544
  * [1.7.0] Two dispatch modes.
1894
2545
  *
@@ -2049,6 +2700,8 @@ export function createWorkplanRuntime(ctx, options = {}) {
2049
2700
  mode: 'async',
2050
2701
  running: true,
2051
2702
  alreadyRunning: false,
2703
+ complete: false,
2704
+ remaining: Math.max(0, Number(live.stats.total ?? 0) - Number(live.stats.done ?? 0)),
2052
2705
  phase: record.phase,
2053
2706
  startedAt,
2054
2707
  stats: live.stats,
@@ -2066,8 +2719,652 @@ export function createWorkplanRuntime(ctx, options = {}) {
2066
2719
  */
2067
2720
  return dispatchSnapshotOf(record);
2068
2721
  }
2722
+ /*
2723
+ * [1.8.7] 回合收尾前的强制闸门——「未完成即输出」的根治点。
2724
+ *
2725
+ * 事故(session-99984ebd…,2026-10-31)里,模型在计划 10/13 时 present 了
2726
+ * 报告并给出收尾答复。插件原来只订阅 `agent/pre-step`,回合结束完全不受
2727
+ * 约束;预算暂停只写了一句「可续跑」,没有任何强制力。
2728
+ *
2729
+ * 官方 harness 为此提供了确切扩展点 `agent/turn-stopping`(@deepseek-ai/dsh-agent
2730
+ * 的 runtime-types 原文:「Awaited before the boundary commits — a listener
2731
+ * that objects steers (agent.steer(...)) and the machine re-reads its inbox:
2732
+ * fresh steering runs another step, none closes the turn.」)。同仓的
2733
+ * dsh-workspace-changes 就注册在插件根 ctx 上,证明该 agent 作用域事件能到
2734
+ * 达根监听器。
2735
+ *
2736
+ * 规则:
2737
+ * - 只看根会话、只看本回合真实任务(state.activeTurns),社交/状态型回合不打扰;
2738
+ * - 降级记录(没有计划)不拦;空计划也不拦(present 仍会拒绝);
2739
+ * - 后台派发仍在跑 ⇒ 先等它结束再判断,绝不让「已结束 ∧ 正在做」复活;
2740
+ * - 计划未通过交付就绪检查(含未完成、证据缺口、已取消但未完成)⇒
2741
+ * `agent.steer()` 一条明确的「禁止收尾」指令,每个回合最多 2 次。
2742
+ *
2743
+ * [1.8.13] 取消不再等于放行。
2744
+ *
2745
+ * 1.8.8 的闸门只问“还有没有 pending/in_progress”,所以全 done 但证据是
2746
+ * legacy/空验收的计划、以及 cancelled 的计划都会安静收尾并声称完成
2747
+ * (T5-B/C/D)。现在闸门与 present 共用 `deliveryReadiness`:凡是能拦住
2748
+ * 交付的缺口,也能拦住“这个回合就这么结束”。取消分支不再要求续跑,
2749
+ * 只要求按未完成口径如实收尾,所以不会空转。
2750
+ */
2751
+ const STOP_STEER_LIMIT = 2;
2752
+ function recordReadiness(record) {
2753
+ const snapshot = derivePlanSnapshot(record.statuses);
2754
+ return deliveryReadiness(snapshot, { phase: record.phase });
2755
+ }
2756
+ function stopGateApplies(record) {
2757
+ if (!record?.plan)
2758
+ return false;
2759
+ if (record.degraded)
2760
+ return false;
2761
+ const readiness = recordReadiness(record);
2762
+ if (Number(readiness.total ?? 0) === 0)
2763
+ return false;
2764
+ return !readiness.ready;
2765
+ }
2766
+ function planChildIds(record) {
2767
+ const ids = new Set();
2768
+ for (const item of record?.statuses ?? []) {
2769
+ if (typeof item?.childId === 'string' && item.childId)
2770
+ ids.add(item.childId);
2771
+ }
2772
+ for (const stage of record?.plan?.stages ?? []) {
2773
+ for (const subtask of stage?.subtasks ?? []) {
2774
+ if (typeof subtask?.childId === 'string' && subtask.childId)
2775
+ ids.add(subtask.childId);
2776
+ }
2777
+ }
2778
+ return ids;
2779
+ }
2780
+ const PLAN_CONTINUATION_KINDS = new Set(['subagent-settled', 'workplan-result', 'workplan-continue']);
2781
+ /**
2782
+ * [1.8.9] 子会话谱系判定。
2783
+ *
2784
+ * `childId` 在预算重置时会被清空(`applyStatus({status:'pending'})` 走
2785
+ * `normaliseStatusEntry` 强制 childId=null),事故里的 T11 因此不在
2786
+ * planChildIds 中,turn 2 又一次绕过闸门。`header.parentSession` 是子会话
2787
+ * 自身的身份,预算与重启都不会改写它,用它旁证“这条结算来自本计划的执行者”。
2788
+ */
2789
+ function isChildSessionOf(senderId, session) {
2790
+ if (!senderId)
2791
+ return false;
2792
+ try {
2793
+ const child = ctx.sessions?.get?.(senderId);
2794
+ const header = child?.header;
2795
+ if (!header)
2796
+ return false;
2797
+ return header.parentSession === session.id;
2798
+ }
2799
+ catch {
2800
+ return false;
2801
+ }
2802
+ }
2803
+ /**
2804
+ * [1.8.11] 用父会话自己的 `subagent/catalog` 事件认亲。
2805
+ *
2806
+ * `subagent-settled` 到达时子会话已经被 dispose(dsh-subagent 的
2807
+ * `finishDisposal` 先 `handle.dispose()` 再 `notifySettlement`),
2808
+ * `ctx.sessions.get(senderId)` 必然拿不到 header,1.8.9 的谱系判定因此
2809
+ * 在真实生命周期下恒为 false。spawn 记录却留在父会话的事件流里,重启、
2810
+ * 回放、预算重置都不会改写它,是唯一持久可靠的父链证据。
2811
+ */
2812
+ const spawnedChildCache = new Map();
2813
+ function spawnedChildIds(session) {
2814
+ const cached = spawnedChildCache.get(session.id);
2815
+ if (cached && cached.at === session.seq)
2816
+ return cached.ids;
2817
+ const ids = new Set();
2818
+ if (typeof session?.eventAt === 'function') {
2819
+ for (let i = 0; i < session.seq; i += 1) {
2820
+ let event;
2821
+ try {
2822
+ event = session.eventAt(i);
2823
+ }
2824
+ catch {
2825
+ continue;
2826
+ }
2827
+ if (event?.type === 'subagent/catalog' && typeof event.data?.childId === 'string') {
2828
+ ids.add(event.data.childId);
2829
+ }
2830
+ }
2831
+ }
2832
+ spawnedChildCache.set(session.id, { at: session.seq, ids });
2833
+ return ids;
2834
+ }
2835
+ /*
2836
+ * [1.8.14] N5:结算回合要判的是「这条结算对应的计划」,不是「最后生成的计划」。
2837
+ *
2838
+ * 重启后内存为空时,收尾闸门原本走默认回放(最后一个 plan 消息):事故会话在
2839
+ * A 未完成时又生成了 B,A 的结果随后到达,闸门于是按 B 判定。结算输入
2840
+ * (workplan-result)自带 planId;显式传 planId 还能触发 1.8.10 的窗口前移,
2841
+ * 旧计划落在 2000 事件窗口外时也能重建。
2842
+ */
2843
+ function planIdFromTurn(session, turn) {
2844
+ if (typeof session?.eventAt !== 'function' || !(turn >= 1))
2845
+ return undefined;
2846
+ let started = -1;
2847
+ for (let i = session.seq - 1; i >= 0; i -= 1) {
2848
+ const event = session.eventAt(i);
2849
+ if (event?.type === 'turn/start' && Number(event.data?.turn) === turn) {
2850
+ started = i;
2851
+ break;
2852
+ }
2853
+ }
2854
+ if (started < 0)
2855
+ return undefined;
2856
+ for (let i = started + 1; i < session.seq; i += 1) {
2857
+ const event = session.eventAt(i);
2858
+ if (!event)
2859
+ continue;
2860
+ if (event.type === 'turn/end' && Number(event.data?.turn) === turn)
2861
+ break;
2862
+ if (event.type !== 'user/message')
2863
+ continue;
2864
+ const data = event.data?.message ?? event.data;
2865
+ if (!data || typeof data !== 'object')
2866
+ continue;
2867
+ /*
2868
+ * planId 不在信封上:结果消息的 planId 在正文标记之间的 JSON 里,
2869
+ * plan 消息的 planId 在 plan 对象里。两者都走已有的解析器,避免
2870
+ * 对消息形状再发明一套假设。
2871
+ */
2872
+ const result = parseResultMessage(data);
2873
+ if (result && typeof result.planId === 'string' && result.planId)
2874
+ return result.planId;
2875
+ const planMessage = parseWorkplanMessage(data);
2876
+ const planId = planMessage?.plan?.planId;
2877
+ if (typeof planId === 'string' && planId)
2878
+ return planId;
2879
+ }
2880
+ return undefined;
2881
+ }
2882
+ /**
2883
+ * [1.8.15] 当前正在进行的回合号;没有打开中的回合时返回 undefined。
2884
+ *
2885
+ * `present` 的闸门需要知道「这一回合在结算哪个计划」。默认回放回答的是
2886
+ * 「最后定义的计划」,在 A 定义、B 后定义、A 的结果在 B 之后到达时会判错
2887
+ * 计划(T3 B5)。这里不新增状态,只从会话尾部回扫 `turn/start`;遇到
2888
+ * `turn/end` 说明当前没有打开中的回合。
2889
+ */
2890
+ function currentTurnOf(session) {
2891
+ if (typeof session?.eventAt !== 'function')
2892
+ return undefined;
2893
+ for (let i = session.seq - 1; i >= 0; i -= 1) {
2894
+ let event;
2895
+ try {
2896
+ event = session.eventAt(i);
2897
+ }
2898
+ catch {
2899
+ return undefined;
2900
+ }
2901
+ if (!event)
2902
+ continue;
2903
+ if (event.type === 'turn/start') {
2904
+ const turn = Number(event.data?.turn);
2905
+ return Number.isFinite(turn) && turn >= 1 ? turn : undefined;
2906
+ }
2907
+ if (event.type === 'turn/end')
2908
+ return undefined;
2909
+ }
2910
+ return undefined;
2911
+ }
2912
+ /**
2913
+ * [1.8.8] 结算/结果唤醒的回合也属于“本回合的任务”。
2914
+ *
2915
+ * 事故 turn 2 由 `subagent-settled` 消息唤醒:它不是 human task,
2916
+ * `humanMessages()` 不认,`maybePlan()` 不会写 `state.activeTurns`,
2917
+ * 收尾闸门因此在 turn 2 直接放行,模型又在 11/13 时收尾。
2918
+ * 这里按会话事件判断“这一回合是否装载了本计划的续跑输入”,
2919
+ * 只认三类来源,且子 Agent 结算必须来自本计划派出过的 child,
2920
+ * 避免无关后台任务把闸门误激活。
2921
+ */
2922
+ function turnCarriesPlanWork(session, turn, record) {
2923
+ if (typeof session?.eventAt !== 'function' || !(turn >= 1))
2924
+ return false;
2925
+ const childIds = planChildIds(record);
2926
+ let started = -1;
2927
+ for (let i = session.seq - 1; i >= 0; i -= 1) {
2928
+ const event = session.eventAt(i);
2929
+ if (event?.type === 'turn/start' && Number(event.data?.turn) === turn) {
2930
+ started = i;
2931
+ break;
2932
+ }
2933
+ }
2934
+ if (started < 0)
2935
+ return false;
2936
+ for (let i = started + 1; i < session.seq; i += 1) {
2937
+ const event = session.eventAt(i);
2938
+ if (!event)
2939
+ continue;
2940
+ if (event.type === 'turn/end' && Number(event.data?.turn) === turn)
2941
+ break;
2942
+ if (event.type !== 'user/message')
2943
+ continue;
2944
+ const message = event.data?.message ?? event.data;
2945
+ const source = message?.source ?? {};
2946
+ const kind = String(source.kind ?? '');
2947
+ if (!PLAN_CONTINUATION_KINDS.has(kind))
2948
+ continue;
2949
+ if (kind === 'subagent-settled') {
2950
+ const sender = String(source.senderSessionId ?? '');
2951
+ /*
2952
+ * 只认“本计划派出过的 child”“本会话的真实子会话”或“父会话 spawn
2953
+ * 记录里出现过的 child”。第三者是 dispose 之后唯一还能取到的证据;
2954
+ * 三者都不命中时,无关后台任务不能把闸门误激活。
2955
+ */
2956
+ if (!childIds.has(sender) && !isChildSessionOf(sender, session) && !spawnedChildIds(session).has(sender))
2957
+ continue;
2958
+ }
2959
+ return true;
2960
+ }
2961
+ return false;
2962
+ }
2963
+ async function onTurnStopping(payload) {
2964
+ try {
2965
+ const agent = payload?.agent;
2966
+ const session = agent?.session;
2967
+ if (!agent || !session || !isRootSession(session))
2968
+ return;
2969
+ if (typeof agent.steer !== 'function')
2970
+ return;
2971
+ const turn = Number(payload?.turn ?? 0);
2972
+ const known = state.records.get(session.id);
2973
+ /*
2974
+ * [1.8.8] 不再只认 human task 标记的 activeTurns:结算唤醒的回合
2975
+ * (subagent-settled / workplan-result / workplan-continue)同样装载
2976
+ * 了本计划的续跑输入,必须受同一道收尾闸门约束。
2977
+ */
2978
+ if (state.activeTurns?.get?.(session.id) !== turn && !turnCarriesPlanWork(session, turn, known))
2979
+ return;
2980
+ if (isPlanModeActive(ctx, session))
2981
+ return;
2982
+ let record = known;
2983
+ if (!record?.plan) {
2984
+ // [1.8.14] N5:优先按本回合结算消息里点名的计划重建,而不是最后生成的计划。
2985
+ record = reconstructFromSession(session, planIdFromTurn(session, turn));
2986
+ if (record?.plan)
2987
+ state.records.set(session.id, record);
2988
+ }
2989
+ if (!stopGateApplies(record))
2990
+ return;
2991
+ if (record.dispatchPromise) {
2992
+ try {
2993
+ await record.dispatchPromise;
2994
+ }
2995
+ catch {
2996
+ /* the failure is already on record.errors; the gate only needs the outcome */
2997
+ }
2998
+ finishRound(record, session);
2999
+ if (!stopGateApplies(record))
3000
+ return;
3001
+ }
3002
+ const book = record.stopSteers && record.stopSteers.turn === turn
3003
+ ? record.stopSteers
3004
+ : { turn, count: 0 };
3005
+ if (book.count >= STOP_STEER_LIMIT)
3006
+ return;
3007
+ book.count += 1;
3008
+ record.stopSteers = book;
3009
+ const snapshot = derivePlanSnapshot(record.statuses);
3010
+ agent.steer(makeUserMessage(buildStopSteerText({
3011
+ planId: record.plan.planId,
3012
+ phase: record.phase,
3013
+ stats: snapshot.stats,
3014
+ statuses: snapshot.statuses,
3015
+ attempt: book.count,
3016
+ }), {
3017
+ kind: 'workplan-continue',
3018
+ form: 'notice',
3019
+ summary: `【计划未就绪】${snapshot.stats.done}/${snapshot.stats.total},本回合被要求按未完成口径收尾或继续`,
3020
+ }));
3021
+ ctx.logger?.warn?.(`dsh-workplan: 计划 ${record.plan.planId} 未通过交付就绪检查(${snapshot.stats.done}/${snapshot.stats.total}),`
3022
+ + `已在回合收尾前要求继续/如实收尾(第 ${book.count} 次)`);
3023
+ }
3024
+ catch (error) {
3025
+ ctx.logger?.warn?.(`dsh-workplan: 回合收尾检查失败:${error instanceof Error ? error.message : String(error)}`);
3026
+ }
3027
+ }
3028
+ /**
3029
+ * [1.8.8] present 的硬闸门:计划未完成时不允许把产物作为成品交付。
3030
+ *
3031
+ * 1.8.7 只把这条规则写进提示词;事故里模型在回合中途直接 present,
3032
+ * 交付卡片先出现、收尾闸门后到,卡片无法撤回。这里在工具执行前拒绝,
3033
+ * 与回合闸门形成前后两道防线。
3034
+ *
3035
+ * [1.8.13] 判据换成与回合闸门同一个 `deliveryReadiness`。
3036
+ *
3037
+ * 1.8.9 只拦三类硬缺口(自检失败/验收失败/产物缺失),而把 legacy、
3038
+ * unverified、空 acceptance、undefined verification 当作“软缺口”放行;
3039
+ * 同时 `planIncomplete` 对 cancelled 直接返回 false,于是“取消 1/3 再
3040
+ * present”也能过(T5-C)。这两条都被本会话的行为探针证实。现在:
3041
+ * - 只有 `deliveryReady === true` 才能 present;
3042
+ * - 取消、降级(有 plan 时)、全 blocked、全 done 但无结构化证据一律拒绝;
3043
+ * - 拒绝文案必须给出可执行的出路(dispatch / update 补证 / 改 blocked),
3044
+ * cancel 不再被写成交付许可。
3045
+ */
3046
+ /**
3047
+ * [1.8.16] 会话里所有「定义过」的计划。
3048
+ *
3049
+ * `reconstructFromSession(session)` 只回答「默认该看哪个计划」,而 `present`
3050
+ * 需要回答「会话里还有没有没交付完的计划」。1.8.15 的活体 E2E 暴露了这个差
3051
+ * 距:wp-6753e19f 停在 13/14,但最后定义的计划已就绪,`present` 仍然交付了
3052
+ * 报告。这里按日志里出现的 planId 逐个重建;数量极少(本会话只有 4 个),
3053
+ * 每个重建各自带回扫窗口,因此旧计划不会因为超过 2000 事件而消失。
3054
+ */
3055
+ function sessionPlanRecords(session) {
3056
+ if (typeof session?.eventAt !== 'function')
3057
+ return [];
3058
+ const ids = new Set();
3059
+ for (let i = 0; i < session.seq; i += 1) {
3060
+ let event;
3061
+ try {
3062
+ event = session.eventAt(i);
3063
+ }
3064
+ catch {
3065
+ continue;
3066
+ }
3067
+ if (!event || event.type !== 'user/message')
3068
+ continue;
3069
+ const planId = parseWorkplanMessage(event.data)?.plan?.planId;
3070
+ if (typeof planId === 'string' && planId)
3071
+ ids.add(planId);
3072
+ }
3073
+ const records = [];
3074
+ for (const planId of ids) {
3075
+ const record = reconstructFromSession(session, planId);
3076
+ if (record?.plan)
3077
+ records.push(record);
3078
+ }
3079
+ return records;
3080
+ }
3081
+ /**
3082
+ * [1.8.18] The last plan that actually defines work, for the restart replay.
3083
+ *
3084
+ * The gate used to fall back only to the live record or the turn's plan. After
3085
+ * a restart both are gone, so a session whose last action was cancelling an
3086
+ * unfinished plan allowed `present` — contradicting the cancel tool's own
3087
+ * contract ("取消后如仍有未完成项或证据缺口,present 仍会被拒绝"). T5 E1/E6
3088
+ * pinned that hole.
3089
+ *
3090
+ * Empty plans are skipped: they are not delivery objects (U6), and accepting
3091
+ * one as "the last plan" would let a builder cancel real work and define an
3092
+ * empty plan as a shield. Older cancelled plans still do not block a newer
3093
+ * plan, so cancelling a stale plan does not deadlock the session.
3094
+ */
3095
+ function lastGateablePlanRecord(session) {
3096
+ if (typeof session?.eventAt !== 'function')
3097
+ return undefined;
3098
+ for (let i = session.seq - 1; i >= 0; i -= 1) {
3099
+ let event;
3100
+ try {
3101
+ event = session.eventAt(i);
3102
+ }
3103
+ catch {
3104
+ continue;
3105
+ }
3106
+ if (!event || event.type !== 'user/message')
3107
+ continue;
3108
+ const plan = parseWorkplanMessage(event.data)?.plan;
3109
+ if (!plan || typeof plan.planId !== 'string' || plan.planId === '')
3110
+ continue;
3111
+ if (definedSubtaskCount(plan) === 0)
3112
+ continue;
3113
+ const record = reconstructFromSession(session, plan.planId);
3114
+ if (record?.plan && definedSubtaskCount(record.plan) > 0)
3115
+ return record;
3116
+ }
3117
+ return undefined;
3118
+ }
3119
+ function presentDenialReason(agent) {
3120
+ const session = agent?.session;
3121
+ if (!session || !isRootSession(session))
3122
+ return undefined;
3123
+ if (isPlanModeActive(ctx, session))
3124
+ return undefined;
3125
+ /*
3126
+ * [1.8.16] Every plan in the session matters, not just the turn's plan.
3127
+ *
3128
+ * 1.8.15 taught this gate to prefer the plan named by the current turn's
3129
+ * messages, but a session can hold several plans at once (the incident
3130
+ * session itself ended with four). A live E2E on 1.8.15 showed the hole:
3131
+ * wp-6753e19f was still 13/14, the last defined plan was ready, and
3132
+ * `present` delivered the report. The gate now asks every plan in the log;
3133
+ * `dsh_workplan_cancel` is the documented escape hatch for a plan that
3134
+ * will not be finished.
3135
+ */
3136
+ const turn = currentTurnOf(session);
3137
+ const turnPlanId = turn ? planIdFromTurn(session, turn) : undefined;
3138
+ const candidates = sessionPlanRecords(session);
3139
+ const live = state.records.get(session.id);
3140
+ if (live?.plan && !candidates.some((item) => item.plan.planId === live.plan.planId))
3141
+ candidates.push(live);
3142
+ if (turnPlanId && !candidates.some((item) => item.plan.planId === turnPlanId)) {
3143
+ const named = reconstructFromSession(session, turnPlanId);
3144
+ if (named?.plan)
3145
+ candidates.push(named);
3146
+ }
3147
+ if (candidates.length === 0)
3148
+ return undefined;
3149
+ /*
3150
+ * [U6] a plan with zero defined subtasks is not a delivery object.
3151
+ * `deliveryReadiness` can never call it ready (`total > 0`), so judging it
3152
+ * only produced the false refusal "0 个子任务虽都已 done". Filter by the
3153
+ * definition itself — not by `statuses.length` — so a real plan whose
3154
+ * statuses failed to derive is still judged (and stays closed).
3155
+ */
3156
+ const gateable = candidates.filter((item) => definedSubtaskCount(item.plan) > 0);
3157
+ if (gateable.length === 0)
3158
+ return undefined;
3159
+ const unresolved = gateable
3160
+ .map((item) => ({
3161
+ record: item,
3162
+ readiness: deliveryReadiness(derivePlanSnapshot(item.statuses), { phase: item.phase }),
3163
+ }))
3164
+ /*
3165
+ * A cancelled plan is not a delivery blocker for *other* plans — the
3166
+ * incident session accumulates cancelled plans that will never be
3167
+ * finished, and blocking on them forever would deadlock delivery. It is
3168
+ * still checked below when it is the plan this turn (or the live record,
3169
+ * or the last defined plan after a restart) is about: cancel stops
3170
+ * execution, it does not make the work deliverable.
3171
+ */
3172
+ .filter((entry) => entry.record.phase !== 'cancelled' && !entry.readiness.ready);
3173
+ if (unresolved.length > 1) {
3174
+ const lines = unresolved.slice(0, 6).map((entry) => {
3175
+ const ids = entry.readiness.remaining.slice(0, 6).join('、');
3176
+ const suffix = ids ? `(${ids}${entry.readiness.remaining.length > 6 ? '…' : ''})` : '';
3177
+ const gaps = entry.readiness.blockers.slice(0, 4).join(';');
3178
+ return `- 计划 ${entry.record.plan.planId}:完成 ${entry.readiness.done}/${entry.readiness.total}${suffix}`
3179
+ + `${gaps ? `;证据缺口:${gaps}` : ''}`;
3180
+ });
3181
+ return `本会话还有 ${unresolved.length} 个计划未通过交付就绪检查:\n${lines.join('\n')}\n`
3182
+ + '在它们全部通过交付就绪检查之前,不得调用 present 交付任何产物:'
3183
+ + '先调用 dsh_workplan_dispatch 续跑,证据缺口用 dsh_workplan_update 补齐。'
3184
+ + '取消只停止执行,不会让未完成的计划变成可交付,也不能用来绕过这道检查。';
3185
+ }
3186
+ let record;
3187
+ let readiness;
3188
+ if (unresolved.length === 1) {
3189
+ record = unresolved[0].record;
3190
+ readiness = unresolved[0].readiness;
3191
+ }
3192
+ else {
3193
+ /*
3194
+ * No unfinished active plan. The plan this turn is about (or the live
3195
+ * record) may still be a cancelled one that never finished — T5-C pins
3196
+ * that `present` must be refused for it. After a restart neither exists,
3197
+ * so fall back to the last plan that defines work; otherwise the
3198
+ * sequence "cancel an unfinished plan, restart, present" silently
3199
+ * bypasses the cancel tool's own contract (T5 E1/E6).
3200
+ */
3201
+ record = state.records.get(session.id);
3202
+ if (turnPlanId)
3203
+ record = reconstructFromSession(session, turnPlanId) ?? record;
3204
+ if (!record?.plan)
3205
+ record = lastGateablePlanRecord(session);
3206
+ if (!record?.plan)
3207
+ return undefined;
3208
+ if (definedSubtaskCount(record.plan) === 0)
3209
+ return undefined;
3210
+ readiness = deliveryReadiness(derivePlanSnapshot(record.statuses), { phase: record.phase });
3211
+ if (readiness.ready)
3212
+ return undefined;
3213
+ }
3214
+ if (record?.plan)
3215
+ state.records.set(session.id, record);
3216
+ const snapshot = derivePlanSnapshot(record.statuses);
3217
+ const planId = record.plan?.planId ?? record.planId;
3218
+ const ids = readiness.remaining.slice(0, 10).join('、');
3219
+ const idSuffix = ids ? `(${ids}${readiness.remaining.length > 10 ? '…' : ''})` : '';
3220
+ const blockers = readiness.blockers.slice(0, 10).join(';');
3221
+ if (readiness.cancelled) {
3222
+ /*
3223
+ * [1.8.13] `deliveryReadiness` already puts the cancellation fact at the
3224
+ * head of `blockers`; repeating it here produced the T6b/C0 copy with the
3225
+ * same sentence twice. Only the *evidence* gaps belong in this suffix.
3226
+ */
3227
+ const gaps = readiness.blockers
3228
+ .filter((line) => !line.startsWith('计划已取消但只完成'))
3229
+ .slice(0, 10)
3230
+ .join(';');
3231
+ if (readiness.remaining.length === 0) {
3232
+ return `计划 ${planId} 已取消,${readiness.total} 个子任务虽已 done,但证据未通过:${gaps || '缺少结构化证据'}。`
3233
+ + '取消只停止执行,不等于完成:不得调用 present,不得声称“已完成/最终版/已交付”;'
3234
+ + '答复必须说明取消状态与证据缺口,不能写成“全部完成”。';
3235
+ }
3236
+ return `计划 ${planId} 已取消,但只完成 ${readiness.done}/${readiness.total},剩余 ${readiness.remaining.length} 项${idSuffix}`
3237
+ + `${gaps ? `;证据缺口:${gaps}` : ''}。`
3238
+ + '取消只停止执行,不等于完成,也不会让未完成项变成可交付:不得调用 present,不得声称“已完成/最终版/已交付”;'
3239
+ + '答复开头必须写「未完成:剩余 N 项(列出 ID)与原因」。';
3240
+ }
3241
+ if (readiness.remaining.length === 0) {
3242
+ return `计划 ${planId} 的 ${readiness.total} 个子任务虽都已 done,但证据未通过:${blockers || '缺少结构化证据'}。`
3243
+ + '在 deliveryReady 变为 true 之前,产物不得作为成品交付:'
3244
+ + "用 dsh_workplan_update 为这些子任务补 verification='structured' 与 acceptance(每项 result='pass' 并附证据),"
3245
+ + '或把对应子任务改回 blocked 并写明原因;不要调用 present。';
3246
+ }
3247
+ return `计划 ${planId} 未完成:完成 ${readiness.done}/${readiness.total},剩余 ${readiness.remaining.length} 项${idSuffix}`
3248
+ + `${blockers ? `;另有证据缺口:${blockers}` : ''}。`
3249
+ + '在计划通过交付就绪检查之前不得调用 present 交付产物:先调用 dsh_workplan_dispatch 续跑剩余项;'
3250
+ + '证据缺口用 dsh_workplan_update 补齐;确实无法继续时,把答复写成「未完成:剩余 N 项与原因」。'
3251
+ + '取消只停止执行,不会改变“未完成”的结论。';
3252
+ }
3253
+ /*
3254
+ * [1.8.18] 已交付文件的写保护(T7-N2)。
3255
+ *
3256
+ * `present` 不复制内容(工具描述原文:the user opens the current files),
3257
+ * write/edit 也不校验路径是否已经交付。事故的迟到回合在 12:13 两次原地改写
3258
+ * 12:04 已 present 的报告,卡片背后的文件因此变了。这里把「present 时点
3259
+ * 已经定义过的计划」记到路径上:只要这些计划至今仍未通过交付就绪检查,
3260
+ * 根会话对同一路径的 write/edit 就被拒绝。present 之后才定义的新计划不在
3261
+ * 集合里,所以“用户要求改版 → 新计划”不会被写保护卡死;cancel 仍是显式出路。
3262
+ */
3263
+ const presentedPaths = new Map();
3264
+ function canonicalPath(session, value) {
3265
+ if (typeof value !== 'string' || value.trim() === '')
3266
+ return undefined;
3267
+ if (isAbsolute(value))
3268
+ return resolve(value);
3269
+ const cwd = session?.header?.cwd ?? options.cwd;
3270
+ return typeof cwd === 'string' && cwd ? resolve(cwd, value) : undefined;
3271
+ }
3272
+ function presentedEntries(session) {
3273
+ if (typeof session?.eventAt !== 'function' || !(Number(session.seq) >= 0))
3274
+ return [];
3275
+ const cache = presentedPaths.get(session.id);
3276
+ const reusable = cache !== undefined && cache.scannedTo <= Number(session.seq);
3277
+ const from = reusable ? cache.scannedTo : 0;
3278
+ const seen = new Set(reusable ? cache.planIds : []);
3279
+ const entries = reusable ? cache.entries.slice() : [];
3280
+ for (let i = from; i < Number(session.seq); i += 1) {
3281
+ let event;
3282
+ try {
3283
+ event = session.eventAt(i);
3284
+ }
3285
+ catch {
3286
+ continue;
3287
+ }
3288
+ if (!event)
3289
+ continue;
3290
+ if (event.type === 'user/message') {
3291
+ const planId = parseWorkplanMessage(event.data)?.plan?.planId;
3292
+ if (typeof planId === 'string' && planId)
3293
+ seen.add(planId);
3294
+ continue;
3295
+ }
3296
+ if (event.type !== 'deliverables/presented')
3297
+ continue;
3298
+ const planIds = [...seen];
3299
+ for (const file of event.data?.files ?? []) {
3300
+ if (typeof file?.path !== 'string' || file.path.trim() === '')
3301
+ continue;
3302
+ entries.push({ raw: file.path, canonical: canonicalPath(session, file.path), planIds });
3303
+ }
3304
+ }
3305
+ presentedPaths.set(session.id, {
3306
+ scannedTo: Number(session.seq),
3307
+ planIds: seen,
3308
+ entries,
3309
+ });
3310
+ return entries;
3311
+ }
3312
+ function recordForPlan(session, planId) {
3313
+ const live = state.records.get(session.id);
3314
+ if (live?.plan?.planId === planId)
3315
+ return live;
3316
+ return reconstructFromSession(session, planId);
3317
+ }
3318
+ function presentedWriteDenialReason(agent, args) {
3319
+ const session = agent?.session;
3320
+ if (!session || !isRootSession(session))
3321
+ return undefined;
3322
+ if (isPlanModeActive(ctx, session))
3323
+ return undefined;
3324
+ const entries = presentedEntries(session);
3325
+ if (entries.length === 0)
3326
+ return undefined;
3327
+ const requested = args?.file_path ?? args?.path;
3328
+ if (typeof requested !== 'string' || requested.trim() === '')
3329
+ return undefined;
3330
+ const canonical = canonicalPath(session, requested);
3331
+ const matched = entries.filter((entry) => entry.raw === requested
3332
+ || (canonical !== undefined && entry.canonical !== undefined && entry.canonical === canonical));
3333
+ if (matched.length === 0)
3334
+ return undefined;
3335
+ const planIds = new Set();
3336
+ for (const entry of matched)
3337
+ for (const planId of entry.planIds)
3338
+ planIds.add(planId);
3339
+ if (planIds.size === 0)
3340
+ return undefined;
3341
+ const unresolved = [...planIds]
3342
+ .map((planId) => recordForPlan(session, planId))
3343
+ .filter((record) => record?.plan
3344
+ && record.phase !== 'cancelled'
3345
+ && !deliveryReadiness(derivePlanSnapshot(record.statuses), { phase: record.phase }).ready);
3346
+ if (unresolved.length === 0)
3347
+ return undefined;
3348
+ const ids = unresolved.slice(0, 4).map((record) => record.plan.planId);
3349
+ return `文件 ${requested} 已通过 present 交付给用户,而交付时点已存在的计划`
3350
+ + `${ids.length ? ` ${ids.join('、')}` : ''} 仍未通过交付就绪检查。`
3351
+ + '计划未就绪期间不得原地改写已交付文件:先调用 dsh_workplan_dispatch 续跑剩余项,'
3352
+ + '完成后重新 present 新版本;确实不做的计划用 dsh_workplan_cancel 显式取消。'
3353
+ + '(present 之后新建的计划不受此限制。)';
3354
+ }
2069
3355
  function plansPayload(sessionId) {
2070
- return buildPlansPayload(ctx, state, sessionId);
3356
+ /*
3357
+ * [1.8.15] The feed must carry build identity too.
3358
+ *
3359
+ * `status` learned version/runtime in 1.8.14, but the Web UI reads this
3360
+ * feed only — so after a rebuild the card could not tell "the process is
3361
+ * still running yesterday's bytes" (T5c §6.2). Same helpers, one source.
3362
+ */
3363
+ return {
3364
+ ...buildPlansPayload(ctx, state, sessionId),
3365
+ version: pluginVersion,
3366
+ runtime: runtimeIdentity(),
3367
+ };
2071
3368
  }
2072
3369
  async function route(req, res, connectionCtx = ctx) {
2073
3370
  applyHardeningHeaders(res);
@@ -2140,6 +3437,9 @@ export function createWorkplanRuntime(ctx, options = {}) {
2140
3437
  state,
2141
3438
  limits,
2142
3439
  onPreStep,
3440
+ onTurnStopping,
3441
+ presentDenialReason,
3442
+ presentedWriteDenialReason,
2143
3443
  updateStatus,
2144
3444
  cancelPlan,
2145
3445
  dispatchTool,
@@ -2201,6 +3501,17 @@ async function maybePlan(ctx, state, payload, downstream, options) {
2201
3501
  return downstream;
2202
3502
  if (isStatusQuestion(taskText))
2203
3503
  return downstream;
3504
+ /*
3505
+ * [1.8.7] Remember that this turn carries a real task.
3506
+ *
3507
+ * `agent/turn-stopping` must only object on turns whose plan belongs to the
3508
+ * user's actual request. A plan left paused in an earlier turn must not turn
3509
+ * every later "谢谢/进度如何" turn into a forced 20-minute dispatch, so the
3510
+ * stop gate reads this marker and stays silent on social or status turns.
3511
+ */
3512
+ if (!state.activeTurns)
3513
+ state.activeTurns = new Map();
3514
+ state.activeTurns.set(session.id, Number(payload.turn ?? 0));
2204
3515
  const conversationContext = recentConversation(session);
2205
3516
  const existing = state.records.get(session.id);
2206
3517
  if (existing?.plan?.createdTurn === payload.turn)
@@ -2378,6 +3689,10 @@ export function updateToolOutputSchema() {
2378
3689
  subtaskId: { type: 'string' },
2379
3690
  status: { type: 'string' },
2380
3691
  stats: { type: 'object' },
3692
+ deliveryReady: { type: 'boolean' },
3693
+ deliveryBlockers: { type: 'array' },
3694
+ deliveryRemaining: { type: 'array' },
3695
+ hint: { type: 'string' },
2381
3696
  },
2382
3697
  required: ['ok'],
2383
3698
  additionalProperties: true,
@@ -2391,6 +3706,14 @@ export function cancelToolOutputSchema() {
2391
3706
  planId: { type: 'string' },
2392
3707
  phase: { type: 'string' },
2393
3708
  reason: { type: 'string' },
3709
+ /*
3710
+ * [1.8.14] `cancelRecorded` is the difference between "the UI says
3711
+ * cancelled" and "a restart will still say cancelled". A cancel whose
3712
+ * durable append failed reports false so the caller does not build on it.
3713
+ */
3714
+ cancelRecorded: { type: 'boolean' },
3715
+ alreadyCancelled: { type: 'boolean' },
3716
+ abortedRunning: { type: 'boolean' },
2394
3717
  },
2395
3718
  required: ['ok'],
2396
3719
  additionalProperties: true,
@@ -2411,6 +3734,13 @@ export function statusToolOutputSchema() {
2411
3734
  statuses: { type: 'array' },
2412
3735
  errors: { type: 'array' },
2413
3736
  resumeLimit: { type: 'number' },
3737
+ version: { type: 'string' },
3738
+ // [1.8.14] Loaded-build identity: version alone cannot prove which bytes
3739
+ // the process is running after a rebuild or a profile recomposition.
3740
+ runtime: { type: 'object' },
3741
+ deliveryReady: { type: 'boolean' },
3742
+ deliveryBlockers: { type: 'array' },
3743
+ deliveryRemaining: { type: 'array' },
2414
3744
  hint: { type: 'string' },
2415
3745
  error: { type: 'string' },
2416
3746
  code: { type: 'string' },
@@ -2430,6 +3760,18 @@ export function dispatchToolOutputSchema() {
2430
3760
  running: { type: 'boolean' },
2431
3761
  joined: { type: 'boolean' },
2432
3762
  mode: { type: 'string' },
3763
+ /*
3764
+ * [1.8.7] `ok:true` used to be the only success signal, so a budget pause
3765
+ * (10/13) read as a finished dispatch. `complete` is the field the model
3766
+ * must test before it presents anything.
3767
+ */
3768
+ complete: { type: 'boolean' },
3769
+ remaining: { type: 'integer' },
3770
+ deliveryReady: { type: 'boolean' },
3771
+ deliveryBlockers: { type: 'array' },
3772
+ deliveryRemaining: { type: 'array' },
3773
+ version: { type: 'string' },
3774
+ runtime: { type: 'object' },
2433
3775
  elapsedMs: { type: 'number' },
2434
3776
  statuses: { type: 'array' },
2435
3777
  phase: { type: 'string' },