dsh-chief 1.5.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/chief-review.js CHANGED
@@ -7,6 +7,7 @@
7
7
  import crypto from 'node:crypto'
8
8
  import { loadArchiveStore } from './archives.js'
9
9
  import { normalizePermissionMode, permissionRank } from './chief-executor.js'
10
+ import { detectPrematurePromiseText } from './idle-guard.js'
10
11
  import {
11
12
  CHAT_CAP,
12
13
  REVIEW_DELAY_MS,
@@ -34,6 +35,7 @@ import {
34
35
  beginChiefActiveWork,
35
36
  updateChiefActiveWork,
36
37
  endChiefActiveWork,
38
+ pushAlertEventToWs,
37
39
  } from './chief-state.js'
38
40
  import { listChiefModels, callChiefLlm } from './chief-models.js'
39
41
  import { listPeerDirectory, deliverCrossMessage } from './chief-network.js'
@@ -65,7 +67,7 @@ const TURN_REVIEW_SYSTEM = [
65
67
  ' - 当 `INTERVENTION_SUPERVISOR` 或 `AUTO_PILOT_SESSION_ONLY` 开启时,你必须严密审查:主/子代理刚刚提出、准备执行、请求用户拍板,或接下来继续推进是否**存在重大不可逆风险,或继续推进必然会撞穿当前生效边界(尤其 🚫 禁止红线)**?',
66
68
  ' - **重要提示(下列仅是常见举例,绝不限于此!)**:包括但不限于实际花钱/扣费/下单/付费 API 调用、不可逆删除或清空文件/数据/仓库、下载超大文件占用巨额磁盘或流量、关闭/重启服务器或关键宿主服务、对外公开推送/发布不可撤回变更、破坏宿主机隔离边界、以及任何一旦继续推跑就会导致不可逆损失或必然撞穿红线的情形。',
67
69
  ' - 一旦命中任一上述风险或必然撞边界:**必须立即设 `"hazardStop": { "triggered": true, "category": "...", "title": "简短醒目告警标题", "reason": "用清晰人话说清具体会造成什么不可逆损失或必然撞上哪条边界,以及为何必须立即停下等用户处理" }`,并强制设 `"shouldIntervene": false`、`interventionText: ""`**(严禁再推下一轮!)。',
68
- '6. `shouldIntervene` & `interventionText`:当开启「主动强介入 (`INTERVENTION_SUPERVISOR`)」且 `hazardStop.triggered === false`、主代理停下时,对照「核心目标 + 必做事项 + 最新用户诉求」逐项核验!只要目标或必做事项尚未真正做完、缺少实测验证证据却自称完成,必须设 `shouldIntervene: true` 并写出清晰可执行、可直接投递给 `@lead` 继续推进下一回合的督导指令;若处于 `strictVerify` 模式但回复无实测输出证据,务必驳回自称完成并要求补跑验证;若开启 `conciseBrief`,督导指令严格限定在 3 条以内要点。仅当核心目标与必做事项均已完成 (`achieved`)、或正在等待子代理回信时,设 `shouldIntervene: false`。',
70
+ '6. `shouldIntervene` & `interventionText`:当开启「主动强介入 (`INTERVENTION_SUPERVISOR`)」且 `hazardStop.triggered === false` 时,**触发复盘代表主对话刚刚结束了本轮输出、当前已停下进入空闲 (`status=idle`)**!对照「核心目标 + 必做事项 + 最新用户/参谋诉求」逐项核验:只要目标或必做事项尚未真正做完、主对话仅用「重启 XX / 补跑剩余 N 张 / 接下来写脚本 / 继续推进」等口头预告收尾却未真正调用工具落实、或缺少实测验证证据却自称完成,**必须**设 `shouldIntervene: true` 并写出清晰可执行、可直接投递给 `@lead` 继续推进下一回合的 `interventionText` 督导指令;若处于 `strictVerify` 模式但回复无实测输出证据,务必驳回自称完成并要求补跑验证;若开启 `conciseBrief`,督导指令严格限定在 3 条以内要点。仅当核心目标与必做事项均已完成 (`achieved`)、或确认有活跃子代理正在后台运行等待回信时,才设 `shouldIntervene: false`。',
69
71
  '7. `suggestions`(最多 1 条,宁缺毋滥):',
70
72
  ' - `"kind": "bound"`:明显撞墙或发现长期红线/必做规矩时请示注入边界;',
71
73
  ' - `"kind": "relay"`:发现明确跨对话信息差时的递话建议;',
@@ -146,6 +148,58 @@ function detectEmergencyHazardFallback({ parsed, digestText = '', bounds = {}, i
146
148
 
147
149
  const reviewTimers = new Map()
148
150
 
151
+ const DIRECTIVE_SOURCE_KINDS = new Set([
152
+ '',
153
+ 'user',
154
+ 'dsh-chief-relay',
155
+ 'dsh-chief-execution-request',
156
+ 'dsh-chief-auto-continue',
157
+ ])
158
+
159
+ const HIGH_RISK_FALLBACK_RE = /(?:花钱|扣费|付款|付费|下单|充值|删库|永久删除|清空目录|格式化|关闭服务器|停服|重启宿主|git\s+push|npm\s+publish|请确认|请选择|需要您|请指示|请拍板)/i
160
+
161
+ function extractMessageTextBlocks(msg) {
162
+ const blocks = Array.isArray(msg && msg.content)
163
+ ? msg.content
164
+ : (typeof (msg && msg.content) === 'string' ? [{ type: 'text', text: msg.content }] : [])
165
+ const textParts = []
166
+ const toolHints = []
167
+ for (const b of blocks) {
168
+ if (!b || typeof b !== 'object') continue
169
+ if (b.type === 'text' && typeof b.text === 'string' && b.text.trim()) {
170
+ textParts.push(b.text.trim())
171
+ } else if ((b.type === 'tool_use' || b.type === 'tool-call' || b.type === 'toolCall') && (b.name || b.toolName)) {
172
+ const tName = String(b.name || b.toolName)
173
+ let argHint = ''
174
+ try {
175
+ const rawArgs = b.input || b.arguments || b.args
176
+ const obj = typeof rawArgs === 'string' ? JSON.parse(rawArgs) : rawArgs
177
+ if (obj && typeof obj === 'object') {
178
+ const val = obj.action || obj.command || obj.cmd || obj.path || obj.file_path || obj.agent || obj.title || ''
179
+ if (val) argHint = clamp(String(val), 40)
180
+ }
181
+ } catch {}
182
+ toolHints.push(argHint ? `${tName}(${argHint})` : tName)
183
+ }
184
+ }
185
+ return {
186
+ text: textParts.join('\n').trim(),
187
+ toolHints,
188
+ }
189
+ }
190
+
191
+ function resolveTurnTag(turn) {
192
+ if (typeof turn === 'number' && Number.isFinite(turn)) return String(turn)
193
+ if (turn && typeof turn === 'object') {
194
+ if (turn.turn !== undefined) return String(turn.turn)
195
+ if (turn.index !== undefined) return String(turn.index)
196
+ if (turn.id !== undefined) return String(turn.id)
197
+ if (turn.ok) return 'ok'
198
+ if (turn.error) return 'err'
199
+ }
200
+ return 't'
201
+ }
202
+
149
203
  function extractLatestTurnDigest(agent, turn) {
150
204
  if (!agent || !agent.session) return null
151
205
  try {
@@ -155,48 +209,63 @@ function extractLatestTurnDigest(agent, turn) {
155
209
  for (let i = msgs.length - 1; i >= 0; i -= 1) {
156
210
  const um = msgs[i]
157
211
  if (!um || um.role !== 'user') continue
158
- if (um.source && um.source.kind && um.source.kind !== 'user') continue
159
- const uBlocks = Array.isArray(um.content) ? um.content : []
160
- const uTxt = uBlocks
161
- .filter(b => b && b.type === 'text' && typeof b.text === 'string')
162
- .map(b => b.text)
163
- .join('\n')
164
- .trim()
212
+ const srcKind = String((um.source && um.source.kind) || '').trim()
213
+ if (!DIRECTIVE_SOURCE_KINDS.has(srcKind)) continue
214
+ const uTxt = extractMessageTextBlocks(um).text
165
215
  if (uTxt && !isInternalCheckpointNoise(uTxt)) {
166
216
  latestUserPrompt = clamp(uTxt, 1000)
167
217
  break
168
218
  }
169
219
  }
170
220
 
171
- const tail = msgs.slice(-6)
172
- const lines = []
221
+ const scanStart = Math.max(0, msgs.length - 24)
222
+ const collected = []
173
223
  let hasUser = false
174
- for (const m of tail) {
224
+ let lastAssistantText = ''
225
+ for (let i = msgs.length - 1; i >= scanStart && collected.length < 8; i -= 1) {
226
+ const m = msgs[i]
175
227
  if (!m || !m.role) continue
176
- if (m.source && m.source.kind && m.source.kind !== 'user' && m.role === 'user') continue
177
- const blocks = Array.isArray(m.content) ? m.content : []
178
- const txt = blocks
179
- .filter(b => b && b.type === 'text' && typeof b.text === 'string')
180
- .map(b => b.text)
181
- .join('\n')
182
- .trim()
183
- if (!txt || isInternalCheckpointNoise(txt)) continue
228
+ const srcKind = String((m.source && m.source.kind) || '').trim()
184
229
  if (m.role === 'user') {
185
- hasUser = true
186
- lines.push('User: ' + clamp(txt, 1200))
230
+ if (!DIRECTIVE_SOURCE_KINDS.has(srcKind)) continue
231
+ const uTxt = extractMessageTextBlocks(m).text
232
+ if (!uTxt || isInternalCheckpointNoise(uTxt)) continue
233
+ if (!srcKind || srcKind === 'user') {
234
+ hasUser = true
235
+ collected.push('User: ' + clamp(uTxt, 1200))
236
+ } else {
237
+ collected.push('Chief->Lead: ' + clamp(uTxt, 900))
238
+ }
187
239
  } else if (m.role === 'assistant') {
188
- lines.push('Assistant: ' + clamp(txt, 900))
240
+ const { text: aTxt, toolHints } = extractMessageTextBlocks(m)
241
+ const cleanTxt = aTxt && !isInternalCheckpointNoise(aTxt) ? aTxt : ''
242
+ if (!cleanTxt && !toolHints.length) continue
243
+ if (cleanTxt) {
244
+ if (!lastAssistantText) lastAssistantText = cleanTxt
245
+ collected.push('Assistant: ' + clamp(cleanTxt, 900) + (toolHints.length ? ` [Tools: ${toolHints.slice(0, 4).join(' -> ')}]` : ''))
246
+ } else {
247
+ collected.push('Assistant Tools: ' + toolHints.slice(0, 6).join(' -> '))
248
+ }
189
249
  }
190
250
  }
191
- if (lines.length > 0) return { text: lines.join('\n'), hasUser, latestUserPrompt, stamp: msgs.length }
251
+ const lines = collected.reverse()
252
+ if (lines.length > 0) {
253
+ const joined = lines.join('\n')
254
+ const lastMsg = msgs[msgs.length - 1]
255
+ const lastMsgId = String((lastMsg && (lastMsg.id || lastMsg.messageId || lastMsg.timestamp)) || 'm').slice(0, 24)
256
+ const tailHash8 = crypto.createHash('sha1').update(joined).digest('hex').slice(0, 8)
257
+ const stamp = `${resolveTurnTag(turn)}:${msgs.length}:${lastMsgId}:${tailHash8}`
258
+ return { text: joined, hasUser, latestUserPrompt, lastAssistantText, msgCount: msgs.length, stamp }
259
+ }
192
260
  }
193
261
  } catch {}
194
262
  return null
195
263
  }
196
264
 
197
265
  const lastReviewAtByRoot = new Map()
266
+ const lastFallbackStampByRoot = new Map()
198
267
 
199
- export function scheduleChiefTurnReview(deps, { agent, sessionId, turn, abnormalTrigger = '' }) {
268
+ export function scheduleChiefTurnReview(deps, { agent, sessionId, turn, abnormalTrigger = '', delayOverrideMs = null }) {
200
269
  const sid = String(sessionId || (agent && agent.id) || '').trim()
201
270
  if (!sid) return
202
271
  // Never waste tokens reviewing internal mnemon checkpoint / probe subagents
@@ -211,16 +280,17 @@ export function scheduleChiefTurnReview(deps, { agent, sessionId, turn, abnormal
211
280
  const wsSnap = state.workspaces && state.workspaces[rootKey] ? state.workspaces[rootKey] : null
212
281
  const pendingSmart = Boolean(wsSnap && wsSnap.runtimeGuard && wsSnap.runtimeGuard.pendingSmartCompact)
213
282
  const compactChannel = Boolean(tactical.autoCompact || tactical.smartCompact || pendingSmart)
283
+ const interventionChannel = Boolean(tactical.intervention)
214
284
 
215
- if (effCfg.stopped || (runMode === 'off' && !compactChannel)) {
285
+ if (effCfg.stopped || (runMode === 'off' && !compactChannel && !interventionChannel)) {
216
286
  clearTimeout(reviewTimers.get(rootKey))
217
287
  reviewTimers.delete(rootKey)
218
288
  return
219
289
  }
220
290
 
221
- // In PATROL mode: normal turns consume 0 background tokens; wake ONLY on explicit abnormal triggers or compaction checks
291
+ // In PATROL mode: normal turns consume 0 background tokens; wake ONLY on explicit abnormal triggers, compaction, or intervention
222
292
  const hasAbnormal = Boolean(String(abnormalTrigger || '').trim())
223
- if (runMode === 'patrol' && !hasAbnormal && !compactChannel) {
293
+ if (runMode === 'patrol' && !hasAbnormal && !compactChannel && !interventionChannel) {
224
294
  return
225
295
  }
226
296
 
@@ -228,10 +298,12 @@ export function scheduleChiefTurnReview(deps, { agent, sessionId, turn, abnormal
228
298
  ? deps.boardForSession(deps.boardFileFor(rootKey))
229
299
  : null
230
300
  const isGoalMode = Boolean(board && board.mode === 'goal')
231
- const hasHighPriorityChannel = hasAbnormal || isGoalMode || compactChannel || tactical.intervention || tactical.redlineSentinel || tactical.strictVerify
301
+ const hasHighPriorityChannel = hasAbnormal || isGoalMode || compactChannel || interventionChannel || tactical.redlineSentinel || tactical.strictVerify
232
302
 
233
303
  clearTimeout(reviewTimers.get(rootKey))
234
- const delayMs = hasHighPriorityChannel ? 1_200 : REVIEW_DELAY_MS
304
+ const delayMs = delayOverrideMs !== null && Number.isFinite(Number(delayOverrideMs)) && Number(delayOverrideMs) >= 0
305
+ ? Math.max(100, Math.round(Number(delayOverrideMs)))
306
+ : (hasHighPriorityChannel ? 1_200 : REVIEW_DELAY_MS)
235
307
  const timer = setTimeout(() => {
236
308
  reviewTimers.delete(rootKey)
237
309
  runTurnReview(deps, { agent, sessionId: sid, turn, abnormalTrigger }).catch(() => {})
@@ -253,12 +325,13 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
253
325
  const wsBefore = ensureWorkspace(stateBefore, rootId)
254
326
  const pendingSmart = Boolean(wsBefore.runtimeGuard && wsBefore.runtimeGuard.pendingSmartCompact)
255
327
  const compactChannel = Boolean(tactical.autoCompact || tactical.smartCompact || pendingSmart)
328
+ const interventionChannel = Boolean(tactical.intervention)
256
329
  const hasAbnormal = Boolean(String(abnormalTrigger || '').trim())
257
330
 
258
331
  if (!force && effCfgBefore.stopped) {
259
332
  return { ok: false, skipped: 'chief-stopped' }
260
333
  }
261
- if (!force && runMode === 'off' && !compactChannel) {
334
+ if (!force && runMode === 'off' && !compactChannel && !interventionChannel) {
262
335
  return { ok: false, skipped: 'off' }
263
336
  }
264
337
  const board = deps.boardForSession && deps.boardFileFor
@@ -266,7 +339,7 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
266
339
  : null
267
340
  const isGoalMode = Boolean(board && board.mode === 'goal')
268
341
  const smartCoManaged = Boolean(tactical.smartCompact)
269
- const hasHighPriority = hasAbnormal || isGoalMode || tactical.intervention || tactical.redlineSentinel || tactical.strictVerify || compactChannel
342
+ const hasHighPriority = hasAbnormal || isGoalMode || interventionChannel || tactical.redlineSentinel || tactical.strictVerify || compactChannel
270
343
 
271
344
  // Always check pre-compaction pipeline first when autoCompact/smartCompact/pendingSmartCompact is active
272
345
  if (compactChannel) {
@@ -278,21 +351,22 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
278
351
  }
279
352
  return { ok: false, error: msg }
280
353
  })
281
- if (preRes && preRes.ok && preRes.smartCompacted) {
354
+ if (preRes && preRes.ok && preRes.smartCompacted && !interventionChannel) {
282
355
  return { ok: true, smartCompacted: true, harvestId: preRes.harvestId }
283
356
  }
284
357
  }
285
358
 
286
359
  // If runMode === 'off' and we only entered for standalone smartCompact/autoCompact pre-check,
287
- // exit cleanly once autoCompact threshold isn't forcing LLM, except when smartCoManaged needs its idle evaluation.
288
- if (!force && runMode === 'off' && !smartCoManaged) {
360
+ // exit cleanly once autoCompact threshold isn't forcing LLM, except when smartCoManaged or intervention needs evaluation.
361
+ if (!force && runMode === 'off' && !smartCoManaged && !interventionChannel) {
289
362
  return { ok: true, onlyCompactionChecked: true }
290
363
  }
291
364
 
292
- // If ONLY fixed-threshold autoCompact was on (without smartCompact or patrol-abnormal or managed), exit cleanly
365
+ // If ONLY fixed-threshold autoCompact was on (without smartCompact, intervention, patrol-abnormal, or managed), exit cleanly
293
366
  const needsSupervisorLlm = (runMode === 'managed')
294
367
  || (runMode === 'patrol' && hasAbnormal)
295
368
  || smartCoManaged
369
+ || interventionChannel
296
370
  || (force && (isGoalMode || tactical.intervention || tactical.redlineSentinel || tactical.strictVerify))
297
371
  if (!force && !needsSupervisorLlm && runMode !== 'patrol') {
298
372
  return { ok: true, onlyCompactionChecked: true }
@@ -302,7 +376,7 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
302
376
  if (!digest || !digest.text) return { ok: false, skipped: 'no-digest' }
303
377
 
304
378
  const hasWallCue = hasAbnormal || /(?:permission denied|eacces|eperm|forbidden|blocked|not allowed|sandbox|read-only|撞墙|受阻|权限拒绝|越界)/i.test(digest.text)
305
- if (!force && runMode === 'patrol' && !hasWallCue && !smartCoManaged) {
379
+ if (!force && runMode === 'patrol' && !hasWallCue && !smartCoManaged && !interventionChannel) {
306
380
  return { ok: false, skipped: 'patrol-no-abnormal' }
307
381
  }
308
382
 
@@ -319,7 +393,14 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
319
393
  const cooldownMs = hasHighPriority
320
394
  ? (smartCoManaged && !isGoalMode && !tactical.intervention && !hasAbnormal ? 12_000 : 4_000)
321
395
  : (runMode === 'patrol' ? (hasWallCue ? 45_000 : SMART_REVIEW_COOLDOWN_MS) : AUTO_REVIEW_COOLDOWN_MS)
322
- if (!force && now - lastAt < cooldownMs) return { ok: false, skipped: 'cooldown' }
396
+ if (!force && now - lastAt < cooldownMs) {
397
+ if (interventionChannel || isGoalMode || hasAbnormal) {
398
+ const waitMs = Math.max(500, cooldownMs - (now - lastAt) + 250)
399
+ scheduleChiefTurnReview(deps, { agent, sessionId: sid, turn, abnormalTrigger, delayOverrideMs: waitMs })
400
+ return { ok: false, skipped: 'cooldown', rescheduled: true, waitMs }
401
+ }
402
+ return { ok: false, skipped: 'cooldown' }
403
+ }
323
404
 
324
405
  // Wait if supervisor/goal/smart-compact is active so turn-stopping settles to idle before evaluating usage
325
406
  if ((tactical.intervention || isGoalMode || smartCoManaged) && typeof deps.getAgentStatus === 'function' && !force) {
@@ -344,7 +425,7 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
344
425
  if (smartCoManaged && runMode === 'off') {
345
426
  const ratio = liveUsage && liveUsage.contextWindow ? (Number(liveUsage.totalTokens) || 0) / Number(liveUsage.contextWindow) : 0
346
427
  const sinceCompact = now - ((wsBefore.runtimeGuard && wsBefore.runtimeGuard.lastCompactedAt) || 0)
347
- if ((digest.stamp < 4 && ratio < 0.25) || sinceCompact < 20_000) {
428
+ if ((digest.msgCount < 4 && ratio < 0.25) || sinceCompact < 20_000) {
348
429
  return { ok: false, skipped: 'smart-compact-light' }
349
430
  }
350
431
  } else if (runMode === 'managed') {
@@ -388,7 +469,7 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
388
469
  ].filter(Boolean)
389
470
 
390
471
  const smartUsageHint = smartCoManaged
391
- ? `智选共管状态(硬阈值已停用):消息序号≈${digest.stamp}${liveUsage && liveUsage.totalTokens ? `,当前估算上下文 ${liveUsage.totalTokens}/${liveUsage.contextWindow} (${Math.round((liveUsage.totalTokens / liveUsage.contextWindow) * 100)}%)` : ''}`
472
+ ? `智选共管状态(硬阈值已停用):消息数≈${digest.msgCount}${liveUsage && liveUsage.totalTokens ? `,当前估算上下文 ${liveUsage.totalTokens}/${liveUsage.contextWindow} (${Math.round((liveUsage.totalTokens / liveUsage.contextWindow) * 100)}%)` : ''}`
392
473
  : ''
393
474
 
394
475
  const prompt = [
@@ -423,10 +504,56 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
423
504
  prompt,
424
505
  maxTokens: SUMMARY_MAX_TOKENS,
425
506
  })
426
- if (!res.ok) return { ok: false, error: res.error }
427
-
428
- const parsed = extractJsonObject(res.text)
429
- if (!parsed) return { ok: false, error: 'non-json-review' }
507
+ const parsed = res && res.ok ? extractJsonObject(res.text) : null
508
+ if (!res.ok || !parsed) {
509
+ const errTag = !res.ok ? (res.error || 'review-llm-failed') : 'non-json-review'
510
+ if (interventionChannel) {
511
+ if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
512
+ deps.appendBoardLog(rootId, `⚠️ 强介入后台复盘异常(${clamp(errTag, 100)}),准备自动重试/兜底检查`, 'chief')
513
+ }
514
+ if (!force && abnormalTrigger !== 'review_retry') {
515
+ scheduleChiefTurnReview(deps, { agent, sessionId: sid, turn, abnormalTrigger: 'review_retry', delayOverrideMs: 5_000 })
516
+ }
517
+ const permCheck = normalizePermissionMode(effCfgBefore.permissionMode, {
518
+ requireAck: true,
519
+ hasChiefRiskAck: hasValidChiefRiskAck(wsBefore),
520
+ })
521
+ const canZeroLlmFallback = permCheck === 'chief'
522
+ && hasValidChiefRiskAck(wsBefore)
523
+ && !(identity && identity.isChild)
524
+ && !HIGH_RISK_FALLBACK_RE.test(digest.lastAssistantText || '')
525
+ const fallbackCue = canZeroLlmFallback ? detectPrematurePromiseText(digest.lastAssistantText || '') : ''
526
+ if (fallbackCue && lastFallbackStampByRoot.get(rootId) !== digest.stamp) {
527
+ lastFallbackStampByRoot.set(rootId, digest.stamp)
528
+ const fbMsg = `【⚡ 参谋长零模型兜底续推】后台复盘模型暂时波动(${clamp(errTag, 60)}),但我检测到你刚才以口头预告下一步(「${fallbackCue}」)直接停在空闲态,且无高危风险提示。请立即调用工具落实该步并验证结果。`
529
+ const fbDeliv = await deliverCrossMessage(deps, {
530
+ fromSession: rootId,
531
+ fromLabel: 'DSH 参谋长 (强介入安全兜底)',
532
+ target: 'lead',
533
+ subject: '口头预告停摆 · 安全兜底推进',
534
+ text: fbMsg,
535
+ mode: 'followup',
536
+ envelopeKind: 'execution_request',
537
+ }).catch(() => null)
538
+ if (fbDeliv && fbDeliv.ok && fbDeliv.deliveredPhysical !== false) {
539
+ mutateChiefState((s) => {
540
+ const ws = ensureWorkspace(s, rootId)
541
+ ws.chat.push({
542
+ id: nextId('chat'),
543
+ role: 'chief',
544
+ kind: 'receipt',
545
+ text: `- 【⚡ 强介入兜底推进】复盘模型暂不可用,已针对口头预告停摆(「${fallbackCue}」)触发安全兜底唤醒 \`@lead\`。`,
546
+ actions: ['⚡ 兜底续推'],
547
+ at: Date.now(),
548
+ })
549
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
550
+ })
551
+ return { ok: true, fallbackIntervened: true, reason: errTag }
552
+ }
553
+ }
554
+ }
555
+ return !res.ok ? { ok: false, error: res.error } : { ok: false, error: 'non-json-review' }
556
+ }
430
557
 
431
558
  const cfgNow = resolveWorkspaceConfig(loadChiefState(), rootId)
432
559
  const wsNowPerm = ensureWorkspace(loadChiefState(), rootId)
@@ -498,6 +625,11 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
498
625
  const autoBoundUpdates = []
499
626
  let shouldAutoOrganizeSession = false
500
627
 
628
+ const hasRunningChild = realPeers.some(p => p.kind === 'subagent' && p.status === 'running')
629
+ const prematureCue = !(identity && identity.isChild)
630
+ ? detectPrematurePromiseText(digest.lastAssistantText || '')
631
+ : ''
632
+
501
633
  const isInternalRelayTarget = (targetRaw) => {
502
634
  const tq = String(targetRaw || '').trim().replace(/^@/, '')
503
635
  if (!tq) return false
@@ -647,15 +779,41 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
647
779
  })
648
780
  if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
649
781
  pushAuditToWs(ws, { mode: permNow, stage: 'safety_guard', decision: 'hazard_stop', operation: '强介入紧急煞车', target: 'lead', reason: hazardAlertCreated.reason, outcome: 'blocked', by: 'chief' })
782
+ pushAlertEventToWs(ws, {
783
+ kind: 'hazard_halt',
784
+ level: 'danger',
785
+ title: hazardAlertCreated.title,
786
+ body: hazardAlertCreated.reason,
787
+ dedupeKey: 'haz:' + hazardAlertCreated.id,
788
+ at: hazardAlertCreated.at || Date.now(),
789
+ })
650
790
  } else {
651
791
  // Intervention Supervisor follow-up + Circuit Breaker (differentiated across L0 / L1 / L2 / L3)
652
792
  const unmetMustDoFallback = unmetMustDo.length > 0
653
793
  ? '当前尚有以下【必做事项】未确认交付或缺少验证证据,请逐项补齐并交卷:\n' + unmetMustDo.map((u, idx) => `${idx + 1}. ${u}`).join('\n')
654
794
  : ''
795
+ const goalMissingFallback = cleanMultiline(parsed.goalMissing || '', 420)
796
+ ? `对照锁定核心目标尚有未闭环缺口:${cleanMultiline(parsed.goalMissing, 360)}。请基于当前进展立刻调用工具补齐并提交验证结果。`
797
+ : ''
798
+ const prematureFallback = prematureCue && !hasRunningChild
799
+ ? `检测到你刚才以口头预告下一步(「${prematureCue}」)直接结束了回合,但核心目标仍未收口。请立即调用工具把该步实际执行到位并验证输出。`
800
+ : ''
655
801
  const candidateIntervention = parsed.interventionText
656
802
  || unmetMustDoFallback
803
+ || goalMissingFallback
804
+ || prematureFallback
657
805
  || (parsed.nextActionForLead && (parsed.shouldIntervene || parsed.goalStatus === 'in_progress') ? parsed.nextActionForLead : '')
658
- if (!isGoalAchieved && tactical.intervention && (parsed.shouldIntervene || parsed.goalStatus === 'in_progress' || unmetMustDo.length > 0) && candidateIntervention) {
806
+ const wantsIntervene = Boolean(
807
+ parsed.shouldIntervene
808
+ || unmetMustDo.length > 0
809
+ || (parsed.goalStatus === 'in_progress' && (
810
+ Boolean(parsed.interventionText)
811
+ || Boolean(parsed.nextActionForLead)
812
+ || Boolean(parsed.goalMissing)
813
+ || Boolean(prematureCue && !hasRunningChild)
814
+ ))
815
+ )
816
+ if (!isGoalAchieved && tactical.intervention && wantsIntervene && candidateIntervention) {
659
817
  const assistantTail = (digest.text.split('Assistant:').pop() || digest.text)
660
818
  const sig = crypto
661
819
  .createHash('sha1')
@@ -805,7 +963,7 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
805
963
  } else {
806
964
  const contextWindow = Math.max(1000, Number(liveUsage && liveUsage.contextWindow) || 128_000)
807
965
  const totalTokens = Number(liveUsage && liveUsage.totalTokens) || 0
808
- const seq = Math.max(0, Math.round(Number(liveUsage && liveUsage.seq) || digest.stamp || 0))
966
+ const seq = Math.max(0, Math.round(Number(liveUsage && liveUsage.seq) || digest.msgCount || 0))
809
967
  const ratioPct = totalTokens > 0 ? (totalTokens / contextWindow) * 100 : 0
810
968
  updateChiefActiveWork(rootId, reviewWorkId, {
811
969
  tone: 'archive',
@@ -866,20 +1024,59 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
866
1024
  })
867
1025
  }
868
1026
 
1027
+ let interventionDeliveredFailed = false
869
1028
  if (interventionMessage) {
870
1029
  const tags = [
871
1030
  tactical.strictVerify ? '严格校验实测' : '',
872
1031
  tactical.redlineSentinel ? '红线哨兵巡检' : '',
873
1032
  tactical.conciseBrief ? '精炼要点' : '',
874
1033
  ].filter(Boolean).join(' · ')
875
- await deliverCrossMessage(deps, {
1034
+ const delivRes = await deliverCrossMessage(deps, {
876
1035
  fromSession: rootId,
877
1036
  fromLabel: `DSH 参谋长 (接管督导${tags ? '·' + tags : ''})`,
878
1037
  target: 'lead',
879
1038
  subject: '参谋长自动督导推进',
880
1039
  text: interventionMessage,
881
1040
  mode: 'followup',
882
- })
1041
+ envelopeKind: 'execution_request',
1042
+ }).catch(err => ({ ok: false, deliveredPhysical: false, error: String(err && err.message ? err.message : err) }))
1043
+ const deliveredOk = Boolean(delivRes && delivRes.ok && delivRes.deliveredPhysical !== false)
1044
+ if (deliveredOk) {
1045
+ mutateChiefState((s) => {
1046
+ const ws = ensureWorkspace(s, rootId)
1047
+ const turnIdx = ws.runtimeGuard.interventionTurns || 1
1048
+ ws.chat.push({
1049
+ id: nextId('chat'),
1050
+ role: 'chief',
1051
+ kind: 'receipt',
1052
+ ...(res.thinkingEffort ? { thinkingEffort: res.thinkingEffort } : {}),
1053
+ ...(res.thinkingEffortMode ? { thinkingEffortMode: res.thinkingEffortMode } : {}),
1054
+ text: `- 【⚡ 强介入督导 · 第 ${turnIdx} 轮】已推动 \`@lead\` 继续执行:${clamp(interventionMessage, 220)}`,
1055
+ actions: [`⚡ 强介入督导 #${turnIdx}`],
1056
+ at: Date.now(),
1057
+ })
1058
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
1059
+ })
1060
+ } else {
1061
+ interventionDeliveredFailed = true
1062
+ const failReason = (delivRes && (delivRes.note || delivRes.error)) || '目标会话句柄不可用或离线排队'
1063
+ mutateChiefState((s) => {
1064
+ const ws = ensureWorkspace(s, rootId)
1065
+ ws.runtimeGuard.interventionTurns = Math.max(0, (ws.runtimeGuard.interventionTurns || 0) - 1)
1066
+ ws.chat.push({
1067
+ id: nextId('chat'),
1068
+ role: 'chief',
1069
+ kind: 'receipt',
1070
+ text: `- 【⚠️ 强介入督导未能物理唤醒】未能直接推醒 \`@lead\`(${clamp(failReason, 160)}),本轮未计入强介入次数。`,
1071
+ actions: ['⚠️ 强介入未送达'],
1072
+ at: Date.now(),
1073
+ })
1074
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
1075
+ })
1076
+ if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
1077
+ deps.appendBoardLog(rootId, `⚠️ 强介入督导投递未物理唤醒 @lead:${clamp(failReason, 140)}`, 'chief')
1078
+ }
1079
+ }
883
1080
  }
884
1081
 
885
1082
  if (permRankNow >= 1 && autoBoundUpdates.length > 0 && deps.runAction) {
@@ -1044,7 +1241,7 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
1044
1241
  goalProposalCreated,
1045
1242
  hazardStopped,
1046
1243
  ...(hazardAlertCreated ? { hazardAlert: hazardAlertCreated } : {}),
1047
- intervened: Boolean(interventionMessage),
1244
+ intervened: Boolean(interventionMessage && !interventionDeliveredFailed),
1048
1245
  queuedInterventionApproval: Boolean(interventionForApproval),
1049
1246
  smartCompacted,
1050
1247
  circuitTripped,
@@ -1084,6 +1281,9 @@ export async function checkAndStopIdleAutoPilot(deps, sessionId, opts = {}) {
1084
1281
  if (effBefore.stopped || effBefore.runMode !== 'managed') {
1085
1282
  return { ok: true, stopped: false, reason: 'not-managed' }
1086
1283
  }
1284
+ if (effBefore.tacticalModes && effBefore.tacticalModes.intervention && !opts.goalAchievedFastStop) {
1285
+ return { ok: true, stopped: false, reason: 'intervention-active' }
1286
+ }
1087
1287
  // Condition 5a: 0 pending review timers
1088
1288
  if (reviewTimers.has(rootId)) {
1089
1289
  return { ok: true, stopped: false, reason: 'review-pending' }
@@ -1227,6 +1427,13 @@ export async function checkAndStopIdleAutoPilot(deps, sessionId, opts = {}) {
1227
1427
  at: Date.now(),
1228
1428
  })
1229
1429
  if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
1430
+ pushAlertEventToWs(ws, {
1431
+ kind: 'managed_auto_sleep',
1432
+ level: 'success',
1433
+ title: '🌙 托管已自动休眠收工',
1434
+ body: '连续闲置达阈值且在途任务、待批弹窗与问询均已清零,已切回「⏸ 关停」。',
1435
+ dedupeKey: `sleep:${rootId}:${Math.floor(Date.now() / 15_000)}`,
1436
+ })
1230
1437
  stoppedNow = true
1231
1438
  })
1232
1439