dsh-workplan 1.8.4 → 1.9.1
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/CHANGELOG.md +686 -0
- package/README.en.md +1 -1
- package/README.md +1 -1
- package/client.js +18 -2
- package/docs/postmortem-1.8.4-20261030.md +51 -0
- package/docs/postmortem-1.8.7-20261031.md +498 -0
- package/docs/release-notes-1.9.1.md +67 -0
- package/docs/release-record-1.8.4-20261030.md +70 -0
- package/lib/host.js +345 -31
- package/lib/plan.js +494 -17
- package/lib/runtime.js +1819 -124
- package/lib/supersede-digest.js +115 -0
- package/lib/supersede.js +378 -0
- package/package.json +2 -2
- package/src/client.ts +19 -2
- package/src/host.ts +370 -33
- package/src/plan.ts +537 -17
- package/src/runtime.ts +1813 -114
- package/src/supersede-digest.ts +116 -0
- package/src/supersede.ts +429 -0
package/lib/runtime.js
CHANGED
|
@@ -14,8 +14,32 @@
|
|
|
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, isTerminalPhase, isStatusQuestion, isVagueContinuation, makeUserMessage, markDependentsBlocked, messageText, readySubtasks, MAX_PLAN_RESUMES, PRESENT_DENY_CODES, canResumePlan, resetBlockedStatuses, parseCancelMessage, parseResultMessage, parseWorkplanMessage, planPhase, reconcilePhase, truncate, validatePlan, applyResultStatuses, adjudicateResult, activeDenyCode, MAX_CONVERSATION_CHARS, parseUpdateMessage, buildUpdateMessage, } from './plan.js';
|
|
18
|
+
import { computeMappingDigest, verifyMappingDigest } from './supersede-digest.js';
|
|
19
|
+
import { supersedePlanRecord } from './supersede.js';
|
|
18
20
|
import { createProgressWatchdog, describeError } from './watchdog.js';
|
|
21
|
+
/**
|
|
22
|
+
* [1.8.18] How many subtasks the plan *defines*.
|
|
23
|
+
*
|
|
24
|
+
* `deliveryReadiness` counts the derived statuses, and `ready` requires
|
|
25
|
+
* `total > 0`, so a plan with `stages: []` can never be ready. Such a plan is
|
|
26
|
+
* not a delivery object at all: normal planning rejects it (`validatePlan`),
|
|
27
|
+
* and it can only reach replay from a malformed historical message. Judging it
|
|
28
|
+
* as "0/0 unfinished forever" was U6 (T5 P13): present was refused with the
|
|
29
|
+
* false copy "0 个子任务虽都已 done".
|
|
30
|
+
*
|
|
31
|
+
* A malformed plan that reaches this function still counts as deliverable
|
|
32
|
+
* (`MAX_SAFE_INTEGER`); plans failing reconstruction earlier are dropped by
|
|
33
|
+
* `sessionPlanRecords` — a known fail-open boundary (T5 A9), not closed here.
|
|
34
|
+
*/
|
|
35
|
+
function definedSubtaskCount(plan) {
|
|
36
|
+
try {
|
|
37
|
+
return flattenSubtasks(plan).length;
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return Number.MAX_SAFE_INTEGER;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
19
43
|
export const PLANNER_TIMEOUT_MS = 120000;
|
|
20
44
|
/**
|
|
21
45
|
* Absolute ceiling for one child execution.
|
|
@@ -287,7 +311,7 @@ async function disposeActivation(activation, record, subtaskId, guard) {
|
|
|
287
311
|
catch (error) {
|
|
288
312
|
if (!guard?.timedOut) {
|
|
289
313
|
record.errors = [
|
|
290
|
-
...record.errors,
|
|
314
|
+
...(record.errors ?? []),
|
|
291
315
|
`${subtaskId} dispose: ${truncate(String(error?.message ?? error), 300)}`,
|
|
292
316
|
].slice(-20);
|
|
293
317
|
}
|
|
@@ -338,7 +362,7 @@ function writeSubtaskStatus(record, subtaskId, patch, guard) {
|
|
|
338
362
|
function recordSubtaskError(record, subtaskId, message, guard) {
|
|
339
363
|
if (guard.timedOut)
|
|
340
364
|
return;
|
|
341
|
-
record.errors = [...record.errors, `${subtaskId}: ${truncate(message, 500)}`].slice(-20);
|
|
365
|
+
record.errors = [...(record.errors ?? []), `${subtaskId}: ${truncate(message, 500)}`].slice(-20);
|
|
342
366
|
}
|
|
343
367
|
/**
|
|
344
368
|
* Resolve one artifact reference against the round's working directory.
|
|
@@ -383,6 +407,147 @@ export function checkArtifacts(artifacts, cwd, artifactExists = existsSync) {
|
|
|
383
407
|
});
|
|
384
408
|
return { artifacts: checked, missingArtifacts };
|
|
385
409
|
}
|
|
410
|
+
/**
|
|
411
|
+
* [1.8.5] 被中断时,先说清「东西到底写出来没有」。
|
|
412
|
+
*
|
|
413
|
+
* 事故(2026-10-30):一个子 Agent 在 21:34:52 写完了 38KB 交付物,两秒后被
|
|
414
|
+
* 外部中断;插件只留下「结束状态为 aborted」,产物存在与否完全不进判定,主
|
|
415
|
+
* Agent 只能把它当彻底失败,下游 6 个任务跟着停摆。
|
|
416
|
+
*
|
|
417
|
+
* 这里不改变任何判定语义(中断依然记为失败、依然不自动重试),只在报错里
|
|
418
|
+
* 附上一句可核实的事实:该步声明的产物里有哪几个已经在盘上。看到这句话的人
|
|
419
|
+
* 才知道下一步该去核对、改判,而不是白等一次重试。
|
|
420
|
+
*/
|
|
421
|
+
export function probeInterruptedArtifacts(output, subtask, cwd, artifactExists = existsSync) {
|
|
422
|
+
const candidates = new Set();
|
|
423
|
+
const collect = (text) => {
|
|
424
|
+
if (typeof text !== 'string' || !text)
|
|
425
|
+
return;
|
|
426
|
+
// 文件名可能带中文(本次事故就是「T6_人性博弈推演_20261030.md」这种),
|
|
427
|
+
// 所以字符集必须放行 CJK,否则真正的产物会被当成没写。
|
|
428
|
+
for (const hit of text.matchAll(/[\w\u4e00-\u9fff@.\/-]+\.(?:md|csv|json|html|txt|ts|js|py|ya?ml)/g)) {
|
|
429
|
+
const ref = hit[0].replace(/^\.\//, '');
|
|
430
|
+
// 太短的多半是扩展名碎片(如 “.md”),不足以定位文件。
|
|
431
|
+
if (ref.length > 3)
|
|
432
|
+
candidates.add(ref);
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
collect(output);
|
|
436
|
+
for (const item of Array.isArray(subtask?.outputs) ? subtask.outputs : [])
|
|
437
|
+
collect(item);
|
|
438
|
+
const landed = [];
|
|
439
|
+
for (const ref of candidates) {
|
|
440
|
+
const target = resolveArtifactPath(ref, cwd);
|
|
441
|
+
if (!target)
|
|
442
|
+
continue;
|
|
443
|
+
let exists = false;
|
|
444
|
+
try {
|
|
445
|
+
exists = artifactExists(target) === true;
|
|
446
|
+
}
|
|
447
|
+
catch {
|
|
448
|
+
exists = false;
|
|
449
|
+
}
|
|
450
|
+
if (exists)
|
|
451
|
+
landed.push(ref);
|
|
452
|
+
if (landed.length >= 6)
|
|
453
|
+
break;
|
|
454
|
+
}
|
|
455
|
+
return landed;
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* [1.8.6] Turn "the child was interrupted" into evidence the plan can hold.
|
|
459
|
+
*
|
|
460
|
+
* 1.8.5 only put the landed files into the error string. That helped a human
|
|
461
|
+
* read the message, but the plan still recorded `blocked` with no
|
|
462
|
+
* `artifacts` / `missingArtifacts`, so the dispatcher had nothing to check and
|
|
463
|
+
* cascaded every dependent into `blocked`: one interrupted child still killed
|
|
464
|
+
* its whole downstream. This records the same finding in the status fields the
|
|
465
|
+
* scheduler already understands.
|
|
466
|
+
*
|
|
467
|
+
* It deliberately does NOT change the verdict: an interrupted task stays
|
|
468
|
+
* `blocked` (no auto-retry, no auto-adjudication). It only stops the cascade
|
|
469
|
+
* and leaves the main Agent a factual basis to re-adjudicate.
|
|
470
|
+
*/
|
|
471
|
+
export function probeInterruptedEvidence(output, subtask, cwd, artifactExists = existsSync) {
|
|
472
|
+
const landed = probeInterruptedArtifacts(output, subtask, cwd, artifactExists);
|
|
473
|
+
const declared = [];
|
|
474
|
+
for (const item of Array.isArray(subtask?.outputs) ? subtask.outputs : []) {
|
|
475
|
+
for (const hit of String(item).matchAll(/[\w\u4e00-\u9fff@.\/-]+\.(?:md|csv|json|html|txt|ts|js|py|ya?ml)/g)) {
|
|
476
|
+
const ref = hit[0].replace(/^\.\//, '');
|
|
477
|
+
if (ref.length > 3 && !declared.includes(ref))
|
|
478
|
+
declared.push(ref);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
const refs = [...new Set([...declared, ...landed])];
|
|
482
|
+
const artifacts = refs.map((ref) => ({ kind: 'file', ref, exists: landed.includes(ref) }));
|
|
483
|
+
const missingArtifacts = declared.filter((ref) => !landed.includes(ref));
|
|
484
|
+
return { artifacts, missingArtifacts };
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* [1.8.19] Find a subtask definition by id, without assuming the plan is valid.
|
|
488
|
+
*/
|
|
489
|
+
export function findSubtaskById(plan, subtaskId) {
|
|
490
|
+
for (const stage of Array.isArray(plan?.stages) ? plan.stages : []) {
|
|
491
|
+
for (const subtask of Array.isArray(stage?.subtasks) ? stage.subtasks : []) {
|
|
492
|
+
if (subtask?.id === subtaskId)
|
|
493
|
+
return subtask;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
return null;
|
|
497
|
+
}
|
|
498
|
+
/**
|
|
499
|
+
* [1.8.19] A hard per-subtask timeout must not erase what the child already wrote.
|
|
500
|
+
*
|
|
501
|
+
* Real incident (2026-10-31 23:23:38): T11/T12 were aborted by the 900 s
|
|
502
|
+
* per-subtask ceiling four seconds after their deliverables had landed
|
|
503
|
+
* (T11 32,996 B report + 140-row index; T12 51,547 B report). The parent only
|
|
504
|
+
* saw `blocked / 达到执行上限`, with no hint that the files existed, so the same
|
|
505
|
+
* work would be redone from scratch. This probe records the landed declared
|
|
506
|
+
* outputs in the status row and in the error text — it does not change the
|
|
507
|
+
* verdict (a timeout is still `blocked`), it only stops the evidence loss.
|
|
508
|
+
*/
|
|
509
|
+
export function timeoutBlockedPatch(subtask, cwd, message, artifactExists = existsSync) {
|
|
510
|
+
const evidence = probeInterruptedEvidence(null, subtask, cwd, artifactExists);
|
|
511
|
+
const landed = evidence.artifacts.filter((item) => item?.exists === true).map((item) => String(item.ref));
|
|
512
|
+
const artifactNote = landed.length > 0
|
|
513
|
+
? `;该步声明的产物已在盘上:${landed.slice(0, 6).join('、')}(先核对,不要当作从未运行)`
|
|
514
|
+
: '';
|
|
515
|
+
return {
|
|
516
|
+
patch: {
|
|
517
|
+
status: 'blocked',
|
|
518
|
+
progress: 100,
|
|
519
|
+
finishedAt: Date.now(),
|
|
520
|
+
error: message + artifactNote,
|
|
521
|
+
summary: truncate(`未完成:${message}${artifactNote}`, 3000),
|
|
522
|
+
...(evidence.artifacts.length > 0 ? { artifacts: evidence.artifacts } : {}),
|
|
523
|
+
...(evidence.missingArtifacts.length > 0 ? { missingArtifacts: evidence.missingArtifacts } : {}),
|
|
524
|
+
},
|
|
525
|
+
landed,
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* [1.8.19] The round budget reset used to erase every trace of the attempt.
|
|
530
|
+
*
|
|
531
|
+
* The 20-minute `TOTAL_TIMEOUT` branch resets unfinished rows to `pending`, and
|
|
532
|
+
* `applyStatus` (by design) clears `childId / startedAt / finishedAt`. In the
|
|
533
|
+
* 2026-10-31 incident T10 had run for ~19 minutes and had already written its
|
|
534
|
+
* coverage report at 23:06:26 when the budget fired at 23:07:25; the card then
|
|
535
|
+
* said "not started" and the user asked "why did T10 stop by itself". The
|
|
536
|
+
* attempt provenance and any landed declared outputs now travel in the error
|
|
537
|
+
* text, so the reset stays a pause but stops being an erasure.
|
|
538
|
+
*/
|
|
539
|
+
export function budgetResetError(item, subtask, cwd, artifactExists = existsSync) {
|
|
540
|
+
const landed = probeInterruptedArtifacts(null, subtask, cwd, artifactExists);
|
|
541
|
+
const parts = ['本轮预算用尽,等待续跑'];
|
|
542
|
+
if (item?.childId)
|
|
543
|
+
parts.push(`上一轮子会话 ${String(item.childId).slice(0, 8)}`);
|
|
544
|
+
if (Number.isFinite(item?.startedAt) && Number.isFinite(item?.finishedAt)) {
|
|
545
|
+
parts.push(`运行 ${Math.max(0, Math.round((Number(item.finishedAt) - Number(item.startedAt)) / 1000))}s`);
|
|
546
|
+
}
|
|
547
|
+
if (landed.length > 0)
|
|
548
|
+
parts.push(`声明产物已在盘上:${landed.slice(0, 6).join('、')}`);
|
|
549
|
+
return parts.join(';');
|
|
550
|
+
}
|
|
386
551
|
/**
|
|
387
552
|
* Turn one child output into a status verdict.
|
|
388
553
|
*
|
|
@@ -441,6 +606,15 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
441
606
|
const { parentSignal, deadline, modelSelection, conversationContext = '', child, guard } = options;
|
|
442
607
|
let lastError = null;
|
|
443
608
|
let lastFailure = null;
|
|
609
|
+
/*
|
|
610
|
+
* [1.8.6] The interrupt has to outlive the thrown error.
|
|
611
|
+
*
|
|
612
|
+
* `interruptedFlag` travels back to the dispatcher (it must not cascade this
|
|
613
|
+
* task's dependents); `interruptedEvidence` is what gets written into the
|
|
614
|
+
* blocked status so the main Agent can re-adjudicate on facts.
|
|
615
|
+
*/
|
|
616
|
+
let interruptedFlag = false;
|
|
617
|
+
let interruptedEvidence = null;
|
|
444
618
|
try {
|
|
445
619
|
if (!writeSubtaskStatus(record, subtask.id, {
|
|
446
620
|
status: 'in_progress',
|
|
@@ -451,6 +625,7 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
451
625
|
for (let attempt = 1; attempt <= 2; attempt += 1) {
|
|
452
626
|
if (guard.timedOut)
|
|
453
627
|
return;
|
|
628
|
+
interruptedEvidence = null;
|
|
454
629
|
if (parentSignal.aborted)
|
|
455
630
|
throw abortError();
|
|
456
631
|
if (Date.now() >= deadline)
|
|
@@ -548,7 +723,25 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
548
723
|
return;
|
|
549
724
|
const output = resultText(result);
|
|
550
725
|
if (result.stopReason !== 'completed') {
|
|
551
|
-
|
|
726
|
+
/*
|
|
727
|
+
* [1.8.5] 中断必须自己说出「接下来怎么办」。
|
|
728
|
+
*
|
|
729
|
+
* 2026-10-30 事故:T6 在被外部中断前 2 秒已写出 38KB 交付物,插件只留下
|
|
730
|
+
* 「子 Agent 结束状态为 aborted」,主 Agent 无从知道产物其实已经在盘上,
|
|
731
|
+
* 于是把它当彻底失败处理,并把 6 个下游一起判死。中断类失败要显式提示
|
|
732
|
+
* 「先核对已写出的产物」,并给出据实改判与续跑这两条出口。
|
|
733
|
+
*/
|
|
734
|
+
const interrupted = result.stopReason === 'aborted';
|
|
735
|
+
const landed = interrupted ? probeInterruptedArtifacts(output, subtask, options.cwd, options.artifactExists) : [];
|
|
736
|
+
if (interrupted) {
|
|
737
|
+
interruptedFlag = true;
|
|
738
|
+
interruptedEvidence = probeInterruptedEvidence(output, subtask, options.cwd, options.artifactExists);
|
|
739
|
+
}
|
|
740
|
+
throw new PlanError(`子 Agent 结束状态为 ${result.stopReason}${result.diagnostic ? `:${result.diagnostic}` : ''}${interrupted
|
|
741
|
+
? `(子 Agent 在完成前被中断:先核对该步声明的产物是否已写出${landed.length > 0
|
|
742
|
+
? `——已核到 ${landed.length} 个文件确实在盘上:${landed.join('、')}`
|
|
743
|
+
: ''};据实改判,再决定是否续跑)`
|
|
744
|
+
: ''}`, 'CHILD_NOT_COMPLETED');
|
|
552
745
|
}
|
|
553
746
|
if (!output)
|
|
554
747
|
throw new PlanError('子 Agent 没有返回文本结果', 'EMPTY_CHILD_OUTPUT');
|
|
@@ -587,7 +780,7 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
587
780
|
const retry = !isAbort && shouldRetryAttempt(error, attempt, remaining, idleTimeoutMs);
|
|
588
781
|
if (retry) {
|
|
589
782
|
record.errors = [
|
|
590
|
-
...record.errors,
|
|
783
|
+
...(record.errors ?? []),
|
|
591
784
|
`${subtask.id}: 第 ${attempt} 次执行失败(${lastFailure.code}),已带上失败原因重试`,
|
|
592
785
|
].slice(-20);
|
|
593
786
|
writeSubtaskStatus(record, subtask.id, { progress: 15 }, guard);
|
|
@@ -595,7 +788,7 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
595
788
|
}
|
|
596
789
|
if (!isAbort && remaining <= idleTimeoutMs && error?.code !== 'CHILD_TIMEOUT') {
|
|
597
790
|
record.errors = [
|
|
598
|
-
...record.errors,
|
|
791
|
+
...(record.errors ?? []),
|
|
599
792
|
`${subtask.id}: 剩余预算不足(${Math.max(0, Math.round(remaining / 1000))}s),未重试`,
|
|
600
793
|
].slice(-20);
|
|
601
794
|
}
|
|
@@ -615,8 +808,18 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
|
|
|
615
808
|
finishedAt: Date.now(),
|
|
616
809
|
error: truncate(message, 2000),
|
|
617
810
|
summary: truncate(`未完成:${message}`, 3000),
|
|
811
|
+
// [1.8.6] A blocked status that carries no evidence is what made the
|
|
812
|
+
// dispatcher treat "interrupted, file on disk" exactly like "produced
|
|
813
|
+
// nothing". Record what was actually found.
|
|
814
|
+
...(interruptedEvidence && interruptedEvidence.artifacts.length > 0
|
|
815
|
+
? { artifacts: interruptedEvidence.artifacts }
|
|
816
|
+
: {}),
|
|
817
|
+
...(interruptedEvidence && interruptedEvidence.missingArtifacts.length > 0
|
|
818
|
+
? { missingArtifacts: interruptedEvidence.missingArtifacts }
|
|
819
|
+
: {}),
|
|
618
820
|
}, guard);
|
|
619
821
|
recordSubtaskError(record, subtask.id, message, guard);
|
|
822
|
+
return interruptedFlag ? { interrupted: true } : undefined;
|
|
620
823
|
}
|
|
621
824
|
catch (error) {
|
|
622
825
|
const message = describeError(error);
|
|
@@ -658,19 +861,15 @@ async function runSubtask(ctx, record, stage, subtask, options) {
|
|
|
658
861
|
// plain "too slow" and the next investigation goes down the wrong path.
|
|
659
862
|
const message = `子任务 ${subtask.id} 达到执行上限(${childTimeoutMs}ms),已强制结束`;
|
|
660
863
|
try {
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
error: message,
|
|
666
|
-
summary: truncate(`未完成:${message}`, 3000),
|
|
667
|
-
});
|
|
668
|
-
record.errors = [...record.errors, `${subtask.id}: ${message}`].slice(-20);
|
|
864
|
+
// [1.8.19] Keep the evidence of what already landed on disk.
|
|
865
|
+
const { patch } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists);
|
|
866
|
+
record.statuses = applyStatus(record.statuses, subtask.id, patch);
|
|
867
|
+
record.errors = [...(record.errors ?? []), `${subtask.id}: ${patch.error}`].slice(-20);
|
|
669
868
|
record.updatedAt = Date.now();
|
|
670
869
|
}
|
|
671
870
|
catch (error) {
|
|
672
871
|
record.errors = [
|
|
673
|
-
...record.errors,
|
|
872
|
+
...(record.errors ?? []),
|
|
674
873
|
`${subtask.id}: 超时状态写入失败:${truncate(String(error?.message ?? error), 500)}`,
|
|
675
874
|
].slice(-20);
|
|
676
875
|
}
|
|
@@ -685,7 +884,9 @@ async function runSubtask(ctx, record, stage, subtask, options) {
|
|
|
685
884
|
timer.unref?.();
|
|
686
885
|
});
|
|
687
886
|
try {
|
|
688
|
-
|
|
887
|
+
// [1.8.6] The outcome (`{interrupted:true}`) has to reach the dispatcher;
|
|
888
|
+
// swallowing it here is why an interrupted child looked like any failure.
|
|
889
|
+
return await Promise.race([
|
|
689
890
|
executeSubtask(ctx, record, stage, subtask, {
|
|
690
891
|
...options,
|
|
691
892
|
child,
|
|
@@ -748,6 +949,15 @@ export function modelStatusLines(statuses) {
|
|
|
748
949
|
summary: truncate(item.summary ?? item.error ?? '', 2000),
|
|
749
950
|
error: item.error ?? null,
|
|
750
951
|
verification: item.verification ?? null,
|
|
952
|
+
// [1.8.13] The model must see *which* acceptance item failed, not just the
|
|
953
|
+
// verdict; it cannot repair a gap it cannot name.
|
|
954
|
+
acceptance: Array.isArray(item.acceptance)
|
|
955
|
+
? item.acceptance.slice(0, 8).map((entry) => ({
|
|
956
|
+
criterion: truncate(String(entry?.criterion ?? ''), 200),
|
|
957
|
+
result: String(entry?.result ?? ''),
|
|
958
|
+
evidence: truncate(String(entry?.evidence ?? ''), 300),
|
|
959
|
+
}))
|
|
960
|
+
: [],
|
|
751
961
|
revision: Number(item.revision ?? 0),
|
|
752
962
|
updatedBy: item.updatedBy ?? null,
|
|
753
963
|
missingArtifacts: Array.isArray(item.missingArtifacts) ? item.missingArtifacts : [],
|
|
@@ -770,6 +980,49 @@ export function buildRoundResult(record, sessionId, limits) {
|
|
|
770
980
|
resumeAvailable: canResumePlan(record, limits.maxResumes).resume,
|
|
771
981
|
});
|
|
772
982
|
}
|
|
983
|
+
/**
|
|
984
|
+
* [1.8.6] Explain why a `pending` task cannot run, instead of calling it blocked.
|
|
985
|
+
*
|
|
986
|
+
* A single generic sentence made three different situations indistinguishable:
|
|
987
|
+
* a budget pause (nothing ran yet), an upstream whose declared file is missing
|
|
988
|
+
* (the work may well be done), and a genuinely failed upstream. The main Agent
|
|
989
|
+
* read all three as "7 卡住了" and had to re-derive the cause by hand.
|
|
990
|
+
*/
|
|
991
|
+
function describePendingCause(plan, statuses, id) {
|
|
992
|
+
const byId = new Map(statuses.map((item) => [item.subtaskId, item]));
|
|
993
|
+
const entry = flattenSubtasks(plan).find((candidate) => candidate.subtask.id === id);
|
|
994
|
+
if (!entry)
|
|
995
|
+
return '计划里找不到该步骤';
|
|
996
|
+
const declared = Array.isArray(entry.subtask.dependsOn) ? entry.subtask.dependsOn : [];
|
|
997
|
+
if (declared.length === 0)
|
|
998
|
+
return '没有上游依赖,但本轮未被调度到';
|
|
999
|
+
const bad = declared.filter((dep) => {
|
|
1000
|
+
const state = byId.get(dep);
|
|
1001
|
+
if (!state || state.status !== 'done')
|
|
1002
|
+
return true;
|
|
1003
|
+
if (Array.isArray(state.missingArtifacts) && state.missingArtifacts.length > 0)
|
|
1004
|
+
return true;
|
|
1005
|
+
if (state.verification === 'legacy')
|
|
1006
|
+
return true;
|
|
1007
|
+
return false;
|
|
1008
|
+
});
|
|
1009
|
+
if (bad.length === 0)
|
|
1010
|
+
return '上游都已就绪,但本轮未被调度到';
|
|
1011
|
+
return bad.map((dep) => {
|
|
1012
|
+
const state = byId.get(dep);
|
|
1013
|
+
if (!state)
|
|
1014
|
+
return `上游 ${dep} 缺失`;
|
|
1015
|
+
if (state.status !== 'done') {
|
|
1016
|
+
return `上游 ${dep} 状态为 ${state.status}${state.error ? `(${String(state.error).slice(0, 80)})` : ''}`;
|
|
1017
|
+
}
|
|
1018
|
+
if (Array.isArray(state.missingArtifacts) && state.missingArtifacts.length > 0) {
|
|
1019
|
+
return `上游 ${dep} 的声明产物缺失:${state.missingArtifacts.join('、')}`;
|
|
1020
|
+
}
|
|
1021
|
+
if (state.verification === 'legacy')
|
|
1022
|
+
return `上游 ${dep} 完成但未提供结构化证据`;
|
|
1023
|
+
return `上游 ${dep} 不可用`;
|
|
1024
|
+
}).join(';');
|
|
1025
|
+
}
|
|
773
1026
|
export async function dispatchPlan(ctx, record, options) {
|
|
774
1027
|
const { agent, signal, modelSelection, cwd, conversationContext = '' } = options;
|
|
775
1028
|
const deadline = Date.now() + (options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS);
|
|
@@ -825,6 +1078,16 @@ export async function dispatchPlan(ctx, record, options) {
|
|
|
825
1078
|
record.updatedAt = record.dispatchedAt;
|
|
826
1079
|
try {
|
|
827
1080
|
let guard = 0;
|
|
1081
|
+
/*
|
|
1082
|
+
* [1.8.6] Interrupted tasks are not cascaded.
|
|
1083
|
+
*
|
|
1084
|
+
* The 2026-10-30 incident: one child was interrupted after it had already
|
|
1085
|
+
* written its deliverable; the dispatcher blocked its 6 dependents. Those
|
|
1086
|
+
* children were never given a chance, and the plan looked like a 7-task
|
|
1087
|
+
* failure. Keep the interrupted task itself `blocked` (its verdict must not
|
|
1088
|
+
* be rewritten automatically), but leave dependents `pending` and say why.
|
|
1089
|
+
*/
|
|
1090
|
+
const interruptedIds = new Set();
|
|
828
1091
|
while (true) {
|
|
829
1092
|
guard += 1;
|
|
830
1093
|
if (guard > 200)
|
|
@@ -846,12 +1109,22 @@ export async function dispatchPlan(ctx, record, options) {
|
|
|
846
1109
|
}
|
|
847
1110
|
: {});
|
|
848
1111
|
if (ready.length === 0) {
|
|
1112
|
+
/*
|
|
1113
|
+
* [1.8.6] "Nothing is ready" is not the same thing as "everything
|
|
1114
|
+
* failed".
|
|
1115
|
+
*
|
|
1116
|
+
* The old code rewrote every remaining `pending` task to `blocked` with
|
|
1117
|
+
* one generic line ("依赖未完成或上游受阻"). A budget pause, a missing
|
|
1118
|
+
* artifact and a genuinely failed upstream all produced that same
|
|
1119
|
+
* status, the plan turned `blocked`, and a resume was billed against
|
|
1120
|
+
* the failure budget. Keep them `pending`, and record the actual cause.
|
|
1121
|
+
*/
|
|
849
1122
|
const pending = record.statuses.filter((item) => item.status === 'pending');
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
1123
|
+
if (pending.length > 0) {
|
|
1124
|
+
const reasons = pending.map((item) => `${item.subtaskId}:${describePendingCause(record.plan, record.statuses, item.subtaskId)}`);
|
|
1125
|
+
const message = `本轮结束,仍有 ${pending.length} 项保持 pending(不是失败,也未级联成 blocked):${reasons.slice(0, 6).join(';')}`;
|
|
1126
|
+
record.error = message;
|
|
1127
|
+
record.errors = [...(record.errors ?? []), message].slice(-20);
|
|
855
1128
|
}
|
|
856
1129
|
break;
|
|
857
1130
|
}
|
|
@@ -863,7 +1136,7 @@ export async function dispatchPlan(ctx, record, options) {
|
|
|
863
1136
|
.find((candidate) => candidate.subtask.id === item.id);
|
|
864
1137
|
if (!entry)
|
|
865
1138
|
return;
|
|
866
|
-
await runSubtask(ctx, record, entry.stage, entry.subtask, {
|
|
1139
|
+
const outcome = await runSubtask(ctx, record, entry.stage, entry.subtask, {
|
|
867
1140
|
agent,
|
|
868
1141
|
parentSignal: childController.signal,
|
|
869
1142
|
deadline,
|
|
@@ -875,6 +1148,10 @@ export async function dispatchPlan(ctx, record, options) {
|
|
|
875
1148
|
strictEvidence: options.strictEvidence,
|
|
876
1149
|
artifactExists: options.artifactExists,
|
|
877
1150
|
});
|
|
1151
|
+
// [1.8.6] Remember which failures were interrupts, so the cascade below
|
|
1152
|
+
// can leave their dependents pending instead of blaming them.
|
|
1153
|
+
if (outcome && outcome.interrupted)
|
|
1154
|
+
interruptedIds.add(item.id);
|
|
878
1155
|
});
|
|
879
1156
|
const blocked = record.statuses
|
|
880
1157
|
.filter((item) => item.status === 'blocked')
|
|
@@ -886,6 +1163,19 @@ export async function dispatchPlan(ctx, record, options) {
|
|
|
886
1163
|
* had to re-read the whole plan to guess what to repair.
|
|
887
1164
|
*/
|
|
888
1165
|
const upstream = record.statuses.find((item) => item.subtaskId === id);
|
|
1166
|
+
/*
|
|
1167
|
+
* [1.8.6] An interrupted task blocked itself, not its dependents.
|
|
1168
|
+
*
|
|
1169
|
+
* Recording the interruption in `errors` (instead of silently skipping)
|
|
1170
|
+
* keeps the reason visible in the result message, and `continue` leaves
|
|
1171
|
+
* the dependents `pending` so a re-dispatch can still run them once the
|
|
1172
|
+
* main Agent re-adjudicates the interrupted step.
|
|
1173
|
+
*/
|
|
1174
|
+
if (interruptedIds.has(id)) {
|
|
1175
|
+
record.errors = [...(record.errors ?? []),
|
|
1176
|
+
`${id}: 被中断但产物已核对(见 artifacts),未自动级联下游;请据实改判或续跑`].slice(-20);
|
|
1177
|
+
continue;
|
|
1178
|
+
}
|
|
889
1179
|
const cause = upstream
|
|
890
1180
|
? {
|
|
891
1181
|
reason: upstream.error,
|
|
@@ -900,7 +1190,17 @@ export async function dispatchPlan(ctx, record, options) {
|
|
|
900
1190
|
*/
|
|
901
1191
|
record.updatedAt = Date.now();
|
|
902
1192
|
}
|
|
903
|
-
|
|
1193
|
+
/*
|
|
1194
|
+
* [1.8.6] Do not let a pending tail masquerade as a failure.
|
|
1195
|
+
*
|
|
1196
|
+
* `planPhase` turns any `blocked` row into `blocked`; with D8's fix a round
|
|
1197
|
+
* can end with real blocked rows *and* untouched pending rows. Keep
|
|
1198
|
+
* `blocked` for real failures, and report `paused` when only pending work
|
|
1199
|
+
* is left, so a resume is not billed against the failure budget.
|
|
1200
|
+
*/
|
|
1201
|
+
const hasBlocked = record.statuses.some((item) => item.status === 'blocked');
|
|
1202
|
+
const hasPending = record.statuses.some((item) => item.status === 'pending');
|
|
1203
|
+
record.phase = hasBlocked ? 'blocked' : (hasPending ? 'paused' : planPhase(record.statuses));
|
|
904
1204
|
}
|
|
905
1205
|
catch (error) {
|
|
906
1206
|
const message = describeError(error);
|
|
@@ -932,9 +1232,12 @@ export async function dispatchPlan(ctx, record, options) {
|
|
|
932
1232
|
for (const item of record.statuses) {
|
|
933
1233
|
if (item.status === 'done')
|
|
934
1234
|
continue;
|
|
1235
|
+
// [1.8.19] Carry the aborted attempt's provenance and landed files into
|
|
1236
|
+
// the pause reason instead of silently erasing them.
|
|
1237
|
+
const definition = findSubtaskById(record.plan, item.subtaskId);
|
|
935
1238
|
reset = applyStatus(reset, item.subtaskId, {
|
|
936
1239
|
status: 'pending',
|
|
937
|
-
error:
|
|
1240
|
+
error: budgetResetError(item, definition, options.cwd, options.artifactExists),
|
|
938
1241
|
});
|
|
939
1242
|
}
|
|
940
1243
|
record.statuses = reset;
|
|
@@ -962,7 +1265,7 @@ export async function dispatchPlan(ctx, record, options) {
|
|
|
962
1265
|
*/
|
|
963
1266
|
record.errors = (record.errors ?? []).filter((line) => !/总执行超时/.test(String(line)));
|
|
964
1267
|
if (!allDoneNow)
|
|
965
|
-
record.errors = [...record.errors, record.error].slice(-20);
|
|
1268
|
+
record.errors = [...(record.errors ?? []), record.error].slice(-20);
|
|
966
1269
|
}
|
|
967
1270
|
else {
|
|
968
1271
|
/*
|
|
@@ -1155,6 +1458,7 @@ function serialisePlan(record, session) {
|
|
|
1155
1458
|
* 而不是等用户截图发现。附在 payload 上而不是抛错:展示层不应因自检而白屏。
|
|
1156
1459
|
*/
|
|
1157
1460
|
const violations = aggregateInvariantViolations(snapshot, phase);
|
|
1461
|
+
const readiness = deliveryReadiness(snapshot, { phase: record.phase });
|
|
1158
1462
|
return {
|
|
1159
1463
|
sessionId: session.id,
|
|
1160
1464
|
planId: record.planId ?? plan?.planId ?? null,
|
|
@@ -1171,6 +1475,17 @@ function serialisePlan(record, session) {
|
|
|
1171
1475
|
plan,
|
|
1172
1476
|
statuses,
|
|
1173
1477
|
stats,
|
|
1478
|
+
/*
|
|
1479
|
+
* [1.8.13] Delivery readiness travels with the dashboard payload too.
|
|
1480
|
+
*
|
|
1481
|
+
* `phase` alone cannot express "all rows done but evidence missing, or a
|
|
1482
|
+
* cancelled plan is still incomplete"; a green 100% card next to a denied
|
|
1483
|
+
* present is exactly the contradiction this incident exposed. The UI can
|
|
1484
|
+
* now show the same verdict the gate uses.
|
|
1485
|
+
*/
|
|
1486
|
+
deliveryReady: readiness.ready,
|
|
1487
|
+
deliveryBlockers: readiness.blockers.slice(0, 12),
|
|
1488
|
+
deliveryRemaining: readiness.remaining.slice(0, 20),
|
|
1174
1489
|
/*
|
|
1175
1490
|
* Liveness and resume bookkeeping. Without these the dashboard could not
|
|
1176
1491
|
* tell a slow-but-alive child from a wedged one, and the model could not
|
|
@@ -1216,30 +1531,129 @@ function readToolArguments(value) {
|
|
|
1216
1531
|
return null;
|
|
1217
1532
|
}
|
|
1218
1533
|
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
1534
|
/*
|
|
1231
|
-
*
|
|
1535
|
+
* [1.8.10] 回放窗口必须包含目标计划的定义。
|
|
1536
|
+
*
|
|
1537
|
+
* 会话事件超过 MAX_HISTORY_EVENTS(2000)后,窗口起点会越过早期的 plan
|
|
1538
|
+
* 消息。此时按 planId 重建旧计划得到 null,dispatch / status 都会退回
|
|
1539
|
+
* 内存里那个更新的计划,旧计划在卡片上消失,也无法再续跑。
|
|
1540
|
+
* 显式指定 planId 时向前扫到该计划的 plan 消息,把窗口起点前移。
|
|
1541
|
+
*/
|
|
1542
|
+
let start = Math.max(0, session.seq - MAX_HISTORY_EVENTS);
|
|
1543
|
+
if (targetPlanId) {
|
|
1544
|
+
for (let seq = start - 1; seq >= 0; seq -= 1) {
|
|
1545
|
+
let event;
|
|
1546
|
+
try {
|
|
1547
|
+
event = session.eventAt(seq);
|
|
1548
|
+
}
|
|
1549
|
+
catch {
|
|
1550
|
+
continue;
|
|
1551
|
+
}
|
|
1552
|
+
if (!event || event.type !== 'user/message')
|
|
1553
|
+
continue;
|
|
1554
|
+
const payload = parseWorkplanMessage(event.data);
|
|
1555
|
+
if (payload?.plan?.planId === targetPlanId) {
|
|
1556
|
+
start = seq;
|
|
1557
|
+
break;
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
/*
|
|
1562
|
+
* [1.8.15] Default replay keeps the "last defined plan" contract, but it
|
|
1563
|
+
* must still find that plan when its message predates the 2000-event window.
|
|
1564
|
+
*
|
|
1565
|
+
* T3 B4 measured the window failure on 1.8.14: on a >2000-event session the
|
|
1566
|
+
* window started after the plan message, the default replay returned null,
|
|
1567
|
+
* and `present` had no plan to judge — the delivery was silently allowed.
|
|
1568
|
+
* The scan reads backwards for the last `workplan` definition and moves the
|
|
1569
|
+
* window start to it.
|
|
1570
|
+
*
|
|
1571
|
+
* The "newest activity" variant was deliberately NOT adopted: the same
|
|
1572
|
+
* default answer also feeds `dispatch`, so an older plan that merely kept
|
|
1573
|
+
* receiving result/update messages would hijack a new task's default
|
|
1574
|
+
* dispatch target (the reason N5 in 1.8.14 left the contract alone). The
|
|
1575
|
+
* turn-scoped fixes (`planIdFromTurn`, the present gate) name the plan
|
|
1576
|
+
* explicitly instead of changing the default.
|
|
1577
|
+
*/
|
|
1578
|
+
let defaultPlanId = null;
|
|
1579
|
+
if (!targetPlanId) {
|
|
1580
|
+
for (let seq = session.seq - 1; seq >= 0; seq -= 1) {
|
|
1581
|
+
let event;
|
|
1582
|
+
try {
|
|
1583
|
+
event = session.eventAt(seq);
|
|
1584
|
+
}
|
|
1585
|
+
catch {
|
|
1586
|
+
continue;
|
|
1587
|
+
}
|
|
1588
|
+
if (!event || event.type !== 'user/message')
|
|
1589
|
+
continue;
|
|
1590
|
+
const planMessage = parseWorkplanMessage(event.data);
|
|
1591
|
+
const planId = planMessage?.plan?.planId;
|
|
1592
|
+
if (typeof planId !== 'string' || planId === '')
|
|
1593
|
+
continue;
|
|
1594
|
+
defaultPlanId = planId;
|
|
1595
|
+
let planStart = seq;
|
|
1596
|
+
for (let back = seq - 1; back >= 0; back -= 1) {
|
|
1597
|
+
let prior;
|
|
1598
|
+
try {
|
|
1599
|
+
prior = session.eventAt(back);
|
|
1600
|
+
}
|
|
1601
|
+
catch {
|
|
1602
|
+
continue;
|
|
1603
|
+
}
|
|
1604
|
+
if (!prior || prior.type !== 'user/message')
|
|
1605
|
+
continue;
|
|
1606
|
+
if (parseWorkplanMessage(prior.data)?.plan?.planId === planId)
|
|
1607
|
+
planStart = back;
|
|
1608
|
+
}
|
|
1609
|
+
if (planStart < start)
|
|
1610
|
+
start = planStart;
|
|
1611
|
+
break;
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
/*
|
|
1615
|
+
* [1.8.9] 回放按 planId 分账,不按会话「最后一个计划」分账。
|
|
1232
1616
|
*
|
|
1233
|
-
*
|
|
1234
|
-
*
|
|
1235
|
-
*
|
|
1236
|
-
*
|
|
1237
|
-
*
|
|
1617
|
+
* 旧实现只有一组 plan/statuses:中途出现第二个计划(这次事故里是「继续」被
|
|
1618
|
+
* 误判后生成的 wp-dd26f206)时,第一个计划的快照被冻结在当时,之后所有属于
|
|
1619
|
+
* 它的结果消息与人工改判都被丢弃——重启后卡片从 13/14 掉回 5/14,而会话
|
|
1620
|
+
* 日志里明明有 7/14 的结果消息和 6 条 done 改判。现在每个计划各一份快照,
|
|
1621
|
+
* 每条 durable 消息只写给 planId 指定的那个计划。
|
|
1238
1622
|
*/
|
|
1239
|
-
const
|
|
1623
|
+
const snapshots = new Map();
|
|
1624
|
+
let currentId = null;
|
|
1625
|
+
let degraded = null;
|
|
1626
|
+
const ensure = (plan) => {
|
|
1627
|
+
let snap = snapshots.get(plan.planId);
|
|
1628
|
+
if (!snap) {
|
|
1629
|
+
snap = {
|
|
1630
|
+
plan,
|
|
1631
|
+
statuses: createStatuses(plan),
|
|
1632
|
+
resultPhase: '',
|
|
1633
|
+
resultSeen: false,
|
|
1634
|
+
resumeCount: 0,
|
|
1635
|
+
cancelled: false,
|
|
1636
|
+
superseded: false,
|
|
1637
|
+
supersededBy: undefined,
|
|
1638
|
+
errors: [],
|
|
1639
|
+
};
|
|
1640
|
+
snapshots.set(plan.planId, snap);
|
|
1641
|
+
}
|
|
1642
|
+
currentId = plan.planId;
|
|
1643
|
+
return snap;
|
|
1644
|
+
};
|
|
1240
1645
|
/** [1.6.0] callId → 待确认的 update 写入;只有配对的 tool/result 才能定案。 */
|
|
1241
1646
|
const pendingToolCalls = new Map();
|
|
1242
|
-
|
|
1647
|
+
/**
|
|
1648
|
+
* [1.8.11] 已经由 durable `workplan-update` 消息应用过的人工改判。
|
|
1649
|
+
*
|
|
1650
|
+
* 一次 `dsh_workplan_update` 会写两份记录:一条 durable 用户消息(带
|
|
1651
|
+
* revision 与 updatedBy=agent)和一条 tool/result。回放原来两份都应用,
|
|
1652
|
+
* 第二次以 system 身份把 revision 再抬一级并覆盖 summary——人工改判的
|
|
1653
|
+
* 证据后缀就这么丢了。这里记下消息的 seq,配对的 tool/result 不再重复写。
|
|
1654
|
+
*/
|
|
1655
|
+
const appliedUpdates = new Map();
|
|
1656
|
+
const updateKey = (planId, subtaskId) => `${planId}\u0000${subtaskId}`;
|
|
1243
1657
|
for (let seq = start; seq < session.seq; seq += 1) {
|
|
1244
1658
|
let event;
|
|
1245
1659
|
try {
|
|
@@ -1254,36 +1668,42 @@ export function reconstructFromSession(session, targetPlanId) {
|
|
|
1254
1668
|
const payload = parseWorkplanMessage(event.data);
|
|
1255
1669
|
if (payload?.degraded) {
|
|
1256
1670
|
degraded = payload;
|
|
1257
|
-
|
|
1258
|
-
statuses = [];
|
|
1259
|
-
cancelled = false;
|
|
1671
|
+
currentId = null;
|
|
1260
1672
|
}
|
|
1261
1673
|
else if (payload?.plan) {
|
|
1262
|
-
|
|
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;
|
|
1674
|
+
ensure(payload.plan);
|
|
1278
1675
|
}
|
|
1676
|
+
/*
|
|
1677
|
+
* Every result message is routed by its own planId. A result that arrives
|
|
1678
|
+
* after a newer plan was generated must still update the plan it names —
|
|
1679
|
+
* that was the 13/14 → 5/14 replay regression. A plan never inherits
|
|
1680
|
+
* another plan's round phase or resume counter (each snapshot owns them).
|
|
1681
|
+
*/
|
|
1279
1682
|
const result = parseResultMessage(event.data);
|
|
1280
|
-
if (result &&
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1683
|
+
if (result && typeof result.planId === 'string') {
|
|
1684
|
+
const snap = snapshots.get(result.planId);
|
|
1685
|
+
if (snap) {
|
|
1686
|
+
snap.statuses = applyResultStatuses(snap.statuses, result);
|
|
1687
|
+
// Resume bookkeeping must survive a page refresh, otherwise the budget
|
|
1688
|
+
// silently resets and a never-succeeding subtask can loop forever.
|
|
1689
|
+
snap.resumeCount = Number(result.resumeCount ?? snap.resumeCount) || 0;
|
|
1690
|
+
snap.resultPhase = typeof result.phase === 'string' ? result.phase : '';
|
|
1691
|
+
snap.resultSeen = true;
|
|
1692
|
+
// [1.8.17] Keep the durable failure lines so a replayed record is
|
|
1693
|
+
// shaped like a live one (never `undefined`).
|
|
1694
|
+
if (Array.isArray(result.errors)) {
|
|
1695
|
+
snap.errors = snap.errors.concat(result.errors.map((line) => String(line))).slice(-20);
|
|
1696
|
+
}
|
|
1697
|
+
/*
|
|
1698
|
+
* [1.8.14] A cancel that lands while a dispatch is in flight writes no
|
|
1699
|
+
* separate cancel message (it aborts the dispatch instead), so the
|
|
1700
|
+
* only durable trace of that cancellation is `phase: 'cancelled'` in
|
|
1701
|
+
* the round result. Without this the plan reopens as "executing"
|
|
1702
|
+
* after a restart — the cancel is silently lost.
|
|
1703
|
+
*/
|
|
1704
|
+
if (snap.resultPhase === 'cancelled')
|
|
1705
|
+
snap.cancelled = true;
|
|
1706
|
+
}
|
|
1287
1707
|
}
|
|
1288
1708
|
/*
|
|
1289
1709
|
* [1.7.0] Manual re-adjudications replay in order.
|
|
@@ -1295,26 +1715,59 @@ export function reconstructFromSession(session, targetPlanId) {
|
|
|
1295
1715
|
* newer one (see `applyResultStatuses`).
|
|
1296
1716
|
*/
|
|
1297
1717
|
const update = parseUpdateMessage(event.data);
|
|
1298
|
-
if (update &&
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1718
|
+
if (update && typeof update.planId === 'string' && typeof update.subtaskId === 'string') {
|
|
1719
|
+
const snap = snapshots.get(update.planId);
|
|
1720
|
+
if (snap) {
|
|
1721
|
+
try {
|
|
1722
|
+
snap.statuses = applyStatus(snap.statuses, update.subtaskId, {
|
|
1723
|
+
status: update.status,
|
|
1724
|
+
progress: typeof update.progress === 'number' ? update.progress : undefined,
|
|
1725
|
+
summary: typeof update.note === 'string' ? update.note : undefined,
|
|
1726
|
+
// [1.8.13] Evidence written through the update tool must survive replay.
|
|
1727
|
+
verification: update.verification,
|
|
1728
|
+
acceptance: update.acceptance,
|
|
1729
|
+
artifacts: update.artifacts,
|
|
1730
|
+
missingArtifacts: update.missingArtifacts,
|
|
1731
|
+
revision: Number.isInteger(update.revision) ? update.revision : undefined,
|
|
1732
|
+
updatedBy: 'agent',
|
|
1733
|
+
});
|
|
1734
|
+
appliedUpdates.set(updateKey(update.planId, update.subtaskId), {
|
|
1735
|
+
seq: Number(event.seq ?? 0),
|
|
1736
|
+
status: String(update.status ?? ''),
|
|
1737
|
+
});
|
|
1738
|
+
}
|
|
1739
|
+
catch {
|
|
1740
|
+
// An invalid historical update is ignored; the rest still replays.
|
|
1741
|
+
}
|
|
1310
1742
|
}
|
|
1311
1743
|
}
|
|
1312
1744
|
const cancel = parseCancelMessage(event.data);
|
|
1313
|
-
if (cancel &&
|
|
1314
|
-
|
|
1745
|
+
if (cancel && typeof cancel.planId === 'string') {
|
|
1746
|
+
const snap = snapshots.get(cancel.planId);
|
|
1747
|
+
if (snap) {
|
|
1748
|
+
/*
|
|
1749
|
+
* [1.9.0] disposition='superseded' 的信封表示「责任已转移」,不是
|
|
1750
|
+
* 用户撤销。旧解析器只校验 kind,因此该字段对新旧版本都安全:旧版
|
|
1751
|
+
* 按 cancelled 读(不可派发、不可交付),不会复活成 active。
|
|
1752
|
+
*/
|
|
1753
|
+
if (cancel.disposition === 'superseded') {
|
|
1754
|
+
snap.superseded = true;
|
|
1755
|
+
snap.supersededBy = cancel.supersededBy;
|
|
1756
|
+
/*
|
|
1757
|
+
* [1.9.2] 互斥(T6):取代永远发生在取消之后,所以日志里两条信封
|
|
1758
|
+
* 都在。只加 superseded 不清 cancelled,冷启动记录就会变成「既已
|
|
1759
|
+
* 取消、又被取代」,与 live 记录(`supersedePlanRecord` 写入时
|
|
1760
|
+
* 把 cancelled 置 false)分叉 —— 这正是写侧收敛要杜绝的那类分叉。
|
|
1761
|
+
*/
|
|
1762
|
+
snap.cancelled = false;
|
|
1763
|
+
}
|
|
1764
|
+
else {
|
|
1765
|
+
snap.cancelled = true;
|
|
1766
|
+
}
|
|
1767
|
+
}
|
|
1315
1768
|
}
|
|
1316
1769
|
}
|
|
1317
|
-
else if (event.type === 'tool/call'
|
|
1770
|
+
else if (event.type === 'tool/call') {
|
|
1318
1771
|
/*
|
|
1319
1772
|
* [1.6.0] 只登记,不下结论。
|
|
1320
1773
|
*
|
|
@@ -1328,7 +1781,9 @@ export function reconstructFromSession(session, targetPlanId) {
|
|
|
1328
1781
|
if (data?.name === 'dsh_workplan_update' && typeof data.callId === 'string') {
|
|
1329
1782
|
const args = readToolArguments(data.arguments);
|
|
1330
1783
|
if (args && typeof args.subtaskId === 'string' && typeof args.status === 'string') {
|
|
1331
|
-
|
|
1784
|
+
const planId = typeof args.planId === 'string' ? args.planId : currentId;
|
|
1785
|
+
if (planId)
|
|
1786
|
+
pendingToolCalls.set(data.callId, { args, planId, callSeq: Number(event.seq ?? 0) });
|
|
1332
1787
|
}
|
|
1333
1788
|
}
|
|
1334
1789
|
}
|
|
@@ -1339,7 +1794,8 @@ export function reconstructFromSession(session, targetPlanId) {
|
|
|
1339
1794
|
continue;
|
|
1340
1795
|
const pending = pendingToolCalls.get(callId);
|
|
1341
1796
|
pendingToolCalls.delete(callId);
|
|
1342
|
-
|
|
1797
|
+
const snap = pending && typeof pending.planId === 'string' ? snapshots.get(pending.planId) : null;
|
|
1798
|
+
if (!snap) {
|
|
1343
1799
|
// 结果晚于新计划到达:旧计划的写入不污染新计划的状态表。
|
|
1344
1800
|
}
|
|
1345
1801
|
else if (message.isError === true) {
|
|
@@ -1347,22 +1803,46 @@ export function reconstructFromSession(session, targetPlanId) {
|
|
|
1347
1803
|
}
|
|
1348
1804
|
else {
|
|
1349
1805
|
const args = pending.args;
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1806
|
+
/*
|
|
1807
|
+
* [1.8.11] 同一次改判已经由 durable 消息应用过时,配对结果不再写第二遍。
|
|
1808
|
+
* 判据是 seq 与状态都一致:durable 消息在本次调用之后到达且状态相同,
|
|
1809
|
+
* 才说明它是这次调用的记录;更早/更晚的人工改判仍按自己的顺序生效。
|
|
1810
|
+
*/
|
|
1811
|
+
const applied = appliedUpdates.get(updateKey(pending.planId, args.subtaskId));
|
|
1812
|
+
const alreadyDurable = Boolean(applied)
|
|
1813
|
+
&& applied.seq > Number(pending.callSeq ?? 0)
|
|
1814
|
+
&& applied.status === String(args.status ?? '');
|
|
1815
|
+
if (!alreadyDurable) {
|
|
1816
|
+
try {
|
|
1817
|
+
snap.statuses = applyStatus(snap.statuses, args.subtaskId, {
|
|
1818
|
+
status: args.status,
|
|
1819
|
+
progress: typeof args.progress === 'number' ? args.progress : undefined,
|
|
1820
|
+
summary: typeof args.note === 'string' ? args.note : undefined,
|
|
1821
|
+
// [1.8.13] A tool/result fallback carries the same evidence fields.
|
|
1822
|
+
verification: args.verification,
|
|
1823
|
+
acceptance: args.acceptance,
|
|
1824
|
+
artifacts: args.artifacts,
|
|
1825
|
+
missingArtifacts: args.missingArtifacts,
|
|
1826
|
+
});
|
|
1827
|
+
}
|
|
1828
|
+
catch {
|
|
1829
|
+
// An invalid historical call is ignored; the live cache remains authoritative.
|
|
1830
|
+
}
|
|
1359
1831
|
}
|
|
1360
1832
|
}
|
|
1361
1833
|
}
|
|
1362
1834
|
}
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1835
|
+
/*
|
|
1836
|
+
* [1.8.15] Prefer the explicitly named plan, then the plan that owns the
|
|
1837
|
+
* newest activity, then the last definition seen in the replay window.
|
|
1838
|
+
*/
|
|
1839
|
+
const chosenId = targetPlanId ?? defaultPlanId ?? currentId;
|
|
1840
|
+
let chosen = chosenId ? snapshots.get(chosenId) ?? null : null;
|
|
1841
|
+
if (!chosen && currentId)
|
|
1842
|
+
chosen = snapshots.get(currentId) ?? null;
|
|
1843
|
+
if (!chosen) {
|
|
1844
|
+
if (!degraded)
|
|
1845
|
+
return null;
|
|
1366
1846
|
return {
|
|
1367
1847
|
plan: null,
|
|
1368
1848
|
planId: degraded.planId ?? null,
|
|
@@ -1376,19 +1856,25 @@ export function reconstructFromSession(session, targetPlanId) {
|
|
|
1376
1856
|
createdTurn: degraded.createdTurn ?? null,
|
|
1377
1857
|
};
|
|
1378
1858
|
}
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1859
|
+
const plan = chosen.plan;
|
|
1860
|
+
const statuses = chosen.statuses;
|
|
1861
|
+
const resultPhase = chosen.resultPhase;
|
|
1862
|
+
const resultSeen = chosen.resultSeen;
|
|
1863
|
+
const resumeCount = chosen.resumeCount;
|
|
1864
|
+
const superseded = chosen.superseded;
|
|
1865
|
+
/*
|
|
1866
|
+
* [1.9.2] 终态互斥(T6):superseded 与 cancelled 不会同时成立。手写/旧版
|
|
1867
|
+
* 日志里可能出现「supersede 信封之后又有一条取消信封」,此时按终态优先级
|
|
1868
|
+
* 只认 superseded(fail-closed:被取代依然不可派发、不可交付)。
|
|
1869
|
+
*/
|
|
1870
|
+
const cancelled = chosen.cancelled && !superseded;
|
|
1387
1871
|
let phase = planPhase(statuses, resultSeen);
|
|
1388
1872
|
if (resultPhase === 'paused' && statuses.some((item) => item.status !== 'done'))
|
|
1389
1873
|
phase = 'paused';
|
|
1390
1874
|
if (cancelled)
|
|
1391
1875
|
phase = 'cancelled';
|
|
1876
|
+
if (superseded)
|
|
1877
|
+
phase = 'superseded';
|
|
1392
1878
|
/*
|
|
1393
1879
|
* [1.5.2] 回放也必须走同一套对账。
|
|
1394
1880
|
*
|
|
@@ -1418,9 +1904,32 @@ export function reconstructFromSession(session, targetPlanId) {
|
|
|
1418
1904
|
updatedAt: Date.now(),
|
|
1419
1905
|
createdTurn: plan.createdTurn,
|
|
1420
1906
|
resumeCount,
|
|
1907
|
+
/*
|
|
1908
|
+
* [1.8.17] A reconstructed record must carry every field the live dispatch
|
|
1909
|
+
* path spreads/pushes unconditionally. `errors` was the one that was
|
|
1910
|
+
* missing; its absence turned a recoverable child failure into a round
|
|
1911
|
+
* abort that marked the rest of the plan blocked.
|
|
1912
|
+
*/
|
|
1913
|
+
errors: (chosen.errors ?? []).slice(-20),
|
|
1421
1914
|
resumeLimit: MAX_PLAN_RESUMES,
|
|
1422
1915
|
resumeAvailable: canResumePlan({ phase, statuses, resumeCount }, MAX_PLAN_RESUMES).resume,
|
|
1423
1916
|
stale: stalePending,
|
|
1917
|
+
/*
|
|
1918
|
+
* [1.8.14] Two facts, one from the log: whether the plan is cancelled and
|
|
1919
|
+
* whether that cancellation is durably recorded. For replay they are the
|
|
1920
|
+
* same; the live `cancelPlan` uses `cancelRecorded` to make a second
|
|
1921
|
+
* cancel a no-op instead of appending a duplicate message (N8).
|
|
1922
|
+
*
|
|
1923
|
+
* [1.9.2] 被取代的计划同样有一条已落盘的终态记录(V3 要求先取消才允许
|
|
1924
|
+
* 取代),因此 cancelRecorded 在 superseded 时为 true —— 与 live 记录一致
|
|
1925
|
+
* (`supersedePlanRecord` 保留先前的 cancelRecorded)。`supersedeRecorded`
|
|
1926
|
+
* 是取代信封的写入见证,补齐后普通取消的拒绝体在冷启动/热路径上字段相同。
|
|
1927
|
+
*/
|
|
1928
|
+
cancelled,
|
|
1929
|
+
cancelRecorded: cancelled || superseded,
|
|
1930
|
+
superseded,
|
|
1931
|
+
supersedeRecorded: superseded,
|
|
1932
|
+
supersededBy: superseded ? chosen.supersededBy : undefined,
|
|
1424
1933
|
};
|
|
1425
1934
|
}
|
|
1426
1935
|
function liveSessions(ctx) {
|
|
@@ -1494,11 +2003,48 @@ function respondJson(res, status, payload) {
|
|
|
1494
2003
|
res.end(body);
|
|
1495
2004
|
}
|
|
1496
2005
|
export function createWorkplanRuntime(ctx, options = {}) {
|
|
1497
|
-
|
|
2006
|
+
/*
|
|
2007
|
+
* `activeTurns` maps a root session to the turn whose user message carried a
|
|
2008
|
+
* real task; the `agent/turn-stopping` gate only objects on those turns.
|
|
2009
|
+
*/
|
|
2010
|
+
const state = { records: new Map(), activeTurns: new Map() };
|
|
1498
2011
|
/*
|
|
1499
2012
|
* Resolve the tunables once, at construction, so every code path (dispatch,
|
|
1500
2013
|
* resume, cancel, the host's tool timeout) agrees on the same numbers.
|
|
1501
2014
|
*/
|
|
2015
|
+
const pluginVersion = typeof options.version === 'string' && options.version ? options.version : 'unknown';
|
|
2016
|
+
/*
|
|
2017
|
+
* [1.8.14] Build identity, captured once.
|
|
2018
|
+
*
|
|
2019
|
+
* `startedAt` is derived from `process.uptime()` so it is the real process
|
|
2020
|
+
* start, not the plugin's construction time; `uptimeMs` is computed live.
|
|
2021
|
+
* Tests construct the runtime without a `build` option, so every field is
|
|
2022
|
+
* optional and the answer degrades to `unknown` instead of failing.
|
|
2023
|
+
*/
|
|
2024
|
+
const buildInfo = {
|
|
2025
|
+
pid: Number.isInteger(options.build?.pid) && Number(options.build?.pid) > 0
|
|
2026
|
+
? Number(options.build.pid)
|
|
2027
|
+
: process.pid,
|
|
2028
|
+
startedAt: Number.isFinite(Number(options.build?.startedAt)) && Number(options.build?.startedAt) > 0
|
|
2029
|
+
? Number(options.build.startedAt)
|
|
2030
|
+
: Math.round(Date.now() - process.uptime() * 1000),
|
|
2031
|
+
entryPath: typeof options.build?.entryPath === 'string' && options.build.entryPath
|
|
2032
|
+
? options.build.entryPath
|
|
2033
|
+
: '',
|
|
2034
|
+
buildHash: typeof options.build?.buildHash === 'string' && options.build.buildHash
|
|
2035
|
+
? options.build.buildHash
|
|
2036
|
+
: 'unknown',
|
|
2037
|
+
};
|
|
2038
|
+
function runtimeIdentity() {
|
|
2039
|
+
return {
|
|
2040
|
+
version: pluginVersion,
|
|
2041
|
+
pid: buildInfo.pid,
|
|
2042
|
+
startedAt: buildInfo.startedAt,
|
|
2043
|
+
uptimeMs: Math.max(0, Date.now() - buildInfo.startedAt),
|
|
2044
|
+
entryPath: buildInfo.entryPath,
|
|
2045
|
+
buildHash: buildInfo.buildHash,
|
|
2046
|
+
};
|
|
2047
|
+
}
|
|
1502
2048
|
const limits = {
|
|
1503
2049
|
childTimeoutMs: normaliseChildTimeout(options.childTimeoutMs),
|
|
1504
2050
|
idleTimeoutMs: normaliseIdleTimeout(options.idleTimeoutMs),
|
|
@@ -1556,18 +2102,44 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1556
2102
|
}
|
|
1557
2103
|
}
|
|
1558
2104
|
}
|
|
2105
|
+
/**
|
|
2106
|
+
* Point an edit or a cancellation at the plan the caller actually named.
|
|
2107
|
+
*
|
|
2108
|
+
* dispatch has always rebuilt an older plan out of the session log
|
|
2109
|
+
* (`needsRebuild` + `reconstructFromSession(session, requestedPlanId)`), but
|
|
2110
|
+
* update and cancel compared the id and threw PLAN_ID_MISMATCH — so the one
|
|
2111
|
+
* repair path for "the child wrote its artifact and was then interrupted"
|
|
2112
|
+
* (re-adjudicating that step) was closed on exactly the plans that needed it.
|
|
2113
|
+
* Align the three tools: a named plan that exists in the session log becomes
|
|
2114
|
+
* the target record. While a *different* plan is dispatching, refuse with a
|
|
2115
|
+
* reason instead of silently swapping the running record out from under it.
|
|
2116
|
+
*/
|
|
2117
|
+
function adoptRequestedPlan(session, current, requestedPlanId) {
|
|
2118
|
+
if (!current?.plan || !requestedPlanId || current.plan.planId === requestedPlanId)
|
|
2119
|
+
return current;
|
|
2120
|
+
if (current.dispatchPromise) {
|
|
2121
|
+
throw new PlanError(`计划 ${requestedPlanId} 不是当前记录:${current.plan.planId} 正在执行,先等它结束或先取消它`, 'PLAN_ID_MISMATCH');
|
|
2122
|
+
}
|
|
2123
|
+
const rebuilt = reconstructFromSession(session, requestedPlanId);
|
|
2124
|
+
if (!rebuilt?.plan || rebuilt.plan.planId !== requestedPlanId) {
|
|
2125
|
+
throw new PlanError(`planId 与当前计划不匹配(当前 ${current.plan.planId},会话日志里也没有 ${requestedPlanId})`, 'PLAN_ID_MISMATCH');
|
|
2126
|
+
}
|
|
2127
|
+
rebuilt.resumeLimit = current.resumeLimit ?? rebuilt.resumeLimit;
|
|
2128
|
+
state.records.set(session.id, rebuilt);
|
|
2129
|
+
return rebuilt;
|
|
2130
|
+
}
|
|
1559
2131
|
async function updateStatus(agent, args) {
|
|
1560
2132
|
const session = agent?.session;
|
|
1561
2133
|
if (!session)
|
|
1562
2134
|
throw new PlanError('只能在会话内更新计划', 'NO_SESSION');
|
|
1563
2135
|
if (!isRootSession(session))
|
|
1564
2136
|
throw new PlanError('子 Agent 不能更新主计划', 'NOT_ROOT');
|
|
1565
|
-
|
|
2137
|
+
let record = state.records.get(session.id);
|
|
2138
|
+
if (!record?.plan)
|
|
2139
|
+
record = reconstructFromSession(session, args?.planId);
|
|
2140
|
+
record = adoptRequestedPlan(session, record, args?.planId);
|
|
1566
2141
|
if (!record?.plan)
|
|
1567
2142
|
throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN');
|
|
1568
|
-
if (args?.planId && record.plan.planId !== args.planId) {
|
|
1569
|
-
throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH');
|
|
1570
|
-
}
|
|
1571
2143
|
const subtaskId = typeof args?.subtaskId === 'string' ? args.subtaskId : '';
|
|
1572
2144
|
if (!subtaskId)
|
|
1573
2145
|
throw new PlanError('缺少 subtaskId', 'MISSING_SUBTASK');
|
|
@@ -1622,11 +2194,31 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1622
2194
|
};
|
|
1623
2195
|
}
|
|
1624
2196
|
const revision = Number(current?.revision ?? 0) + 1;
|
|
2197
|
+
/*
|
|
2198
|
+
* [1.8.13] A manual verdict can carry structured evidence.
|
|
2199
|
+
*
|
|
2200
|
+
* The tool used to accept only `status/progress/note/evidence`, so the
|
|
2201
|
+
* documented escape from the present gate ("先用 dsh_workplan_update 复核
|
|
2202
|
+
* 并补证据") did not exist: a done row stayed `verification: undefined`
|
|
2203
|
+
* and could never become deliverable. These four fields are now accepted,
|
|
2204
|
+
* sanitised by `applyStatus`, persisted in the durable update message and
|
|
2205
|
+
* replayed. Omitted fields keep their previous values.
|
|
2206
|
+
*/
|
|
2207
|
+
const evidencePatch = {};
|
|
2208
|
+
if (args?.verification !== undefined)
|
|
2209
|
+
evidencePatch.verification = args.verification;
|
|
2210
|
+
if (args?.acceptance !== undefined)
|
|
2211
|
+
evidencePatch.acceptance = args.acceptance;
|
|
2212
|
+
if (args?.artifacts !== undefined)
|
|
2213
|
+
evidencePatch.artifacts = args.artifacts;
|
|
2214
|
+
if (args?.missingArtifacts !== undefined)
|
|
2215
|
+
evidencePatch.missingArtifacts = args.missingArtifacts;
|
|
1625
2216
|
record.statuses = applyStatus(record.statuses, subtaskId, {
|
|
1626
2217
|
status,
|
|
1627
2218
|
progress: typeof args?.progress === 'number' ? args.progress : undefined,
|
|
1628
2219
|
summary: summary || undefined,
|
|
1629
2220
|
error: status === 'blocked' ? (summary || '由主 Agent 标记为受阻') : undefined,
|
|
2221
|
+
...evidencePatch,
|
|
1630
2222
|
revision,
|
|
1631
2223
|
updatedBy: 'agent',
|
|
1632
2224
|
});
|
|
@@ -1641,6 +2233,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1641
2233
|
* result. Appending one small message keeps the replay path honest.
|
|
1642
2234
|
*/
|
|
1643
2235
|
try {
|
|
2236
|
+
const writtenRow = record.statuses.find((item) => item.subtaskId === subtaskId);
|
|
1644
2237
|
session.append('user/message', buildUpdateMessage({
|
|
1645
2238
|
planId: record.plan.planId,
|
|
1646
2239
|
subtaskId,
|
|
@@ -1648,6 +2241,10 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1648
2241
|
progress: typeof args?.progress === 'number' ? args.progress : undefined,
|
|
1649
2242
|
note: summary || undefined,
|
|
1650
2243
|
revision,
|
|
2244
|
+
verification: writtenRow?.verification,
|
|
2245
|
+
acceptance: writtenRow?.acceptance,
|
|
2246
|
+
artifacts: writtenRow?.artifacts,
|
|
2247
|
+
missingArtifacts: writtenRow?.missingArtifacts,
|
|
1651
2248
|
}), { surfaceOp: 'append' });
|
|
1652
2249
|
}
|
|
1653
2250
|
catch (error) {
|
|
@@ -1666,6 +2263,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1666
2263
|
record.updatedAt = Date.now();
|
|
1667
2264
|
const snapshot = derivePlanSnapshot(record.statuses);
|
|
1668
2265
|
const written = snapshot.statuses.find((item) => item.subtaskId === subtaskId);
|
|
2266
|
+
const readiness = deliveryReadiness(snapshot, { phase: record.phase });
|
|
1669
2267
|
return {
|
|
1670
2268
|
ok: true,
|
|
1671
2269
|
planId: record.plan.planId,
|
|
@@ -1674,6 +2272,16 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1674
2272
|
revision: written?.revision ?? revision,
|
|
1675
2273
|
updatedBy: written?.updatedBy ?? 'agent',
|
|
1676
2274
|
stats: snapshot.stats,
|
|
2275
|
+
deliveryReady: readiness.ready,
|
|
2276
|
+
deliveryBlockers: readiness.blockers.slice(0, 12),
|
|
2277
|
+
deliveryRemaining: readiness.remaining.slice(0, 20),
|
|
2278
|
+
...(readiness.ready
|
|
2279
|
+
? { hint: '计划已全部 done 且证据通过,可以交付。' }
|
|
2280
|
+
: {
|
|
2281
|
+
hint: written?.status === 'done'
|
|
2282
|
+
? '该子任务已是 done,但计划尚未通过交付就绪检查;若这项仍有证据缺口,请用 verification/acceptance 补齐或改回 blocked。'
|
|
2283
|
+
: '计划尚未通过交付就绪检查;继续推进剩余项,不要调用 present。',
|
|
2284
|
+
}),
|
|
1677
2285
|
};
|
|
1678
2286
|
}
|
|
1679
2287
|
async function cancelPlan(agent, args) {
|
|
@@ -1684,11 +2292,46 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1684
2292
|
throw new PlanError('子 Agent 不能取消主计划', 'NOT_ROOT');
|
|
1685
2293
|
let record = state.records.get(session.id);
|
|
1686
2294
|
if (!record?.plan)
|
|
1687
|
-
record = reconstructFromSession(session);
|
|
2295
|
+
record = reconstructFromSession(session, args?.planId);
|
|
2296
|
+
record = adoptRequestedPlan(session, record, args?.planId);
|
|
1688
2297
|
if (!record?.plan)
|
|
1689
2298
|
throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN');
|
|
1690
|
-
|
|
1691
|
-
|
|
2299
|
+
/*
|
|
2300
|
+
* [1.9.2] superseded 的唯一写入入口(T6)。
|
|
2301
|
+
*
|
|
2302
|
+
* `disposition` 只有两个合法取值:省略/'cancelled' 走既有取消语义(返回体
|
|
2303
|
+
* 与 1.8.19 逐字相同);'superseded' 交给 `supersedePlanRecord`(V1–V8
|
|
2304
|
+
* 复算 + digest + durable 信封)。其他取值一律拒绝:静默忽略一个拼错的
|
|
2305
|
+
* disposition 会把「想取代」写成「取消」,而两者的读侧判定完全不同。
|
|
2306
|
+
*/
|
|
2307
|
+
const disposition = args?.disposition;
|
|
2308
|
+
if (disposition !== undefined && disposition !== 'cancelled' && disposition !== 'superseded') {
|
|
2309
|
+
throw new PlanError(`disposition 只能是 cancelled 或 superseded(收到 ${String(disposition)})`, 'INVALID_DISPOSITION');
|
|
2310
|
+
}
|
|
2311
|
+
if (disposition === 'superseded') {
|
|
2312
|
+
const result = supersedePlanRecord(session, record, args, { reconstruct: reconstructFromSession });
|
|
2313
|
+
state.records.set(session.id, record);
|
|
2314
|
+
return result;
|
|
2315
|
+
}
|
|
2316
|
+
/*
|
|
2317
|
+
* [1.9.2] 被取代的计划不允许被普通取消静默改回 cancelled。
|
|
2318
|
+
*
|
|
2319
|
+
* 旧路径会追加第二条不带 disposition 的取消信封:live 变 cancelled,
|
|
2320
|
+
* replay 却因同一 planId 先读到 superseded 而仍是 superseded —— 又一种
|
|
2321
|
+
* live/replay 分叉。行政撤销(E6)需要用户明确要求并写入新的处置记录,
|
|
2322
|
+
* 本版本不实现,因此这里 fail-closed 并给出可执行说明。
|
|
2323
|
+
*/
|
|
2324
|
+
if (record.phase === 'superseded' || record.superseded === true) {
|
|
2325
|
+
return {
|
|
2326
|
+
ok: false,
|
|
2327
|
+
planId: record.plan.planId,
|
|
2328
|
+
phase: 'superseded',
|
|
2329
|
+
code: 'SUPERSEDED_LOCKED',
|
|
2330
|
+
error: '计划已被取代:不能静默改回 cancelled(行政撤销 E6 需要用户明确要求并写入新的处置记录,本版本未实现)',
|
|
2331
|
+
hint: '被取代不等于完成:不得调用 present、不得声称“已完成”。如需撤销该处置,请先向用户确认,再由主 Agent 走审计流程。',
|
|
2332
|
+
cancelRecorded: record.supersedeRecorded === true,
|
|
2333
|
+
stats: derivePlanSnapshot(record.statuses).stats,
|
|
2334
|
+
};
|
|
1692
2335
|
}
|
|
1693
2336
|
const reason = typeof args?.reason === 'string' && args.reason.trim()
|
|
1694
2337
|
? args.reason.trim()
|
|
@@ -1716,6 +2359,56 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1716
2359
|
stats: before.stats,
|
|
1717
2360
|
};
|
|
1718
2361
|
}
|
|
2362
|
+
/*
|
|
2363
|
+
* [1.8.14] N8: a second cancel used to append a second cancel message.
|
|
2364
|
+
*
|
|
2365
|
+
* Cancelling is idempotent by definition: once the cancellation is durably
|
|
2366
|
+
* recorded, repeating it must not grow the log — every duplicate is
|
|
2367
|
+
* replayed and shows up as another "取消" line in the transcript, which is
|
|
2368
|
+
* exactly the kind of "did it happen twice?" noise this incident was made
|
|
2369
|
+
* of.
|
|
2370
|
+
*
|
|
2371
|
+
* [1.8.15] The abort path was the exception that still duplicated: while
|
|
2372
|
+
* `dispatchPromise` was in flight the guard fell through every time, so two
|
|
2373
|
+
* cancels during one dispatch appended two messages (T4e F2). Once the
|
|
2374
|
+
* abort has been requested there is nothing left to stop, so the presence
|
|
2375
|
+
* of an in-flight promise is no longer a reason to append again.
|
|
2376
|
+
*/
|
|
2377
|
+
if (record.phase === 'cancelled' && record.cancelRecorded === true
|
|
2378
|
+
&& (!record.dispatchPromise || record.abortRequested === true)) {
|
|
2379
|
+
state.records.set(session.id, record);
|
|
2380
|
+
return {
|
|
2381
|
+
ok: true,
|
|
2382
|
+
planId: record.plan.planId,
|
|
2383
|
+
phase: 'cancelled',
|
|
2384
|
+
reason: typeof record.cancelReason === 'string' && record.cancelReason ? record.cancelReason : reason,
|
|
2385
|
+
alreadyCancelled: true,
|
|
2386
|
+
abortedRunning: false,
|
|
2387
|
+
cancelRecorded: true,
|
|
2388
|
+
stats: before.stats,
|
|
2389
|
+
};
|
|
2390
|
+
}
|
|
2391
|
+
const cancelMessage = buildCancelMessage(record.plan.planId, reason);
|
|
2392
|
+
/*
|
|
2393
|
+
* [1.8.14] N12: the durable cancel used to be the only append without a
|
|
2394
|
+
* try/catch. A failing append threw out of the tool after the in-memory
|
|
2395
|
+
* phase had already flipped to `cancelled`, leaving the UI saying
|
|
2396
|
+
* "已取消" while the log said nothing — the next restart silently undid it.
|
|
2397
|
+
* Record the failure and report `cancelRecorded: false` instead.
|
|
2398
|
+
*/
|
|
2399
|
+
const appendCancelRecord = () => {
|
|
2400
|
+
try {
|
|
2401
|
+
session.append('user/message', cancelMessage, { surfaceOp: 'append' });
|
|
2402
|
+
record.cancelRecorded = true;
|
|
2403
|
+
record.cancelReason = reason;
|
|
2404
|
+
return true;
|
|
2405
|
+
}
|
|
2406
|
+
catch (error) {
|
|
2407
|
+
record.cancelRecorded = false;
|
|
2408
|
+
pushRecordError(record, `写入取消消息失败:${error instanceof Error ? error.message : String(error)}`);
|
|
2409
|
+
return false;
|
|
2410
|
+
}
|
|
2411
|
+
};
|
|
1719
2412
|
if (record.dispatchPromise) {
|
|
1720
2413
|
/*
|
|
1721
2414
|
* Cancel must always work.
|
|
@@ -1731,32 +2424,47 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1731
2424
|
record.updatedAt = Date.now();
|
|
1732
2425
|
let aborted = false;
|
|
1733
2426
|
try {
|
|
2427
|
+
/*
|
|
2428
|
+
* [1.8.15] Mark the abort before asking for it. The idempotency guard
|
|
2429
|
+
* above keys on this flag, so a second cancel that arrives while the
|
|
2430
|
+
* dispatch promise is still settling cannot append a second message.
|
|
2431
|
+
*/
|
|
2432
|
+
record.abortRequested = true;
|
|
1734
2433
|
record.abortDispatch?.(reason);
|
|
1735
2434
|
aborted = true;
|
|
1736
2435
|
}
|
|
1737
2436
|
catch (error) {
|
|
1738
2437
|
record.errors = [...(record.errors ?? []), `取消时中止执行失败:${String(error?.message ?? error)}`].slice(-20);
|
|
1739
2438
|
}
|
|
2439
|
+
/*
|
|
2440
|
+
* [1.8.14] The abort path now writes the cancel durably too. 1.8.13
|
|
2441
|
+
* returned here without touching the log, so a later failed result write
|
|
2442
|
+
* left no trace of the cancellation at all and a restart reopened the
|
|
2443
|
+
* plan as "executing".
|
|
2444
|
+
*/
|
|
2445
|
+
const recorded = appendCancelRecord();
|
|
2446
|
+
state.records.set(session.id, record);
|
|
1740
2447
|
return {
|
|
1741
2448
|
ok: true,
|
|
1742
2449
|
planId: record.plan.planId,
|
|
1743
2450
|
phase: 'cancelled',
|
|
1744
2451
|
reason,
|
|
1745
2452
|
abortedRunning: aborted,
|
|
2453
|
+
cancelRecorded: recorded,
|
|
1746
2454
|
stats: derivePlanSnapshot(record.statuses).stats,
|
|
1747
2455
|
};
|
|
1748
2456
|
}
|
|
1749
2457
|
record.phase = 'cancelled';
|
|
1750
2458
|
record.error = `计划已取消:${reason}`;
|
|
1751
2459
|
record.updatedAt = Date.now();
|
|
1752
|
-
const
|
|
1753
|
-
session.append('user/message', message, { surfaceOp: 'append' });
|
|
2460
|
+
const recorded = appendCancelRecord();
|
|
1754
2461
|
state.records.set(session.id, record);
|
|
1755
2462
|
return {
|
|
1756
2463
|
ok: true,
|
|
1757
2464
|
planId: record.plan.planId,
|
|
1758
2465
|
phase: 'cancelled',
|
|
1759
2466
|
reason,
|
|
2467
|
+
cancelRecorded: recorded,
|
|
1760
2468
|
stats: derivePlanSnapshot(record.statuses).stats,
|
|
1761
2469
|
};
|
|
1762
2470
|
}
|
|
@@ -1776,6 +2484,12 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1776
2484
|
}
|
|
1777
2485
|
catch (error) {
|
|
1778
2486
|
ctx.logger?.warn?.(`dsh-workplan: 写入结果消息失败:${error instanceof Error ? error.message : String(error)}`);
|
|
2487
|
+
/*
|
|
2488
|
+
* [1.8.14] N13: a failed result write is a real, user-visible failure —
|
|
2489
|
+
* the round summary is absent from the transcript and a restart can
|
|
2490
|
+
* disagree with the live phase. Log it durably, not only in the host log.
|
|
2491
|
+
*/
|
|
2492
|
+
pushRecordError(record, `写入结果消息失败:${error instanceof Error ? error.message : String(error)}`);
|
|
1779
2493
|
}
|
|
1780
2494
|
}
|
|
1781
2495
|
/*
|
|
@@ -1788,12 +2502,45 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1788
2502
|
record.phase = reconcilePhase(record.phase, record.statuses);
|
|
1789
2503
|
return record;
|
|
1790
2504
|
}
|
|
2505
|
+
/*
|
|
2506
|
+
* [1.8.7] `ok` alone was read as "the plan is finished".
|
|
2507
|
+
*
|
|
2508
|
+
* The incident's tool result said `ok: true` while 3 of 13 subtasks had never
|
|
2509
|
+
* run; the rendered line added "已加入进行中的派发并等到结果", so the model
|
|
2510
|
+
* had no field telling it the round ended early. `complete`/`remaining` make
|
|
2511
|
+
* that state machine-readable instead of a sentence to interpret.
|
|
2512
|
+
*/
|
|
2513
|
+
function completionFields(snapshot, phase) {
|
|
2514
|
+
const stats = snapshot?.stats ?? {};
|
|
2515
|
+
const total = Number(stats.total ?? 0);
|
|
2516
|
+
const done = Number(stats.done ?? 0);
|
|
2517
|
+
/*
|
|
2518
|
+
* [1.8.13] `complete` and `deliveryReady` are different facts.
|
|
2519
|
+
*
|
|
2520
|
+
* `complete` keeps its old meaning (every subtask done) so existing callers
|
|
2521
|
+
* do not break, but a dispatch answer that only said `complete:true` was
|
|
2522
|
+
* read as "finished" even when every row was legacy/empty-evidence. The
|
|
2523
|
+
* model now also sees whether the plan passed the delivery gate, plus the
|
|
2524
|
+
* exact gaps.
|
|
2525
|
+
*/
|
|
2526
|
+
const readiness = deliveryReadiness(snapshot, { phase });
|
|
2527
|
+
return {
|
|
2528
|
+
complete: total > 0 && done >= total,
|
|
2529
|
+
remaining: Math.max(0, total - done),
|
|
2530
|
+
deliveryReady: readiness.ready,
|
|
2531
|
+
deliveryBlockers: readiness.blockers.slice(0, 12),
|
|
2532
|
+
deliveryRemaining: readiness.remaining.slice(0, 20),
|
|
2533
|
+
};
|
|
2534
|
+
}
|
|
1791
2535
|
function dispatchSnapshotOf(record, extra = {}) {
|
|
1792
2536
|
const snapshot = derivePlanSnapshot(record.statuses);
|
|
1793
2537
|
return {
|
|
1794
2538
|
ok: true,
|
|
2539
|
+
version: pluginVersion,
|
|
2540
|
+
runtime: runtimeIdentity(),
|
|
1795
2541
|
planId: record.plan.planId,
|
|
1796
2542
|
alreadyRunning: false,
|
|
2543
|
+
...completionFields(snapshot, record.phase),
|
|
1797
2544
|
...extra,
|
|
1798
2545
|
phase: record.phase,
|
|
1799
2546
|
stats: snapshot.stats,
|
|
@@ -1820,18 +2567,30 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1820
2567
|
record = rebuilt;
|
|
1821
2568
|
}
|
|
1822
2569
|
if (!record?.plan) {
|
|
2570
|
+
/*
|
|
2571
|
+
* [1.8.14] N1/§14.6 step 2: the identity of the loaded build must be
|
|
2572
|
+
* answerable even before a plan exists. 1.8.13 returned NO_PLAN with no
|
|
2573
|
+
* version here, so the documented restart check ("call status, confirm
|
|
2574
|
+
* the version") failed on a fresh session — the check itself was wrong,
|
|
2575
|
+
* not just the docs.
|
|
2576
|
+
*/
|
|
1823
2577
|
return {
|
|
1824
2578
|
ok: false,
|
|
1825
2579
|
code: 'NO_PLAN',
|
|
1826
2580
|
running: false,
|
|
2581
|
+
version: pluginVersion,
|
|
2582
|
+
runtime: runtimeIdentity(),
|
|
1827
2583
|
error: '当前会话没有可查看的计划',
|
|
1828
2584
|
hint: '先让本轮生成计划并调用 dsh_workplan_dispatch。',
|
|
1829
2585
|
};
|
|
1830
2586
|
}
|
|
1831
2587
|
const running = Boolean(record.dispatchPromise);
|
|
1832
2588
|
const snapshot = derivePlanSnapshot(record.statuses);
|
|
2589
|
+
const readiness = deliveryReadiness(snapshot, { phase: record.phase });
|
|
1833
2590
|
return {
|
|
1834
2591
|
ok: true,
|
|
2592
|
+
version: pluginVersion,
|
|
2593
|
+
runtime: runtimeIdentity(),
|
|
1835
2594
|
planId: record.plan.planId,
|
|
1836
2595
|
running,
|
|
1837
2596
|
phase: record.phase,
|
|
@@ -1840,16 +2599,85 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1840
2599
|
statuses: modelStatusLines(snapshot.statuses),
|
|
1841
2600
|
errors: (record.errors ?? []).slice(-10),
|
|
1842
2601
|
resumeLimit: Number(record.resumeLimit ?? limits.maxResumes),
|
|
2602
|
+
deliveryReady: readiness.ready,
|
|
2603
|
+
deliveryBlockers: readiness.blockers.slice(0, 12),
|
|
2604
|
+
deliveryRemaining: readiness.remaining.slice(0, 20),
|
|
1843
2605
|
...(running
|
|
1844
2606
|
? { hint: '计划仍在执行:先向用户报告进度,不要声称完成;等结果消息出现后再逐项核对证据。' }
|
|
1845
|
-
:
|
|
2607
|
+
: readiness.ready
|
|
2608
|
+
? { hint: '计划已全部 done 且证据通过,可以交付。' }
|
|
2609
|
+
: readiness.cancelled
|
|
2610
|
+
? { hint: '计划已取消且未完成:不要 dispatch 或 present;答复按「未完成:剩余 N 项与原因」开头。' }
|
|
2611
|
+
: { hint: '当前没有正在执行的派发。计划尚未通过交付就绪检查:先 dispatch 续跑剩余项;若只剩已 done 项的证据缺口,用 dsh_workplan_update 补 verification/acceptance。不要调用 present。' }),
|
|
1846
2612
|
};
|
|
1847
2613
|
}
|
|
1848
|
-
|
|
2614
|
+
/*
|
|
2615
|
+
* [1.9.1] 用户授权的 follow-up 通道。
|
|
2616
|
+
*
|
|
2617
|
+
* 事故背景:三条子会话 a0d5b134 / 031225ef / 7934905a 在 2026-10-31
|
|
2618
|
+
* 23:07–23:23 之间被整轮预算与 900s 子任务上限中止,各自末轮
|
|
2619
|
+
* `turn/end = aborted/parent`;界面据此显示 idle(灰色),而台账侧三条
|
|
2620
|
+
* 都是 done/structured。用户 2026-11-01 明确同意「补发 follow-up,让圈注
|
|
2621
|
+
* 三行真正变绿」——做法是让子会话自己再跑完一个正常回合,而不是伪造
|
|
2622
|
+
* turn/end 或改投影缓存。
|
|
2623
|
+
*
|
|
2624
|
+
* 本工具只做一件事:把一条消息投递到本会话的**直接**子会话。它不写计划
|
|
2625
|
+
* 状态、不触发交付、也不改变 `lastTurnCompleted`——那个字段只会被子会话
|
|
2626
|
+
* 自己真实完成的回合改写。投递成功后子会话开始新一轮;它正常结束,界面
|
|
2627
|
+
* 才可能变绿。失败一律返回 ok:false,不吞错。
|
|
2628
|
+
*/
|
|
2629
|
+
async function followupTool(agent, args, signal) {
|
|
1849
2630
|
const session = agent?.session;
|
|
1850
|
-
if (!session)
|
|
1851
|
-
|
|
1852
|
-
|
|
2631
|
+
if (!session) {
|
|
2632
|
+
return { ok: false, code: 'NO_SESSION', error: '只能在会话内补发 follow-up' };
|
|
2633
|
+
}
|
|
2634
|
+
if (!isRootSession(session)) {
|
|
2635
|
+
return { ok: false, code: 'NOT_ROOT', error: '只有根会话可以补发 follow-up' };
|
|
2636
|
+
}
|
|
2637
|
+
const childId = typeof args?.sessionId === 'string' ? args.sessionId.trim() : '';
|
|
2638
|
+
const message = typeof args?.message === 'string' ? args.message.trim() : '';
|
|
2639
|
+
if (!childId) {
|
|
2640
|
+
return { ok: false, code: 'INVALID_SESSION', error: 'sessionId 必填:必须是本会话的直接子会话 ID' };
|
|
2641
|
+
}
|
|
2642
|
+
if (!message) {
|
|
2643
|
+
return { ok: false, code: 'INVALID_MESSAGE', error: 'message 必填:要发给子会话的说明' };
|
|
2644
|
+
}
|
|
2645
|
+
if (message.length > 4000) {
|
|
2646
|
+
return { ok: false, code: 'MESSAGE_TOO_LONG', error: 'message 过长(上限 4000 字符)' };
|
|
2647
|
+
}
|
|
2648
|
+
if (!spawnedChildIds(session).has(childId)) {
|
|
2649
|
+
return {
|
|
2650
|
+
ok: false,
|
|
2651
|
+
code: 'NOT_DIRECT_CHILD',
|
|
2652
|
+
error: `${childId} 不是本会话的直接子会话(父会话 catalog 未登记),拒绝投递`,
|
|
2653
|
+
};
|
|
2654
|
+
}
|
|
2655
|
+
const service = ctx.subagents;
|
|
2656
|
+
if (!service || typeof service.sendMessage !== 'function') {
|
|
2657
|
+
return {
|
|
2658
|
+
ok: false,
|
|
2659
|
+
code: 'NO_SUBAGENT_SERVICE',
|
|
2660
|
+
error: '当前部署没有可用的 subagent 服务,无法投递 follow-up',
|
|
2661
|
+
};
|
|
2662
|
+
}
|
|
2663
|
+
try {
|
|
2664
|
+
const messageId = await service.sendMessage(agent, childId, [{ type: 'text', text: message }], { signal });
|
|
2665
|
+
return { ok: true, sessionId: childId, messageId: String(messageId ?? '') };
|
|
2666
|
+
}
|
|
2667
|
+
catch (error) {
|
|
2668
|
+
return {
|
|
2669
|
+
ok: false,
|
|
2670
|
+
code: 'DELIVERY_FAILED',
|
|
2671
|
+
sessionId: childId,
|
|
2672
|
+
error: truncate(error instanceof Error ? error.message : String(error), 500),
|
|
2673
|
+
};
|
|
2674
|
+
}
|
|
2675
|
+
}
|
|
2676
|
+
async function dispatchTool(agent, args, signal) {
|
|
2677
|
+
const session = agent?.session;
|
|
2678
|
+
if (!session)
|
|
2679
|
+
throw new PlanError('只能在会话内派发计划', 'NO_SESSION');
|
|
2680
|
+
if (!isRootSession(session))
|
|
1853
2681
|
throw new PlanError('子 Agent 不能派发主计划', 'NOT_ROOT');
|
|
1854
2682
|
let record = state.records.get(session.id);
|
|
1855
2683
|
const requestedPlanId = typeof args?.planId === 'string' ? args.planId : undefined;
|
|
@@ -1889,6 +2717,41 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
1889
2717
|
if (args?.planId && record.plan.planId !== args.planId) {
|
|
1890
2718
|
throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH');
|
|
1891
2719
|
}
|
|
2720
|
+
/*
|
|
2721
|
+
* [1.8.15] Cancelled is terminal: dispatch must refuse, not resurrect.
|
|
2722
|
+
*
|
|
2723
|
+
* T4e F1/C16 proved the old path answered `ok: true` and really started
|
|
2724
|
+
* department Agents on a cancelled plan (`activationCalled: true`), and a
|
|
2725
|
+
* 2/2-done cancelled plan was silently rewritten to `phase: done`. Cancel
|
|
2726
|
+
* is the user's stop signal; the only honest answer is a refusal that says
|
|
2727
|
+
* how to continue deliberately (a new plan, or the main Agent takes over).
|
|
2728
|
+
*/
|
|
2729
|
+
if (isTerminalPhase(record.phase) || record.cancelled === true) {
|
|
2730
|
+
/*
|
|
2731
|
+
* [1.9.0] 终态集合:cancelled(用户撤销)与 superseded(责任已转移)
|
|
2732
|
+
* 都不允许派发、不允许复活。superseded 用独立拒绝码,便于调用方区分
|
|
2733
|
+
* 「用户叫停」与「已被别的计划承接」。cancelled 的返回体与 1.8.19 相同。
|
|
2734
|
+
*/
|
|
2735
|
+
const superseded = record.phase === 'superseded';
|
|
2736
|
+
const snapshot = derivePlanSnapshot(record.statuses);
|
|
2737
|
+
return {
|
|
2738
|
+
ok: false,
|
|
2739
|
+
planId: record.plan.planId,
|
|
2740
|
+
phase: superseded ? 'superseded' : 'cancelled',
|
|
2741
|
+
running: false,
|
|
2742
|
+
alreadyRunning: false,
|
|
2743
|
+
complete: false,
|
|
2744
|
+
remaining: Math.max(0, Number(snapshot.stats.total ?? 0) - Number(snapshot.stats.done ?? 0)),
|
|
2745
|
+
stats: snapshot.stats,
|
|
2746
|
+
code: superseded ? 'PLAN_SUPERSEDED' : 'PLAN_CANCELLED',
|
|
2747
|
+
error: superseded
|
|
2748
|
+
? '计划已被取代:不会再启动任何部门 Agent'
|
|
2749
|
+
: '计划已取消:取消只停止执行,不会再启动任何部门 Agent',
|
|
2750
|
+
hint: superseded
|
|
2751
|
+
? '不要再次派发。被取代不等于完成:如需交付,请按覆盖链核对承接计划的证据;承接计划未就绪时不得调用 present。'
|
|
2752
|
+
: '不要再次派发。如需继续这项工作,请向用户确认后重新生成计划;或由主 Agent 直接接手剩余项,并在答复中说明这是直接执行而非派发。',
|
|
2753
|
+
};
|
|
2754
|
+
}
|
|
1892
2755
|
/*
|
|
1893
2756
|
* [1.7.0] Two dispatch modes.
|
|
1894
2757
|
*
|
|
@@ -2049,6 +2912,8 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
2049
2912
|
mode: 'async',
|
|
2050
2913
|
running: true,
|
|
2051
2914
|
alreadyRunning: false,
|
|
2915
|
+
complete: false,
|
|
2916
|
+
remaining: Math.max(0, Number(live.stats.total ?? 0) - Number(live.stats.done ?? 0)),
|
|
2052
2917
|
phase: record.phase,
|
|
2053
2918
|
startedAt,
|
|
2054
2919
|
stats: live.stats,
|
|
@@ -2066,8 +2931,754 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
2066
2931
|
*/
|
|
2067
2932
|
return dispatchSnapshotOf(record);
|
|
2068
2933
|
}
|
|
2934
|
+
/*
|
|
2935
|
+
* [1.8.7] 回合收尾前的强制闸门——「未完成即输出」的根治点。
|
|
2936
|
+
*
|
|
2937
|
+
* 事故(session-99984ebd…,2026-10-31)里,模型在计划 10/13 时 present 了
|
|
2938
|
+
* 报告并给出收尾答复。插件原来只订阅 `agent/pre-step`,回合结束完全不受
|
|
2939
|
+
* 约束;预算暂停只写了一句「可续跑」,没有任何强制力。
|
|
2940
|
+
*
|
|
2941
|
+
* 官方 harness 为此提供了确切扩展点 `agent/turn-stopping`(@deepseek-ai/dsh-agent
|
|
2942
|
+
* 的 runtime-types 原文:「Awaited before the boundary commits — a listener
|
|
2943
|
+
* that objects steers (agent.steer(...)) and the machine re-reads its inbox:
|
|
2944
|
+
* fresh steering runs another step, none closes the turn.」)。同仓的
|
|
2945
|
+
* dsh-workspace-changes 就注册在插件根 ctx 上,证明该 agent 作用域事件能到
|
|
2946
|
+
* 达根监听器。
|
|
2947
|
+
*
|
|
2948
|
+
* 规则:
|
|
2949
|
+
* - 只看根会话、只看本回合真实任务(state.activeTurns),社交/状态型回合不打扰;
|
|
2950
|
+
* - 降级记录(没有计划)不拦;空计划也不拦(present 仍会拒绝);
|
|
2951
|
+
* - 后台派发仍在跑 ⇒ 先等它结束再判断,绝不让「已结束 ∧ 正在做」复活;
|
|
2952
|
+
* - 计划未通过交付就绪检查(含未完成、证据缺口、已取消但未完成)⇒
|
|
2953
|
+
* `agent.steer()` 一条明确的「禁止收尾」指令,每个回合最多 2 次。
|
|
2954
|
+
*
|
|
2955
|
+
* [1.8.13] 取消不再等于放行。
|
|
2956
|
+
*
|
|
2957
|
+
* 1.8.8 的闸门只问“还有没有 pending/in_progress”,所以全 done 但证据是
|
|
2958
|
+
* legacy/空验收的计划、以及 cancelled 的计划都会安静收尾并声称完成
|
|
2959
|
+
* (T5-B/C/D)。现在闸门与 present 共用 `deliveryReadiness`:凡是能拦住
|
|
2960
|
+
* 交付的缺口,也能拦住“这个回合就这么结束”。取消分支不再要求续跑,
|
|
2961
|
+
* 只要求按未完成口径如实收尾,所以不会空转。
|
|
2962
|
+
*/
|
|
2963
|
+
const STOP_STEER_LIMIT = 2;
|
|
2964
|
+
function recordReadiness(record) {
|
|
2965
|
+
const snapshot = derivePlanSnapshot(record.statuses);
|
|
2966
|
+
return deliveryReadiness(snapshot, { phase: record.phase });
|
|
2967
|
+
}
|
|
2968
|
+
function stopGateApplies(record, session, turn) {
|
|
2969
|
+
if (!record?.plan)
|
|
2970
|
+
return false;
|
|
2971
|
+
if (record.degraded)
|
|
2972
|
+
return false;
|
|
2973
|
+
/*
|
|
2974
|
+
* [1.9.0] 终态不再触发收尾 steer —— 这正是死锁的第二个出口(T8 I7)。
|
|
2975
|
+
* cancelled 只有在本回合被结构化点名时才提醒一次(present 仍会硬拦);
|
|
2976
|
+
* superseded 不 steer:它的判定对象是承接计划,present 的拒绝文案已给出出路。
|
|
2977
|
+
*/
|
|
2978
|
+
if (isTerminalPhase(record.phase)) {
|
|
2979
|
+
return record.phase === 'cancelled'
|
|
2980
|
+
&& Boolean(session && turn && planIdFromTurn(session, turn) === record.plan.planId);
|
|
2981
|
+
}
|
|
2982
|
+
const readiness = recordReadiness(record);
|
|
2983
|
+
if (Number(readiness.total ?? 0) === 0)
|
|
2984
|
+
return false;
|
|
2985
|
+
return !readiness.ready;
|
|
2986
|
+
}
|
|
2987
|
+
function planChildIds(record) {
|
|
2988
|
+
const ids = new Set();
|
|
2989
|
+
for (const item of record?.statuses ?? []) {
|
|
2990
|
+
if (typeof item?.childId === 'string' && item.childId)
|
|
2991
|
+
ids.add(item.childId);
|
|
2992
|
+
}
|
|
2993
|
+
for (const stage of record?.plan?.stages ?? []) {
|
|
2994
|
+
for (const subtask of stage?.subtasks ?? []) {
|
|
2995
|
+
if (typeof subtask?.childId === 'string' && subtask.childId)
|
|
2996
|
+
ids.add(subtask.childId);
|
|
2997
|
+
}
|
|
2998
|
+
}
|
|
2999
|
+
return ids;
|
|
3000
|
+
}
|
|
3001
|
+
const PLAN_CONTINUATION_KINDS = new Set(['subagent-settled', 'workplan-result', 'workplan-continue']);
|
|
3002
|
+
/**
|
|
3003
|
+
* [1.8.9] 子会话谱系判定。
|
|
3004
|
+
*
|
|
3005
|
+
* `childId` 在预算重置时会被清空(`applyStatus({status:'pending'})` 走
|
|
3006
|
+
* `normaliseStatusEntry` 强制 childId=null),事故里的 T11 因此不在
|
|
3007
|
+
* planChildIds 中,turn 2 又一次绕过闸门。`header.parentSession` 是子会话
|
|
3008
|
+
* 自身的身份,预算与重启都不会改写它,用它旁证“这条结算来自本计划的执行者”。
|
|
3009
|
+
*/
|
|
3010
|
+
function isChildSessionOf(senderId, session) {
|
|
3011
|
+
if (!senderId)
|
|
3012
|
+
return false;
|
|
3013
|
+
try {
|
|
3014
|
+
const child = ctx.sessions?.get?.(senderId);
|
|
3015
|
+
const header = child?.header;
|
|
3016
|
+
if (!header)
|
|
3017
|
+
return false;
|
|
3018
|
+
return header.parentSession === session.id;
|
|
3019
|
+
}
|
|
3020
|
+
catch {
|
|
3021
|
+
return false;
|
|
3022
|
+
}
|
|
3023
|
+
}
|
|
3024
|
+
/**
|
|
3025
|
+
* [1.8.11] 用父会话自己的 `subagent/catalog` 事件认亲。
|
|
3026
|
+
*
|
|
3027
|
+
* `subagent-settled` 到达时子会话已经被 dispose(dsh-subagent 的
|
|
3028
|
+
* `finishDisposal` 先 `handle.dispose()` 再 `notifySettlement`),
|
|
3029
|
+
* `ctx.sessions.get(senderId)` 必然拿不到 header,1.8.9 的谱系判定因此
|
|
3030
|
+
* 在真实生命周期下恒为 false。spawn 记录却留在父会话的事件流里,重启、
|
|
3031
|
+
* 回放、预算重置都不会改写它,是唯一持久可靠的父链证据。
|
|
3032
|
+
*/
|
|
3033
|
+
const spawnedChildCache = new Map();
|
|
3034
|
+
function spawnedChildIds(session) {
|
|
3035
|
+
const cached = spawnedChildCache.get(session.id);
|
|
3036
|
+
if (cached && cached.at === session.seq)
|
|
3037
|
+
return cached.ids;
|
|
3038
|
+
const ids = new Set();
|
|
3039
|
+
if (typeof session?.eventAt === 'function') {
|
|
3040
|
+
for (let i = 0; i < session.seq; i += 1) {
|
|
3041
|
+
let event;
|
|
3042
|
+
try {
|
|
3043
|
+
event = session.eventAt(i);
|
|
3044
|
+
}
|
|
3045
|
+
catch {
|
|
3046
|
+
continue;
|
|
3047
|
+
}
|
|
3048
|
+
if (event?.type === 'subagent/catalog' && typeof event.data?.childId === 'string') {
|
|
3049
|
+
ids.add(event.data.childId);
|
|
3050
|
+
}
|
|
3051
|
+
}
|
|
3052
|
+
}
|
|
3053
|
+
spawnedChildCache.set(session.id, { at: session.seq, ids });
|
|
3054
|
+
return ids;
|
|
3055
|
+
}
|
|
3056
|
+
/*
|
|
3057
|
+
* [1.8.14] N5:结算回合要判的是「这条结算对应的计划」,不是「最后生成的计划」。
|
|
3058
|
+
*
|
|
3059
|
+
* 重启后内存为空时,收尾闸门原本走默认回放(最后一个 plan 消息):事故会话在
|
|
3060
|
+
* A 未完成时又生成了 B,A 的结果随后到达,闸门于是按 B 判定。结算输入
|
|
3061
|
+
* (workplan-result)自带 planId;显式传 planId 还能触发 1.8.10 的窗口前移,
|
|
3062
|
+
* 旧计划落在 2000 事件窗口外时也能重建。
|
|
3063
|
+
*/
|
|
3064
|
+
function planIdFromTurn(session, turn) {
|
|
3065
|
+
if (typeof session?.eventAt !== 'function' || !(turn >= 1))
|
|
3066
|
+
return undefined;
|
|
3067
|
+
let started = -1;
|
|
3068
|
+
for (let i = session.seq - 1; i >= 0; i -= 1) {
|
|
3069
|
+
const event = session.eventAt(i);
|
|
3070
|
+
if (event?.type === 'turn/start' && Number(event.data?.turn) === turn) {
|
|
3071
|
+
started = i;
|
|
3072
|
+
break;
|
|
3073
|
+
}
|
|
3074
|
+
}
|
|
3075
|
+
if (started < 0)
|
|
3076
|
+
return undefined;
|
|
3077
|
+
for (let i = started + 1; i < session.seq; i += 1) {
|
|
3078
|
+
const event = session.eventAt(i);
|
|
3079
|
+
if (!event)
|
|
3080
|
+
continue;
|
|
3081
|
+
if (event.type === 'turn/end' && Number(event.data?.turn) === turn)
|
|
3082
|
+
break;
|
|
3083
|
+
if (event.type !== 'user/message')
|
|
3084
|
+
continue;
|
|
3085
|
+
const data = event.data?.message ?? event.data;
|
|
3086
|
+
if (!data || typeof data !== 'object')
|
|
3087
|
+
continue;
|
|
3088
|
+
/*
|
|
3089
|
+
* planId 不在信封上:结果消息的 planId 在正文标记之间的 JSON 里,
|
|
3090
|
+
* plan 消息的 planId 在 plan 对象里。两者都走已有的解析器,避免
|
|
3091
|
+
* 对消息形状再发明一套假设。
|
|
3092
|
+
*/
|
|
3093
|
+
const result = parseResultMessage(data);
|
|
3094
|
+
if (result && typeof result.planId === 'string' && result.planId)
|
|
3095
|
+
return result.planId;
|
|
3096
|
+
const planMessage = parseWorkplanMessage(data);
|
|
3097
|
+
const planId = planMessage?.plan?.planId;
|
|
3098
|
+
if (typeof planId === 'string' && planId)
|
|
3099
|
+
return planId;
|
|
3100
|
+
}
|
|
3101
|
+
return undefined;
|
|
3102
|
+
}
|
|
3103
|
+
/**
|
|
3104
|
+
* [1.8.15] 当前正在进行的回合号;没有打开中的回合时返回 undefined。
|
|
3105
|
+
*
|
|
3106
|
+
* `present` 的闸门需要知道「这一回合在结算哪个计划」。默认回放回答的是
|
|
3107
|
+
* 「最后定义的计划」,在 A 定义、B 后定义、A 的结果在 B 之后到达时会判错
|
|
3108
|
+
* 计划(T3 B5)。这里不新增状态,只从会话尾部回扫 `turn/start`;遇到
|
|
3109
|
+
* `turn/end` 说明当前没有打开中的回合。
|
|
3110
|
+
*/
|
|
3111
|
+
function currentTurnOf(session) {
|
|
3112
|
+
if (typeof session?.eventAt !== 'function')
|
|
3113
|
+
return undefined;
|
|
3114
|
+
for (let i = session.seq - 1; i >= 0; i -= 1) {
|
|
3115
|
+
let event;
|
|
3116
|
+
try {
|
|
3117
|
+
event = session.eventAt(i);
|
|
3118
|
+
}
|
|
3119
|
+
catch {
|
|
3120
|
+
return undefined;
|
|
3121
|
+
}
|
|
3122
|
+
if (!event)
|
|
3123
|
+
continue;
|
|
3124
|
+
if (event.type === 'turn/start') {
|
|
3125
|
+
const turn = Number(event.data?.turn);
|
|
3126
|
+
return Number.isFinite(turn) && turn >= 1 ? turn : undefined;
|
|
3127
|
+
}
|
|
3128
|
+
if (event.type === 'turn/end')
|
|
3129
|
+
return undefined;
|
|
3130
|
+
}
|
|
3131
|
+
return undefined;
|
|
3132
|
+
}
|
|
3133
|
+
/**
|
|
3134
|
+
* [1.8.8] 结算/结果唤醒的回合也属于“本回合的任务”。
|
|
3135
|
+
*
|
|
3136
|
+
* 事故 turn 2 由 `subagent-settled` 消息唤醒:它不是 human task,
|
|
3137
|
+
* `humanMessages()` 不认,`maybePlan()` 不会写 `state.activeTurns`,
|
|
3138
|
+
* 收尾闸门因此在 turn 2 直接放行,模型又在 11/13 时收尾。
|
|
3139
|
+
* 这里按会话事件判断“这一回合是否装载了本计划的续跑输入”,
|
|
3140
|
+
* 只认三类来源,且子 Agent 结算必须来自本计划派出过的 child,
|
|
3141
|
+
* 避免无关后台任务把闸门误激活。
|
|
3142
|
+
*/
|
|
3143
|
+
function turnCarriesPlanWork(session, turn, record) {
|
|
3144
|
+
if (typeof session?.eventAt !== 'function' || !(turn >= 1))
|
|
3145
|
+
return false;
|
|
3146
|
+
const childIds = planChildIds(record);
|
|
3147
|
+
let started = -1;
|
|
3148
|
+
for (let i = session.seq - 1; i >= 0; i -= 1) {
|
|
3149
|
+
const event = session.eventAt(i);
|
|
3150
|
+
if (event?.type === 'turn/start' && Number(event.data?.turn) === turn) {
|
|
3151
|
+
started = i;
|
|
3152
|
+
break;
|
|
3153
|
+
}
|
|
3154
|
+
}
|
|
3155
|
+
if (started < 0)
|
|
3156
|
+
return false;
|
|
3157
|
+
for (let i = started + 1; i < session.seq; i += 1) {
|
|
3158
|
+
const event = session.eventAt(i);
|
|
3159
|
+
if (!event)
|
|
3160
|
+
continue;
|
|
3161
|
+
if (event.type === 'turn/end' && Number(event.data?.turn) === turn)
|
|
3162
|
+
break;
|
|
3163
|
+
if (event.type !== 'user/message')
|
|
3164
|
+
continue;
|
|
3165
|
+
const message = event.data?.message ?? event.data;
|
|
3166
|
+
const source = message?.source ?? {};
|
|
3167
|
+
const kind = String(source.kind ?? '');
|
|
3168
|
+
if (!PLAN_CONTINUATION_KINDS.has(kind))
|
|
3169
|
+
continue;
|
|
3170
|
+
if (kind === 'subagent-settled') {
|
|
3171
|
+
const sender = String(source.senderSessionId ?? '');
|
|
3172
|
+
/*
|
|
3173
|
+
* 只认“本计划派出过的 child”“本会话的真实子会话”或“父会话 spawn
|
|
3174
|
+
* 记录里出现过的 child”。第三者是 dispose 之后唯一还能取到的证据;
|
|
3175
|
+
* 三者都不命中时,无关后台任务不能把闸门误激活。
|
|
3176
|
+
*/
|
|
3177
|
+
if (!childIds.has(sender) && !isChildSessionOf(sender, session) && !spawnedChildIds(session).has(sender))
|
|
3178
|
+
continue;
|
|
3179
|
+
}
|
|
3180
|
+
return true;
|
|
3181
|
+
}
|
|
3182
|
+
return false;
|
|
3183
|
+
}
|
|
3184
|
+
async function onTurnStopping(payload) {
|
|
3185
|
+
try {
|
|
3186
|
+
const agent = payload?.agent;
|
|
3187
|
+
const session = agent?.session;
|
|
3188
|
+
if (!agent || !session || !isRootSession(session))
|
|
3189
|
+
return;
|
|
3190
|
+
if (typeof agent.steer !== 'function')
|
|
3191
|
+
return;
|
|
3192
|
+
const turn = Number(payload?.turn ?? 0);
|
|
3193
|
+
const known = state.records.get(session.id);
|
|
3194
|
+
/*
|
|
3195
|
+
* [1.8.8] 不再只认 human task 标记的 activeTurns:结算唤醒的回合
|
|
3196
|
+
* (subagent-settled / workplan-result / workplan-continue)同样装载
|
|
3197
|
+
* 了本计划的续跑输入,必须受同一道收尾闸门约束。
|
|
3198
|
+
*/
|
|
3199
|
+
if (state.activeTurns?.get?.(session.id) !== turn && !turnCarriesPlanWork(session, turn, known))
|
|
3200
|
+
return;
|
|
3201
|
+
if (isPlanModeActive(ctx, session))
|
|
3202
|
+
return;
|
|
3203
|
+
let record = known;
|
|
3204
|
+
if (!record?.plan) {
|
|
3205
|
+
// [1.8.14] N5:优先按本回合结算消息里点名的计划重建,而不是最后生成的计划。
|
|
3206
|
+
record = reconstructFromSession(session, planIdFromTurn(session, turn));
|
|
3207
|
+
if (record?.plan)
|
|
3208
|
+
state.records.set(session.id, record);
|
|
3209
|
+
}
|
|
3210
|
+
if (!stopGateApplies(record, session, turn))
|
|
3211
|
+
return;
|
|
3212
|
+
if (record.dispatchPromise) {
|
|
3213
|
+
try {
|
|
3214
|
+
await record.dispatchPromise;
|
|
3215
|
+
}
|
|
3216
|
+
catch {
|
|
3217
|
+
/* the failure is already on record.errors; the gate only needs the outcome */
|
|
3218
|
+
}
|
|
3219
|
+
finishRound(record, session);
|
|
3220
|
+
if (!stopGateApplies(record, session, turn))
|
|
3221
|
+
return;
|
|
3222
|
+
}
|
|
3223
|
+
const book = record.stopSteers && record.stopSteers.turn === turn
|
|
3224
|
+
? record.stopSteers
|
|
3225
|
+
: { turn, count: 0 };
|
|
3226
|
+
if (book.count >= STOP_STEER_LIMIT)
|
|
3227
|
+
return;
|
|
3228
|
+
book.count += 1;
|
|
3229
|
+
record.stopSteers = book;
|
|
3230
|
+
const snapshot = derivePlanSnapshot(record.statuses);
|
|
3231
|
+
agent.steer(makeUserMessage(buildStopSteerText({
|
|
3232
|
+
planId: record.plan.planId,
|
|
3233
|
+
phase: record.phase,
|
|
3234
|
+
stats: snapshot.stats,
|
|
3235
|
+
statuses: snapshot.statuses,
|
|
3236
|
+
attempt: book.count,
|
|
3237
|
+
}), {
|
|
3238
|
+
kind: 'workplan-continue',
|
|
3239
|
+
form: 'notice',
|
|
3240
|
+
summary: `【计划未就绪】${snapshot.stats.done}/${snapshot.stats.total},本回合被要求按未完成口径收尾或继续`,
|
|
3241
|
+
}));
|
|
3242
|
+
ctx.logger?.warn?.(`dsh-workplan: 计划 ${record.plan.planId} 未通过交付就绪检查(${snapshot.stats.done}/${snapshot.stats.total}),`
|
|
3243
|
+
+ `已在回合收尾前要求继续/如实收尾(第 ${book.count} 次)`);
|
|
3244
|
+
}
|
|
3245
|
+
catch (error) {
|
|
3246
|
+
ctx.logger?.warn?.(`dsh-workplan: 回合收尾检查失败:${error instanceof Error ? error.message : String(error)}`);
|
|
3247
|
+
}
|
|
3248
|
+
}
|
|
3249
|
+
/**
|
|
3250
|
+
* [1.8.8] present 的硬闸门:计划未完成时不允许把产物作为成品交付。
|
|
3251
|
+
*
|
|
3252
|
+
* 1.8.7 只把这条规则写进提示词;事故里模型在回合中途直接 present,
|
|
3253
|
+
* 交付卡片先出现、收尾闸门后到,卡片无法撤回。这里在工具执行前拒绝,
|
|
3254
|
+
* 与回合闸门形成前后两道防线。
|
|
3255
|
+
*
|
|
3256
|
+
* [1.8.13] 判据换成与回合闸门同一个 `deliveryReadiness`。
|
|
3257
|
+
*
|
|
3258
|
+
* 1.8.9 只拦三类硬缺口(自检失败/验收失败/产物缺失),而把 legacy、
|
|
3259
|
+
* unverified、空 acceptance、undefined verification 当作“软缺口”放行;
|
|
3260
|
+
* 同时 `planIncomplete` 对 cancelled 直接返回 false,于是“取消 1/3 再
|
|
3261
|
+
* present”也能过(T5-C)。这两条都被本会话的行为探针证实。现在:
|
|
3262
|
+
* - 只有 `deliveryReady === true` 才能 present;
|
|
3263
|
+
* - 取消、降级(有 plan 时)、全 blocked、全 done 但无结构化证据一律拒绝;
|
|
3264
|
+
* - 拒绝文案必须给出可执行的出路(dispatch / update 补证 / 改 blocked),
|
|
3265
|
+
* cancel 不再被写成交付许可。
|
|
3266
|
+
*/
|
|
3267
|
+
/**
|
|
3268
|
+
* [1.8.16] 会话里所有「定义过」的计划。
|
|
3269
|
+
*
|
|
3270
|
+
* `reconstructFromSession(session)` 只回答「默认该看哪个计划」,而 `present`
|
|
3271
|
+
* 需要回答「会话里还有没有没交付完的计划」。1.8.15 的活体 E2E 暴露了这个差
|
|
3272
|
+
* 距:wp-6753e19f 停在 13/14,但最后定义的计划已就绪,`present` 仍然交付了
|
|
3273
|
+
* 报告。这里按日志里出现的 planId 逐个重建;数量极少(本会话只有 4 个),
|
|
3274
|
+
* 每个重建各自带回扫窗口,因此旧计划不会因为超过 2000 事件而消失。
|
|
3275
|
+
*/
|
|
3276
|
+
function sessionPlanRecords(session) {
|
|
3277
|
+
if (typeof session?.eventAt !== 'function')
|
|
3278
|
+
return [];
|
|
3279
|
+
const ids = new Set();
|
|
3280
|
+
for (let i = 0; i < session.seq; i += 1) {
|
|
3281
|
+
let event;
|
|
3282
|
+
try {
|
|
3283
|
+
event = session.eventAt(i);
|
|
3284
|
+
}
|
|
3285
|
+
catch {
|
|
3286
|
+
continue;
|
|
3287
|
+
}
|
|
3288
|
+
if (!event || event.type !== 'user/message')
|
|
3289
|
+
continue;
|
|
3290
|
+
const planId = parseWorkplanMessage(event.data)?.plan?.planId;
|
|
3291
|
+
if (typeof planId === 'string' && planId)
|
|
3292
|
+
ids.add(planId);
|
|
3293
|
+
}
|
|
3294
|
+
const records = [];
|
|
3295
|
+
for (const planId of ids) {
|
|
3296
|
+
const record = reconstructFromSession(session, planId);
|
|
3297
|
+
if (record?.plan)
|
|
3298
|
+
records.push(record);
|
|
3299
|
+
}
|
|
3300
|
+
return records;
|
|
3301
|
+
}
|
|
3302
|
+
/**
|
|
3303
|
+
* [1.8.18] The last plan that actually defines work, for the restart replay.
|
|
3304
|
+
*
|
|
3305
|
+
* The gate used to fall back only to the live record or the turn's plan. After
|
|
3306
|
+
* a restart both are gone, so a session whose last action was cancelling an
|
|
3307
|
+
* unfinished plan allowed `present` — contradicting the cancel tool's own
|
|
3308
|
+
* contract ("取消后如仍有未完成项或证据缺口,present 仍会被拒绝"). T5 E1/E6
|
|
3309
|
+
* pinned that hole.
|
|
3310
|
+
*
|
|
3311
|
+
* Empty plans are skipped: they are not delivery objects (U6), and accepting
|
|
3312
|
+
* one as "the last plan" would let a builder cancel real work and define an
|
|
3313
|
+
* empty plan as a shield. Older cancelled plans still do not block a newer
|
|
3314
|
+
* plan, so cancelling a stale plan does not deadlock the session.
|
|
3315
|
+
*/
|
|
3316
|
+
function lastGateablePlanRecord(session) {
|
|
3317
|
+
if (typeof session?.eventAt !== 'function')
|
|
3318
|
+
return undefined;
|
|
3319
|
+
for (let i = session.seq - 1; i >= 0; i -= 1) {
|
|
3320
|
+
let event;
|
|
3321
|
+
try {
|
|
3322
|
+
event = session.eventAt(i);
|
|
3323
|
+
}
|
|
3324
|
+
catch {
|
|
3325
|
+
continue;
|
|
3326
|
+
}
|
|
3327
|
+
if (!event || event.type !== 'user/message')
|
|
3328
|
+
continue;
|
|
3329
|
+
const plan = parseWorkplanMessage(event.data)?.plan;
|
|
3330
|
+
if (!plan || typeof plan.planId !== 'string' || plan.planId === '')
|
|
3331
|
+
continue;
|
|
3332
|
+
if (definedSubtaskCount(plan) === 0)
|
|
3333
|
+
continue;
|
|
3334
|
+
const record = reconstructFromSession(session, plan.planId);
|
|
3335
|
+
if (record?.plan && definedSubtaskCount(record.plan) > 0)
|
|
3336
|
+
return record;
|
|
3337
|
+
}
|
|
3338
|
+
return undefined;
|
|
3339
|
+
}
|
|
3340
|
+
/**
|
|
3341
|
+
* [1.9.0] 点名 superseded 时的覆盖链判定(T8 §4.2 第 4 条、§6.3)。
|
|
3342
|
+
*
|
|
3343
|
+
* superseded 只是「责任已转移」,不是完成:本回合点名它时,判的是承接计划
|
|
3344
|
+
* 是否真的就绪。承接计划缺失/已终止/无法复核 ⇒ fail-closed(SUPERSEDED_STALE);
|
|
3345
|
+
* 承接计划未就绪 ⇒ 拒绝;只有承接计划 deliveryReady 才放行(产物来自承接计划)。
|
|
3346
|
+
*
|
|
3347
|
+
* [1.9.2] 返回值带上拒绝码(T8 §4.3 `judgeEffective`):覆盖链无法复核
|
|
3348
|
+
* ⇒ `SUPERSEDED_STALE`;覆盖链有效但承接计划未就绪 ⇒ `ACTIVE_NOT_READY`。
|
|
3349
|
+
* 文案保持逐字不变,码值走 `src/plan.ts` 的同一组常量。
|
|
3350
|
+
*/
|
|
3351
|
+
function supersededDenialVerdict(session, record) {
|
|
3352
|
+
const planId = record.plan?.planId ?? record.planId ?? '';
|
|
3353
|
+
const by = record.supersededBy;
|
|
3354
|
+
const successorPlanId = typeof by?.successorPlanId === 'string' && by.successorPlanId
|
|
3355
|
+
? by.successorPlanId
|
|
3356
|
+
: typeof by?.planId === 'string' ? by.planId : '';
|
|
3357
|
+
if (!successorPlanId) {
|
|
3358
|
+
return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE, `计划 ${planId} 已被取代,但缺少可验证的承接计划(supersededBy.successorPlanId):`
|
|
3359
|
+
+ '覆盖证据失效(SUPERSEDED_STALE),不得调用 present;请向用户说明覆盖链无法复核并重新确认交付对象。');
|
|
3360
|
+
}
|
|
3361
|
+
/*
|
|
3362
|
+
* [W1] 覆盖摘要:present 复验从 mapping 重算摘要,不读缓存数值(T8 §6.3)。
|
|
3363
|
+
*
|
|
3364
|
+
* 摘要一旦对不上(含 mapping/digest 缺失),覆盖记录就无法复核 —— 无法复核
|
|
3365
|
+
* ≠ 通过,一律 stale。这条检查只证明「存下来的 mapping 没被改动」,不证明
|
|
3366
|
+
* 「两项工作在语义上等价」;后者仍只能由用户确认(V8)承载。
|
|
3367
|
+
*/
|
|
3368
|
+
const mapping = by?.mapping;
|
|
3369
|
+
if (!Array.isArray(mapping)) {
|
|
3370
|
+
return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE, `计划 ${planId} 已被取代,但缺少可复算的逐项映射(supersededBy.mapping):`
|
|
3371
|
+
+ '覆盖证据失效(SUPERSEDED_STALE),不得调用 present,不得声称“已完成/最终版/已交付”;'
|
|
3372
|
+
+ '请重新按用户确认的逐项映射做覆盖迁移,并由运行时写入复算后的 digest。');
|
|
3373
|
+
}
|
|
3374
|
+
const computedDigest = computeMappingDigest(mapping);
|
|
3375
|
+
if (!verifyMappingDigest(mapping, by?.digest)) {
|
|
3376
|
+
const stored = typeof by?.digest === 'string' ? by.digest.slice(0, 15) : '缺失';
|
|
3377
|
+
return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE, `计划 ${planId} 已被取代,但覆盖证据摘要与逐项映射不一致(supersededBy.digest=${stored},`
|
|
3378
|
+
+ `重算=${computedDigest.slice(0, 15)}):覆盖证据失效(SUPERSEDED_STALE),不得调用 present,`
|
|
3379
|
+
+ '不得声称“已完成/最终版/已交付”;请重新按用户确认的逐项映射做覆盖迁移,并由运行时复算 digest。');
|
|
3380
|
+
}
|
|
3381
|
+
const successor = reconstructFromSession(session, successorPlanId);
|
|
3382
|
+
if (!successor?.plan || definedSubtaskCount(successor.plan) === 0 || isTerminalPhase(successor.phase)) {
|
|
3383
|
+
return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE, `计划 ${planId} 已被取代,但承接计划 ${successorPlanId} 不存在、不是交付对象或已终止:`
|
|
3384
|
+
+ '覆盖证据失效(SUPERSEDED_STALE)。被取代不等于完成:不得调用 present,不得声称“已完成/最终版/已交付”。');
|
|
3385
|
+
}
|
|
3386
|
+
const readiness = deliveryReadiness(derivePlanSnapshot(successor.statuses), { phase: successor.phase });
|
|
3387
|
+
if (!readiness.ready) {
|
|
3388
|
+
const ids = readiness.remaining.slice(0, 10).join('、');
|
|
3389
|
+
return presentDenial(PRESENT_DENY_CODES.ACTIVE_NOT_READY, `计划 ${planId} 已被取代,承接计划 ${successorPlanId} 只完成 ${readiness.done}/${readiness.total}`
|
|
3390
|
+
+ `${ids ? `,剩余 ${readiness.remaining.length} 项(${ids})` : ''}。`
|
|
3391
|
+
+ '被取代不等于完成:承接计划通过交付就绪检查之前不得调用 present。');
|
|
3392
|
+
}
|
|
3393
|
+
return undefined;
|
|
3394
|
+
}
|
|
3395
|
+
/**
|
|
3396
|
+
* [1.9.2] present 拒绝点的唯一出口:码值取常量,拒绝文案保持逐字不变。
|
|
3397
|
+
*
|
|
3398
|
+
* host 的 guard 契约是 `string`(`ctx.tools.checkGuards`),所以工具错误里
|
|
3399
|
+
* 仍只有文案;码值由 `presentDenialVerdict` 一并返回,供断言、日志与后续
|
|
3400
|
+
* UI 使用。所有分支都必须经由这里,不要在分支里手写码值。
|
|
3401
|
+
*/
|
|
3402
|
+
function presentDenial(code, message) {
|
|
3403
|
+
return { code, message };
|
|
3404
|
+
}
|
|
3405
|
+
function presentDenialVerdict(agent) {
|
|
3406
|
+
const session = agent?.session;
|
|
3407
|
+
if (!session || !isRootSession(session))
|
|
3408
|
+
return undefined;
|
|
3409
|
+
if (isPlanModeActive(ctx, session))
|
|
3410
|
+
return undefined;
|
|
3411
|
+
/*
|
|
3412
|
+
* [1.8.16] Every plan in the session matters, not just the turn's plan.
|
|
3413
|
+
*
|
|
3414
|
+
* 1.8.15 taught this gate to prefer the plan named by the current turn's
|
|
3415
|
+
* messages, but a session can hold several plans at once (the incident
|
|
3416
|
+
* session itself ended with four). A live E2E on 1.8.15 showed the hole:
|
|
3417
|
+
* wp-6753e19f was still 13/14, the last defined plan was ready, and
|
|
3418
|
+
* `present` delivered the report. The gate now asks every plan in the log;
|
|
3419
|
+
* `dsh_workplan_cancel` is the documented escape hatch for a plan that
|
|
3420
|
+
* will not be finished.
|
|
3421
|
+
*/
|
|
3422
|
+
const turn = currentTurnOf(session);
|
|
3423
|
+
const turnPlanId = turn ? planIdFromTurn(session, turn) : undefined;
|
|
3424
|
+
const candidates = sessionPlanRecords(session);
|
|
3425
|
+
const live = state.records.get(session.id);
|
|
3426
|
+
if (live?.plan && !candidates.some((item) => item.plan.planId === live.plan.planId))
|
|
3427
|
+
candidates.push(live);
|
|
3428
|
+
if (turnPlanId && !candidates.some((item) => item.plan.planId === turnPlanId)) {
|
|
3429
|
+
const named = reconstructFromSession(session, turnPlanId);
|
|
3430
|
+
if (named?.plan)
|
|
3431
|
+
candidates.push(named);
|
|
3432
|
+
}
|
|
3433
|
+
if (candidates.length === 0)
|
|
3434
|
+
return undefined;
|
|
3435
|
+
/*
|
|
3436
|
+
* [U6] a plan with zero defined subtasks is not a delivery object.
|
|
3437
|
+
* `deliveryReadiness` can never call it ready (`total > 0`), so judging it
|
|
3438
|
+
* only produced the false refusal "0 个子任务虽都已 done". Filter by the
|
|
3439
|
+
* definition itself — not by `statuses.length` — so a real plan whose
|
|
3440
|
+
* statuses failed to derive is still judged (and stays closed).
|
|
3441
|
+
*/
|
|
3442
|
+
const gateable = candidates.filter((item) => definedSubtaskCount(item.plan) > 0);
|
|
3443
|
+
if (gateable.length === 0)
|
|
3444
|
+
return undefined;
|
|
3445
|
+
const unresolved = gateable
|
|
3446
|
+
.map((item) => ({
|
|
3447
|
+
record: item,
|
|
3448
|
+
readiness: deliveryReadiness(derivePlanSnapshot(item.statuses), { phase: item.phase }),
|
|
3449
|
+
}))
|
|
3450
|
+
/*
|
|
3451
|
+
* A cancelled plan is not a delivery blocker for *other* plans — the
|
|
3452
|
+
* incident session accumulates cancelled plans that will never be
|
|
3453
|
+
* finished, and blocking on them forever would deadlock delivery. It is
|
|
3454
|
+
* still checked below when it is the plan this turn (or the live record,
|
|
3455
|
+
* or the last defined plan after a restart) is about: cancel stops
|
|
3456
|
+
* execution, it does not make the work deliverable.
|
|
3457
|
+
*/
|
|
3458
|
+
.filter((entry) => !isTerminalPhase(entry.record.phase) && !entry.readiness.ready);
|
|
3459
|
+
if (unresolved.length > 1) {
|
|
3460
|
+
const lines = unresolved.slice(0, 6).map((entry) => {
|
|
3461
|
+
const ids = entry.readiness.remaining.slice(0, 6).join('、');
|
|
3462
|
+
const suffix = ids ? `(${ids}${entry.readiness.remaining.length > 6 ? '…' : ''})` : '';
|
|
3463
|
+
const gaps = entry.readiness.blockers.slice(0, 4).join(';');
|
|
3464
|
+
return `- 计划 ${entry.record.plan.planId}:完成 ${entry.readiness.done}/${entry.readiness.total}${suffix}`
|
|
3465
|
+
+ `${gaps ? `;证据缺口:${gaps}` : ''}`;
|
|
3466
|
+
});
|
|
3467
|
+
return presentDenial(PRESENT_DENY_CODES.ACTIVE_NOT_READY, `本会话还有 ${unresolved.length} 个计划未通过交付就绪检查:\n${lines.join('\n')}\n`
|
|
3468
|
+
+ '在它们全部通过交付就绪检查之前,不得调用 present 交付任何产物:'
|
|
3469
|
+
+ '先调用 dsh_workplan_dispatch 续跑,证据缺口用 dsh_workplan_update 补齐。'
|
|
3470
|
+
+ '取消只停止执行,不会让未完成的计划变成可交付,也不能用来绕过这道检查。');
|
|
3471
|
+
}
|
|
3472
|
+
let record;
|
|
3473
|
+
let readiness;
|
|
3474
|
+
if (unresolved.length === 1) {
|
|
3475
|
+
record = unresolved[0].record;
|
|
3476
|
+
readiness = unresolved[0].readiness;
|
|
3477
|
+
}
|
|
3478
|
+
else {
|
|
3479
|
+
/*
|
|
3480
|
+
* No unfinished active plan. The plan this turn is about (or the live
|
|
3481
|
+
* record) may still be a cancelled one that never finished — T5-C pins
|
|
3482
|
+
* that `present` must be refused for it. After a restart neither exists,
|
|
3483
|
+
* so fall back to the last plan that defines work; otherwise the
|
|
3484
|
+
* sequence "cancel an unfinished plan, restart, present" silently
|
|
3485
|
+
* bypasses the cancel tool's own contract (T5 E1/E6).
|
|
3486
|
+
*/
|
|
3487
|
+
record = state.records.get(session.id);
|
|
3488
|
+
if (turnPlanId)
|
|
3489
|
+
record = reconstructFromSession(session, turnPlanId) ?? record;
|
|
3490
|
+
if (!record?.plan)
|
|
3491
|
+
record = lastGateablePlanRecord(session);
|
|
3492
|
+
if (!record?.plan)
|
|
3493
|
+
return undefined;
|
|
3494
|
+
if (definedSubtaskCount(record.plan) === 0)
|
|
3495
|
+
return undefined;
|
|
3496
|
+
/*
|
|
3497
|
+
* [1.9.0] 终态解耦(T8 §4.3 P3):终态计划不再被自动选为判定对象。
|
|
3498
|
+
*
|
|
3499
|
+
* 只有「本回合结构化点名」时才判定;否则不再写回 live、不再拦截其它
|
|
3500
|
+
* 计划的交付。取消 ≠ 完成:记录仍是 cancelled 0/N,只是不再永久挡门。
|
|
3501
|
+
*/
|
|
3502
|
+
const namedThisTurn = Boolean(turnPlanId && record.plan.planId === turnPlanId);
|
|
3503
|
+
if (isTerminalPhase(record.phase) && !namedThisTurn)
|
|
3504
|
+
return undefined;
|
|
3505
|
+
if (record.phase === 'superseded') {
|
|
3506
|
+
const denial = supersededDenialVerdict(session, record);
|
|
3507
|
+
if (denial)
|
|
3508
|
+
return denial;
|
|
3509
|
+
return undefined;
|
|
3510
|
+
}
|
|
3511
|
+
readiness = deliveryReadiness(derivePlanSnapshot(record.statuses), { phase: record.phase });
|
|
3512
|
+
if (readiness.ready)
|
|
3513
|
+
return undefined;
|
|
3514
|
+
}
|
|
3515
|
+
if (record?.plan && !isTerminalPhase(record.phase))
|
|
3516
|
+
state.records.set(session.id, record);
|
|
3517
|
+
const snapshot = derivePlanSnapshot(record.statuses);
|
|
3518
|
+
const planId = record.plan?.planId ?? record.planId;
|
|
3519
|
+
const ids = readiness.remaining.slice(0, 10).join('、');
|
|
3520
|
+
const idSuffix = ids ? `(${ids}${readiness.remaining.length > 10 ? '…' : ''})` : '';
|
|
3521
|
+
const blockers = readiness.blockers.slice(0, 10).join(';');
|
|
3522
|
+
if (readiness.cancelled) {
|
|
3523
|
+
/*
|
|
3524
|
+
* [1.8.13] `deliveryReadiness` already puts the cancellation fact at the
|
|
3525
|
+
* head of `blockers`; repeating it here produced the T6b/C0 copy with the
|
|
3526
|
+
* same sentence twice. Only the *evidence* gaps belong in this suffix.
|
|
3527
|
+
*/
|
|
3528
|
+
const gaps = readiness.blockers
|
|
3529
|
+
.filter((line) => !line.startsWith('计划已取消但只完成'))
|
|
3530
|
+
.slice(0, 10)
|
|
3531
|
+
.join(';');
|
|
3532
|
+
if (readiness.remaining.length === 0) {
|
|
3533
|
+
return presentDenial(PRESENT_DENY_CODES.CANCELLED_NAMED, `计划 ${planId} 已取消,${readiness.total} 个子任务虽已 done,但证据未通过:${gaps || '缺少结构化证据'}。`
|
|
3534
|
+
+ '取消只停止执行,不等于完成:不得调用 present,不得声称“已完成/最终版/已交付”;'
|
|
3535
|
+
+ '答复必须说明取消状态与证据缺口,不能写成“全部完成”。');
|
|
3536
|
+
}
|
|
3537
|
+
return presentDenial(PRESENT_DENY_CODES.CANCELLED_NAMED, `计划 ${planId} 已取消,但只完成 ${readiness.done}/${readiness.total},剩余 ${readiness.remaining.length} 项${idSuffix}`
|
|
3538
|
+
+ `${gaps ? `;证据缺口:${gaps}` : ''}。`
|
|
3539
|
+
+ '取消只停止执行,不等于完成,也不会让未完成项变成可交付:不得调用 present,不得声称“已完成/最终版/已交付”;'
|
|
3540
|
+
+ '答复开头必须写「未完成:剩余 N 项(列出 ID)与原因」。');
|
|
3541
|
+
}
|
|
3542
|
+
/*
|
|
3543
|
+
* [1.9.2] P1 的单一映射:`activeDenyCode` 只看就绪结果。
|
|
3544
|
+
* `remaining` 为空但 `blockers` 非空 ⇒ `EVIDENCE_GAP`(T9 C05 的修法);
|
|
3545
|
+
* 还有子任务没做完 ⇒ `ACTIVE_NOT_READY`。两个分支共用同一个码值来源。
|
|
3546
|
+
*/
|
|
3547
|
+
const activeCode = activeDenyCode(readiness);
|
|
3548
|
+
if (readiness.remaining.length === 0) {
|
|
3549
|
+
return presentDenial(activeCode, `计划 ${planId} 的 ${readiness.total} 个子任务虽都已 done,但证据未通过:${blockers || '缺少结构化证据'}。`
|
|
3550
|
+
+ '在 deliveryReady 变为 true 之前,产物不得作为成品交付:'
|
|
3551
|
+
+ "用 dsh_workplan_update 为这些子任务补 verification='structured' 与 acceptance(每项 result='pass' 并附证据),"
|
|
3552
|
+
+ '或把对应子任务改回 blocked 并写明原因;不要调用 present。');
|
|
3553
|
+
}
|
|
3554
|
+
return presentDenial(activeCode, `计划 ${planId} 未完成:完成 ${readiness.done}/${readiness.total},剩余 ${readiness.remaining.length} 项${idSuffix}`
|
|
3555
|
+
+ `${blockers ? `;另有证据缺口:${blockers}` : ''}。`
|
|
3556
|
+
+ '在计划通过交付就绪检查之前不得调用 present 交付产物:先调用 dsh_workplan_dispatch 续跑剩余项;'
|
|
3557
|
+
+ '证据缺口用 dsh_workplan_update 补齐;确实无法继续时,把答复写成「未完成:剩余 N 项与原因」。'
|
|
3558
|
+
+ '取消只停止执行,不会改变“未完成”的结论。');
|
|
3559
|
+
}
|
|
3560
|
+
/**
|
|
3561
|
+
* 兼容入口:host 的 guard 只接受字符串,所以工具错误仍是原来的文案。
|
|
3562
|
+
* 需要码值时调用 `presentDenialVerdict`。
|
|
3563
|
+
*/
|
|
3564
|
+
function presentDenialReason(agent) {
|
|
3565
|
+
return presentDenialVerdict(agent)?.message;
|
|
3566
|
+
}
|
|
3567
|
+
/*
|
|
3568
|
+
* [1.8.18] 已交付文件的写保护(T7-N2)。
|
|
3569
|
+
*
|
|
3570
|
+
* `present` 不复制内容(工具描述原文:the user opens the current files),
|
|
3571
|
+
* write/edit 也不校验路径是否已经交付。事故的迟到回合在 12:13 两次原地改写
|
|
3572
|
+
* 12:04 已 present 的报告,卡片背后的文件因此变了。这里把「present 时点
|
|
3573
|
+
* 已经定义过的计划」记到路径上:只要这些计划至今仍未通过交付就绪检查,
|
|
3574
|
+
* 根会话对同一路径的 write/edit 就被拒绝。present 之后才定义的新计划不在
|
|
3575
|
+
* 集合里,所以“用户要求改版 → 新计划”不会被写保护卡死;cancel 仍是显式出路。
|
|
3576
|
+
*/
|
|
3577
|
+
const presentedPaths = new Map();
|
|
3578
|
+
function canonicalPath(session, value) {
|
|
3579
|
+
if (typeof value !== 'string' || value.trim() === '')
|
|
3580
|
+
return undefined;
|
|
3581
|
+
if (isAbsolute(value))
|
|
3582
|
+
return resolve(value);
|
|
3583
|
+
const cwd = session?.header?.cwd ?? options.cwd;
|
|
3584
|
+
return typeof cwd === 'string' && cwd ? resolve(cwd, value) : undefined;
|
|
3585
|
+
}
|
|
3586
|
+
function presentedEntries(session) {
|
|
3587
|
+
if (typeof session?.eventAt !== 'function' || !(Number(session.seq) >= 0))
|
|
3588
|
+
return [];
|
|
3589
|
+
const cache = presentedPaths.get(session.id);
|
|
3590
|
+
const reusable = cache !== undefined && cache.scannedTo <= Number(session.seq);
|
|
3591
|
+
const from = reusable ? cache.scannedTo : 0;
|
|
3592
|
+
const seen = new Set(reusable ? cache.planIds : []);
|
|
3593
|
+
const entries = reusable ? cache.entries.slice() : [];
|
|
3594
|
+
for (let i = from; i < Number(session.seq); i += 1) {
|
|
3595
|
+
let event;
|
|
3596
|
+
try {
|
|
3597
|
+
event = session.eventAt(i);
|
|
3598
|
+
}
|
|
3599
|
+
catch {
|
|
3600
|
+
continue;
|
|
3601
|
+
}
|
|
3602
|
+
if (!event)
|
|
3603
|
+
continue;
|
|
3604
|
+
if (event.type === 'user/message') {
|
|
3605
|
+
const planId = parseWorkplanMessage(event.data)?.plan?.planId;
|
|
3606
|
+
if (typeof planId === 'string' && planId)
|
|
3607
|
+
seen.add(planId);
|
|
3608
|
+
continue;
|
|
3609
|
+
}
|
|
3610
|
+
if (event.type !== 'deliverables/presented')
|
|
3611
|
+
continue;
|
|
3612
|
+
const planIds = [...seen];
|
|
3613
|
+
for (const file of event.data?.files ?? []) {
|
|
3614
|
+
if (typeof file?.path !== 'string' || file.path.trim() === '')
|
|
3615
|
+
continue;
|
|
3616
|
+
entries.push({ raw: file.path, canonical: canonicalPath(session, file.path), planIds });
|
|
3617
|
+
}
|
|
3618
|
+
}
|
|
3619
|
+
presentedPaths.set(session.id, {
|
|
3620
|
+
scannedTo: Number(session.seq),
|
|
3621
|
+
planIds: seen,
|
|
3622
|
+
entries,
|
|
3623
|
+
});
|
|
3624
|
+
return entries;
|
|
3625
|
+
}
|
|
3626
|
+
function recordForPlan(session, planId) {
|
|
3627
|
+
const live = state.records.get(session.id);
|
|
3628
|
+
if (live?.plan?.planId === planId)
|
|
3629
|
+
return live;
|
|
3630
|
+
return reconstructFromSession(session, planId);
|
|
3631
|
+
}
|
|
3632
|
+
function presentedWriteDenialReason(agent, args) {
|
|
3633
|
+
const session = agent?.session;
|
|
3634
|
+
if (!session || !isRootSession(session))
|
|
3635
|
+
return undefined;
|
|
3636
|
+
if (isPlanModeActive(ctx, session))
|
|
3637
|
+
return undefined;
|
|
3638
|
+
const entries = presentedEntries(session);
|
|
3639
|
+
if (entries.length === 0)
|
|
3640
|
+
return undefined;
|
|
3641
|
+
const requested = args?.file_path ?? args?.path;
|
|
3642
|
+
if (typeof requested !== 'string' || requested.trim() === '')
|
|
3643
|
+
return undefined;
|
|
3644
|
+
const canonical = canonicalPath(session, requested);
|
|
3645
|
+
const matched = entries.filter((entry) => entry.raw === requested
|
|
3646
|
+
|| (canonical !== undefined && entry.canonical !== undefined && entry.canonical === canonical));
|
|
3647
|
+
if (matched.length === 0)
|
|
3648
|
+
return undefined;
|
|
3649
|
+
const planIds = new Set();
|
|
3650
|
+
for (const entry of matched)
|
|
3651
|
+
for (const planId of entry.planIds)
|
|
3652
|
+
planIds.add(planId);
|
|
3653
|
+
if (planIds.size === 0)
|
|
3654
|
+
return undefined;
|
|
3655
|
+
const unresolved = [...planIds]
|
|
3656
|
+
.map((planId) => recordForPlan(session, planId))
|
|
3657
|
+
.filter((record) => record?.plan
|
|
3658
|
+
&& !isTerminalPhase(record.phase)
|
|
3659
|
+
&& !deliveryReadiness(derivePlanSnapshot(record.statuses), { phase: record.phase }).ready);
|
|
3660
|
+
if (unresolved.length === 0)
|
|
3661
|
+
return undefined;
|
|
3662
|
+
const ids = unresolved.slice(0, 4).map((record) => record.plan.planId);
|
|
3663
|
+
return `文件 ${requested} 已通过 present 交付给用户,而交付时点已存在的计划`
|
|
3664
|
+
+ `${ids.length ? ` ${ids.join('、')}` : ''} 仍未通过交付就绪检查。`
|
|
3665
|
+
+ '计划未就绪期间不得原地改写已交付文件:先调用 dsh_workplan_dispatch 续跑剩余项,'
|
|
3666
|
+
+ '完成后重新 present 新版本;确实不做的计划用 dsh_workplan_cancel 显式取消。'
|
|
3667
|
+
+ '(present 之后新建的计划不受此限制。)';
|
|
3668
|
+
}
|
|
2069
3669
|
function plansPayload(sessionId) {
|
|
2070
|
-
|
|
3670
|
+
/*
|
|
3671
|
+
* [1.8.15] The feed must carry build identity too.
|
|
3672
|
+
*
|
|
3673
|
+
* `status` learned version/runtime in 1.8.14, but the Web UI reads this
|
|
3674
|
+
* feed only — so after a rebuild the card could not tell "the process is
|
|
3675
|
+
* still running yesterday's bytes" (T5c §6.2). Same helpers, one source.
|
|
3676
|
+
*/
|
|
3677
|
+
return {
|
|
3678
|
+
...buildPlansPayload(ctx, state, sessionId),
|
|
3679
|
+
version: pluginVersion,
|
|
3680
|
+
runtime: runtimeIdentity(),
|
|
3681
|
+
};
|
|
2071
3682
|
}
|
|
2072
3683
|
async function route(req, res, connectionCtx = ctx) {
|
|
2073
3684
|
applyHardeningHeaders(res);
|
|
@@ -2140,10 +3751,16 @@ export function createWorkplanRuntime(ctx, options = {}) {
|
|
|
2140
3751
|
state,
|
|
2141
3752
|
limits,
|
|
2142
3753
|
onPreStep,
|
|
3754
|
+
onTurnStopping,
|
|
3755
|
+
presentDenialReason,
|
|
3756
|
+
presentDenialVerdict,
|
|
3757
|
+
supersededDenialVerdict,
|
|
3758
|
+
presentedWriteDenialReason,
|
|
2143
3759
|
updateStatus,
|
|
2144
3760
|
cancelPlan,
|
|
2145
3761
|
dispatchTool,
|
|
2146
3762
|
statusTool,
|
|
3763
|
+
followupTool,
|
|
2147
3764
|
plansPayload,
|
|
2148
3765
|
route,
|
|
2149
3766
|
dispose,
|
|
@@ -2201,6 +3818,17 @@ async function maybePlan(ctx, state, payload, downstream, options) {
|
|
|
2201
3818
|
return downstream;
|
|
2202
3819
|
if (isStatusQuestion(taskText))
|
|
2203
3820
|
return downstream;
|
|
3821
|
+
/*
|
|
3822
|
+
* [1.8.7] Remember that this turn carries a real task.
|
|
3823
|
+
*
|
|
3824
|
+
* `agent/turn-stopping` must only object on turns whose plan belongs to the
|
|
3825
|
+
* user's actual request. A plan left paused in an earlier turn must not turn
|
|
3826
|
+
* every later "谢谢/进度如何" turn into a forced 20-minute dispatch, so the
|
|
3827
|
+
* stop gate reads this marker and stays silent on social or status turns.
|
|
3828
|
+
*/
|
|
3829
|
+
if (!state.activeTurns)
|
|
3830
|
+
state.activeTurns = new Map();
|
|
3831
|
+
state.activeTurns.set(session.id, Number(payload.turn ?? 0));
|
|
2204
3832
|
const conversationContext = recentConversation(session);
|
|
2205
3833
|
const existing = state.records.get(session.id);
|
|
2206
3834
|
if (existing?.plan?.createdTurn === payload.turn)
|
|
@@ -2213,7 +3841,13 @@ async function maybePlan(ctx, state, payload, downstream, options) {
|
|
|
2213
3841
|
// A plan committed but not yet dispatched must not be overwritten in the
|
|
2214
3842
|
// same turn; a later turn may supersede it, otherwise one abandoned plan
|
|
2215
3843
|
// would lock planning forever.
|
|
2216
|
-
|
|
3844
|
+
//
|
|
3845
|
+
// [1.9.2] 自动覆盖路径**只允许**写 cancelled,永不写 superseded(规则设计
|
|
3846
|
+
// §7.1:自动路径没有逐项映射与用户确认,满足不了 V4–V8)。它也不得把已经
|
|
3847
|
+
// superseded 的终态记录改回 cancelled:内存写 cancelled、日志里仍是
|
|
3848
|
+
// supersede 信封,会让 live 与 replay 分叉。终态记录由 present 的终态解耦
|
|
3849
|
+
// 处理(不再自动挡门),不需要在这里「取消」。
|
|
3850
|
+
if (existing?.plan && !existing.dispatchedAt && !isTerminalPhase(existing.phase)) {
|
|
2217
3851
|
if (existing.plan.createdTurn === payload.turn)
|
|
2218
3852
|
return downstream;
|
|
2219
3853
|
existing.phase = 'cancelled';
|
|
@@ -2378,6 +4012,10 @@ export function updateToolOutputSchema() {
|
|
|
2378
4012
|
subtaskId: { type: 'string' },
|
|
2379
4013
|
status: { type: 'string' },
|
|
2380
4014
|
stats: { type: 'object' },
|
|
4015
|
+
deliveryReady: { type: 'boolean' },
|
|
4016
|
+
deliveryBlockers: { type: 'array' },
|
|
4017
|
+
deliveryRemaining: { type: 'array' },
|
|
4018
|
+
hint: { type: 'string' },
|
|
2381
4019
|
},
|
|
2382
4020
|
required: ['ok'],
|
|
2383
4021
|
additionalProperties: true,
|
|
@@ -2391,6 +4029,44 @@ export function cancelToolOutputSchema() {
|
|
|
2391
4029
|
planId: { type: 'string' },
|
|
2392
4030
|
phase: { type: 'string' },
|
|
2393
4031
|
reason: { type: 'string' },
|
|
4032
|
+
/*
|
|
4033
|
+
* [1.8.14] `cancelRecorded` is the difference between "the UI says
|
|
4034
|
+
* cancelled" and "a restart will still say cancelled". A cancel whose
|
|
4035
|
+
* durable append failed reports false so the caller does not build on it.
|
|
4036
|
+
*/
|
|
4037
|
+
cancelRecorded: { type: 'boolean' },
|
|
4038
|
+
alreadyCancelled: { type: 'boolean' },
|
|
4039
|
+
abortedRunning: { type: 'boolean' },
|
|
4040
|
+
/*
|
|
4041
|
+
* [1.9.2] `disposition="superseded"` answers. `supersedeRecorded` is the
|
|
4042
|
+
* durable-write witness for the supersede envelope (the cancelled answer
|
|
4043
|
+
* uses `cancelRecorded`); `alreadySuperseded` is the §7.4 idempotent
|
|
4044
|
+
* re-submission. `code` carries the SUPERSEDE_* refusal; `gaps` /
|
|
4045
|
+
* `missingFrom` / `problems` explain exactly which V-rule failed so a
|
|
4046
|
+
* caller can repair the mapping instead of guessing.
|
|
4047
|
+
*/
|
|
4048
|
+
disposition: { type: 'string' },
|
|
4049
|
+
supersededAt: { type: 'number' },
|
|
4050
|
+
supersedeRecorded: { type: 'boolean' },
|
|
4051
|
+
alreadySuperseded: { type: 'boolean' },
|
|
4052
|
+
coverage: { type: 'string' },
|
|
4053
|
+
requiredCount: { type: 'number' },
|
|
4054
|
+
coveredCount: { type: 'number' },
|
|
4055
|
+
successorSeenAtSeq: { type: 'number' },
|
|
4056
|
+
confirmedAtSeq: { type: 'number' },
|
|
4057
|
+
supersededBy: {
|
|
4058
|
+
type: 'object',
|
|
4059
|
+
properties: {
|
|
4060
|
+
planId: { type: 'string' },
|
|
4061
|
+
},
|
|
4062
|
+
additionalProperties: true,
|
|
4063
|
+
},
|
|
4064
|
+
code: { type: 'string' },
|
|
4065
|
+
error: { type: 'string' },
|
|
4066
|
+
hint: { type: 'string' },
|
|
4067
|
+
gaps: { type: 'array', items: { type: 'string' } },
|
|
4068
|
+
missingFrom: { type: 'array', items: { type: 'string' } },
|
|
4069
|
+
problems: { type: 'array', items: { type: 'string' } },
|
|
2394
4070
|
},
|
|
2395
4071
|
required: ['ok'],
|
|
2396
4072
|
additionalProperties: true,
|
|
@@ -2411,6 +4087,13 @@ export function statusToolOutputSchema() {
|
|
|
2411
4087
|
statuses: { type: 'array' },
|
|
2412
4088
|
errors: { type: 'array' },
|
|
2413
4089
|
resumeLimit: { type: 'number' },
|
|
4090
|
+
version: { type: 'string' },
|
|
4091
|
+
// [1.8.14] Loaded-build identity: version alone cannot prove which bytes
|
|
4092
|
+
// the process is running after a rebuild or a profile recomposition.
|
|
4093
|
+
runtime: { type: 'object' },
|
|
4094
|
+
deliveryReady: { type: 'boolean' },
|
|
4095
|
+
deliveryBlockers: { type: 'array' },
|
|
4096
|
+
deliveryRemaining: { type: 'array' },
|
|
2414
4097
|
hint: { type: 'string' },
|
|
2415
4098
|
error: { type: 'string' },
|
|
2416
4099
|
code: { type: 'string' },
|
|
@@ -2430,6 +4113,18 @@ export function dispatchToolOutputSchema() {
|
|
|
2430
4113
|
running: { type: 'boolean' },
|
|
2431
4114
|
joined: { type: 'boolean' },
|
|
2432
4115
|
mode: { type: 'string' },
|
|
4116
|
+
/*
|
|
4117
|
+
* [1.8.7] `ok:true` used to be the only success signal, so a budget pause
|
|
4118
|
+
* (10/13) read as a finished dispatch. `complete` is the field the model
|
|
4119
|
+
* must test before it presents anything.
|
|
4120
|
+
*/
|
|
4121
|
+
complete: { type: 'boolean' },
|
|
4122
|
+
remaining: { type: 'integer' },
|
|
4123
|
+
deliveryReady: { type: 'boolean' },
|
|
4124
|
+
deliveryBlockers: { type: 'array' },
|
|
4125
|
+
deliveryRemaining: { type: 'array' },
|
|
4126
|
+
version: { type: 'string' },
|
|
4127
|
+
runtime: { type: 'object' },
|
|
2433
4128
|
elapsedMs: { type: 'number' },
|
|
2434
4129
|
statuses: { type: 'array' },
|
|
2435
4130
|
phase: { type: 'string' },
|