dsh-chief 1.2.1 → 1.4.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.
@@ -0,0 +1,735 @@
1
+ /**
2
+ * runtime-hooks.js
3
+ *
4
+ * Cordis plugin lifecycle initialization, board migration, idle guard, auto-continue, routes, and tool registration.
5
+ */
6
+
7
+ import fs from 'node:fs'
8
+ import path from 'node:path'
9
+ import { renderDigest } from './digest.js'
10
+ import { appendMemory, captureTurn } from './memory.js'
11
+ import {
12
+ buildNotice,
13
+ clearCallTrail,
14
+ isPlanWrite,
15
+ noteCallTrail,
16
+ noteIntervention,
17
+ notePlanWrite,
18
+ noteToolCall,
19
+ remainingInterventions,
20
+ shouldGuard,
21
+ } from './idle-guard.js'
22
+ import {
23
+ loadChiefState,
24
+ mutateChiefState,
25
+ resolveWorkspaceConfig,
26
+ invalidateChiefModelCatalog,
27
+ buildMessageEnvelope,
28
+ consumePreStepDelta,
29
+ scheduleChiefTurnReview,
30
+ hasValidChiefRiskAck,
31
+ queueChiefApproval,
32
+ appendChiefAuditLog,
33
+ } from './chief.js'
34
+ import { createAutoContinueEngine } from './auto-continue.js'
35
+ import { bootstrapArchivesFromSharedBoard } from './archives.js'
36
+ import { normalizePermissionMode, evaluatePreExecuteDefense } from './chief-executor.js'
37
+ import {
38
+ newId,
39
+ nowMs,
40
+ emptyBoard,
41
+ CAP_TASK_EVIDENCE,
42
+ reconcileTaskDependencies,
43
+ normalizeNote,
44
+ normalizeBoard,
45
+ pushLog,
46
+ guardLogText,
47
+ } from './board-schema.js'
48
+
49
+ export function createRuntimeHooks(deps) {
50
+
51
+ const boardFile = (...args) => deps.boardFile(...args)
52
+ const boardFileFor = (...args) => deps.boardFileFor(...args)
53
+ const boardForSession = (...args) => deps.boardForSession(...args)
54
+ const boardTool = (...args) => deps.boardTool(...args)
55
+ const boundariesTool = (...args) => deps.boundariesTool(...args)
56
+ const clearPending = (...args) => deps.clearPending(...args)
57
+ const clearPendingDeploy = (...args) => deps.clearPendingDeploy(...args)
58
+ const collectDigestArchiveContext = (...args) => deps.collectDigestArchiveContext(...args)
59
+ const deployStateToTargetChief = (...args) => deps.deployStateToTargetChief(...args)
60
+ const getSessionCwd = (...args) => deps.getSessionCwd(...args)
61
+ const getSubagentRoster = (...args) => deps.getSubagentRoster(...args)
62
+ const handoffTool = (...args) => deps.handoffTool(...args)
63
+ const injectInto = (...args) => deps.injectInto(...args)
64
+ const linkedPeersForSession = (...args) => deps.linkedPeersForSession(...args)
65
+ const loadBoard = (...args) => deps.loadBoard(...args)
66
+ const makeChiefDeps = (...args) => deps.makeChiefDeps(...args)
67
+ const memoryTool = (...args) => deps.memoryTool(...args)
68
+ const pendingFile = (...args) => deps.pendingFile(...args)
69
+ const probeSubagentSupport = (...args) => deps.probeSubagentSupport(...args)
70
+ const readPending = (...args) => deps.readPending(...args)
71
+ const readPendingDeploy = (...args) => deps.readPendingDeploy(...args)
72
+ const refreshSubagentTree = (...args) => deps.refreshSubagentTree(...args)
73
+ const resolveAgentIdentity = (...args) => deps.resolveAgentIdentity(...args)
74
+ const resolveEffectiveHandoff = (...args) => deps.resolveEffectiveHandoff(...args)
75
+ const resolveRootSessionId = (...args) => deps.resolveRootSessionId(...args)
76
+ const routeTable = (...args) => deps.routeTable(...args)
77
+ const saveBoard = (...args) => deps.saveBoard(...args)
78
+ const sessionBoardFile = (...args) => deps.sessionBoardFile(...args)
79
+ const syncObjective = (...args) => deps.syncObjective(...args)
80
+ const syncPlanFromTodos = (...args) => deps.syncPlanFromTodos(...args)
81
+ const syncSubagentToolCall = (...args) => deps.syncSubagentToolCall(...args)
82
+ const withBoardLock = (...args) => deps.withBoardLock(...args)
83
+
84
+ /* ------------------------------------------------------------------------ apply */
85
+
86
+ function apply(ctx) {
87
+ const runtime = {
88
+ get(name) {
89
+ try {
90
+ return typeof ctx.get === 'function' ? ctx.get(name) : undefined
91
+ } catch {
92
+ return undefined
93
+ }
94
+ },
95
+ }
96
+ deps.hostState.activeRuntime = runtime
97
+
98
+ // 1) Not inflated, not reminded: every prompt assembly carries a small digest,
99
+ // so a compacted transcript does not take the objective and the open steps
100
+ // away from the next turn.
101
+ // Migrate a pre-split shared board into per-session boards ONCE: the first
102
+ // session that claims it copies it, so anchors are not lost and no session
103
+ // silently inherits another's tasks.
104
+ ;(function migrateSharedBoard() {
105
+ try {
106
+ const sharedFile = boardFile()
107
+ const dir = path.join(path.dirname(sharedFile), 'boards')
108
+ const flag = path.join(path.dirname(sharedFile), '.split-done')
109
+ if (fs.existsSync(flag)) return
110
+ let stat
111
+ try { stat = fs.statSync(sharedFile) } catch { return }
112
+ if (!stat || !stat.isFile()) return
113
+ const board = normalizeBoard(JSON.parse(fs.readFileSync(sharedFile, 'utf8')))
114
+ const touched = Object.keys(board.sessions || {})
115
+ const targets = new Set(touched)
116
+ // Every note/task that carries a session id also seeds that board; a
117
+ // session with only a heartbeat still gets the shared anchors.
118
+ for (const note of board.notes || []) if (note.session) targets.add(String(note.session))
119
+ for (const task of board.tasks || []) if (task.session) targets.add(String(task.session))
120
+ // No owner at all → keep it as the shared/anchor board only.
121
+ if (!targets.size) return
122
+ const anchors = (board.notes || []).filter(note => (note.tags || []).includes('anchor'))
123
+ fs.mkdirSync(dir, { recursive: true })
124
+ for (const sid of targets) {
125
+ const dst = sessionBoardFile(sid)
126
+ if (fs.existsSync(dst)) continue
127
+ // Seed only what is machine-wide: settings, the heartbeat table, the log
128
+ // tail and the shared anchors. NOT the objective, NOT the plan, NOT the
129
+ // bounds — those stay on the shared board and are inherited on every
130
+ // read (boardForSession), so freezing a copy into each session would
131
+ // recreate exactly the cross-session pollution the split removed.
132
+ const seed = emptyBoard()
133
+ seed.settings = board.settings || seed.settings
134
+ seed.notes = anchors
135
+ seed.sessions = board.sessions || {}
136
+ seed.log = board.log || []
137
+ fs.writeFileSync(dst, JSON.stringify(seed, null, 2), 'utf8')
138
+ }
139
+ fs.writeFileSync(flag, JSON.stringify({ at: nowMs(), seeded: [...targets] }, null, 2), 'utf8')
140
+ // Shrink the shared board to the machine-wide facts only: the objective,
141
+ // the plan, the bounds and the anchors are what a new session inherits,
142
+ // while tasks/notes/memory stay per-session.
143
+ withBoardLock(sharedFile, () => {
144
+ const slim = emptyBoard()
145
+ slim.settings = board.settings || slim.settings
146
+ slim.bounds = board.bounds || slim.bounds
147
+ slim.notes = anchors
148
+ slim.sessions = board.sessions || {}
149
+ slim.log = board.log || []
150
+ slim.objective = board.objective
151
+ slim.objectiveBy = board.objectiveBy
152
+ slim.objectiveAt = board.objectiveAt
153
+ slim.plan = board.plan
154
+ saveBoard(slim, sharedFile)
155
+ })
156
+ } catch {}
157
+ })()
158
+
159
+ // Precipitate legacy shared-board engineering notes into `archives.json` ONCE
160
+ // (after creating `board.pre-archive-backup.json`), sealing them as cold lazy-loaded dossiers.
161
+ bootstrapArchivesFromSharedBoard({
162
+ sharedFile: boardFile(),
163
+ loadBoard,
164
+ saveBoard,
165
+ pushLog,
166
+ })
167
+
168
+ const isRootStopped = (rootKey, sid) => {
169
+ try {
170
+ const st = loadChiefState()
171
+ const rk = resolveRootSessionId(rootKey || sid) || rootKey || sid
172
+ const cfg = resolveWorkspaceConfig(st, rk)
173
+ return Boolean(cfg.stopped || cfg.paceMode === 'stopped')
174
+ } catch {
175
+ return false
176
+ }
177
+ }
178
+
179
+ const autoContinue = createAutoContinueEngine({
180
+ createMessage: (text, sourceKind) => buildMessageEnvelope(text, sourceKind),
181
+ getAgent: async (sid) => {
182
+ try {
183
+ const agents = runtime && runtime.get ? runtime.get('agents') : null
184
+ const direct = agents && typeof agents.get === 'function' ? agents.get(sid) : null
185
+ if (direct) return direct
186
+ const ctrl = runtime && runtime.get ? runtime.get('sessionController') : null
187
+ if (ctrl && typeof ctrl.resolveAgent === 'function') {
188
+ const resolved = await ctrl.resolveAgent(sid)
189
+ if (resolved && resolved.agent) return resolved.agent
190
+ }
191
+ return null
192
+ } catch {
193
+ return null
194
+ }
195
+ },
196
+ isChiefStopped: (rootId, sid) => isRootStopped(rootId, sid),
197
+ canAutoContinue: ({ sessionId, rootId, trigger, detail }) => {
198
+ try {
199
+ const key = rootId || sessionId || 'global'
200
+ const state = loadChiefState()
201
+ const ws = state && state.workspaces && state.workspaces[key] ? state.workspaces[key] : null
202
+ const effCfg = resolveWorkspaceConfig(state, key)
203
+ const hasAck = hasValidChiefRiskAck(ws)
204
+ const mode = normalizePermissionMode(effCfg && effCfg.permissionMode, {
205
+ requireAck: true,
206
+ hasChiefRiskAck: hasAck,
207
+ })
208
+ if (mode === 'advisor') {
209
+ return { allowed: false, skipped: 'advisor-readonly', logMessage: 'L0 顾问模式(只读):禁止自动向主对话续跑' }
210
+ }
211
+ if (mode === 'assistant') {
212
+ return { allowed: false, skipped: 'assistant-no-workflow', logMessage: 'L1 助手模式:仅维护参谋系统,跳过主对话断线自动续跑' }
213
+ }
214
+ if (mode === 'strategist') {
215
+ const apr = queueChiefApproval(key, {
216
+ category: 'main_workflow',
217
+ operationLabel: '断线自动续跑主对话',
218
+ targetLabel: '主对话 (@lead)',
219
+ reason: `检测到会话中断或未收口(${trigger}),L2 参谋模式需您允许后再发送续跑指令`,
220
+ impact: '点击「允许本次操作」后将立即唤醒主对话继续推进当前任务',
221
+ preview: detail ? String(detail).slice(0, 220) : `触发原因:${trigger}`,
222
+ dedupeKey: `autocont:${sessionId}:${trigger}:${Math.floor(Date.now() / 15_000)}`,
223
+ kind: 'auto_continue',
224
+ payload: { sessionId, trigger, detail: detail || '' },
225
+ by: 'auto-continue',
226
+ })
227
+ appendChiefAuditLog(key, {
228
+ mode,
229
+ stage: 'permission_gate',
230
+ decision: 'pending_approval',
231
+ operation: '断线自动续跑主对话',
232
+ target: sessionId,
233
+ reason: `触发源:${trigger}`,
234
+ outcome: 'pending',
235
+ by: 'auto-continue',
236
+ })
237
+ return {
238
+ allowed: false,
239
+ skipped: 'pending-approval',
240
+ approvalId: apr && apr.id,
241
+ logMessage: `L2 参谋模式:已提交断线续跑逐项授权弹窗(${trigger})`,
242
+ }
243
+ }
244
+ return { allowed: true }
245
+ } catch {
246
+ return { allowed: false, skipped: 'permission-error' }
247
+ }
248
+ },
249
+ resolveRootSessionId: (sid) => resolveRootSessionId(sid) || sid,
250
+ onLog: (sid, msg) => {
251
+ try {
252
+ const rootId = resolveRootSessionId(sid) || sid
253
+ if (!rootId) return
254
+ const file = boardFileFor(rootId)
255
+ withBoardLock(file, () => {
256
+ const board = loadBoard(file)
257
+ pushLog(board, `🔄 断线续跑:${msg}`, 'chief', sid)
258
+ saveBoard(board, file)
259
+ })
260
+ } catch {}
261
+ },
262
+ })
263
+ deps.hostState.activeAutoContinue = autoContinue
264
+ ctx.effect(() => () => {
265
+ if (deps.hostState.activeAutoContinue === autoContinue) deps.hostState.activeAutoContinue = null
266
+ autoContinue.dispose()
267
+ }, 'dsh-chief: auto-continue cleanup')
268
+
269
+ ctx.inject(['llm'], llmCtx => {
270
+ const ownLlm = (llmCtx && llmCtx.llm) || (llmCtx && llmCtx.get ? llmCtx.get('llm') : null)
271
+ if (ownLlm) deps.hostState.activeLlm = ownLlm
272
+ llmCtx.effect(() => () => {
273
+ if (deps.hostState.activeLlm === ownLlm) deps.hostState.activeLlm = null
274
+ }, 'dsh-chief: chief llm service')
275
+ })
276
+ ctx.on?.('llm/adapters-updated', () => invalidateChiefModelCatalog())
277
+ ctx.on?.('settings/document-updated', () => invalidateChiefModelCatalog())
278
+
279
+ ctx.effect(() => ctx.on('agent/pre-step', async ({ agent, signal }, next) => {
280
+ const decision = await next()
281
+ try {
282
+ if (!decision || decision.kind === 'reject' || signal?.aborted || !Array.isArray(decision.messages)) {
283
+ return decision
284
+ }
285
+ const deltaMsg = await consumePreStepDelta(makeChiefDeps(runtime), agent)
286
+ if (!deltaMsg) return decision
287
+ return { ...decision, messages: [deltaMsg, ...decision.messages] }
288
+ } catch {
289
+ return decision
290
+ }
291
+ }), 'dsh-chief: chief pre-step delta')
292
+
293
+ ctx.inject(['systemPrompt'], spCtx => {
294
+ const systemPrompt = spCtx.get ? spCtx.get('systemPrompt') : undefined
295
+ if (!systemPrompt || typeof systemPrompt.section !== 'function') return
296
+ // Always on, and always FIRST. A model that only meets the chief after
297
+ // ten thousand tokens of other context writes for a while and forgets it,
298
+ // which is exactly the failure the operator kept hitting. The section is
299
+ // registered unconditionally so the board is in front of the model from the
300
+ // first turn; -10000 sorts ahead of every built-in section (they use small
301
+ // positive orders, and equal orders fall back to name order), and the host
302
+ // only requires the order to be a finite number.
303
+ const fallbackAgentId = spCtx && spCtx.agent && spCtx.agent.id ? String(spCtx.agent.id)
304
+ : (spCtx && spCtx.get && spCtx.get('agent') && spCtx.get('agent').id ? String(spCtx.get('agent').id) : '')
305
+ spCtx.effect(() => systemPrompt.section({
306
+ name: 'dsh-chief',
307
+ order: -10000,
308
+ text: (promptCtx) => {
309
+ const liveAgent = (promptCtx && promptCtx.agent) || (spCtx && spCtx.agent) || null
310
+ const curId = liveAgent && liveAgent.id ? String(liveAgent.id) : fallbackAgentId
311
+ const rootId = resolveRootSessionId(curId, liveAgent) || curId
312
+ let teamTasks
313
+ try {
314
+ const svc = runtime.get('agentTeams')
315
+ if (svc && typeof svc.listTasks === 'function' && liveAgent) {
316
+ teamTasks = svc.listTasks(liveAgent)
317
+ }
318
+ } catch {}
319
+ const board = boardForSession(boardFileFor(rootId))
320
+ const agentIdentity = resolveAgentIdentity(runtime, curId, liveAgent)
321
+ const subagents = getSubagentRoster(runtime, rootId, board)
322
+ const linked = linkedPeersForSession(runtime, rootId || 'global')
323
+ const archCtx = collectDigestArchiveContext(runtime, rootId, board.activeCabinetId)
324
+ if (rootId) refreshSubagentTree(runtime, rootId, board).catch(() => {})
325
+ return renderDigest(board, {
326
+ teamTasks,
327
+ agentIdentity,
328
+ subagents,
329
+ linkedPeersCount: linked.linkedPeersCount,
330
+ linkedPeersProgress: linked.linkedPeersProgress,
331
+ takenOutArchives: archCtx.takenOutArchives,
332
+ sessionArchiveBriefs: archCtx.sessionArchiveBriefs,
333
+ smartCompactActive: archCtx.smartCompactActive,
334
+ chiefPermissionMode: archCtx.chiefPermissionMode,
335
+ })
336
+ },
337
+ }), 'dsh-chief: prompt digest')
338
+ })
339
+
340
+ // 2) Whatever plan or subagent delegation the model executed is mirrored into the board.
341
+ ctx.effect(() => ctx.on('tools/result', (exec, result) => {
342
+ try {
343
+ if (!exec || !result || result.isError) return
344
+ const caller = exec.agent || null
345
+ const sessionId = caller && caller.id ? String(caller.id) : ''
346
+ const rootId = resolveRootSessionId(sessionId, caller) || sessionId
347
+ if (exec.name === 'todo_write') syncPlanFromTodos(exec.arguments, rootId)
348
+ else if (exec.name === 'create_goal' || exec.name === 'update_goal') syncObjective(exec.name, exec.arguments, rootId)
349
+ else if (exec.name === 'subagent' || exec.name === 'subagent_fork' || exec.name === 'send_message' || exec.name === 'interrupt_agent') {
350
+ syncSubagentToolCall(runtime, exec, result)
351
+ }
352
+ } catch {}
353
+ }), 'dsh-chief: plan & subagent mirror')
354
+
355
+ // 2b) A transferred packet + staged Chief deployment waits for one new Session.
356
+ ctx.effect(() => ctx.on('agent/created', async payload => {
357
+ try {
358
+ const agent = payload && payload.agent
359
+ if (!agent || !agent.id) return
360
+ const id = String(agent.id)
361
+
362
+ const pendingDeploy = readPendingDeploy()
363
+ if (pendingDeploy && pendingDeploy.fromSessionId && pendingDeploy.fromSessionId !== id) {
364
+ clearPendingDeploy()
365
+ try {
366
+ deployStateToTargetChief(runtime, {
367
+ fromSessionId: pendingDeploy.fromSessionId,
368
+ toSessionId: id,
369
+ archiveTransferPolicy: pendingDeploy.archiveTransferPolicy || 'none',
370
+ archiveDrawer: pendingDeploy.archiveDrawer || '',
371
+ toCabinetId: pendingDeploy.toCabinetId || '',
372
+ customNote: pendingDeploy.customNote || '',
373
+ })
374
+ } catch {}
375
+ }
376
+
377
+ const pending = readPending()
378
+ if (!pending) return
379
+ const delivered = await injectInto(agent, pending.text)
380
+ if (delivered.ok) clearPending()
381
+ const file = boardFileFor(id)
382
+ const short = id.replace(/^session-/, '').slice(0, 8)
383
+ withBoardLock(file, () => {
384
+ const board = loadBoard(file)
385
+ pushLog(
386
+ board,
387
+ (delivered.ok ? '交接单已被本会话领取 ' : '交接单投放失败(' + delivered.error + '),仍待领取:') + short,
388
+ 'agent',
389
+ id,
390
+ )
391
+ // An injected packet only reaches the conversation, so the board the
392
+ // claimant actually opens would look empty. Keep the packet itself on
393
+ // that board, as a note, so the next reader sees the handover there.
394
+ if (delivered.ok) {
395
+ const title = '接手:' + (String(pending.text).split('\n')[0] || '上一段对话').replace(/^#\s*交接单\s*·\s*/, '').slice(0, 120)
396
+ const body = String(pending.text).slice(0, 6000)
397
+ const same = board.notes.find(note => note.title === title)
398
+ if (same) {
399
+ same.body = body
400
+ same.updatedAt = nowMs()
401
+ same.session = id
402
+ } else {
403
+ board.notes.unshift(normalizeNote({ id: newId('n'), title, body, tags: ['handoff'], by: 'agent', session: id }))
404
+ }
405
+ }
406
+ return saveBoard(board, file)
407
+ })
408
+ } catch {}
409
+ }), 'dsh-chief: deliver pending transfer')
410
+
411
+ // 2c) Incremental record of what each turn actually did + Auto-Continue detection
412
+ // on interruptions / transient failures / empty outputs (unless Chief is stopped).
413
+ ctx.effect(() => ctx.on('session/event', (session, event) => {
414
+ try {
415
+ if (!event || !session || !session.id) return
416
+ const id = String(session.id)
417
+ if (event.type === 'tool/call' && event.data) {
418
+ const turn = event.data.turn
419
+ noteToolCall(id, turn)
420
+ if (isPlanWrite(event.data.name, event.data.arguments)) notePlanWrite(id, turn)
421
+ noteCallTrail(id, event.data.name, event.data.arguments)
422
+ }
423
+ autoContinue.onSessionEvent(session, event)
424
+
425
+ if (event.type === 'turn/end') {
426
+ const rawReason = event.data && event.data.reason
427
+ const reason = String(rawReason && typeof rawReason === 'object' ? (rawReason.kind || '') : (rawReason || '')).toLowerCase()
428
+ const nestedReason = String(rawReason && typeof rawReason === 'object' && rawReason.reason && typeof rawReason.reason === 'object' ? (rawReason.reason.kind || '') : '').toLowerCase()
429
+ const isStoppedByUserOrPolicy = reason === 'aborted' || reason === 'blocked' || nestedReason === 'aborted' || nestedReason === 'blocked'
430
+ const turnNum = Number(event.data && event.data.turn)
431
+ const steerKey = `${id}:${turnNum}`
432
+ const steeredAt = deps.hostState.autoSteeredTurns.get(steerKey) || 0
433
+ 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)) {
437
+ const agents = runtime && runtime.get ? runtime.get('agents') : null
438
+ const liveAgent = agents && typeof agents.get === 'function' ? agents.get(id) : null
439
+ if (liveAgent) {
440
+ scheduleChiefTurnReview(makeChiefDeps(runtime), { agent: liveAgent, sessionId: id, turn: event.data && event.data.turn })
441
+ }
442
+ }
443
+ }
444
+ }
445
+ } catch {}
446
+ }), 'dsh-chief: tool call ledger & auto-continue')
447
+
448
+ // 3) One heartbeat per finished turn: which Sessions are still warm — and the
449
+ // idle guard: a turn that closes with a short answer, no tool call, and open
450
+ // work still on the board gets one more step instead of closing.
451
+ ctx.effect(() => ctx.on('agent/turn-stopping', payload => {
452
+ let id = ''
453
+ try {
454
+ const agent = payload && payload.agent
455
+ id = agent && agent.id ? String(agent.id) : ''
456
+ if (!id) return
457
+
458
+ const turn = Number(payload && payload.turn)
459
+ const file = boardFileFor(id)
460
+
461
+ // One critical section: heartbeat, memory line and the guard verdict all
462
+ // read and rewrite the same board, so a route landing mid-way must not be
463
+ // able to overwrite any of them.
464
+ withBoardLock(file, () => {
465
+ const board = loadBoard(file)
466
+
467
+ // Heartbeat, inlined so the three edits share one load and one save.
468
+ try {
469
+ const entry = board.sessions[id] || { lastSeen: 0, cwd: '', turns: 0 }
470
+ entry.lastSeen = nowMs()
471
+ entry.turns = (entry.turns || 0) + 1
472
+ const resolvedCwd = getSessionCwd(runtime, id)
473
+ if (resolvedCwd) entry.cwd = resolvedCwd
474
+ board.sessions[id] = entry
475
+ const ids = Object.keys(board.sessions)
476
+ if (ids.length > 40) {
477
+ ids.sort((a, b) => (board.sessions[a].lastSeen || 0) - (board.sessions[b].lastSeen || 0))
478
+ for (const stale of ids.slice(0, ids.length - 40)) delete board.sessions[stale]
479
+ }
480
+ } catch {}
481
+
482
+ // Memory first: every finished turn leaves one line in the board's memory
483
+ // before the guard can decide anything, so asking "what did we do" works
484
+ // even when the turn was idle.
485
+ let capturedEntry = null
486
+ const identity = resolveAgentIdentity(runtime, id, agent)
487
+ try {
488
+ capturedEntry = captureTurn(agent && agent.session, turn, null)
489
+ if (capturedEntry) {
490
+ capturedEntry.session = id
491
+ if (identity && identity.isChild && identity.self) {
492
+ capturedEntry.by = identity.self
493
+ }
494
+ appendMemory(board, capturedEntry)
495
+ }
496
+ } catch {}
497
+
498
+ // If a child subagent just finished its turn, auto-settle its assigned
499
+ // 'doing' task on the shared root board and unlock downstream dependencies.
500
+ if (identity && identity.isChild) {
501
+ const selfName = String(identity.self || '').toLowerCase()
502
+ const shortSelf = selfName.split('/').pop()
503
+ let settledCount = 0
504
+ for (const task of board.tasks || []) {
505
+ if (!task || task.status !== 'doing') continue
506
+ const tSub = String(task.subagent || '').toLowerCase()
507
+ const tOwn = String(task.owner || '').toLowerCase()
508
+ const matched = (selfName && (tSub === selfName || tOwn === selfName || tSub.split('/').pop() === shortSelf || tOwn.split('/').pop() === shortSelf))
509
+ || (task.session && String(task.session) === id)
510
+ if (matched && capturedEntry && capturedEntry.text) {
511
+ task.status = 'done'
512
+ if (!task.evidence) {
513
+ task.evidence = String(capturedEntry.title || capturedEntry.text).slice(0, CAP_TASK_EVIDENCE)
514
+ }
515
+ task.updatedAt = nowMs()
516
+ settledCount += 1
517
+ pushLog(board, '✅ 子代理 ' + identity.self + ' 完成任务 #' + task.id + '「' + task.title.slice(0, 36) + '」', identity.self, id)
518
+ }
519
+ }
520
+ if (settledCount > 0) {
521
+ reconcileTaskDependencies(board, identity.self, id)
522
+ }
523
+ saveBoard(board, file)
524
+ const childRoot = resolveRootSessionId(id, agent) || id
525
+ if (!isRootStopped(childRoot, id)) {
526
+ scheduleChiefTurnReview(makeChiefDeps(runtime), { agent, sessionId: id, turn })
527
+ }
528
+ return
529
+ }
530
+
531
+ const rootId = resolveRootSessionId(id, agent) || id
532
+ if (isRootStopped(rootId, id)) {
533
+ saveBoard(board, file)
534
+ return
535
+ }
536
+
537
+ // autoInject is machine-wide on the shared board; guardIdle follows the
538
+ // same rule so one switch turns the guard off everywhere.
539
+ const shared = loadBoard(boardFile())
540
+ const settings = { ...(board.settings || {}), ...(shared.settings || {}) }
541
+ const verdict = shouldGuard({ board, session: agent && agent.session, sessionId: id, turn, settings })
542
+ if (!verdict) {
543
+ saveBoard(board, file)
544
+ scheduleChiefTurnReview(makeChiefDeps(runtime), { agent, sessionId: id, turn })
545
+ return
546
+ }
547
+
548
+ if (typeof agent.steer !== 'function') {
549
+ pushLog(board, '空转拦截:这个 agent 没有 steer 方法,转由断线续跑模块跟进', 'guard', id)
550
+ saveBoard(board, file)
551
+ autoContinue.notifyIdleOrInterrupt(id, { kind: 'idle-stall', reason: verdict.reason || '' })
552
+ return
553
+ }
554
+
555
+ // Steer inside the lock: the notice is queued before another request can
556
+ // observe a board that claims an intervention that never happened.
557
+ const notice = buildNotice({ ...verdict, board })
558
+ agent.steer(notice)
559
+ deps.hostState.autoSteeredTurns.set(`${id}:${turn}`, Date.now())
560
+ if (deps.hostState.autoSteeredTurns.size > 120) {
561
+ const oldest = deps.hostState.autoSteeredTurns.keys().next().value
562
+ if (oldest) deps.hostState.autoSteeredTurns.delete(oldest)
563
+ }
564
+ noteIntervention(id, turn)
565
+ // Clear the trail only once the steer landed: a loop that survived a
566
+ // failed steer deserves the next nudge, not a silent reset.
567
+ if (verdict.kind === 'loop') clearCallTrail(id)
568
+ pushLog(board, guardLogText(verdict, turn, remainingInterventions(id, settings)), 'guard', id)
569
+
570
+ // Auto-handoff: when the guard has spent its last intervention and the
571
+ // session still has open work, the turn is not idle — it is stuck in a
572
+ // context that has grown too long to be productive. Generate the
573
+ // handover packet right now so the next Session (or a manual reopen)
574
+ // inherits it instead of a blank board. The steer already fired above
575
+ // tells the model to wrap up; this packet is what the next one reads.
576
+ if (remainingInterventions(id, settings) === 0) {
577
+ try {
578
+ const packet = resolveEffectiveHandoff(runtime, id, board).text
579
+ const pendingFile_ = pendingFile()
580
+ fs.writeFileSync(pendingFile_, JSON.stringify({ text: packet, at: nowMs(), from: id }))
581
+ pushLog(board, '上下文压力:干预计数耗尽,交接单已自动生成并放入待领取', 'handoff', id)
582
+ } catch (handoffError) {
583
+ pushLog(board, '自动交接单生成失败:' + String(handoffError && handoffError.message ? handoffError.message : handoffError).slice(0, 160), 'handoff', id)
584
+ }
585
+ }
586
+ saveBoard(board, file)
587
+ })
588
+ } catch (error) {
589
+ // Never let the guard break the turn boundary.
590
+ try {
591
+ if (!id) return
592
+ const file = boardFileFor(id)
593
+ withBoardLock(file, () => {
594
+ const board = loadBoard(file)
595
+ pushLog(board, '空转拦截自身出错:' + String(error && error.message ? error.message : error).slice(0, 160), 'guard', id)
596
+ saveBoard(board, file)
597
+ })
598
+ } catch {}
599
+ }
600
+ }), 'dsh-chief: session heartbeat and idle guard')
601
+
602
+ // Routes: the browser half of this same package calls them same-origin.
603
+ ctx.inject(['webServer'], webCtx => {
604
+ for (const route of routeTable(runtime)) {
605
+ webCtx.effect(() => webCtx.webServer.register(route), 'dsh-chief: route ' + route.path)
606
+ }
607
+ })
608
+
609
+ // Model tools: the cross-Session half of the same operations + whole-session pre-execute physical defense.
610
+ ctx.inject(['tools'], toolCtx => {
611
+ for (const tool of [boardTool(runtime), boundariesTool(runtime), handoffTool(runtime), memoryTool(runtime)]) {
612
+ toolCtx.effect(() => toolCtx.tools.register(tool), 'dsh-chief: tool ' + tool.name)
613
+ }
614
+ const hookOn = typeof toolCtx.on === 'function'
615
+ ? toolCtx.on.bind(toolCtx)
616
+ : (typeof ctx.on === 'function' ? ctx.on.bind(ctx) : null)
617
+ if (hookOn) {
618
+ toolCtx.effect(() => hookOn('tools/pre-execute', async (exec, next) => {
619
+ try {
620
+ if (!exec || !exec.name) return next()
621
+ const caller = exec.agent || null
622
+ const sid = caller && caller.id ? String(caller.id) : ''
623
+ const rootId = resolveRootSessionId(sid, caller) || sid || 'global'
624
+ const cwd = (sid && getSessionCwd(runtime, sid)) || (rootId !== 'global' && getSessionCwd(runtime, rootId)) || process.cwd()
625
+ const board = rootId && rootId !== 'global' ? boardForSession(boardFileFor(rootId)) : loadBoard(boardFile())
626
+ const verdict = evaluatePreExecuteDefense({
627
+ tool: String(exec.name),
628
+ args: exec.arguments && typeof exec.arguments === 'object' ? exec.arguments : {},
629
+ cwd,
630
+ board,
631
+ })
632
+ if (verdict && verdict.decision === 'deny') {
633
+ const st = loadChiefState()
634
+ const effCfg = resolveWorkspaceConfig(st, rootId)
635
+ const ident = resolveAgentIdentity(runtime, sid, caller)
636
+ const actorName = (ident && ident.self) || 'lead'
637
+ const targetPreview = String(
638
+ (exec.arguments && (exec.arguments.path || exec.arguments.file_path || exec.arguments.command || exec.arguments.cmd))
639
+ || exec.name,
640
+ ).slice(0, 120)
641
+ appendChiefAuditLog(rootId, {
642
+ mode: effCfg.permissionMode || 'advisor',
643
+ stage: verdict.stage || 'guard_wall',
644
+ rule: verdict.rule || 'pre_execute_denied',
645
+ decision: 'blocked',
646
+ operation: String(exec.name),
647
+ target: targetPreview,
648
+ reason: verdict.reason,
649
+ outcome: 'blocked',
650
+ by: actorName,
651
+ })
652
+ try {
653
+ const bFile = rootId !== 'global' ? boardFileFor(rootId) : boardFile()
654
+ withBoardLock(bFile, () => {
655
+ const b = loadBoard(bFile)
656
+ pushLog(b, `🧱 事前物理防线已拦截 @${actorName} 调用 ${exec.name}:${String(verdict.reason || '').slice(0, 110)}`, 'guard', sid || rootId)
657
+ saveBoard(b, bFile)
658
+ })
659
+ } catch {}
660
+ if (effCfg.tacticalModes && effCfg.tacticalModes.redlineSentinel) {
661
+ mutateChiefState((s) => {
662
+ if (!s.workspaces || !s.workspaces[rootId]) return
663
+ const ws = s.workspaces[rootId]
664
+ if (!Array.isArray(ws.chat)) ws.chat = []
665
+ ws.chat.push({
666
+ id: 'chat-' + Date.now().toString(36),
667
+ role: 'chief',
668
+ kind: 'receipt',
669
+ text: `- 【🧱 红线哨兵 · 事前物理拦截】已当场阻断 \`@${actorName}\` 的越界调用 \`${exec.name}\`\n- 【拦截原因】${verdict.reason}`,
670
+ actions: [verdict.badge || '🧱 事前物理拦截'],
671
+ at: Date.now(),
672
+ })
673
+ })
674
+ }
675
+ return {
676
+ kind: 'deny',
677
+ reason: `[DSH 安全卫兵事前物理拦截] ${verdict.reason}`,
678
+ info: { stage: verdict.stage, rule: verdict.rule, wallId: verdict.wallId || '' },
679
+ }
680
+ } else if (verdict && verdict.decision === 'ask') {
681
+ const st = loadChiefState()
682
+ const effCfg = resolveWorkspaceConfig(st, rootId)
683
+ const ident = resolveAgentIdentity(runtime, sid, caller)
684
+ const actorName = (ident && ident.self) || 'lead'
685
+ const targetPreview = String(
686
+ (exec.arguments && (exec.arguments.path || exec.arguments.file_path || exec.arguments.command || exec.arguments.cmd))
687
+ || exec.name,
688
+ ).slice(0, 120)
689
+ appendChiefAuditLog(rootId, {
690
+ mode: effCfg.permissionMode || 'advisor',
691
+ stage: verdict.stage || 'guard_wall',
692
+ rule: verdict.rule || 'guard_wall_require_approval_cmd',
693
+ decision: 'pending_approval',
694
+ operation: String(exec.name),
695
+ target: targetPreview,
696
+ reason: verdict.reason,
697
+ outcome: 'pending',
698
+ by: actorName,
699
+ })
700
+ return {
701
+ kind: 'ask',
702
+ reason: `[DSH 物理驻墙审批] ${verdict.reason}`,
703
+ displayReason: verdict.displayReason || verdict.reason,
704
+ }
705
+ }
706
+ } catch {}
707
+ return next()
708
+ }), 'dsh-chief: pre-execute physical defense')
709
+ }
710
+ })
711
+
712
+ // Runtime capability probe for DSH >= 0.2.2-rc.2 named subagent APIs
713
+ ctx.inject(['subagents'], () => {
714
+ const compat = probeSubagentSupport(runtime)
715
+ if (compat.present && !compat.namedSubagentsSupported) {
716
+ try {
717
+ console.warn('[dsh-chief] ' + compat.warning)
718
+ } catch {}
719
+ }
720
+ })
721
+
722
+ // Cold-start safety reconciliation for persistent TaskLedger (stale running/resuming -> interrupted; past TTL -> expired)
723
+ try {
724
+ const bootSt = loadChiefState({ forceDisk: true })
725
+ const hasNeedReconcile = Object.values((bootSt && bootSt.workspaces) || {}).some(
726
+ ws => Array.isArray(ws && ws.taskLedger) && ws.taskLedger.some(t => t && (t.status === 'interrupted' || t.status === 'expired')),
727
+ )
728
+ if (hasNeedReconcile) mutateChiefState(() => {})
729
+ } catch {}
730
+ }
731
+
732
+ return {
733
+ apply,
734
+ }
735
+ }