dsh-chief 1.2.0 → 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.
@@ -0,0 +1,905 @@
1
+ /**
2
+ * chief-archives.js
3
+ *
4
+ * Archive organization, turn evidence harvesting, experience precipitation, and archive relay for DSH Chief.
5
+ */
6
+
7
+ import path from 'node:path'
8
+ import {
9
+ resolveProjectKey,
10
+ loadArchiveStore,
11
+ listArchiveHeaders,
12
+ getArchiveDetail,
13
+ smartParseNoteToDossier,
14
+ mutateArchive,
15
+ applyChiefArchiveCurations,
16
+ getPrecipitatedDetail,
17
+ savePrecipitatedEntry,
18
+ } from './archives.js'
19
+ import {
20
+ CHAT_CAP,
21
+ SUMMARY_MAX_TOKENS,
22
+ archiveTargetForRoot,
23
+ nextId,
24
+ clamp,
25
+ cleanMultiline,
26
+ secretLike,
27
+ loadChiefState,
28
+ mutateChiefState,
29
+ ensureWorkspace,
30
+ stripCheckpointNoise,
31
+ isInternalCheckpointNoise,
32
+ extractJsonObject,
33
+ } from './chief-state.js'
34
+ import { callChiefLlm } from './chief-models.js'
35
+ import { deliverCrossMessage } from './chief-network.js'
36
+ import { getChiefView } from './chief-view.js'
37
+
38
+ const ORGANIZE_ARCHIVES_SYSTEM = [
39
+ '你是「DSH 参谋长」的工程档案馆馆长。请把杂乱的工程笔记按「档案柜文件夹抽屉 → 曲别针卷宗 → 分条记忆点 → 小点记忆」结构化整理收纳。',
40
+ '',
41
+ '【核心铁律】',
42
+ '1. 默认标准抽屉 ID(优先归入这 5 个抽屉;仅当用户指令明确要求新建分类时才在 newFolders 中定义新抽屉):',
43
+ ' - "coords" : 工程坐标与部署锚点(源码路径、端口、热更口令、验证脚本命令)',
44
+ ' - "incidents" : 排障实录与硬事实(症状→根因→修复、踩坑实录、线上/本地故障)',
45
+ ' - "contracts" : 架构契约与方法论(写入/截断/类型宽容契约、自检断言、设计规范)',
46
+ ' - "ops" : 运维链路与机器环境(本机环境硬事实、服务器/代理/容器链路、运维手册)',
47
+ ' - "plans" : 阶段蓝图与归档计划(能力对照表、历史阶段计划存档、交接里程碑)',
48
+ '2. 曲别针等级 (`paperclip`):',
49
+ ' - "gold" : 跨会话最核心必查锚点(如工程坐标、核心红线实录)',
50
+ ' - "silver" : 标准已验证工程经验/契约/排障记录',
51
+ ' - "copper" : 阶段性历史存档/旧计划备查',
52
+ '3. 分条分块记忆点 (`points`):',
53
+ ' - 每份卷宗提炼 2~6 个结构清晰的「记忆点」,禁止把整篇堆成 1 大坨!',
54
+ ' - 每个记忆点必须包含:',
55
+ ' * `title` : 记忆点短标题(≤24字,点明这一条讲什么,如「症状表现」「根因与服务注入契约」「部署态验证命令」)',
56
+ ' * `cue` : 一句话速览钩子(≤48字,未展开时就能扫一眼看懂结论)',
57
+ ' * `detail`: 点击展开的「小点记忆」(**必须无损保留**原文中的具体命令、文件路径、行号、参数名、错误码与核心判据,严禁编造原文没有的事实!)',
58
+ '4. **只输出一个合法 JSON 对象**,格式如下:',
59
+ '{',
60
+ ' "newFolders": [',
61
+ ' { "id": "custom-key", "label": "新抽屉名称", "hint": "简短说明" }',
62
+ ' ],',
63
+ ' "items": [',
64
+ ' {',
65
+ ' "id": "原样回填输入的档案 id",',
66
+ ' "folder": "coords|incidents|contracts|ops|plans 或自定义 id",',
67
+ ' "paperclip": "gold|silver|copper",',
68
+ ' "summary": "一句话卷宗总提要(≤52字)",',
69
+ ' "tags": ["精炼标签1", "精炼标签2"],',
70
+ ' "points": [',
71
+ ' { "title": "记忆点标题", "cue": "速览钩子", "detail": "展开后的详细小点记忆(保留命令与路径)" }',
72
+ ' ]',
73
+ ' }',
74
+ ' ]',
75
+ '}',
76
+ ].join('\n')
77
+
78
+ /**
79
+ * Organize & structure engineering archives via DSH Chief LLM (`请参谋长整理收纳`).
80
+ * Classifies dossiers into filing-cabinet folders, assigns gold/silver/copper paperclips,
81
+ * and breaks walls of text into crisp `points: [{ title, cue, detail }]` while 100% preserving raw `body`!
82
+ */
83
+ export async function organizeArchivesWithChief(deps, {
84
+ sessionId = '',
85
+ vaultScope = 'session',
86
+ cabinetId = '',
87
+ ids = [],
88
+ folder = '',
89
+ scope = 'unorganized',
90
+ instruction = '',
91
+ } = {}) {
92
+ const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(sessionId)) || String(sessionId || 'global')
93
+ const effScope = vaultScope === 'global' ? 'global' : 'session'
94
+ if (effScope === 'session' && (!rootId || rootId === 'global')) {
95
+ return {
96
+ ok: false,
97
+ error: '当前为空白新对话,尚未建立本会话档案柜;如需整理全局知识请切至「🌐 全局档案柜」',
98
+ }
99
+ }
100
+ const targetOpt = archiveTargetForRoot(deps, rootId, { cabinetId, vaultScope: effScope })
101
+ const store = loadArchiveStore(targetOpt)
102
+
103
+ if (!store.items.length) {
104
+ return {
105
+ ok: false,
106
+ error: '当前「档案」柜中暂无可整理的工程卷宗,可先新建卷宗或将便签沉淀入柜。',
107
+ }
108
+ }
109
+
110
+ const explicitIds = Array.isArray(ids) ? ids.map(x => String(x || '').trim()).filter(Boolean) : []
111
+ let candidates = []
112
+ if (explicitIds.length > 0) {
113
+ const idSet = new Set(explicitIds)
114
+ candidates = store.items.filter(it => idSet.has(it.id))
115
+ } else if (folder) {
116
+ candidates = store.items.filter(it => it.folder === folder)
117
+ } else if (scope === 'all') {
118
+ candidates = store.items.slice()
119
+ } else {
120
+ // Prefer unorganized / inbox / single-point items first; if all were already organized, take newest batch
121
+ const unorg = store.items.filter(it => it.folder === 'inbox' || it.organizedBy !== 'chief' || (it.points || []).length <= 1)
122
+ candidates = unorg.length > 0 ? unorg : store.items.slice(0, 8)
123
+ }
124
+
125
+ if (!candidates.length) {
126
+ return { ok: false, error: '未找到符合筛选范围的工程档案。' }
127
+ }
128
+
129
+ const BATCH_SIZE = 5
130
+ const MAX_ITEMS_PER_RUN = explicitIds.length > 0 ? Math.min(explicitIds.length, 15) : 10
131
+ const selected = candidates.slice(0, MAX_ITEMS_PER_RUN)
132
+ const remainingCount = Math.max(0, candidates.length - selected.length)
133
+
134
+ const folderLines = store.folders.map(f => `- "${f.id}": ${f.label}(${f.hint || ''})`)
135
+ const allCurations = []
136
+ const allNewFolders = []
137
+ let usedLlm = false
138
+
139
+ for (let offset = 0; offset < selected.length; offset += BATCH_SIZE) {
140
+ const batch = selected.slice(offset, offset + BATCH_SIZE)
141
+ const promptParts = [
142
+ '现有档案柜文件夹抽屉:',
143
+ ...folderLines,
144
+ instruction ? `\n用户收纳叮嘱:${clamp(instruction, 240)}` : '',
145
+ `\n待整理收纳的 ${batch.length} 份工程卷宗:`,
146
+ ]
147
+ batch.forEach((item, idx) => {
148
+ promptParts.push(
149
+ `\n--- 卷宗 #${idx + 1} ---`,
150
+ `id: ${item.id}`,
151
+ `标题: ${item.title}`,
152
+ `当前抽屉: ${item.folder} | 当前曲别针: ${item.paperclip} | 原标签: ${(item.tags || []).join(', ') || '无'}`,
153
+ `原始正文:\n${cleanMultiline(item.body || item.summary || item.title, 2600)}`,
154
+ )
155
+ })
156
+
157
+ const llmRes = await callChiefLlm(deps, {
158
+ sessionId: rootId,
159
+ system: ORGANIZE_ARCHIVES_SYSTEM,
160
+ prompt: promptParts.filter(Boolean).join('\n'),
161
+ maxTokens: SUMMARY_MAX_TOKENS,
162
+ })
163
+
164
+ const parsed = llmRes.ok ? extractJsonObject(llmRes.text) : null
165
+ if (parsed && Array.isArray(parsed.items) && parsed.items.length > 0) {
166
+ usedLlm = true
167
+ if (Array.isArray(parsed.newFolders)) {
168
+ for (const nf of parsed.newFolders) allNewFolders.push(nf)
169
+ }
170
+ const byId = new Map(parsed.items.filter(x => x && x.id).map(x => [String(x.id).trim(), x]))
171
+ for (const orig of batch) {
172
+ const cur = byId.get(orig.id)
173
+ if (cur) {
174
+ allCurations.push(cur)
175
+ } else {
176
+ const fb = smartParseNoteToDossier(orig)
177
+ allCurations.push({
178
+ id: orig.id,
179
+ folder: fb.folder,
180
+ paperclip: fb.paperclip,
181
+ summary: fb.summary,
182
+ tags: orig.tags,
183
+ points: fb.points,
184
+ })
185
+ }
186
+ }
187
+ } else {
188
+ // Deterministic high-precision fallback when LLM is offline or returned non-JSON
189
+ for (const orig of batch) {
190
+ const fb = smartParseNoteToDossier(orig)
191
+ allCurations.push({
192
+ id: orig.id,
193
+ folder: orig.folder === 'inbox' ? fb.folder : (orig.folder || fb.folder),
194
+ paperclip: fb.paperclip,
195
+ summary: fb.summary,
196
+ tags: orig.tags,
197
+ points: fb.points,
198
+ })
199
+ }
200
+ }
201
+ }
202
+
203
+ const applied = applyChiefArchiveCurations(allCurations, allNewFolders, targetOpt)
204
+ const refreshedList = listArchiveHeaders(rootId, { includePrecipitated: false }, targetOpt)
205
+ const folderNameMap = new Map(refreshedList.folders.map(f => [f.id, f.label]))
206
+
207
+ const folderStats = new Map()
208
+ for (const c of allCurations) {
209
+ const fName = folderNameMap.get(c.folder) || c.folder
210
+ folderStats.set(fName, (folderStats.get(fName) || 0) + 1)
211
+ }
212
+ const statSummary = [...folderStats.entries()].map(([k, n]) => `「${k}」${n} 卷`).join('、')
213
+ const reply = `- 【档案收纳完成】已${usedLlm ? '由参谋长模型深度提炼' : '按结构规则分拣'} **${applied.updatedCount} 份**工程卷宗(归入 ${statSummary}),每份均已拆解「记忆点 → 小点记忆」,原文 100% 无损封存。`
214
+ + (remainingCount > 0 ? `\n- 【分批提示】柜内另有 ${remainingCount} 份卷宗待精修,可再点一次「请参谋长整理收纳」继续完成剩余部分。` : '')
215
+
216
+ mutateChiefState((s) => {
217
+ const ws = ensureWorkspace(s, rootId)
218
+ ws.chat.push(
219
+ {
220
+ id: nextId('chat'),
221
+ role: 'user',
222
+ text: instruction ? `整理工程档案:${instruction}` : `请参谋长整理收纳工程档案(${applied.updatedCount} 卷)`,
223
+ actions: [],
224
+ at: Date.now(),
225
+ },
226
+ {
227
+ id: nextId('chat'),
228
+ role: 'chief',
229
+ text: reply,
230
+ actions: [`已收纳 ${applied.updatedCount} 卷档案`],
231
+ at: Date.now(),
232
+ },
233
+ )
234
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
235
+ })
236
+
237
+ if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
238
+ deps.appendBoardLog(rootId, `🗄️ 参谋长完成工程档案收纳:共精修 ${applied.updatedCount} 卷(${statSummary})`, 'chief')
239
+ }
240
+
241
+ return {
242
+ ok: true,
243
+ updatedCount: applied.updatedCount,
244
+ remainingCount,
245
+ usedLlm,
246
+ reply,
247
+ archives: refreshedList,
248
+ view: await getChiefView(deps, rootId, { autoSummarize: false }),
249
+ }
250
+ }
251
+
252
+ const HARVEST_ARCHIVE_SYSTEM = [
253
+ '你是「DSH 参谋长」的高精度上下文抢救员。当前即将执行上下文压缩或用户主动抢救本轮现场细节,请从原始对话与看板轨迹中无损抢救工程硬细节并归档!',
254
+ '要求:',
255
+ '1. 重点抓取:**具体文件路径、行号、真实命令/脚本参数、刚确认的报错根因与结论、尚未完成的断点、未解决的阻塞细节**,严禁泛泛而谈或丢弃关键参数。',
256
+ '2. 绝对不要编造原文未出现的文件名或命令。',
257
+ '3. 只输出一个合法 JSON 对象:',
258
+ '{',
259
+ ' "folder": "coords|incidents|contracts|ops|plans",',
260
+ ' "paperclip": "gold|silver|copper",',
261
+ ' "title": "精炼明确归档标题(≤38字)",',
262
+ ' "summary": "一句话总结核心工程事实(≤56字)",',
263
+ ' "tags": ["标签1", "标签2"],',
264
+ ' "points": [',
265
+ ' { "title": "记忆点短标题", "cue": "速览钩子", "detail": "含原文件路径/命令/结论的高保真明细" }',
266
+ ' ]',
267
+ '}',
268
+ ].join('\n')
269
+
270
+ function collectRawSessionEvidence(deps, { sessionId = '', rootId = '', agent = null }) {
271
+ const board = deps && deps.boardForSession && deps.boardFileFor
272
+ ? deps.boardForSession(deps.boardFileFor(rootId))
273
+ : null
274
+ const lines = []
275
+ if (board && board.objective) lines.push(`【当前总目标】${board.objective}`)
276
+ if (board && board.cursor && (board.cursor.step || board.cursor.next || board.cursor.blocked)) {
277
+ lines.push(`【断点游标】当前=${board.cursor.step || '无'} | 下一步=${board.cursor.next || '无'} | 阻塞=${board.cursor.blocked || '无'}`)
278
+ }
279
+ const tasks = Array.isArray(board && board.tasks) ? board.tasks : []
280
+ const openTasks = tasks.filter(t => t.status !== 'done').slice(0, 6)
281
+ if (openTasks.length > 0) {
282
+ lines.push('【进行中/未完任务】')
283
+ for (const t of openTasks) {
284
+ lines.push(`- [${t.status}] #${t.id} ${t.title}${t.note ? `(${clamp(t.note, 100)})` : ''}`)
285
+ }
286
+ }
287
+
288
+ let targetAgent = agent
289
+ if (!targetAgent && deps && deps.runtime) {
290
+ try {
291
+ const agentsSvc = deps.runtime.get('agents')
292
+ if (agentsSvc && typeof agentsSvc.get === 'function') {
293
+ targetAgent = agentsSvc.get(sessionId) || agentsSvc.get(rootId)
294
+ }
295
+ } catch {}
296
+ }
297
+
298
+ const pathsFound = new Set()
299
+ const cmdsFound = new Set()
300
+ const rawTurns = []
301
+ try {
302
+ if (targetAgent && targetAgent.session && typeof targetAgent.session.deriveMessages === 'function') {
303
+ const msgs = targetAgent.session.deriveMessages() || []
304
+ for (const m of msgs.slice(-14)) {
305
+ if (!m || !m.role) continue
306
+ if (m.source && m.source.kind && m.source.kind !== 'user' && m.role === 'user') continue
307
+ const blocks = Array.isArray(m.content)
308
+ ? m.content
309
+ : (typeof m.content === 'string' ? [{ type: 'text', text: m.content }] : [])
310
+ for (const b of blocks) {
311
+ if (!b || typeof b !== 'object') continue
312
+ if (b.type === 'text' && typeof b.text === 'string') {
313
+ const clean = stripCheckpointNoise(b.text)
314
+ if (!clean || isInternalCheckpointNoise(clean) || secretLike(clean)) continue
315
+ rawTurns.push(`${m.role === 'user' ? 'User' : 'Assistant'}: ${clamp(clean, 500)}`)
316
+ const pathMatches = clean.match(/(?:[A-Za-z]:)?(?:[\\/][^\s'"`<>|]{2,70})+/g) || []
317
+ for (const p of pathMatches.slice(0, 8)) pathsFound.add(p)
318
+ } else if ((b.type === 'tool_use' || b.type === 'tool-call' || b.type === 'toolCall') && (b.name || b.toolName)) {
319
+ const name = String(b.name || b.toolName)
320
+ const rawArgs = b.input || b.arguments || b.args
321
+ let obj = null
322
+ try { obj = typeof rawArgs === 'string' ? JSON.parse(rawArgs) : rawArgs } catch {}
323
+ const cmd = obj && (obj.command || obj.cmd || obj.CommandLine)
324
+ const fpath = obj && (obj.path || obj.file_path || obj.Path)
325
+ if (fpath && !secretLike(String(fpath))) pathsFound.add(String(fpath))
326
+ if (cmd && !secretLike(String(cmd))) cmdsFound.add(clamp(String(cmd), 140))
327
+ rawTurns.push(`Tool[${name}]: ${clamp(JSON.stringify(obj || {}), 220)}`)
328
+ }
329
+ }
330
+ }
331
+ }
332
+ } catch {}
333
+
334
+ if (pathsFound.size > 0) lines.push('', '【涉及路径与符号】\n' + [...pathsFound].slice(0, 12).map(p => `- ${p}`).join('\n'))
335
+ if (cmdsFound.size > 0) lines.push('', '【近期执行命令】\n' + [...cmdsFound].slice(0, 8).map(c => `- \`${c}\``).join('\n'))
336
+ if (rawTurns.length > 0) lines.push('', '【近期对话与工具流水】\n' + rawTurns.slice(-10).join('\n'))
337
+ return {
338
+ board,
339
+ text: lines.join('\n').trim(),
340
+ hasTranscript: rawTurns.length > 0,
341
+ pathCount: pathsFound.size,
342
+ cmdCount: cmdsFound.size,
343
+ }
344
+ }
345
+
346
+ /** High-precision harvest of recent session details into active working archive cabinet (`pre-compaction` or `manual`). */
347
+ export async function harvestTurnDetailsToArchive(deps, {
348
+ sessionId = '',
349
+ agent = null,
350
+ trigger = 'manual',
351
+ focusHint = '',
352
+ cabinetId = '',
353
+ vaultScope = 'session',
354
+ } = {}) {
355
+ const rootId = (deps && deps.resolveRootSessionId && deps.resolveRootSessionId(sessionId, agent)) || String(sessionId || 'global')
356
+ const effScope = vaultScope === 'global' ? 'global' : 'session'
357
+ if (effScope === 'session' && (!rootId || rootId === 'global')) {
358
+ return { ok: false, error: '当前为空白新对话(未绑定会话 ID),请先发送一条消息或切至「🌐 全局档案柜」再抢救归档' }
359
+ }
360
+ const targetOpt = archiveTargetForRoot(deps, rootId, { cabinetId, vaultScope: effScope })
361
+ const evidence = collectRawSessionEvidence(deps, { sessionId: sessionId || rootId, rootId, agent })
362
+ const bodySource = [
363
+ focusHint ? `【抢救焦点提示】${cleanMultiline(focusHint, 240)}` : '',
364
+ evidence.text || `【抢救快照】时间 ${new Date().toLocaleString('zh-CN')} | 触发原因:${trigger}`,
365
+ ].filter(Boolean).join('\n\n')
366
+
367
+ let parsed = null
368
+ let usedLlm = false
369
+ try {
370
+ const llmRes = await callChiefLlm(deps, {
371
+ sessionId: rootId,
372
+ system: HARVEST_ARCHIVE_SYSTEM,
373
+ prompt: `触发模式:${trigger === 'pre-compaction' ? '上下文压缩前自动高保真抢救' : '用户手动抢救当前工作细节入柜'}\n\n${cleanMultiline(bodySource, 5200)}`,
374
+ maxTokens: SUMMARY_MAX_TOKENS,
375
+ })
376
+ if (llmRes && llmRes.ok && llmRes.text) {
377
+ parsed = extractJsonObject(llmRes.text)
378
+ if (parsed && (parsed.title || (Array.isArray(parsed.points) && parsed.points.length > 0))) {
379
+ usedLlm = true
380
+ }
381
+ }
382
+ } catch {}
383
+
384
+ const fallback = smartParseNoteToDossier({
385
+ title: `${trigger === 'pre-compaction' ? '【压缩前抢救】' : '【细节抢救】'}${clamp(focusHint || (evidence.board && evidence.board.objective) || '本轮工作现场细节', 28)}`,
386
+ body: bodySource,
387
+ })
388
+ const d = new Date()
389
+ const timeStamp = `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
390
+ const title = clamp((parsed && parsed.title) || `${fallback.title || '工作细节抢救'} (${timeStamp})`, 70)
391
+ const folder = String((parsed && parsed.folder) || fallback.folder || 'incidents').trim()
392
+ const paperclip = ['gold', 'silver', 'copper'].includes(parsed && parsed.paperclip)
393
+ ? parsed.paperclip
394
+ : (trigger === 'pre-compaction' ? 'gold' : fallback.paperclip)
395
+ const summary = clamp((parsed && parsed.summary) || fallback.summary || clamp(bodySource, 110), 180)
396
+ const tags = Array.isArray(parsed && parsed.tags) && parsed.tags.length > 0
397
+ ? parsed.tags.slice(0, 6)
398
+ : [trigger === 'pre-compaction' ? '压缩抢救' : '细节抢救', ...(evidence.cmdCount > 0 ? ['命令流水'] : [])]
399
+ const points = Array.isArray(parsed && parsed.points) && parsed.points.length > 0
400
+ ? parsed.points
401
+ : fallback.points
402
+
403
+ const saveRes = mutateArchive({
404
+ op: 'save',
405
+ session: rootId,
406
+ folder,
407
+ paperclip,
408
+ title,
409
+ summary,
410
+ tags,
411
+ points,
412
+ body: bodySource,
413
+ }, targetOpt)
414
+
415
+ if (!saveRes || !saveRes.ok || !saveRes.item || !saveRes.item.id) {
416
+ return { ok: false, error: (saveRes && saveRes.error) || '工作档案写入失败,未执行后续操作' }
417
+ }
418
+
419
+ // Strictly verify persistence on disk before returning ok!
420
+ const verify = getArchiveDetail(saveRes.item.id, rootId, targetOpt)
421
+ if (!verify || !verify.ok || !verify.item || verify.item.id !== saveRes.item.id) {
422
+ return { ok: false, error: '档案硬盘落盘复核失败' }
423
+ }
424
+
425
+ if (deps && typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
426
+ deps.appendBoardLog(rootId, `📥 已将本轮工程细节抢救入柜:《${title}》(trigger=${trigger})`, 'chief')
427
+ }
428
+
429
+ return {
430
+ ok: true,
431
+ trigger,
432
+ usedLlm,
433
+ savedId: saveRes.item.id,
434
+ item: verify.item,
435
+ cabinetId: targetOpt.cabinetId || verify.cabinetId || '',
436
+ archives: listArchiveHeaders(rootId, { includePrecipitated: trigger === 'manual' }, targetOpt),
437
+ }
438
+ }
439
+
440
+ const PRECIPITATE_EXPERIENCE_SYSTEM = [
441
+ '你是「DSH 参谋长」的知识沉淀总编。请把当前工作档案柜(或指定抽屉)的多份工作卷宗脱水提炼为 1~3 条**跨会话长期可复用**的高密度经验胶囊,准备封存入 0-Token 冷库!',
442
+ '原则:',
443
+ '1. **去水保干**:彻底剔除单轮聊天客套话、过时中间试错步骤与一次性状态;只保留长期有价值的【工程架构契约 / 踩坑根因与解法 / 核心文件路径与校验命令】。',
444
+ '2. 保留真实文件名、函数名、配置键、关键命令,绝不编造不存在的细节。',
445
+ '3. 只输出一个合法 JSON 对象:',
446
+ '{',
447
+ ' "entries": [',
448
+ ' {',
449
+ ' "title": "沉淀经验短标题(≤36字)",',
450
+ ' "category": "coords|incidents|contracts|ops",',
451
+ ' "summary": "一句话价值摘要(≤60字)",',
452
+ ' "tags": ["标签1", "标签2"],',
453
+ ' "points": [',
454
+ ' { "title": "要点标题", "cue": "一句话钩子", "detail": "完整可复用步骤/路径/契约" }',
455
+ ' ],',
456
+ ' "body": "完整精炼正文"',
457
+ ' }',
458
+ ' ]',
459
+ '}',
460
+ ].join('\n')
461
+
462
+ /** Purify working archive items into reusable long-term entries saved to `precipitated/vault-global.json`. */
463
+ export async function precipitateExperienceWithChief(deps, {
464
+ sessionId = '',
465
+ vaultScope = 'global',
466
+ op = 'cabinet',
467
+ cabinetId = '',
468
+ folder = '',
469
+ ids = [],
470
+ clearSource = false,
471
+ } = {}) {
472
+ if (vaultScope !== 'global') {
473
+ return {
474
+ ok: false,
475
+ error: '实行三层档案梯度制度:本会话档案不可直接沉淀入冷库!请先点击「🌐 升级入全局」进入全局档案柜,再从全局档案柜沉淀可复用冷经验。',
476
+ }
477
+ }
478
+ const rootId = (deps && deps.resolveRootSessionId && deps.resolveRootSessionId(sessionId)) || String(sessionId || 'global')
479
+ const effScope = 'global'
480
+ const targetOpt = archiveTargetForRoot(deps, rootId, { cabinetId, vaultScope: effScope })
481
+ const store = loadArchiveStore(targetOpt)
482
+ const projectKey = resolveProjectKey(targetOpt.cwd)
483
+
484
+ const idSet = Array.isArray(ids) && ids.length > 0
485
+ ? new Set(ids.map(x => String(x || '').trim()).filter(Boolean))
486
+ : null
487
+ const selectedItems = idSet
488
+ ? store.items.filter(it => idSet.has(String(it.id)))
489
+ : ((op === 'drawer' && folder) ? store.items.filter(it => it.folder === folder) : store.items.slice())
490
+
491
+ if (!selectedItems.length) {
492
+ return { ok: false, error: '当前选定范围暂无工作档案可沉淀' }
493
+ }
494
+
495
+ const promptBody = selectedItems.slice(0, 12).map((it, idx) => [
496
+ `--- 工作档案 #${idx + 1}: 《${it.title}》 (drawer=${it.folder}, clip=${it.paperclip}) ---`,
497
+ `提要: ${it.summary || '无'}`,
498
+ Array.isArray(it.points) && it.points.length > 0
499
+ ? '记忆点:\n' + it.points.map(p => `- ${p.title}: ${p.detail || p.cue}`).join('\n')
500
+ : `正文:\n${cleanMultiline(it.body, 1500)}`,
501
+ ].join('\n')).join('\n\n')
502
+
503
+ let entriesRaw = null
504
+ let usedLlm = false
505
+ try {
506
+ const llmRes = await callChiefLlm(deps, {
507
+ sessionId: rootId,
508
+ system: PRECIPITATE_EXPERIENCE_SYSTEM,
509
+ prompt: `待沉淀工程档案范围:${op === 'drawer' && folder ? `抽屉 ${folder}` : '整柜'}(共 ${selectedItems.length} 卷)\n\n${cleanMultiline(promptBody, 6400)}`,
510
+ maxTokens: SUMMARY_MAX_TOKENS,
511
+ })
512
+ if (llmRes && llmRes.ok && llmRes.text) {
513
+ const parsed = extractJsonObject(llmRes.text)
514
+ if (parsed && Array.isArray(parsed.entries) && parsed.entries.length > 0) {
515
+ entriesRaw = parsed.entries.slice(0, 4)
516
+ usedLlm = true
517
+ }
518
+ }
519
+ } catch {}
520
+
521
+ if (!entriesRaw) {
522
+ // Deterministic distillation fallback preserving high-signal points & paths
523
+ const leadTitle = op === 'drawer' && folder
524
+ ? `【${folder} 沉淀】${selectedItems[0].title}`
525
+ : `【工程沉淀】${selectedItems[0].title}${selectedItems.length > 1 ? ` 等 ${selectedItems.length} 卷精华` : ''}`
526
+ const mergedPoints = []
527
+ const mergedTags = new Set(['已沉淀'])
528
+ const bodyBlocks = []
529
+ for (const it of selectedItems.slice(0, 8)) {
530
+ for (const tg of (it.tags || [])) mergedTags.add(tg)
531
+ bodyBlocks.push(`### ${it.title}\n${cleanMultiline(it.summary || it.body, 500)}`)
532
+ if (Array.isArray(it.points) && it.points.length > 0) {
533
+ for (const pt of it.points.slice(0, 3)) {
534
+ mergedPoints.push(pt)
535
+ }
536
+ } else {
537
+ mergedPoints.push({
538
+ title: clamp(it.title, 32),
539
+ cue: clamp(it.summary || it.body, 56),
540
+ detail: cleanMultiline(it.body || it.summary, 420),
541
+ })
542
+ }
543
+ }
544
+ entriesRaw = [{
545
+ title: clamp(leadTitle, 64),
546
+ category: folder || selectedItems[0].folder || 'contracts',
547
+ summary: clamp(selectedItems.map(x => x.summary || x.title).filter(Boolean).slice(0, 2).join(';'), 140),
548
+ tags: [...mergedTags].slice(0, 6),
549
+ points: mergedPoints.slice(0, 10),
550
+ body: bodyBlocks.join('\n\n'),
551
+ }]
552
+ }
553
+
554
+ const savedEntries = []
555
+ for (const raw of entriesRaw) {
556
+ const res = savePrecipitatedEntry(projectKey, {
557
+ ...raw,
558
+ sourceCabinet: store.cabinetName || store.cabinetId,
559
+ sourceCount: selectedItems.length,
560
+ }, targetOpt)
561
+ if (res && res.ok && res.entry) savedEntries.push(res.entry)
562
+ }
563
+
564
+ if (!savedEntries.length) {
565
+ return { ok: false, error: '沉淀写入冷库失败,已保留原有工作档案' }
566
+ }
567
+
568
+ let clearedSource = false
569
+ if (clearSource) {
570
+ if (!idSet && op === 'drawer' && folder) {
571
+ mutateArchive({ op: 'clearFolder', folder }, targetOpt)
572
+ clearedSource = true
573
+ } else {
574
+ mutateArchive({ op: 'clearByIds', ids: selectedItems.map(x => x.id) }, targetOpt)
575
+ clearedSource = true
576
+ }
577
+ }
578
+
579
+ if (deps && typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
580
+ deps.appendBoardLog(rootId, `⏬ 已从${selectedItems.length} 卷工作档案提炼 ${savedEntries.length} 条可复用经验封存入 0-Token 冷库`, 'chief')
581
+ }
582
+
583
+ return {
584
+ ok: true,
585
+ projectKey,
586
+ usedLlm,
587
+ createdCount: savedEntries.length,
588
+ entries: savedEntries,
589
+ clearedSource,
590
+ archives: listArchiveHeaders(rootId, { includePrecipitated: true }, targetOpt),
591
+ }
592
+ }
593
+
594
+ const DISTILL_TO_GLOBAL_SYSTEM = [
595
+ '你是「DSH 参谋长」的知识萃取总编。请审查当前「本会话工作档案柜」中的临时工作卷宗:',
596
+ '1. **摘除一次性噪音**:剔除只属于本次调试流水账、临时状态快照或纯闲聊过渡的信息;',
597
+ '2. **萃取可复用精华**:只摘出并总结未来跨会话仍长期有用的【工程坐标、入口路径、架构契约、核心命令、接口定义、通用踩坑与红线经验】;',
598
+ '3. **浓缩成全局卷宗**:同类主题合并为 1~4 卷高信息密度、结构清晰的全局档案,保留真实文件名/函数名/命令参数,严禁编造;',
599
+ '4. **只输出一个合法 JSON 对象**:',
600
+ '{',
601
+ ' "entries": [',
602
+ ' {',
603
+ ' "title": "全局档案短标题(≤36字)",',
604
+ ' "folder": "coords|incidents|contracts|ops",',
605
+ ' "paperclip": "gold|silver",',
606
+ ' "summary": "一句话可复用价值摘要(≤60字)",',
607
+ ' "tags": ["标签1", "标签2"],',
608
+ ' "points": [',
609
+ ' { "title": "要点标题", "cue": "一句话钩子", "detail": "完整可复用步骤/路径/契约" }',
610
+ ' ],',
611
+ ' "body": "完整精炼正文"',
612
+ ' }',
613
+ ' ]',
614
+ '}',
615
+ ].join('\n')
616
+
617
+ /** Extract, summarize, and distill reusable items from the current Session Cabinet into the Global Vault (`vaultScope: 'global'`). */
618
+ export async function distillSessionArchivesToGlobal(deps, {
619
+ sessionId = '',
620
+ cabinetId = '',
621
+ ids = null,
622
+ folder = '',
623
+ clearSource = false,
624
+ instruction = '',
625
+ } = {}) {
626
+ const rootId = (deps && deps.resolveRootSessionId && deps.resolveRootSessionId(sessionId)) || String(sessionId || '').trim()
627
+ if (!rootId || rootId === 'global') {
628
+ return { ok: false, error: '当前未绑定具体对话会话,无法从本局档案柜提炼入全局库' }
629
+ }
630
+
631
+ const sessionOpt = archiveTargetForRoot(deps, rootId, { cabinetId, vaultScope: 'session' })
632
+ const globalOpt = archiveTargetForRoot(deps, rootId, { vaultScope: 'global' })
633
+ const store = loadArchiveStore(sessionOpt)
634
+
635
+ const idSet = Array.isArray(ids) && ids.length > 0
636
+ ? new Set(ids.map(x => String(x || '').trim()).filter(Boolean))
637
+ : null
638
+ const folderClean = typeof folder === 'string' ? folder.trim() : ''
639
+ let selected = idSet
640
+ ? store.items.filter(it => idSet.has(String(it.id)))
641
+ : (folderClean ? store.items.filter(it => it.folder === folderClean) : store.items.slice())
642
+
643
+ if (!selected.length) {
644
+ return { ok: false, error: '当前本会话档案柜暂无可供提炼的档案条目' }
645
+ }
646
+
647
+ // Prioritize reusable engineering anchors/clips first
648
+ const clipRank = { gold: 0, silver: 1, copper: 2 }
649
+ selected = [...selected].sort((a, b) => (clipRank[a.paperclip] ?? 1) - (clipRank[b.paperclip] ?? 1))
650
+
651
+ const promptBody = selected.slice(0, 14).map((it, idx) => [
652
+ `--- 本局档案 #${idx + 1}: 《${it.title}》 (folder=${it.folder}, clip=${it.paperclip}) ---`,
653
+ `提要: ${it.summary || '无'}`,
654
+ Array.isArray(it.points) && it.points.length > 0
655
+ ? '记忆点:\n' + it.points.map(p => `- ${p.title}: ${p.detail || p.cue}`).join('\n')
656
+ : `正文:\n${cleanMultiline(it.body, 1400)}`,
657
+ ].join('\n')).join('\n\n')
658
+
659
+ let entriesRaw = null
660
+ let usedLlm = false
661
+ try {
662
+ const llmRes = await callChiefLlm(deps, {
663
+ sessionId: rootId,
664
+ system: DISTILL_TO_GLOBAL_SYSTEM,
665
+ prompt: [
666
+ instruction ? `用户指定提炼侧重:${clamp(instruction, 240)}\n` : '',
667
+ `待萃取本局工作档案(共 ${selected.length} 卷):`,
668
+ cleanMultiline(promptBody, 6800),
669
+ ].filter(Boolean).join('\n'),
670
+ maxTokens: SUMMARY_MAX_TOKENS,
671
+ })
672
+ if (llmRes && llmRes.ok && llmRes.text) {
673
+ const parsed = extractJsonObject(llmRes.text)
674
+ if (parsed && Array.isArray(parsed.entries) && parsed.entries.length > 0) {
675
+ entriesRaw = parsed.entries.slice(0, 4)
676
+ usedLlm = true
677
+ }
678
+ }
679
+ } catch {}
680
+
681
+ if (!entriesRaw) {
682
+ // Deterministic fallback: distill gold/silver/reusable items grouped cleanly into global vault entries
683
+ const reusable = selected.filter(it => it.paperclip !== 'copper')
684
+ const pool = reusable.length ? reusable : selected
685
+ const lead = pool[0]
686
+ const mergedPoints = []
687
+ const bodyBlocks = []
688
+ const mergedTags = new Set(['全局萃取', ...(instruction ? ['专项提炼'] : [])])
689
+ for (const it of pool.slice(0, 8)) {
690
+ for (const tg of (it.tags || [])) mergedTags.add(tg)
691
+ bodyBlocks.push(`### 《${it.title}》\n${cleanMultiline(it.summary || it.body, 480)}`)
692
+ if (Array.isArray(it.points) && it.points.length > 0) {
693
+ for (const pt of it.points.slice(0, 3)) mergedPoints.push(pt)
694
+ } else {
695
+ mergedPoints.push({
696
+ title: clamp(it.title, 32),
697
+ cue: clamp(it.summary || it.body, 56),
698
+ detail: cleanMultiline(it.body || it.summary, 420),
699
+ })
700
+ }
701
+ }
702
+ const validFolders = new Set(['coords', 'incidents', 'contracts', 'ops', 'inbox'])
703
+ entriesRaw = [{
704
+ title: clamp(`【全局萃取】${lead.title}${pool.length > 1 ? ` 等 ${pool.length} 卷精选` : ''}`, 56),
705
+ folder: validFolders.has(lead.folder) ? lead.folder : 'contracts',
706
+ paperclip: lead.paperclip === 'gold' ? 'gold' : 'silver',
707
+ summary: clamp(pool.map(x => x.summary || x.title).filter(Boolean).slice(0, 2).join(';'), 140),
708
+ tags: [...mergedTags].slice(0, 6),
709
+ points: mergedPoints.slice(0, 10),
710
+ body: bodyBlocks.join('\n\n'),
711
+ }]
712
+ }
713
+
714
+ const savedEntries = []
715
+ const validFolders = new Set(['coords', 'incidents', 'contracts', 'ops', 'inbox'])
716
+ for (const raw of entriesRaw) {
717
+ if (!raw || typeof raw !== 'object') continue
718
+ const title = clamp(raw.title || '全局萃取卷宗', 64)
719
+ const f = validFolders.has(raw.folder) ? raw.folder : 'contracts'
720
+ const clip = raw.paperclip === 'gold' ? 'gold' : 'silver'
721
+ const res = mutateArchive({
722
+ op: 'save',
723
+ vaultScope: 'global',
724
+ folder: f,
725
+ paperclip: clip,
726
+ title,
727
+ summary: clamp(raw.summary || '', 160),
728
+ tags: Array.isArray(raw.tags) ? raw.tags.slice(0, 8) : ['全局萃取'],
729
+ points: Array.isArray(raw.points) ? raw.points : [],
730
+ body: cleanMultiline(raw.body || raw.summary || title, 4000),
731
+ by: 'DSH 参谋长萃取',
732
+ rootSessionId: rootId,
733
+ }, globalOpt)
734
+ if (res && res.ok && res.item) savedEntries.push(res.item)
735
+ }
736
+
737
+ if (!savedEntries.length) {
738
+ return { ok: false, error: '全局档案柜写入失败,已保留原有本局工作档案' }
739
+ }
740
+
741
+ let clearedSource = false
742
+ if (clearSource) {
743
+ if (!idSet && folderClean) {
744
+ mutateArchive({ op: 'clearFolder', folder: folderClean, vaultScope: 'session' }, sessionOpt)
745
+ clearedSource = true
746
+ } else {
747
+ mutateArchive({ op: 'clearByIds', ids: selected.map(x => x.id), vaultScope: 'session' }, sessionOpt)
748
+ clearedSource = true
749
+ }
750
+ }
751
+
752
+ const summaryReply = `- 【✦ 本局萃取入全局】已从本会话 ${selected.length} 卷工作档案中摘除临时噪音并提炼 **${savedEntries.length} 卷**可复用精华存入「🌐 全局档案柜」${clearedSource ? '(已按勾选清理本局原卷宗)' : '(本局原卷宗无损保留)'}:${savedEntries.map(e => `《${e.title}》`).join('、')}。`
753
+ mutateChiefState((s) => {
754
+ const ws = ensureWorkspace(s, rootId)
755
+ ws.chat.push({
756
+ id: nextId('chat'),
757
+ role: 'chief',
758
+ text: summaryReply,
759
+ actions: [`萃取入全局 ×${savedEntries.length}`],
760
+ at: Date.now(),
761
+ })
762
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
763
+ })
764
+ if (deps && typeof deps.appendBoardLog === 'function') {
765
+ deps.appendBoardLog(rootId, `✦ 参谋长已从本局 ${selected.length} 卷档案摘出可复用精华,保存 ${savedEntries.length} 卷入全局档案柜`, 'chief')
766
+ }
767
+
768
+ const stNow = loadChiefState()
769
+ const wsNow = stNow.workspaces ? stNow.workspaces[rootId] : null
770
+ const flippedIds = wsNow && Array.isArray(wsNow.flippedPrecipitatedIds) ? wsNow.flippedPrecipitatedIds : []
771
+ return {
772
+ ok: true,
773
+ usedLlm,
774
+ createdCount: savedEntries.length,
775
+ entries: savedEntries,
776
+ clearedSource,
777
+ reply: summaryReply,
778
+ archives: listArchiveHeaders(rootId, { vaultScope: 'session', includePrecipitated: true, flippedIds }, sessionOpt),
779
+ globalArchives: listArchiveHeaders(rootId, { vaultScope: 'global', includePrecipitated: true, flippedIds }, globalOpt),
780
+ view: await getChiefView(deps, rootId, { autoSummarize: false }),
781
+ }
782
+ }
783
+
784
+ export function buildChiefArchiveUpsertFn(deps, rootId) {
785
+ return async (arc) => {
786
+ const sc = arc && arc.vaultScope === 'global' ? 'global' : 'session'
787
+ const opt = archiveTargetForRoot(deps, rootId, { vaultScope: sc })
788
+ return mutateArchive({
789
+ op: 'save',
790
+ session: rootId,
791
+ folder: (arc && arc.folder) || 'inbox',
792
+ paperclip: 'silver',
793
+ title: (arc && arc.title) || '参谋长工作归档',
794
+ summary: (arc && arc.summary) || '',
795
+ body: (arc && arc.body) || '',
796
+ tags: Array.isArray(arc && arc.tags) ? arc.tags : [],
797
+ by: 'chief',
798
+ }, opt)
799
+ }
800
+ }
801
+
802
+ /**
803
+ * Multi-Archive Combinatorial Relay (`递话`):
804
+ * Bundles 1+ archives across Session / Global / Precipitated vaults together with the user's explicit instruction
805
+ * and delivers them cleanly to `@lead` or the specified target agent.
806
+ */
807
+ export async function relayArchivesWithChief(deps, { sessionId, items = [], instruction = '', target = 'lead', mode = 'steer', cabinetId = '' } = {}) {
808
+ const rawSid = String(sessionId || '').trim()
809
+ const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(rawSid)) || rawSid || 'global'
810
+ const selected = Array.isArray(items) ? items.slice(0, 8) : []
811
+ const reqText = cleanMultiline(instruction, 800)
812
+ if (!selected.length && !reqText) {
813
+ return { ok: false, error: '请先勾选至少 1 份档案或输入带话要求' }
814
+ }
815
+
816
+ const baseOpt = archiveTargetForRoot(deps, rootId, { cabinetId, vaultScope: 'session' })
817
+ const projectKey = resolveProjectKey(baseOpt.cwd)
818
+ const loaded = []
819
+ const scopeLabelMap = { session: '本局档案', global: '全局档案', precipitated: '沉淀冷库' }
820
+
821
+ for (const ref of selected) {
822
+ if (!ref || !ref.id) continue
823
+ const rawSc = ref.scope || ref.vaultScope
824
+ const sc = ['session', 'global', 'precipitated'].includes(rawSc) ? rawSc : 'session'
825
+ let entry = null
826
+ if (sc === 'precipitated') {
827
+ const pRes = getPrecipitatedDetail(projectKey, ref.id, rootId, baseOpt)
828
+ if (pRes && pRes.ok && pRes.item) entry = pRes.item
829
+ } else {
830
+ const opt = archiveTargetForRoot(deps, rootId, { cabinetId: sc === 'session' ? cabinetId : '', vaultScope: sc })
831
+ const aRes = getArchiveDetail(ref.id, rootId, opt)
832
+ if (aRes && aRes.ok && aRes.item) entry = aRes.item
833
+ }
834
+ if (entry) {
835
+ loaded.push({ scope: sc, scopeLabel: scopeLabelMap[sc], item: entry })
836
+ } else if (ref.title) {
837
+ loaded.push({ scope: sc, scopeLabel: scopeLabelMap[sc], item: { id: ref.id, title: ref.title, summary: ref.summary || '', body: '', points: [] } })
838
+ }
839
+ }
840
+
841
+ if (!loaded.length && selected.length) {
842
+ return { ok: false, error: '未能读取所选档案内容,请刷新档案列表后重试' }
843
+ }
844
+
845
+ const header = `📎 【参谋长代用户带要求递交工程档案(共 ${loaded.length} 份)】`
846
+ const reqBlock = reqText
847
+ ? `📝 【用户本次明确要求】:\n${reqText}`
848
+ : '📝 【用户要求】:请重点结合以下档案内容对照推进当前任务。'
849
+ const docBlocks = loaded.map((d, idx) => {
850
+ const it = d.item
851
+ const pts = Array.isArray(it.points) && it.points.length
852
+ ? it.points.slice(0, 5).map(p => ` - ${p.title}:${clamp(p.detail || p.cue, 160)}`).join('\n')
853
+ : ''
854
+ const rawSnippet = cleanMultiline(it.rawBody || it.body || it.summary || '', 360)
855
+ return [
856
+ `### ${idx + 1}. [${d.scopeLabel}] 《${clamp(it.title || '未命名档案', 56)}》`,
857
+ it.summary ? `> 摘要:${clamp(it.summary, 140)}` : '',
858
+ pts || '',
859
+ rawSnippet && !pts ? rawSnippet : '',
860
+ ].filter(Boolean).join('\n')
861
+ })
862
+
863
+ const fullText = [header, reqBlock, '', ...docBlocks].join('\n\n')
864
+ const safeMode = ['steer', 'followup', 'silent'].includes(mode) ? mode : 'steer'
865
+ const delivery = await deliverCrossMessage(deps, {
866
+ fromSession: rootId,
867
+ fromLabel: '用户(经 DSH 参谋长递送档案)',
868
+ target: target || 'lead',
869
+ subject: loaded.length === 1 ? `递交档案《${clamp(loaded[0].item.title, 28)}》` : `合并递交 ${loaded.length} 份档案`,
870
+ text: fullText,
871
+ mode: safeMode,
872
+ })
873
+
874
+ const titlesStr = loaded.map(d => `《${clamp(d.item.title, 24)}》`).join('、')
875
+ mutateChiefState((s) => {
876
+ const ws = ensureWorkspace(s, rootId)
877
+ ws.chat.push(
878
+ {
879
+ id: nextId('chat'),
880
+ role: 'user',
881
+ text: `📎 递送档案 ${titlesStr || '(无)'}${reqText ? `\n要求:${reqText}` : ''}`,
882
+ actions: [],
883
+ at: Date.now(),
884
+ },
885
+ {
886
+ id: nextId('chat'),
887
+ role: 'chief',
888
+ text: delivery.ok
889
+ ? `- 【已按要求合并递话】已将 ${titlesStr} 连同你的要求(${safeMode === 'steer' ? '立即插话' : safeMode === 'silent' ? '静默纸条' : '排入续行'})传达给 ${delivery.target || target || '@lead'}。`
890
+ : `- 【递话失败】${delivery.error || '目标不可达'}`,
891
+ actions: delivery.ok ? [`→ ${delivery.target || target || 'lead'} (${loaded.length}卷)`] : ['递话失败'],
892
+ at: Date.now(),
893
+ },
894
+ )
895
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
896
+ })
897
+
898
+ return {
899
+ ok: Boolean(delivery && delivery.ok),
900
+ error: delivery && !delivery.ok ? delivery.error : '',
901
+ delivery,
902
+ count: loaded.length,
903
+ view: await getChiefView(deps, rootId, { autoSummarize: false }),
904
+ }
905
+ }