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/src/runtime.ts
CHANGED
|
@@ -28,18 +28,23 @@ import {
|
|
|
28
28
|
buildPlanMessage,
|
|
29
29
|
buildPlannerPrompt,
|
|
30
30
|
buildResultMessage,
|
|
31
|
+
buildStopSteerText,
|
|
31
32
|
createStatuses,
|
|
33
|
+
deliveryReadiness,
|
|
32
34
|
derivePlanSnapshot,
|
|
33
35
|
extractJson,
|
|
34
36
|
flattenSubtasks,
|
|
35
37
|
isRecord,
|
|
36
38
|
isSocialMessage,
|
|
39
|
+
isTerminalPhase,
|
|
37
40
|
isStatusQuestion,
|
|
38
41
|
isVagueContinuation,
|
|
42
|
+
makeUserMessage,
|
|
39
43
|
markDependentsBlocked,
|
|
40
44
|
messageText,
|
|
41
45
|
readySubtasks,
|
|
42
46
|
MAX_PLAN_RESUMES,
|
|
47
|
+
PRESENT_DENY_CODES,
|
|
43
48
|
canResumePlan,
|
|
44
49
|
resetBlockedStatuses,
|
|
45
50
|
parseCancelMessage,
|
|
@@ -51,12 +56,38 @@ import {
|
|
|
51
56
|
validatePlan,
|
|
52
57
|
applyResultStatuses,
|
|
53
58
|
adjudicateResult,
|
|
59
|
+
activeDenyCode,
|
|
54
60
|
MAX_CONVERSATION_CHARS,
|
|
55
61
|
parseUpdateMessage,
|
|
56
62
|
buildUpdateMessage,
|
|
57
63
|
} from './plan.js'
|
|
64
|
+
import type { PresentDenialVerdict, PresentDenyCode } from './plan.js'
|
|
65
|
+
import { computeMappingDigest, verifyMappingDigest } from './supersede-digest.js'
|
|
66
|
+
import { supersedePlanRecord } from './supersede.js'
|
|
58
67
|
import { createProgressWatchdog, describeError } from './watchdog.js'
|
|
59
68
|
|
|
69
|
+
/**
|
|
70
|
+
* [1.8.18] How many subtasks the plan *defines*.
|
|
71
|
+
*
|
|
72
|
+
* `deliveryReadiness` counts the derived statuses, and `ready` requires
|
|
73
|
+
* `total > 0`, so a plan with `stages: []` can never be ready. Such a plan is
|
|
74
|
+
* not a delivery object at all: normal planning rejects it (`validatePlan`),
|
|
75
|
+
* and it can only reach replay from a malformed historical message. Judging it
|
|
76
|
+
* as "0/0 unfinished forever" was U6 (T5 P13): present was refused with the
|
|
77
|
+
* false copy "0 个子任务虽都已 done".
|
|
78
|
+
*
|
|
79
|
+
* A malformed plan that reaches this function still counts as deliverable
|
|
80
|
+
* (`MAX_SAFE_INTEGER`); plans failing reconstruction earlier are dropped by
|
|
81
|
+
* `sessionPlanRecords` — a known fail-open boundary (T5 A9), not closed here.
|
|
82
|
+
*/
|
|
83
|
+
function definedSubtaskCount(plan: any): number {
|
|
84
|
+
try {
|
|
85
|
+
return flattenSubtasks(plan).length
|
|
86
|
+
} catch {
|
|
87
|
+
return Number.MAX_SAFE_INTEGER
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
60
91
|
export const PLANNER_TIMEOUT_MS = 120000
|
|
61
92
|
/**
|
|
62
93
|
* Absolute ceiling for one child execution.
|
|
@@ -320,7 +351,7 @@ async function disposeActivation(activation: any, record: any, subtaskId: string
|
|
|
320
351
|
} catch (error: any) {
|
|
321
352
|
if (!guard?.timedOut) {
|
|
322
353
|
record.errors = [
|
|
323
|
-
...record.errors,
|
|
354
|
+
...(record.errors ?? []),
|
|
324
355
|
`${subtaskId} dispose: ${truncate(String(error?.message ?? error), 300)}`,
|
|
325
356
|
].slice(-20)
|
|
326
357
|
}
|
|
@@ -375,7 +406,7 @@ function writeSubtaskStatus(record: any, subtaskId: any, patch: any, guard: Subt
|
|
|
375
406
|
|
|
376
407
|
function recordSubtaskError(record: any, subtaskId: any, message: any, guard: SubtaskGuard) {
|
|
377
408
|
if (guard.timedOut) return
|
|
378
|
-
record.errors = [...record.errors, `${subtaskId}: ${truncate(message, 500)}`].slice(-20)
|
|
409
|
+
record.errors = [...(record.errors ?? []), `${subtaskId}: ${truncate(message, 500)}`].slice(-20)
|
|
379
410
|
}
|
|
380
411
|
|
|
381
412
|
/**
|
|
@@ -418,6 +449,141 @@ export function checkArtifacts(artifacts: any, cwd: any, artifactExists: any = e
|
|
|
418
449
|
return { artifacts: checked, missingArtifacts }
|
|
419
450
|
}
|
|
420
451
|
|
|
452
|
+
/**
|
|
453
|
+
* [1.8.5] 被中断时,先说清「东西到底写出来没有」。
|
|
454
|
+
*
|
|
455
|
+
* 事故(2026-10-30):一个子 Agent 在 21:34:52 写完了 38KB 交付物,两秒后被
|
|
456
|
+
* 外部中断;插件只留下「结束状态为 aborted」,产物存在与否完全不进判定,主
|
|
457
|
+
* Agent 只能把它当彻底失败,下游 6 个任务跟着停摆。
|
|
458
|
+
*
|
|
459
|
+
* 这里不改变任何判定语义(中断依然记为失败、依然不自动重试),只在报错里
|
|
460
|
+
* 附上一句可核实的事实:该步声明的产物里有哪几个已经在盘上。看到这句话的人
|
|
461
|
+
* 才知道下一步该去核对、改判,而不是白等一次重试。
|
|
462
|
+
*/
|
|
463
|
+
export function probeInterruptedArtifacts(output: any, subtask: any, cwd: any, artifactExists: any = existsSync) {
|
|
464
|
+
const candidates = new Set<string>()
|
|
465
|
+
const collect = (text: any) => {
|
|
466
|
+
if (typeof text !== 'string' || !text) return
|
|
467
|
+
// 文件名可能带中文(本次事故就是「T6_人性博弈推演_20261030.md」这种),
|
|
468
|
+
// 所以字符集必须放行 CJK,否则真正的产物会被当成没写。
|
|
469
|
+
for (const hit of text.matchAll(/[\w\u4e00-\u9fff@.\/-]+\.(?:md|csv|json|html|txt|ts|js|py|ya?ml)/g)) {
|
|
470
|
+
const ref = hit[0].replace(/^\.\//, '')
|
|
471
|
+
// 太短的多半是扩展名碎片(如 “.md”),不足以定位文件。
|
|
472
|
+
if (ref.length > 3) candidates.add(ref)
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
collect(output)
|
|
476
|
+
for (const item of Array.isArray(subtask?.outputs) ? subtask.outputs : []) collect(item)
|
|
477
|
+
const landed: string[] = []
|
|
478
|
+
for (const ref of candidates) {
|
|
479
|
+
const target = resolveArtifactPath(ref, cwd)
|
|
480
|
+
if (!target) continue
|
|
481
|
+
let exists = false
|
|
482
|
+
try {
|
|
483
|
+
exists = artifactExists(target) === true
|
|
484
|
+
} catch {
|
|
485
|
+
exists = false
|
|
486
|
+
}
|
|
487
|
+
if (exists) landed.push(ref)
|
|
488
|
+
if (landed.length >= 6) break
|
|
489
|
+
}
|
|
490
|
+
return landed
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* [1.8.6] Turn "the child was interrupted" into evidence the plan can hold.
|
|
495
|
+
*
|
|
496
|
+
* 1.8.5 only put the landed files into the error string. That helped a human
|
|
497
|
+
* read the message, but the plan still recorded `blocked` with no
|
|
498
|
+
* `artifacts` / `missingArtifacts`, so the dispatcher had nothing to check and
|
|
499
|
+
* cascaded every dependent into `blocked`: one interrupted child still killed
|
|
500
|
+
* its whole downstream. This records the same finding in the status fields the
|
|
501
|
+
* scheduler already understands.
|
|
502
|
+
*
|
|
503
|
+
* It deliberately does NOT change the verdict: an interrupted task stays
|
|
504
|
+
* `blocked` (no auto-retry, no auto-adjudication). It only stops the cascade
|
|
505
|
+
* and leaves the main Agent a factual basis to re-adjudicate.
|
|
506
|
+
*/
|
|
507
|
+
export function probeInterruptedEvidence(output: any, subtask: any, cwd: any, artifactExists: any = existsSync) {
|
|
508
|
+
const landed = probeInterruptedArtifacts(output, subtask, cwd, artifactExists)
|
|
509
|
+
const declared: string[] = []
|
|
510
|
+
for (const item of Array.isArray(subtask?.outputs) ? subtask.outputs : []) {
|
|
511
|
+
for (const hit of String(item).matchAll(/[\w\u4e00-\u9fff@.\/-]+\.(?:md|csv|json|html|txt|ts|js|py|ya?ml)/g)) {
|
|
512
|
+
const ref = hit[0].replace(/^\.\//, '')
|
|
513
|
+
if (ref.length > 3 && !declared.includes(ref)) declared.push(ref)
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
const refs = [...new Set([...declared, ...landed])]
|
|
517
|
+
const artifacts = refs.map((ref) => ({ kind: 'file', ref, exists: landed.includes(ref) }))
|
|
518
|
+
const missingArtifacts = declared.filter((ref) => !landed.includes(ref))
|
|
519
|
+
return { artifacts, missingArtifacts }
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* [1.8.19] Find a subtask definition by id, without assuming the plan is valid.
|
|
524
|
+
*/
|
|
525
|
+
export function findSubtaskById(plan: any, subtaskId: string) {
|
|
526
|
+
for (const stage of Array.isArray(plan?.stages) ? plan.stages : []) {
|
|
527
|
+
for (const subtask of Array.isArray(stage?.subtasks) ? stage.subtasks : []) {
|
|
528
|
+
if (subtask?.id === subtaskId) return subtask
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
return null
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* [1.8.19] A hard per-subtask timeout must not erase what the child already wrote.
|
|
536
|
+
*
|
|
537
|
+
* Real incident (2026-10-31 23:23:38): T11/T12 were aborted by the 900 s
|
|
538
|
+
* per-subtask ceiling four seconds after their deliverables had landed
|
|
539
|
+
* (T11 32,996 B report + 140-row index; T12 51,547 B report). The parent only
|
|
540
|
+
* saw `blocked / 达到执行上限`, with no hint that the files existed, so the same
|
|
541
|
+
* work would be redone from scratch. This probe records the landed declared
|
|
542
|
+
* outputs in the status row and in the error text — it does not change the
|
|
543
|
+
* verdict (a timeout is still `blocked`), it only stops the evidence loss.
|
|
544
|
+
*/
|
|
545
|
+
export function timeoutBlockedPatch(subtask: any, cwd: any, message: string, artifactExists: any = existsSync) {
|
|
546
|
+
const evidence = probeInterruptedEvidence(null, subtask, cwd, artifactExists)
|
|
547
|
+
const landed = evidence.artifacts.filter((item: any) => item?.exists === true).map((item: any) => String(item.ref))
|
|
548
|
+
const artifactNote = landed.length > 0
|
|
549
|
+
? `;该步声明的产物已在盘上:${landed.slice(0, 6).join('、')}(先核对,不要当作从未运行)`
|
|
550
|
+
: ''
|
|
551
|
+
return {
|
|
552
|
+
patch: {
|
|
553
|
+
status: 'blocked',
|
|
554
|
+
progress: 100,
|
|
555
|
+
finishedAt: Date.now(),
|
|
556
|
+
error: message + artifactNote,
|
|
557
|
+
summary: truncate(`未完成:${message}${artifactNote}`, 3000),
|
|
558
|
+
...(evidence.artifacts.length > 0 ? { artifacts: evidence.artifacts } : {}),
|
|
559
|
+
...(evidence.missingArtifacts.length > 0 ? { missingArtifacts: evidence.missingArtifacts } : {}),
|
|
560
|
+
},
|
|
561
|
+
landed,
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* [1.8.19] The round budget reset used to erase every trace of the attempt.
|
|
567
|
+
*
|
|
568
|
+
* The 20-minute `TOTAL_TIMEOUT` branch resets unfinished rows to `pending`, and
|
|
569
|
+
* `applyStatus` (by design) clears `childId / startedAt / finishedAt`. In the
|
|
570
|
+
* 2026-10-31 incident T10 had run for ~19 minutes and had already written its
|
|
571
|
+
* coverage report at 23:06:26 when the budget fired at 23:07:25; the card then
|
|
572
|
+
* said "not started" and the user asked "why did T10 stop by itself". The
|
|
573
|
+
* attempt provenance and any landed declared outputs now travel in the error
|
|
574
|
+
* text, so the reset stays a pause but stops being an erasure.
|
|
575
|
+
*/
|
|
576
|
+
export function budgetResetError(item: any, subtask: any, cwd: any, artifactExists: any = existsSync) {
|
|
577
|
+
const landed = probeInterruptedArtifacts(null, subtask, cwd, artifactExists)
|
|
578
|
+
const parts = ['本轮预算用尽,等待续跑']
|
|
579
|
+
if (item?.childId) parts.push(`上一轮子会话 ${String(item.childId).slice(0, 8)}`)
|
|
580
|
+
if (Number.isFinite(item?.startedAt) && Number.isFinite(item?.finishedAt)) {
|
|
581
|
+
parts.push(`运行 ${Math.max(0, Math.round((Number(item.finishedAt) - Number(item.startedAt)) / 1000))}s`)
|
|
582
|
+
}
|
|
583
|
+
if (landed.length > 0) parts.push(`声明产物已在盘上:${landed.slice(0, 6).join('、')}`)
|
|
584
|
+
return parts.join(';')
|
|
585
|
+
}
|
|
586
|
+
|
|
421
587
|
/**
|
|
422
588
|
* Turn one child output into a status verdict.
|
|
423
589
|
*
|
|
@@ -473,6 +639,15 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
473
639
|
const { parentSignal, deadline, modelSelection, conversationContext = '', child, guard } = options
|
|
474
640
|
let lastError: any = null
|
|
475
641
|
let lastFailure: any = null
|
|
642
|
+
/*
|
|
643
|
+
* [1.8.6] The interrupt has to outlive the thrown error.
|
|
644
|
+
*
|
|
645
|
+
* `interruptedFlag` travels back to the dispatcher (it must not cascade this
|
|
646
|
+
* task's dependents); `interruptedEvidence` is what gets written into the
|
|
647
|
+
* blocked status so the main Agent can re-adjudicate on facts.
|
|
648
|
+
*/
|
|
649
|
+
let interruptedFlag = false
|
|
650
|
+
let interruptedEvidence: { artifacts: any[]; missingArtifacts: string[] } | null = null
|
|
476
651
|
try {
|
|
477
652
|
if (!writeSubtaskStatus(record, subtask.id, {
|
|
478
653
|
status: 'in_progress',
|
|
@@ -482,6 +657,7 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
482
657
|
|
|
483
658
|
for (let attempt = 1; attempt <= 2; attempt += 1) {
|
|
484
659
|
if (guard.timedOut) return
|
|
660
|
+
interruptedEvidence = null
|
|
485
661
|
if (parentSignal.aborted) throw abortError()
|
|
486
662
|
if (Date.now() >= deadline) throw new PlanError('总执行超时', 'TOTAL_TIMEOUT')
|
|
487
663
|
let activation: any = null
|
|
@@ -576,8 +752,30 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
576
752
|
if (guard.timedOut) return
|
|
577
753
|
const output = resultText(result)
|
|
578
754
|
if (result.stopReason !== 'completed') {
|
|
755
|
+
/*
|
|
756
|
+
* [1.8.5] 中断必须自己说出「接下来怎么办」。
|
|
757
|
+
*
|
|
758
|
+
* 2026-10-30 事故:T6 在被外部中断前 2 秒已写出 38KB 交付物,插件只留下
|
|
759
|
+
* 「子 Agent 结束状态为 aborted」,主 Agent 无从知道产物其实已经在盘上,
|
|
760
|
+
* 于是把它当彻底失败处理,并把 6 个下游一起判死。中断类失败要显式提示
|
|
761
|
+
* 「先核对已写出的产物」,并给出据实改判与续跑这两条出口。
|
|
762
|
+
*/
|
|
763
|
+
const interrupted = result.stopReason === 'aborted'
|
|
764
|
+
const landed = interrupted ? probeInterruptedArtifacts(output, subtask, options.cwd, options.artifactExists) : []
|
|
765
|
+
if (interrupted) {
|
|
766
|
+
interruptedFlag = true
|
|
767
|
+
interruptedEvidence = probeInterruptedEvidence(output, subtask, options.cwd, options.artifactExists)
|
|
768
|
+
}
|
|
579
769
|
throw new PlanError(
|
|
580
|
-
`子 Agent 结束状态为 ${result.stopReason}${result.diagnostic ? `:${result.diagnostic}` : ''}
|
|
770
|
+
`子 Agent 结束状态为 ${result.stopReason}${result.diagnostic ? `:${result.diagnostic}` : ''}${
|
|
771
|
+
interrupted
|
|
772
|
+
? `(子 Agent 在完成前被中断:先核对该步声明的产物是否已写出${
|
|
773
|
+
landed.length > 0
|
|
774
|
+
? `——已核到 ${landed.length} 个文件确实在盘上:${landed.join('、')}`
|
|
775
|
+
: ''
|
|
776
|
+
};据实改判,再决定是否续跑)`
|
|
777
|
+
: ''
|
|
778
|
+
}`,
|
|
581
779
|
'CHILD_NOT_COMPLETED',
|
|
582
780
|
)
|
|
583
781
|
}
|
|
@@ -615,7 +813,7 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
615
813
|
const retry = !isAbort && shouldRetryAttempt(error, attempt, remaining, idleTimeoutMs)
|
|
616
814
|
if (retry) {
|
|
617
815
|
record.errors = [
|
|
618
|
-
...record.errors,
|
|
816
|
+
...(record.errors ?? []),
|
|
619
817
|
`${subtask.id}: 第 ${attempt} 次执行失败(${lastFailure.code}),已带上失败原因重试`,
|
|
620
818
|
].slice(-20)
|
|
621
819
|
writeSubtaskStatus(record, subtask.id, { progress: 15 }, guard)
|
|
@@ -623,7 +821,7 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
623
821
|
}
|
|
624
822
|
if (!isAbort && remaining <= idleTimeoutMs && error?.code !== 'CHILD_TIMEOUT') {
|
|
625
823
|
record.errors = [
|
|
626
|
-
...record.errors,
|
|
824
|
+
...(record.errors ?? []),
|
|
627
825
|
`${subtask.id}: 剩余预算不足(${Math.max(0, Math.round(remaining / 1000))}s),未重试`,
|
|
628
826
|
].slice(-20)
|
|
629
827
|
}
|
|
@@ -643,8 +841,18 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
|
|
|
643
841
|
finishedAt: Date.now(),
|
|
644
842
|
error: truncate(message, 2000),
|
|
645
843
|
summary: truncate(`未完成:${message}`, 3000),
|
|
844
|
+
// [1.8.6] A blocked status that carries no evidence is what made the
|
|
845
|
+
// dispatcher treat "interrupted, file on disk" exactly like "produced
|
|
846
|
+
// nothing". Record what was actually found.
|
|
847
|
+
...(interruptedEvidence && interruptedEvidence.artifacts.length > 0
|
|
848
|
+
? { artifacts: interruptedEvidence.artifacts }
|
|
849
|
+
: {}),
|
|
850
|
+
...(interruptedEvidence && interruptedEvidence.missingArtifacts.length > 0
|
|
851
|
+
? { missingArtifacts: interruptedEvidence.missingArtifacts }
|
|
852
|
+
: {}),
|
|
646
853
|
}, guard)
|
|
647
854
|
recordSubtaskError(record, subtask.id, message, guard)
|
|
855
|
+
return interruptedFlag ? { interrupted: true } : undefined
|
|
648
856
|
} catch (error) {
|
|
649
857
|
const message = describeError(error)
|
|
650
858
|
try {
|
|
@@ -685,18 +893,14 @@ async function runSubtask(ctx: any, record: any, stage: any, subtask: any, optio
|
|
|
685
893
|
// plain "too slow" and the next investigation goes down the wrong path.
|
|
686
894
|
const message = `子任务 ${subtask.id} 达到执行上限(${childTimeoutMs}ms),已强制结束`
|
|
687
895
|
try {
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
error: message,
|
|
693
|
-
summary: truncate(`未完成:${message}`, 3000),
|
|
694
|
-
})
|
|
695
|
-
record.errors = [...record.errors, `${subtask.id}: ${message}`].slice(-20)
|
|
896
|
+
// [1.8.19] Keep the evidence of what already landed on disk.
|
|
897
|
+
const { patch } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists)
|
|
898
|
+
record.statuses = applyStatus(record.statuses, subtask.id, patch)
|
|
899
|
+
record.errors = [...(record.errors ?? []), `${subtask.id}: ${patch.error}`].slice(-20)
|
|
696
900
|
record.updatedAt = Date.now()
|
|
697
901
|
} catch (error: any) {
|
|
698
902
|
record.errors = [
|
|
699
|
-
...record.errors,
|
|
903
|
+
...(record.errors ?? []),
|
|
700
904
|
`${subtask.id}: 超时状态写入失败:${truncate(String(error?.message ?? error), 500)}`,
|
|
701
905
|
].slice(-20)
|
|
702
906
|
} finally {
|
|
@@ -710,7 +914,9 @@ async function runSubtask(ctx: any, record: any, stage: any, subtask: any, optio
|
|
|
710
914
|
timer.unref?.()
|
|
711
915
|
})
|
|
712
916
|
try {
|
|
713
|
-
|
|
917
|
+
// [1.8.6] The outcome (`{interrupted:true}`) has to reach the dispatcher;
|
|
918
|
+
// swallowing it here is why an interrupted child looked like any failure.
|
|
919
|
+
return await Promise.race([
|
|
714
920
|
executeSubtask(ctx, record, stage, subtask, {
|
|
715
921
|
...options,
|
|
716
922
|
child,
|
|
@@ -772,6 +978,15 @@ export function modelStatusLines(statuses: any) {
|
|
|
772
978
|
summary: truncate(item.summary ?? item.error ?? '', 2000),
|
|
773
979
|
error: item.error ?? null,
|
|
774
980
|
verification: item.verification ?? null,
|
|
981
|
+
// [1.8.13] The model must see *which* acceptance item failed, not just the
|
|
982
|
+
// verdict; it cannot repair a gap it cannot name.
|
|
983
|
+
acceptance: Array.isArray(item.acceptance)
|
|
984
|
+
? item.acceptance.slice(0, 8).map((entry: any) => ({
|
|
985
|
+
criterion: truncate(String(entry?.criterion ?? ''), 200),
|
|
986
|
+
result: String(entry?.result ?? ''),
|
|
987
|
+
evidence: truncate(String(entry?.evidence ?? ''), 300),
|
|
988
|
+
}))
|
|
989
|
+
: [],
|
|
775
990
|
revision: Number(item.revision ?? 0),
|
|
776
991
|
updatedBy: item.updatedBy ?? null,
|
|
777
992
|
missingArtifacts: Array.isArray(item.missingArtifacts) ? item.missingArtifacts : [],
|
|
@@ -796,6 +1011,42 @@ export function buildRoundResult(record: any, sessionId: any, limits: any) {
|
|
|
796
1011
|
})
|
|
797
1012
|
}
|
|
798
1013
|
|
|
1014
|
+
/**
|
|
1015
|
+
* [1.8.6] Explain why a `pending` task cannot run, instead of calling it blocked.
|
|
1016
|
+
*
|
|
1017
|
+
* A single generic sentence made three different situations indistinguishable:
|
|
1018
|
+
* a budget pause (nothing ran yet), an upstream whose declared file is missing
|
|
1019
|
+
* (the work may well be done), and a genuinely failed upstream. The main Agent
|
|
1020
|
+
* read all three as "7 卡住了" and had to re-derive the cause by hand.
|
|
1021
|
+
*/
|
|
1022
|
+
function describePendingCause(plan: any, statuses: any[], id: string): string {
|
|
1023
|
+
const byId = new Map<string, any>(statuses.map((item: any) => [item.subtaskId, item]))
|
|
1024
|
+
const entry = flattenSubtasks(plan).find((candidate: any) => candidate.subtask.id === id)
|
|
1025
|
+
if (!entry) return '计划里找不到该步骤'
|
|
1026
|
+
const declared: string[] = Array.isArray(entry.subtask.dependsOn) ? entry.subtask.dependsOn : []
|
|
1027
|
+
if (declared.length === 0) return '没有上游依赖,但本轮未被调度到'
|
|
1028
|
+
const bad = declared.filter((dep: string) => {
|
|
1029
|
+
const state = byId.get(dep)
|
|
1030
|
+
if (!state || state.status !== 'done') return true
|
|
1031
|
+
if (Array.isArray(state.missingArtifacts) && state.missingArtifacts.length > 0) return true
|
|
1032
|
+
if (state.verification === 'legacy') return true
|
|
1033
|
+
return false
|
|
1034
|
+
})
|
|
1035
|
+
if (bad.length === 0) return '上游都已就绪,但本轮未被调度到'
|
|
1036
|
+
return bad.map((dep: string) => {
|
|
1037
|
+
const state = byId.get(dep)
|
|
1038
|
+
if (!state) return `上游 ${dep} 缺失`
|
|
1039
|
+
if (state.status !== 'done') {
|
|
1040
|
+
return `上游 ${dep} 状态为 ${state.status}${state.error ? `(${String(state.error).slice(0, 80)})` : ''}`
|
|
1041
|
+
}
|
|
1042
|
+
if (Array.isArray(state.missingArtifacts) && state.missingArtifacts.length > 0) {
|
|
1043
|
+
return `上游 ${dep} 的声明产物缺失:${state.missingArtifacts.join('、')}`
|
|
1044
|
+
}
|
|
1045
|
+
if (state.verification === 'legacy') return `上游 ${dep} 完成但未提供结构化证据`
|
|
1046
|
+
return `上游 ${dep} 不可用`
|
|
1047
|
+
}).join(';')
|
|
1048
|
+
}
|
|
1049
|
+
|
|
799
1050
|
export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
800
1051
|
const { agent, signal, modelSelection, cwd, conversationContext = '' } = options
|
|
801
1052
|
const deadline = Date.now() + (options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS)
|
|
@@ -847,6 +1098,16 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
847
1098
|
record.updatedAt = record.dispatchedAt
|
|
848
1099
|
try {
|
|
849
1100
|
let guard = 0
|
|
1101
|
+
/*
|
|
1102
|
+
* [1.8.6] Interrupted tasks are not cascaded.
|
|
1103
|
+
*
|
|
1104
|
+
* The 2026-10-30 incident: one child was interrupted after it had already
|
|
1105
|
+
* written its deliverable; the dispatcher blocked its 6 dependents. Those
|
|
1106
|
+
* children were never given a chance, and the plan looked like a 7-task
|
|
1107
|
+
* failure. Keep the interrupted task itself `blocked` (its verdict must not
|
|
1108
|
+
* be rewritten automatically), but leave dependents `pending` and say why.
|
|
1109
|
+
*/
|
|
1110
|
+
const interruptedIds = new Set<string>()
|
|
850
1111
|
while (true) {
|
|
851
1112
|
guard += 1
|
|
852
1113
|
if (guard > 200) throw new PlanError('调度次数异常', 'DISPATCH_LOOP')
|
|
@@ -865,12 +1126,23 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
865
1126
|
}
|
|
866
1127
|
: {})
|
|
867
1128
|
if (ready.length === 0) {
|
|
1129
|
+
/*
|
|
1130
|
+
* [1.8.6] "Nothing is ready" is not the same thing as "everything
|
|
1131
|
+
* failed".
|
|
1132
|
+
*
|
|
1133
|
+
* The old code rewrote every remaining `pending` task to `blocked` with
|
|
1134
|
+
* one generic line ("依赖未完成或上游受阻"). A budget pause, a missing
|
|
1135
|
+
* artifact and a genuinely failed upstream all produced that same
|
|
1136
|
+
* status, the plan turned `blocked`, and a resume was billed against
|
|
1137
|
+
* the failure budget. Keep them `pending`, and record the actual cause.
|
|
1138
|
+
*/
|
|
868
1139
|
const pending = record.statuses.filter((item: any) => item.status === 'pending')
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
1140
|
+
if (pending.length > 0) {
|
|
1141
|
+
const reasons = pending.map((item: any) =>
|
|
1142
|
+
`${item.subtaskId}:${describePendingCause(record.plan, record.statuses, item.subtaskId)}`)
|
|
1143
|
+
const message = `本轮结束,仍有 ${pending.length} 项保持 pending(不是失败,也未级联成 blocked):${reasons.slice(0, 6).join(';')}`
|
|
1144
|
+
record.error = message
|
|
1145
|
+
record.errors = [...(record.errors ?? []), message].slice(-20)
|
|
874
1146
|
}
|
|
875
1147
|
break
|
|
876
1148
|
}
|
|
@@ -881,7 +1153,7 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
881
1153
|
const entry = flattenSubtasks(record.plan)
|
|
882
1154
|
.find((candidate: any) => candidate.subtask.id === item.id)
|
|
883
1155
|
if (!entry) return
|
|
884
|
-
await runSubtask(ctx, record, entry.stage, entry.subtask, {
|
|
1156
|
+
const outcome: any = await runSubtask(ctx, record, entry.stage, entry.subtask, {
|
|
885
1157
|
agent,
|
|
886
1158
|
parentSignal: childController.signal,
|
|
887
1159
|
deadline,
|
|
@@ -893,6 +1165,9 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
893
1165
|
strictEvidence: options.strictEvidence,
|
|
894
1166
|
artifactExists: options.artifactExists,
|
|
895
1167
|
})
|
|
1168
|
+
// [1.8.6] Remember which failures were interrupts, so the cascade below
|
|
1169
|
+
// can leave their dependents pending instead of blaming them.
|
|
1170
|
+
if (outcome && outcome.interrupted) interruptedIds.add(item.id)
|
|
896
1171
|
})
|
|
897
1172
|
const blocked = record.statuses
|
|
898
1173
|
.filter((item: any) => item.status === 'blocked')
|
|
@@ -904,6 +1179,19 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
904
1179
|
* had to re-read the whole plan to guess what to repair.
|
|
905
1180
|
*/
|
|
906
1181
|
const upstream = record.statuses.find((item: any) => item.subtaskId === id)
|
|
1182
|
+
/*
|
|
1183
|
+
* [1.8.6] An interrupted task blocked itself, not its dependents.
|
|
1184
|
+
*
|
|
1185
|
+
* Recording the interruption in `errors` (instead of silently skipping)
|
|
1186
|
+
* keeps the reason visible in the result message, and `continue` leaves
|
|
1187
|
+
* the dependents `pending` so a re-dispatch can still run them once the
|
|
1188
|
+
* main Agent re-adjudicates the interrupted step.
|
|
1189
|
+
*/
|
|
1190
|
+
if (interruptedIds.has(id)) {
|
|
1191
|
+
record.errors = [...(record.errors ?? []),
|
|
1192
|
+
`${id}: 被中断但产物已核对(见 artifacts),未自动级联下游;请据实改判或续跑`].slice(-20)
|
|
1193
|
+
continue
|
|
1194
|
+
}
|
|
907
1195
|
const cause = upstream
|
|
908
1196
|
? {
|
|
909
1197
|
reason: upstream.error,
|
|
@@ -918,7 +1206,17 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
918
1206
|
*/
|
|
919
1207
|
record.updatedAt = Date.now()
|
|
920
1208
|
}
|
|
921
|
-
|
|
1209
|
+
/*
|
|
1210
|
+
* [1.8.6] Do not let a pending tail masquerade as a failure.
|
|
1211
|
+
*
|
|
1212
|
+
* `planPhase` turns any `blocked` row into `blocked`; with D8's fix a round
|
|
1213
|
+
* can end with real blocked rows *and* untouched pending rows. Keep
|
|
1214
|
+
* `blocked` for real failures, and report `paused` when only pending work
|
|
1215
|
+
* is left, so a resume is not billed against the failure budget.
|
|
1216
|
+
*/
|
|
1217
|
+
const hasBlocked = record.statuses.some((item: any) => item.status === 'blocked')
|
|
1218
|
+
const hasPending = record.statuses.some((item: any) => item.status === 'pending')
|
|
1219
|
+
record.phase = hasBlocked ? 'blocked' : (hasPending ? 'paused' : planPhase(record.statuses))
|
|
922
1220
|
} catch (error) {
|
|
923
1221
|
const message = describeError(error)
|
|
924
1222
|
pushRecordError(record, error)
|
|
@@ -948,9 +1246,12 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
948
1246
|
let reset = record.statuses
|
|
949
1247
|
for (const item of record.statuses) {
|
|
950
1248
|
if (item.status === 'done') continue
|
|
1249
|
+
// [1.8.19] Carry the aborted attempt's provenance and landed files into
|
|
1250
|
+
// the pause reason instead of silently erasing them.
|
|
1251
|
+
const definition = findSubtaskById(record.plan, item.subtaskId)
|
|
951
1252
|
reset = applyStatus(reset, item.subtaskId, {
|
|
952
1253
|
status: 'pending',
|
|
953
|
-
error:
|
|
1254
|
+
error: budgetResetError(item, definition, options.cwd, options.artifactExists),
|
|
954
1255
|
})
|
|
955
1256
|
}
|
|
956
1257
|
record.statuses = reset
|
|
@@ -977,7 +1278,7 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
|
|
|
977
1278
|
* report for subtasks that were explicitly *not* failures.
|
|
978
1279
|
*/
|
|
979
1280
|
record.errors = (record.errors ?? []).filter((line: string) => !/总执行超时/.test(String(line)))
|
|
980
|
-
if (!allDoneNow) record.errors = [...record.errors, record.error].slice(-20)
|
|
1281
|
+
if (!allDoneNow) record.errors = [...(record.errors ?? []), record.error].slice(-20)
|
|
981
1282
|
} else {
|
|
982
1283
|
/*
|
|
983
1284
|
* `blocked` is a terminal state, so it always reports progress 100 — the
|
|
@@ -1170,6 +1471,7 @@ function serialisePlan(record: any, session: any) {
|
|
|
1170
1471
|
* 而不是等用户截图发现。附在 payload 上而不是抛错:展示层不应因自检而白屏。
|
|
1171
1472
|
*/
|
|
1172
1473
|
const violations = aggregateInvariantViolations(snapshot, phase)
|
|
1474
|
+
const readiness = deliveryReadiness(snapshot, { phase: record.phase })
|
|
1173
1475
|
return {
|
|
1174
1476
|
sessionId: session.id,
|
|
1175
1477
|
planId: record.planId ?? plan?.planId ?? null,
|
|
@@ -1186,6 +1488,17 @@ function serialisePlan(record: any, session: any) {
|
|
|
1186
1488
|
plan,
|
|
1187
1489
|
statuses,
|
|
1188
1490
|
stats,
|
|
1491
|
+
/*
|
|
1492
|
+
* [1.8.13] Delivery readiness travels with the dashboard payload too.
|
|
1493
|
+
*
|
|
1494
|
+
* `phase` alone cannot express "all rows done but evidence missing, or a
|
|
1495
|
+
* cancelled plan is still incomplete"; a green 100% card next to a denied
|
|
1496
|
+
* present is exactly the contradiction this incident exposed. The UI can
|
|
1497
|
+
* now show the same verdict the gate uses.
|
|
1498
|
+
*/
|
|
1499
|
+
deliveryReady: readiness.ready,
|
|
1500
|
+
deliveryBlockers: readiness.blockers.slice(0, 12),
|
|
1501
|
+
deliveryRemaining: readiness.remaining.slice(0, 20),
|
|
1189
1502
|
/*
|
|
1190
1503
|
* Liveness and resume bookkeeping. Without these the dashboard could not
|
|
1191
1504
|
* tell a slow-but-alive child from a wedged one, and the model could not
|
|
@@ -1231,30 +1544,143 @@ function readToolArguments(value: any) {
|
|
|
1231
1544
|
}
|
|
1232
1545
|
|
|
1233
1546
|
export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
1234
|
-
const start = Math.max(0, session.seq - MAX_HISTORY_EVENTS)
|
|
1235
|
-
let plan: any = null
|
|
1236
|
-
let statuses: any[] = []
|
|
1237
|
-
let degraded: any = null
|
|
1238
|
-
let resultSeen = false
|
|
1239
|
-
// A round-budget pause must survive a page refresh; otherwise the replayed
|
|
1240
|
-
// plan looks “executing” forever (nothing is running) and the card stops
|
|
1241
|
-
// telling the user it can simply be dispatched again.
|
|
1242
|
-
let resultPhase = ''
|
|
1243
|
-
let cancelled = false
|
|
1244
|
-
let resumeCount = 0
|
|
1245
1547
|
/*
|
|
1246
|
-
*
|
|
1548
|
+
* [1.8.10] 回放窗口必须包含目标计划的定义。
|
|
1247
1549
|
*
|
|
1248
|
-
*
|
|
1249
|
-
*
|
|
1250
|
-
*
|
|
1251
|
-
*
|
|
1252
|
-
* plan and let the caller ask for a specific one.
|
|
1550
|
+
* 会话事件超过 MAX_HISTORY_EVENTS(2000)后,窗口起点会越过早期的 plan
|
|
1551
|
+
* 消息。此时按 planId 重建旧计划得到 null,dispatch / status 都会退回
|
|
1552
|
+
* 内存里那个更新的计划,旧计划在卡片上消失,也无法再续跑。
|
|
1553
|
+
* 显式指定 planId 时向前扫到该计划的 plan 消息,把窗口起点前移。
|
|
1253
1554
|
*/
|
|
1254
|
-
|
|
1555
|
+
let start = Math.max(0, session.seq - MAX_HISTORY_EVENTS)
|
|
1556
|
+
if (targetPlanId) {
|
|
1557
|
+
for (let seq = start - 1; seq >= 0; seq -= 1) {
|
|
1558
|
+
let event
|
|
1559
|
+
try {
|
|
1560
|
+
event = session.eventAt(seq)
|
|
1561
|
+
} catch {
|
|
1562
|
+
continue
|
|
1563
|
+
}
|
|
1564
|
+
if (!event || event.type !== 'user/message') continue
|
|
1565
|
+
const payload = parseWorkplanMessage(event.data)
|
|
1566
|
+
if (payload?.plan?.planId === targetPlanId) {
|
|
1567
|
+
start = seq
|
|
1568
|
+
break
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
/*
|
|
1573
|
+
* [1.8.15] Default replay keeps the "last defined plan" contract, but it
|
|
1574
|
+
* must still find that plan when its message predates the 2000-event window.
|
|
1575
|
+
*
|
|
1576
|
+
* T3 B4 measured the window failure on 1.8.14: on a >2000-event session the
|
|
1577
|
+
* window started after the plan message, the default replay returned null,
|
|
1578
|
+
* and `present` had no plan to judge — the delivery was silently allowed.
|
|
1579
|
+
* The scan reads backwards for the last `workplan` definition and moves the
|
|
1580
|
+
* window start to it.
|
|
1581
|
+
*
|
|
1582
|
+
* The "newest activity" variant was deliberately NOT adopted: the same
|
|
1583
|
+
* default answer also feeds `dispatch`, so an older plan that merely kept
|
|
1584
|
+
* receiving result/update messages would hijack a new task's default
|
|
1585
|
+
* dispatch target (the reason N5 in 1.8.14 left the contract alone). The
|
|
1586
|
+
* turn-scoped fixes (`planIdFromTurn`, the present gate) name the plan
|
|
1587
|
+
* explicitly instead of changing the default.
|
|
1588
|
+
*/
|
|
1589
|
+
let defaultPlanId: string | null = null
|
|
1590
|
+
if (!targetPlanId) {
|
|
1591
|
+
for (let seq = session.seq - 1; seq >= 0; seq -= 1) {
|
|
1592
|
+
let event
|
|
1593
|
+
try {
|
|
1594
|
+
event = session.eventAt(seq)
|
|
1595
|
+
} catch {
|
|
1596
|
+
continue
|
|
1597
|
+
}
|
|
1598
|
+
if (!event || event.type !== 'user/message') continue
|
|
1599
|
+
const planMessage = parseWorkplanMessage(event.data)
|
|
1600
|
+
const planId = planMessage?.plan?.planId
|
|
1601
|
+
if (typeof planId !== 'string' || planId === '') continue
|
|
1602
|
+
defaultPlanId = planId
|
|
1603
|
+
let planStart = seq
|
|
1604
|
+
for (let back = seq - 1; back >= 0; back -= 1) {
|
|
1605
|
+
let prior
|
|
1606
|
+
try {
|
|
1607
|
+
prior = session.eventAt(back)
|
|
1608
|
+
} catch {
|
|
1609
|
+
continue
|
|
1610
|
+
}
|
|
1611
|
+
if (!prior || prior.type !== 'user/message') continue
|
|
1612
|
+
if (parseWorkplanMessage(prior.data)?.plan?.planId === planId) planStart = back
|
|
1613
|
+
}
|
|
1614
|
+
if (planStart < start) start = planStart
|
|
1615
|
+
break
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
interface ReplaySnapshot {
|
|
1619
|
+
plan: any
|
|
1620
|
+
statuses: any[]
|
|
1621
|
+
resultPhase: string
|
|
1622
|
+
resultSeen: boolean
|
|
1623
|
+
resumeCount: number
|
|
1624
|
+
cancelled: boolean
|
|
1625
|
+
/*
|
|
1626
|
+
* [1.9.0] 被取代(责任已转移)。与 cancelled 互斥。本补丁只做读取、
|
|
1627
|
+
* 判定与拒绝;写入路径(V1–V8 核验 + 用户确认)见规则文档 §6,属下一批。
|
|
1628
|
+
*/
|
|
1629
|
+
superseded: boolean
|
|
1630
|
+
supersededBy: any
|
|
1631
|
+
/*
|
|
1632
|
+
* [1.8.17] The durable result message carries the round's failure lines.
|
|
1633
|
+
* Replay used to drop them, and the reconstructed record then had no
|
|
1634
|
+
* `errors` field at all: the next dispatching round spread it
|
|
1635
|
+
* (`[...record.errors, …]`) and died with
|
|
1636
|
+
* `TypeError: record.errors is not iterable`, blocking every remaining
|
|
1637
|
+
* subtask at the budget boundary (wp-40ce5eee, 17:51:37).
|
|
1638
|
+
*/
|
|
1639
|
+
errors: string[]
|
|
1640
|
+
}
|
|
1641
|
+
/*
|
|
1642
|
+
* [1.8.9] 回放按 planId 分账,不按会话「最后一个计划」分账。
|
|
1643
|
+
*
|
|
1644
|
+
* 旧实现只有一组 plan/statuses:中途出现第二个计划(这次事故里是「继续」被
|
|
1645
|
+
* 误判后生成的 wp-dd26f206)时,第一个计划的快照被冻结在当时,之后所有属于
|
|
1646
|
+
* 它的结果消息与人工改判都被丢弃——重启后卡片从 13/14 掉回 5/14,而会话
|
|
1647
|
+
* 日志里明明有 7/14 的结果消息和 6 条 done 改判。现在每个计划各一份快照,
|
|
1648
|
+
* 每条 durable 消息只写给 planId 指定的那个计划。
|
|
1649
|
+
*/
|
|
1650
|
+
const snapshots = new Map<string, ReplaySnapshot>()
|
|
1651
|
+
let currentId: string | null = null
|
|
1652
|
+
let degraded: any = null
|
|
1653
|
+
const ensure = (plan: any): ReplaySnapshot => {
|
|
1654
|
+
let snap = snapshots.get(plan.planId)
|
|
1655
|
+
if (!snap) {
|
|
1656
|
+
snap = {
|
|
1657
|
+
plan,
|
|
1658
|
+
statuses: createStatuses(plan),
|
|
1659
|
+
resultPhase: '',
|
|
1660
|
+
resultSeen: false,
|
|
1661
|
+
resumeCount: 0,
|
|
1662
|
+
cancelled: false,
|
|
1663
|
+
superseded: false,
|
|
1664
|
+
supersededBy: undefined,
|
|
1665
|
+
errors: [],
|
|
1666
|
+
}
|
|
1667
|
+
snapshots.set(plan.planId, snap)
|
|
1668
|
+
}
|
|
1669
|
+
currentId = plan.planId
|
|
1670
|
+
return snap
|
|
1671
|
+
}
|
|
1255
1672
|
/** [1.6.0] callId → 待确认的 update 写入;只有配对的 tool/result 才能定案。 */
|
|
1256
1673
|
const pendingToolCalls = new Map<string, any>()
|
|
1257
|
-
|
|
1674
|
+
/**
|
|
1675
|
+
* [1.8.11] 已经由 durable `workplan-update` 消息应用过的人工改判。
|
|
1676
|
+
*
|
|
1677
|
+
* 一次 `dsh_workplan_update` 会写两份记录:一条 durable 用户消息(带
|
|
1678
|
+
* revision 与 updatedBy=agent)和一条 tool/result。回放原来两份都应用,
|
|
1679
|
+
* 第二次以 system 身份把 revision 再抬一级并覆盖 summary——人工改判的
|
|
1680
|
+
* 证据后缀就这么丢了。这里记下消息的 seq,配对的 tool/result 不再重复写。
|
|
1681
|
+
*/
|
|
1682
|
+
const appliedUpdates = new Map<string, { seq: number; status: string }>()
|
|
1683
|
+
const updateKey = (planId: string, subtaskId: string) => `${planId}\u0000${subtaskId}`
|
|
1258
1684
|
for (let seq = start; seq < session.seq; seq += 1) {
|
|
1259
1685
|
let event
|
|
1260
1686
|
try {
|
|
@@ -1267,34 +1693,40 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
1267
1693
|
const payload = parseWorkplanMessage(event.data)
|
|
1268
1694
|
if (payload?.degraded) {
|
|
1269
1695
|
degraded = payload
|
|
1270
|
-
|
|
1271
|
-
statuses = []
|
|
1272
|
-
cancelled = false
|
|
1696
|
+
currentId = null
|
|
1273
1697
|
} else if (payload?.plan) {
|
|
1274
|
-
|
|
1275
|
-
plan = payload.plan
|
|
1276
|
-
statuses = createStatuses(plan)
|
|
1277
|
-
cancelled = false
|
|
1278
|
-
/*
|
|
1279
|
-
* A new plan must not inherit the previous plan's round phase.
|
|
1280
|
-
*
|
|
1281
|
-
* `resultPhase` outlived the old plan, so after a paused plan the next
|
|
1282
|
-
* plan in the same session replayed as `paused` before its first
|
|
1283
|
-
* dispatch — the card claimed the new plan was out of budget when it had
|
|
1284
|
-
* not started. Only a result message for *this* plan may set it.
|
|
1285
|
-
*/
|
|
1286
|
-
resultPhase = ''
|
|
1287
|
-
resultSeen = false
|
|
1288
|
-
resumeCount = 0
|
|
1698
|
+
ensure(payload.plan)
|
|
1289
1699
|
}
|
|
1700
|
+
/*
|
|
1701
|
+
* Every result message is routed by its own planId. A result that arrives
|
|
1702
|
+
* after a newer plan was generated must still update the plan it names —
|
|
1703
|
+
* that was the 13/14 → 5/14 replay regression. A plan never inherits
|
|
1704
|
+
* another plan's round phase or resume counter (each snapshot owns them).
|
|
1705
|
+
*/
|
|
1290
1706
|
const result = parseResultMessage(event.data)
|
|
1291
|
-
if (result &&
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1707
|
+
if (result && typeof result.planId === 'string') {
|
|
1708
|
+
const snap = snapshots.get(result.planId)
|
|
1709
|
+
if (snap) {
|
|
1710
|
+
snap.statuses = applyResultStatuses(snap.statuses, result)
|
|
1711
|
+
// Resume bookkeeping must survive a page refresh, otherwise the budget
|
|
1712
|
+
// silently resets and a never-succeeding subtask can loop forever.
|
|
1713
|
+
snap.resumeCount = Number(result.resumeCount ?? snap.resumeCount) || 0
|
|
1714
|
+
snap.resultPhase = typeof result.phase === 'string' ? result.phase : ''
|
|
1715
|
+
snap.resultSeen = true
|
|
1716
|
+
// [1.8.17] Keep the durable failure lines so a replayed record is
|
|
1717
|
+
// shaped like a live one (never `undefined`).
|
|
1718
|
+
if (Array.isArray(result.errors)) {
|
|
1719
|
+
snap.errors = snap.errors.concat(result.errors.map((line: any) => String(line))).slice(-20)
|
|
1720
|
+
}
|
|
1721
|
+
/*
|
|
1722
|
+
* [1.8.14] A cancel that lands while a dispatch is in flight writes no
|
|
1723
|
+
* separate cancel message (it aborts the dispatch instead), so the
|
|
1724
|
+
* only durable trace of that cancellation is `phase: 'cancelled'` in
|
|
1725
|
+
* the round result. Without this the plan reopens as "executing"
|
|
1726
|
+
* after a restart — the cancel is silently lost.
|
|
1727
|
+
*/
|
|
1728
|
+
if (snap.resultPhase === 'cancelled') snap.cancelled = true
|
|
1729
|
+
}
|
|
1298
1730
|
}
|
|
1299
1731
|
/*
|
|
1300
1732
|
* [1.7.0] Manual re-adjudications replay in order.
|
|
@@ -1306,24 +1738,56 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
1306
1738
|
* newer one (see `applyResultStatuses`).
|
|
1307
1739
|
*/
|
|
1308
1740
|
const update = parseUpdateMessage(event.data)
|
|
1309
|
-
if (update &&
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1741
|
+
if (update && typeof update.planId === 'string' && typeof update.subtaskId === 'string') {
|
|
1742
|
+
const snap = snapshots.get(update.planId)
|
|
1743
|
+
if (snap) {
|
|
1744
|
+
try {
|
|
1745
|
+
snap.statuses = applyStatus(snap.statuses, update.subtaskId, {
|
|
1746
|
+
status: update.status,
|
|
1747
|
+
progress: typeof update.progress === 'number' ? update.progress : undefined,
|
|
1748
|
+
summary: typeof update.note === 'string' ? update.note : undefined,
|
|
1749
|
+
// [1.8.13] Evidence written through the update tool must survive replay.
|
|
1750
|
+
verification: update.verification,
|
|
1751
|
+
acceptance: update.acceptance,
|
|
1752
|
+
artifacts: update.artifacts,
|
|
1753
|
+
missingArtifacts: update.missingArtifacts,
|
|
1754
|
+
revision: Number.isInteger(update.revision) ? update.revision : undefined,
|
|
1755
|
+
updatedBy: 'agent',
|
|
1756
|
+
})
|
|
1757
|
+
appliedUpdates.set(updateKey(update.planId, update.subtaskId), {
|
|
1758
|
+
seq: Number(event.seq ?? 0),
|
|
1759
|
+
status: String(update.status ?? ''),
|
|
1760
|
+
})
|
|
1761
|
+
} catch {
|
|
1762
|
+
// An invalid historical update is ignored; the rest still replays.
|
|
1763
|
+
}
|
|
1320
1764
|
}
|
|
1321
1765
|
}
|
|
1322
1766
|
const cancel = parseCancelMessage(event.data)
|
|
1323
|
-
if (cancel &&
|
|
1324
|
-
|
|
1767
|
+
if (cancel && typeof cancel.planId === 'string') {
|
|
1768
|
+
const snap = snapshots.get(cancel.planId)
|
|
1769
|
+
if (snap) {
|
|
1770
|
+
/*
|
|
1771
|
+
* [1.9.0] disposition='superseded' 的信封表示「责任已转移」,不是
|
|
1772
|
+
* 用户撤销。旧解析器只校验 kind,因此该字段对新旧版本都安全:旧版
|
|
1773
|
+
* 按 cancelled 读(不可派发、不可交付),不会复活成 active。
|
|
1774
|
+
*/
|
|
1775
|
+
if (cancel.disposition === 'superseded') {
|
|
1776
|
+
snap.superseded = true
|
|
1777
|
+
snap.supersededBy = cancel.supersededBy
|
|
1778
|
+
/*
|
|
1779
|
+
* [1.9.2] 互斥(T6):取代永远发生在取消之后,所以日志里两条信封
|
|
1780
|
+
* 都在。只加 superseded 不清 cancelled,冷启动记录就会变成「既已
|
|
1781
|
+
* 取消、又被取代」,与 live 记录(`supersedePlanRecord` 写入时
|
|
1782
|
+
* 把 cancelled 置 false)分叉 —— 这正是写侧收敛要杜绝的那类分叉。
|
|
1783
|
+
*/
|
|
1784
|
+
snap.cancelled = false
|
|
1785
|
+
} else {
|
|
1786
|
+
snap.cancelled = true
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1325
1789
|
}
|
|
1326
|
-
} else if (event.type === 'tool/call'
|
|
1790
|
+
} else if (event.type === 'tool/call') {
|
|
1327
1791
|
/*
|
|
1328
1792
|
* [1.6.0] 只登记,不下结论。
|
|
1329
1793
|
*
|
|
@@ -1337,7 +1801,8 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
1337
1801
|
if (data?.name === 'dsh_workplan_update' && typeof data.callId === 'string') {
|
|
1338
1802
|
const args = readToolArguments(data.arguments)
|
|
1339
1803
|
if (args && typeof args.subtaskId === 'string' && typeof args.status === 'string') {
|
|
1340
|
-
|
|
1804
|
+
const planId = typeof args.planId === 'string' ? args.planId : currentId
|
|
1805
|
+
if (planId) pendingToolCalls.set(data.callId, { args, planId, callSeq: Number(event.seq ?? 0) })
|
|
1341
1806
|
}
|
|
1342
1807
|
}
|
|
1343
1808
|
} else if (event.type === 'tool/result') {
|
|
@@ -1346,26 +1811,50 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
1346
1811
|
if (typeof callId !== 'string') continue
|
|
1347
1812
|
const pending = pendingToolCalls.get(callId)
|
|
1348
1813
|
pendingToolCalls.delete(callId)
|
|
1349
|
-
|
|
1814
|
+
const snap = pending && typeof pending.planId === 'string' ? snapshots.get(pending.planId) : null
|
|
1815
|
+
if (!snap) {
|
|
1350
1816
|
// 结果晚于新计划到达:旧计划的写入不污染新计划的状态表。
|
|
1351
1817
|
} else if (message.isError === true) {
|
|
1352
1818
|
// 失败的更新不是完成:状态表保持原样。
|
|
1353
1819
|
} else {
|
|
1354
1820
|
const args = pending.args
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1821
|
+
/*
|
|
1822
|
+
* [1.8.11] 同一次改判已经由 durable 消息应用过时,配对结果不再写第二遍。
|
|
1823
|
+
* 判据是 seq 与状态都一致:durable 消息在本次调用之后到达且状态相同,
|
|
1824
|
+
* 才说明它是这次调用的记录;更早/更晚的人工改判仍按自己的顺序生效。
|
|
1825
|
+
*/
|
|
1826
|
+
const applied = appliedUpdates.get(updateKey(pending.planId, args.subtaskId))
|
|
1827
|
+
const alreadyDurable = Boolean(applied)
|
|
1828
|
+
&& applied!.seq > Number(pending.callSeq ?? 0)
|
|
1829
|
+
&& applied!.status === String(args.status ?? '')
|
|
1830
|
+
if (!alreadyDurable) {
|
|
1831
|
+
try {
|
|
1832
|
+
snap.statuses = applyStatus(snap.statuses, args.subtaskId, {
|
|
1833
|
+
status: args.status,
|
|
1834
|
+
progress: typeof args.progress === 'number' ? args.progress : undefined,
|
|
1835
|
+
summary: typeof args.note === 'string' ? args.note : undefined,
|
|
1836
|
+
// [1.8.13] A tool/result fallback carries the same evidence fields.
|
|
1837
|
+
verification: args.verification,
|
|
1838
|
+
acceptance: args.acceptance,
|
|
1839
|
+
artifacts: args.artifacts,
|
|
1840
|
+
missingArtifacts: args.missingArtifacts,
|
|
1841
|
+
})
|
|
1842
|
+
} catch {
|
|
1843
|
+
// An invalid historical call is ignored; the live cache remains authoritative.
|
|
1844
|
+
}
|
|
1363
1845
|
}
|
|
1364
1846
|
}
|
|
1365
1847
|
}
|
|
1366
1848
|
}
|
|
1367
|
-
|
|
1368
|
-
|
|
1849
|
+
/*
|
|
1850
|
+
* [1.8.15] Prefer the explicitly named plan, then the plan that owns the
|
|
1851
|
+
* newest activity, then the last definition seen in the replay window.
|
|
1852
|
+
*/
|
|
1853
|
+
const chosenId = targetPlanId ?? defaultPlanId ?? currentId
|
|
1854
|
+
let chosen = chosenId ? snapshots.get(chosenId) ?? null : null
|
|
1855
|
+
if (!chosen && currentId) chosen = snapshots.get(currentId) ?? null
|
|
1856
|
+
if (!chosen) {
|
|
1857
|
+
if (!degraded) return null
|
|
1369
1858
|
return {
|
|
1370
1859
|
plan: null,
|
|
1371
1860
|
planId: degraded.planId ?? null,
|
|
@@ -1379,15 +1868,22 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
1379
1868
|
createdTurn: degraded.createdTurn ?? null,
|
|
1380
1869
|
}
|
|
1381
1870
|
}
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1871
|
+
const plan = chosen.plan
|
|
1872
|
+
const statuses = chosen.statuses
|
|
1873
|
+
const resultPhase = chosen.resultPhase
|
|
1874
|
+
const resultSeen = chosen.resultSeen
|
|
1875
|
+
const resumeCount = chosen.resumeCount
|
|
1876
|
+
const superseded = chosen.superseded
|
|
1877
|
+
/*
|
|
1878
|
+
* [1.9.2] 终态互斥(T6):superseded 与 cancelled 不会同时成立。手写/旧版
|
|
1879
|
+
* 日志里可能出现「supersede 信封之后又有一条取消信封」,此时按终态优先级
|
|
1880
|
+
* 只认 superseded(fail-closed:被取代依然不可派发、不可交付)。
|
|
1881
|
+
*/
|
|
1882
|
+
const cancelled = chosen.cancelled && !superseded
|
|
1388
1883
|
let phase = planPhase(statuses, resultSeen)
|
|
1389
1884
|
if (resultPhase === 'paused' && statuses.some((item: any) => item.status !== 'done')) phase = 'paused'
|
|
1390
1885
|
if (cancelled) phase = 'cancelled'
|
|
1886
|
+
if (superseded) phase = 'superseded'
|
|
1391
1887
|
/*
|
|
1392
1888
|
* [1.5.2] 回放也必须走同一套对账。
|
|
1393
1889
|
*
|
|
@@ -1417,9 +1913,32 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
|
|
|
1417
1913
|
updatedAt: Date.now(),
|
|
1418
1914
|
createdTurn: plan.createdTurn,
|
|
1419
1915
|
resumeCount,
|
|
1916
|
+
/*
|
|
1917
|
+
* [1.8.17] A reconstructed record must carry every field the live dispatch
|
|
1918
|
+
* path spreads/pushes unconditionally. `errors` was the one that was
|
|
1919
|
+
* missing; its absence turned a recoverable child failure into a round
|
|
1920
|
+
* abort that marked the rest of the plan blocked.
|
|
1921
|
+
*/
|
|
1922
|
+
errors: (chosen.errors ?? []).slice(-20),
|
|
1420
1923
|
resumeLimit: MAX_PLAN_RESUMES,
|
|
1421
1924
|
resumeAvailable: canResumePlan({ phase, statuses, resumeCount }, MAX_PLAN_RESUMES).resume,
|
|
1422
1925
|
stale: stalePending,
|
|
1926
|
+
/*
|
|
1927
|
+
* [1.8.14] Two facts, one from the log: whether the plan is cancelled and
|
|
1928
|
+
* whether that cancellation is durably recorded. For replay they are the
|
|
1929
|
+
* same; the live `cancelPlan` uses `cancelRecorded` to make a second
|
|
1930
|
+
* cancel a no-op instead of appending a duplicate message (N8).
|
|
1931
|
+
*
|
|
1932
|
+
* [1.9.2] 被取代的计划同样有一条已落盘的终态记录(V3 要求先取消才允许
|
|
1933
|
+
* 取代),因此 cancelRecorded 在 superseded 时为 true —— 与 live 记录一致
|
|
1934
|
+
* (`supersedePlanRecord` 保留先前的 cancelRecorded)。`supersedeRecorded`
|
|
1935
|
+
* 是取代信封的写入见证,补齐后普通取消的拒绝体在冷启动/热路径上字段相同。
|
|
1936
|
+
*/
|
|
1937
|
+
cancelled,
|
|
1938
|
+
cancelRecorded: cancelled || superseded,
|
|
1939
|
+
superseded,
|
|
1940
|
+
supersedeRecorded: superseded,
|
|
1941
|
+
supersededBy: superseded ? chosen.supersededBy : undefined,
|
|
1423
1942
|
}
|
|
1424
1943
|
}
|
|
1425
1944
|
|
|
@@ -1504,14 +2023,78 @@ export type WorkplanRuntimeOptions = {
|
|
|
1504
2023
|
totalTimeoutMs?: number
|
|
1505
2024
|
/** How many times a blocked plan may be resumed. */
|
|
1506
2025
|
maxResumes?: number
|
|
2026
|
+
/**
|
|
2027
|
+
* [1.8.13] Package version, supplied by the host from its `meta.version`.
|
|
2028
|
+
*
|
|
2029
|
+
* `dsh_workplan_status` used to say nothing about which build answered, so a
|
|
2030
|
+
* stale process (the incident ran 1.8.9 while the workspace had 1.8.11) could
|
|
2031
|
+
* only be detected by inspecting the PID by hand. The version now travels
|
|
2032
|
+
* with every status/dispatch answer.
|
|
2033
|
+
*/
|
|
2034
|
+
version?: string
|
|
2035
|
+
/**
|
|
2036
|
+
* [1.8.14] Identity of the modules this process actually loaded.
|
|
2037
|
+
*
|
|
2038
|
+
* 1.8.13 made the *package version* visible, but the incident's N1 stayed
|
|
2039
|
+
* open: a version string cannot distinguish "this build" from "the same
|
|
2040
|
+
* version rebuilt", and after a profile recomposition the in-memory modules
|
|
2041
|
+
* may not be the files on disk. The host therefore hashes the loaded
|
|
2042
|
+
* `lib/host.js` + `lib/runtime.js` + `lib/plan.js` at module-init time and
|
|
2043
|
+
* passes the digest (plus PID and process start time) here. `status` answers
|
|
2044
|
+
* it even when there is no plan, so the "did the restart load the fix"
|
|
2045
|
+
* question needs no PID archaeology.
|
|
2046
|
+
*/
|
|
2047
|
+
build?: {
|
|
2048
|
+
pid?: number
|
|
2049
|
+
startedAt?: number
|
|
2050
|
+
entryPath?: string
|
|
2051
|
+
buildHash?: string
|
|
2052
|
+
}
|
|
1507
2053
|
}
|
|
1508
2054
|
|
|
1509
2055
|
export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions = {}) {
|
|
1510
|
-
|
|
2056
|
+
/*
|
|
2057
|
+
* `activeTurns` maps a root session to the turn whose user message carried a
|
|
2058
|
+
* real task; the `agent/turn-stopping` gate only objects on those turns.
|
|
2059
|
+
*/
|
|
2060
|
+
const state: any = { records: new Map(), activeTurns: new Map() }
|
|
1511
2061
|
/*
|
|
1512
2062
|
* Resolve the tunables once, at construction, so every code path (dispatch,
|
|
1513
2063
|
* resume, cancel, the host's tool timeout) agrees on the same numbers.
|
|
1514
2064
|
*/
|
|
2065
|
+
const pluginVersion = typeof options.version === 'string' && options.version ? options.version : 'unknown'
|
|
2066
|
+
/*
|
|
2067
|
+
* [1.8.14] Build identity, captured once.
|
|
2068
|
+
*
|
|
2069
|
+
* `startedAt` is derived from `process.uptime()` so it is the real process
|
|
2070
|
+
* start, not the plugin's construction time; `uptimeMs` is computed live.
|
|
2071
|
+
* Tests construct the runtime without a `build` option, so every field is
|
|
2072
|
+
* optional and the answer degrades to `unknown` instead of failing.
|
|
2073
|
+
*/
|
|
2074
|
+
const buildInfo = {
|
|
2075
|
+
pid: Number.isInteger(options.build?.pid) && Number(options.build?.pid) > 0
|
|
2076
|
+
? Number(options.build!.pid)
|
|
2077
|
+
: process.pid,
|
|
2078
|
+
startedAt: Number.isFinite(Number(options.build?.startedAt)) && Number(options.build?.startedAt) > 0
|
|
2079
|
+
? Number(options.build!.startedAt)
|
|
2080
|
+
: Math.round(Date.now() - process.uptime() * 1000),
|
|
2081
|
+
entryPath: typeof options.build?.entryPath === 'string' && options.build.entryPath
|
|
2082
|
+
? options.build.entryPath
|
|
2083
|
+
: '',
|
|
2084
|
+
buildHash: typeof options.build?.buildHash === 'string' && options.build.buildHash
|
|
2085
|
+
? options.build.buildHash
|
|
2086
|
+
: 'unknown',
|
|
2087
|
+
}
|
|
2088
|
+
function runtimeIdentity() {
|
|
2089
|
+
return {
|
|
2090
|
+
version: pluginVersion,
|
|
2091
|
+
pid: buildInfo.pid,
|
|
2092
|
+
startedAt: buildInfo.startedAt,
|
|
2093
|
+
uptimeMs: Math.max(0, Date.now() - buildInfo.startedAt),
|
|
2094
|
+
entryPath: buildInfo.entryPath,
|
|
2095
|
+
buildHash: buildInfo.buildHash,
|
|
2096
|
+
}
|
|
2097
|
+
}
|
|
1515
2098
|
const limits = {
|
|
1516
2099
|
childTimeoutMs: normaliseChildTimeout(options.childTimeoutMs),
|
|
1517
2100
|
idleTimeoutMs: normaliseIdleTimeout(options.idleTimeoutMs),
|
|
@@ -1567,15 +2150,46 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1567
2150
|
}
|
|
1568
2151
|
}
|
|
1569
2152
|
|
|
1570
|
-
|
|
2153
|
+
/**
|
|
2154
|
+
* Point an edit or a cancellation at the plan the caller actually named.
|
|
2155
|
+
*
|
|
2156
|
+
* dispatch has always rebuilt an older plan out of the session log
|
|
2157
|
+
* (`needsRebuild` + `reconstructFromSession(session, requestedPlanId)`), but
|
|
2158
|
+
* update and cancel compared the id and threw PLAN_ID_MISMATCH — so the one
|
|
2159
|
+
* repair path for "the child wrote its artifact and was then interrupted"
|
|
2160
|
+
* (re-adjudicating that step) was closed on exactly the plans that needed it.
|
|
2161
|
+
* Align the three tools: a named plan that exists in the session log becomes
|
|
2162
|
+
* the target record. While a *different* plan is dispatching, refuse with a
|
|
2163
|
+
* reason instead of silently swapping the running record out from under it.
|
|
2164
|
+
*/
|
|
2165
|
+
function adoptRequestedPlan(session: any, current: any, requestedPlanId: any) {
|
|
2166
|
+
if (!current?.plan || !requestedPlanId || current.plan.planId === requestedPlanId) return current
|
|
2167
|
+
if (current.dispatchPromise) {
|
|
2168
|
+
throw new PlanError(
|
|
2169
|
+
`计划 ${requestedPlanId} 不是当前记录:${current.plan.planId} 正在执行,先等它结束或先取消它`,
|
|
2170
|
+
'PLAN_ID_MISMATCH',
|
|
2171
|
+
)
|
|
2172
|
+
}
|
|
2173
|
+
const rebuilt = reconstructFromSession(session, requestedPlanId)
|
|
2174
|
+
if (!rebuilt?.plan || rebuilt.plan.planId !== requestedPlanId) {
|
|
2175
|
+
throw new PlanError(
|
|
2176
|
+
`planId 与当前计划不匹配(当前 ${current.plan.planId},会话日志里也没有 ${requestedPlanId})`,
|
|
2177
|
+
'PLAN_ID_MISMATCH',
|
|
2178
|
+
)
|
|
2179
|
+
}
|
|
2180
|
+
rebuilt.resumeLimit = current.resumeLimit ?? rebuilt.resumeLimit
|
|
2181
|
+
state.records.set(session.id, rebuilt)
|
|
2182
|
+
return rebuilt
|
|
2183
|
+
}
|
|
2184
|
+
|
|
2185
|
+
async function updateStatus(agent: any, args: any): Promise<any> {
|
|
1571
2186
|
const session = agent?.session
|
|
1572
2187
|
if (!session) throw new PlanError('只能在会话内更新计划', 'NO_SESSION')
|
|
1573
2188
|
if (!isRootSession(session)) throw new PlanError('子 Agent 不能更新主计划', 'NOT_ROOT')
|
|
1574
|
-
|
|
2189
|
+
let record = state.records.get(session.id)
|
|
2190
|
+
if (!record?.plan) record = reconstructFromSession(session, args?.planId)
|
|
2191
|
+
record = adoptRequestedPlan(session, record, args?.planId)
|
|
1575
2192
|
if (!record?.plan) throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN')
|
|
1576
|
-
if (args?.planId && record.plan.planId !== args.planId) {
|
|
1577
|
-
throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH')
|
|
1578
|
-
}
|
|
1579
2193
|
const subtaskId = typeof args?.subtaskId === 'string' ? args.subtaskId : ''
|
|
1580
2194
|
if (!subtaskId) throw new PlanError('缺少 subtaskId', 'MISSING_SUBTASK')
|
|
1581
2195
|
const status = typeof args?.status === 'string' ? args.status : ''
|
|
@@ -1629,11 +2243,27 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1629
2243
|
}
|
|
1630
2244
|
}
|
|
1631
2245
|
const revision = Number(current?.revision ?? 0) + 1
|
|
2246
|
+
/*
|
|
2247
|
+
* [1.8.13] A manual verdict can carry structured evidence.
|
|
2248
|
+
*
|
|
2249
|
+
* The tool used to accept only `status/progress/note/evidence`, so the
|
|
2250
|
+
* documented escape from the present gate ("先用 dsh_workplan_update 复核
|
|
2251
|
+
* 并补证据") did not exist: a done row stayed `verification: undefined`
|
|
2252
|
+
* and could never become deliverable. These four fields are now accepted,
|
|
2253
|
+
* sanitised by `applyStatus`, persisted in the durable update message and
|
|
2254
|
+
* replayed. Omitted fields keep their previous values.
|
|
2255
|
+
*/
|
|
2256
|
+
const evidencePatch: any = {}
|
|
2257
|
+
if (args?.verification !== undefined) evidencePatch.verification = args.verification
|
|
2258
|
+
if (args?.acceptance !== undefined) evidencePatch.acceptance = args.acceptance
|
|
2259
|
+
if (args?.artifacts !== undefined) evidencePatch.artifacts = args.artifacts
|
|
2260
|
+
if (args?.missingArtifacts !== undefined) evidencePatch.missingArtifacts = args.missingArtifacts
|
|
1632
2261
|
record.statuses = applyStatus(record.statuses, subtaskId, {
|
|
1633
2262
|
status,
|
|
1634
2263
|
progress: typeof args?.progress === 'number' ? args.progress : undefined,
|
|
1635
2264
|
summary: summary || undefined,
|
|
1636
2265
|
error: status === 'blocked' ? (summary || '由主 Agent 标记为受阻') : undefined,
|
|
2266
|
+
...evidencePatch,
|
|
1637
2267
|
revision,
|
|
1638
2268
|
updatedBy: 'agent',
|
|
1639
2269
|
})
|
|
@@ -1648,6 +2278,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1648
2278
|
* result. Appending one small message keeps the replay path honest.
|
|
1649
2279
|
*/
|
|
1650
2280
|
try {
|
|
2281
|
+
const writtenRow = record.statuses.find((item: any) => item.subtaskId === subtaskId)
|
|
1651
2282
|
session.append('user/message', buildUpdateMessage({
|
|
1652
2283
|
planId: record.plan.planId,
|
|
1653
2284
|
subtaskId,
|
|
@@ -1655,6 +2286,10 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1655
2286
|
progress: typeof args?.progress === 'number' ? args.progress : undefined,
|
|
1656
2287
|
note: summary || undefined,
|
|
1657
2288
|
revision,
|
|
2289
|
+
verification: writtenRow?.verification,
|
|
2290
|
+
acceptance: writtenRow?.acceptance,
|
|
2291
|
+
artifacts: writtenRow?.artifacts,
|
|
2292
|
+
missingArtifacts: writtenRow?.missingArtifacts,
|
|
1658
2293
|
}), { surfaceOp: 'append' })
|
|
1659
2294
|
} catch (error) {
|
|
1660
2295
|
pushRecordError(record, error)
|
|
@@ -1672,6 +2307,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1672
2307
|
record.updatedAt = Date.now()
|
|
1673
2308
|
const snapshot = derivePlanSnapshot(record.statuses)
|
|
1674
2309
|
const written = snapshot.statuses.find((item: any) => item.subtaskId === subtaskId)
|
|
2310
|
+
const readiness = deliveryReadiness(snapshot, { phase: record.phase })
|
|
1675
2311
|
return {
|
|
1676
2312
|
ok: true,
|
|
1677
2313
|
planId: record.plan.planId,
|
|
@@ -1680,6 +2316,16 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1680
2316
|
revision: written?.revision ?? revision,
|
|
1681
2317
|
updatedBy: written?.updatedBy ?? 'agent',
|
|
1682
2318
|
stats: snapshot.stats,
|
|
2319
|
+
deliveryReady: readiness.ready,
|
|
2320
|
+
deliveryBlockers: readiness.blockers.slice(0, 12),
|
|
2321
|
+
deliveryRemaining: readiness.remaining.slice(0, 20),
|
|
2322
|
+
...(readiness.ready
|
|
2323
|
+
? { hint: '计划已全部 done 且证据通过,可以交付。' }
|
|
2324
|
+
: {
|
|
2325
|
+
hint: written?.status === 'done'
|
|
2326
|
+
? '该子任务已是 done,但计划尚未通过交付就绪检查;若这项仍有证据缺口,请用 verification/acceptance 补齐或改回 blocked。'
|
|
2327
|
+
: '计划尚未通过交付就绪检查;继续推进剩余项,不要调用 present。',
|
|
2328
|
+
}),
|
|
1683
2329
|
}
|
|
1684
2330
|
}
|
|
1685
2331
|
|
|
@@ -1688,10 +2334,48 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1688
2334
|
if (!session) throw new PlanError('只能在会话内取消计划', 'NO_SESSION')
|
|
1689
2335
|
if (!isRootSession(session)) throw new PlanError('子 Agent 不能取消主计划', 'NOT_ROOT')
|
|
1690
2336
|
let record = state.records.get(session.id)
|
|
1691
|
-
if (!record?.plan) record = reconstructFromSession(session)
|
|
2337
|
+
if (!record?.plan) record = reconstructFromSession(session, args?.planId)
|
|
2338
|
+
record = adoptRequestedPlan(session, record, args?.planId)
|
|
1692
2339
|
if (!record?.plan) throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN')
|
|
1693
|
-
|
|
1694
|
-
|
|
2340
|
+
/*
|
|
2341
|
+
* [1.9.2] superseded 的唯一写入入口(T6)。
|
|
2342
|
+
*
|
|
2343
|
+
* `disposition` 只有两个合法取值:省略/'cancelled' 走既有取消语义(返回体
|
|
2344
|
+
* 与 1.8.19 逐字相同);'superseded' 交给 `supersedePlanRecord`(V1–V8
|
|
2345
|
+
* 复算 + digest + durable 信封)。其他取值一律拒绝:静默忽略一个拼错的
|
|
2346
|
+
* disposition 会把「想取代」写成「取消」,而两者的读侧判定完全不同。
|
|
2347
|
+
*/
|
|
2348
|
+
const disposition = args?.disposition
|
|
2349
|
+
if (disposition !== undefined && disposition !== 'cancelled' && disposition !== 'superseded') {
|
|
2350
|
+
throw new PlanError(
|
|
2351
|
+
`disposition 只能是 cancelled 或 superseded(收到 ${String(disposition)})`,
|
|
2352
|
+
'INVALID_DISPOSITION',
|
|
2353
|
+
)
|
|
2354
|
+
}
|
|
2355
|
+
if (disposition === 'superseded') {
|
|
2356
|
+
const result = supersedePlanRecord(session, record, args, { reconstruct: reconstructFromSession })
|
|
2357
|
+
state.records.set(session.id, record)
|
|
2358
|
+
return result
|
|
2359
|
+
}
|
|
2360
|
+
/*
|
|
2361
|
+
* [1.9.2] 被取代的计划不允许被普通取消静默改回 cancelled。
|
|
2362
|
+
*
|
|
2363
|
+
* 旧路径会追加第二条不带 disposition 的取消信封:live 变 cancelled,
|
|
2364
|
+
* replay 却因同一 planId 先读到 superseded 而仍是 superseded —— 又一种
|
|
2365
|
+
* live/replay 分叉。行政撤销(E6)需要用户明确要求并写入新的处置记录,
|
|
2366
|
+
* 本版本不实现,因此这里 fail-closed 并给出可执行说明。
|
|
2367
|
+
*/
|
|
2368
|
+
if (record.phase === 'superseded' || record.superseded === true) {
|
|
2369
|
+
return {
|
|
2370
|
+
ok: false,
|
|
2371
|
+
planId: record.plan.planId,
|
|
2372
|
+
phase: 'superseded',
|
|
2373
|
+
code: 'SUPERSEDED_LOCKED',
|
|
2374
|
+
error: '计划已被取代:不能静默改回 cancelled(行政撤销 E6 需要用户明确要求并写入新的处置记录,本版本未实现)',
|
|
2375
|
+
hint: '被取代不等于完成:不得调用 present、不得声称“已完成”。如需撤销该处置,请先向用户确认,再由主 Agent 走审计流程。',
|
|
2376
|
+
cancelRecorded: record.supersedeRecorded === true,
|
|
2377
|
+
stats: derivePlanSnapshot(record.statuses).stats,
|
|
2378
|
+
}
|
|
1695
2379
|
}
|
|
1696
2380
|
const reason = typeof args?.reason === 'string' && args.reason.trim()
|
|
1697
2381
|
? args.reason.trim()
|
|
@@ -1719,6 +2403,55 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1719
2403
|
stats: before.stats,
|
|
1720
2404
|
}
|
|
1721
2405
|
}
|
|
2406
|
+
/*
|
|
2407
|
+
* [1.8.14] N8: a second cancel used to append a second cancel message.
|
|
2408
|
+
*
|
|
2409
|
+
* Cancelling is idempotent by definition: once the cancellation is durably
|
|
2410
|
+
* recorded, repeating it must not grow the log — every duplicate is
|
|
2411
|
+
* replayed and shows up as another "取消" line in the transcript, which is
|
|
2412
|
+
* exactly the kind of "did it happen twice?" noise this incident was made
|
|
2413
|
+
* of.
|
|
2414
|
+
*
|
|
2415
|
+
* [1.8.15] The abort path was the exception that still duplicated: while
|
|
2416
|
+
* `dispatchPromise` was in flight the guard fell through every time, so two
|
|
2417
|
+
* cancels during one dispatch appended two messages (T4e F2). Once the
|
|
2418
|
+
* abort has been requested there is nothing left to stop, so the presence
|
|
2419
|
+
* of an in-flight promise is no longer a reason to append again.
|
|
2420
|
+
*/
|
|
2421
|
+
if (record.phase === 'cancelled' && record.cancelRecorded === true
|
|
2422
|
+
&& (!record.dispatchPromise || record.abortRequested === true)) {
|
|
2423
|
+
state.records.set(session.id, record)
|
|
2424
|
+
return {
|
|
2425
|
+
ok: true,
|
|
2426
|
+
planId: record.plan.planId,
|
|
2427
|
+
phase: 'cancelled',
|
|
2428
|
+
reason: typeof record.cancelReason === 'string' && record.cancelReason ? record.cancelReason : reason,
|
|
2429
|
+
alreadyCancelled: true,
|
|
2430
|
+
abortedRunning: false,
|
|
2431
|
+
cancelRecorded: true,
|
|
2432
|
+
stats: before.stats,
|
|
2433
|
+
}
|
|
2434
|
+
}
|
|
2435
|
+
const cancelMessage = buildCancelMessage(record.plan.planId, reason)
|
|
2436
|
+
/*
|
|
2437
|
+
* [1.8.14] N12: the durable cancel used to be the only append without a
|
|
2438
|
+
* try/catch. A failing append threw out of the tool after the in-memory
|
|
2439
|
+
* phase had already flipped to `cancelled`, leaving the UI saying
|
|
2440
|
+
* "已取消" while the log said nothing — the next restart silently undid it.
|
|
2441
|
+
* Record the failure and report `cancelRecorded: false` instead.
|
|
2442
|
+
*/
|
|
2443
|
+
const appendCancelRecord = () => {
|
|
2444
|
+
try {
|
|
2445
|
+
session.append('user/message', cancelMessage, { surfaceOp: 'append' })
|
|
2446
|
+
record.cancelRecorded = true
|
|
2447
|
+
record.cancelReason = reason
|
|
2448
|
+
return true
|
|
2449
|
+
} catch (error: any) {
|
|
2450
|
+
record.cancelRecorded = false
|
|
2451
|
+
pushRecordError(record, `写入取消消息失败:${error instanceof Error ? error.message : String(error)}`)
|
|
2452
|
+
return false
|
|
2453
|
+
}
|
|
2454
|
+
}
|
|
1722
2455
|
if (record.dispatchPromise) {
|
|
1723
2456
|
/*
|
|
1724
2457
|
* Cancel must always work.
|
|
@@ -1734,31 +2467,46 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1734
2467
|
record.updatedAt = Date.now()
|
|
1735
2468
|
let aborted = false
|
|
1736
2469
|
try {
|
|
2470
|
+
/*
|
|
2471
|
+
* [1.8.15] Mark the abort before asking for it. The idempotency guard
|
|
2472
|
+
* above keys on this flag, so a second cancel that arrives while the
|
|
2473
|
+
* dispatch promise is still settling cannot append a second message.
|
|
2474
|
+
*/
|
|
2475
|
+
record.abortRequested = true
|
|
1737
2476
|
record.abortDispatch?.(reason)
|
|
1738
2477
|
aborted = true
|
|
1739
2478
|
} catch (error: any) {
|
|
1740
2479
|
record.errors = [...(record.errors ?? []), `取消时中止执行失败:${String(error?.message ?? error)}`].slice(-20)
|
|
1741
2480
|
}
|
|
2481
|
+
/*
|
|
2482
|
+
* [1.8.14] The abort path now writes the cancel durably too. 1.8.13
|
|
2483
|
+
* returned here without touching the log, so a later failed result write
|
|
2484
|
+
* left no trace of the cancellation at all and a restart reopened the
|
|
2485
|
+
* plan as "executing".
|
|
2486
|
+
*/
|
|
2487
|
+
const recorded = appendCancelRecord()
|
|
2488
|
+
state.records.set(session.id, record)
|
|
1742
2489
|
return {
|
|
1743
2490
|
ok: true,
|
|
1744
2491
|
planId: record.plan.planId,
|
|
1745
2492
|
phase: 'cancelled',
|
|
1746
2493
|
reason,
|
|
1747
2494
|
abortedRunning: aborted,
|
|
2495
|
+
cancelRecorded: recorded,
|
|
1748
2496
|
stats: derivePlanSnapshot(record.statuses).stats,
|
|
1749
2497
|
}
|
|
1750
2498
|
}
|
|
1751
2499
|
record.phase = 'cancelled'
|
|
1752
2500
|
record.error = `计划已取消:${reason}`
|
|
1753
2501
|
record.updatedAt = Date.now()
|
|
1754
|
-
const
|
|
1755
|
-
session.append('user/message', message, { surfaceOp: 'append' })
|
|
2502
|
+
const recorded = appendCancelRecord()
|
|
1756
2503
|
state.records.set(session.id, record)
|
|
1757
2504
|
return {
|
|
1758
2505
|
ok: true,
|
|
1759
2506
|
planId: record.plan.planId,
|
|
1760
2507
|
phase: 'cancelled',
|
|
1761
2508
|
reason,
|
|
2509
|
+
cancelRecorded: recorded,
|
|
1762
2510
|
stats: derivePlanSnapshot(record.statuses).stats,
|
|
1763
2511
|
}
|
|
1764
2512
|
}
|
|
@@ -1778,6 +2526,12 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1778
2526
|
record.resultWritten = true
|
|
1779
2527
|
} catch (error) {
|
|
1780
2528
|
ctx.logger?.warn?.(`dsh-workplan: 写入结果消息失败:${error instanceof Error ? error.message : String(error)}`)
|
|
2529
|
+
/*
|
|
2530
|
+
* [1.8.14] N13: a failed result write is a real, user-visible failure —
|
|
2531
|
+
* the round summary is absent from the transcript and a restart can
|
|
2532
|
+
* disagree with the live phase. Log it durably, not only in the host log.
|
|
2533
|
+
*/
|
|
2534
|
+
pushRecordError(record, `写入结果消息失败:${error instanceof Error ? error.message : String(error)}`)
|
|
1781
2535
|
}
|
|
1782
2536
|
}
|
|
1783
2537
|
/*
|
|
@@ -1791,12 +2545,46 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1791
2545
|
return record
|
|
1792
2546
|
}
|
|
1793
2547
|
|
|
2548
|
+
/*
|
|
2549
|
+
* [1.8.7] `ok` alone was read as "the plan is finished".
|
|
2550
|
+
*
|
|
2551
|
+
* The incident's tool result said `ok: true` while 3 of 13 subtasks had never
|
|
2552
|
+
* run; the rendered line added "已加入进行中的派发并等到结果", so the model
|
|
2553
|
+
* had no field telling it the round ended early. `complete`/`remaining` make
|
|
2554
|
+
* that state machine-readable instead of a sentence to interpret.
|
|
2555
|
+
*/
|
|
2556
|
+
function completionFields(snapshot: any, phase: any) {
|
|
2557
|
+
const stats = snapshot?.stats ?? {}
|
|
2558
|
+
const total = Number(stats.total ?? 0)
|
|
2559
|
+
const done = Number(stats.done ?? 0)
|
|
2560
|
+
/*
|
|
2561
|
+
* [1.8.13] `complete` and `deliveryReady` are different facts.
|
|
2562
|
+
*
|
|
2563
|
+
* `complete` keeps its old meaning (every subtask done) so existing callers
|
|
2564
|
+
* do not break, but a dispatch answer that only said `complete:true` was
|
|
2565
|
+
* read as "finished" even when every row was legacy/empty-evidence. The
|
|
2566
|
+
* model now also sees whether the plan passed the delivery gate, plus the
|
|
2567
|
+
* exact gaps.
|
|
2568
|
+
*/
|
|
2569
|
+
const readiness = deliveryReadiness(snapshot, { phase })
|
|
2570
|
+
return {
|
|
2571
|
+
complete: total > 0 && done >= total,
|
|
2572
|
+
remaining: Math.max(0, total - done),
|
|
2573
|
+
deliveryReady: readiness.ready,
|
|
2574
|
+
deliveryBlockers: readiness.blockers.slice(0, 12),
|
|
2575
|
+
deliveryRemaining: readiness.remaining.slice(0, 20),
|
|
2576
|
+
}
|
|
2577
|
+
}
|
|
2578
|
+
|
|
1794
2579
|
function dispatchSnapshotOf(record: any, extra: any = {}) {
|
|
1795
2580
|
const snapshot = derivePlanSnapshot(record.statuses)
|
|
1796
2581
|
return {
|
|
1797
2582
|
ok: true,
|
|
2583
|
+
version: pluginVersion,
|
|
2584
|
+
runtime: runtimeIdentity(),
|
|
1798
2585
|
planId: record.plan.planId,
|
|
1799
2586
|
alreadyRunning: false,
|
|
2587
|
+
...completionFields(snapshot, record.phase),
|
|
1800
2588
|
...extra,
|
|
1801
2589
|
phase: record.phase,
|
|
1802
2590
|
stats: snapshot.stats,
|
|
@@ -1822,18 +2610,30 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1822
2610
|
if (rebuilt?.plan) record = rebuilt
|
|
1823
2611
|
}
|
|
1824
2612
|
if (!record?.plan) {
|
|
2613
|
+
/*
|
|
2614
|
+
* [1.8.14] N1/§14.6 step 2: the identity of the loaded build must be
|
|
2615
|
+
* answerable even before a plan exists. 1.8.13 returned NO_PLAN with no
|
|
2616
|
+
* version here, so the documented restart check ("call status, confirm
|
|
2617
|
+
* the version") failed on a fresh session — the check itself was wrong,
|
|
2618
|
+
* not just the docs.
|
|
2619
|
+
*/
|
|
1825
2620
|
return {
|
|
1826
2621
|
ok: false,
|
|
1827
2622
|
code: 'NO_PLAN',
|
|
1828
2623
|
running: false,
|
|
2624
|
+
version: pluginVersion,
|
|
2625
|
+
runtime: runtimeIdentity(),
|
|
1829
2626
|
error: '当前会话没有可查看的计划',
|
|
1830
2627
|
hint: '先让本轮生成计划并调用 dsh_workplan_dispatch。',
|
|
1831
2628
|
}
|
|
1832
2629
|
}
|
|
1833
2630
|
const running = Boolean(record.dispatchPromise)
|
|
1834
2631
|
const snapshot = derivePlanSnapshot(record.statuses)
|
|
2632
|
+
const readiness = deliveryReadiness(snapshot, { phase: record.phase })
|
|
1835
2633
|
return {
|
|
1836
2634
|
ok: true,
|
|
2635
|
+
version: pluginVersion,
|
|
2636
|
+
runtime: runtimeIdentity(),
|
|
1837
2637
|
planId: record.plan.planId,
|
|
1838
2638
|
running,
|
|
1839
2639
|
phase: record.phase,
|
|
@@ -1842,9 +2642,83 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1842
2642
|
statuses: modelStatusLines(snapshot.statuses),
|
|
1843
2643
|
errors: (record.errors ?? []).slice(-10),
|
|
1844
2644
|
resumeLimit: Number(record.resumeLimit ?? limits.maxResumes),
|
|
2645
|
+
deliveryReady: readiness.ready,
|
|
2646
|
+
deliveryBlockers: readiness.blockers.slice(0, 12),
|
|
2647
|
+
deliveryRemaining: readiness.remaining.slice(0, 20),
|
|
1845
2648
|
...(running
|
|
1846
2649
|
? { hint: '计划仍在执行:先向用户报告进度,不要声称完成;等结果消息出现后再逐项核对证据。' }
|
|
1847
|
-
:
|
|
2650
|
+
: readiness.ready
|
|
2651
|
+
? { hint: '计划已全部 done 且证据通过,可以交付。' }
|
|
2652
|
+
: readiness.cancelled
|
|
2653
|
+
? { hint: '计划已取消且未完成:不要 dispatch 或 present;答复按「未完成:剩余 N 项与原因」开头。' }
|
|
2654
|
+
: { hint: '当前没有正在执行的派发。计划尚未通过交付就绪检查:先 dispatch 续跑剩余项;若只剩已 done 项的证据缺口,用 dsh_workplan_update 补 verification/acceptance。不要调用 present。' }),
|
|
2655
|
+
}
|
|
2656
|
+
}
|
|
2657
|
+
|
|
2658
|
+
/*
|
|
2659
|
+
* [1.9.1] 用户授权的 follow-up 通道。
|
|
2660
|
+
*
|
|
2661
|
+
* 事故背景:三条子会话 a0d5b134 / 031225ef / 7934905a 在 2026-10-31
|
|
2662
|
+
* 23:07–23:23 之间被整轮预算与 900s 子任务上限中止,各自末轮
|
|
2663
|
+
* `turn/end = aborted/parent`;界面据此显示 idle(灰色),而台账侧三条
|
|
2664
|
+
* 都是 done/structured。用户 2026-11-01 明确同意「补发 follow-up,让圈注
|
|
2665
|
+
* 三行真正变绿」——做法是让子会话自己再跑完一个正常回合,而不是伪造
|
|
2666
|
+
* turn/end 或改投影缓存。
|
|
2667
|
+
*
|
|
2668
|
+
* 本工具只做一件事:把一条消息投递到本会话的**直接**子会话。它不写计划
|
|
2669
|
+
* 状态、不触发交付、也不改变 `lastTurnCompleted`——那个字段只会被子会话
|
|
2670
|
+
* 自己真实完成的回合改写。投递成功后子会话开始新一轮;它正常结束,界面
|
|
2671
|
+
* 才可能变绿。失败一律返回 ok:false,不吞错。
|
|
2672
|
+
*/
|
|
2673
|
+
async function followupTool(agent: any, args: any, signal: any) {
|
|
2674
|
+
const session = agent?.session
|
|
2675
|
+
if (!session) {
|
|
2676
|
+
return { ok: false, code: 'NO_SESSION', error: '只能在会话内补发 follow-up' }
|
|
2677
|
+
}
|
|
2678
|
+
if (!isRootSession(session)) {
|
|
2679
|
+
return { ok: false, code: 'NOT_ROOT', error: '只有根会话可以补发 follow-up' }
|
|
2680
|
+
}
|
|
2681
|
+
const childId = typeof args?.sessionId === 'string' ? args.sessionId.trim() : ''
|
|
2682
|
+
const message = typeof args?.message === 'string' ? args.message.trim() : ''
|
|
2683
|
+
if (!childId) {
|
|
2684
|
+
return { ok: false, code: 'INVALID_SESSION', error: 'sessionId 必填:必须是本会话的直接子会话 ID' }
|
|
2685
|
+
}
|
|
2686
|
+
if (!message) {
|
|
2687
|
+
return { ok: false, code: 'INVALID_MESSAGE', error: 'message 必填:要发给子会话的说明' }
|
|
2688
|
+
}
|
|
2689
|
+
if (message.length > 4000) {
|
|
2690
|
+
return { ok: false, code: 'MESSAGE_TOO_LONG', error: 'message 过长(上限 4000 字符)' }
|
|
2691
|
+
}
|
|
2692
|
+
if (!spawnedChildIds(session).has(childId)) {
|
|
2693
|
+
return {
|
|
2694
|
+
ok: false,
|
|
2695
|
+
code: 'NOT_DIRECT_CHILD',
|
|
2696
|
+
error: `${childId} 不是本会话的直接子会话(父会话 catalog 未登记),拒绝投递`,
|
|
2697
|
+
}
|
|
2698
|
+
}
|
|
2699
|
+
const service: any = (ctx as any).subagents
|
|
2700
|
+
if (!service || typeof service.sendMessage !== 'function') {
|
|
2701
|
+
return {
|
|
2702
|
+
ok: false,
|
|
2703
|
+
code: 'NO_SUBAGENT_SERVICE',
|
|
2704
|
+
error: '当前部署没有可用的 subagent 服务,无法投递 follow-up',
|
|
2705
|
+
}
|
|
2706
|
+
}
|
|
2707
|
+
try {
|
|
2708
|
+
const messageId = await service.sendMessage(
|
|
2709
|
+
agent,
|
|
2710
|
+
childId,
|
|
2711
|
+
[{ type: 'text', text: message }],
|
|
2712
|
+
{ signal },
|
|
2713
|
+
)
|
|
2714
|
+
return { ok: true, sessionId: childId, messageId: String(messageId ?? '') }
|
|
2715
|
+
} catch (error: any) {
|
|
2716
|
+
return {
|
|
2717
|
+
ok: false,
|
|
2718
|
+
code: 'DELIVERY_FAILED',
|
|
2719
|
+
sessionId: childId,
|
|
2720
|
+
error: truncate(error instanceof Error ? error.message : String(error), 500),
|
|
2721
|
+
}
|
|
1848
2722
|
}
|
|
1849
2723
|
}
|
|
1850
2724
|
|
|
@@ -1889,6 +2763,41 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
1889
2763
|
if (args?.planId && record.plan.planId !== args.planId) {
|
|
1890
2764
|
throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH')
|
|
1891
2765
|
}
|
|
2766
|
+
/*
|
|
2767
|
+
* [1.8.15] Cancelled is terminal: dispatch must refuse, not resurrect.
|
|
2768
|
+
*
|
|
2769
|
+
* T4e F1/C16 proved the old path answered `ok: true` and really started
|
|
2770
|
+
* department Agents on a cancelled plan (`activationCalled: true`), and a
|
|
2771
|
+
* 2/2-done cancelled plan was silently rewritten to `phase: done`. Cancel
|
|
2772
|
+
* is the user's stop signal; the only honest answer is a refusal that says
|
|
2773
|
+
* how to continue deliberately (a new plan, or the main Agent takes over).
|
|
2774
|
+
*/
|
|
2775
|
+
if (isTerminalPhase(record.phase) || record.cancelled === true) {
|
|
2776
|
+
/*
|
|
2777
|
+
* [1.9.0] 终态集合:cancelled(用户撤销)与 superseded(责任已转移)
|
|
2778
|
+
* 都不允许派发、不允许复活。superseded 用独立拒绝码,便于调用方区分
|
|
2779
|
+
* 「用户叫停」与「已被别的计划承接」。cancelled 的返回体与 1.8.19 相同。
|
|
2780
|
+
*/
|
|
2781
|
+
const superseded = record.phase === 'superseded'
|
|
2782
|
+
const snapshot = derivePlanSnapshot(record.statuses)
|
|
2783
|
+
return {
|
|
2784
|
+
ok: false,
|
|
2785
|
+
planId: record.plan.planId,
|
|
2786
|
+
phase: superseded ? 'superseded' : 'cancelled',
|
|
2787
|
+
running: false,
|
|
2788
|
+
alreadyRunning: false,
|
|
2789
|
+
complete: false,
|
|
2790
|
+
remaining: Math.max(0, Number(snapshot.stats.total ?? 0) - Number(snapshot.stats.done ?? 0)),
|
|
2791
|
+
stats: snapshot.stats,
|
|
2792
|
+
code: superseded ? 'PLAN_SUPERSEDED' : 'PLAN_CANCELLED',
|
|
2793
|
+
error: superseded
|
|
2794
|
+
? '计划已被取代:不会再启动任何部门 Agent'
|
|
2795
|
+
: '计划已取消:取消只停止执行,不会再启动任何部门 Agent',
|
|
2796
|
+
hint: superseded
|
|
2797
|
+
? '不要再次派发。被取代不等于完成:如需交付,请按覆盖链核对承接计划的证据;承接计划未就绪时不得调用 present。'
|
|
2798
|
+
: '不要再次派发。如需继续这项工作,请向用户确认后重新生成计划;或由主 Agent 直接接手剩余项,并在答复中说明这是直接执行而非派发。',
|
|
2799
|
+
}
|
|
2800
|
+
}
|
|
1892
2801
|
/*
|
|
1893
2802
|
* [1.7.0] Two dispatch modes.
|
|
1894
2803
|
*
|
|
@@ -2046,6 +2955,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
2046
2955
|
mode: 'async',
|
|
2047
2956
|
running: true,
|
|
2048
2957
|
alreadyRunning: false,
|
|
2958
|
+
complete: false,
|
|
2959
|
+
remaining: Math.max(0, Number(live.stats.total ?? 0) - Number(live.stats.done ?? 0)),
|
|
2049
2960
|
phase: record.phase,
|
|
2050
2961
|
startedAt,
|
|
2051
2962
|
stats: live.stats,
|
|
@@ -2064,8 +2975,713 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
2064
2975
|
return dispatchSnapshotOf(record)
|
|
2065
2976
|
}
|
|
2066
2977
|
|
|
2978
|
+
/*
|
|
2979
|
+
* [1.8.7] 回合收尾前的强制闸门——「未完成即输出」的根治点。
|
|
2980
|
+
*
|
|
2981
|
+
* 事故(session-99984ebd…,2026-10-31)里,模型在计划 10/13 时 present 了
|
|
2982
|
+
* 报告并给出收尾答复。插件原来只订阅 `agent/pre-step`,回合结束完全不受
|
|
2983
|
+
* 约束;预算暂停只写了一句「可续跑」,没有任何强制力。
|
|
2984
|
+
*
|
|
2985
|
+
* 官方 harness 为此提供了确切扩展点 `agent/turn-stopping`(@deepseek-ai/dsh-agent
|
|
2986
|
+
* 的 runtime-types 原文:「Awaited before the boundary commits — a listener
|
|
2987
|
+
* that objects steers (agent.steer(...)) and the machine re-reads its inbox:
|
|
2988
|
+
* fresh steering runs another step, none closes the turn.」)。同仓的
|
|
2989
|
+
* dsh-workspace-changes 就注册在插件根 ctx 上,证明该 agent 作用域事件能到
|
|
2990
|
+
* 达根监听器。
|
|
2991
|
+
*
|
|
2992
|
+
* 规则:
|
|
2993
|
+
* - 只看根会话、只看本回合真实任务(state.activeTurns),社交/状态型回合不打扰;
|
|
2994
|
+
* - 降级记录(没有计划)不拦;空计划也不拦(present 仍会拒绝);
|
|
2995
|
+
* - 后台派发仍在跑 ⇒ 先等它结束再判断,绝不让「已结束 ∧ 正在做」复活;
|
|
2996
|
+
* - 计划未通过交付就绪检查(含未完成、证据缺口、已取消但未完成)⇒
|
|
2997
|
+
* `agent.steer()` 一条明确的「禁止收尾」指令,每个回合最多 2 次。
|
|
2998
|
+
*
|
|
2999
|
+
* [1.8.13] 取消不再等于放行。
|
|
3000
|
+
*
|
|
3001
|
+
* 1.8.8 的闸门只问“还有没有 pending/in_progress”,所以全 done 但证据是
|
|
3002
|
+
* legacy/空验收的计划、以及 cancelled 的计划都会安静收尾并声称完成
|
|
3003
|
+
* (T5-B/C/D)。现在闸门与 present 共用 `deliveryReadiness`:凡是能拦住
|
|
3004
|
+
* 交付的缺口,也能拦住“这个回合就这么结束”。取消分支不再要求续跑,
|
|
3005
|
+
* 只要求按未完成口径如实收尾,所以不会空转。
|
|
3006
|
+
*/
|
|
3007
|
+
const STOP_STEER_LIMIT = 2
|
|
3008
|
+
|
|
3009
|
+
function recordReadiness(record: any) {
|
|
3010
|
+
const snapshot = derivePlanSnapshot(record.statuses)
|
|
3011
|
+
return deliveryReadiness(snapshot, { phase: record.phase })
|
|
3012
|
+
}
|
|
3013
|
+
|
|
3014
|
+
function stopGateApplies(record: any, session?: any, turn?: number) {
|
|
3015
|
+
if (!record?.plan) return false
|
|
3016
|
+
if (record.degraded) return false
|
|
3017
|
+
/*
|
|
3018
|
+
* [1.9.0] 终态不再触发收尾 steer —— 这正是死锁的第二个出口(T8 I7)。
|
|
3019
|
+
* cancelled 只有在本回合被结构化点名时才提醒一次(present 仍会硬拦);
|
|
3020
|
+
* superseded 不 steer:它的判定对象是承接计划,present 的拒绝文案已给出出路。
|
|
3021
|
+
*/
|
|
3022
|
+
if (isTerminalPhase(record.phase)) {
|
|
3023
|
+
return record.phase === 'cancelled'
|
|
3024
|
+
&& Boolean(session && turn && planIdFromTurn(session, turn) === record.plan.planId)
|
|
3025
|
+
}
|
|
3026
|
+
const readiness = recordReadiness(record)
|
|
3027
|
+
if (Number(readiness.total ?? 0) === 0) return false
|
|
3028
|
+
return !readiness.ready
|
|
3029
|
+
}
|
|
3030
|
+
|
|
3031
|
+
function planChildIds(record: any) {
|
|
3032
|
+
const ids = new Set<string>()
|
|
3033
|
+
for (const item of record?.statuses ?? []) {
|
|
3034
|
+
if (typeof item?.childId === 'string' && item.childId) ids.add(item.childId)
|
|
3035
|
+
}
|
|
3036
|
+
for (const stage of record?.plan?.stages ?? []) {
|
|
3037
|
+
for (const subtask of stage?.subtasks ?? []) {
|
|
3038
|
+
if (typeof subtask?.childId === 'string' && subtask.childId) ids.add(subtask.childId)
|
|
3039
|
+
}
|
|
3040
|
+
}
|
|
3041
|
+
return ids
|
|
3042
|
+
}
|
|
3043
|
+
|
|
3044
|
+
const PLAN_CONTINUATION_KINDS = new Set(['subagent-settled', 'workplan-result', 'workplan-continue'])
|
|
3045
|
+
|
|
3046
|
+
/**
|
|
3047
|
+
* [1.8.9] 子会话谱系判定。
|
|
3048
|
+
*
|
|
3049
|
+
* `childId` 在预算重置时会被清空(`applyStatus({status:'pending'})` 走
|
|
3050
|
+
* `normaliseStatusEntry` 强制 childId=null),事故里的 T11 因此不在
|
|
3051
|
+
* planChildIds 中,turn 2 又一次绕过闸门。`header.parentSession` 是子会话
|
|
3052
|
+
* 自身的身份,预算与重启都不会改写它,用它旁证“这条结算来自本计划的执行者”。
|
|
3053
|
+
*/
|
|
3054
|
+
function isChildSessionOf(senderId: string, session: any) {
|
|
3055
|
+
if (!senderId) return false
|
|
3056
|
+
try {
|
|
3057
|
+
const child = ctx.sessions?.get?.(senderId)
|
|
3058
|
+
const header = child?.header
|
|
3059
|
+
if (!header) return false
|
|
3060
|
+
return header.parentSession === session.id
|
|
3061
|
+
} catch {
|
|
3062
|
+
return false
|
|
3063
|
+
}
|
|
3064
|
+
}
|
|
3065
|
+
|
|
3066
|
+
/**
|
|
3067
|
+
* [1.8.11] 用父会话自己的 `subagent/catalog` 事件认亲。
|
|
3068
|
+
*
|
|
3069
|
+
* `subagent-settled` 到达时子会话已经被 dispose(dsh-subagent 的
|
|
3070
|
+
* `finishDisposal` 先 `handle.dispose()` 再 `notifySettlement`),
|
|
3071
|
+
* `ctx.sessions.get(senderId)` 必然拿不到 header,1.8.9 的谱系判定因此
|
|
3072
|
+
* 在真实生命周期下恒为 false。spawn 记录却留在父会话的事件流里,重启、
|
|
3073
|
+
* 回放、预算重置都不会改写它,是唯一持久可靠的父链证据。
|
|
3074
|
+
*/
|
|
3075
|
+
const spawnedChildCache = new Map<string, { at: number; ids: Set<string> }>()
|
|
3076
|
+
function spawnedChildIds(session: any): Set<string> {
|
|
3077
|
+
const cached = spawnedChildCache.get(session.id)
|
|
3078
|
+
if (cached && cached.at === session.seq) return cached.ids
|
|
3079
|
+
const ids = new Set<string>()
|
|
3080
|
+
if (typeof session?.eventAt === 'function') {
|
|
3081
|
+
for (let i = 0; i < session.seq; i += 1) {
|
|
3082
|
+
let event
|
|
3083
|
+
try {
|
|
3084
|
+
event = session.eventAt(i)
|
|
3085
|
+
} catch {
|
|
3086
|
+
continue
|
|
3087
|
+
}
|
|
3088
|
+
if (event?.type === 'subagent/catalog' && typeof event.data?.childId === 'string') {
|
|
3089
|
+
ids.add(event.data.childId)
|
|
3090
|
+
}
|
|
3091
|
+
}
|
|
3092
|
+
}
|
|
3093
|
+
spawnedChildCache.set(session.id, { at: session.seq, ids })
|
|
3094
|
+
return ids
|
|
3095
|
+
}
|
|
3096
|
+
|
|
3097
|
+
/*
|
|
3098
|
+
* [1.8.14] N5:结算回合要判的是「这条结算对应的计划」,不是「最后生成的计划」。
|
|
3099
|
+
*
|
|
3100
|
+
* 重启后内存为空时,收尾闸门原本走默认回放(最后一个 plan 消息):事故会话在
|
|
3101
|
+
* A 未完成时又生成了 B,A 的结果随后到达,闸门于是按 B 判定。结算输入
|
|
3102
|
+
* (workplan-result)自带 planId;显式传 planId 还能触发 1.8.10 的窗口前移,
|
|
3103
|
+
* 旧计划落在 2000 事件窗口外时也能重建。
|
|
3104
|
+
*/
|
|
3105
|
+
function planIdFromTurn(session: any, turn: number): string | undefined {
|
|
3106
|
+
if (typeof session?.eventAt !== 'function' || !(turn >= 1)) return undefined
|
|
3107
|
+
let started = -1
|
|
3108
|
+
for (let i = session.seq - 1; i >= 0; i -= 1) {
|
|
3109
|
+
const event = session.eventAt(i)
|
|
3110
|
+
if (event?.type === 'turn/start' && Number(event.data?.turn) === turn) {
|
|
3111
|
+
started = i
|
|
3112
|
+
break
|
|
3113
|
+
}
|
|
3114
|
+
}
|
|
3115
|
+
if (started < 0) return undefined
|
|
3116
|
+
for (let i = started + 1; i < session.seq; i += 1) {
|
|
3117
|
+
const event = session.eventAt(i)
|
|
3118
|
+
if (!event) continue
|
|
3119
|
+
if (event.type === 'turn/end' && Number(event.data?.turn) === turn) break
|
|
3120
|
+
if (event.type !== 'user/message') continue
|
|
3121
|
+
const data = event.data?.message ?? event.data
|
|
3122
|
+
if (!data || typeof data !== 'object') continue
|
|
3123
|
+
/*
|
|
3124
|
+
* planId 不在信封上:结果消息的 planId 在正文标记之间的 JSON 里,
|
|
3125
|
+
* plan 消息的 planId 在 plan 对象里。两者都走已有的解析器,避免
|
|
3126
|
+
* 对消息形状再发明一套假设。
|
|
3127
|
+
*/
|
|
3128
|
+
const result = parseResultMessage(data)
|
|
3129
|
+
if (result && typeof result.planId === 'string' && result.planId) return result.planId
|
|
3130
|
+
const planMessage = parseWorkplanMessage(data)
|
|
3131
|
+
const planId = planMessage?.plan?.planId
|
|
3132
|
+
if (typeof planId === 'string' && planId) return planId
|
|
3133
|
+
}
|
|
3134
|
+
return undefined
|
|
3135
|
+
}
|
|
3136
|
+
|
|
3137
|
+
/**
|
|
3138
|
+
* [1.8.15] 当前正在进行的回合号;没有打开中的回合时返回 undefined。
|
|
3139
|
+
*
|
|
3140
|
+
* `present` 的闸门需要知道「这一回合在结算哪个计划」。默认回放回答的是
|
|
3141
|
+
* 「最后定义的计划」,在 A 定义、B 后定义、A 的结果在 B 之后到达时会判错
|
|
3142
|
+
* 计划(T3 B5)。这里不新增状态,只从会话尾部回扫 `turn/start`;遇到
|
|
3143
|
+
* `turn/end` 说明当前没有打开中的回合。
|
|
3144
|
+
*/
|
|
3145
|
+
function currentTurnOf(session: any): number | undefined {
|
|
3146
|
+
if (typeof session?.eventAt !== 'function') return undefined
|
|
3147
|
+
for (let i = session.seq - 1; i >= 0; i -= 1) {
|
|
3148
|
+
let event
|
|
3149
|
+
try {
|
|
3150
|
+
event = session.eventAt(i)
|
|
3151
|
+
} catch {
|
|
3152
|
+
return undefined
|
|
3153
|
+
}
|
|
3154
|
+
if (!event) continue
|
|
3155
|
+
if (event.type === 'turn/start') {
|
|
3156
|
+
const turn = Number(event.data?.turn)
|
|
3157
|
+
return Number.isFinite(turn) && turn >= 1 ? turn : undefined
|
|
3158
|
+
}
|
|
3159
|
+
if (event.type === 'turn/end') return undefined
|
|
3160
|
+
}
|
|
3161
|
+
return undefined
|
|
3162
|
+
}
|
|
3163
|
+
|
|
3164
|
+
/**
|
|
3165
|
+
* [1.8.8] 结算/结果唤醒的回合也属于“本回合的任务”。
|
|
3166
|
+
*
|
|
3167
|
+
* 事故 turn 2 由 `subagent-settled` 消息唤醒:它不是 human task,
|
|
3168
|
+
* `humanMessages()` 不认,`maybePlan()` 不会写 `state.activeTurns`,
|
|
3169
|
+
* 收尾闸门因此在 turn 2 直接放行,模型又在 11/13 时收尾。
|
|
3170
|
+
* 这里按会话事件判断“这一回合是否装载了本计划的续跑输入”,
|
|
3171
|
+
* 只认三类来源,且子 Agent 结算必须来自本计划派出过的 child,
|
|
3172
|
+
* 避免无关后台任务把闸门误激活。
|
|
3173
|
+
*/
|
|
3174
|
+
function turnCarriesPlanWork(session: any, turn: number, record: any) {
|
|
3175
|
+
if (typeof session?.eventAt !== 'function' || !(turn >= 1)) return false
|
|
3176
|
+
const childIds = planChildIds(record)
|
|
3177
|
+
let started = -1
|
|
3178
|
+
for (let i = session.seq - 1; i >= 0; i -= 1) {
|
|
3179
|
+
const event = session.eventAt(i)
|
|
3180
|
+
if (event?.type === 'turn/start' && Number(event.data?.turn) === turn) {
|
|
3181
|
+
started = i
|
|
3182
|
+
break
|
|
3183
|
+
}
|
|
3184
|
+
}
|
|
3185
|
+
if (started < 0) return false
|
|
3186
|
+
for (let i = started + 1; i < session.seq; i += 1) {
|
|
3187
|
+
const event = session.eventAt(i)
|
|
3188
|
+
if (!event) continue
|
|
3189
|
+
if (event.type === 'turn/end' && Number(event.data?.turn) === turn) break
|
|
3190
|
+
if (event.type !== 'user/message') continue
|
|
3191
|
+
const message = event.data?.message ?? event.data
|
|
3192
|
+
const source = message?.source ?? {}
|
|
3193
|
+
const kind = String(source.kind ?? '')
|
|
3194
|
+
if (!PLAN_CONTINUATION_KINDS.has(kind)) continue
|
|
3195
|
+
if (kind === 'subagent-settled') {
|
|
3196
|
+
const sender = String(source.senderSessionId ?? '')
|
|
3197
|
+
/*
|
|
3198
|
+
* 只认“本计划派出过的 child”“本会话的真实子会话”或“父会话 spawn
|
|
3199
|
+
* 记录里出现过的 child”。第三者是 dispose 之后唯一还能取到的证据;
|
|
3200
|
+
* 三者都不命中时,无关后台任务不能把闸门误激活。
|
|
3201
|
+
*/
|
|
3202
|
+
if (!childIds.has(sender) && !isChildSessionOf(sender, session) && !spawnedChildIds(session).has(sender)) continue
|
|
3203
|
+
}
|
|
3204
|
+
return true
|
|
3205
|
+
}
|
|
3206
|
+
return false
|
|
3207
|
+
}
|
|
3208
|
+
|
|
3209
|
+
async function onTurnStopping(payload: any) {
|
|
3210
|
+
try {
|
|
3211
|
+
const agent = payload?.agent
|
|
3212
|
+
const session = agent?.session
|
|
3213
|
+
if (!agent || !session || !isRootSession(session)) return
|
|
3214
|
+
if (typeof agent.steer !== 'function') return
|
|
3215
|
+
const turn = Number(payload?.turn ?? 0)
|
|
3216
|
+
const known = state.records.get(session.id)
|
|
3217
|
+
/*
|
|
3218
|
+
* [1.8.8] 不再只认 human task 标记的 activeTurns:结算唤醒的回合
|
|
3219
|
+
* (subagent-settled / workplan-result / workplan-continue)同样装载
|
|
3220
|
+
* 了本计划的续跑输入,必须受同一道收尾闸门约束。
|
|
3221
|
+
*/
|
|
3222
|
+
if (state.activeTurns?.get?.(session.id) !== turn && !turnCarriesPlanWork(session, turn, known)) return
|
|
3223
|
+
if (isPlanModeActive(ctx, session)) return
|
|
3224
|
+
let record = known
|
|
3225
|
+
if (!record?.plan) {
|
|
3226
|
+
// [1.8.14] N5:优先按本回合结算消息里点名的计划重建,而不是最后生成的计划。
|
|
3227
|
+
record = reconstructFromSession(session, planIdFromTurn(session, turn))
|
|
3228
|
+
if (record?.plan) state.records.set(session.id, record)
|
|
3229
|
+
}
|
|
3230
|
+
if (!stopGateApplies(record, session, turn)) return
|
|
3231
|
+
if (record.dispatchPromise) {
|
|
3232
|
+
try {
|
|
3233
|
+
await record.dispatchPromise
|
|
3234
|
+
} catch {
|
|
3235
|
+
/* the failure is already on record.errors; the gate only needs the outcome */
|
|
3236
|
+
}
|
|
3237
|
+
finishRound(record, session)
|
|
3238
|
+
if (!stopGateApplies(record, session, turn)) return
|
|
3239
|
+
}
|
|
3240
|
+
const book = record.stopSteers && record.stopSteers.turn === turn
|
|
3241
|
+
? record.stopSteers
|
|
3242
|
+
: { turn, count: 0 }
|
|
3243
|
+
if (book.count >= STOP_STEER_LIMIT) return
|
|
3244
|
+
book.count += 1
|
|
3245
|
+
record.stopSteers = book
|
|
3246
|
+
const snapshot = derivePlanSnapshot(record.statuses)
|
|
3247
|
+
agent.steer(makeUserMessage(
|
|
3248
|
+
buildStopSteerText({
|
|
3249
|
+
planId: record.plan.planId,
|
|
3250
|
+
phase: record.phase,
|
|
3251
|
+
stats: snapshot.stats,
|
|
3252
|
+
statuses: snapshot.statuses,
|
|
3253
|
+
attempt: book.count,
|
|
3254
|
+
}),
|
|
3255
|
+
{
|
|
3256
|
+
kind: 'workplan-continue',
|
|
3257
|
+
form: 'notice',
|
|
3258
|
+
summary: `【计划未就绪】${snapshot.stats.done}/${snapshot.stats.total},本回合被要求按未完成口径收尾或继续`,
|
|
3259
|
+
},
|
|
3260
|
+
))
|
|
3261
|
+
ctx.logger?.warn?.(
|
|
3262
|
+
`dsh-workplan: 计划 ${record.plan.planId} 未通过交付就绪检查(${snapshot.stats.done}/${snapshot.stats.total}),`
|
|
3263
|
+
+ `已在回合收尾前要求继续/如实收尾(第 ${book.count} 次)`,
|
|
3264
|
+
)
|
|
3265
|
+
} catch (error) {
|
|
3266
|
+
ctx.logger?.warn?.(`dsh-workplan: 回合收尾检查失败:${error instanceof Error ? error.message : String(error)}`)
|
|
3267
|
+
}
|
|
3268
|
+
}
|
|
3269
|
+
|
|
3270
|
+
/**
|
|
3271
|
+
* [1.8.8] present 的硬闸门:计划未完成时不允许把产物作为成品交付。
|
|
3272
|
+
*
|
|
3273
|
+
* 1.8.7 只把这条规则写进提示词;事故里模型在回合中途直接 present,
|
|
3274
|
+
* 交付卡片先出现、收尾闸门后到,卡片无法撤回。这里在工具执行前拒绝,
|
|
3275
|
+
* 与回合闸门形成前后两道防线。
|
|
3276
|
+
*
|
|
3277
|
+
* [1.8.13] 判据换成与回合闸门同一个 `deliveryReadiness`。
|
|
3278
|
+
*
|
|
3279
|
+
* 1.8.9 只拦三类硬缺口(自检失败/验收失败/产物缺失),而把 legacy、
|
|
3280
|
+
* unverified、空 acceptance、undefined verification 当作“软缺口”放行;
|
|
3281
|
+
* 同时 `planIncomplete` 对 cancelled 直接返回 false,于是“取消 1/3 再
|
|
3282
|
+
* present”也能过(T5-C)。这两条都被本会话的行为探针证实。现在:
|
|
3283
|
+
* - 只有 `deliveryReady === true` 才能 present;
|
|
3284
|
+
* - 取消、降级(有 plan 时)、全 blocked、全 done 但无结构化证据一律拒绝;
|
|
3285
|
+
* - 拒绝文案必须给出可执行的出路(dispatch / update 补证 / 改 blocked),
|
|
3286
|
+
* cancel 不再被写成交付许可。
|
|
3287
|
+
*/
|
|
3288
|
+
/**
|
|
3289
|
+
* [1.8.16] 会话里所有「定义过」的计划。
|
|
3290
|
+
*
|
|
3291
|
+
* `reconstructFromSession(session)` 只回答「默认该看哪个计划」,而 `present`
|
|
3292
|
+
* 需要回答「会话里还有没有没交付完的计划」。1.8.15 的活体 E2E 暴露了这个差
|
|
3293
|
+
* 距:wp-6753e19f 停在 13/14,但最后定义的计划已就绪,`present` 仍然交付了
|
|
3294
|
+
* 报告。这里按日志里出现的 planId 逐个重建;数量极少(本会话只有 4 个),
|
|
3295
|
+
* 每个重建各自带回扫窗口,因此旧计划不会因为超过 2000 事件而消失。
|
|
3296
|
+
*/
|
|
3297
|
+
function sessionPlanRecords(session: any): any[] {
|
|
3298
|
+
if (typeof session?.eventAt !== 'function') return []
|
|
3299
|
+
const ids = new Set<string>()
|
|
3300
|
+
for (let i = 0; i < session.seq; i += 1) {
|
|
3301
|
+
let event
|
|
3302
|
+
try {
|
|
3303
|
+
event = session.eventAt(i)
|
|
3304
|
+
} catch {
|
|
3305
|
+
continue
|
|
3306
|
+
}
|
|
3307
|
+
if (!event || event.type !== 'user/message') continue
|
|
3308
|
+
const planId = parseWorkplanMessage(event.data)?.plan?.planId
|
|
3309
|
+
if (typeof planId === 'string' && planId) ids.add(planId)
|
|
3310
|
+
}
|
|
3311
|
+
const records: any[] = []
|
|
3312
|
+
for (const planId of ids) {
|
|
3313
|
+
const record = reconstructFromSession(session, planId)
|
|
3314
|
+
if (record?.plan) records.push(record)
|
|
3315
|
+
}
|
|
3316
|
+
return records
|
|
3317
|
+
}
|
|
3318
|
+
|
|
3319
|
+
/**
|
|
3320
|
+
* [1.8.18] The last plan that actually defines work, for the restart replay.
|
|
3321
|
+
*
|
|
3322
|
+
* The gate used to fall back only to the live record or the turn's plan. After
|
|
3323
|
+
* a restart both are gone, so a session whose last action was cancelling an
|
|
3324
|
+
* unfinished plan allowed `present` — contradicting the cancel tool's own
|
|
3325
|
+
* contract ("取消后如仍有未完成项或证据缺口,present 仍会被拒绝"). T5 E1/E6
|
|
3326
|
+
* pinned that hole.
|
|
3327
|
+
*
|
|
3328
|
+
* Empty plans are skipped: they are not delivery objects (U6), and accepting
|
|
3329
|
+
* one as "the last plan" would let a builder cancel real work and define an
|
|
3330
|
+
* empty plan as a shield. Older cancelled plans still do not block a newer
|
|
3331
|
+
* plan, so cancelling a stale plan does not deadlock the session.
|
|
3332
|
+
*/
|
|
3333
|
+
function lastGateablePlanRecord(session: any): any {
|
|
3334
|
+
if (typeof session?.eventAt !== 'function') return undefined
|
|
3335
|
+
for (let i = session.seq - 1; i >= 0; i -= 1) {
|
|
3336
|
+
let event
|
|
3337
|
+
try {
|
|
3338
|
+
event = session.eventAt(i)
|
|
3339
|
+
} catch {
|
|
3340
|
+
continue
|
|
3341
|
+
}
|
|
3342
|
+
if (!event || event.type !== 'user/message') continue
|
|
3343
|
+
const plan = parseWorkplanMessage(event.data)?.plan
|
|
3344
|
+
if (!plan || typeof plan.planId !== 'string' || plan.planId === '') continue
|
|
3345
|
+
if (definedSubtaskCount(plan) === 0) continue
|
|
3346
|
+
const record = reconstructFromSession(session, plan.planId)
|
|
3347
|
+
if (record?.plan && definedSubtaskCount(record.plan) > 0) return record
|
|
3348
|
+
}
|
|
3349
|
+
return undefined
|
|
3350
|
+
}
|
|
3351
|
+
|
|
3352
|
+
/**
|
|
3353
|
+
* [1.9.0] 点名 superseded 时的覆盖链判定(T8 §4.2 第 4 条、§6.3)。
|
|
3354
|
+
*
|
|
3355
|
+
* superseded 只是「责任已转移」,不是完成:本回合点名它时,判的是承接计划
|
|
3356
|
+
* 是否真的就绪。承接计划缺失/已终止/无法复核 ⇒ fail-closed(SUPERSEDED_STALE);
|
|
3357
|
+
* 承接计划未就绪 ⇒ 拒绝;只有承接计划 deliveryReady 才放行(产物来自承接计划)。
|
|
3358
|
+
*
|
|
3359
|
+
* [1.9.2] 返回值带上拒绝码(T8 §4.3 `judgeEffective`):覆盖链无法复核
|
|
3360
|
+
* ⇒ `SUPERSEDED_STALE`;覆盖链有效但承接计划未就绪 ⇒ `ACTIVE_NOT_READY`。
|
|
3361
|
+
* 文案保持逐字不变,码值走 `src/plan.ts` 的同一组常量。
|
|
3362
|
+
*/
|
|
3363
|
+
function supersededDenialVerdict(session: any, record: any): PresentDenialVerdict | undefined {
|
|
3364
|
+
const planId = record.plan?.planId ?? record.planId ?? ''
|
|
3365
|
+
const by = record.supersededBy
|
|
3366
|
+
const successorPlanId = typeof by?.successorPlanId === 'string' && by.successorPlanId
|
|
3367
|
+
? by.successorPlanId
|
|
3368
|
+
: typeof by?.planId === 'string' ? by.planId : ''
|
|
3369
|
+
if (!successorPlanId) {
|
|
3370
|
+
return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE,
|
|
3371
|
+
`计划 ${planId} 已被取代,但缺少可验证的承接计划(supersededBy.successorPlanId):`
|
|
3372
|
+
+ '覆盖证据失效(SUPERSEDED_STALE),不得调用 present;请向用户说明覆盖链无法复核并重新确认交付对象。')
|
|
3373
|
+
}
|
|
3374
|
+
/*
|
|
3375
|
+
* [W1] 覆盖摘要:present 复验从 mapping 重算摘要,不读缓存数值(T8 §6.3)。
|
|
3376
|
+
*
|
|
3377
|
+
* 摘要一旦对不上(含 mapping/digest 缺失),覆盖记录就无法复核 —— 无法复核
|
|
3378
|
+
* ≠ 通过,一律 stale。这条检查只证明「存下来的 mapping 没被改动」,不证明
|
|
3379
|
+
* 「两项工作在语义上等价」;后者仍只能由用户确认(V8)承载。
|
|
3380
|
+
*/
|
|
3381
|
+
const mapping = by?.mapping
|
|
3382
|
+
if (!Array.isArray(mapping)) {
|
|
3383
|
+
return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE,
|
|
3384
|
+
`计划 ${planId} 已被取代,但缺少可复算的逐项映射(supersededBy.mapping):`
|
|
3385
|
+
+ '覆盖证据失效(SUPERSEDED_STALE),不得调用 present,不得声称“已完成/最终版/已交付”;'
|
|
3386
|
+
+ '请重新按用户确认的逐项映射做覆盖迁移,并由运行时写入复算后的 digest。')
|
|
3387
|
+
}
|
|
3388
|
+
const computedDigest = computeMappingDigest(mapping)
|
|
3389
|
+
if (!verifyMappingDigest(mapping, by?.digest)) {
|
|
3390
|
+
const stored = typeof by?.digest === 'string' ? by.digest.slice(0, 15) : '缺失'
|
|
3391
|
+
return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE,
|
|
3392
|
+
`计划 ${planId} 已被取代,但覆盖证据摘要与逐项映射不一致(supersededBy.digest=${stored},`
|
|
3393
|
+
+ `重算=${computedDigest.slice(0, 15)}):覆盖证据失效(SUPERSEDED_STALE),不得调用 present,`
|
|
3394
|
+
+ '不得声称“已完成/最终版/已交付”;请重新按用户确认的逐项映射做覆盖迁移,并由运行时复算 digest。')
|
|
3395
|
+
}
|
|
3396
|
+
const successor = reconstructFromSession(session, successorPlanId)
|
|
3397
|
+
if (!successor?.plan || definedSubtaskCount(successor.plan) === 0 || isTerminalPhase(successor.phase)) {
|
|
3398
|
+
return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE,
|
|
3399
|
+
`计划 ${planId} 已被取代,但承接计划 ${successorPlanId} 不存在、不是交付对象或已终止:`
|
|
3400
|
+
+ '覆盖证据失效(SUPERSEDED_STALE)。被取代不等于完成:不得调用 present,不得声称“已完成/最终版/已交付”。')
|
|
3401
|
+
}
|
|
3402
|
+
const readiness = deliveryReadiness(derivePlanSnapshot(successor.statuses), { phase: successor.phase })
|
|
3403
|
+
if (!readiness.ready) {
|
|
3404
|
+
const ids = readiness.remaining.slice(0, 10).join('、')
|
|
3405
|
+
return presentDenial(PRESENT_DENY_CODES.ACTIVE_NOT_READY,
|
|
3406
|
+
`计划 ${planId} 已被取代,承接计划 ${successorPlanId} 只完成 ${readiness.done}/${readiness.total}`
|
|
3407
|
+
+ `${ids ? `,剩余 ${readiness.remaining.length} 项(${ids})` : ''}。`
|
|
3408
|
+
+ '被取代不等于完成:承接计划通过交付就绪检查之前不得调用 present。')
|
|
3409
|
+
}
|
|
3410
|
+
return undefined
|
|
3411
|
+
}
|
|
3412
|
+
|
|
3413
|
+
/**
|
|
3414
|
+
* [1.9.2] present 拒绝点的唯一出口:码值取常量,拒绝文案保持逐字不变。
|
|
3415
|
+
*
|
|
3416
|
+
* host 的 guard 契约是 `string`(`ctx.tools.checkGuards`),所以工具错误里
|
|
3417
|
+
* 仍只有文案;码值由 `presentDenialVerdict` 一并返回,供断言、日志与后续
|
|
3418
|
+
* UI 使用。所有分支都必须经由这里,不要在分支里手写码值。
|
|
3419
|
+
*/
|
|
3420
|
+
function presentDenial(code: PresentDenyCode, message: string): PresentDenialVerdict {
|
|
3421
|
+
return { code, message }
|
|
3422
|
+
}
|
|
3423
|
+
|
|
3424
|
+
function presentDenialVerdict(agent: any): PresentDenialVerdict | undefined {
|
|
3425
|
+
const session = agent?.session
|
|
3426
|
+
if (!session || !isRootSession(session)) return undefined
|
|
3427
|
+
if (isPlanModeActive(ctx, session)) return undefined
|
|
3428
|
+
/*
|
|
3429
|
+
* [1.8.16] Every plan in the session matters, not just the turn's plan.
|
|
3430
|
+
*
|
|
3431
|
+
* 1.8.15 taught this gate to prefer the plan named by the current turn's
|
|
3432
|
+
* messages, but a session can hold several plans at once (the incident
|
|
3433
|
+
* session itself ended with four). A live E2E on 1.8.15 showed the hole:
|
|
3434
|
+
* wp-6753e19f was still 13/14, the last defined plan was ready, and
|
|
3435
|
+
* `present` delivered the report. The gate now asks every plan in the log;
|
|
3436
|
+
* `dsh_workplan_cancel` is the documented escape hatch for a plan that
|
|
3437
|
+
* will not be finished.
|
|
3438
|
+
*/
|
|
3439
|
+
const turn = currentTurnOf(session)
|
|
3440
|
+
const turnPlanId = turn ? planIdFromTurn(session, turn) : undefined
|
|
3441
|
+
const candidates = sessionPlanRecords(session)
|
|
3442
|
+
const live = state.records.get(session.id)
|
|
3443
|
+
if (live?.plan && !candidates.some((item: any) => item.plan.planId === live.plan.planId)) candidates.push(live)
|
|
3444
|
+
if (turnPlanId && !candidates.some((item: any) => item.plan.planId === turnPlanId)) {
|
|
3445
|
+
const named = reconstructFromSession(session, turnPlanId)
|
|
3446
|
+
if (named?.plan) candidates.push(named)
|
|
3447
|
+
}
|
|
3448
|
+
if (candidates.length === 0) return undefined
|
|
3449
|
+
/*
|
|
3450
|
+
* [U6] a plan with zero defined subtasks is not a delivery object.
|
|
3451
|
+
* `deliveryReadiness` can never call it ready (`total > 0`), so judging it
|
|
3452
|
+
* only produced the false refusal "0 个子任务虽都已 done". Filter by the
|
|
3453
|
+
* definition itself — not by `statuses.length` — so a real plan whose
|
|
3454
|
+
* statuses failed to derive is still judged (and stays closed).
|
|
3455
|
+
*/
|
|
3456
|
+
const gateable = candidates.filter((item: any) => definedSubtaskCount(item.plan) > 0)
|
|
3457
|
+
if (gateable.length === 0) return undefined
|
|
3458
|
+
const unresolved = gateable
|
|
3459
|
+
.map((item: any) => ({
|
|
3460
|
+
record: item,
|
|
3461
|
+
readiness: deliveryReadiness(derivePlanSnapshot(item.statuses), { phase: item.phase }),
|
|
3462
|
+
}))
|
|
3463
|
+
/*
|
|
3464
|
+
* A cancelled plan is not a delivery blocker for *other* plans — the
|
|
3465
|
+
* incident session accumulates cancelled plans that will never be
|
|
3466
|
+
* finished, and blocking on them forever would deadlock delivery. It is
|
|
3467
|
+
* still checked below when it is the plan this turn (or the live record,
|
|
3468
|
+
* or the last defined plan after a restart) is about: cancel stops
|
|
3469
|
+
* execution, it does not make the work deliverable.
|
|
3470
|
+
*/
|
|
3471
|
+
.filter((entry: any) => !isTerminalPhase(entry.record.phase) && !entry.readiness.ready)
|
|
3472
|
+
if (unresolved.length > 1) {
|
|
3473
|
+
const lines = unresolved.slice(0, 6).map((entry: any) => {
|
|
3474
|
+
const ids = entry.readiness.remaining.slice(0, 6).join('、')
|
|
3475
|
+
const suffix = ids ? `(${ids}${entry.readiness.remaining.length > 6 ? '…' : ''})` : ''
|
|
3476
|
+
const gaps = entry.readiness.blockers.slice(0, 4).join(';')
|
|
3477
|
+
return `- 计划 ${entry.record.plan.planId}:完成 ${entry.readiness.done}/${entry.readiness.total}${suffix}`
|
|
3478
|
+
+ `${gaps ? `;证据缺口:${gaps}` : ''}`
|
|
3479
|
+
})
|
|
3480
|
+
return presentDenial(PRESENT_DENY_CODES.ACTIVE_NOT_READY,
|
|
3481
|
+
`本会话还有 ${unresolved.length} 个计划未通过交付就绪检查:\n${lines.join('\n')}\n`
|
|
3482
|
+
+ '在它们全部通过交付就绪检查之前,不得调用 present 交付任何产物:'
|
|
3483
|
+
+ '先调用 dsh_workplan_dispatch 续跑,证据缺口用 dsh_workplan_update 补齐。'
|
|
3484
|
+
+ '取消只停止执行,不会让未完成的计划变成可交付,也不能用来绕过这道检查。')
|
|
3485
|
+
}
|
|
3486
|
+
let record: any
|
|
3487
|
+
let readiness: any
|
|
3488
|
+
if (unresolved.length === 1) {
|
|
3489
|
+
record = unresolved[0].record
|
|
3490
|
+
readiness = unresolved[0].readiness
|
|
3491
|
+
} else {
|
|
3492
|
+
/*
|
|
3493
|
+
* No unfinished active plan. The plan this turn is about (or the live
|
|
3494
|
+
* record) may still be a cancelled one that never finished — T5-C pins
|
|
3495
|
+
* that `present` must be refused for it. After a restart neither exists,
|
|
3496
|
+
* so fall back to the last plan that defines work; otherwise the
|
|
3497
|
+
* sequence "cancel an unfinished plan, restart, present" silently
|
|
3498
|
+
* bypasses the cancel tool's own contract (T5 E1/E6).
|
|
3499
|
+
*/
|
|
3500
|
+
record = state.records.get(session.id)
|
|
3501
|
+
if (turnPlanId) record = reconstructFromSession(session, turnPlanId) ?? record
|
|
3502
|
+
if (!record?.plan) record = lastGateablePlanRecord(session)
|
|
3503
|
+
if (!record?.plan) return undefined
|
|
3504
|
+
if (definedSubtaskCount(record.plan) === 0) return undefined
|
|
3505
|
+
/*
|
|
3506
|
+
* [1.9.0] 终态解耦(T8 §4.3 P3):终态计划不再被自动选为判定对象。
|
|
3507
|
+
*
|
|
3508
|
+
* 只有「本回合结构化点名」时才判定;否则不再写回 live、不再拦截其它
|
|
3509
|
+
* 计划的交付。取消 ≠ 完成:记录仍是 cancelled 0/N,只是不再永久挡门。
|
|
3510
|
+
*/
|
|
3511
|
+
const namedThisTurn = Boolean(turnPlanId && record.plan.planId === turnPlanId)
|
|
3512
|
+
if (isTerminalPhase(record.phase) && !namedThisTurn) return undefined
|
|
3513
|
+
if (record.phase === 'superseded') {
|
|
3514
|
+
const denial = supersededDenialVerdict(session, record)
|
|
3515
|
+
if (denial) return denial
|
|
3516
|
+
return undefined
|
|
3517
|
+
}
|
|
3518
|
+
readiness = deliveryReadiness(derivePlanSnapshot(record.statuses), { phase: record.phase })
|
|
3519
|
+
if (readiness.ready) return undefined
|
|
3520
|
+
}
|
|
3521
|
+
if (record?.plan && !isTerminalPhase(record.phase)) state.records.set(session.id, record)
|
|
3522
|
+
const snapshot = derivePlanSnapshot(record.statuses)
|
|
3523
|
+
const planId = record.plan?.planId ?? record.planId
|
|
3524
|
+
const ids = readiness.remaining.slice(0, 10).join('、')
|
|
3525
|
+
const idSuffix = ids ? `(${ids}${readiness.remaining.length > 10 ? '…' : ''})` : ''
|
|
3526
|
+
const blockers = readiness.blockers.slice(0, 10).join(';')
|
|
3527
|
+
if (readiness.cancelled) {
|
|
3528
|
+
/*
|
|
3529
|
+
* [1.8.13] `deliveryReadiness` already puts the cancellation fact at the
|
|
3530
|
+
* head of `blockers`; repeating it here produced the T6b/C0 copy with the
|
|
3531
|
+
* same sentence twice. Only the *evidence* gaps belong in this suffix.
|
|
3532
|
+
*/
|
|
3533
|
+
const gaps = readiness.blockers
|
|
3534
|
+
.filter((line: string) => !line.startsWith('计划已取消但只完成'))
|
|
3535
|
+
.slice(0, 10)
|
|
3536
|
+
.join(';')
|
|
3537
|
+
if (readiness.remaining.length === 0) {
|
|
3538
|
+
return presentDenial(PRESENT_DENY_CODES.CANCELLED_NAMED,
|
|
3539
|
+
`计划 ${planId} 已取消,${readiness.total} 个子任务虽已 done,但证据未通过:${gaps || '缺少结构化证据'}。`
|
|
3540
|
+
+ '取消只停止执行,不等于完成:不得调用 present,不得声称“已完成/最终版/已交付”;'
|
|
3541
|
+
+ '答复必须说明取消状态与证据缺口,不能写成“全部完成”。')
|
|
3542
|
+
}
|
|
3543
|
+
return presentDenial(PRESENT_DENY_CODES.CANCELLED_NAMED,
|
|
3544
|
+
`计划 ${planId} 已取消,但只完成 ${readiness.done}/${readiness.total},剩余 ${readiness.remaining.length} 项${idSuffix}`
|
|
3545
|
+
+ `${gaps ? `;证据缺口:${gaps}` : ''}。`
|
|
3546
|
+
+ '取消只停止执行,不等于完成,也不会让未完成项变成可交付:不得调用 present,不得声称“已完成/最终版/已交付”;'
|
|
3547
|
+
+ '答复开头必须写「未完成:剩余 N 项(列出 ID)与原因」。')
|
|
3548
|
+
}
|
|
3549
|
+
/*
|
|
3550
|
+
* [1.9.2] P1 的单一映射:`activeDenyCode` 只看就绪结果。
|
|
3551
|
+
* `remaining` 为空但 `blockers` 非空 ⇒ `EVIDENCE_GAP`(T9 C05 的修法);
|
|
3552
|
+
* 还有子任务没做完 ⇒ `ACTIVE_NOT_READY`。两个分支共用同一个码值来源。
|
|
3553
|
+
*/
|
|
3554
|
+
const activeCode = activeDenyCode(readiness)
|
|
3555
|
+
if (readiness.remaining.length === 0) {
|
|
3556
|
+
return presentDenial(activeCode,
|
|
3557
|
+
`计划 ${planId} 的 ${readiness.total} 个子任务虽都已 done,但证据未通过:${blockers || '缺少结构化证据'}。`
|
|
3558
|
+
+ '在 deliveryReady 变为 true 之前,产物不得作为成品交付:'
|
|
3559
|
+
+ "用 dsh_workplan_update 为这些子任务补 verification='structured' 与 acceptance(每项 result='pass' 并附证据),"
|
|
3560
|
+
+ '或把对应子任务改回 blocked 并写明原因;不要调用 present。')
|
|
3561
|
+
}
|
|
3562
|
+
return presentDenial(activeCode,
|
|
3563
|
+
`计划 ${planId} 未完成:完成 ${readiness.done}/${readiness.total},剩余 ${readiness.remaining.length} 项${idSuffix}`
|
|
3564
|
+
+ `${blockers ? `;另有证据缺口:${blockers}` : ''}。`
|
|
3565
|
+
+ '在计划通过交付就绪检查之前不得调用 present 交付产物:先调用 dsh_workplan_dispatch 续跑剩余项;'
|
|
3566
|
+
+ '证据缺口用 dsh_workplan_update 补齐;确实无法继续时,把答复写成「未完成:剩余 N 项与原因」。'
|
|
3567
|
+
+ '取消只停止执行,不会改变“未完成”的结论。')
|
|
3568
|
+
}
|
|
3569
|
+
|
|
3570
|
+
/**
|
|
3571
|
+
* 兼容入口:host 的 guard 只接受字符串,所以工具错误仍是原来的文案。
|
|
3572
|
+
* 需要码值时调用 `presentDenialVerdict`。
|
|
3573
|
+
*/
|
|
3574
|
+
function presentDenialReason(agent: any) {
|
|
3575
|
+
return presentDenialVerdict(agent)?.message
|
|
3576
|
+
}
|
|
3577
|
+
|
|
3578
|
+
/*
|
|
3579
|
+
* [1.8.18] 已交付文件的写保护(T7-N2)。
|
|
3580
|
+
*
|
|
3581
|
+
* `present` 不复制内容(工具描述原文:the user opens the current files),
|
|
3582
|
+
* write/edit 也不校验路径是否已经交付。事故的迟到回合在 12:13 两次原地改写
|
|
3583
|
+
* 12:04 已 present 的报告,卡片背后的文件因此变了。这里把「present 时点
|
|
3584
|
+
* 已经定义过的计划」记到路径上:只要这些计划至今仍未通过交付就绪检查,
|
|
3585
|
+
* 根会话对同一路径的 write/edit 就被拒绝。present 之后才定义的新计划不在
|
|
3586
|
+
* 集合里,所以“用户要求改版 → 新计划”不会被写保护卡死;cancel 仍是显式出路。
|
|
3587
|
+
*/
|
|
3588
|
+
const presentedPaths = new Map<string, {
|
|
3589
|
+
scannedTo: number
|
|
3590
|
+
planIds: Set<string>
|
|
3591
|
+
entries: Array<{ raw: string; canonical?: string; planIds: string[] }>
|
|
3592
|
+
}>()
|
|
3593
|
+
|
|
3594
|
+
function canonicalPath(session: any, value: any) {
|
|
3595
|
+
if (typeof value !== 'string' || value.trim() === '') return undefined
|
|
3596
|
+
if (isAbsolute(value)) return resolve(value)
|
|
3597
|
+
const cwd = session?.header?.cwd ?? options.cwd
|
|
3598
|
+
return typeof cwd === 'string' && cwd ? resolve(cwd, value) : undefined
|
|
3599
|
+
}
|
|
3600
|
+
|
|
3601
|
+
function presentedEntries(session: any) {
|
|
3602
|
+
if (typeof session?.eventAt !== 'function' || !(Number(session.seq) >= 0)) return []
|
|
3603
|
+
const cache = presentedPaths.get(session.id)
|
|
3604
|
+
const reusable = cache !== undefined && cache.scannedTo <= Number(session.seq)
|
|
3605
|
+
const from = reusable ? cache.scannedTo : 0
|
|
3606
|
+
const seen = new Set<string>(reusable ? cache.planIds : [])
|
|
3607
|
+
const entries = reusable ? cache.entries.slice() : []
|
|
3608
|
+
for (let i = from; i < Number(session.seq); i += 1) {
|
|
3609
|
+
let event
|
|
3610
|
+
try {
|
|
3611
|
+
event = session.eventAt(i)
|
|
3612
|
+
} catch {
|
|
3613
|
+
continue
|
|
3614
|
+
}
|
|
3615
|
+
if (!event) continue
|
|
3616
|
+
if (event.type === 'user/message') {
|
|
3617
|
+
const planId = parseWorkplanMessage(event.data)?.plan?.planId
|
|
3618
|
+
if (typeof planId === 'string' && planId) seen.add(planId)
|
|
3619
|
+
continue
|
|
3620
|
+
}
|
|
3621
|
+
if (event.type !== 'deliverables/presented') continue
|
|
3622
|
+
const planIds = [...seen]
|
|
3623
|
+
for (const file of event.data?.files ?? []) {
|
|
3624
|
+
if (typeof file?.path !== 'string' || file.path.trim() === '') continue
|
|
3625
|
+
entries.push({ raw: file.path, canonical: canonicalPath(session, file.path), planIds })
|
|
3626
|
+
}
|
|
3627
|
+
}
|
|
3628
|
+
presentedPaths.set(session.id, {
|
|
3629
|
+
scannedTo: Number(session.seq),
|
|
3630
|
+
planIds: seen,
|
|
3631
|
+
entries,
|
|
3632
|
+
})
|
|
3633
|
+
return entries
|
|
3634
|
+
}
|
|
3635
|
+
|
|
3636
|
+
function recordForPlan(session: any, planId: string) {
|
|
3637
|
+
const live = state.records.get(session.id)
|
|
3638
|
+
if (live?.plan?.planId === planId) return live
|
|
3639
|
+
return reconstructFromSession(session, planId)
|
|
3640
|
+
}
|
|
3641
|
+
|
|
3642
|
+
function presentedWriteDenialReason(agent: any, args: any) {
|
|
3643
|
+
const session = agent?.session
|
|
3644
|
+
if (!session || !isRootSession(session)) return undefined
|
|
3645
|
+
if (isPlanModeActive(ctx, session)) return undefined
|
|
3646
|
+
const entries = presentedEntries(session)
|
|
3647
|
+
if (entries.length === 0) return undefined
|
|
3648
|
+
const requested = args?.file_path ?? args?.path
|
|
3649
|
+
if (typeof requested !== 'string' || requested.trim() === '') return undefined
|
|
3650
|
+
const canonical = canonicalPath(session, requested)
|
|
3651
|
+
const matched = entries.filter((entry: any) =>
|
|
3652
|
+
entry.raw === requested
|
|
3653
|
+
|| (canonical !== undefined && entry.canonical !== undefined && entry.canonical === canonical))
|
|
3654
|
+
if (matched.length === 0) return undefined
|
|
3655
|
+
const planIds = new Set<string>()
|
|
3656
|
+
for (const entry of matched) for (const planId of entry.planIds) planIds.add(planId)
|
|
3657
|
+
if (planIds.size === 0) return undefined
|
|
3658
|
+
const unresolved = [...planIds]
|
|
3659
|
+
.map((planId) => recordForPlan(session, planId))
|
|
3660
|
+
.filter((record: any) => record?.plan
|
|
3661
|
+
&& !isTerminalPhase(record.phase)
|
|
3662
|
+
&& !deliveryReadiness(derivePlanSnapshot(record.statuses), { phase: record.phase }).ready)
|
|
3663
|
+
if (unresolved.length === 0) return undefined
|
|
3664
|
+
const ids = unresolved.slice(0, 4).map((record: any) => record.plan.planId)
|
|
3665
|
+
return `文件 ${requested} 已通过 present 交付给用户,而交付时点已存在的计划`
|
|
3666
|
+
+ `${ids.length ? ` ${ids.join('、')}` : ''} 仍未通过交付就绪检查。`
|
|
3667
|
+
+ '计划未就绪期间不得原地改写已交付文件:先调用 dsh_workplan_dispatch 续跑剩余项,'
|
|
3668
|
+
+ '完成后重新 present 新版本;确实不做的计划用 dsh_workplan_cancel 显式取消。'
|
|
3669
|
+
+ '(present 之后新建的计划不受此限制。)'
|
|
3670
|
+
}
|
|
3671
|
+
|
|
2067
3672
|
function plansPayload(sessionId: any) {
|
|
2068
|
-
|
|
3673
|
+
/*
|
|
3674
|
+
* [1.8.15] The feed must carry build identity too.
|
|
3675
|
+
*
|
|
3676
|
+
* `status` learned version/runtime in 1.8.14, but the Web UI reads this
|
|
3677
|
+
* feed only — so after a rebuild the card could not tell "the process is
|
|
3678
|
+
* still running yesterday's bytes" (T5c §6.2). Same helpers, one source.
|
|
3679
|
+
*/
|
|
3680
|
+
return {
|
|
3681
|
+
...buildPlansPayload(ctx, state, sessionId),
|
|
3682
|
+
version: pluginVersion,
|
|
3683
|
+
runtime: runtimeIdentity(),
|
|
3684
|
+
}
|
|
2069
3685
|
}
|
|
2070
3686
|
|
|
2071
3687
|
async function route(req: any, res: any, connectionCtx: any = ctx) {
|
|
@@ -2138,10 +3754,16 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
|
|
|
2138
3754
|
state,
|
|
2139
3755
|
limits,
|
|
2140
3756
|
onPreStep,
|
|
3757
|
+
onTurnStopping,
|
|
3758
|
+
presentDenialReason,
|
|
3759
|
+
presentDenialVerdict,
|
|
3760
|
+
supersededDenialVerdict,
|
|
3761
|
+
presentedWriteDenialReason,
|
|
2141
3762
|
updateStatus,
|
|
2142
3763
|
cancelPlan,
|
|
2143
3764
|
dispatchTool,
|
|
2144
3765
|
statusTool,
|
|
3766
|
+
followupTool,
|
|
2145
3767
|
plansPayload,
|
|
2146
3768
|
route,
|
|
2147
3769
|
dispose,
|
|
@@ -2193,6 +3815,16 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
2193
3815
|
if (isSocialMessage(taskText)) return downstream
|
|
2194
3816
|
if (isVagueContinuation(taskText)) return downstream
|
|
2195
3817
|
if (isStatusQuestion(taskText)) return downstream
|
|
3818
|
+
/*
|
|
3819
|
+
* [1.8.7] Remember that this turn carries a real task.
|
|
3820
|
+
*
|
|
3821
|
+
* `agent/turn-stopping` must only object on turns whose plan belongs to the
|
|
3822
|
+
* user's actual request. A plan left paused in an earlier turn must not turn
|
|
3823
|
+
* every later "谢谢/进度如何" turn into a forced 20-minute dispatch, so the
|
|
3824
|
+
* stop gate reads this marker and stays silent on social or status turns.
|
|
3825
|
+
*/
|
|
3826
|
+
if (!state.activeTurns) state.activeTurns = new Map()
|
|
3827
|
+
state.activeTurns.set(session.id, Number(payload.turn ?? 0))
|
|
2196
3828
|
const conversationContext = recentConversation(session)
|
|
2197
3829
|
const existing = state.records.get(session.id)
|
|
2198
3830
|
if (existing?.plan?.createdTurn === payload.turn) return downstream
|
|
@@ -2203,7 +3835,13 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
|
|
|
2203
3835
|
// A plan committed but not yet dispatched must not be overwritten in the
|
|
2204
3836
|
// same turn; a later turn may supersede it, otherwise one abandoned plan
|
|
2205
3837
|
// would lock planning forever.
|
|
2206
|
-
|
|
3838
|
+
//
|
|
3839
|
+
// [1.9.2] 自动覆盖路径**只允许**写 cancelled,永不写 superseded(规则设计
|
|
3840
|
+
// §7.1:自动路径没有逐项映射与用户确认,满足不了 V4–V8)。它也不得把已经
|
|
3841
|
+
// superseded 的终态记录改回 cancelled:内存写 cancelled、日志里仍是
|
|
3842
|
+
// supersede 信封,会让 live 与 replay 分叉。终态记录由 present 的终态解耦
|
|
3843
|
+
// 处理(不再自动挡门),不需要在这里「取消」。
|
|
3844
|
+
if (existing?.plan && !existing.dispatchedAt && !isTerminalPhase(existing.phase)) {
|
|
2207
3845
|
if (existing.plan.createdTurn === payload.turn) return downstream
|
|
2208
3846
|
existing.phase = 'cancelled'
|
|
2209
3847
|
existing.cancelledAt = Date.now()
|
|
@@ -2366,6 +4004,10 @@ export function updateToolOutputSchema() {
|
|
|
2366
4004
|
subtaskId: { type: 'string' },
|
|
2367
4005
|
status: { type: 'string' },
|
|
2368
4006
|
stats: { type: 'object' },
|
|
4007
|
+
deliveryReady: { type: 'boolean' },
|
|
4008
|
+
deliveryBlockers: { type: 'array' },
|
|
4009
|
+
deliveryRemaining: { type: 'array' },
|
|
4010
|
+
hint: { type: 'string' },
|
|
2369
4011
|
},
|
|
2370
4012
|
required: ['ok'],
|
|
2371
4013
|
additionalProperties: true,
|
|
@@ -2380,6 +4022,44 @@ export function cancelToolOutputSchema() {
|
|
|
2380
4022
|
planId: { type: 'string' },
|
|
2381
4023
|
phase: { type: 'string' },
|
|
2382
4024
|
reason: { type: 'string' },
|
|
4025
|
+
/*
|
|
4026
|
+
* [1.8.14] `cancelRecorded` is the difference between "the UI says
|
|
4027
|
+
* cancelled" and "a restart will still say cancelled". A cancel whose
|
|
4028
|
+
* durable append failed reports false so the caller does not build on it.
|
|
4029
|
+
*/
|
|
4030
|
+
cancelRecorded: { type: 'boolean' },
|
|
4031
|
+
alreadyCancelled: { type: 'boolean' },
|
|
4032
|
+
abortedRunning: { type: 'boolean' },
|
|
4033
|
+
/*
|
|
4034
|
+
* [1.9.2] `disposition="superseded"` answers. `supersedeRecorded` is the
|
|
4035
|
+
* durable-write witness for the supersede envelope (the cancelled answer
|
|
4036
|
+
* uses `cancelRecorded`); `alreadySuperseded` is the §7.4 idempotent
|
|
4037
|
+
* re-submission. `code` carries the SUPERSEDE_* refusal; `gaps` /
|
|
4038
|
+
* `missingFrom` / `problems` explain exactly which V-rule failed so a
|
|
4039
|
+
* caller can repair the mapping instead of guessing.
|
|
4040
|
+
*/
|
|
4041
|
+
disposition: { type: 'string' },
|
|
4042
|
+
supersededAt: { type: 'number' },
|
|
4043
|
+
supersedeRecorded: { type: 'boolean' },
|
|
4044
|
+
alreadySuperseded: { type: 'boolean' },
|
|
4045
|
+
coverage: { type: 'string' },
|
|
4046
|
+
requiredCount: { type: 'number' },
|
|
4047
|
+
coveredCount: { type: 'number' },
|
|
4048
|
+
successorSeenAtSeq: { type: 'number' },
|
|
4049
|
+
confirmedAtSeq: { type: 'number' },
|
|
4050
|
+
supersededBy: {
|
|
4051
|
+
type: 'object',
|
|
4052
|
+
properties: {
|
|
4053
|
+
planId: { type: 'string' },
|
|
4054
|
+
},
|
|
4055
|
+
additionalProperties: true,
|
|
4056
|
+
},
|
|
4057
|
+
code: { type: 'string' },
|
|
4058
|
+
error: { type: 'string' },
|
|
4059
|
+
hint: { type: 'string' },
|
|
4060
|
+
gaps: { type: 'array', items: { type: 'string' } },
|
|
4061
|
+
missingFrom: { type: 'array', items: { type: 'string' } },
|
|
4062
|
+
problems: { type: 'array', items: { type: 'string' } },
|
|
2383
4063
|
},
|
|
2384
4064
|
required: ['ok'],
|
|
2385
4065
|
additionalProperties: true,
|
|
@@ -2401,6 +4081,13 @@ export function statusToolOutputSchema() {
|
|
|
2401
4081
|
statuses: { type: 'array' },
|
|
2402
4082
|
errors: { type: 'array' },
|
|
2403
4083
|
resumeLimit: { type: 'number' },
|
|
4084
|
+
version: { type: 'string' },
|
|
4085
|
+
// [1.8.14] Loaded-build identity: version alone cannot prove which bytes
|
|
4086
|
+
// the process is running after a rebuild or a profile recomposition.
|
|
4087
|
+
runtime: { type: 'object' },
|
|
4088
|
+
deliveryReady: { type: 'boolean' },
|
|
4089
|
+
deliveryBlockers: { type: 'array' },
|
|
4090
|
+
deliveryRemaining: { type: 'array' },
|
|
2404
4091
|
hint: { type: 'string' },
|
|
2405
4092
|
error: { type: 'string' },
|
|
2406
4093
|
code: { type: 'string' },
|
|
@@ -2421,6 +4108,18 @@ export function dispatchToolOutputSchema() {
|
|
|
2421
4108
|
running: { type: 'boolean' },
|
|
2422
4109
|
joined: { type: 'boolean' },
|
|
2423
4110
|
mode: { type: 'string' },
|
|
4111
|
+
/*
|
|
4112
|
+
* [1.8.7] `ok:true` used to be the only success signal, so a budget pause
|
|
4113
|
+
* (10/13) read as a finished dispatch. `complete` is the field the model
|
|
4114
|
+
* must test before it presents anything.
|
|
4115
|
+
*/
|
|
4116
|
+
complete: { type: 'boolean' },
|
|
4117
|
+
remaining: { type: 'integer' },
|
|
4118
|
+
deliveryReady: { type: 'boolean' },
|
|
4119
|
+
deliveryBlockers: { type: 'array' },
|
|
4120
|
+
deliveryRemaining: { type: 'array' },
|
|
4121
|
+
version: { type: 'string' },
|
|
4122
|
+
runtime: { type: 'object' },
|
|
2424
4123
|
elapsedMs: { type: 'number' },
|
|
2425
4124
|
statuses: { type: 'array' },
|
|
2426
4125
|
phase: { type: 'string' },
|