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.
package/digest.js CHANGED
@@ -325,13 +325,16 @@ function linkedPeersLines(extras, limit = 4) {
325
325
 
326
326
  function takenOutArchiveLines(extras, limit, budget) {
327
327
  const taken = extras && Array.isArray(extras.takenOutArchives) ? extras.takenOutArchives : []
328
- const briefs = extras && Array.isArray(extras.sessionArchiveBriefs) ? extras.sessionArchiveBriefs : []
329
- if (!taken.length && !briefs.length) return []
328
+ const hooks = extras && Array.isArray(extras.sessionHookedArchives) ? extras.sessionHookedArchives : []
329
+ if (!taken.length && !hooks.length) return []
330
330
  const linesOut = []
331
+ const total = Number.isFinite(budget) ? Math.max(220, budget) : ANCHOR_BUDGET
331
332
  if (taken.length) {
332
- const shown = taken.slice(0, limit || 4)
333
- const header = '📌 当前摆上桌面备选(重点强调,主模型与参谋长共同关注) ' + taken.length + ' 份:'
334
- const total = Number.isFinite(budget) ? Math.max(200, budget) : ANCHOR_BUDGET
333
+ const shown = taken.slice(0, limit || 6)
334
+ const tokLabel = Number.isFinite(Number(extras && extras.desktopUsedTokens)) && Number(extras.desktopUsedTokens) > 0
335
+ ? ` · ${Number(extras.desktopUsedTokens)}/2400 Tokens`
336
+ : ''
337
+ const header = `📌 桌面在读档案(主代理与参谋同看 · 唯一正文注入源 · ${taken.length} 份${tokLabel}):`
335
338
  const build = perItem =>
336
339
  [header].concat(
337
340
  shown.map(item => {
@@ -348,10 +351,16 @@ function takenOutArchiveLines(extras, limit, budget) {
348
351
  }
349
352
  linesOut.push(...lines)
350
353
  }
351
- if (briefs.length) {
352
- const idxText = briefs.slice(0, 6).map(b => `《${clamp(b.title || '未命名', 28)}》`).join('、')
353
- const more = briefs.length > 6 ? ` 等共 ${briefs.length} 份` : ''
354
- linesOut.push(`🗂️ 本会话档案柜封存索引:${idxText}${more}(按需调用 chief_board({ action: "archive.search" }) 检索)`)
354
+ if (hooks.length) {
355
+ const shownHooks = hooks.slice(0, 6)
356
+ linesOut.push('🪝 本局档案柜可用钩子(参谋已整理 · 需看正文请调 chief_board({ action: "archive.pull", id: "档案ID" }) 拉出):')
357
+ for (const hItem of shownHooks) {
358
+ const kws = Array.isArray(hItem.hookKeywords) && hItem.hookKeywords.length
359
+ ? ' ' + hItem.hookKeywords.slice(0, 4).map(k => '#' + clamp(k, 14)).join(' ')
360
+ : ''
361
+ const cue = hItem.hookCue ? ' — ' + clamp(hItem.hookCue, 34) : ''
362
+ linesOut.push(` · [${hItem.id}] 《${clamp(hItem.title || '未命名', 30)}》${kws}${cue}`)
363
+ }
355
364
  }
356
365
  return linesOut
357
366
  }
package/model-tools.js CHANGED
@@ -12,6 +12,7 @@ import {
12
12
  proposeBoundToChief,
13
13
  readMailboxForAgent,
14
14
  requestChiefElevation,
15
+ appendChiefAuditLog,
15
16
  CHIEF_PERMISSION_META,
16
17
  } from './chief.js'
17
18
  import { normalizePermissionMode } from './chief-executor.js'
@@ -90,10 +91,14 @@ export function createModelTools(deps) {
90
91
  'note.remove',
91
92
  'note.read',
92
93
  'archive.search',
94
+ 'archive.pull',
93
95
  'archive.read',
94
96
  'archive.save',
95
97
  'context.compact',
96
98
  'permission.request',
99
+ 'inquiry.reply',
100
+ 'chief.request',
101
+ 'wall.list',
97
102
  'memory.add',
98
103
  'memory.remove',
99
104
  'memory.ask',
@@ -102,9 +107,13 @@ export function createModelTools(deps) {
102
107
  'Board operation (MUST be called whenever recording tasks/status/conclusions or relaying messages; plain text alone does NOT update the board or notify peers). '
103
108
  + 'Use "graph.plan" (or "task.batch") to plan a hierarchical/DAG task graph in one call (supports parentId, blockedBy, owner/subagent, intent, evidence). '
104
109
  + 'Use "task.dispatch" to spawn or message a subagent, "team.steer" to steer a subagent, and "mail.send" to relay messages across lead/subagents/sessions. '
110
+ + 'Use "inquiry.reply" (inquiryId, text) whenever you see a priority [INQUIRY #id] from DSH Chief — answer accurately and continue your current work immediately without stopping. '
111
+ + 'Use "chief.request" (subject, text) to ask DSH Chief for cross-session coordination, permission elevation, to report exploration & planning results, or when blocked by an insurmountable guard wall that cannot be bypassed safely. '
112
+ + 'Use "wall.list" (read-only) to inspect currently active persistent guard walls defending high-risk paths/commands. '
105
113
  + 'Use "bounds.propose" (field: "forbidden"|"allowed"|"notes", item, reason) when hitting a permission/sandbox/environment wall or summarizing boundaries ("allowed" = 必做事项, "forbidden" = 禁止红线, "notes" = 注意事项) so DSH Chief can request user approval. '
106
114
  + 'Use "permission.request" (targetMode: "assistant"|"strategist"|"chief", reason) when requesting higher DSH Chief permission tier from the user. '
107
- + 'Session Engineering Archives ("archive.search", "archive.read", "archive.save") access ONLY the current conversation\'s Session Cabinet (never Global Cabinet or unflipped Precipitated cold vault). '
115
+ + 'Session Engineering Archives ("archive.search", "archive.pull", "archive.read", "archive.save") access ONLY the current conversation\'s Session Cabinet (never Global Cabinet or unflipped Precipitated cold vault). '
116
+ + 'When you see a hook 🪝 in the digest, call "archive.pull" (with id or title) to read that curated dossier on demand. '
108
117
  + 'When Smart Co-Managed Compaction ("✦ 智选") is enabled, call "context.compact" with a concise phase-summary in "text" at clean phase boundaries to ask DSH Chief to harvest details into this session\'s cabinet and compact.',
109
118
  },
110
119
  tasks: {
@@ -169,9 +178,10 @@ export function createModelTools(deps) {
169
178
  enum: ['plan', 'goal'],
170
179
  description: 'mode.set: how this board is run. plan = a list of steps being ticked off. goal = one persistent objective steered toward.',
171
180
  },
172
- id: { type: 'string', description: 'Task id for update/claim/release/remove/dispatch/verify, or archive id for archive.read / archive.save.' },
181
+ id: { type: 'string', description: 'Task id for update/claim/release/remove/dispatch/verify, or archive id for archive.pull / archive.read / archive.save.' },
182
+ inquiryId: { type: 'string', description: 'Inquiry id (e.g. inq_xxx) when action is "inquiry.reply".' },
173
183
  noteId: { type: 'string', description: 'Note id for note.write / note.pin / note.unpin / note.remove; omit to create a new note.' },
174
- archiveId: { type: 'string', description: 'Archive dossier id for archive.read / archive.save (on-demand cold archive lookup/update).' },
184
+ archiveId: { type: 'string', description: 'Archive dossier id for archive.pull / archive.read / archive.save (on-demand session cabinet lookup/pull).' },
175
185
  query: { type: 'string', description: 'Keyword query for archive.search (searched only on explicit user demand).' },
176
186
  folder: { type: 'string', description: 'Filing cabinet drawer id for archive.search / archive.save (coords / incidents / contracts / ops / plans / inbox).' },
177
187
  paperclip: { type: 'string', enum: ['gold', 'silver', 'copper'], description: 'Paperclip importance badge for archive.save ("gold" anchor, "silver" verified, "copper" historical).' },
@@ -260,6 +270,11 @@ export function createModelTools(deps) {
260
270
  description: 'mail.send: delivery posture ("steer" cuts into next step boundary, "followup" queues/wakes next turn, "silent" drops into chief inbox for next pre-step).',
261
271
  },
262
272
  unreadOnly: { type: 'boolean', description: 'mail.inbox: when true, returns only unread messages.' },
273
+ reasoningEffort: {
274
+ type: 'string',
275
+ enum: ['off', 'low', 'medium', 'high', 'xhigh'],
276
+ description: 'task.dispatch: optional model reasoning effort hint (respects user 🔒 lock).',
277
+ },
263
278
  by: { type: 'string', description: 'Who acts: an agent label or a user name. Defaults to "agent".' },
264
279
  session: { type: 'string', description: 'Session id that owns the change; the GUI fills it automatically.' },
265
280
  scope: { type: 'string', enum: ['session', 'shared'], description: 'Board to hit. Default "session" = the caller\'s own (or root tree) board; "shared" = the machine-wide anchor board.' },
@@ -296,7 +311,10 @@ export function createModelTools(deps) {
296
311
  }
297
312
  if (view.archiveItem) {
298
313
  const it = view.archiveItem
299
- lines.push('📎 archive «' + it.title + '» [' + it.folder + ' · ' + it.paperclip + '] (' + it.id + ')')
314
+ const hooks = Array.isArray(it.hookKeywords) && it.hookKeywords.length ? ` 🪝[${it.hookKeywords.join(' · ')}]` : ''
315
+ const pulledTag = Array.isArray(it.leadPulledSessions) && it.leadPulledSessions.length ? ' · 📖 主代理已拉阅' : ''
316
+ lines.push('📎 archive «' + it.title + '» [' + it.folder + ' · ' + it.paperclip + pulledTag + '] (' + it.id + ')' + hooks)
317
+ if (it.hookCue) lines.push('hookCue: ' + it.hookCue)
300
318
  lines.push('summary: ' + (it.summary || ''))
301
319
  for (const pt of Array.isArray(it.points) ? it.points : []) {
302
320
  lines.push(' • ' + pt.title + ': ' + (pt.detail || pt.cue || ''))
@@ -438,6 +456,55 @@ export function createModelTools(deps) {
438
456
  }
439
457
  }
440
458
 
459
+ if (passed.action === 'inquiry.reply') {
460
+ const replyBody = str(passed.text || passed.body || passed.message || passed.note, '').trim()
461
+ if (!replyBody) return { ok: false, error: 'inquiry.reply 需要非空 text 参数' }
462
+ const deliv = await deliverCrossMessage(makeChiefDeps(runtime), {
463
+ fromSession: rawSession || session,
464
+ fromLabel: byDefault,
465
+ target: 'chief',
466
+ subject: '优先问询答复',
467
+ text: replyBody,
468
+ envelopeKind: 'inquiry_reply',
469
+ inquiryId: str(passed.inquiryId || passed.id || passed.taskId, ''),
470
+ })
471
+ if (!deliv.ok) return { ok: false, error: deliv.error }
472
+ const board = session ? loadBoard(boardFileFor(session)) : emptyBoard()
473
+ const roster = session ? await refreshSubagentTree(runtime, session, board) : []
474
+ return {
475
+ ok: true,
476
+ inquiryAnswered: deliv.inquiryAnswered || null,
477
+ continueOwnWork: true,
478
+ ...summary(board, roster),
479
+ }
480
+ }
481
+
482
+ if (passed.action === 'chief.request') {
483
+ const reqBody = str(passed.text || passed.body || passed.message || passed.note, '').trim()
484
+ if (!reqBody) return { ok: false, error: 'chief.request 需要非空 text 参数' }
485
+ const deliv = await deliverCrossMessage(makeChiefDeps(runtime), {
486
+ fromSession: rawSession || session,
487
+ fromLabel: byDefault,
488
+ target: 'chief',
489
+ subject: str(passed.subject || passed.title, '') || '主对话协同请求',
490
+ text: reqBody,
491
+ mode: 'followup',
492
+ })
493
+ if (!deliv.ok) return { ok: false, error: deliv.error }
494
+ const board = session ? boardForSession(boardFileFor(session)) : emptyBoard()
495
+ const roster = session ? await refreshSubagentTree(runtime, session, board) : []
496
+ return {
497
+ ok: true,
498
+ chiefRequest: {
499
+ mode: deliv.mode || deliv.deliveryMode || 'handled',
500
+ actionTaken: deliv.actionTaken || '',
501
+ taskId: deliv.taskId || '',
502
+ reply: deliv.reply || '',
503
+ },
504
+ ...summary(board, roster),
505
+ }
506
+ }
507
+
441
508
  if (passed.action === 'mail.send') {
442
509
  const target = str(passed.target || passed.agent || passed.subagent, 'lead').trim() || 'lead'
443
510
  const msgText = str(passed.text || passed.message || passed.prompt || passed.body || passed.note, '').trim()
@@ -531,8 +598,26 @@ export function createModelTools(deps) {
531
598
  }
532
599
  }
533
600
 
534
- const result = runAction(session ? { ...passed, by: byDefault, session } : { ...passed, by: byDefault })
535
- if (!result.ok) return { ok: false, error: result.error }
601
+ const actionArgs = session
602
+ ? { ...passed, by: byDefault, session, _callerOrigin: 'model_tool' }
603
+ : { ...passed, by: byDefault, _callerOrigin: 'model_tool' }
604
+ const result = runAction(actionArgs)
605
+ if (!result.ok) {
606
+ if (result.blockedBySafetyGuard) {
607
+ appendChiefAuditLog(session || rawSession || 'global', {
608
+ mode: 'advisor',
609
+ stage: 'safety_guard',
610
+ rule: result.rule || 'bounds_human_only',
611
+ decision: 'blocked',
612
+ operation: String(passed.action || 'bounds'),
613
+ target: String(passed.field || 'bounds'),
614
+ reason: result.error,
615
+ outcome: 'blocked',
616
+ by: byDefault,
617
+ })
618
+ }
619
+ return { ok: false, error: result.error }
620
+ }
536
621
  const mergedBoard = session && result.board ? boardForSession(boardFileFor(session)) : result.board
537
622
  const roster = session ? await refreshSubagentTree(runtime, session, mergedBoard) : []
538
623
  return {
@@ -541,6 +626,7 @@ export function createModelTools(deps) {
541
626
  ...(result.archiveSearch ? { archiveSearch: result.archiveSearch } : {}),
542
627
  ...(result.archiveItem ? { archiveItem: result.archiveItem } : {}),
543
628
  ...(result.archiveSaved ? { archiveSaved: result.archiveSaved } : {}),
629
+ ...(result.walls ? { guardWalls: result.walls } : {}),
544
630
  ...(result.truncated ? { truncated: result.truncated } : {}),
545
631
  }
546
632
  },
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "dsh-chief",
3
- "version": "1.3.0",
3
+ "version": "1.5.0",
4
4
  "icon": "icon.svg",
5
5
  "type": "module",
6
- "description": "AI manager for your agent crews. Let AI manage AI — it watches the flow, stops a runaway loop before it burns budget, and asks before touching your workspace. Less babysitting, fewer blow-ups.",
6
+ "description": "Right-sidebar supervisor for DeepSeek Harness (DSH): prevents context-compaction amnesia, monitors subagent DAGs, gates file edits and shell commands behind per-action approvals, breaks runaway loops, and hands off long sessions without bloating prompt tokens.",
7
7
  "author": "gluztm",
8
8
  "license": "AGPL-3.0-only",
9
9
  "repository": {
@@ -19,28 +19,43 @@
19
19
  "deepseek-harness",
20
20
  "dsh",
21
21
  "dsh-plugin",
22
- "ai-manager",
23
- "ai管家",
24
- "ai-orchestrator",
25
- "ai-supervisor",
26
- "no-babysitting",
27
- "免监工",
28
- "autonomous-agents",
29
- "agent-orchestration",
30
- "multi-agent",
31
- "subagent",
32
- "dag",
33
- "session-management",
34
- "long-session",
35
- "workflow-automation",
36
22
  "context-compaction",
23
+ "compaction-amnesia",
24
+ "context-loss",
25
+ "context-window",
26
+ "token-saving",
27
+ "agent-loop",
28
+ "infinite-loop",
29
+ "unattended-agent",
30
+ "overnight-coding",
31
+ "auto-continue",
32
+ "stop-babysitting",
33
+ "session-handoff",
34
+ "chat-too-long",
37
35
  "cross-session-memory",
38
- "cost-control",
39
- "runaway-loop",
40
- "read-only-guardrails",
41
- "handoff",
42
- "archive-vault",
43
- "superagent"
36
+ "subagent-monitor",
37
+ "multi-agent",
38
+ "task-dag",
39
+ "approval-gate",
40
+ "human-in-the-loop",
41
+ "read-only-mode",
42
+ "command-guardrails",
43
+ "workspace-safety",
44
+ "guard-walls",
45
+ "pre-execute-guard",
46
+ "事前拦截",
47
+ "压缩失忆",
48
+ "挂机跑任务",
49
+ "跨窗口交接",
50
+ "防死循环",
51
+ "只读护栏",
52
+ "ai-manager",
53
+ "superagent",
54
+ "cognitive-desktop",
55
+ "thinking-effort",
56
+ "dream-roam",
57
+ "认知桌面",
58
+ "物理驻墙"
44
59
  ],
45
60
  "engines": {
46
61
  "node": ">=22.13.0",
@@ -50,9 +65,9 @@
50
65
  "scripts": {
51
66
  "build:client": "node ./scripts/build-client.mjs",
52
67
  "check:client": "node ./scripts/build-client.mjs --check",
53
- "check:syntax": "node -e \"const fs=require('fs'),cp=require('child_process');for(const f of fs.readdirSync('.').filter(x=>x.endsWith('.js')))cp.execFileSync(process.execPath,['--check',f]);\"",
54
- "test:ci": "npm run check:client && npm run check:syntax && node ./tests/verify-v130-release-gate.mjs",
55
- "test": "node ./tests/verify-v130-release-gate.mjs && node -e \"const fs=require('fs'),path=require('path'),cp=require('child_process');if(fs.existsSync('../tools')){for(const s of ['verify-chief-facade-split.mjs','verify-index-modular-split.mjs','verify-archives-modular-split.mjs','verify-client-modular-build.mjs','verify-v121-permissions-and-ui.mjs','verify-compaction-and-blank-chat.mjs','check-action-surface.mjs','verify-v130-four-chains.mjs']){cp.execFileSync(process.execPath,[path.resolve('..','tools',s)],{stdio:'inherit'});}}\""
68
+ "check:syntax": "node -e \"const fs=require('fs'),path=require('path'),cp=require('child_process');const walk=d=>{for(const e of fs.readdirSync(d,{withFileTypes:true})){const p=path.join(d,e.name);if(e.isDirectory()&&(e.name==='safety'||e.name==='src'||e.name==='client'))walk(p);else if(e.isFile()&&e.name.endsWith('.js'))cp.execFileSync(process.execPath,['--check',p]);}};walk('.');\"",
69
+ "test:ci": "npm run check:client && npm run check:syntax && node ./tests/verify-v130-release-gate.mjs && node ./tests/verify-v140-safety-gate.mjs && node ./tests/verify-v140-collab-gate.mjs && node ./tests/verify-v150-final-gate.mjs",
70
+ "test": "node ./tests/verify-v130-release-gate.mjs && node ./tests/verify-v140-safety-gate.mjs && node ./tests/verify-v140-collab-gate.mjs && node ./tests/verify-v150-final-gate.mjs && node -e \"const fs=require('fs'),path=require('path'),cp=require('child_process');if(fs.existsSync('../tools')){for(const s of ['verify-chief-facade-split.mjs','verify-index-modular-split.mjs','verify-archives-modular-split.mjs','verify-client-modular-build.mjs','verify-v121-permissions-and-ui.mjs','verify-compaction-and-blank-chat.mjs','check-action-surface.mjs','verify-v130-four-chains.mjs']){cp.execFileSync(process.execPath,[path.resolve('..','tools',s)],{stdio:'inherit'});}}\""
56
71
  },
57
72
  "exports": {
58
73
  ".": "./index.js",
@@ -83,6 +98,7 @@
83
98
  "chief-review.js",
84
99
  "chief-approvals.js",
85
100
  "chief-executor.js",
101
+ "safety/*.js",
86
102
  "auto-continue.js",
87
103
  "archives.js",
88
104
  "archive-core.js",
package/runtime-hooks.js CHANGED
@@ -21,6 +21,7 @@ import {
21
21
  } from './idle-guard.js'
22
22
  import {
23
23
  loadChiefState,
24
+ mutateChiefState,
24
25
  resolveWorkspaceConfig,
25
26
  invalidateChiefModelCatalog,
26
27
  buildMessageEnvelope,
@@ -30,9 +31,16 @@ import {
30
31
  queueChiefApproval,
31
32
  appendChiefAuditLog,
32
33
  } from './chief.js'
34
+ import {
35
+ touchWorkspaceActivity,
36
+ upsertTaskLedgerOnWs,
37
+ normalizeSuggestion,
38
+ ensureWorkspace,
39
+ SUGGESTIONS_CAP,
40
+ } from './chief-state.js'
33
41
  import { createAutoContinueEngine } from './auto-continue.js'
34
42
  import { bootstrapArchivesFromSharedBoard } from './archives.js'
35
- import { normalizePermissionMode } from './chief-executor.js'
43
+ import { normalizePermissionMode, evaluatePreExecuteDefense, evaluateSafetyGuardHardRules, listGuardWalls } from './chief-executor.js'
36
44
  import {
37
45
  newId,
38
46
  nowMs,
@@ -169,7 +177,7 @@ export function createRuntimeHooks(deps) {
169
177
  const st = loadChiefState()
170
178
  const rk = resolveRootSessionId(rootKey || sid) || rootKey || sid
171
179
  const cfg = resolveWorkspaceConfig(st, rk)
172
- return Boolean(cfg.stopped || cfg.paceMode === 'stopped')
180
+ return Boolean(cfg.stopped || cfg.paceMode === 'stopped' || cfg.runMode === 'off')
173
181
  } catch {
174
182
  return false
175
183
  }
@@ -199,28 +207,88 @@ export function createRuntimeHooks(deps) {
199
207
  const state = loadChiefState()
200
208
  const ws = state && state.workspaces && state.workspaces[key] ? state.workspaces[key] : null
201
209
  const effCfg = resolveWorkspaceConfig(state, key)
210
+ const runMode = effCfg && effCfg.runMode ? effCfg.runMode : 'off'
211
+ if ((effCfg && effCfg.stopped) || (runMode !== 'patrol' && runMode !== 'managed')) {
212
+ return { allowed: false, skipped: 'run-mode-off', logMessage: '参谋处于「⏸ 关停」模式,仅 patrol/managed 模式允许 Auto continue 唤醒' }
213
+ }
214
+
215
+ // Check forbidden bounds and active guard walls BEFORE continuing
216
+ const cwdForCheck = (key && key !== 'global' && getSessionCwd(runtime, key)) || process.cwd()
217
+ const board = key && key !== 'global' ? boardForSession(boardFileFor(key)) : null
218
+ const detailSample = `${trigger || ''} ${detail || ''}`.trim()
219
+ const safetyGuard = evaluateSafetyGuardHardRules({ tool: 'relay', opClass: 'workflow', command: detailSample, board })
220
+ if (safetyGuard && safetyGuard.blocked) {
221
+ appendChiefAuditLog(key, {
222
+ mode: effCfg.permissionMode || 'advisor',
223
+ stage: 'safety_guard',
224
+ rule: safetyGuard.rule || 'auto_continue_blocked',
225
+ decision: 'blocked',
226
+ operation: '断线续跑边界检查',
227
+ target: sessionId,
228
+ reason: safetyGuard.reason,
229
+ outcome: 'blocked',
230
+ by: 'auto-continue',
231
+ })
232
+ return { allowed: false, skipped: 'guard-wall-blocked', logMessage: `安全护栏阻断自动续跑:${safetyGuard.reason}` }
233
+ }
234
+ const activeWalls = listGuardWalls(cwdForCheck)
235
+ if (detail && Array.isArray(activeWalls) && activeWalls.some(w => w && w.enabled && w.mode === 'deny' && Array.isArray(w.patterns) && w.patterns.some(p => p && detail.includes(p)))) {
236
+ return { allowed: false, skipped: 'guard-wall-blocked', logMessage: '触发动态物理墙保护红线,已暂停自动续跑等待人工确认' }
237
+ }
238
+
202
239
  const hasAck = hasValidChiefRiskAck(ws)
203
240
  const mode = normalizePermissionMode(effCfg && effCfg.permissionMode, {
204
241
  requireAck: true,
205
242
  hasChiefRiskAck: hasAck,
206
243
  })
207
244
  if (mode === 'advisor') {
208
- return { allowed: false, skipped: 'advisor-readonly', logMessage: 'L0 顾问模式(只读):禁止自动向主对话续跑' }
245
+ return { allowed: false, skipped: 'advisor-readonly', logMessage: 'L0 顾问模式(只读):检测到断流仅作提示,不向主对话发送续跑请求' }
209
246
  }
210
247
  if (mode === 'assistant') {
211
- return { allowed: false, skipped: 'assistant-no-workflow', logMessage: 'L1 助手模式:仅维护参谋系统,跳过主对话断线自动续跑' }
248
+ mutateChiefState((s) => {
249
+ const w = ensureWorkspace(s, key)
250
+ const sug = normalizeSuggestion({
251
+ kind: 'advice',
252
+ fromAgent: '⚡ 断流检测提醒',
253
+ title: `主对话断流待手动续跑(${trigger})`,
254
+ reason: detail ? String(detail).slice(0, 160) : 'L1 助手模式不接管主对话工作流,点此一键下发续跑请求。',
255
+ target: 'lead',
256
+ targetLabel: '主对话 (@lead)',
257
+ mode: 'followup',
258
+ draftText: `[EXECUTION_REQUEST] 检测到上一轮中断(${trigger}),请核查进度后继续推进。`,
259
+ })
260
+ if (sug && !w.suggestions.some(x => x && x.status === 'pending' && x.title === sug.title)) {
261
+ w.suggestions.push(sug)
262
+ if (w.suggestions.length > SUGGESTIONS_CAP) w.suggestions = w.suggestions.slice(-SUGGESTIONS_CAP)
263
+ }
264
+ })
265
+ return { allowed: false, skipped: 'assistant-no-workflow', logMessage: 'L1 助手模式:已记入建议卡提醒断流,跳过主对话工作流续跑' }
212
266
  }
213
267
  if (mode === 'strategist') {
268
+ let ledgerId = ''
269
+ mutateChiefState((s) => {
270
+ const w = ensureWorkspace(s, key)
271
+ const entry = upsertTaskLedgerOnWs(w, {
272
+ kind: 'auto_continue',
273
+ status: 'awaiting_approval',
274
+ originalText: `[断线续跑 · ${trigger}] ${detail ? String(detail).slice(0, 160) : '异常中断恢复'}`,
275
+ forcedTarget: 'lead',
276
+ lastReceipt: '等待 L2 逐项授权唤醒主对话',
277
+ })
278
+ if (entry) ledgerId = entry.taskId || entry.id
279
+ })
214
280
  const apr = queueChiefApproval(key, {
215
281
  category: 'main_workflow',
216
282
  operationLabel: '断线自动续跑主对话',
217
283
  targetLabel: '主对话 (@lead)',
218
- reason: `检测到会话中断或未收口(${trigger}),L2 参谋模式需您允许后再发送续跑指令`,
219
- impact: '点击「允许本次操作」后将立即唤醒主对话继续推进当前任务',
284
+ reason: `检测到会话中断或未收口(${trigger}),已核验安全边界与物理墙,L2 参谋模式需您允许后唤醒续跑`,
285
+ impact: '点击「允许本次操作」后将发出 [EXECUTION_REQUEST] 信封唤醒主对话继续推进',
220
286
  preview: detail ? String(detail).slice(0, 220) : `触发原因:${trigger}`,
221
287
  dedupeKey: `autocont:${sessionId}:${trigger}:${Math.floor(Date.now() / 15_000)}`,
222
288
  kind: 'auto_continue',
223
- payload: { sessionId, trigger, detail: detail || '' },
289
+ taskId: ledgerId,
290
+ resumeTaskId: ledgerId,
291
+ payload: { sessionId, trigger, detail: detail || '', taskId: ledgerId },
224
292
  by: 'auto-continue',
225
293
  })
226
294
  appendChiefAuditLog(key, {
@@ -237,10 +305,23 @@ export function createRuntimeHooks(deps) {
237
305
  allowed: false,
238
306
  skipped: 'pending-approval',
239
307
  approvalId: apr && apr.id,
308
+ taskId: ledgerId,
240
309
  logMessage: `L2 参谋模式:已提交断线续跑逐项授权弹窗(${trigger})`,
241
310
  }
242
311
  }
243
- return { allowed: true }
312
+ let l3TaskId = ''
313
+ mutateChiefState((s) => {
314
+ const w = ensureWorkspace(s, key)
315
+ const entry = upsertTaskLedgerOnWs(w, {
316
+ kind: 'auto_continue',
317
+ status: 'running',
318
+ originalText: `[L3 断线自动续跑 · ${trigger}] ${detail ? String(detail).slice(0, 160) : '异常中断自动恢复'}`,
319
+ forcedTarget: 'lead',
320
+ lastReceipt: '已过边界与物理墙核验,准备下发 [EXECUTION_REQUEST]',
321
+ })
322
+ if (entry) l3TaskId = entry.taskId || entry.id
323
+ })
324
+ return { allowed: true, taskId: l3TaskId }
244
325
  } catch {
245
326
  return { allowed: false, skipped: 'permission-error' }
246
327
  }
@@ -328,7 +409,8 @@ export function createRuntimeHooks(deps) {
328
409
  linkedPeersCount: linked.linkedPeersCount,
329
410
  linkedPeersProgress: linked.linkedPeersProgress,
330
411
  takenOutArchives: archCtx.takenOutArchives,
331
- sessionArchiveBriefs: archCtx.sessionArchiveBriefs,
412
+ sessionHookedArchives: archCtx.sessionHookedArchives,
413
+ desktopUsedTokens: archCtx.desktopUsedTokens,
332
414
  smartCompactActive: archCtx.smartCompactActive,
333
415
  chiefPermissionMode: archCtx.chiefPermissionMode,
334
416
  })
@@ -413,6 +495,10 @@ export function createRuntimeHooks(deps) {
413
495
  try {
414
496
  if (!event || !session || !session.id) return
415
497
  const id = String(session.id)
498
+ const rootIdForAct = resolveRootSessionId(id) || id
499
+ if (event.type === 'turn/start' || event.type === 'message/user' || event.type === 'tool/call' || event.type === 'turn/end') {
500
+ touchWorkspaceActivity(rootIdForAct)
501
+ }
416
502
  if (event.type === 'tool/call' && event.data) {
417
503
  const turn = event.data.turn
418
504
  noteToolCall(id, turn)
@@ -426,17 +512,25 @@ export function createRuntimeHooks(deps) {
426
512
  const reason = String(rawReason && typeof rawReason === 'object' ? (rawReason.kind || '') : (rawReason || '')).toLowerCase()
427
513
  const nestedReason = String(rawReason && typeof rawReason === 'object' && rawReason.reason && typeof rawReason.reason === 'object' ? (rawReason.reason.kind || '') : '').toLowerCase()
428
514
  const isStoppedByUserOrPolicy = reason === 'aborted' || reason === 'blocked' || nestedReason === 'aborted' || nestedReason === 'blocked'
515
+ const abnormalTrig = (reason === 'error' || nestedReason === 'error')
516
+ ? 'turn_error'
517
+ : ((reason === 'interrupted' || nestedReason === 'interrupted' || reason === 'max-tokens' || reason === 'no-visible-output') ? 'stream_interrupted' : '')
429
518
  const turnNum = Number(event.data && event.data.turn)
430
519
  const steerKey = `${id}:${turnNum}`
431
520
  const steeredAt = deps.hostState.autoSteeredTurns.get(steerKey) || 0
432
521
  if (steeredAt) deps.hostState.autoSteeredTurns.delete(steerKey)
433
522
  if (!isStoppedByUserOrPolicy && !(steeredAt && Date.now() - steeredAt < 30_000)) {
434
523
  const rootId = resolveRootSessionId(id) || id
435
- if (!isRootStopped(rootId, id)) {
524
+ if (!isRootStopped(rootId, id) || abnormalTrig) {
436
525
  const agents = runtime && runtime.get ? runtime.get('agents') : null
437
526
  const liveAgent = agents && typeof agents.get === 'function' ? agents.get(id) : null
438
527
  if (liveAgent) {
439
- scheduleChiefTurnReview(makeChiefDeps(runtime), { agent: liveAgent, sessionId: id, turn: event.data && event.data.turn })
528
+ scheduleChiefTurnReview(makeChiefDeps(runtime), {
529
+ agent: liveAgent,
530
+ sessionId: id,
531
+ turn: event.data && event.data.turn,
532
+ ...(abnormalTrig ? { abnormalTrigger: abnormalTrig } : {}),
533
+ })
440
534
  }
441
535
  }
442
536
  }
@@ -605,11 +699,117 @@ export function createRuntimeHooks(deps) {
605
699
  }
606
700
  })
607
701
 
608
- // Model tools: the cross-Session half of the same operations.
702
+ // Model tools: the cross-Session half of the same operations + whole-session pre-execute physical defense.
609
703
  ctx.inject(['tools'], toolCtx => {
610
704
  for (const tool of [boardTool(runtime), boundariesTool(runtime), handoffTool(runtime), memoryTool(runtime)]) {
611
705
  toolCtx.effect(() => toolCtx.tools.register(tool), 'dsh-chief: tool ' + tool.name)
612
706
  }
707
+ const hookOn = typeof toolCtx.on === 'function'
708
+ ? toolCtx.on.bind(toolCtx)
709
+ : (typeof ctx.on === 'function' ? ctx.on.bind(ctx) : null)
710
+ if (hookOn) {
711
+ toolCtx.effect(() => hookOn('tools/pre-execute', async (exec, next) => {
712
+ try {
713
+ if (!exec || !exec.name) return next()
714
+ const caller = exec.agent || null
715
+ const sid = caller && caller.id ? String(caller.id) : ''
716
+ const rootId = resolveRootSessionId(sid, caller) || sid || 'global'
717
+ const cwd = (sid && getSessionCwd(runtime, sid)) || (rootId !== 'global' && getSessionCwd(runtime, rootId)) || process.cwd()
718
+ const board = rootId && rootId !== 'global' ? boardForSession(boardFileFor(rootId)) : loadBoard(boardFile())
719
+ const verdict = evaluatePreExecuteDefense({
720
+ tool: String(exec.name),
721
+ args: exec.arguments && typeof exec.arguments === 'object' ? exec.arguments : {},
722
+ cwd,
723
+ board,
724
+ })
725
+ if (verdict && verdict.decision === 'deny') {
726
+ const st = loadChiefState()
727
+ const effCfg = resolveWorkspaceConfig(st, rootId)
728
+ const ident = resolveAgentIdentity(runtime, sid, caller)
729
+ const actorName = (ident && ident.self) || 'lead'
730
+ const targetPreview = String(
731
+ (exec.arguments && (exec.arguments.path || exec.arguments.file_path || exec.arguments.command || exec.arguments.cmd))
732
+ || exec.name,
733
+ ).slice(0, 120)
734
+ appendChiefAuditLog(rootId, {
735
+ mode: effCfg.permissionMode || 'advisor',
736
+ stage: verdict.stage || 'guard_wall',
737
+ rule: verdict.rule || 'pre_execute_denied',
738
+ decision: 'blocked',
739
+ operation: String(exec.name),
740
+ target: targetPreview,
741
+ reason: verdict.reason,
742
+ outcome: 'blocked',
743
+ by: actorName,
744
+ })
745
+ try {
746
+ const bFile = rootId !== 'global' ? boardFileFor(rootId) : boardFile()
747
+ withBoardLock(bFile, () => {
748
+ const b = loadBoard(bFile)
749
+ pushLog(b, `🧱 事前物理防线已拦截 @${actorName} 调用 ${exec.name}:${String(verdict.reason || '').slice(0, 110)}`, 'guard', sid || rootId)
750
+ saveBoard(b, bFile)
751
+ })
752
+ } catch {}
753
+ if (effCfg.tacticalModes && effCfg.tacticalModes.redlineSentinel) {
754
+ mutateChiefState((s) => {
755
+ if (!s.workspaces || !s.workspaces[rootId]) return
756
+ const ws = s.workspaces[rootId]
757
+ if (!Array.isArray(ws.chat)) ws.chat = []
758
+ ws.chat.push({
759
+ id: 'chat-' + Date.now().toString(36),
760
+ role: 'chief',
761
+ kind: 'receipt',
762
+ text: `- 【🧱 红线哨兵 · 事前物理拦截】已当场阻断 \`@${actorName}\` 的越界调用 \`${exec.name}\`\n- 【拦截原因】${verdict.reason}`,
763
+ actions: [verdict.badge || '🧱 事前物理拦截'],
764
+ at: Date.now(),
765
+ })
766
+ })
767
+ }
768
+ if (effCfg && (effCfg.runMode === 'patrol' || effCfg.runMode === 'managed') && !effCfg.stopped) {
769
+ scheduleChiefTurnReview(makeChiefDeps(runtime), {
770
+ agent: caller,
771
+ sessionId: sid || rootId,
772
+ abnormalTrigger: 'guard_wall_blocked',
773
+ })
774
+ }
775
+ const escalationCue = verdict.wallId
776
+ ? `(严禁尝试命令或路径变形绕过物理墙 [${verdict.wallId}];仅当你确认无任何合法替代方案可继续任务时,可调用 chief_board({ action: "chief.request", subject: "撞墙阻断上报", text: "说明被拦截墙(${verdict.wallId})、为何无法绕过及当前卡点" }) 上报参谋长评估)`
777
+ : ''
778
+ return {
779
+ kind: 'deny',
780
+ reason: `[DSH 安全卫兵事前物理拦截] ${verdict.reason}${escalationCue}`,
781
+ info: { stage: verdict.stage, rule: verdict.rule, wallId: verdict.wallId || '' },
782
+ }
783
+ } else if (verdict && verdict.decision === 'ask') {
784
+ const st = loadChiefState()
785
+ const effCfg = resolveWorkspaceConfig(st, rootId)
786
+ const ident = resolveAgentIdentity(runtime, sid, caller)
787
+ const actorName = (ident && ident.self) || 'lead'
788
+ const targetPreview = String(
789
+ (exec.arguments && (exec.arguments.path || exec.arguments.file_path || exec.arguments.command || exec.arguments.cmd))
790
+ || exec.name,
791
+ ).slice(0, 120)
792
+ appendChiefAuditLog(rootId, {
793
+ mode: effCfg.permissionMode || 'advisor',
794
+ stage: verdict.stage || 'guard_wall',
795
+ rule: verdict.rule || 'guard_wall_require_approval_cmd',
796
+ decision: 'pending_approval',
797
+ operation: String(exec.name),
798
+ target: targetPreview,
799
+ reason: verdict.reason,
800
+ outcome: 'pending',
801
+ by: actorName,
802
+ })
803
+ return {
804
+ kind: 'ask',
805
+ reason: `[DSH 物理驻墙审批] ${verdict.reason}`,
806
+ displayReason: verdict.displayReason || verdict.reason,
807
+ }
808
+ }
809
+ } catch {}
810
+ return next()
811
+ }), 'dsh-chief: pre-execute physical defense')
812
+ }
613
813
  })
614
814
 
615
815
  // Runtime capability probe for DSH >= 0.2.2-rc.2 named subagent APIs
@@ -621,6 +821,15 @@ export function createRuntimeHooks(deps) {
621
821
  } catch {}
622
822
  }
623
823
  })
824
+
825
+ // Cold-start safety reconciliation for persistent TaskLedger (stale running/resuming -> interrupted; past TTL -> expired)
826
+ try {
827
+ const bootSt = loadChiefState({ forceDisk: true })
828
+ const hasNeedReconcile = Object.values((bootSt && bootSt.workspaces) || {}).some(
829
+ ws => Array.isArray(ws && ws.taskLedger) && ws.taskLedger.some(t => t && (t.status === 'interrupted' || t.status === 'expired')),
830
+ )
831
+ if (hasNeedReconcile) mutateChiefState(() => {})
832
+ } catch {}
624
833
  }
625
834
 
626
835
  return {