dsh-chief 1.2.1 → 1.3.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-view.js ADDED
@@ -0,0 +1,553 @@
1
+ /**
2
+ * chief-view.js
3
+ *
4
+ * Situation awareness view, narrative synthesis, and concise fallback reports for DSH Chief.
5
+ */
6
+
7
+ import crypto from 'node:crypto'
8
+ import { stripToolCallMarkup } from './chief-executor.js'
9
+ import {
10
+ AUTO_SUMMARY_COOLDOWN_MS,
11
+ SUMMARY_MAX_TOKENS,
12
+ collectChiefVisibleArchives,
13
+ clamp,
14
+ resolveWorkspaceConfig,
15
+ loadChiefState,
16
+ mutateChiefState,
17
+ computeClusterSig,
18
+ ensureWorkspace,
19
+ clusterView,
20
+ shortAgentBriefName,
21
+ stripCheckpointNoise,
22
+ isInternalCheckpointNoise,
23
+ } from './chief-state.js'
24
+ import { listChiefModels, callChiefLlm } from './chief-models.js'
25
+ import { collectClusterPeerProgress, listPeerDirectory } from './chief-network.js'
26
+
27
+ let idleAutoPilotHook = null
28
+
29
+ export function registerIdleAutoPilotHook(fn) {
30
+ idleAutoPilotHook = typeof fn === 'function' ? fn : null
31
+ }
32
+
33
+ const SUMMARY_FORMAT_REV = 'v5-six-goal-lines'
34
+
35
+ const NARRATIVE_SYSTEM = [
36
+ '你是「DSH 参谋长」(如同统揽全局的宰相),负责把当前工作区和协同团队的目标、进展、纪律与红线边界,提炼成用户一眼扫完就能掌握全局的「摘要」。',
37
+ '严格遵守以下【简明结构化 · 分点作答】规范:',
38
+ '1. 使用简体中文,语气精炼干脆、直击要害,严禁寒暄套话与冗长铺垫。',
39
+ '2. 全文分为 2 到 4 个模块,每个模块以一行 `## 模块短标题` 开头(如 `## 核心目标与态势`、`## 关键结论与进展`、`## 协作纪律与红线`、`## 协作纪律与边界`)。',
40
+ '3. **每个模块下方必须全部使用 `- ` 分点列表作答(严禁写成挤在一起的长段落散文!)**。每一点控制在 1 行(最多不超过 2 行),推荐在要点开头用方括号短标签提亮,如 `- 【总目标】…`、`- 【推进中】…`、`- 【已完】…`、`- 【已验证】…`、`- 【结论】…`、`- 【待办】…`、`- 【待收尾】…`、`- 【注意】…`、`- 【归因纪律】…`、`- 【收尾纪律】…`、`- 【并列直接原因】…`、`- 【受阻】…`、`- 【禁止红线】…`、`- 【必做事项】…`。',
41
+ '4. **去噪与聚合铁律**:遇到大量同前缀或已结束的后台巡检子代理(如 `mnemon-review-*`),**严禁逐一报菜名罗列**,必须合并成一句话统计;自动忽略 `[dsh-mnemon:...]` 等系统内部检查点噪音。',
42
+ '5. 具体路径、端口、版本号、命令原样保留,同一事实绝不重复,只陈述真实输入,第一个 `## ` 之前不要输出任何多余字符。',
43
+ ].join('\n')
44
+
45
+ const CONCISE_BRIEF_NARRATIVE_EXTRA = [
46
+ '',
47
+ '⚡ 【当前已开启极简战报模式 — 六句话目标边界系列(最高优先级覆盖一切细节规则!)】:',
48
+ '- **一切以目标为导向,说人话,拒绝任何事务细节**:严禁出现任何文件路径、文件名、代码符号/函数名、行号、端口号、Token/字节数、耗时、版本号、终端命令或具体计数统计!',
49
+ '- **严格只输出如下 1 个标题 + 刚好 6 行单句列表(不要多也不要少)**:',
50
+ ' ## 极简目标战报',
51
+ ' - 【🎯 总目标】用一句人话说清最终要达成的目标。',
52
+ ' - 【🚀 当前推进目标】用一句人话说清现在正聚焦推进的阶段目标。',
53
+ ' - 【⛔ 受阻目标】若无受阻写“当前暂无受阻目标”;若有受阻,用一句人话点明卡住的目标与原因。',
54
+ ' - 【🧰 需要什么】用一句人话说明达成目标还缺的前提、验证或支撑条件(无则写“条件已齐备,可顺畅推进”)。',
55
+ ' - 【🙋 用户需要提供什么】若需要您拍板、授权、提供账号/素材或重启确认写一句人话;无需操作写“暂无需您额外提供,可继续推进”。',
56
+ ' - 【💡 参谋长建议】用一句人话给出最清晰可执行的建议或建议弹窗拍板方向。',
57
+ '- 每条控制在 1 句精炼大白话(20~55 字),切忌写成事务流水账或代码改动清单!',
58
+ ].join('\n')
59
+
60
+ /** Remove or qualitatively normalize raw numeric parameters, file paths & technical trivia when Concise Brief Mode (`极简战报模式`) is enabled. */
61
+ export function sanitizeConciseBriefText(text) {
62
+ const src = String(text || '')
63
+ if (!src.trim()) return ''
64
+ return src
65
+ .replace(/[A-Za-z]:\\[^\s"'`))】]+/g, '本地相关目录')
66
+ .replace(/(?:^|\s)\/(?:[\w.-]+\/)+[\w.-]*/g, ' 相关路径')
67
+ .replace(/\b[\w.-]+\.(?:m?[jt]sx?|py|json|ya?ml|md|css|html|sh|ps1)\b/gi, '相关模块')
68
+ .replace(/`[^`]{2,64}`/g, '对应能力')
69
+ .replace(/\bv?\d+\.\d+\.\d+(?:-[a-z0-9.]+)?\b/gi, '当前版本')
70
+ .replace(/\bL\d+(?:\s*[-~–]\s*L?\d+)?\b/g, '相关位置')
71
+ .replace(/:\d{2,5}\b/g, '')
72
+ .replace(/(?:端口|port)\s*\d{2,5}/gi, '对应端口')
73
+ .replace(/(?:第)\s*\d+(?:\.\d+)?\s*(?:行|页|步|轮|阶段)/gi, '当前阶段')
74
+ .replace(/(?:耗时|用时|约|共|已有|剩余|累计|包含|存在|触发|达到|占比)\s*\d+(?:\.\d+)?\s*(?:ms|s|毫秒|秒|分钟|小时|天|字节|bytes?|KB|MB|GB|K|M|%|%|项|个|条|卷|次|步|轮|行|页|张|名|家|处)/gi, (m) => {
75
+ if (/(?:%|%)/.test(m)) return '相应比例'
76
+ if (/(?:ms|s|毫秒|秒|分钟|小时)/.test(m)) return '短暂耗时'
77
+ if (/(?:KB|MB|GB|K|M|字节|bytes?)/i.test(m)) return '一定体量'
78
+ return '若干进展'
79
+ })
80
+ .replace(/\b\d+(?:\.\d+)?\s*(?:%|%)/g, '相应比例')
81
+ .replace(/\b\d+(?:\.\d+)?\s*(?:ms|毫秒|KB|MB|GB)(?![a-z0-9_])/gi, '相应规模')
82
+ .replace(/(^|\s)#\d+\b/g, '$1该目标')
83
+ .replace(/\b\d{3,}\b/g, '若干')
84
+ .replace(/(?<=[\u4e00-\u9fa5\s])\d+(?=[\s]*(?:项|个|条|卷|次|步|轮|名|处|份|行))/g, '若干')
85
+ .replace(/[ \t]{2,}/g, ' ')
86
+ .replace(/\n{3,}/g, '\n\n')
87
+ .trim()
88
+ }
89
+
90
+ /** Synthesize the 6-line goal-only human report (`六句话目标边界系列`) shared by Narrative fallback & AskChief fallback. */
91
+ export function buildConciseSixLineReport({ board, blocked = [], doing = [], todo = [], done = [], workers = [], suggestions = [], needFromUserHint = '' }) {
92
+ const clean = (s, max = 54) => sanitizeConciseBriefText(clamp(String(s || '').replace(/\s+/g, ' ').trim(), max))
93
+ const planSteps = Array.isArray(board && board.plan) ? board.plan.filter(Boolean) : []
94
+ const openPlan = planSteps.filter(s => !s.done)
95
+ const donePlan = planSteps.filter(s => s.done)
96
+ const objText = (board && board.objective) ? clean(board.objective, 56) : '按您当前的指令完成本阶段目标'
97
+ let curText = '等待您确认方向后启动推进'
98
+ if (doing.length > 0) {
99
+ curText = clean(doing[0].title, 54)
100
+ } else if (blocked.length > 0) {
101
+ curText = '正聚焦排查并疏通受阻目标:' + clean(blocked[0].title, 44)
102
+ } else if (todo.length > 0) {
103
+ curText = '准备推进下一项目标:' + clean(todo[0].title, 46)
104
+ } else if (openPlan.length > 0) {
105
+ curText = clean(openPlan[0].text, 54)
106
+ } else if (done.length > 0 || (donePlan.length > 0 && !openPlan.length)) {
107
+ curText = '本阶段核心事项已基本收尾,待核对确认后交卷'
108
+ }
109
+
110
+ let blockedText = '当前暂无受阻目标,推进链路顺畅'
111
+ if (blocked.length > 0) {
112
+ const b0 = blocked[0]
113
+ blockedText = clean(b0.title, 40) + (b0.note ? '(症结:' + clean(b0.note, 34) + ')' : '(需排查卡点条件)')
114
+ }
115
+
116
+ let needWhatText = '前提条件与执行环境基本齐备,可按既定节奏完成验证与收尾'
117
+ if (blocked.length > 0) {
118
+ needWhatText = '需要先解除受阻卡点并补齐相关前置验证条件'
119
+ } else if (todo.length > 0 && workers.some(w => w.status === 'running')) {
120
+ needWhatText = '需要等当前并行协作收口并完成关键结果核验'
121
+ } else if (todo.length > 0) {
122
+ needWhatText = '需要按序完成剩余收尾环节与最终效果检验'
123
+ } else if (openPlan.length > 0) {
124
+ needWhatText = '需要推进或确认当前待完成环节:' + clean(openPlan[0].text, 40)
125
+ } else if (!board || !board.objective) {
126
+ needWhatText = '需要明确具体的最终验收标准或本轮预期效果'
127
+ }
128
+
129
+ const pendingBoundOrApproval = (Array.isArray(suggestions) ? suggestions : []).find(
130
+ s => s && s.status === 'pending' && (s.kind === 'goal_approval' || s.kind === 'bound' || s.kind === 'advice'),
131
+ )
132
+ let userNeedText = '暂无需您额外提供,参谋长与主对话可继续自动推进'
133
+ if (needFromUserHint) {
134
+ userNeedText = clean(needFromUserHint, 54)
135
+ } else if (pendingBoundOrApproval) {
136
+ userNeedText = '请您查看并拍板确认「' + clean(pendingBoundOrApproval.title, 38) + '」'
137
+ } else if (blocked.length > 0 && /权限|登录|账号|密钥|token|重启|确认|决定|选择/i.test(String(blocked[0].note || blocked[0].title || ''))) {
138
+ userNeedText = '需要您协助授权、提供凭据或拍板选定解决路线'
139
+ } else if (openPlan.length > 0 && /用户|确认|拍板|点头|决定|选择/.test(String(openPlan[0].text || ''))) {
140
+ userNeedText = '需要您拍板选定下一步路线:' + clean(openPlan[0].text, 38)
141
+ }
142
+
143
+ let adviceText = '建议保持当前推进节奏,收口前做一轮完整实测核对即可交卷'
144
+ if (pendingBoundOrApproval && pendingBoundOrApproval.kind === 'advice') {
145
+ adviceText = clean(pendingBoundOrApproval.reason || pendingBoundOrApproval.draftText || pendingBoundOrApproval.title, 54)
146
+ } else if (blocked.length > 0) {
147
+ adviceText = '建议先集中解决首要受阻目标,必要时由参谋长向主对话插话纠偏'
148
+ } else if (openPlan.length > 0 && doing.length === 0 && todo.length === 0) {
149
+ adviceText = '建议按当前待定环节及时确认方向,确认后即可顺畅续跑'
150
+ } else if (todo.length > 0) {
151
+ adviceText = '建议优先收拢在手推进项,顺势拿下紧接的待办目标'
152
+ } else if ((done.length > 0 || (donePlan.length > 0 && !openPlan.length)) && !doing.length && !todo.length) {
153
+ adviceText = '建议您核对整体表现,满意后即可批准结项或开启下一目标'
154
+ }
155
+
156
+ return [
157
+ '## 极简目标战报',
158
+ `- 【🎯 总目标】${objText}`,
159
+ `- 【🚀 当前推进目标】${curText}`,
160
+ `- 【⛔ 受阻目标】${blockedText}`,
161
+ `- 【🧰 需要什么】${needWhatText}`,
162
+ `- 【🙋 用户需要提供什么】${userNeedText}`,
163
+ `- 【💡 参谋长建议】${adviceText}`,
164
+ ].join('\n')
165
+ }
166
+
167
+ export function summarizeSubagentsCompact(workers) {
168
+ if (!Array.isArray(workers) || workers.length === 0) return ''
169
+ const running = workers.filter(w => w.status === 'running')
170
+ const idle = workers.filter(w => w.status !== 'running')
171
+ const parts = []
172
+ if (running.length > 0) {
173
+ const detail = running.slice(0, 4).map(w => {
174
+ const cleanTask = w.taskTitle && !isInternalCheckpointNoise(w.taskTitle) ? `(推进:${clamp(w.taskTitle, 28)})` : ''
175
+ return `@${shortAgentBriefName(w.name)}${cleanTask}`
176
+ }).join('、')
177
+ parts.push(`${running.length} 运行中:${detail}${running.length > 4 ? ' 等' : ''}`)
178
+ }
179
+ if (idle.length > 0) {
180
+ if (running.length === 0 && idle.length <= 3) {
181
+ parts.push(`待命:${idle.map(w => '@' + shortAgentBriefName(w.name)).join('、')}`)
182
+ } else {
183
+ parts.push(`${idle.length} 已结束/待命`)
184
+ }
185
+ }
186
+ return `共 ${workers.length} 名子代理(${parts.join(';')})`
187
+ }
188
+
189
+ function buildNarrativeInput({ board, facts, cluster, targets, peerProgress = [], archiveDigest = null }) {
190
+ const bounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
191
+ const tasks = Array.isArray(board && board.tasks) ? board.tasks : []
192
+ const memory = (Array.isArray(board && board.memory) ? board.memory : [])
193
+ .filter(m => m && !isInternalCheckpointNoise(m.title || m.text))
194
+ const anchors = (Array.isArray(board && board.notes) ? board.notes : []).filter(n => (n.tags || []).includes('anchor'))
195
+
196
+ const lines = []
197
+ if (board && board.objective) lines.push(`当前总目标:${board.objective}`)
198
+ if ((bounds.forbidden || []).length) lines.push(`禁止红线:${bounds.forbidden.join(';')}`)
199
+ if ((bounds.allowed || []).length) lines.push(`必做事项:${bounds.allowed.join(';')}`)
200
+ if ((bounds.notes || []).length) lines.push(`边界注意:${bounds.notes.join(';')}`)
201
+
202
+ if (cluster.length > 1) {
203
+ lines.push(`跨窗口协同频道:当前已串联 ${cluster.length} 个主对话窗口协同作业(网络内自动共享进度)。`)
204
+ }
205
+ if (Array.isArray(peerProgress) && peerProgress.length > 0) {
206
+ lines.push('', '【协同对话网络共享进度】')
207
+ for (const p of peerProgress) {
208
+ lines.push(`- 联动对话「${p.name}」[${p.status === 'running' ? '🟢运行中' : '⚪空闲'}]:目标="${p.objective || '未设'}" | 任务=${p.doneCount}完/${p.doingCount}做/${p.blockedCount}阻/${p.todoCount}待${p.cursorStep ? ` | 断点=${p.cursorStep}` : ''}`)
209
+ if (Array.isArray(p.topTasks) && p.topTasks.length) {
210
+ lines.push(` · 在手任务:${p.topTasks.join(';')}`)
211
+ }
212
+ if (Array.isArray(p.recentConclusions) && p.recentConclusions.length) {
213
+ lines.push(` · 近期结论:${p.recentConclusions.join(';')}`)
214
+ }
215
+ }
216
+ }
217
+ const activeWorkers = targets.filter(t => t.kind === 'subagent' && !/^mnemon-(?:review|run)/i.test(String(t.name || t.key || '')))
218
+ if (activeWorkers.length > 0) {
219
+ lines.push(`子代理态势:${summarizeSubagentsCompact(activeWorkers)}`)
220
+ }
221
+
222
+ if (facts.length > 0) {
223
+ lines.push('', '【持久记忆与纪律条目】')
224
+ for (const f of facts) {
225
+ lines.push(`- [${f.category}] ${f.text}`)
226
+ }
227
+ }
228
+
229
+ if (anchors.length > 0) {
230
+ lines.push('', '【关键锚点笔记】')
231
+ for (const a of anchors.slice(0, 8)) {
232
+ lines.push(`- ${a.title}:${clamp(a.body, 220)}`)
233
+ }
234
+ }
235
+
236
+ if (tasks.length > 0) {
237
+ const done = tasks.filter(t => t.status === 'done')
238
+ const open = tasks.filter(t => t.status !== 'done')
239
+ lines.push('', '【任务图态势】')
240
+ for (const t of open.slice(0, 10)) {
241
+ lines.push(`- 未完 [${t.status}] #${t.id} ${t.title}${t.owner ? '(@' + shortAgentBriefName(t.owner) + ')' : ''}${t.note ? ':' + clamp(t.note, 120) : ''}`)
242
+ }
243
+ for (const t of done.slice(-8)) {
244
+ lines.push(`- 已完 #${t.id} ${t.title}${t.evidence ? '(证据:' + clamp(t.evidence, 140) + ')' : ''}`)
245
+ }
246
+ }
247
+
248
+ if (memory.length > 0) {
249
+ lines.push('', '【近期回合关键结论】')
250
+ for (const m of memory.slice(-10)) {
251
+ const cleaned = stripCheckpointNoise(m.title || m.text)
252
+ if (cleaned) lines.push(`- [${m.section}] ${clamp(cleaned, 180)}`)
253
+ }
254
+ }
255
+
256
+ if (archiveDigest) {
257
+ const dSess = Array.isArray(archiveDigest.deskSessionItems) ? archiveDigest.deskSessionItems : []
258
+ const dGlob = Array.isArray(archiveDigest.deskGlobalItems) ? archiveDigest.deskGlobalItems : []
259
+ const dFlip = Array.isArray(archiveDigest.deskFlippedItems) ? archiveDigest.deskFlippedItems : []
260
+ const mGlob = Array.isArray(archiveDigest.mountedGlobalItems) ? archiveDigest.mountedGlobalItems : []
261
+ const sw = archiveDigest.sealedWatch || {}
262
+ const deskAll = [
263
+ ...dSess.map(it => `[桌面·本局(主可见)] 《${clamp(it.title, 40)}》:${clamp(it.summary || it.body, 140)}`),
264
+ ...dGlob.map(it => `[桌面·全局(主可见)] 《${clamp(it.title, 40)}》:${clamp(it.summary || it.body, 140)}`),
265
+ ...dFlip.map(it => `[桌面·沉淀(主可见)] 《${clamp(it.title, 40)}》:${clamp(it.summary || it.rawBody, 140)}`),
266
+ ]
267
+ if (deskAll.length > 0) {
268
+ lines.push('', '【当前摆上桌面备选(重点强调,主对话与参谋长共同可见)】', ...deskAll.slice(0, 8).map(x => '- ' + x))
269
+ }
270
+ if (mGlob.length > 0) {
271
+ lines.push('', '【参谋长单独参阅中的全局档案(主对话不可见)】')
272
+ for (const it of mGlob.slice(0, 5)) {
273
+ lines.push(`- [全局参阅] 《${clamp(it.title, 40)}》:${clamp(it.summary || it.body, 120)}`)
274
+ }
275
+ }
276
+ const sealedLines = [
277
+ ...((sw.sessionSealed || []).slice(0, 4).map(it => `- [本局封存·仅参谋关注] 《${clamp(it.title, 36)}》:${clamp(it.summary, 90)}`)),
278
+ ...((sw.globalSealed || []).slice(0, 4).map(it => `- [全局封存·仅参谋关注] 《${clamp(it.title, 36)}》:${clamp(it.summary, 90)}`)),
279
+ ...((sw.precipSealed || []).slice(0, 3).map(it => `- [沉淀封存·仅参谋关注] 《${clamp(it.title, 36)}》:${clamp(it.summary, 90)}`)),
280
+ ]
281
+ if (sealedLines.length > 0) {
282
+ lines.push('', '【参谋长后台守望的三库封存索引(主对话上下文零注入)】', ...sealedLines)
283
+ }
284
+ }
285
+
286
+ return lines.join('\n').trim()
287
+ }
288
+
289
+ /** Deterministic structured bullet summary when no LLM key is configured or while first summary is warming up. */
290
+ function buildFallbackNarrative({ board, facts, targets, peerProgress = [], conciseBrief = false, suggestions = [] }) {
291
+ const sections = []
292
+ const tasks = Array.isArray(board && board.tasks) ? board.tasks : []
293
+ const blocked = tasks.filter(t => t.status === 'blocked')
294
+ const doing = tasks.filter(t => t.status === 'doing')
295
+ const todo = tasks.filter(t => t.status === 'todo')
296
+ const done = tasks.filter(t => t.status === 'done')
297
+ const workers = targets.filter(t => t.kind === 'subagent' && !/^mnemon-(?:review|run)/i.test(String(t.name || t.key || '')))
298
+
299
+ if (conciseBrief) {
300
+ return buildConciseSixLineReport({ board, blocked, doing, todo, done, workers, suggestions })
301
+ }
302
+
303
+ const statusBullets = []
304
+ if (board && board.objective) {
305
+ statusBullets.push(`- 【总目标】${clamp(board.objective, 150)}`)
306
+ }
307
+ for (const b of blocked.slice(0, 4)) {
308
+ statusBullets.push(`- 【受阻】${clamp(b.title, 70)}${b.note ? ' — ' + clamp(b.note, 70) : ''}`)
309
+ }
310
+ for (const d of doing.slice(0, 4)) {
311
+ const who = d.subagent || d.owner ? `(@${shortAgentBriefName(d.subagent || d.owner)})` : ''
312
+ statusBullets.push(`- 【推进中】${clamp(d.title, 72)}${who}`)
313
+ }
314
+ if (tasks.length > 0) {
315
+ statusBullets.push(`- 【任务进度】已完成 ${done.length} 项 / 推进中 ${doing.length} 项 / 受阻 ${blocked.length} 项 / 待推进 ${todo.length} 项`)
316
+ }
317
+ if (workers.length > 0) {
318
+ statusBullets.push(`- 【子代理团队】${summarizeSubagentsCompact(workers)}`)
319
+ }
320
+ if (Array.isArray(peerProgress) && peerProgress.length > 0) {
321
+ for (const p of peerProgress.slice(0, 4)) {
322
+ statusBullets.push(`- 【协同进度·${clamp(p.name, 22)}】${p.objective ? clamp(p.objective, 70) + ' · ' : ''}任务 ${p.doneCount}完/${p.doingCount}做${p.blockedCount ? `/${p.blockedCount}阻` : ''}${p.cursorStep ? '(断点:' + clamp(p.cursorStep, 32) + ')' : ''}`)
323
+ }
324
+ }
325
+ if (statusBullets.length > 0) {
326
+ sections.push('## 核心目标与态势\n' + statusBullets.join('\n'))
327
+ }
328
+
329
+ const otherFacts = facts.filter(f => f.category !== 'discipline' && f.category !== 'preference')
330
+ const mem = (Array.isArray(board && board.memory) ? board.memory : [])
331
+ .filter(m => m && !isInternalCheckpointNoise(m.title || m.text))
332
+ .slice(-5)
333
+ const progressBullets = [
334
+ ...otherFacts.slice(-5).map(f => `- 【结论】${clamp(stripCheckpointNoise(f.text), 130)}`),
335
+ ...mem.map(m => `- 【进展】${clamp(stripCheckpointNoise(m.title || m.text), 120)}`),
336
+ ]
337
+ if (progressBullets.length > 0) {
338
+ sections.push('## 关键结论与进展\n' + progressBullets.join('\n'))
339
+ }
340
+
341
+ const bounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
342
+ const disciplines = facts.filter(f => f.category === 'discipline' || f.category === 'preference')
343
+ const ruleBullets = []
344
+ for (const f of (bounds.forbidden || []).slice(0, 6)) ruleBullets.push(`- 【禁止红线】${clamp(f, 110)}`)
345
+ for (const a of (bounds.allowed || []).slice(0, 4)) ruleBullets.push(`- 【必做事项】${clamp(a, 110)}`)
346
+ for (const n of (bounds.notes || []).slice(0, 3)) ruleBullets.push(`- 【注意事项】${clamp(n, 110)}`)
347
+ for (const d of disciplines.slice(-5)) ruleBullets.push(`- 【协作纪律】${clamp(d.text, 120)}`)
348
+ if (ruleBullets.length > 0) {
349
+ sections.push('## 协作纪律与边界\n' + ruleBullets.join('\n'))
350
+ }
351
+
352
+ if (sections.length === 0) {
353
+ return '## 尚无沉淀摘要\n- 【状态】当前会话刚启动,暂未沉淀阶段结论或红线纪律\n- 【用法】可在下方参谋栏直接立规矩、查进展,或用一句话拆话调度主对话与各子代理'
354
+ }
355
+ return sections.join('\n\n')
356
+ }
357
+
358
+ export const summarizingLocks = new Map()
359
+
360
+ export async function getChiefView(deps, sessionId, { regenerate = false, autoSummarize = false, syncHandoff = undefined, _skipAutoPilotCheck = false } = {}) {
361
+ const rootId = deps.resolveRootSessionId(sessionId) || String(sessionId || 'global')
362
+ const directory = await listPeerDirectory(deps, rootId)
363
+ const board = deps.boardForSession(deps.boardFileFor(rootId))
364
+ const state = loadChiefState()
365
+ const view = clusterView(state, rootId)
366
+ const modelsInfo = await listChiefModels(deps, false, rootId)
367
+ const effCfgBefore = resolveWorkspaceConfig(state, rootId)
368
+ const paceMode = effCfgBefore.paceMode || 'manual'
369
+ const isConciseBrief = Boolean(effCfgBefore.tacticalModes && effCfgBefore.tacticalModes.conciseBrief)
370
+ const currentSig = view.clusterSig || computeClusterSig(directory.cluster)
371
+ const peerProgress = directory.cluster.length > 1
372
+ ? collectClusterPeerProgress(deps, directory.cluster, rootId)
373
+ : []
374
+ const archiveDigest = collectChiefVisibleArchives(deps, rootId, state)
375
+
376
+ const rawInput = buildNarrativeInput({
377
+ board,
378
+ facts: view.facts,
379
+ cluster: directory.cluster,
380
+ targets: directory.targets,
381
+ peerProgress,
382
+ archiveDigest,
383
+ })
384
+ const inputHash = rawInput
385
+ ? crypto.createHash('sha256').update(SUMMARY_FORMAT_REV + '\n' + (isConciseBrief ? 'concise:1' : 'concise:0') + '\n' + currentSig + '\n' + rawInput).digest('hex').slice(0, 24)
386
+ : 'empty'
387
+
388
+ const isClusterSigValid = (nar) => {
389
+ if (!nar || !nar.text) return false
390
+ if (nar.clusterSig && nar.clusterSig !== currentSig) return false
391
+ if (!nar.clusterSig && directory.cluster.length > 1) return false
392
+ return true
393
+ }
394
+
395
+ const hasSaved = isClusterSigValid(view.narrative)
396
+ const lastSummaryAt = Number((view.narrative && view.narrative.at) || 0)
397
+ const isFresh = !rawInput || (hasSaved && view.narrative.hash === inputHash)
398
+ const cooledForAuto = Date.now() - lastSummaryAt >= AUTO_SUMMARY_COOLDOWN_MS
399
+ const allowBackgroundSummary = paceMode === 'auto' && autoSummarize && !isFresh && cooledForAuto
400
+
401
+ // Human-paced rule: ONLY call LLM when operator explicitly clicked Regenerate (`regenerate: true`),
402
+ // OR when operator explicitly chose `paceMode === 'auto'` AND the 5-minute cooldown has elapsed!
403
+ if (rawInput && (regenerate || allowBackgroundSummary) && modelsInfo.available && !summarizingLocks.has(rootId)) {
404
+ const job = (async () => {
405
+ const sysPrompt = isConciseBrief
406
+ ? (NARRATIVE_SYSTEM + CONCISE_BRIEF_NARRATIVE_EXTRA)
407
+ : NARRATIVE_SYSTEM
408
+ const res = await callChiefLlm(deps, {
409
+ sessionId: rootId,
410
+ system: sysPrompt,
411
+ prompt: rawInput + (isConciseBrief
412
+ ? '\n\n请开启【极简战报模式】:分结构列出多个简明短句,不写具体数字参数,精确概括现状:'
413
+ : '\n\n请按上述规范输出简体中文摘要:'),
414
+ maxTokens: SUMMARY_MAX_TOKENS,
415
+ })
416
+ if (res.ok && res.text) {
417
+ const finalNarText = isConciseBrief ? sanitizeConciseBriefText(res.text) : res.text
418
+ mutateChiefState((s) => {
419
+ const ws = ensureWorkspace(s, rootId)
420
+ ws.narrative = {
421
+ hash: inputHash,
422
+ text: finalNarText,
423
+ at: Date.now(),
424
+ byModel: res.modelRef || '',
425
+ clusterSig: currentSig,
426
+ }
427
+ })
428
+ }
429
+ })().finally(() => {
430
+ summarizingLocks.delete(rootId)
431
+ })
432
+ summarizingLocks.set(rootId, job)
433
+ if (regenerate) {
434
+ await job.catch(() => {})
435
+ }
436
+ }
437
+
438
+ const latestState = loadChiefState()
439
+ const latestView = clusterView(latestState, rootId)
440
+ const hasLatestSaved = isClusterSigValid(latestView.narrative)
441
+ const latestFresh = !rawInput || (hasLatestSaved && latestView.narrative.hash === inputHash)
442
+ const narrativeText = (hasLatestSaved && (!isConciseBrief || latestFresh))
443
+ ? (isConciseBrief ? sanitizeConciseBriefText(latestView.narrative.text) : latestView.narrative.text)
444
+ : buildFallbackNarrative({ board, facts: latestView.facts, targets: directory.targets, peerProgress, conciseBrief: isConciseBrief, suggestions: latestView.suggestions })
445
+
446
+ // Optional 1-click Handoff Packet Sync on Digest regeneration or explicit sync request (strictly blocked if pinned by human!)
447
+ let handoffSyncResult = null
448
+ const latestBoardBeforeSync = deps.boardForSession(deps.boardFileFor(rootId))
449
+ const shouldSyncHandoff = syncHandoff !== undefined
450
+ ? Boolean(syncHandoff)
451
+ : Boolean(regenerate && latestBoardBeforeSync && latestBoardBeforeSync.handoff && latestBoardBeforeSync.handoff.syncOnDigest)
452
+ if (shouldSyncHandoff && typeof deps.runAction === 'function') {
453
+ const isPinned = Boolean(latestBoardBeforeSync && latestBoardBeforeSync.handoff && latestBoardBeforeSync.handoff.pinned)
454
+ if (isPinned) {
455
+ handoffSyncResult = {
456
+ synced: false,
457
+ skipped: 'pinned-by-human',
458
+ reason: 'pinned',
459
+ message: '交接单已被人工定住,参谋长跳过自动覆写',
460
+ }
461
+ } else {
462
+ const composed = typeof deps.composeHandoffFromNarrative === 'function'
463
+ ? deps.composeHandoffFromNarrative(rootId, narrativeText)
464
+ : ''
465
+ if (composed && composed.trim()) {
466
+ const saveRes = deps.runAction({
467
+ action: 'handoff.save',
468
+ session: rootId === 'global' ? '' : rootId,
469
+ by: 'chief',
470
+ source: 'chief',
471
+ text: composed,
472
+ })
473
+ const isLocked = Boolean(saveRes && (saveRes.pinned || saveRes.locked))
474
+ handoffSyncResult = saveRes && saveRes.ok
475
+ ? { synced: true, at: Date.now() }
476
+ : {
477
+ synced: false,
478
+ ...(isLocked ? { skipped: 'pinned-by-human' } : {}),
479
+ reason: isLocked ? 'pinned' : 'error',
480
+ message: (saveRes && saveRes.error) || '同步失败',
481
+ }
482
+ }
483
+ }
484
+ }
485
+
486
+ const ownWsBeforeStop = ensureWorkspace(latestState, rootId)
487
+ const effectiveConfigBeforeStop = resolveWorkspaceConfig(latestState, rootId)
488
+ if (
489
+ !_skipAutoPilotCheck
490
+ && rootId
491
+ && rootId !== 'global'
492
+ && effectiveConfigBeforeStop.autoPilot
493
+ && effectiveConfigBeforeStop.paceMode === 'auto'
494
+ && !effectiveConfigBeforeStop.stopped
495
+ ) {
496
+ if (idleAutoPilotHook) {
497
+ await idleAutoPilotHook(deps, rootId, {
498
+ allowStartupGrace: true,
499
+ directory,
500
+ currentFresh: latestFresh,
501
+ fromViewCheck: true,
502
+ }).catch(() => null)
503
+ }
504
+ }
505
+
506
+ const finalState = loadChiefState()
507
+ const finalView = clusterView(finalState, rootId)
508
+ const ownWs = ensureWorkspace(finalState, rootId)
509
+ const effectiveConfig = resolveWorkspaceConfig(finalState, rootId)
510
+ const narrativeAt = hasLatestSaved
511
+ ? (latestView.narrative.at || 0)
512
+ : (ownWs.narrative && ownWs.narrative.at ? ownWs.narrative.at : (board.updatedAt || 0))
513
+ const finalNarrativeText = ownWs.narrative && ownWs.narrative.text && (!isConciseBrief || latestFresh)
514
+ ? (isConciseBrief ? sanitizeConciseBriefText(ownWs.narrative.text) : ownWs.narrative.text)
515
+ : narrativeText
516
+ return {
517
+ ok: true,
518
+ rootId,
519
+ config: effectiveConfig,
520
+ models: modelsInfo,
521
+ narrative: {
522
+ text: finalNarrativeText,
523
+ at: narrativeAt,
524
+ byModel: hasLatestSaved ? (latestView.narrative.byModel || '') : ((ownWs.narrative && ownWs.narrative.byModel) || ''),
525
+ clusterSig: currentSig,
526
+ isLiveZeroToken: !hasLatestSaved && !(ownWs.narrative && ownWs.narrative.text),
527
+ hasUnsummarizedChanges: Boolean(rawInput && !latestFresh && !(ownWs.narrative && ownWs.narrative.hash === inputHash)),
528
+ summarizing: summarizingLocks.has(rootId),
529
+ fresh: latestFresh || Boolean(ownWs.narrative && ownWs.narrative.hash === inputHash),
530
+ },
531
+ ...(handoffSyncResult ? { handoffSyncResult } : {}),
532
+ facts: finalView.facts.slice().reverse(),
533
+ suggestions: finalView.suggestions.slice().reverse(),
534
+ chat: finalView.chat.slice(-40).map((c) => {
535
+ if (!c || typeof c !== 'object') return c
536
+ const cleaned = stripToolCallMarkup(c.text || '')
537
+ return cleaned !== c.text
538
+ ? { ...c, text: cleaned || '(该条历史响应仅包含内部工具调用标记,已自动净化)' }
539
+ : c
540
+ }),
541
+ mailbox: finalView.mailbox.slice(-30).reverse(),
542
+ peers: directory.targets,
543
+ otherSessions: directory.otherSessions,
544
+ cluster: directory.cluster,
545
+ peerProgress,
546
+ flippedPrecipitatedIds: (ownWs.flippedPrecipitatedIds || []).slice(),
547
+ runtimeGuard: { ...ownWs.runtimeGuard },
548
+ chiefRiskAck: ownWs.chiefRiskAck ? { ...ownWs.chiefRiskAck } : null,
549
+ pendingApprovals: (Array.isArray(ownWs.pendingApprovals) ? ownWs.pendingApprovals : []).slice(-15).reverse(),
550
+ pendingElevation: ownWs.pendingElevation ? { ...ownWs.pendingElevation } : null,
551
+ auditLog: (Array.isArray(ownWs.auditLog) ? ownWs.auditLog : []).slice(-50).reverse(),
552
+ }
553
+ }