dsh-chief 1.3.0 → 1.5.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.
@@ -11,6 +11,10 @@ import {
11
11
  permissionRank,
12
12
  evaluateSafetyGuardHardRules,
13
13
  executeChiefToolCall,
14
+ HUMAN_BOUNDS_CONFIRM_TOKEN,
15
+ buildCapabilityScope,
16
+ verifyCapabilityScope,
17
+ mutateGuardWalls,
14
18
  } from './chief-executor.js'
15
19
  import {
16
20
  CHAT_CAP,
@@ -21,7 +25,9 @@ import {
21
25
  cleanMultiline,
22
26
  hasValidChiefRiskAck,
23
27
  computeApprovalPayloadHash,
24
- upsertResumeTaskOnWs,
28
+ upsertTaskLedgerOnWs,
29
+ markTaskResumingActive,
30
+ unmarkTaskResumingActive,
25
31
  pushAuditToWs,
26
32
  normalizeMail,
27
33
  resolveWorkspaceConfig,
@@ -36,9 +42,9 @@ import { deliverCrossMessage } from './chief-network.js'
36
42
  import { getChiefView } from './chief-view.js'
37
43
  import { buildChiefArchiveUpsertFn } from './chief-archives.js'
38
44
  import { buildChiefCompactFn, recordSmartCompactionChatReceipt } from './chief-compaction.js'
39
- import { askOrCommandChief } from './chief-commands.js'
45
+ import { askOrCommandChief, executeChiefArchiveInjectionOp } from './chief-commands.js'
40
46
 
41
- export async function handleSuggestionDecision(deps, { sessionId, suggestionId, decision, editedText, boundField, pinGlobal }) {
47
+ export async function handleSuggestionDecision(deps, { sessionId, suggestionId, decision, editedText, boundField, pinGlobal, _suppressChatReceipt = false, _byUserClick = true }) {
42
48
  const rootId = deps.resolveRootSessionId(sessionId) || String(sessionId || 'global')
43
49
  let found = null
44
50
  mutateChiefState((state) => {
@@ -76,6 +82,8 @@ export async function handleSuggestionDecision(deps, { sessionId, suggestionId,
76
82
  pinned: shouldPin,
77
83
  session: rootId === 'global' ? '' : rootId,
78
84
  by: 'DSH 参谋长',
85
+ _callerOrigin: 'human_approval',
86
+ _humanConfirmToken: HUMAN_BOUNDS_CONFIRM_TOKEN,
79
87
  })
80
88
  : deps.runAction({
81
89
  action: 'bounds.add',
@@ -84,6 +92,8 @@ export async function handleSuggestionDecision(deps, { sessionId, suggestionId,
84
92
  pinned: shouldPin,
85
93
  session: rootId === 'global' ? '' : rootId,
86
94
  by: 'DSH 参谋长',
95
+ _callerOrigin: 'human_approval',
96
+ _humanConfirmToken: HUMAN_BOUNDS_CONFIRM_TOKEN,
87
97
  }))
88
98
  : { ok: false, error: 'runAction unavailable' }
89
99
  if (!writeRes || !writeRes.ok) {
@@ -123,6 +133,113 @@ export async function handleSuggestionDecision(deps, { sessionId, suggestionId,
123
133
  }
124
134
  }
125
135
 
136
+ if (decision === 'approve' && found.kind === 'guard_wall') {
137
+ const cwdNow = resolveSessionWorkspaceCwd(deps, rootId)
138
+ const spec = found.wallSpec && typeof found.wallSpec === 'object' ? found.wallSpec : {
139
+ title: String(found.title || '参谋长手搓物理墙').replace(/^🧱\s*驻防物理墙[::]\s*/, ''),
140
+ scope: found.pinGlobal === false ? 'workspace' : 'global',
141
+ ruleType: 'forbid_path',
142
+ patterns: String(found.draftText || '').split(/[,,;\n]+/).map(s => s.trim()).filter(Boolean),
143
+ reason: found.reason || '',
144
+ source: 'chief_crafted',
145
+ }
146
+ const wallRes = mutateGuardWalls({
147
+ op: 'save',
148
+ wall: { ...spec, source: 'chief_crafted' },
149
+ cwd: cwdNow,
150
+ callerOrigin: 'human_approval',
151
+ humanConfirmToken: HUMAN_BOUNDS_CONFIRM_TOKEN,
152
+ })
153
+ if (!wallRes || !wallRes.ok) {
154
+ return { ok: false, error: (wallRes && wallRes.error) || '驻防物理墙落锁失败' }
155
+ }
156
+ mutateChiefState((state) => {
157
+ const ws = ensureWorkspace(state, rootId)
158
+ if (!_suppressChatReceipt) {
159
+ ws.chat.push({
160
+ id: nextId('chat'),
161
+ role: 'chief',
162
+ kind: 'receipt',
163
+ text: `- 【🧱 物理驻墙已确认落锁】${wallRes.wall.title}\n- 【拦截范围】${wallRes.wall.scope === 'workspace' ? '仅绑定当前工程' : '🌐 全局随身常驻'} | 规则:\`${wallRes.wall.patterns.join(', ')}\``,
164
+ actions: ['确认驻防物理墙'],
165
+ at: Date.now(),
166
+ })
167
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
168
+ }
169
+ pushAuditToWs(ws, {
170
+ mode: resolveWorkspaceConfig(state, rootId).permissionMode,
171
+ stage: 'guard_wall',
172
+ rule: 'guard_wall_approved',
173
+ decision: 'executed',
174
+ operation: '落锁物理驻墙',
175
+ target: wallRes.wall.title,
176
+ reason: wallRes.wall.patterns.join(', '),
177
+ outcome: 'ok',
178
+ by: 'operator',
179
+ }, rootId)
180
+ })
181
+ return {
182
+ ok: true,
183
+ wallApplied: wallRes.wall,
184
+ guardWalls: wallRes.walls,
185
+ view: await getChiefView(deps, rootId, { autoSummarize: false }),
186
+ }
187
+ }
188
+
189
+ if (decision === 'approve' && found.kind === 'wall_removal') {
190
+ const cwdNow = resolveSessionWorkspaceCwd(deps, rootId)
191
+ const spec = (found.wallRemovalSpec && typeof found.wallRemovalSpec === 'object') ? found.wallRemovalSpec : {}
192
+ const targetWallId = String(spec.wallId || '').trim()
193
+ const opType = spec.action === 'remove' ? 'remove' : 'set_scope'
194
+ if (!targetWallId) {
195
+ return { ok: false, error: '拆墙申请缺少有效的目标物理驻墙 ID (wallId)' }
196
+ }
197
+ const wallRes = mutateGuardWalls({
198
+ op: opType,
199
+ wallId: targetWallId,
200
+ ...(opType === 'set_scope' ? { scope: 'paused' } : {}),
201
+ cwd: cwdNow,
202
+ callerOrigin: 'human_approval',
203
+ humanConfirmToken: HUMAN_BOUNDS_CONFIRM_TOKEN,
204
+ })
205
+ if (!wallRes || !wallRes.ok) {
206
+ return { ok: false, error: (wallRes && wallRes.error) || '按人工批复调整物理驻墙失败' }
207
+ }
208
+ const wallTitle = spec.wallTitle || (wallRes.wall && wallRes.wall.title) || targetWallId
209
+ const actVerb = opType === 'remove' ? '拆除移除' : '暂挂休眠'
210
+ mutateChiefState((state) => {
211
+ const ws = ensureWorkspace(state, rootId)
212
+ if (!_suppressChatReceipt) {
213
+ ws.chat.push({
214
+ id: nextId('chat'),
215
+ role: 'chief',
216
+ kind: 'receipt',
217
+ text: `- 【🧱 已按人工批示${actVerb}物理驻墙】${wallTitle} (\`${targetWallId}\`)\n- 【代理上报与拆墙依据】${clamp(spec.blockerEvidence || found.reason || '主/子代理撞墙无法绕过,参谋呈报经人类批准后执行', 180)}`,
218
+ actions: [`已${actVerb}驻墙`],
219
+ at: Date.now(),
220
+ })
221
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
222
+ }
223
+ pushAuditToWs(ws, {
224
+ mode: resolveWorkspaceConfig(state, rootId).permissionMode,
225
+ stage: 'guard_wall',
226
+ rule: 'wall_removal_approved',
227
+ decision: 'executed',
228
+ operation: `人工批复${actVerb}物理驻墙`,
229
+ target: `${wallTitle} (${targetWallId})`,
230
+ reason: clamp(spec.reason || found.reason || '代理撞墙无法绕过,经人类显式审批后放行', 180),
231
+ outcome: 'ok',
232
+ by: 'operator',
233
+ }, rootId)
234
+ })
235
+ return {
236
+ ok: true,
237
+ wallRemoved: { wallId: targetWallId, title: wallTitle, action: opType === 'remove' ? 'remove' : 'pause' },
238
+ guardWalls: wallRes.walls,
239
+ view: _suppressChatReceipt ? null : await getChiefView(deps, rootId, { autoSummarize: false }),
240
+ }
241
+ }
242
+
126
243
  if (decision === 'approve' && found.kind === 'goal_approval') {
127
244
  const res = deps.runAction
128
245
  ? deps.runAction({ action: 'goal.approve', session: rootId, by: 'user' })
@@ -150,6 +267,53 @@ export async function handleSuggestionDecision(deps, { sessionId, suggestionId,
150
267
  }
151
268
  }
152
269
 
270
+ if (decision === 'approve' && found.kind === 'archive_op') {
271
+ const spec = (found.archiveSpec && typeof found.archiveSpec === 'object')
272
+ ? found.archiveSpec
273
+ : ((found.archiveOp && typeof found.archiveOp === 'object') ? found.archiveOp : {})
274
+ const archRes = await executeChiefArchiveInjectionOp(deps, rootId, {
275
+ op: spec.op || 'pin_to_desktop',
276
+ vaultScope: spec.vaultScope || 'session',
277
+ id: spec.id || '',
278
+ title: spec.title || found.title || '',
279
+ target: spec.target || found.target || 'lead',
280
+ instruction: editedText || spec.instruction || found.reason || '',
281
+ }, { byLabel: 'DSH 参谋长 (获批档案调配)' }).catch(e => ({ ok: false, error: (e && e.message) || 'archive-op-failed' }))
282
+ return {
283
+ ok: Boolean(archRes && archRes.ok),
284
+ archiveApplied: archRes,
285
+ error: archRes && !archRes.ok ? archRes.error : '',
286
+ view: _suppressChatReceipt ? null : await getChiefView(deps, rootId, { autoSummarize: false }),
287
+ }
288
+ }
289
+
290
+ if (decision === 'approve' && found.kind === 'model_effort') {
291
+ const spec = (found.effortSpec && typeof found.effortSpec === 'object')
292
+ ? found.effortSpec
293
+ : ((found.effortOp && typeof found.effortOp === 'object') ? found.effortOp : {})
294
+ const target = spec.target || found.target || 'lead'
295
+ const eff = spec.effort || 'medium'
296
+ const effReason = spec.reason || found.reason || '按参谋建议调整思考强度'
297
+ const effRes = deps && typeof deps.controlMainAgent === 'function'
298
+ ? await deps.controlMainAgent({
299
+ rootId,
300
+ sessionId: rootId,
301
+ op: 'set_effort',
302
+ target,
303
+ reasoningEffort: eff,
304
+ reason: effReason,
305
+ byUser: Boolean(_byUserClick !== false),
306
+ }).catch(e => ({ ok: false, error: (e && e.message) || 'effort-failed' }))
307
+ : { ok: false, error: '当前宿主未绑定会话控制接口' }
308
+ return {
309
+ ok: Boolean(effRes && effRes.ok),
310
+ effortApplied: effRes,
311
+ lockedByUser: Boolean(effRes && effRes.lockedByUser),
312
+ error: effRes && !effRes.ok ? effRes.error : '',
313
+ view: _suppressChatReceipt ? null : await getChiefView(deps, rootId, { autoSummarize: false }),
314
+ }
315
+ }
316
+
153
317
  if (decision === 'approve' && (found.kind === 'relay' || found.kind === 'advice')) {
154
318
  const body = editedText ? cleanMultiline(editedText, 1200) : found.draftText
155
319
  const deliverTarget = found.target || 'lead'
@@ -187,6 +351,10 @@ export async function executeBatchSuggestions(deps, {
187
351
  ids = [],
188
352
  includeGoalApproval = false,
189
353
  pinGlobalDefault = undefined,
354
+ skipGuardWalls = false,
355
+ skipGlobalBounds = false,
356
+ byAutoRunner = false,
357
+ skipChatReceipt = false,
190
358
  } = {}) {
191
359
  const rootId = (deps && typeof deps.resolveRootSessionId === 'function' ? deps.resolveRootSessionId(sessionId) : '') || String(sessionId || 'global')
192
360
  const stateSnap = loadChiefState()
@@ -213,7 +381,7 @@ export async function executeBatchSuggestions(deps, {
213
381
  blocked: [],
214
382
  skippedGoals: [],
215
383
  summaries: ['当前没有待执行的参谋长建议。'],
216
- view: await getChiefView(deps, rootId, { autoSummarize: false }),
384
+ view: skipChatReceipt ? null : await getChiefView(deps, rootId, { autoSummarize: false }),
217
385
  }
218
386
  }
219
387
 
@@ -228,8 +396,20 @@ export async function executeBatchSuggestions(deps, {
228
396
  skippedGoals.push({ id: sug.id, title: sug.title })
229
397
  continue
230
398
  }
399
+ if (skipGuardWalls && (sug.kind === 'guard_wall' || sug.kind === 'wall_removal')) {
400
+ skippedGoals.push({ id: sug.id, title: sug.title })
401
+ continue
402
+ }
403
+ if (sug.kind === 'wall_removal' && byAutoRunner) {
404
+ skippedGoals.push({ id: sug.id, title: sug.title })
405
+ continue
406
+ }
407
+ if (skipGlobalBounds && sug.kind === 'bound' && sug.pinGlobal) {
408
+ skippedGoals.push({ id: sug.id, title: sug.title })
409
+ continue
410
+ }
231
411
 
232
- if (sug.kind !== 'bound' && sug.kind !== 'goal_approval') {
412
+ if (sug.kind !== 'bound' && sug.kind !== 'goal_approval' && sug.kind !== 'guard_wall' && sug.kind !== 'wall_removal') {
233
413
  const cmdSample = `${sug.draftText || ''}\n${sug.title || ''}`.trim()
234
414
  const guardRes = evaluateSafetyGuardHardRules({
235
415
  tool: 'relay',
@@ -251,7 +431,7 @@ export async function executeBatchSuggestions(deps, {
251
431
  target: clamp(sug.title, 80),
252
432
  reason: guardRes.reason,
253
433
  outcome: 'blocked',
254
- by: 'operator',
434
+ by: byAutoRunner ? 'chief' : 'operator',
255
435
  }, rootId)
256
436
  })
257
437
  blocked.push({ id: sug.id, title: sug.title, reason: guardRes.reason })
@@ -265,14 +445,28 @@ export async function executeBatchSuggestions(deps, {
265
445
  suggestionId: sug.id,
266
446
  decision: 'approve',
267
447
  pinGlobal: sug.kind === 'bound' && typeof pinGlobalDefault === 'boolean' ? pinGlobalDefault : undefined,
448
+ _suppressChatReceipt: true,
449
+ _byUserClick: !byAutoRunner,
268
450
  })
269
451
 
270
452
  if (res && res.ok) {
271
453
  executed.push({ id: sug.id, kind: sug.kind, title: sug.title, target: sug.targetLabel || sug.target })
272
454
  if (res.boundApplied) {
273
455
  summaries.push(`✅ 已应用边界「${res.boundApplied.label}」:${clamp(res.boundApplied.item, 44)}`)
456
+ } else if (res.wallApplied) {
457
+ const w = res.wallApplied
458
+ const scopeLabel = w.scope === 'workspace' ? '仅本工程' : '🌐全局随身'
459
+ const patPreview = Array.isArray(w.patterns) ? clamp(w.patterns.join(', '), 60) : ''
460
+ summaries.push(`🧱 已落锁物理驻墙「${clamp(w.title, 36)}」(${scopeLabel}${patPreview ? ` · \`${patPreview}\`` : ''})`)
461
+ } else if (res.wallRemoved) {
462
+ const r = res.wallRemoved
463
+ summaries.push(`🧱 已按人工批复${r.action === 'remove' ? '拆除' : '暂挂'}物理驻墙「${clamp(r.title || r.wallId, 36)}」`)
274
464
  } else if (res.goalApproved) {
275
465
  summaries.push('✅ 已批准并结项当前核心目标')
466
+ } else if (res.archiveApplied && res.archiveApplied.actionText) {
467
+ summaries.push(`✅ ${res.archiveApplied.actionText}`)
468
+ } else if (res.effortApplied && res.effortApplied.reasoningEffort) {
469
+ summaries.push(`✅ 🧠 已调挡 @${res.effortApplied.target || 'lead'} → ${res.effortApplied.reasoningEffort}`)
276
470
  } else if (res.delivery && res.delivery.target) {
277
471
  summaries.push(`✅ 已采纳并递话给 @${res.delivery.target}:「${clamp(sug.title, 36)}」`)
278
472
  } else {
@@ -281,7 +475,7 @@ export async function executeBatchSuggestions(deps, {
281
475
  } else {
282
476
  const errMsg = (res && res.error) || '执行未完成'
283
477
  failed.push({ id: sug.id, title: sug.title, error: errMsg })
284
- summaries.push(`⚠️ 未完成「${clamp(sug.title, 36)}」:${errMsg}`)
478
+ summaries.push(`${res && res.lockedByUser ? '🔒' : '⚠️'} ${res && res.lockedByUser ? '用户已锁挡跳过' : '未完成'}「${clamp(sug.title, 36)}」:${errMsg}`)
285
479
  }
286
480
  }
287
481
 
@@ -291,14 +485,14 @@ export async function executeBatchSuggestions(deps, {
291
485
  mode: permMode,
292
486
  stage: 'executor',
293
487
  decision: executed.length > 0 ? 'executed' : (blocked.length > 0 ? 'blocked' : 'noop'),
294
- operation: '统一执行参谋建议',
488
+ operation: byAutoRunner ? 'L3强介入一站式执行建议' : '统一执行参谋建议',
295
489
  target: `${executed.length} 项执行 / ${blocked.length} 项拦截 / ${skippedGoals.length} 项跳过`,
296
490
  reason: clamp(summaries.slice(0, 3).join(';'), 200) || '批量执行建议',
297
491
  outcome: blocked.length > 0 && executed.length === 0 ? 'blocked' : 'ok',
298
- by: 'operator',
492
+ by: byAutoRunner ? 'chief' : 'operator',
299
493
  }, rootId)
300
- if (executed.length > 0 || blocked.length > 0 || failed.length > 0) {
301
- const header = `- 【📋 统一执行参谋建议回执】完成 ${executed.length} 项${blocked.length ? ` · 拦截 ${blocked.length} 项` : ''}${failed.length ? ` · 异常 ${failed.length} 项` : ''}${skippedGoals.length ? ` · 保留目标结项请示 ${skippedGoals.length} 项单独拍板` : ''}`
494
+ if (!skipChatReceipt && (executed.length > 0 || blocked.length > 0 || failed.length > 0)) {
495
+ const header = `- 【📋 统一执行参谋建议回执】完成 ${executed.length} 项${blocked.length ? ` · 拦截 ${blocked.length} 项` : ''}${failed.length ? ` · 异常 ${failed.length} 项` : ''}${skippedGoals.length ? ` · 保留需单独拍板项 ${skippedGoals.length} 项` : ''}`
302
496
  const actionTags = [`📋 执行建议 ×${executed.length}`]
303
497
  if (blocked.length) actionTags.push(`🛡️ 红线拦截 ×${blocked.length}`)
304
498
  ws.chat.push({
@@ -324,7 +518,7 @@ export async function executeBatchSuggestions(deps, {
324
518
  failed,
325
519
  skippedGoals,
326
520
  summaries,
327
- view: await getChiefView(deps, rootId, { autoSummarize: executed.some(e => e.kind === 'bound') }),
521
+ view: skipChatReceipt ? null : await getChiefView(deps, rootId, { autoSummarize: executed.some(e => e.kind === 'bound') }),
328
522
  }
329
523
  }
330
524
 
@@ -337,6 +531,7 @@ export async function handleApprovalDecision(deps, {
337
531
  const rootId = (deps && typeof deps.resolveRootSessionId === 'function' ? deps.resolveRootSessionId(sessionId) : '') || String(sessionId || 'global')
338
532
  let found = null
339
533
  let currentMode = DEFAULT_CHIEF_PERMISSION_MODE
534
+ let effPolicyPlugins = []
340
535
  let existingNonPending = false
341
536
  let hashMismatch = false
342
537
 
@@ -345,12 +540,14 @@ export async function handleApprovalDecision(deps, {
345
540
  const ackOk = hasValidChiefRiskAck(ws)
346
541
  const eff = resolveWorkspaceConfig(state, rootId)
347
542
  currentMode = normalizePermissionMode(eff.permissionMode, { requireAck: true, hasChiefRiskAck: ackOk })
543
+ effPolicyPlugins = Array.isArray(eff.policyPlugins) ? eff.policyPlugins : []
348
544
  const item = (ws.pendingApprovals || []).find(a => a && a.id === approvalId && a.status === 'pending')
349
545
  if (!item) {
350
546
  existingNonPending = (ws.pendingApprovals || []).some(a => a && a.id === approvalId)
351
547
  pushAuditToWs(ws, {
352
548
  mode: currentMode,
353
549
  stage: 'permission_gate',
550
+ rule: existingNonPending ? 'replayed_approval' : 'invalid_approval_id',
354
551
  decision: existingNonPending ? 'replayed_approval' : 'invalid_approval_id',
355
552
  operation: '伪造或重放审批拦截',
356
553
  target: clamp(approvalId || '(empty)', 100),
@@ -361,6 +558,7 @@ export async function handleApprovalDecision(deps, {
361
558
  return
362
559
  }
363
560
 
561
+ const linkedTaskId = item.taskId || item.resumeTaskId || ''
364
562
  const expectedHash = computeApprovalPayloadHash(item.kind, item.payload || {})
365
563
  if (decision === 'approve' && item.payloadHash && item.payloadHash !== expectedHash) {
366
564
  hashMismatch = true
@@ -369,16 +567,20 @@ export async function handleApprovalDecision(deps, {
369
567
  item.resolvedAt = Date.now()
370
568
  item.resolvedBy = 'safety_guard'
371
569
  item.resultMessage = '审批载荷哈希校验失败(疑似载荷被篡改)'
372
- if (item.resumeTaskId && Array.isArray(ws.resumeTasks)) {
373
- const linkedTask = ws.resumeTasks.find(t => t && t.id === item.resumeTaskId)
570
+ const ledgerList = Array.isArray(ws.taskLedger) ? ws.taskLedger : (Array.isArray(ws.resumeTasks) ? ws.resumeTasks : [])
571
+ if (linkedTaskId) {
572
+ const linkedTask = ledgerList.find(t => t && (t.taskId === linkedTaskId || t.id === linkedTaskId))
374
573
  if (linkedTask) {
375
574
  linkedTask.status = 'failed'
575
+ linkedTask.updatedAt = Date.now()
376
576
  linkedTask.resolvedAt = Date.now()
577
+ linkedTask.lastReceipt = '审批载荷哈希校验失败,事务中止'
377
578
  }
378
579
  }
379
580
  pushAuditToWs(ws, {
380
581
  mode: currentMode,
381
582
  stage: 'safety_guard',
583
+ rule: 'tampered_approval_payload',
382
584
  decision: 'tampered_approval_payload',
383
585
  operation: item.operationLabel,
384
586
  target: item.targetLabel,
@@ -404,16 +606,20 @@ export async function handleApprovalDecision(deps, {
404
606
  item.resolvedAt = Date.now()
405
607
  item.resolvedBy = 'operator'
406
608
  item.resultMessage = '用户拒绝执行本次操作'
407
- if (item.resumeTaskId && Array.isArray(ws.resumeTasks)) {
408
- const linkedTask = ws.resumeTasks.find(t => t && t.id === item.resumeTaskId)
609
+ const ledgerList = Array.isArray(ws.taskLedger) ? ws.taskLedger : (Array.isArray(ws.resumeTasks) ? ws.resumeTasks : [])
610
+ if (linkedTaskId) {
611
+ const linkedTask = ledgerList.find(t => t && (t.taskId === linkedTaskId || t.id === linkedTaskId))
409
612
  if (linkedTask) {
410
613
  linkedTask.status = 'cancelled'
614
+ linkedTask.updatedAt = Date.now()
411
615
  linkedTask.resolvedAt = Date.now()
616
+ linkedTask.lastReceipt = '用户拒绝本次操作授权'
412
617
  }
413
618
  }
414
619
  pushAuditToWs(ws, {
415
620
  mode: currentMode,
416
621
  stage: 'permission_gate',
622
+ rule: 'rejected_by_user',
417
623
  decision: 'rejected_by_user',
418
624
  operation: item.operationLabel,
419
625
  target: item.targetLabel,
@@ -437,6 +643,7 @@ export async function handleApprovalDecision(deps, {
437
643
  pushAuditToWs(ws, {
438
644
  mode: currentMode,
439
645
  stage: 'permission_gate',
646
+ rule: 'approved_by_user',
440
647
  decision: 'approved_by_user',
441
648
  operation: item.operationLabel,
442
649
  target: item.targetLabel,
@@ -462,6 +669,13 @@ export async function handleApprovalDecision(deps, {
462
669
  ? deps.boardForSession(deps.boardFileFor(rootId))
463
670
  : null
464
671
  const payload = found.payload || {}
672
+ const resolvedScope = found.capabilityScope || buildCapabilityScope({
673
+ kind: found.kind,
674
+ tool: payload.tool || found.kind,
675
+ args: payload.args || {},
676
+ cwd: payload.cwd || resolveSessionWorkspaceCwd(deps, rootId),
677
+ target: payload.target || '',
678
+ })
465
679
  let execOk = false
466
680
  let execRes = null
467
681
  let resultMsg = ''
@@ -474,6 +688,8 @@ export async function handleApprovalDecision(deps, {
474
688
  cwd: payload.cwd || resolveSessionWorkspaceCwd(deps, rootId),
475
689
  permissionMode: currentMode === 'chief' ? 'chief' : 'strategist',
476
690
  hasChiefRiskAck: currentMode === 'chief',
691
+ policyPlugins: effPolicyPlugins,
692
+ capabilityScope: resolvedScope,
477
693
  approvedOnce: true,
478
694
  board,
479
695
  upsertArchiveFn: buildChiefArchiveUpsertFn(deps, rootId),
@@ -486,45 +702,55 @@ export async function handleApprovalDecision(deps, {
486
702
  ? `已执行 ${found.operationLabel}(${found.targetLabel})`
487
703
  : (execRes && execRes.error) || '执行未成功'
488
704
  } else if (found.kind === 'relay') {
489
- const guardRes = evaluateSafetyGuardHardRules({ tool: 'relay', opClass: 'workflow', command: payload.text || '', board })
490
- if (guardRes.blocked) {
705
+ const scopeCheck = verifyCapabilityScope(resolvedScope, { kind: 'relay', tool: 'relay', target: payload.target || '' })
706
+ if (!scopeCheck.ok) {
491
707
  execOk = false
492
- execRes = { ok: false, blockedBySafetyGuard: true, error: guardRes.reason }
493
- resultMsg = guardRes.reason
494
- appendChiefAuditLog(rootId, { mode: currentMode, stage: 'safety_guard', decision: 'blocked', operation: found.operationLabel, target: found.targetLabel, reason: guardRes.reason, outcome: 'blocked', by: 'operator' })
708
+ execRes = { ok: false, deniedByScopeMismatch: true, error: scopeCheck.error }
709
+ resultMsg = scopeCheck.error
710
+ appendChiefAuditLog(rootId, { mode: currentMode, stage: 'scope_guard', rule: scopeCheck.rule, decision: 'rejected', operation: found.operationLabel, target: found.targetLabel, reason: scopeCheck.error, outcome: 'rejected', by: 'operator' })
495
711
  } else {
496
- const deliv = await deliverCrossMessage(deps, {
497
- fromSession: rootId,
498
- fromLabel: payload.fromLabel || 'DSH 参谋 (逐项授权)',
499
- target: payload.target || 'lead',
500
- subject: payload.subject || '',
501
- text: payload.text || '',
502
- mode: payload.mode || 'steer',
503
- imageBlocks: Array.isArray(payload.imageBlocks) ? payload.imageBlocks : [],
504
- savedImagePaths: Array.isArray(payload.savedImagePaths) ? payload.savedImagePaths : [],
505
- })
506
- const isLeadTarget = /^(?:lead|main|主对话)$/i.test(String(payload.target || 'lead').trim())
507
- if (isLeadTarget && (!deliv.ok || (payload.isBlankContext && !deliv.deliveredPhysical)) && deps && typeof deps.stagePendingTransfer === 'function') {
508
- const staged = deps.stagePendingTransfer(
509
- `[DSH 参谋预派发指令${payload.subject ? ' · ' + payload.subject : ''}]\n${payload.text || ''}`,
510
- rootId,
511
- { by: 'chief', subject: payload.subject || '' },
512
- )
513
- if (staged) {
514
- execOk = true
515
- execRes = { ...deliv, ok: true, stagedPending: true, target: '主对话(待领)' }
516
- resultMsg = '已暂存主对话待领交接指令'
712
+ const guardRes = evaluateSafetyGuardHardRules({ tool: 'relay', opClass: 'workflow', command: payload.text || '', board })
713
+ if (guardRes.blocked) {
714
+ execOk = false
715
+ execRes = { ok: false, blockedBySafetyGuard: true, error: guardRes.reason }
716
+ resultMsg = guardRes.reason
717
+ appendChiefAuditLog(rootId, { mode: currentMode, stage: 'safety_guard', rule: guardRes.rule || 'hard_guard', decision: 'blocked', operation: found.operationLabel, target: found.targetLabel, reason: guardRes.reason, outcome: 'blocked', by: 'operator' })
718
+ } else {
719
+ const deliv = await deliverCrossMessage(deps, {
720
+ fromSession: rootId,
721
+ fromLabel: payload.fromLabel || 'DSH 参谋 (逐项授权)',
722
+ target: payload.target || 'lead',
723
+ subject: payload.subject || '',
724
+ text: payload.text || '',
725
+ mode: payload.mode || 'steer',
726
+ envelopeKind: payload.envelopeKind || 'execution_request',
727
+ taskId: payload.taskId || '',
728
+ imageBlocks: Array.isArray(payload.imageBlocks) ? payload.imageBlocks : [],
729
+ savedImagePaths: Array.isArray(payload.savedImagePaths) ? payload.savedImagePaths : [],
730
+ })
731
+ const isLeadTarget = /^(?:lead|main|主对话)$/i.test(String(payload.target || 'lead').trim())
732
+ if (isLeadTarget && (!deliv.ok || (payload.isBlankContext && !deliv.deliveredPhysical)) && deps && typeof deps.stagePendingTransfer === 'function') {
733
+ const staged = deps.stagePendingTransfer(
734
+ `[DSH 参谋预派发指令${payload.subject ? ' · ' + payload.subject : ''}]\n${payload.text || ''}`,
735
+ rootId,
736
+ { by: 'chief', subject: payload.subject || '' },
737
+ )
738
+ if (staged) {
739
+ execOk = true
740
+ execRes = { ...deliv, ok: true, stagedPending: true, target: '主对话(待领)' }
741
+ resultMsg = '已暂存主对话待领交接指令'
742
+ } else {
743
+ execOk = Boolean(deliv && deliv.ok)
744
+ execRes = deliv
745
+ resultMsg = execOk ? `已投递给 ${deliv.target || found.targetLabel}` : ((deliv && deliv.error) || '投递失败')
746
+ }
517
747
  } else {
518
748
  execOk = Boolean(deliv && deliv.ok)
519
749
  execRes = deliv
520
750
  resultMsg = execOk ? `已投递给 ${deliv.target || found.targetLabel}` : ((deliv && deliv.error) || '投递失败')
521
751
  }
522
- } else {
523
- execOk = Boolean(deliv && deliv.ok)
524
- execRes = deliv
525
- resultMsg = execOk ? `已投递给 ${deliv.target || found.targetLabel}` : ((deliv && deliv.error) || '投递失败')
752
+ appendChiefAuditLog(rootId, { mode: currentMode, stage: 'executor', rule: 'approved_once', decision: 'executed_approved', operation: found.operationLabel, target: found.targetLabel, reason: clamp(resultMsg, 120), outcome: execOk ? 'ok' : 'error', by: 'operator' })
526
753
  }
527
- appendChiefAuditLog(rootId, { mode: currentMode, stage: 'executor', decision: 'executed_approved', operation: found.operationLabel, target: found.targetLabel, reason: clamp(resultMsg, 120), outcome: execOk ? 'ok' : 'error', by: 'operator' })
528
754
  }
529
755
  } else if (found.kind === 'compact') {
530
756
  const guardRes = evaluateSafetyGuardHardRules({ tool: 'session_compact', opClass: 'workflow', board })
@@ -545,7 +771,47 @@ export async function handleApprovalDecision(deps, {
545
771
  resultMsg = execOk
546
772
  ? (execRes.noop ? '已抢救细节入本会话档案柜(当前历史免压)' : '已抢救细节并完成主对话上下文静默压缩')
547
773
  : ((execRes && execRes.error) || '压缩未完成')
548
- appendChiefAuditLog(rootId, { mode: currentMode, stage: 'executor', decision: 'executed_approved', operation: found.operationLabel, target: found.targetLabel, reason: clamp(resultMsg, 120), outcome: execOk ? 'ok' : 'error', by: 'operator' })
774
+ appendChiefAuditLog(rootId, { mode: currentMode, stage: 'executor', rule: 'approved_once', decision: 'executed_approved', operation: found.operationLabel, target: found.targetLabel, reason: clamp(resultMsg, 120), outcome: execOk ? 'ok' : 'error', by: 'operator' })
775
+ }
776
+ } else if (found.kind === 'archive_op') {
777
+ const scopeCheck = verifyCapabilityScope(resolvedScope, { kind: 'archive_op', tool: 'archive_op', target: payload.title || payload.id || found.targetLabel || '' })
778
+ if (!scopeCheck.ok) {
779
+ execOk = false
780
+ execRes = { ok: false, deniedByScopeMismatch: true, error: scopeCheck.error }
781
+ resultMsg = scopeCheck.error
782
+ appendChiefAuditLog(rootId, { mode: currentMode, stage: 'scope_guard', rule: scopeCheck.rule, decision: 'rejected', operation: found.operationLabel, target: found.targetLabel, reason: scopeCheck.error, outcome: 'rejected', by: 'operator' })
783
+ } else {
784
+ execRes = await executeChiefArchiveInjectionOp(deps, rootId, payload, { input: found.reason || '', byLabel: 'DSH 参谋 (逐项授权档案调配)' })
785
+ execOk = Boolean(execRes && execRes.ok)
786
+ resultMsg = execOk ? (execRes.actionText || '已完成授权档案调配') : ((execRes && execRes.error) || '档案调配失败')
787
+ appendChiefAuditLog(rootId, { mode: currentMode, stage: 'executor', rule: 'approved_once', decision: 'executed_approved', operation: found.operationLabel, target: found.targetLabel, reason: clamp(resultMsg, 120), outcome: execOk ? 'ok' : 'error', by: 'operator' })
788
+ }
789
+ } else if (found.kind === 'model_effort') {
790
+ const effTarget = payload.target || 'lead'
791
+ const scopeCheck = verifyCapabilityScope(resolvedScope, { kind: 'model_effort', tool: 'model_effort', target: effTarget })
792
+ if (!scopeCheck.ok) {
793
+ execOk = false
794
+ execRes = { ok: false, deniedByScopeMismatch: true, error: scopeCheck.error }
795
+ resultMsg = scopeCheck.error
796
+ appendChiefAuditLog(rootId, { mode: currentMode, stage: 'scope_guard', rule: scopeCheck.rule, decision: 'rejected', operation: found.operationLabel, target: found.targetLabel, reason: scopeCheck.error, outcome: 'rejected', by: 'operator' })
797
+ } else if (deps && typeof deps.controlMainAgent === 'function') {
798
+ execRes = await deps.controlMainAgent({
799
+ rootId,
800
+ sessionId: rootId,
801
+ op: 'set_effort',
802
+ target: effTarget,
803
+ reasoningEffort: payload.reasoningEffort || payload.effort || 'medium',
804
+ reason: payload.reason || found.reason || '',
805
+ byUser: false,
806
+ })
807
+ execOk = Boolean(execRes && execRes.ok)
808
+ resultMsg = execOk
809
+ ? `已将 @${effTarget} 思考强度调为 ${execRes.reasoningEffort || payload.reasoningEffort || 'medium'}`
810
+ : ((execRes && execRes.error) || '思考强度调配未成功')
811
+ appendChiefAuditLog(rootId, { mode: currentMode, stage: execRes && execRes.lockedByUser ? 'model_effort_lock' : 'executor', rule: execRes && execRes.lockedByUser ? 'user_effort_lock' : 'approved_once', decision: execOk ? 'executed_approved' : 'blocked', operation: found.operationLabel, target: found.targetLabel, reason: clamp(resultMsg, 120), outcome: execOk ? 'ok' : 'blocked', by: 'operator' })
812
+ } else {
813
+ execOk = false
814
+ resultMsg = '当前宿主未提供代理思考强度控制接口'
549
815
  }
550
816
  } else if (found.kind === 'auto_continue') {
551
817
  if (deps && typeof deps.triggerAutoContinueNow === 'function') {
@@ -556,7 +822,7 @@ export async function handleApprovalDecision(deps, {
556
822
  execOk = false
557
823
  resultMsg = '当前宿主未提供续跑回调接口'
558
824
  }
559
- appendChiefAuditLog(rootId, { mode: currentMode, stage: 'executor', decision: 'executed_approved', operation: found.operationLabel, target: found.targetLabel, reason: clamp(resultMsg, 120), outcome: execOk ? 'ok' : 'error', by: 'operator' })
825
+ appendChiefAuditLog(rootId, { mode: currentMode, stage: 'executor', rule: 'approved_once', decision: 'executed_approved', operation: found.operationLabel, target: found.targetLabel, reason: clamp(resultMsg, 120), outcome: execOk ? 'ok' : 'error', by: 'operator' })
560
826
  }
561
827
  } catch (err) {
562
828
  execOk = false
@@ -566,6 +832,7 @@ export async function handleApprovalDecision(deps, {
566
832
 
567
833
  let updatedApproval = { ...found, status: execOk ? 'executed' : 'failed', resultMessage: resultMsg }
568
834
  let resumeTaskToRun = null
835
+ const linkedTaskId = found.taskId || found.resumeTaskId || ''
569
836
  mutateChiefState((state) => {
570
837
  const ws = ensureWorkspace(state, rootId)
571
838
  const item = (ws.pendingApprovals || []).find(a => a && a.id === approvalId)
@@ -578,7 +845,7 @@ export async function handleApprovalDecision(deps, {
578
845
  id: nextId('chat'),
579
846
  role: 'chief',
580
847
  kind: 'receipt',
581
- ...(found.resumeTaskId ? { resumeTaskId: found.resumeTaskId } : {}),
848
+ ...(linkedTaskId ? { resumeTaskId: linkedTaskId } : {}),
582
849
  text: execOk
583
850
  ? `- 【✅ 已允许并执行】${found.operationLabel} · \`${found.targetLabel}\`\n 结果:${clamp(resultMsg, 240)}`
584
851
  : `- 【⚠️ 授权操作未完成】${found.operationLabel} · \`${found.targetLabel}\`\n 说明:${clamp(resultMsg, 240)}`,
@@ -587,31 +854,39 @@ export async function handleApprovalDecision(deps, {
587
854
  })
588
855
  if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
589
856
 
590
- if (found.resumeTaskId && Array.isArray(ws.resumeTasks)) {
591
- const task = ws.resumeTasks.find(t => t && t.id === found.resumeTaskId)
857
+ const ledgerList = Array.isArray(ws.taskLedger) ? ws.taskLedger : (Array.isArray(ws.resumeTasks) ? ws.resumeTasks : [])
858
+ if (linkedTaskId) {
859
+ const task = ledgerList.find(t => t && (t.taskId === linkedTaskId || t.id === linkedTaskId))
592
860
  if (task) {
593
861
  const doneSummary = `${found.operationLabel} (${found.targetLabel}): ${clamp(resultMsg, 140)}`
594
- const updatedTask = upsertResumeTaskOnWs(ws, {
595
- id: task.id,
862
+ const updatedTask = upsertTaskLedgerOnWs(ws, {
863
+ taskId: task.taskId || task.id,
864
+ id: task.taskId || task.id,
596
865
  appendCompletedAction: doneSummary,
866
+ lastReceipt: clamp(resultMsg, 240),
597
867
  })
598
868
  const siblingPending = (ws.pendingApprovals || []).some(
599
- a => a && a.id !== approvalId && a.resumeTaskId === task.id && a.status === 'pending',
869
+ a => a && a.id !== approvalId && (a.taskId === (task.taskId || task.id) || a.resumeTaskId === (task.taskId || task.id)) && a.status === 'pending',
600
870
  )
601
871
  if (!execOk) {
602
872
  if (updatedTask) {
603
873
  updatedTask.status = 'failed'
874
+ updatedTask.updatedAt = Date.now()
604
875
  updatedTask.resolvedAt = Date.now()
605
876
  }
606
877
  } else if (!siblingPending && updatedTask) {
607
878
  if (updatedTask.expiresAt && Date.now() > updatedTask.expiresAt) {
608
879
  updatedTask.status = 'expired'
880
+ updatedTask.updatedAt = Date.now()
609
881
  updatedTask.resolvedAt = Date.now()
610
- } else if (found.kind === 'tool' && (updatedTask.resumeDepth || 0) < 2 && updatedTask.status !== 'resuming') {
882
+ } else if (found.kind === 'tool' && (updatedTask.retryCount || updatedTask.resumeDepth || 0) < 2 && updatedTask.status !== 'resuming') {
883
+ markTaskResumingActive(updatedTask.taskId || updatedTask.id)
611
884
  updatedTask.status = 'resuming'
885
+ updatedTask.updatedAt = Date.now()
612
886
  resumeTaskToRun = { ...updatedTask }
613
887
  } else if (updatedTask.status === 'awaiting_approval') {
614
888
  updatedTask.status = 'completed'
889
+ updatedTask.updatedAt = Date.now()
615
890
  updatedTask.resolvedAt = Date.now()
616
891
  }
617
892
  }
@@ -621,34 +896,54 @@ export async function handleApprovalDecision(deps, {
621
896
 
622
897
  let resumeOut = null
623
898
  if (resumeTaskToRun) {
899
+ const rTaskId = resumeTaskToRun.taskId || resumeTaskToRun.id
624
900
  const execSummaryJson = (() => {
625
901
  try { return JSON.stringify(execRes || {}).slice(0, 1000) } catch { return clamp(resultMsg, 400) }
626
902
  })()
627
903
  try {
904
+ const spec = resumeTaskToRun.resumeSpec || resumeTaskToRun
628
905
  resumeOut = await askOrCommandChief(deps, {
629
906
  sessionId: rootId,
630
- text: resumeTaskToRun.originalText,
631
- forcedTarget: resumeTaskToRun.forcedTarget || '',
632
- forcedMode: resumeTaskToRun.forcedMode || 'steer',
907
+ text: spec.originalText || resumeTaskToRun.originalText,
908
+ forcedTarget: spec.forcedTarget || resumeTaskToRun.forcedTarget || '',
909
+ forcedMode: spec.forcedMode || resumeTaskToRun.forcedMode || 'steer',
633
910
  _resumeCtx: {
634
- resumeTaskId: resumeTaskToRun.id,
635
- resumeDepth: (resumeTaskToRun.resumeDepth || 0) + 1,
911
+ resumeTaskId: rTaskId,
912
+ resumeDepth: (resumeTaskToRun.retryCount || resumeTaskToRun.resumeDepth || 0) + 1,
636
913
  triggerKind: 'approval',
637
914
  executedSummary: `${found.operationLabel} (${found.targetLabel}) => ${execSummaryJson}`,
638
- savedImagePaths: resumeTaskToRun.savedImagePaths || [],
915
+ savedImagePaths: spec.savedImagePaths || resumeTaskToRun.savedImagePaths || [],
639
916
  },
640
917
  })
918
+ mutateChiefState((st) => {
919
+ const ws = ensureWorkspace(st, rootId)
920
+ const ledgerList = Array.isArray(ws.taskLedger) ? ws.taskLedger : (ws.resumeTasks || [])
921
+ const task = ledgerList.find(t => t && (t.taskId === rTaskId || t.id === rTaskId))
922
+ if (task && (task.status === 'resuming' || task.status === 'verifying')) {
923
+ task.status = 'verifying'
924
+ task.updatedAt = Date.now()
925
+ const verifiedOk = Boolean(resumeOut && resumeOut.ok !== false)
926
+ task.status = verifiedOk ? 'completed' : 'failed'
927
+ task.lastReceipt = clamp((resumeOut && (resumeOut.reply || resumeOut.error)) || resultMsg, 260)
928
+ task.resolvedAt = Date.now()
929
+ }
930
+ })
641
931
  } catch (err) {
642
932
  resumeOut = { ok: false, error: (err && err.message) || String(err || 'resume failed') }
933
+ mutateChiefState((st) => {
934
+ const ws = ensureWorkspace(st, rootId)
935
+ const ledgerList = Array.isArray(ws.taskLedger) ? ws.taskLedger : (ws.resumeTasks || [])
936
+ const task = ledgerList.find(t => t && (t.taskId === rTaskId || t.id === rTaskId))
937
+ if (task && (task.status === 'resuming' || task.status === 'verifying')) {
938
+ task.status = 'failed'
939
+ task.updatedAt = Date.now()
940
+ task.lastReceipt = clamp(resumeOut.error, 260)
941
+ task.resolvedAt = Date.now()
942
+ }
943
+ })
944
+ } finally {
945
+ unmarkTaskResumingActive(rTaskId)
643
946
  }
644
- mutateChiefState((st) => {
645
- const ws = ensureWorkspace(st, rootId)
646
- const task = (ws.resumeTasks || []).find(t => t && t.id === resumeTaskToRun.id)
647
- if (task && task.status === 'resuming') {
648
- task.status = resumeOut && resumeOut.ok !== false ? 'completed' : 'failed'
649
- task.resolvedAt = Date.now()
650
- }
651
- })
652
947
  }
653
948
 
654
949
  const latestBoard = (resumeOut && resumeOut.board)
@@ -697,16 +992,21 @@ export async function handleElevationDecision(deps, {
697
992
  mutateChiefState((s) => {
698
993
  const ws = ensureWorkspace(s, rootId)
699
994
  ws.pendingElevation = null
700
- if (elev.resumeTaskId && Array.isArray(ws.resumeTasks)) {
701
- const linkedTask = ws.resumeTasks.find(t => t && t.id === elev.resumeTaskId)
995
+ const elevTaskId = elev.taskId || elev.resumeTaskId || ''
996
+ const ledgerList = Array.isArray(ws.taskLedger) ? ws.taskLedger : (ws.resumeTasks || [])
997
+ if (elevTaskId) {
998
+ const linkedTask = ledgerList.find(t => t && (t.taskId === elevTaskId || t.id === elevTaskId))
702
999
  if (linkedTask) {
703
1000
  linkedTask.status = 'cancelled'
1001
+ linkedTask.updatedAt = Date.now()
704
1002
  linkedTask.resolvedAt = Date.now()
1003
+ linkedTask.lastReceipt = '用户拒绝提权申请'
705
1004
  }
706
1005
  }
707
1006
  pushAuditToWs(ws, {
708
1007
  mode: resolveWorkspaceConfig(s, rootId).permissionMode,
709
1008
  stage: 'permission_gate',
1009
+ rule: 'elevation_rejected',
710
1010
  decision: 'elevation_rejected',
711
1011
  operation: '拒绝提权申请',
712
1012
  target: `${elev.fromMode} -> ${elev.targetMode}`,
@@ -760,12 +1060,14 @@ export async function handleElevationDecision(deps, {
760
1060
  }
761
1061
 
762
1062
  let resumeTaskToRun = null
1063
+ const elevTaskId = elev.taskId || elev.resumeTaskId || ''
763
1064
  mutateChiefState((s) => {
764
1065
  const ws = ensureWorkspace(s, rootId)
765
1066
  ws.pendingElevation = null
766
1067
  pushAuditToWs(ws, {
767
1068
  mode: chosenMode,
768
1069
  stage: 'permission_gate',
1070
+ rule: 'elevation_approved',
769
1071
  decision: 'elevation_approved',
770
1072
  operation: '批准提权',
771
1073
  target: `${CHIEF_PERMISSION_META[elev.fromMode]?.level || elev.fromMode} -> ${CHIEF_PERMISSION_META[chosenMode].level}`,
@@ -778,21 +1080,25 @@ export async function handleElevationDecision(deps, {
778
1080
  id: nextId('chat'),
779
1081
  role: 'chief',
780
1082
  kind: 'receipt',
781
- ...(elev.resumeTaskId ? { resumeTaskId: elev.resumeTaskId } : {}),
1083
+ ...(elevTaskId ? { resumeTaskId: elevTaskId } : {}),
782
1084
  text: `- 【🔐 已批准提权】当前会话权限已升级为「**${meta.level} · ${meta.title}**」${chosenMode === 'chief' ? '(已完成高风险确认)' : ''}。`,
783
1085
  actions: [`🔐 升至 ${meta.level}`],
784
1086
  at: Date.now(),
785
1087
  })
786
1088
  if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
787
1089
 
788
- if (elev.resumeTaskId && Array.isArray(ws.resumeTasks)) {
789
- const task = ws.resumeTasks.find(t => t && t.id === elev.resumeTaskId)
1090
+ const ledgerList = Array.isArray(ws.taskLedger) ? ws.taskLedger : (ws.resumeTasks || [])
1091
+ if (elevTaskId) {
1092
+ const task = ledgerList.find(t => t && (t.taskId === elevTaskId || t.id === elevTaskId))
790
1093
  if (task) {
791
1094
  if (task.expiresAt && Date.now() > task.expiresAt) {
792
1095
  task.status = 'expired'
1096
+ task.updatedAt = Date.now()
793
1097
  task.resolvedAt = Date.now()
794
- } else if ((task.resumeDepth || 0) < 2 && task.status !== 'resuming') {
1098
+ } else if ((task.retryCount || task.resumeDepth || 0) < 2 && task.status !== 'resuming') {
1099
+ markTaskResumingActive(task.taskId || task.id)
795
1100
  task.status = 'resuming'
1101
+ task.updatedAt = Date.now()
796
1102
  resumeTaskToRun = { ...task }
797
1103
  }
798
1104
  }
@@ -801,32 +1107,51 @@ export async function handleElevationDecision(deps, {
801
1107
 
802
1108
  let resumeOut = null
803
1109
  if (resumeTaskToRun) {
1110
+ const rTaskId = resumeTaskToRun.taskId || resumeTaskToRun.id
804
1111
  const meta = CHIEF_PERMISSION_META[chosenMode]
805
1112
  try {
1113
+ const spec = resumeTaskToRun.resumeSpec || resumeTaskToRun
806
1114
  resumeOut = await askOrCommandChief(deps, {
807
1115
  sessionId: rootId,
808
- text: resumeTaskToRun.originalText,
809
- forcedTarget: resumeTaskToRun.forcedTarget || '',
810
- forcedMode: resumeTaskToRun.forcedMode || 'steer',
1116
+ text: spec.originalText || resumeTaskToRun.originalText,
1117
+ forcedTarget: spec.forcedTarget || resumeTaskToRun.forcedTarget || '',
1118
+ forcedMode: spec.forcedMode || resumeTaskToRun.forcedMode || 'steer',
811
1119
  _resumeCtx: {
812
- resumeTaskId: resumeTaskToRun.id,
813
- resumeDepth: (resumeTaskToRun.resumeDepth || 0) + 1,
1120
+ resumeTaskId: rTaskId,
1121
+ resumeDepth: (resumeTaskToRun.retryCount || resumeTaskToRun.resumeDepth || 0) + 1,
814
1122
  triggerKind: 'elevation',
815
1123
  executedSummary: `已批准提权至 ${meta.level} · ${meta.title}`,
816
- savedImagePaths: resumeTaskToRun.savedImagePaths || [],
1124
+ savedImagePaths: spec.savedImagePaths || resumeTaskToRun.savedImagePaths || [],
817
1125
  },
818
1126
  })
1127
+ mutateChiefState((st) => {
1128
+ const ws = ensureWorkspace(st, rootId)
1129
+ const ledgerList = Array.isArray(ws.taskLedger) ? ws.taskLedger : (ws.resumeTasks || [])
1130
+ const task = ledgerList.find(t => t && (t.taskId === rTaskId || t.id === rTaskId))
1131
+ if (task && (task.status === 'resuming' || task.status === 'verifying')) {
1132
+ task.status = 'verifying'
1133
+ task.updatedAt = Date.now()
1134
+ task.status = resumeOut && resumeOut.ok !== false ? 'completed' : 'failed'
1135
+ task.lastReceipt = clamp((resumeOut && (resumeOut.reply || resumeOut.error)) || `提权至 ${meta.level} 后已自动续跑`, 260)
1136
+ task.resolvedAt = Date.now()
1137
+ }
1138
+ })
819
1139
  } catch (err) {
820
1140
  resumeOut = { ok: false, error: (err && err.message) || String(err || 'elevation resume failed') }
1141
+ mutateChiefState((st) => {
1142
+ const ws = ensureWorkspace(st, rootId)
1143
+ const ledgerList = Array.isArray(ws.taskLedger) ? ws.taskLedger : (ws.resumeTasks || [])
1144
+ const task = ledgerList.find(t => t && (t.taskId === rTaskId || t.id === rTaskId))
1145
+ if (task && (task.status === 'resuming' || task.status === 'verifying')) {
1146
+ task.status = 'failed'
1147
+ task.updatedAt = Date.now()
1148
+ task.lastReceipt = clamp(resumeOut.error, 260)
1149
+ task.resolvedAt = Date.now()
1150
+ }
1151
+ })
1152
+ } finally {
1153
+ unmarkTaskResumingActive(rTaskId)
821
1154
  }
822
- mutateChiefState((st) => {
823
- const ws = ensureWorkspace(st, rootId)
824
- const task = (ws.resumeTasks || []).find(t => t && t.id === resumeTaskToRun.id)
825
- if (task && task.status === 'resuming') {
826
- task.status = resumeOut && resumeOut.ok !== false ? 'completed' : 'failed'
827
- task.resolvedAt = Date.now()
828
- }
829
- })
830
1155
  }
831
1156
 
832
1157
  return {