dsh-chief 1.6.0 → 1.7.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
@@ -6,7 +6,7 @@
6
6
 
7
7
  import crypto from 'node:crypto'
8
8
  import { loadArchiveStore } from './archives.js'
9
- import { normalizePermissionMode, permissionRank } from './chief-executor.js'
9
+ import { normalizePermissionMode, permissionRank, buildCapabilityScope } from './chief-executor.js'
10
10
  import { detectPrematurePromiseText } from './idle-guard.js'
11
11
  import {
12
12
  CHAT_CAP,
@@ -16,6 +16,7 @@ import {
16
16
  DEFAULT_MANAGED_IDLE_TIMEOUT_MS,
17
17
  SUMMARY_MAX_TOKENS,
18
18
  archiveTargetForRoot,
19
+ collectChiefVisibleArchives,
19
20
  nextId,
20
21
  clamp,
21
22
  cleanMultiline,
@@ -48,7 +49,7 @@ import {
48
49
  executeHarvestAndCompact,
49
50
  maybeRunPreCompaction,
50
51
  } from './chief-compaction.js'
51
- import { applyFactChanges, applyBoardOps } from './chief-commands.js'
52
+ import { applyFactChanges, applyBoardOps, executeChiefArchiveInjectionOp } from './chief-commands.js'
52
53
  import { executeBatchSuggestions } from './chief-approvals.js'
53
54
 
54
55
  const TURN_REVIEW_SYSTEM = [
@@ -74,6 +75,7 @@ const TURN_REVIEW_SYSTEM = [
74
75
  ' - `"kind": "advice"`:当主模型陷入明显可替代方案、环境坑点或需提醒用户拍板的关键决策时提出一句话建议,可带 `"popup": true|false`(仅关键分叉/阻塞决策设 `true`)。',
75
76
  '8. `shouldCompactNow` & `compactReason`:仅当 `SMART_COMPACT_CO_MANAGED`(✦ 智选)启用时评估!此时硬性上下文阈值已退让为辅助,由你与主会话共同把控压缩时机:只要一个完整阶段目标刚刚收口、工作流切换阶段、出现大量重复试错/工具噪音日志、或上下文估算已达 ≥30% 且适合归档脱水时,果断设 `shouldCompactNow: true` 并填写一句话 `compactReason`;仅在刚起步或上下文极轻时保持 `false`。',
76
77
  '9. `AUTO_PILOT_SESSION_ONLY`(全自动托管安全边界):当激活标志包含 `AUTO_PILOT_SESSION_ONLY` 时,所有自动决策仅限本对话会话内部!严禁将本会话规律生成 `"pinGlobal": true` 的全局定住边界,严禁跨出本对话去篡改全局档案柜或无关独立窗口;发现跨窗口传递信息时可留待人工审批。',
78
+ '10. `desktopArchivePin`(按需取档上认知桌面):仅当 prompt 列出的「可用但尚未摆上认知桌面的可见档案」中存在当前任务/卡点/排障**正高度直接需要**的一份时,设 `"desktopArchivePin": { "vaultScope": "session|global", "id": "候选id", "title": "候选标题", "reason": "为何需要摆上一线桌面(30字内)" }`;不需要时**必须为 `null`**。严禁编造列表外的 ID 或触碰冷藏库;`AUTO_PILOT_SESSION_ONLY` 时严禁选 `global`。',
77
79
  '',
78
80
  '输出格式(严格 JSON):',
79
81
  '{',
@@ -90,10 +92,69 @@ const TURN_REVIEW_SYSTEM = [
90
92
  ' "interventionText": "",',
91
93
  ' "shouldCompactNow": false,',
92
94
  ' "compactReason": "",',
93
- ' "suggestions": []',
95
+ ' "suggestions": [],',
96
+ ' "desktopArchivePin": null',
94
97
  '}',
95
98
  ].join('\n')
96
99
 
100
+ function buildArchiveCandidates(deps, rootId, stateSnapshot, { autoPilot = false } = {}) {
101
+ if (!rootId || rootId === 'global') return []
102
+ try {
103
+ const vis = collectChiefVisibleArchives(deps, rootId, stateSnapshot)
104
+ const out = []
105
+ const seen = new Set()
106
+ const pushItem = (vaultScope, it) => {
107
+ if (!it || !it.id || it.takenOut) return
108
+ if (vaultScope !== 'session' && vaultScope !== 'global') return
109
+ const key = `${vaultScope}:${it.id}`
110
+ if (seen.has(key)) return
111
+ seen.add(key)
112
+ out.push({
113
+ vaultScope,
114
+ id: String(it.id),
115
+ title: String(it.title || it.id),
116
+ folder: String(it.folder || ''),
117
+ summary: String(it.summary || ''),
118
+ hasHook: Boolean(it.hasHook),
119
+ hookCue: String(it.hookCue || ''),
120
+ points: Array.isArray(it.points) ? it.points : [],
121
+ })
122
+ }
123
+ const sess = Array.isArray(vis && vis.sessionItems) ? vis.sessionItems : []
124
+ for (const it of sess.filter(x => x && !x.takenOut).slice(0, 5)) pushItem('session', it)
125
+ if (!autoPilot) {
126
+ const glob = Array.isArray(vis && vis.globalHookIndex) ? vis.globalHookIndex : []
127
+ for (const it of glob.filter(x => x && !x.takenOut).slice(0, 3)) pushItem('global', it)
128
+ }
129
+ return out.slice(0, 8)
130
+ } catch {
131
+ return []
132
+ }
133
+ }
134
+
135
+ function validateDesktopArchivePin(rawPin, candidates, { autoPilot = false, hazardStopped = false } = {}) {
136
+ if (hazardStopped || !rawPin || typeof rawPin !== 'object' || !Array.isArray(candidates) || !candidates.length) return null
137
+ const rawScope = String(rawPin.vaultScope || '').trim()
138
+ if (rawScope === 'precipitated') return null
139
+ if (autoPilot && rawScope && rawScope !== 'session') return null
140
+ const rawId = String(rawPin.id || '').trim()
141
+ const rawTitle = String(rawPin.title || '').trim()
142
+ if (!rawId && !rawTitle) return null
143
+ const matched = candidates.find(c =>
144
+ (!rawScope || c.vaultScope === rawScope)
145
+ && ((rawId && c.id === rawId) || (!rawId && rawTitle && c.title === rawTitle)),
146
+ )
147
+ if (!matched) return null
148
+ if (autoPilot && matched.vaultScope !== 'session') return null
149
+ const reason = clamp(String(rawPin.reason || '').trim() || '当前推进正高度命中该历史工程档案', 140)
150
+ return {
151
+ vaultScope: matched.vaultScope,
152
+ id: matched.id,
153
+ title: matched.title,
154
+ reason,
155
+ }
156
+ }
157
+
97
158
  /** High-precision backup safety net if the turn-review model missed `hazardStop.triggered` despite unmistakable irreversible hazard or boundary collision cues. */
98
159
  function detectEmergencyHazardFallback({ parsed, digestText = '', bounds = {}, isInterventionActive = false }) {
99
160
  const rawHs = parsed && parsed.hazardStop && typeof parsed.hazardStop === 'object' ? parsed.hazardStop : null
@@ -472,6 +533,9 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
472
533
  ? `智选共管状态(硬阈值已停用):消息数≈${digest.msgCount}${liveUsage && liveUsage.totalTokens ? `,当前估算上下文 ${liveUsage.totalTokens}/${liveUsage.contextWindow} (${Math.round((liveUsage.totalTokens / liveUsage.contextWindow) * 100)}%)` : ''}`
473
534
  : ''
474
535
 
536
+ const isAutoPilotBefore = Boolean(runMode === 'managed' && !effCfgBefore.stopped)
537
+ const archiveCandidates = buildArchiveCandidates(deps, rootId, loadChiefState(), { autoPilot: isAutoPilotBefore })
538
+
475
539
  const prompt = [
476
540
  `当前激活监督模式:${activeFlags.join(' | ') || runMode}`,
477
541
  ...(smartUsageHint ? [smartUsageHint] : []),
@@ -489,6 +553,11 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
489
553
  '',
490
554
  '已有持久记忆条目:',
491
555
  ...(numberedFacts.length ? numberedFacts.map((f, i) => `[${i + 1}] (${f.category}) ${f.text}`) : ['(暂无)']),
556
+ ...(archiveCandidates.length ? [
557
+ '',
558
+ '可用但尚未摆上认知桌面的可见档案(仅在当前推进高度直接需要时用 desktopArchivePin 调取 1 份,严禁为充数硬拉;冷藏库完全不可见):',
559
+ ...archiveCandidates.map(c => `- [${c.vaultScope} | id=${c.id}] 《${clamp(c.title, 44)}》${c.folder ? `(${clamp(c.folder, 20)})` : ''} ${clamp(c.hookCue || c.summary || (c.points && c.points[0] && c.points[0].title) || '', 90)}`),
560
+ ] : []),
492
561
  '',
493
562
  '本轮最新对话片段:',
494
563
  digest.text,
@@ -625,6 +694,14 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
625
694
  const autoBoundUpdates = []
626
695
  let shouldAutoOrganizeSession = false
627
696
 
697
+ const validatedArchivePin = validateDesktopArchivePin(parsed.desktopArchivePin, archiveCandidates, {
698
+ autoPilot,
699
+ hazardStopped: Boolean(hazardInfo && hazardInfo.triggered),
700
+ })
701
+ let desktopArchiveSuggestionQueued = false
702
+ let desktopArchiveApprovalQueued = false
703
+ let desktopArchivePinned = null
704
+
628
705
  const hasRunningChild = realPeers.some(p => p.kind === 'subagent' && p.status === 'running')
629
706
  const prematureCue = !(identity && identity.isChild)
630
707
  ? detectPrematurePromiseText(digest.lastAssistantText || '')
@@ -742,6 +819,42 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
742
819
  }
743
820
  }
744
821
 
822
+ if (validatedArchivePin && (permNow === 'advisor' || permNow === 'assistant')) {
823
+ const archSug = normalizeSuggestion({
824
+ kind: 'archive_op',
825
+ fromAgent: '🗂️ 档案调度参谋',
826
+ title: `📌 建议将《${clamp(validatedArchivePin.title, 28)}》摆上认知桌面`,
827
+ reason: validatedArchivePin.reason,
828
+ target: 'desktop',
829
+ targetLabel: clamp(validatedArchivePin.title, 28),
830
+ mode: 'silent',
831
+ draftText: `摆上桌面 《${validatedArchivePin.title}》`,
832
+ archiveSpec: {
833
+ op: 'pin_to_desktop',
834
+ vaultScope: validatedArchivePin.vaultScope,
835
+ id: validatedArchivePin.id,
836
+ title: validatedArchivePin.title,
837
+ instruction: validatedArchivePin.reason,
838
+ },
839
+ })
840
+ const dupArch = archSug && ws.suggestions.some(
841
+ existing => existing.status === 'pending'
842
+ && existing.kind === 'archive_op'
843
+ && existing.archiveSpec
844
+ && existing.archiveSpec.id === validatedArchivePin.id
845
+ && (existing.archiveSpec.vaultScope || 'session') === validatedArchivePin.vaultScope,
846
+ )
847
+ if (archSug && !dupArch) {
848
+ const pending = ws.suggestions.filter(item => item.status === 'pending')
849
+ if (pending.length >= 5) {
850
+ const victim = pending.find(item => item.kind !== 'bound' && item.kind !== 'goal_approval' && item.kind !== 'advice') || pending[0]
851
+ victim.status = 'dismissed'
852
+ }
853
+ ws.suggestions.push(archSug)
854
+ desktopArchiveSuggestionQueued = true
855
+ }
856
+ }
857
+
745
858
  // 0) Emergency hazard / boundary-collision gate takes highest priority under Strong Intervention
746
859
  if (hazardInfo.triggered && (tactical.intervention || autoPilot)) {
747
860
  hazardStopped = true
@@ -1221,6 +1334,80 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
1221
1334
  })
1222
1335
  }
1223
1336
 
1337
+ if (validatedArchivePin && !hazardStopped) {
1338
+ if (permNow === 'chief' && hasAckNow) {
1339
+ try {
1340
+ const archRes = await executeChiefArchiveInjectionOp(deps, rootId, {
1341
+ op: 'pin_to_desktop',
1342
+ vaultScope: validatedArchivePin.vaultScope,
1343
+ id: validatedArchivePin.id,
1344
+ title: validatedArchivePin.title,
1345
+ instruction: validatedArchivePin.reason,
1346
+ }, { by: 'chief', input: validatedArchivePin.reason })
1347
+ if (archRes && archRes.ok) {
1348
+ desktopArchivePinned = {
1349
+ ok: true,
1350
+ id: archRes.id,
1351
+ vaultScope: archRes.scope || validatedArchivePin.vaultScope,
1352
+ title: validatedArchivePin.title,
1353
+ actionText: archRes.actionText || '',
1354
+ evicted: Array.isArray(archRes.evicted) ? archRes.evicted : [],
1355
+ }
1356
+ if (typeof deps.appendBoardLog === 'function') {
1357
+ deps.appendBoardLog(rootId, `📌 参谋长主动取档上桌:《${clamp(validatedArchivePin.title, 36)}》`, 'DSH 参谋长')
1358
+ }
1359
+ mutateChiefState((s) => {
1360
+ const ws = ensureWorkspace(s, rootId)
1361
+ pushAuditToWs(ws, {
1362
+ mode: permNow,
1363
+ stage: 'review',
1364
+ rule: 'desktop_archive_pin',
1365
+ decision: 'executed',
1366
+ operation: '推档案上认知桌面',
1367
+ target: clamp(validatedArchivePin.title, 60),
1368
+ reason: validatedArchivePin.reason,
1369
+ outcome: 'ok',
1370
+ by: 'chief',
1371
+ })
1372
+ ws.chat.push({
1373
+ id: nextId('chat'),
1374
+ role: 'chief',
1375
+ kind: 'receipt',
1376
+ ...(res.thinkingEffort ? { thinkingEffort: res.thinkingEffort } : {}),
1377
+ ...(res.thinkingEffortMode ? { thinkingEffortMode: res.thinkingEffortMode } : {}),
1378
+ text: `- 【📌 参谋长主动取档上桌】已将《${clamp(validatedArchivePin.title, 48)}》(${validatedArchivePin.vaultScope === 'global' ? '全局档案柜' : '本会话档案柜'}) 推入主对话桌面(${validatedArchivePin.reason})。`,
1379
+ actions: [`📌 推档上桌 《${clamp(validatedArchivePin.title, 18)}》`],
1380
+ at: Date.now(),
1381
+ })
1382
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
1383
+ })
1384
+ }
1385
+ } catch {}
1386
+ } else if (permNow === 'strategist') {
1387
+ const refTitle = validatedArchivePin.title || validatedArchivePin.id
1388
+ queueChiefApproval(rootId, {
1389
+ category: 'archive_op',
1390
+ operationLabel: '推档案上认知桌面',
1391
+ targetLabel: refTitle,
1392
+ reason: validatedArchivePin.reason,
1393
+ impact: '允许后将该档案置顶到当前会话认知桌面,下一轮自动注入主对话视图',
1394
+ preview: `[${validatedArchivePin.vaultScope}] 《${refTitle}》 (id=${validatedArchivePin.id})`,
1395
+ dedupeKey: `archpin:${rootId}:${validatedArchivePin.vaultScope}:${validatedArchivePin.id}`,
1396
+ kind: 'archive_op',
1397
+ capabilityScope: buildCapabilityScope({ kind: 'archive_op', tool: 'archive_op', target: refTitle }),
1398
+ payload: {
1399
+ op: 'pin_to_desktop',
1400
+ vaultScope: validatedArchivePin.vaultScope,
1401
+ id: validatedArchivePin.id,
1402
+ title: validatedArchivePin.title,
1403
+ instruction: validatedArchivePin.reason,
1404
+ },
1405
+ by: 'chief',
1406
+ })
1407
+ desktopArchiveApprovalQueued = true
1408
+ }
1409
+ }
1410
+
1224
1411
  let autoPilotStopRes = null
1225
1412
  if (autoPilot && !interventionMessage && autoRelays.length === 0 && !circuitTripped) {
1226
1413
  autoPilotStopRes = await checkAndStopIdleAutoPilot(deps, rootId, {
@@ -1250,6 +1437,9 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
1250
1437
  ...(res.thinkingEffortMode ? { thinkingEffortMode: res.thinkingEffortMode } : {}),
1251
1438
  ...(dreamRoamRes ? { dreamRoam: dreamRoamRes } : {}),
1252
1439
  ...(oneStopReport ? { oneStopReport } : {}),
1440
+ ...(desktopArchivePinned ? { desktopArchivePinned } : {}),
1441
+ ...(desktopArchiveApprovalQueued ? { desktopArchiveApprovalQueued } : {}),
1442
+ ...(desktopArchiveSuggestionQueued ? { desktopArchiveSuggestionQueued } : {}),
1253
1443
  ...(autoPilotStopRes ? { autoPilotStopped: Boolean(autoPilotStopRes.stopped) } : {}),
1254
1444
  }
1255
1445
  } finally {