dsh-chief 1.4.0 → 1.6.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-chief",
3
- "version": "1.4.0",
3
+ "version": "1.6.0",
4
4
  "icon": "icon.svg",
5
5
  "type": "module",
6
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.",
@@ -50,7 +50,14 @@
50
50
  "防死循环",
51
51
  "只读护栏",
52
52
  "ai-manager",
53
- "superagent"
53
+ "superagent",
54
+ "cognitive-desktop",
55
+ "thinking-effort",
56
+ "dream-roam",
57
+ "认知桌面",
58
+ "物理驻墙",
59
+ "workflow-topology",
60
+ "bilingual"
54
61
  ],
55
62
  "engines": {
56
63
  "node": ">=22.13.0",
@@ -61,8 +68,8 @@
61
68
  "build:client": "node ./scripts/build-client.mjs",
62
69
  "check:client": "node ./scripts/build-client.mjs --check",
63
70
  "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('.');\"",
64
- "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",
65
- "test": "node ./tests/verify-v130-release-gate.mjs && node ./tests/verify-v140-safety-gate.mjs && node ./tests/verify-v140-collab-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'});}}\""
71
+ "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 && node ./tests/verify-v160-flow-gate.mjs",
72
+ "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 ./tests/verify-v160-flow-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'});}}\""
66
73
  },
67
74
  "exports": {
68
75
  ".": "./index.js",
package/runtime-hooks.js CHANGED
@@ -10,8 +10,13 @@ import { renderDigest } from './digest.js'
10
10
  import { appendMemory, captureTurn } from './memory.js'
11
11
  import {
12
12
  buildNotice,
13
+ buildMidTurnSpinNotice,
13
14
  clearCallTrail,
15
+ clearMidTurnSpin,
16
+ detectMidTurnSpin,
14
17
  isPlanWrite,
18
+ markMidTurnSpinActed,
19
+ noteCallResult,
15
20
  noteCallTrail,
16
21
  noteIntervention,
17
22
  notePlanWrite,
@@ -31,9 +36,20 @@ import {
31
36
  queueChiefApproval,
32
37
  appendChiefAuditLog,
33
38
  } from './chief.js'
39
+ import {
40
+ touchWorkspaceActivity,
41
+ upsertTaskLedgerOnWs,
42
+ normalizeSuggestion,
43
+ ensureWorkspace,
44
+ recordWorkspaceAlertEvent,
45
+ SUGGESTIONS_CAP,
46
+ CHAT_CAP,
47
+ nextId,
48
+ clamp,
49
+ } from './chief-state.js'
34
50
  import { createAutoContinueEngine } from './auto-continue.js'
35
51
  import { bootstrapArchivesFromSharedBoard } from './archives.js'
36
- import { normalizePermissionMode, evaluatePreExecuteDefense } from './chief-executor.js'
52
+ import { normalizePermissionMode, buildCapabilityScope, evaluatePreExecuteDefense, evaluateSafetyGuardHardRules, listGuardWalls } from './chief-executor.js'
37
53
  import {
38
54
  newId,
39
55
  nowMs,
@@ -165,7 +181,7 @@ export function createRuntimeHooks(deps) {
165
181
  pushLog,
166
182
  })
167
183
 
168
- const isRootStopped = (rootKey, sid) => {
184
+ const isExplicitStopped = (rootKey, sid) => {
169
185
  try {
170
186
  const st = loadChiefState()
171
187
  const rk = resolveRootSessionId(rootKey || sid) || rootKey || sid
@@ -176,6 +192,17 @@ export function createRuntimeHooks(deps) {
176
192
  }
177
193
  }
178
194
 
195
+ const isRootStopped = (rootKey, sid) => {
196
+ try {
197
+ const st = loadChiefState()
198
+ const rk = resolveRootSessionId(rootKey || sid) || rootKey || sid
199
+ const cfg = resolveWorkspaceConfig(st, rk)
200
+ return Boolean(cfg.stopped || cfg.paceMode === 'stopped' || (cfg.runMode === 'off' && !(cfg.tacticalModes && cfg.tacticalModes.intervention)))
201
+ } catch {
202
+ return false
203
+ }
204
+ }
205
+
179
206
  const autoContinue = createAutoContinueEngine({
180
207
  createMessage: (text, sourceKind) => buildMessageEnvelope(text, sourceKind),
181
208
  getAgent: async (sid) => {
@@ -200,28 +227,89 @@ export function createRuntimeHooks(deps) {
200
227
  const state = loadChiefState()
201
228
  const ws = state && state.workspaces && state.workspaces[key] ? state.workspaces[key] : null
202
229
  const effCfg = resolveWorkspaceConfig(state, key)
230
+ const runMode = effCfg && effCfg.runMode ? effCfg.runMode : 'off'
231
+ const interventionOn = Boolean(effCfg && effCfg.tacticalModes && effCfg.tacticalModes.intervention)
232
+ if ((effCfg && effCfg.stopped) || (runMode !== 'patrol' && runMode !== 'managed' && !interventionOn)) {
233
+ return { allowed: false, skipped: 'run-mode-off', logMessage: '参谋处于「⏸ 关停」模式,仅 patrol/managed 或强介入激活时允许 Auto continue 唤醒' }
234
+ }
235
+
236
+ // Check forbidden bounds and active guard walls BEFORE continuing
237
+ const cwdForCheck = (key && key !== 'global' && getSessionCwd(runtime, key)) || process.cwd()
238
+ const board = key && key !== 'global' ? boardForSession(boardFileFor(key)) : null
239
+ const detailSample = `${trigger || ''} ${detail || ''}`.trim()
240
+ const safetyGuard = evaluateSafetyGuardHardRules({ tool: 'relay', opClass: 'workflow', command: detailSample, board })
241
+ if (safetyGuard && safetyGuard.blocked) {
242
+ appendChiefAuditLog(key, {
243
+ mode: effCfg.permissionMode || 'advisor',
244
+ stage: 'safety_guard',
245
+ rule: safetyGuard.rule || 'auto_continue_blocked',
246
+ decision: 'blocked',
247
+ operation: '断线续跑边界检查',
248
+ target: sessionId,
249
+ reason: safetyGuard.reason,
250
+ outcome: 'blocked',
251
+ by: 'auto-continue',
252
+ })
253
+ return { allowed: false, skipped: 'guard-wall-blocked', logMessage: `安全护栏阻断自动续跑:${safetyGuard.reason}` }
254
+ }
255
+ const activeWalls = listGuardWalls(cwdForCheck)
256
+ 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)))) {
257
+ return { allowed: false, skipped: 'guard-wall-blocked', logMessage: '触发动态物理墙保护红线,已暂停自动续跑等待人工确认' }
258
+ }
259
+
203
260
  const hasAck = hasValidChiefRiskAck(ws)
204
261
  const mode = normalizePermissionMode(effCfg && effCfg.permissionMode, {
205
262
  requireAck: true,
206
263
  hasChiefRiskAck: hasAck,
207
264
  })
208
265
  if (mode === 'advisor') {
209
- return { allowed: false, skipped: 'advisor-readonly', logMessage: 'L0 顾问模式(只读):禁止自动向主对话续跑' }
266
+ return { allowed: false, skipped: 'advisor-readonly', logMessage: 'L0 顾问模式(只读):检测到断流仅作提示,不向主对话发送续跑请求' }
210
267
  }
211
268
  if (mode === 'assistant') {
212
- return { allowed: false, skipped: 'assistant-no-workflow', logMessage: 'L1 助手模式:仅维护参谋系统,跳过主对话断线自动续跑' }
269
+ mutateChiefState((s) => {
270
+ const w = ensureWorkspace(s, key)
271
+ const sug = normalizeSuggestion({
272
+ kind: 'advice',
273
+ fromAgent: '⚡ 断流检测提醒',
274
+ title: `主对话断流待手动续跑(${trigger})`,
275
+ reason: detail ? String(detail).slice(0, 160) : 'L1 助手模式不接管主对话工作流,点此一键下发续跑请求。',
276
+ target: 'lead',
277
+ targetLabel: '主对话 (@lead)',
278
+ mode: 'followup',
279
+ draftText: `[EXECUTION_REQUEST] 检测到上一轮中断(${trigger}),请核查进度后继续推进。`,
280
+ })
281
+ if (sug && !w.suggestions.some(x => x && x.status === 'pending' && x.title === sug.title)) {
282
+ w.suggestions.push(sug)
283
+ if (w.suggestions.length > SUGGESTIONS_CAP) w.suggestions = w.suggestions.slice(-SUGGESTIONS_CAP)
284
+ }
285
+ })
286
+ return { allowed: false, skipped: 'assistant-no-workflow', logMessage: 'L1 助手模式:已记入建议卡提醒断流,跳过主对话工作流续跑' }
213
287
  }
214
288
  if (mode === 'strategist') {
289
+ let ledgerId = ''
290
+ mutateChiefState((s) => {
291
+ const w = ensureWorkspace(s, key)
292
+ const entry = upsertTaskLedgerOnWs(w, {
293
+ kind: 'auto_continue',
294
+ status: 'awaiting_approval',
295
+ originalText: `[断线续跑 · ${trigger}] ${detail ? String(detail).slice(0, 160) : '异常中断恢复'}`,
296
+ forcedTarget: 'lead',
297
+ lastReceipt: '等待 L2 逐项授权唤醒主对话',
298
+ })
299
+ if (entry) ledgerId = entry.taskId || entry.id
300
+ })
215
301
  const apr = queueChiefApproval(key, {
216
302
  category: 'main_workflow',
217
303
  operationLabel: '断线自动续跑主对话',
218
304
  targetLabel: '主对话 (@lead)',
219
- reason: `检测到会话中断或未收口(${trigger}),L2 参谋模式需您允许后再发送续跑指令`,
220
- impact: '点击「允许本次操作」后将立即唤醒主对话继续推进当前任务',
305
+ reason: `检测到会话中断或未收口(${trigger}),已核验安全边界与物理墙,L2 参谋模式需您允许后唤醒续跑`,
306
+ impact: '点击「允许本次操作」后将发出 [EXECUTION_REQUEST] 信封唤醒主对话继续推进',
221
307
  preview: detail ? String(detail).slice(0, 220) : `触发原因:${trigger}`,
222
308
  dedupeKey: `autocont:${sessionId}:${trigger}:${Math.floor(Date.now() / 15_000)}`,
223
309
  kind: 'auto_continue',
224
- payload: { sessionId, trigger, detail: detail || '' },
310
+ taskId: ledgerId,
311
+ resumeTaskId: ledgerId,
312
+ payload: { sessionId, trigger, detail: detail || '', taskId: ledgerId },
225
313
  by: 'auto-continue',
226
314
  })
227
315
  appendChiefAuditLog(key, {
@@ -238,10 +326,23 @@ export function createRuntimeHooks(deps) {
238
326
  allowed: false,
239
327
  skipped: 'pending-approval',
240
328
  approvalId: apr && apr.id,
329
+ taskId: ledgerId,
241
330
  logMessage: `L2 参谋模式:已提交断线续跑逐项授权弹窗(${trigger})`,
242
331
  }
243
332
  }
244
- return { allowed: true }
333
+ let l3TaskId = ''
334
+ mutateChiefState((s) => {
335
+ const w = ensureWorkspace(s, key)
336
+ const entry = upsertTaskLedgerOnWs(w, {
337
+ kind: 'auto_continue',
338
+ status: 'running',
339
+ originalText: `[L3 断线自动续跑 · ${trigger}] ${detail ? String(detail).slice(0, 160) : '异常中断自动恢复'}`,
340
+ forcedTarget: 'lead',
341
+ lastReceipt: '已过边界与物理墙核验,准备下发 [EXECUTION_REQUEST]',
342
+ })
343
+ if (entry) l3TaskId = entry.taskId || entry.id
344
+ })
345
+ return { allowed: true, taskId: l3TaskId }
245
346
  } catch {
246
347
  return { allowed: false, skipped: 'permission-error' }
247
348
  }
@@ -257,6 +358,15 @@ export function createRuntimeHooks(deps) {
257
358
  pushLog(board, `🔄 断线续跑:${msg}`, 'chief', sid)
258
359
  saveBoard(board, file)
259
360
  })
361
+ if (String(msg || '').includes('断线续跑已触发')) {
362
+ recordWorkspaceAlertEvent(rootId, {
363
+ kind: 'auto_continue_rescue',
364
+ level: 'info',
365
+ title: '🔄 断流救活已触发续跑',
366
+ body: String(msg).slice(0, 180),
367
+ dedupeKey: `rescue:${rootId}:${Math.floor(Date.now() / 5_000)}`,
368
+ })
369
+ }
260
370
  } catch {}
261
371
  },
262
372
  })
@@ -329,7 +439,8 @@ export function createRuntimeHooks(deps) {
329
439
  linkedPeersCount: linked.linkedPeersCount,
330
440
  linkedPeersProgress: linked.linkedPeersProgress,
331
441
  takenOutArchives: archCtx.takenOutArchives,
332
- sessionArchiveBriefs: archCtx.sessionArchiveBriefs,
442
+ sessionHookedArchives: archCtx.sessionHookedArchives,
443
+ desktopUsedTokens: archCtx.desktopUsedTokens,
333
444
  smartCompactActive: archCtx.smartCompactActive,
334
445
  chiefPermissionMode: archCtx.chiefPermissionMode,
335
446
  })
@@ -408,17 +519,149 @@ export function createRuntimeHooks(deps) {
408
519
  } catch {}
409
520
  }), 'dsh-chief: deliver pending transfer')
410
521
 
522
+ function handleMidTurnSpinCheck(id, rootId) {
523
+ try {
524
+ const agents = runtime && runtime.get ? runtime.get('agents') : null
525
+ const liveAgent = agents && typeof agents.get === 'function' ? agents.get(id) : null
526
+ if (!liveAgent || liveAgent.status !== 'running') return
527
+
528
+ const st = loadChiefState()
529
+ const effCfg = resolveWorkspaceConfig(st, rootId)
530
+ if (effCfg.stopped || effCfg.paceMode === 'stopped') return
531
+
532
+ const strongIntervention = Boolean(effCfg.tacticalModes && effCfg.tacticalModes.intervention)
533
+ const shared = loadBoard(boardFile())
534
+ const board = boardForSession(boardFileFor(id))
535
+ const settings = { ...(board.settings || {}), ...(shared.settings || {}) }
536
+ const guardIdleEnabled = settings.guardIdle !== false
537
+ if (!strongIntervention && !guardIdleEnabled) return
538
+
539
+ const spin = detectMidTurnSpin(id, { strongIntervention })
540
+ if (!spin) return
541
+
542
+ const canSteer = typeof liveAgent.steer === 'function'
543
+ const logLine = guardLogText({ kind: 'mid-turn-spin', spin }, 0, 0)
544
+ const ident = resolveAgentIdentity(runtime, id, liveAgent)
545
+ const targetHandle = (ident && ident.isChild && ident.self) ? ident.self : 'lead'
546
+
547
+ if (spin.kind === 'exact-loop' && guardIdleEnabled) {
548
+ if (!canSteer) return
549
+ liveAgent.steer(buildMidTurnSpinNotice(spin, board))
550
+ markMidTurnSpinActed(id)
551
+ const bFile = boardFileFor(id)
552
+ withBoardLock(bFile, () => {
553
+ const b = loadBoard(bFile)
554
+ pushLog(b, logLine, 'guard', id)
555
+ saveBoard(b, bFile)
556
+ })
557
+ scheduleChiefTurnReview(makeChiefDeps(runtime), { agent: liveAgent, sessionId: id, abnormalTrigger: 'mid_turn_spin' })
558
+ return
559
+ }
560
+
561
+ if (!strongIntervention) return
562
+ const wsSnap = st.workspaces && st.workspaces[rootId] ? st.workspaces[rootId] : null
563
+ const permMode = normalizePermissionMode(effCfg.permissionMode, {
564
+ requireAck: true,
565
+ hasChiefRiskAck: hasValidChiefRiskAck(wsSnap),
566
+ })
567
+ const spinSummary = `${spin.name || 'tool'}${spin.preview ? ' (' + String(spin.preview).slice(0, 60) + ')' : ''}`
568
+
569
+ if (permMode === 'chief' && canSteer) {
570
+ liveAgent.steer(buildMidTurnSpinNotice(spin, board))
571
+ markMidTurnSpinActed(id)
572
+ mutateChiefState((s) => {
573
+ const ws = ensureWorkspace(s, rootId)
574
+ ws.chat.push({
575
+ id: nextId('chat'),
576
+ role: 'chief',
577
+ kind: 'receipt',
578
+ text: `- 【⚡ 强介入 · 运行中空转急刹】已当场插话制止 \`@${targetHandle}\` 原地空转/连续报错(${spin.kind} ×${spin.count}:${clamp(spinSummary, 140)})。`,
579
+ actions: [`⚡ 急刹 ×${spin.count}`],
580
+ at: Date.now(),
581
+ })
582
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
583
+ })
584
+ appendChiefAuditLog(rootId, {
585
+ mode: permMode,
586
+ stage: 'executor',
587
+ rule: 'mid_turn_spin_brake',
588
+ decision: 'executed',
589
+ operation: '强介入运行中空转急刹',
590
+ target: id,
591
+ reason: `${spin.kind} ×${spin.count}: ${clamp(spinSummary, 120)}`,
592
+ outcome: 'ok',
593
+ by: 'chief',
594
+ })
595
+ } else if (permMode === 'strategist') {
596
+ markMidTurnSpinActed(id)
597
+ const noticeObj = buildMidTurnSpinNotice(spin, board)
598
+ const noticeTxt = (noticeObj.content && noticeObj.content[0] && noticeObj.content[0].text) || ''
599
+ queueChiefApproval(rootId, {
600
+ category: 'main_workflow',
601
+ operationLabel: '强介入 · 运行中空转急刹插话',
602
+ targetLabel: targetHandle === 'lead' ? '主对话 (@lead)' : `@${targetHandle}`,
603
+ reason: `检测到运行中连续空转/报错(${spin.kind} ×${spin.count}),L2 参谋模式需您授权后插话急刹`,
604
+ impact: '允许后立即向运行中的目标插入纠偏通知',
605
+ preview: clamp(spinSummary, 200),
606
+ dedupeKey: `midspin:${rootId}:${spin.kind}:${spin.name}`,
607
+ kind: 'relay',
608
+ capabilityScope: buildCapabilityScope({ kind: 'relay', tool: 'relay', target: targetHandle }),
609
+ payload: {
610
+ fromSession: rootId,
611
+ fromLabel: 'DSH 参谋 (运行中空转急刹)',
612
+ target: targetHandle,
613
+ subject: '运行中空转急刹',
614
+ text: noticeTxt,
615
+ mode: 'steer',
616
+ },
617
+ by: 'chief',
618
+ })
619
+ } else {
620
+ markMidTurnSpinActed(id)
621
+ mutateChiefState((s) => {
622
+ const ws = ensureWorkspace(s, rootId)
623
+ ws.chat.push({
624
+ id: nextId('chat'),
625
+ role: 'chief',
626
+ kind: 'receipt',
627
+ text: `- 【👁 运行中空转告警 (${permMode === 'assistant' ? 'L1' : 'L0'})】检测到 \`@${targetHandle}\` 正在连续空转/报错(${spin.kind} ×${spin.count}:${clamp(spinSummary, 140)}),当前权限不自动插话。`,
628
+ actions: ['⚠️ 运行空转告警'],
629
+ at: Date.now(),
630
+ })
631
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
632
+ })
633
+ }
634
+ const bFile = boardFileFor(id)
635
+ withBoardLock(bFile, () => {
636
+ const b = loadBoard(bFile)
637
+ pushLog(b, logLine, 'guard', id)
638
+ saveBoard(b, bFile)
639
+ })
640
+ scheduleChiefTurnReview(makeChiefDeps(runtime), { agent: liveAgent, sessionId: id, abnormalTrigger: 'mid_turn_spin' })
641
+ } catch {}
642
+ }
643
+
411
644
  // 2c) Incremental record of what each turn actually did + Auto-Continue detection
412
645
  // on interruptions / transient failures / empty outputs (unless Chief is stopped).
413
646
  ctx.effect(() => ctx.on('session/event', (session, event) => {
414
647
  try {
415
648
  if (!event || !session || !session.id) return
416
649
  const id = String(session.id)
417
- if (event.type === 'tool/call' && event.data) {
650
+ const rootIdForAct = resolveRootSessionId(id) || id
651
+ if (event.type === 'turn/start' || event.type === 'message/user' || event.type === 'tool/call' || event.type === 'turn/end') {
652
+ touchWorkspaceActivity(rootIdForAct)
653
+ }
654
+ if (event.type === 'turn/start') {
655
+ clearMidTurnSpin(id)
656
+ } else if (event.type === 'tool/call' && event.data) {
418
657
  const turn = event.data.turn
419
658
  noteToolCall(id, turn)
420
659
  if (isPlanWrite(event.data.name, event.data.arguments)) notePlanWrite(id, turn)
421
660
  noteCallTrail(id, event.data.name, event.data.arguments)
661
+ handleMidTurnSpinCheck(id, rootIdForAct)
662
+ } else if (event.type === 'tool/result' && event.data) {
663
+ noteCallResult(id, event.data)
664
+ handleMidTurnSpinCheck(id, rootIdForAct)
422
665
  }
423
666
  autoContinue.onSessionEvent(session, event)
424
667
 
@@ -427,17 +670,28 @@ export function createRuntimeHooks(deps) {
427
670
  const reason = String(rawReason && typeof rawReason === 'object' ? (rawReason.kind || '') : (rawReason || '')).toLowerCase()
428
671
  const nestedReason = String(rawReason && typeof rawReason === 'object' && rawReason.reason && typeof rawReason.reason === 'object' ? (rawReason.reason.kind || '') : '').toLowerCase()
429
672
  const isStoppedByUserOrPolicy = reason === 'aborted' || reason === 'blocked' || nestedReason === 'aborted' || nestedReason === 'blocked'
673
+ const abnormalTrig = (reason === 'error' || nestedReason === 'error')
674
+ ? 'turn_error'
675
+ : ((reason === 'interrupted' || nestedReason === 'interrupted' || reason === 'max-tokens' || reason === 'no-visible-output') ? 'stream_interrupted' : '')
430
676
  const turnNum = Number(event.data && event.data.turn)
431
677
  const steerKey = `${id}:${turnNum}`
432
678
  const steeredAt = deps.hostState.autoSteeredTurns.get(steerKey) || 0
433
679
  if (steeredAt) deps.hostState.autoSteeredTurns.delete(steerKey)
434
- if (!isStoppedByUserOrPolicy && !(steeredAt && Date.now() - steeredAt < 30_000)) {
435
- const rootId = resolveRootSessionId(id) || id
436
- if (!isRootStopped(rootId, id)) {
680
+ const stNow = loadChiefState()
681
+ const rootId = resolveRootSessionId(id) || id
682
+ const cfgNow = resolveWorkspaceConfig(stNow, rootId)
683
+ const strongIntervention = Boolean(cfgNow.tacticalModes && cfgNow.tacticalModes.intervention)
684
+ if (!isStoppedByUserOrPolicy && (strongIntervention || !(steeredAt && Date.now() - steeredAt < 30_000))) {
685
+ if (!isRootStopped(rootId, id) || abnormalTrig) {
437
686
  const agents = runtime && runtime.get ? runtime.get('agents') : null
438
687
  const liveAgent = agents && typeof agents.get === 'function' ? agents.get(id) : null
439
688
  if (liveAgent) {
440
- scheduleChiefTurnReview(makeChiefDeps(runtime), { agent: liveAgent, sessionId: id, turn: event.data && event.data.turn })
689
+ scheduleChiefTurnReview(makeChiefDeps(runtime), {
690
+ agent: liveAgent,
691
+ sessionId: id,
692
+ turn: event.data && event.data.turn,
693
+ ...(abnormalTrig ? { abnormalTrigger: abnormalTrig } : {}),
694
+ })
441
695
  }
442
696
  }
443
697
  }
@@ -514,7 +768,12 @@ export function createRuntimeHooks(deps) {
514
768
  }
515
769
  task.updatedAt = nowMs()
516
770
  settledCount += 1
517
- pushLog(board, '✅ 子代理 ' + identity.self + ' 完成任务 #' + task.id + '「' + task.title.slice(0, 36) + '」', identity.self, id)
771
+ const returnStepId = task.targetPlanStepId || task.planStepId
772
+ const returnStepIdx = returnStepId && Array.isArray(board.plan)
773
+ ? board.plan.findIndex(s => s && s.id === returnStepId)
774
+ : -1
775
+ const returnTag = returnStepIdx >= 0 ? '(已回指步骤 ' + (returnStepIdx + 1) + ')' : ''
776
+ pushLog(board, '✅ 子代理 ' + identity.self + ' 完成任务 #' + task.id + '「' + task.title.slice(0, 36) + '」' + returnTag, identity.self, id)
518
777
  }
519
778
  }
520
779
  if (settledCount > 0) {
@@ -529,7 +788,7 @@ export function createRuntimeHooks(deps) {
529
788
  }
530
789
 
531
790
  const rootId = resolveRootSessionId(id, agent) || id
532
- if (isRootStopped(rootId, id)) {
791
+ if (isExplicitStopped(rootId, id)) {
533
792
  saveBoard(board, file)
534
793
  return
535
794
  }
@@ -538,7 +797,18 @@ export function createRuntimeHooks(deps) {
538
797
  // same rule so one switch turns the guard off everywhere.
539
798
  const shared = loadBoard(boardFile())
540
799
  const settings = { ...(board.settings || {}), ...(shared.settings || {}) }
541
- const verdict = shouldGuard({ board, session: agent && agent.session, sessionId: id, turn, settings })
800
+ const effCfg = resolveWorkspaceConfig(loadChiefState(), rootId)
801
+ const strongIntervention = Boolean(effCfg.tacticalModes && effCfg.tacticalModes.intervention)
802
+ const maxInterventionTurns = Number(effCfg.tacticalModes && effCfg.tacticalModes.maxInterventionTurns) || 0
803
+ const verdict = shouldGuard({
804
+ board,
805
+ session: agent && agent.session,
806
+ sessionId: id,
807
+ turn,
808
+ settings,
809
+ strongIntervention,
810
+ maxInterventionTurns,
811
+ })
542
812
  if (!verdict) {
543
813
  saveBoard(board, file)
544
814
  scheduleChiefTurnReview(makeChiefDeps(runtime), { agent, sessionId: id, turn })
@@ -565,7 +835,8 @@ export function createRuntimeHooks(deps) {
565
835
  // Clear the trail only once the steer landed: a loop that survived a
566
836
  // failed steer deserves the next nudge, not a silent reset.
567
837
  if (verdict.kind === 'loop') clearCallTrail(id)
568
- pushLog(board, guardLogText(verdict, turn, remainingInterventions(id, settings)), 'guard', id)
838
+ const remAfter = remainingInterventions(id, settings, { strongIntervention, maxInterventionTurns })
839
+ pushLog(board, guardLogText(verdict, turn, remAfter), 'guard', id)
569
840
 
570
841
  // Auto-handoff: when the guard has spent its last intervention and the
571
842
  // session still has open work, the turn is not idle — it is stuck in a
@@ -573,7 +844,7 @@ export function createRuntimeHooks(deps) {
573
844
  // handover packet right now so the next Session (or a manual reopen)
574
845
  // inherits it instead of a blank board. The steer already fired above
575
846
  // tells the model to wrap up; this packet is what the next one reads.
576
- if (remainingInterventions(id, settings) === 0) {
847
+ if (remAfter === 0) {
577
848
  try {
578
849
  const packet = resolveEffectiveHandoff(runtime, id, board).text
579
850
  const pendingFile_ = pendingFile()
@@ -649,6 +920,13 @@ export function createRuntimeHooks(deps) {
649
920
  outcome: 'blocked',
650
921
  by: actorName,
651
922
  })
923
+ recordWorkspaceAlertEvent(rootId, {
924
+ kind: 'guard_wall_blocked',
925
+ level: 'danger',
926
+ title: '🧱 物理驻墙已拦截越界调用',
927
+ body: `@${actorName} 调用 ${exec.name}:${String(verdict.reason || '').slice(0, 140)}`,
928
+ dedupeKey: `wall:${rootId}:${exec.name}:${verdict.wallId || verdict.rule || ''}`,
929
+ })
652
930
  try {
653
931
  const bFile = rootId !== 'global' ? boardFileFor(rootId) : boardFile()
654
932
  withBoardLock(bFile, () => {
@@ -672,9 +950,19 @@ export function createRuntimeHooks(deps) {
672
950
  })
673
951
  })
674
952
  }
953
+ if (effCfg && (effCfg.runMode === 'patrol' || effCfg.runMode === 'managed') && !effCfg.stopped) {
954
+ scheduleChiefTurnReview(makeChiefDeps(runtime), {
955
+ agent: caller,
956
+ sessionId: sid || rootId,
957
+ abnormalTrigger: 'guard_wall_blocked',
958
+ })
959
+ }
960
+ const escalationCue = verdict.wallId
961
+ ? `(严禁尝试命令或路径变形绕过物理墙 [${verdict.wallId}];仅当你确认无任何合法替代方案可继续任务时,可调用 chief_board({ action: "chief.request", subject: "撞墙阻断上报", text: "说明被拦截墙(${verdict.wallId})、为何无法绕过及当前卡点" }) 上报参谋长评估)`
962
+ : ''
675
963
  return {
676
964
  kind: 'deny',
677
- reason: `[DSH 安全卫兵事前物理拦截] ${verdict.reason}`,
965
+ reason: `[DSH 安全卫兵事前物理拦截] ${verdict.reason}${escalationCue}`,
678
966
  info: { stage: verdict.stage, rule: verdict.rule, wallId: verdict.wallId || '' },
679
967
  }
680
968
  } else if (verdict && verdict.decision === 'ask') {
@@ -727,6 +1015,56 @@ export function createRuntimeHooks(deps) {
727
1015
  )
728
1016
  if (hasNeedReconcile) mutateChiefState(() => {})
729
1017
  } catch {}
1018
+
1019
+ // Idle watchdog for Strong Intervention: catch already-stalled lead sessions cleanly without extra turns
1020
+ const lastWatchdogByRoot = new Map()
1021
+ const watchdogTimer = setInterval(() => {
1022
+ try {
1023
+ const agents = runtime && runtime.get ? runtime.get('agents') : null
1024
+ const allAgents = agents && typeof agents.list === 'function' ? (agents.list() || []) : []
1025
+ if (!allAgents.length) return
1026
+ const state = loadChiefState()
1027
+ const now = Date.now()
1028
+ for (const ag of allAgents) {
1029
+ const agId = String((ag && ag.id) || '').trim()
1030
+ if (!agId) continue
1031
+ const rootId = resolveRootSessionId(agId, ag) || agId
1032
+ if (rootId !== agId) continue
1033
+ const effCfg = resolveWorkspaceConfig(state, rootId)
1034
+ if (effCfg.stopped || effCfg.paceMode === 'stopped') continue
1035
+ if (!(effCfg.tacticalModes && effCfg.tacticalModes.intervention)) continue
1036
+ if (ag.status === 'running') continue
1037
+
1038
+ const hasRunningChild = allAgents.some(c => {
1039
+ const cId = String((c && c.id) || '').trim()
1040
+ if (!cId || cId === rootId) return false
1041
+ if ((resolveRootSessionId(cId, c) || cId) !== rootId) return false
1042
+ if (/^mnemon-(?:review|run)/i.test(String((c && c.name) || cId))) return false
1043
+ return c && c.status === 'running'
1044
+ })
1045
+ if (hasRunningChild) continue
1046
+
1047
+ const ws = state.workspaces && state.workspaces[rootId] ? state.workspaces[rootId] : null
1048
+ const rg = (ws && ws.runtimeGuard) || {}
1049
+ if (rg.circuitBroken || rg.hazardAlert) continue
1050
+ const hasPendingApr = Array.isArray(ws && ws.pendingApprovals) && ws.pendingApprovals.some(a => a && a.status === 'pending')
1051
+ if (hasPendingApr || (ws && ws.pendingElevation)) continue
1052
+ const hasPendingGoalSug = Array.isArray(ws && ws.suggestions) && ws.suggestions.some(s => s && s.status === 'pending' && s.kind === 'goal_approval')
1053
+ if (hasPendingGoalSug) continue
1054
+
1055
+ const refAt = Math.max(Number(rg.lastActivityAt) || 0, Number(lastWatchdogByRoot.get(rootId)) || 0)
1056
+ if (now - refAt < 22_000) continue
1057
+ lastWatchdogByRoot.set(rootId, now)
1058
+ scheduleChiefTurnReview(makeChiefDeps(runtime), {
1059
+ agent: ag,
1060
+ sessionId: rootId,
1061
+ abnormalTrigger: 'idle_watchdog',
1062
+ })
1063
+ }
1064
+ } catch {}
1065
+ }, 25_000)
1066
+ watchdogTimer.unref?.()
1067
+ ctx.effect(() => () => clearInterval(watchdogTimer), 'dsh-chief: strong intervention watchdog cleanup')
730
1068
  }
731
1069
 
732
1070
  return {
@@ -24,7 +24,8 @@ export const HARD_GUARD_RULE_IDS = Object.freeze([
24
24
  const DESTRUCTIVE_COMMAND_PATTERNS = [
25
25
  /\brm\s+-[a-z]*(?:r[a-z]*f|f[a-z]*r)[a-z]*\s+(?:\/(?:etc|usr|bin|sbin|var|lib|boot|dev|proc|sys|root|home|\*)?(?=$|[\s/])|~|\*|\.\.)/i,
26
26
  /\bgit\s+(?:reset\s+--hard|clean\s+-[a-z]*f[a-z]*d|push\s+(?:--force|-f)\b)/i,
27
- /\b(?:format|diskpart|cipher\s+\/w|bcdedit)\b/i,
27
+ /\b(?:diskpart|cipher\s+\/w|bcdedit)\b/i,
28
+ /(?:^|[;&|]\s*|(?:cmd(?:\.exe)?\s+\/c|powershell(?:\.exe)?\s+-[a-z]*c\w*|pwsh(?:\.exe)?\s+-[a-z]*c\w*)\s+["']?)\bformat(?:\.com)?\s+(?:[a-z]:|\/(?:fs|q|v|x|p|y)\b)/i,
28
29
  /\bdel\s+\/[fqs][^\n]*[a-z]:\\/i,
29
30
  /\bRemove-Item\b[^\n]*-Recurse[^\n]*-Force[^\n]*(?:[a-z]:\\|\*)/i,
30
31
  /\b(?:shutdown(?:\.exe)?|restart-computer|stop-computer|mkfs|dd\s+if=.*of=\/dev\/)\b/i,