dsh-workplan 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/plan.ts CHANGED
@@ -21,6 +21,28 @@ export const RESULT_MARKER_BEGIN = '<!-- DSH-WORKPLAN-RESULT:BEGIN -->'
21
21
  export const RESULT_MARKER_END = '<!-- DSH-WORKPLAN-RESULT:END -->'
22
22
  export const CANCEL_MARKER_BEGIN = '<!-- DSH-WORKPLAN-CANCEL:BEGIN -->'
23
23
  export const CANCEL_MARKER_END = '<!-- DSH-WORKPLAN-CANCEL:END -->'
24
+ /*
25
+ * [1.7.0] Two new durable message kinds.
26
+ *
27
+ * The child's structured result travels inside its own reply (not the session
28
+ * log), while a manual re-adjudication by the main Agent must survive a page
29
+ * refresh — before this it existed only in memory and vanished on reload.
30
+ */
31
+ export const EVIDENCE_MARKER_BEGIN = '<!-- WORKPLAN_EVIDENCE:START -->'
32
+ export const EVIDENCE_MARKER_END = '<!-- WORKPLAN_EVIDENCE:END -->'
33
+ export const UPDATE_MARKER_BEGIN = '<!-- DSH-WORKPLAN-UPDATE:BEGIN -->'
34
+ export const UPDATE_MARKER_END = '<!-- DSH-WORKPLAN-UPDATE:END -->'
35
+
36
+ /** Upper bound for the run-time conversation window (single truncation point). */
37
+ export const MAX_CONVERSATION_CHARS = 7000
38
+ /** Upper bound for one child evidence block; longer blocks are truncated. */
39
+ export const MAX_EVIDENCE_BLOCK_CHARS = 8000
40
+ export const MAX_EVIDENCE_ACCEPTANCE = 20
41
+ export const MAX_EVIDENCE_ARTIFACTS = 20
42
+ export const MAX_EVIDENCE_NEEDS = 10
43
+ export const VERIFICATIONS = Object.freeze(['structured', 'legacy', 'unverified', 'failed', 'unparsable'])
44
+ export const EVIDENCE_STATUSES = Object.freeze(['done', 'blocked', 'partial'])
45
+ export const ACCEPTANCE_RESULTS = Object.freeze(['pass', 'fail', 'unverified'])
24
46
 
25
47
  export const STATUSES = Object.freeze(['pending', 'in_progress', 'done', 'blocked'])
26
48
  export const LIKELIHOODS = Object.freeze(['low', 'medium', 'high'])
@@ -443,6 +465,14 @@ function readSubtasks(value: any, stageIndex: any, errors: any) {
443
465
  dependsOn: readStringArray(source.dependsOn, `${base}.dependsOn`, { min: 0, max: 12, itemMax: 16 }, errors),
444
466
  acceptance: readStringArray(source.acceptance, `${base}.acceptance`, { min: 1, max: 8, itemMax: 800 }, errors),
445
467
  risk: readString(source.risk, `${base}.risk`, 1, 1000, errors),
468
+ /*
469
+ * [1.7.0] Optional time estimate, advisory only. Validation never fails on
470
+ * a missing or out-of-range value: a plan that cannot be dispatched is
471
+ * worse than one carrying a rough estimate.
472
+ */
473
+ ...(Number.isFinite(Number(source.estimateMinutes))
474
+ ? { estimateMinutes: Math.min(15, Math.max(1, Math.round(Number(source.estimateMinutes)))) }
475
+ : {}),
446
476
  }
447
477
  })
448
478
  }
@@ -672,10 +702,14 @@ export function departmentLabel(id: any, language: any = 'zh') {
672
702
  return language === 'en' ? entry.en : entry.zh
673
703
  }
674
704
 
675
- export function buildPlannerPrompt(taskText: any, cwd: any, conversationContext: any = '') {
705
+ export function buildPlannerPrompt(taskText: any, cwd: any, conversationContext: any = '', budget: any = {}) {
676
706
  const departments = DEPARTMENT_IDS
677
707
  .map((id: any) => { const d = DEPARTMENTS[id as keyof typeof DEPARTMENTS]; return `- ${id}(${d.zh} / ${d.en})` })
678
708
  .join('\n')
709
+ const totalMinutes = Math.max(1, Math.round(Number(budget?.totalMinutes) || 20))
710
+ const childMinutes = Math.max(1, Math.round(Number(budget?.childMinutes) || 15))
711
+ const concurrency = Math.max(1, Number(budget?.concurrency) || MAX_CONCURRENT)
712
+ const resumes = Number.isFinite(Number(budget?.maxResumes)) ? Number(budget.maxResumes) : MAX_PLAN_RESUMES
679
713
  const task = truncate(taskText, 16000)
680
714
  const directory = typeof cwd === 'string' && cwd ? cwd : '(未知)'
681
715
  const context = truncate(conversationContext, 7000)
@@ -704,6 +738,12 @@ export function buildPlannerPrompt(taskText: any, cwd: any, conversationContext:
704
738
  '- 单个子任务应能在 10 分钟内完成;动手重的任务要拆成多个小步,避免整条计划被一个慢子任务拖住。',
705
739
  '- 不要输出 Markdown 代码围栏、解释或前后缀;只输出一个 JSON 对象。',
706
740
  '',
741
+ '本轮时间预算(硬事实,请据此规划规模):',
742
+ `- 一轮总预算约 ${totalMinutes} 分钟;单个子任务上限 ${childMinutes} 分钟;同时最多 ${concurrency} 个子任务并行。`,
743
+ `- 受阻后自动续跑额度 ${resumes} 次;总工作量超过一轮预算时,计划会被暂停并在下一轮继续。`,
744
+ '- 每个子任务必须写 estimateMinutes(整数 1-15):你预估它需要多少分钟。宁可估高,不要估低。',
745
+ '- 规模大就如实拆成多轮,不要为了塞进一轮而把多个交付物压进一个子任务。',
746
+ '',
707
747
  '可用部门:',
708
748
  departments,
709
749
  '',
@@ -756,7 +796,8 @@ export function buildPlannerPrompt(taskText: any, cwd: any, conversationContext:
756
796
  ' "outputs": ["输出/交付物"],',
757
797
  ' "dependsOn": [],',
758
798
  ' "acceptance": ["可测试的验收标准"],',
759
- ' "risk": "主要风险"',
799
+ ' "risk": "主要风险",',
800
+ ' "estimateMinutes": 5',
760
801
  ' }',
761
802
  ' ]',
762
803
  ' }',
@@ -801,7 +842,43 @@ export function buildPlanSummary(plan: any) {
801
842
  )
802
843
  }
803
844
 
804
- export function buildPlanMessage(plan: any) {
845
+ /**
846
+ * Conservative lower bound for how long this plan needs, in minutes.
847
+ *
848
+ * The estimate is deliberately a lower bound: `ceil(total / concurrency)` and
849
+ * the largest single estimate, whichever is larger. It only drives an advisory
850
+ * line in the plan message; it never blocks dispatch, because a legal plan that
851
+ * cannot start is a worse failure than one that is merely too big for one round.
852
+ */
853
+ export function estimatePlanMinutes(plan: any, fallbackMinutes = 15, concurrency = MAX_CONCURRENT) {
854
+ const subtasks = flattenSubtasks(plan).map((entry: any) => entry.subtask)
855
+ const total = subtasks.length
856
+ if (total === 0) return 0
857
+ const estimates = subtasks.map((subtask: any) => {
858
+ const value = Number(subtask?.estimateMinutes)
859
+ return Number.isFinite(value) && value > 0 ? value : fallbackMinutes
860
+ })
861
+ const maxEstimate = Math.max(...estimates)
862
+ const waves = Math.ceil(total / Math.max(1, concurrency))
863
+ const totalEstimate = estimates.reduce((sum: number, value: number) => sum + value, 0)
864
+ return Math.max(waves * maxEstimate, Math.ceil(totalEstimate / Math.max(1, concurrency)))
865
+ }
866
+
867
+ export function buildBudgetWarning(plan: any, totalBudgetMinutes = 20, maxResumes = MAX_PLAN_RESUMES) {
868
+ const minutes = estimatePlanMinutes(plan)
869
+ const budget = Math.max(1, Math.round(Number(totalBudgetMinutes) || 20))
870
+ if (minutes <= budget) return ''
871
+ const rounds = Math.max(1, Math.ceil(minutes / budget))
872
+ const missing = flattenSubtasks(plan).some((entry: any) => !Number.isFinite(Number(entry.subtask?.estimateMinutes)))
873
+ return [
874
+ `⚠ 预算提示:本计划 ${flattenSubtasks(plan).length} 项,按其估计约需 ${minutes} 分钟 > 本轮 ${budget} 分钟,`
875
+ + `预计需要约 ${rounds} 轮(续跑额度 ${maxResumes} 次)。`,
876
+ '建议:拆成多轮,或减少同时进行的子任务。',
877
+ ...(missing ? ['(部分子任务缺少 estimateMinutes,已按 15 分钟上限估算。)'] : []),
878
+ ].join('\n')
879
+ }
880
+
881
+ export function buildPlanMessage(plan: any, options: any = {}) {
805
882
  const summary = buildPlanSummary(plan)
806
883
  const payload = {
807
884
  kind: 'workplan',
@@ -812,7 +889,19 @@ export function buildPlanMessage(plan: any) {
812
889
  createdAt: plan.createdAt,
813
890
  plan,
814
891
  }
815
- const text = `${summary}\n\n${PLAN_MARKER_BEGIN}\n${JSON.stringify(payload)}\n${PLAN_MARKER_END}`
892
+ const warning = buildBudgetWarning(
893
+ plan,
894
+ options.totalBudgetMinutes ?? 20,
895
+ options.maxResumes ?? MAX_PLAN_RESUMES,
896
+ )
897
+ const text = [
898
+ summary,
899
+ ...(warning ? ['', warning] : []),
900
+ '',
901
+ PLAN_MARKER_BEGIN,
902
+ JSON.stringify(payload),
903
+ PLAN_MARKER_END,
904
+ ].join('\n')
816
905
  return makeUserMessage(text, { kind: 'workplan', form: 'notice', summary })
817
906
  }
818
907
 
@@ -885,6 +974,36 @@ export function buildResultMessage(result: any) {
885
974
  }
886
975
  const blocked = Number(result.stats?.blocked ?? 0)
887
976
  const paused = Number(result.stats?.pending ?? 0) > 0 && result.phase === 'paused'
977
+ /*
978
+ * [1.7.0] Evidence review block.
979
+ *
980
+ * A done row is no longer self-certifying: the main Agent is told exactly how
981
+ * many claims are unverified, which self-checks failed, which declared files
982
+ * are missing, and what a sibling department asked for. Keeping this out of
983
+ * the payload (it is derived) keeps the durable message small.
984
+ */
985
+ const statuses = Array.isArray(result.statuses) ? result.statuses : []
986
+ const unverified = statuses.filter((item: any) => item?.verification === 'unverified')
987
+ const failed = statuses.filter((item: any) => item?.verification === 'failed')
988
+ const legacy = statuses.filter((item: any) => item?.status === 'done' && item?.verification === 'legacy')
989
+ const missingArtifacts = statuses.flatMap((item: any) =>
990
+ (Array.isArray(item?.missingArtifacts) ? item.missingArtifacts : [])
991
+ .map((ref: any) => `${item.subtaskId}:${ref}`))
992
+ const needs = statuses.flatMap((item: any) =>
993
+ (Array.isArray(item?.needs) ? item.needs : []).map((need: any) => `${item.subtaskId}:${need}`))
994
+ const review: string[] = []
995
+ if (unverified.length > 0) {
996
+ review.push(`- 未验证 ${unverified.length} 条:${unverified.map((item: any) => item.subtaskId).join('、')}(完成但证据不足,需主 Agent 核对)`)
997
+ }
998
+ if (failed.length > 0) {
999
+ review.push(`- 自检失败 ${failed.length} 条:${failed.map((item: any) => item.subtaskId).join('、')}(已按受阻处理,禁止当完成)`)
1000
+ }
1001
+ if (legacy.length > 0) {
1002
+ review.push(`- 未提供结构化证据 ${legacy.length} 条:${legacy.map((item: any) => item.subtaskId).join('、')}(旧格式回传,按“未验证”对待)`)
1003
+ }
1004
+ if (missingArtifacts.length > 0) {
1005
+ review.push(`- 声明产物缺失:${missingArtifacts.slice(0, 10).join(';')}`)
1006
+ }
888
1007
  const lines = [
889
1008
  summary,
890
1009
  '',
@@ -892,6 +1011,10 @@ export function buildResultMessage(result: any) {
892
1011
  '1. 核对每个完成项的证据与验收标准;',
893
1012
  '2. 处理受阻项,必要时向用户确认;',
894
1013
  '3. 给出最终答复,不要声称未验证的完成。',
1014
+ ...(review.length > 0 ? ['', '验收核对:', ...review] : []),
1015
+ ...(needs.length > 0
1016
+ ? ['', '跨部门待转达(子 Agent 提出的需求,请逐条处理):', ...needs.slice(0, 10).map((line: string) => `- ${line}`)]
1017
+ : []),
895
1018
  // A blocked plan used to look identical to a finished one. State the exact
896
1019
  // recovery move so the model retries the failed work instead of rebuilding
897
1020
  // the whole plan or stopping to ask the user for a repeated request.
@@ -984,6 +1107,228 @@ export function parseCancelMessage(message: any) {
984
1107
  }
985
1108
  }
986
1109
 
1110
+ function readEvidenceAcceptance(value: any) {
1111
+ if (!Array.isArray(value)) return []
1112
+ return value.slice(0, MAX_EVIDENCE_ACCEPTANCE).map((item: any) => {
1113
+ const source = isRecord(item) ? item : {}
1114
+ const result = ACCEPTANCE_RESULTS.includes(source.result) ? source.result : 'unverified'
1115
+ return {
1116
+ criterion: truncate(String(source.criterion ?? ''), 500),
1117
+ result,
1118
+ evidence: truncate(String(source.evidence ?? ''), 300),
1119
+ }
1120
+ }).filter((item: any) => item.criterion !== '')
1121
+ }
1122
+
1123
+ function readEvidenceArtifacts(value: any) {
1124
+ if (!Array.isArray(value)) return []
1125
+ return value.slice(0, MAX_EVIDENCE_ARTIFACTS).map((item: any) => {
1126
+ const source = isRecord(item) ? item : {}
1127
+ const kind = ['file', 'url', 'note'].includes(source.kind) ? source.kind : 'note'
1128
+ const artifact: any = { kind, ref: truncate(String(source.ref ?? ''), 500) }
1129
+ if (typeof source.exists === 'boolean') artifact.exists = source.exists
1130
+ return artifact
1131
+ }).filter((item: any) => item.ref !== '')
1132
+ }
1133
+
1134
+ function readEvidenceNeeds(value: any) {
1135
+ if (!Array.isArray(value)) return []
1136
+ return value.slice(0, MAX_EVIDENCE_NEEDS)
1137
+ .map((item: any) => truncate(typeof item === 'string' ? item : String(item ?? ''), 300))
1138
+ .filter(Boolean)
1139
+ }
1140
+
1141
+ /**
1142
+ * Parse the child's structured evidence block.
1143
+ *
1144
+ * Only the last block is read: a child may quote the template from its prompt
1145
+ * before filling in the real one, and the filled-in copy is the last one.
1146
+ * A malformed block is reported as such instead of being silently ignored —
1147
+ * "cannot tell" must never default to "done".
1148
+ */
1149
+ export function parseEvidenceBlock(output: any) {
1150
+ const text = typeof output === 'string' ? output : ''
1151
+ const begin = text.lastIndexOf(EVIDENCE_MARKER_BEGIN)
1152
+ if (begin < 0) return { found: false, malformed: false, truncated: false, payload: null, raw: '' }
1153
+ const end = text.indexOf(EVIDENCE_MARKER_END, begin + EVIDENCE_MARKER_BEGIN.length)
1154
+ if (end < 0) return { found: true, malformed: true, truncated: false, payload: null, raw: '' }
1155
+ const raw = text.slice(begin + EVIDENCE_MARKER_BEGIN.length, end).trim()
1156
+ const truncated = raw.length > MAX_EVIDENCE_BLOCK_CHARS
1157
+ try {
1158
+ const payload = JSON.parse(raw)
1159
+ if (!isRecord(payload) || !EVIDENCE_STATUSES.includes(payload.status)) {
1160
+ return { found: true, malformed: true, truncated, payload: null, raw }
1161
+ }
1162
+ return { found: true, malformed: false, truncated, payload, raw }
1163
+ } catch {
1164
+ return { found: true, malformed: true, truncated, payload: null, raw }
1165
+ }
1166
+ }
1167
+
1168
+ const BLOCKED_LINE = /^\s*(BLOCKED|受阻|无法完成)\s*[::]\s*/i
1169
+
1170
+ /**
1171
+ * Deterministic verdict for one child result.
1172
+ *
1173
+ * This is the single place that decides done vs blocked, so the eight cases in
1174
+ * the acceptance table cannot drift apart between the runtime and the replay.
1175
+ * It never invents evidence and never upgrades a failed self-check to done.
1176
+ */
1177
+ export function adjudicateResult({ output, strict = true }: any) {
1178
+ const text = typeof output === 'string' ? output : ''
1179
+ const parsed = parseEvidenceBlock(text)
1180
+ if (!strict) {
1181
+ if (BLOCKED_LINE.test(text)) {
1182
+ return {
1183
+ status: 'blocked',
1184
+ verification: 'legacy',
1185
+ acceptance: [],
1186
+ artifacts: [],
1187
+ needs: [],
1188
+ error: text.replace(BLOCKED_LINE, '').trim() || '子 Agent 报告受阻',
1189
+ }
1190
+ }
1191
+ return { status: 'done', verification: 'legacy', acceptance: [], artifacts: [], needs: [], error: null }
1192
+ }
1193
+ if (parsed.malformed) {
1194
+ return {
1195
+ status: 'blocked',
1196
+ verification: 'unparsable',
1197
+ acceptance: [],
1198
+ artifacts: [],
1199
+ needs: [],
1200
+ error: '结果块无法解析,请主 Agent 核对',
1201
+ }
1202
+ }
1203
+ if (!parsed.found) {
1204
+ if (BLOCKED_LINE.test(text)) {
1205
+ return {
1206
+ status: 'blocked',
1207
+ verification: 'legacy',
1208
+ acceptance: [],
1209
+ artifacts: [],
1210
+ needs: [],
1211
+ error: text.replace(BLOCKED_LINE, '').trim() || '子 Agent 报告受阻',
1212
+ }
1213
+ }
1214
+ return { status: 'done', verification: 'legacy', acceptance: [], artifacts: [], needs: [], error: null }
1215
+ }
1216
+ const payload: any = parsed.payload
1217
+ const acceptance = readEvidenceAcceptance(payload.acceptance)
1218
+ const artifacts = readEvidenceArtifacts(payload.artifacts)
1219
+ const needs = readEvidenceNeeds(payload.needs)
1220
+ const blockedReason = truncate(String(payload.blockedReason ?? payload.error ?? ''), 2000)
1221
+ if (payload.status === 'blocked') {
1222
+ return {
1223
+ status: 'blocked',
1224
+ verification: 'structured',
1225
+ acceptance,
1226
+ artifacts,
1227
+ needs,
1228
+ error: blockedReason || '子 Agent 报告受阻',
1229
+ }
1230
+ }
1231
+ if (payload.status === 'partial') {
1232
+ const detail = truncate(String(payload.summary ?? payload.blockedReason ?? ''), 2000)
1233
+ return {
1234
+ status: 'blocked',
1235
+ verification: 'structured',
1236
+ acceptance,
1237
+ artifacts,
1238
+ needs,
1239
+ error: detail ? `部分完成:${detail}` : '部分完成',
1240
+ }
1241
+ }
1242
+ const failed = acceptance.filter((item: any) => item.result === 'fail')
1243
+ if (failed.length > 0) {
1244
+ return {
1245
+ status: 'blocked',
1246
+ verification: 'failed',
1247
+ acceptance,
1248
+ artifacts,
1249
+ needs,
1250
+ error: `自检未通过:${failed.map((item: any) => item.criterion).join(';')}`,
1251
+ }
1252
+ }
1253
+ const hasUnverified = acceptance.some((item: any) => item.result === 'unverified')
1254
+ return {
1255
+ status: 'done',
1256
+ verification: hasUnverified ? 'unverified' : 'structured',
1257
+ acceptance,
1258
+ artifacts,
1259
+ needs,
1260
+ error: null,
1261
+ }
1262
+ }
1263
+
1264
+ export function buildUpdateMessage(update: any) {
1265
+ const payload = {
1266
+ kind: 'workplan-update',
1267
+ version: PLAN_VERSION,
1268
+ planId: update.planId,
1269
+ subtaskId: update.subtaskId,
1270
+ status: update.status,
1271
+ ...(update.progress === undefined ? {} : { progress: update.progress }),
1272
+ ...(update.note === undefined ? {} : { note: update.note }),
1273
+ ...(update.evidence === undefined ? {} : { evidence: update.evidence }),
1274
+ ...(update.revision === undefined ? {} : { revision: update.revision }),
1275
+ at: update.at ?? Date.now(),
1276
+ }
1277
+ const summary = truncate(`【状态改判】${update.subtaskId} → ${update.status}`, 300)
1278
+ const lines = [
1279
+ summary,
1280
+ '',
1281
+ '这条记录是主 Agent 的人工改判,刷新/重启后按同一顺序回放,不会丢失。',
1282
+ '',
1283
+ UPDATE_MARKER_BEGIN,
1284
+ JSON.stringify(payload),
1285
+ UPDATE_MARKER_END,
1286
+ ]
1287
+ return makeUserMessage(lines.join('\n'), { kind: 'workplan-update', form: 'notice', summary })
1288
+ }
1289
+
1290
+ export function parseUpdateMessage(message: any) {
1291
+ const body = extractBetween(messageText(message), UPDATE_MARKER_BEGIN, UPDATE_MARKER_END)
1292
+ if (!body) return null
1293
+ try {
1294
+ const payload = JSON.parse(body)
1295
+ if (!isRecord(payload) || payload.kind !== 'workplan-update') return null
1296
+ return payload
1297
+ } catch {
1298
+ return null
1299
+ }
1300
+ }
1301
+
1302
+ /**
1303
+ * Read-only sibling briefing for one child.
1304
+ *
1305
+ * Departments cannot message each other directly (see collaboration docs), so
1306
+ * "紧密联系" is delivered as visibility: every child sees what its siblings are
1307
+ * producing and the status they reached. Only `done` siblings expose a summary,
1308
+ * which keeps half-finished work from leaking into another department's prompt.
1309
+ */
1310
+ export function buildTeamBrief(plan: any, statuses: any, subtask: any) {
1311
+ if (!plan || !Array.isArray(statuses)) return ''
1312
+ const byId = new Map(statuses.map((item: any) => [item.subtaskId, item]))
1313
+ const lines: string[] = []
1314
+ for (const { subtask: sibling } of flattenSubtasks(plan)) {
1315
+ if (sibling.id === subtask?.id) continue
1316
+ const status = byId.get(sibling.id)
1317
+ const state = typeof status?.status === 'string' ? status.status : 'pending'
1318
+ const outputHint = Array.isArray(sibling.outputs) && sibling.outputs.length > 0
1319
+ ? `;产出 ${truncate(sibling.outputs.join('、'), 120)}`
1320
+ : ''
1321
+ const summary = state === 'done' && typeof status?.summary === 'string' && status.summary
1322
+ ? `|摘要:${truncate(status.summary, 200)}`
1323
+ : ''
1324
+ lines.push(
1325
+ `- ${sibling.id} ${departmentLabel(sibling.department)}:目标 ${truncate(sibling.objective, 120)}${outputHint}|状态:${state}${summary}`,
1326
+ )
1327
+ }
1328
+ if (lines.length === 0) return ''
1329
+ return truncate(lines.join('\n'), 2000)
1330
+ }
1331
+
987
1332
  /*
988
1333
  * Replay a durable result message into statuses. Dashboard reconstruction used
989
1334
  * to read only the plan message, so after a page refresh every finished child
@@ -996,7 +1341,15 @@ export function applyResultStatuses(statuses: any, result: any) {
996
1341
  for (const entry of result.statuses) {
997
1342
  if (!isRecord(entry) || typeof entry.subtaskId !== 'string') continue
998
1343
  if (!STATUSES.includes(entry.status)) continue
999
- if (!next.some((item: any) => item.subtaskId === entry.subtaskId)) continue
1344
+ const current = next.find((item: any) => item.subtaskId === entry.subtaskId)
1345
+ if (!current) continue
1346
+ /*
1347
+ * A manually re-adjudicated status (durable `workplan-update`) must not be
1348
+ * rolled back by an older result snapshot. Only comparable revisions are
1349
+ * ordered; legacy entries without `revision` keep the old "last wins" rule.
1350
+ */
1351
+ if (Number.isInteger(entry.revision) && Number.isInteger(current.revision)
1352
+ && Number(entry.revision) < Number(current.revision)) continue
1000
1353
  try {
1001
1354
  next = applyStatus(next, entry.subtaskId, {
1002
1355
  status: entry.status,
@@ -1006,6 +1359,14 @@ export function applyResultStatuses(statuses: any, result: any) {
1006
1359
  finishedAt: entry.finishedAt ?? null,
1007
1360
  summary: typeof entry.summary === 'string' ? entry.summary : undefined,
1008
1361
  error: entry.error ?? null,
1362
+ verification: entry.verification,
1363
+ acceptance: entry.acceptance,
1364
+ artifacts: entry.artifacts,
1365
+ missingArtifacts: entry.missingArtifacts,
1366
+ needs: entry.needs,
1367
+ blockedBy: entry.blockedBy,
1368
+ revision: entry.revision,
1369
+ updatedBy: entry.updatedBy,
1009
1370
  })
1010
1371
  } catch {
1011
1372
  // Ignore a single corrupt historical status; the rest still replay.
@@ -1053,6 +1414,42 @@ export function applyStatus(statuses: any, subtaskId: any, patch: any) {
1053
1414
  if (patch.finishedAt !== undefined) next.finishedAt = patch.finishedAt
1054
1415
  if (patch.summary !== undefined) next.summary = truncate(String(patch.summary), 3000)
1055
1416
  if (patch.error !== undefined) next.error = patch.error === null ? null : truncate(String(patch.error), 2000)
1417
+ if (patch.verification !== undefined) {
1418
+ if (!VERIFICATIONS.includes(patch.verification)) {
1419
+ throw new PlanError(`非法 verification:${String(patch.verification)}`, 'INVALID_VERIFICATION')
1420
+ }
1421
+ next.verification = patch.verification
1422
+ }
1423
+ if (patch.acceptance !== undefined) next.acceptance = readEvidenceAcceptance(patch.acceptance)
1424
+ if (patch.artifacts !== undefined) next.artifacts = readEvidenceArtifacts(patch.artifacts)
1425
+ if (patch.missingArtifacts !== undefined) {
1426
+ let budget = 2000
1427
+ next.missingArtifacts = (Array.isArray(patch.missingArtifacts) ? patch.missingArtifacts : [])
1428
+ .slice(0, MAX_EVIDENCE_ARTIFACTS)
1429
+ .map((ref: any) => truncate(String(ref ?? ''), 300))
1430
+ .filter((ref: string) => {
1431
+ if (!ref || budget <= 0) return false
1432
+ budget -= ref.length
1433
+ return true
1434
+ })
1435
+ }
1436
+ if (patch.needs !== undefined) next.needs = readEvidenceNeeds(patch.needs)
1437
+ if (patch.blockedBy !== undefined) {
1438
+ next.blockedBy = (Array.isArray(patch.blockedBy) ? patch.blockedBy : [])
1439
+ .slice(0, 10)
1440
+ .filter((item: any) => isRecord(item) && typeof item.id === 'string')
1441
+ .map((item: any) => ({ id: item.id, reason: truncate(String(item.reason ?? ''), 300) }))
1442
+ }
1443
+ /*
1444
+ * [1.7.0] Monotonic revision + author.
1445
+ *
1446
+ * Every write bumps the revision, so a stale page (or an older replay entry)
1447
+ * can be told apart from a newer manual re-adjudication. `updatedBy` records
1448
+ * who wrote it: the child, the main Agent, or the system.
1449
+ */
1450
+ const revision = Number.isInteger(patch.revision) ? Number(patch.revision) : Number(current.revision ?? 0) + 1
1451
+ next.revision = Math.max(revision, Number(current.revision ?? 0) + 1)
1452
+ next.updatedBy = ['child', 'agent', 'system'].includes(patch.updatedBy) ? patch.updatedBy : 'system'
1056
1453
  if (patch.status === 'done') {
1057
1454
  next.progress = 100
1058
1455
  if (next.finishedAt === null) next.finishedAt = Date.now()
@@ -1073,6 +1470,13 @@ export function applyStatus(statuses: any, subtaskId: any, patch: any) {
1073
1470
  next.childId = null
1074
1471
  if (patch.summary === undefined) next.summary = ''
1075
1472
  if (patch.error === undefined) next.error = null
1473
+ // The evidence of the failed attempt must not survive a reset either.
1474
+ if (patch.verification === undefined) next.verification = undefined
1475
+ if (patch.acceptance === undefined) next.acceptance = undefined
1476
+ if (patch.artifacts === undefined) next.artifacts = undefined
1477
+ if (patch.missingArtifacts === undefined) next.missingArtifacts = undefined
1478
+ if (patch.needs === undefined) next.needs = undefined
1479
+ if (patch.blockedBy === undefined) next.blockedBy = undefined
1076
1480
  }
1077
1481
  if (patch.status === 'in_progress') {
1078
1482
  if (next.startedAt === null) next.startedAt = Date.now()
@@ -1499,22 +1903,33 @@ export function nextReadyInStage(plan: any, statuses: any[], stageId: string) {
1499
1903
  * Readiness across the whole plan, not per stage. A stage is only a grouping
1500
1904
  * label; making every later stage wait for every earlier stage lets one slow
1501
1905
  * child turn an entire plan red. Only real dependsOn edges gate a subtask.
1906
+ *
1907
+ * [1.7.0] A `done` dependency only counts when its declared file artifacts
1908
+ * actually exist. `dependencyOk` is injectable so the rule stays pure and can
1909
+ * be turned off for compatibility (`artifactGate:false`).
1502
1910
  */
1503
- export function readySubtasks(plan: any, statuses: any[]) {
1911
+ export function readySubtasks(plan: any, statuses: any[], options: any = {}) {
1504
1912
  const byId = new Map(statuses.map((item: any) => [item.subtaskId, item]))
1913
+ const dependencyOk = typeof options.dependencyOk === 'function'
1914
+ ? options.dependencyOk
1915
+ : (dependency: any) => Boolean(dependency) && dependency.status === 'done'
1505
1916
  return flattenSubtasks(plan)
1506
1917
  .map((entry: any) => entry.subtask)
1507
1918
  .filter((subtask: any) => {
1508
1919
  const status = byId.get(subtask.id)
1509
1920
  if (!status || status.status !== 'pending') return false
1510
- return subtask.dependsOn.every((dependency: any) => byId.get(dependency)?.status === 'done')
1921
+ return subtask.dependsOn.every((dependency: any) => dependencyOk(byId.get(dependency), dependency))
1511
1922
  })
1512
1923
  }
1513
1924
 
1514
- export function markDependentsBlocked(plan: any, statuses: any, blockedId: any) {
1925
+ export function markDependentsBlocked(plan: any, statuses: any, blockedId: any, cause: any = null) {
1515
1926
  let next = statuses.slice()
1516
1927
  let changed = true
1517
1928
  const blocked = new Set([blockedId])
1929
+ const upstreamLabel = (id: any) => {
1930
+ const title = findSubtask(plan, id)?.subtask?.title
1931
+ return title ? `${id}「${title}」` : String(id)
1932
+ }
1518
1933
  while (changed) {
1519
1934
  changed = false
1520
1935
  for (const { subtask } of flattenSubtasks(plan)) {
@@ -1522,9 +1937,21 @@ export function markDependentsBlocked(plan: any, statuses: any, blockedId: any)
1522
1937
  const status = next.find((item: any) => item.subtaskId === subtask.id)
1523
1938
  if (!status || status.status !== 'pending') continue
1524
1939
  if (subtask.dependsOn.some((dependency: any) => blocked.has(dependency))) {
1940
+ const direct = subtask.dependsOn.filter((id: any) => blocked.has(id))
1941
+ /*
1942
+ * Name the upstream and the concrete cause. "上游子任务受阻" alone sent
1943
+ * the main Agent back to the plan to guess which child failed and why;
1944
+ * the reason and the missing artifacts belong in the message.
1945
+ */
1946
+ const parts = [`上游子任务受阻:${direct.map(upstreamLabel).join('、')}`]
1947
+ if (cause?.reason) parts.push(`原因:${truncate(String(cause.reason), 300)}`)
1948
+ if (Array.isArray(cause?.missingArtifacts) && cause.missingArtifacts.length > 0) {
1949
+ parts.push(`缺失产物:${cause.missingArtifacts.slice(0, 10).join('、')}`)
1950
+ }
1525
1951
  next = applyStatus(next, subtask.id, {
1526
1952
  status: 'blocked',
1527
- error: `上游子任务受阻:${subtask.dependsOn.filter((id: any) => blocked.has(id)).join('、')}`,
1953
+ error: parts.join(';'),
1954
+ blockedBy: [{ id: blockedId, reason: cause?.reason ? truncate(String(cause.reason), 300) : `上游 ${upstreamLabel(blockedId)} 受阻` }],
1528
1955
  })
1529
1956
  blocked.add(subtask.id)
1530
1957
  changed = true
@@ -1635,7 +2062,16 @@ export function findSubtask(plan: any, subtaskId: any) {
1635
2062
  return null
1636
2063
  }
1637
2064
 
1638
- export function buildChildPrompt({ plan, subtask, stage, dependencyResults, cwd, conversationContext = '' }: any) {
2065
+ export function buildChildPrompt({
2066
+ plan,
2067
+ subtask,
2068
+ stage,
2069
+ dependencyResults,
2070
+ cwd,
2071
+ conversationContext = '',
2072
+ statuses = null,
2073
+ previousFailure = null,
2074
+ }: any) {
1639
2075
  /*
1640
2076
  * Every field below is read defensively.
1641
2077
  *
@@ -1651,11 +2087,28 @@ export function buildChildPrompt({ plan, subtask, stage, dependencyResults, cwd,
1651
2087
  : results
1652
2088
  .map((item: any) => `- ${item.id} ${item.title}:${item.status}${item.summary ? `|${item.summary}` : ''}`)
1653
2089
  .join('\n')
1654
- const background = truncate(conversationContext, 5000)
2090
+ /*
2091
+ * [1.7.0] No second truncation here.
2092
+ *
2093
+ * The background was cut to 5000 chars *after* the caller had already built
2094
+ * it to 7000, so a fresh conversation could lose its most recent turns. The
2095
+ * text now arrives already capped by `recentConversation`.
2096
+ */
2097
+ const background = typeof conversationContext === 'string' ? conversationContext : ''
1655
2098
  const understanding = plan?.taskUnderstanding ?? {}
1656
2099
  const contradiction = plan?.contradictions?.primary?.statement ?? '(未记录)'
1657
2100
  const stageName = stage?.name ?? '(未命名阶段)'
1658
2101
  const stageGoal = stage?.goal ?? '(未记录目标)'
2102
+ const team = statuses ? buildTeamBrief(plan, statuses, subtask) : ''
2103
+ const failure = previousFailure && typeof previousFailure === 'object'
2104
+ ? [
2105
+ '',
2106
+ '上一次尝试失败(这不是新的任务,请先判断上次为什么失败):',
2107
+ `- 失败类型:${previousFailure.code ?? 'UNKNOWN'}${previousFailure.attempt ? `(第 ${previousFailure.attempt} 次尝试)` : ''}`,
2108
+ `- 失败说明:${truncate(String(previousFailure.message ?? '(无说明)'), 600)}`,
2109
+ '请针对上面这个原因调整做法,不要重复相同的失败路径;如果仍然无法完成,第一行输出 `BLOCKED: 原因` 并说明缺少什么。',
2110
+ ].join('\n')
2111
+ : ''
1659
2112
  return [
1660
2113
  `你是「${departmentLabel(subtask.department)}」部门的执行 Agent,只负责下面这一个子任务。`,
1661
2114
  '',
@@ -1679,6 +2132,8 @@ export function buildChildPrompt({ plan, subtask, stage, dependencyResults, cwd,
1679
2132
  '',
1680
2133
  '依赖子任务的已知结果:',
1681
2134
  dependencies,
2135
+ ...(team ? ['', '兄弟部门进展(同一计划内的其他子任务;不要直接联系它们,需要协作请写进 needs 由主 Agent 转达):', team] : []),
2136
+ ...(failure ? [failure] : []),
1682
2137
  '',
1683
2138
  '执行要求:',
1684
2139
  '- 只完成本子任务,不擅自扩大范围;不要派生新的 Agent。',
@@ -1689,5 +2144,15 @@ export function buildChildPrompt({ plan, subtask, stage, dependencyResults, cwd,
1689
2144
  '- 控制工具调用次数,证据足够就立即汇报;不要反复搜索或等待长时间任务。',
1690
2145
  '- 如果确实无法完成,第一行输出 `BLOCKED: 原因`,然后简要说明。',
1691
2146
  '- 完成后用简洁中文汇报:做了什么、证据/文件、验收结果、遗留问题。',
2147
+ '',
2148
+ '结果回传(必填):在汇报的最后附上一个结构化结果块,主 Agent 会按它逐项核对,不再只依赖自述。',
2149
+ EVIDENCE_MARKER_BEGIN,
2150
+ '{"status":"done","blockedReason":"","acceptance":[{"criterion":"把上面的验收标准原文抄在这里","result":"pass","evidence":"用命令输出、文件路径或引用证明"}],"artifacts":[{"kind":"file","ref":"相对工作目录的路径"}],"needs":[]}',
2151
+ EVIDENCE_MARKER_END,
2152
+ '- status 只能是 done / blocked / partial;partial 会被当作受阻处理。',
2153
+ '- acceptance 必须逐条覆盖上面的验收标准;result 只能是 pass / fail / unverified。无法确认就写 unverified,不要写 pass。',
2154
+ '- artifacts 写你实际产出或修改的文件(kind=file,ref 用相对路径)、链接(kind=url)或说明(kind=note)。',
2155
+ '- 需要其他部门配合时写进 needs(每条一句话),主 Agent 会转达;不要直连其他子 Agent。',
2156
+ '- 整块不超过 8000 字符;不要把这段模板本身抄进结果块。',
1692
2157
  ].join('\n')
1693
2158
  }