dsh-chief 1.3.0 → 1.5.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-archives.js CHANGED
@@ -30,6 +30,9 @@ import {
30
30
  stripCheckpointNoise,
31
31
  isInternalCheckpointNoise,
32
32
  extractJsonObject,
33
+ beginChiefActiveWork,
34
+ endChiefActiveWork,
35
+ getChiefActiveWork,
33
36
  } from './chief-state.js'
34
37
  import { callChiefLlm } from './chief-models.js'
35
38
  import { deliverCrossMessage } from './chief-network.js'
@@ -49,12 +52,15 @@ const ORGANIZE_ARCHIVES_SYSTEM = [
49
52
  ' - "gold" : 跨会话最核心必查锚点(如工程坐标、核心红线实录)',
50
53
  ' - "silver" : 标准已验证工程经验/契约/排障记录',
51
54
  ' - "copper" : 阶段性历史存档/旧计划备查',
52
- '3. 分条分块记忆点 (`points`):',
55
+ '3. 分条分块记忆点 (`points`) 与轻量钩子 (`hookKeywords` / `hookCue`):',
53
56
  ' - 每份卷宗提炼 2~6 个结构清晰的「记忆点」,禁止把整篇堆成 1 大坨!',
54
57
  ' - 每个记忆点必须包含:',
55
58
  ' * `title` : 记忆点短标题(≤24字,点明这一条讲什么,如「症状表现」「根因与服务注入契约」「部署态验证命令」)',
56
59
  ' * `cue` : 一句话速览钩子(≤48字,未展开时就能扫一眼看懂结论)',
57
60
  ' * `detail`: 点击展开的「小点记忆」(**必须无损保留**原文中的具体命令、文件路径、行号、参数名、错误码与核心判据,严禁编造原文没有的事实!)',
61
+ ' - 同时为卷宗外表面提取轻量线索钩子:',
62
+ ' * `hookKeywords`: 2~4 个精准短词/技术关键词(每个≤10字,如 `["热更端口", "MCP配置", "sqlite路径"]`)',
63
+ ' * `hookCue` : 一句话线索提示(≤32字,供折叠状态下扫一眼判断是否需要拉阅全文)',
58
64
  '4. **只输出一个合法 JSON 对象**,格式如下:',
59
65
  '{',
60
66
  ' "newFolders": [',
@@ -66,6 +72,8 @@ const ORGANIZE_ARCHIVES_SYSTEM = [
66
72
  ' "folder": "coords|incidents|contracts|ops|plans 或自定义 id",',
67
73
  ' "paperclip": "gold|silver|copper",',
68
74
  ' "summary": "一句话卷宗总提要(≤52字)",',
75
+ ' "hookKeywords": ["关键词1", "关键词2", "关键词3"],',
76
+ ' "hookCue": "一句话线索钩子(≤32字)",',
69
77
  ' "tags": ["精炼标签1", "精炼标签2"],',
70
78
  ' "points": [',
71
79
  ' { "title": "记忆点标题", "cue": "速览钩子", "detail": "展开后的详细小点记忆(保留命令与路径)" }',
@@ -78,7 +86,7 @@ const ORGANIZE_ARCHIVES_SYSTEM = [
78
86
  /**
79
87
  * Organize & structure engineering archives via DSH Chief LLM (`请参谋长整理收纳`).
80
88
  * 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`!
89
+ * extracts lightweight hooks (`hookKeywords`/`hookCue`), and breaks walls of text into crisp `points`.
82
90
  */
83
91
  export async function organizeArchivesWithChief(deps, {
84
92
  sessionId = '',
@@ -88,6 +96,8 @@ export async function organizeArchivesWithChief(deps, {
88
96
  folder = '',
89
97
  scope = 'unorganized',
90
98
  instruction = '',
99
+ reasonKind = 'archive_organize',
100
+ quiet = false,
91
101
  } = {}) {
92
102
  const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(sessionId)) || String(sessionId || 'global')
93
103
  const effScope = vaultScope === 'global' ? 'global' : 'session'
@@ -117,8 +127,8 @@ export async function organizeArchivesWithChief(deps, {
117
127
  } else if (scope === 'all') {
118
128
  candidates = store.items.slice()
119
129
  } 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)
130
+ // Prefer unhooked / unorganized / inbox / single-point items first; if all were already organized, take newest batch
131
+ const unorg = store.items.filter(it => !it.hasHook || it.folder === 'inbox' || it.organizedBy !== 'chief' || (it.points || []).length <= 1)
122
132
  candidates = unorg.length > 0 ? unorg : store.items.slice(0, 8)
123
133
  }
124
134
 
@@ -131,6 +141,16 @@ export async function organizeArchivesWithChief(deps, {
131
141
  const selected = candidates.slice(0, MAX_ITEMS_PER_RUN)
132
142
  const remainingCount = Math.max(0, candidates.length - selected.length)
133
143
 
144
+ const isDream = reasonKind === 'dream_roam' || Boolean(quiet)
145
+ const orgWorkId = getChiefActiveWork(rootId)
146
+ ? ''
147
+ : beginChiefActiveWork(
148
+ rootId,
149
+ isDream
150
+ ? { tone: 'dream', tab: 'archive', label: '🌙 参谋长正在梦境漫游 · 轻拢卷宗与织就钩子中...' }
151
+ : { tone: 'archive', tab: 'archive', label: '参谋长正在整理档案中...' },
152
+ )
153
+ try {
134
154
  const folderLines = store.folders.map(f => `- "${f.id}": ${f.label}(${f.hint || ''})`)
135
155
  const allCurations = []
136
156
  const allNewFolders = []
@@ -156,6 +176,7 @@ export async function organizeArchivesWithChief(deps, {
156
176
 
157
177
  const llmRes = await callChiefLlm(deps, {
158
178
  sessionId: rootId,
179
+ reasonKind,
159
180
  system: ORGANIZE_ARCHIVES_SYSTEM,
160
181
  prompt: promptParts.filter(Boolean).join('\n'),
161
182
  maxTokens: SUMMARY_MAX_TOKENS,
@@ -181,6 +202,8 @@ export async function organizeArchivesWithChief(deps, {
181
202
  summary: fb.summary,
182
203
  tags: orig.tags,
183
204
  points: fb.points,
205
+ hookKeywords: Array.isArray(orig.tags) && orig.tags.length ? orig.tags.slice(0, 4) : [fb.folder],
206
+ hookCue: clamp(fb.summary || orig.title, 48),
184
207
  })
185
208
  }
186
209
  }
@@ -195,12 +218,19 @@ export async function organizeArchivesWithChief(deps, {
195
218
  summary: fb.summary,
196
219
  tags: orig.tags,
197
220
  points: fb.points,
221
+ hookKeywords: Array.isArray(orig.tags) && orig.tags.length ? orig.tags.slice(0, 4) : [fb.folder],
222
+ hookCue: clamp(fb.summary || orig.title, 48),
198
223
  })
199
224
  }
200
225
  }
201
226
  }
202
227
 
203
228
  const applied = applyChiefArchiveCurations(allCurations, allNewFolders, targetOpt)
229
+ if (effScope === 'session' && selected.length > 0) {
230
+ try {
231
+ mutateArchive({ op: 'clearUnpinnedWatch', ids: selected.map(x => x.id), vaultScope: 'session' }, targetOpt)
232
+ } catch {}
233
+ }
204
234
  const refreshedList = listArchiveHeaders(rootId, { includePrecipitated: false }, targetOpt)
205
235
  const folderNameMap = new Map(refreshedList.folders.map(f => [f.id, f.label]))
206
236
 
@@ -210,32 +240,42 @@ export async function organizeArchivesWithChief(deps, {
210
240
  folderStats.set(fName, (folderStats.get(fName) || 0) + 1)
211
241
  }
212
242
  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
- })
243
+ const reply = isDream
244
+ ? `- 【🌙 梦境漫游归整完成】已轻拢 **${applied.updatedCount} 份**零散卷宗入抽屉(${statSummary})并织就线索钩子。`
245
+ : (`- 【档案收纳完成】已${usedLlm ? '由参谋长模型深度提炼' : '按结构规则分拣'} **${applied.updatedCount} 份**工程卷宗(归入 ${statSummary}),每份均已拆解「记忆点 → 小点记忆」并织就线索钩子,原文 100% 无损封存。`
246
+ + (remainingCount > 0 ? `\n- 【分批提示】柜内另有 ${remainingCount} 份卷宗待精修,可再点一次「请参谋长整理收纳」继续完成剩余部分。` : ''))
247
+
248
+ if (!quiet) {
249
+ mutateChiefState((s) => {
250
+ const ws = ensureWorkspace(s, rootId)
251
+ ws.chat.push(
252
+ {
253
+ id: nextId('chat'),
254
+ role: 'user',
255
+ text: instruction ? `整理工程档案:${instruction}` : `请参谋长整理收纳工程档案(${applied.updatedCount} 卷)`,
256
+ actions: [],
257
+ at: Date.now(),
258
+ },
259
+ {
260
+ id: nextId('chat'),
261
+ role: 'chief',
262
+ text: reply,
263
+ actions: [`已收纳 ${applied.updatedCount} 卷档案`],
264
+ at: Date.now(),
265
+ },
266
+ )
267
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
268
+ })
269
+ }
236
270
 
237
271
  if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
238
- deps.appendBoardLog(rootId, `🗄️ 参谋长完成工程档案收纳:共精修 ${applied.updatedCount} 卷(${statSummary})`, 'chief')
272
+ deps.appendBoardLog(
273
+ rootId,
274
+ isDream
275
+ ? `🌙 参谋长梦境漫游已梳理 ${applied.updatedCount} 卷档案(${statSummary})并织就线索钩子`
276
+ : `🗄️ 参谋长完成工程档案收纳:共精修 ${applied.updatedCount} 卷(${statSummary})`,
277
+ 'chief',
278
+ )
239
279
  }
240
280
 
241
281
  return {
@@ -245,7 +285,10 @@ export async function organizeArchivesWithChief(deps, {
245
285
  usedLlm,
246
286
  reply,
247
287
  archives: refreshedList,
248
- view: await getChiefView(deps, rootId, { autoSummarize: false }),
288
+ view: quiet ? null : await getChiefView(deps, rootId, { autoSummarize: false }),
289
+ }
290
+ } finally {
291
+ if (orgWorkId) endChiefActiveWork(rootId, orgWorkId)
249
292
  }
250
293
  }
251
294
 
@@ -358,6 +401,14 @@ export async function harvestTurnDetailsToArchive(deps, {
358
401
  return { ok: false, error: '当前为空白新对话(未绑定会话 ID),请先发送一条消息或切至「🌐 全局档案柜」再抢救归档' }
359
402
  }
360
403
  const targetOpt = archiveTargetForRoot(deps, rootId, { cabinetId, vaultScope: effScope })
404
+ const harvWorkId = getChiefActiveWork(rootId)
405
+ ? ''
406
+ : beginChiefActiveWork(rootId, {
407
+ tone: 'archive',
408
+ tab: 'archive',
409
+ label: trigger === 'pre-compaction' ? '参谋长正在压缩前抢救归档中...' : '参谋长正在抢救归档中...',
410
+ })
411
+ try {
361
412
  const evidence = collectRawSessionEvidence(deps, { sessionId: sessionId || rootId, rootId, agent })
362
413
  const bodySource = [
363
414
  focusHint ? `【抢救焦点提示】${cleanMultiline(focusHint, 240)}` : '',
@@ -410,6 +461,7 @@ export async function harvestTurnDetailsToArchive(deps, {
410
461
  tags,
411
462
  points,
412
463
  body: bodySource,
464
+ organizedBy: 'chief',
413
465
  }, targetOpt)
414
466
 
415
467
  if (!saveRes || !saveRes.ok || !saveRes.item || !saveRes.item.id) {
@@ -435,6 +487,9 @@ export async function harvestTurnDetailsToArchive(deps, {
435
487
  cabinetId: targetOpt.cabinetId || verify.cabinetId || '',
436
488
  archives: listArchiveHeaders(rootId, { includePrecipitated: trigger === 'manual' }, targetOpt),
437
489
  }
490
+ } finally {
491
+ if (harvWorkId) endChiefActiveWork(rootId, harvWorkId)
492
+ }
438
493
  }
439
494
 
440
495
  const PRECIPITATE_EXPERIENCE_SYSTEM = [
@@ -492,6 +547,10 @@ export async function precipitateExperienceWithChief(deps, {
492
547
  return { ok: false, error: '当前选定范围暂无工作档案可沉淀' }
493
548
  }
494
549
 
550
+ const precWorkId = getChiefActiveWork(rootId)
551
+ ? ''
552
+ : beginChiefActiveWork(rootId, { tone: 'archive', tab: 'archive', label: '参谋长正在沉淀经验入库中...' })
553
+ try {
495
554
  const promptBody = selectedItems.slice(0, 12).map((it, idx) => [
496
555
  `--- 工作档案 #${idx + 1}: 《${it.title}》 (drawer=${it.folder}, clip=${it.paperclip}) ---`,
497
556
  `提要: ${it.summary || '无'}`,
@@ -505,6 +564,7 @@ export async function precipitateExperienceWithChief(deps, {
505
564
  try {
506
565
  const llmRes = await callChiefLlm(deps, {
507
566
  sessionId: rootId,
567
+ reasonKind: 'precipitate',
508
568
  system: PRECIPITATE_EXPERIENCE_SYSTEM,
509
569
  prompt: `待沉淀工程档案范围:${op === 'drawer' && folder ? `抽屉 ${folder}` : '整柜'}(共 ${selectedItems.length} 卷)\n\n${cleanMultiline(promptBody, 6400)}`,
510
570
  maxTokens: SUMMARY_MAX_TOKENS,
@@ -589,6 +649,9 @@ export async function precipitateExperienceWithChief(deps, {
589
649
  clearedSource,
590
650
  archives: listArchiveHeaders(rootId, { includePrecipitated: true }, targetOpt),
591
651
  }
652
+ } finally {
653
+ if (precWorkId) endChiefActiveWork(rootId, precWorkId)
654
+ }
592
655
  }
593
656
 
594
657
  const DISTILL_TO_GLOBAL_SYSTEM = [
@@ -644,6 +707,10 @@ export async function distillSessionArchivesToGlobal(deps, {
644
707
  return { ok: false, error: '当前本会话档案柜暂无可供提炼的档案条目' }
645
708
  }
646
709
 
710
+ const distWorkId = getChiefActiveWork(rootId)
711
+ ? ''
712
+ : beginChiefActiveWork(rootId, { tone: 'archive', tab: 'archive', label: '参谋长正在提炼全局档案中...' })
713
+ try {
647
714
  // Prioritize reusable engineering anchors/clips first
648
715
  const clipRank = { gold: 0, silver: 1, copper: 2 }
649
716
  selected = [...selected].sort((a, b) => (clipRank[a.paperclip] ?? 1) - (clipRank[b.paperclip] ?? 1))
@@ -661,6 +728,7 @@ export async function distillSessionArchivesToGlobal(deps, {
661
728
  try {
662
729
  const llmRes = await callChiefLlm(deps, {
663
730
  sessionId: rootId,
731
+ reasonKind: 'distill',
664
732
  system: DISTILL_TO_GLOBAL_SYSTEM,
665
733
  prompt: [
666
734
  instruction ? `用户指定提炼侧重:${clamp(instruction, 240)}\n` : '',
@@ -729,6 +797,7 @@ export async function distillSessionArchivesToGlobal(deps, {
729
797
  points: Array.isArray(raw.points) ? raw.points : [],
730
798
  body: cleanMultiline(raw.body || raw.summary || title, 4000),
731
799
  by: 'DSH 参谋长萃取',
800
+ organizedBy: 'chief',
732
801
  rootSessionId: rootId,
733
802
  }, globalOpt)
734
803
  if (res && res.ok && res.item) savedEntries.push(res.item)
@@ -779,6 +848,9 @@ export async function distillSessionArchivesToGlobal(deps, {
779
848
  globalArchives: listArchiveHeaders(rootId, { vaultScope: 'global', includePrecipitated: true, flippedIds }, globalOpt),
780
849
  view: await getChiefView(deps, rootId, { autoSummarize: false }),
781
850
  }
851
+ } finally {
852
+ if (distWorkId) endChiefActiveWork(rootId, distWorkId)
853
+ }
782
854
  }
783
855
 
784
856
  export function buildChiefArchiveUpsertFn(deps, rootId) {
@@ -795,6 +867,7 @@ export function buildChiefArchiveUpsertFn(deps, rootId) {
795
867
  body: (arc && arc.body) || '',
796
868
  tags: Array.isArray(arc && arc.tags) ? arc.tags : [],
797
869
  by: 'chief',
870
+ organizedBy: 'chief',
798
871
  }, opt)
799
872
  }
800
873
  }
@@ -903,3 +976,92 @@ export async function relayArchivesWithChief(deps, { sessionId, items = [], inst
903
976
  view: await getChiefView(deps, rootId, { autoSummarize: false }),
904
977
  }
905
978
  }
979
+
980
+ /**
981
+ * Managed-mode background「🌙 梦境漫游」:
982
+ * Gently sweeps unhooked drafts & recently unpinned desktop watch entries in session/global vaults,
983
+ * sorts them into filing-cabinet drawers, and weaves lightweight keyword hooks (`hasHook=true`).
984
+ * Strictly forbidden from writing workspace code, pinning items back to Desktop, or pushing to Lead.
985
+ */
986
+ export async function runManagedDreamRoam(deps, { sessionId = '', maxPerVault = 6 } = {}) {
987
+ const rootId = (deps && deps.resolveRootSessionId && deps.resolveRootSessionId(sessionId)) || String(sessionId || 'global')
988
+ let sessionProcessed = 0
989
+ let globalProcessed = 0
990
+ const cap = Math.max(1, Math.min(12, Number(maxPerVault) || 6))
991
+
992
+ const hasOwnSession = Boolean(rootId && rootId !== 'global')
993
+ const sessOpt = hasOwnSession ? archiveTargetForRoot(deps, rootId, { vaultScope: 'session' }) : null
994
+ const globOpt = archiveTargetForRoot(deps, rootId, { vaultScope: 'global' })
995
+
996
+ const todoSessIds = []
997
+ const alreadyHookedWatchIds = []
998
+ if (sessOpt) {
999
+ try {
1000
+ const sStore = loadArchiveStore(sessOpt)
1001
+ const watchSet = new Set((sStore.recentlyUnpinnedWatch || []).map(w => w.id))
1002
+ for (const it of (sStore.items || [])) {
1003
+ const needsWork = !it.hasHook || it.folder === 'inbox' || it.organizedBy !== 'chief' || (it.points || []).length <= 1
1004
+ if (needsWork || watchSet.has(it.id)) {
1005
+ if (needsWork) todoSessIds.push(it.id)
1006
+ else if (watchSet.has(it.id)) alreadyHookedWatchIds.push(it.id)
1007
+ }
1008
+ }
1009
+ } catch {}
1010
+ }
1011
+
1012
+ const todoGlobIds = []
1013
+ try {
1014
+ const gStore = loadArchiveStore(globOpt)
1015
+ for (const it of (gStore.items || [])) {
1016
+ if (!it.hasHook || it.folder === 'inbox' || it.organizedBy !== 'chief' || (it.points || []).length <= 1) {
1017
+ todoGlobIds.push(it.id)
1018
+ }
1019
+ }
1020
+ } catch {}
1021
+
1022
+ if (!todoSessIds.length && !todoGlobIds.length && !alreadyHookedWatchIds.length) {
1023
+ return { ok: true, roamed: 0, sessionProcessed: 0, globalProcessed: 0 }
1024
+ }
1025
+
1026
+ const dreamWorkId = getChiefActiveWork(rootId)
1027
+ ? ''
1028
+ : beginChiefActiveWork(rootId, { tone: 'dream', tab: 'archive', label: '🌙 参谋长正在梦境漫游 · 轻拢卷宗与织就钩子中...' })
1029
+
1030
+ try {
1031
+ if (alreadyHookedWatchIds.length && sessOpt) {
1032
+ try {
1033
+ mutateArchive({ op: 'clearUnpinnedWatch', ids: alreadyHookedWatchIds, vaultScope: 'session' }, sessOpt)
1034
+ } catch {}
1035
+ }
1036
+ if (todoSessIds.length && hasOwnSession) {
1037
+ const res = await organizeArchivesWithChief(deps, {
1038
+ sessionId: rootId,
1039
+ vaultScope: 'session',
1040
+ ids: todoSessIds.slice(0, cap),
1041
+ reasonKind: 'dream_roam',
1042
+ quiet: true,
1043
+ instruction: '🌙 梦境漫游归整:请仅对尚未分类/未织钩子或刚撤下桌面的本局卷宗进行分拣入屉并提炼 hookKeywords/hookCue,严禁擅自改代码或回推桌面。',
1044
+ }).catch(() => null)
1045
+ if (res && res.ok) sessionProcessed = Number(res.updatedCount) || 0
1046
+ }
1047
+ if (todoGlobIds.length) {
1048
+ const res = await organizeArchivesWithChief(deps, {
1049
+ sessionId: rootId,
1050
+ vaultScope: 'global',
1051
+ ids: todoGlobIds.slice(0, cap),
1052
+ reasonKind: 'dream_roam',
1053
+ quiet: true,
1054
+ instruction: '🌙 梦境漫游归整:请为新入全局柜的零散草稿轻拢分类并织就轻量钩子,供后续全局索引备查。',
1055
+ }).catch(() => null)
1056
+ if (res && res.ok) globalProcessed = Number(res.updatedCount) || 0
1057
+ }
1058
+ return {
1059
+ ok: true,
1060
+ roamed: sessionProcessed + globalProcessed,
1061
+ sessionProcessed,
1062
+ globalProcessed,
1063
+ }
1064
+ } finally {
1065
+ if (dreamWorkId) endChiefActiveWork(rootId, dreamWorkId)
1066
+ }
1067
+ }