dsh-chief 1.4.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/chief-archives.js CHANGED
@@ -52,12 +52,15 @@ const ORGANIZE_ARCHIVES_SYSTEM = [
52
52
  ' - "gold" : 跨会话最核心必查锚点(如工程坐标、核心红线实录)',
53
53
  ' - "silver" : 标准已验证工程经验/契约/排障记录',
54
54
  ' - "copper" : 阶段性历史存档/旧计划备查',
55
- '3. 分条分块记忆点 (`points`):',
55
+ '3. 分条分块记忆点 (`points`) 与轻量钩子 (`hookKeywords` / `hookCue`):',
56
56
  ' - 每份卷宗提炼 2~6 个结构清晰的「记忆点」,禁止把整篇堆成 1 大坨!',
57
57
  ' - 每个记忆点必须包含:',
58
58
  ' * `title` : 记忆点短标题(≤24字,点明这一条讲什么,如「症状表现」「根因与服务注入契约」「部署态验证命令」)',
59
59
  ' * `cue` : 一句话速览钩子(≤48字,未展开时就能扫一眼看懂结论)',
60
60
  ' * `detail`: 点击展开的「小点记忆」(**必须无损保留**原文中的具体命令、文件路径、行号、参数名、错误码与核心判据,严禁编造原文没有的事实!)',
61
+ ' - 同时为卷宗外表面提取轻量线索钩子:',
62
+ ' * `hookKeywords`: 2~4 个精准短词/技术关键词(每个≤10字,如 `["热更端口", "MCP配置", "sqlite路径"]`)',
63
+ ' * `hookCue` : 一句话线索提示(≤32字,供折叠状态下扫一眼判断是否需要拉阅全文)',
61
64
  '4. **只输出一个合法 JSON 对象**,格式如下:',
62
65
  '{',
63
66
  ' "newFolders": [',
@@ -69,6 +72,8 @@ const ORGANIZE_ARCHIVES_SYSTEM = [
69
72
  ' "folder": "coords|incidents|contracts|ops|plans 或自定义 id",',
70
73
  ' "paperclip": "gold|silver|copper",',
71
74
  ' "summary": "一句话卷宗总提要(≤52字)",',
75
+ ' "hookKeywords": ["关键词1", "关键词2", "关键词3"],',
76
+ ' "hookCue": "一句话线索钩子(≤32字)",',
72
77
  ' "tags": ["精炼标签1", "精炼标签2"],',
73
78
  ' "points": [',
74
79
  ' { "title": "记忆点标题", "cue": "速览钩子", "detail": "展开后的详细小点记忆(保留命令与路径)" }',
@@ -81,7 +86,7 @@ const ORGANIZE_ARCHIVES_SYSTEM = [
81
86
  /**
82
87
  * Organize & structure engineering archives via DSH Chief LLM (`请参谋长整理收纳`).
83
88
  * Classifies dossiers into filing-cabinet folders, assigns gold/silver/copper paperclips,
84
- * 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`.
85
90
  */
86
91
  export async function organizeArchivesWithChief(deps, {
87
92
  sessionId = '',
@@ -91,6 +96,8 @@ export async function organizeArchivesWithChief(deps, {
91
96
  folder = '',
92
97
  scope = 'unorganized',
93
98
  instruction = '',
99
+ reasonKind = 'archive_organize',
100
+ quiet = false,
94
101
  } = {}) {
95
102
  const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(sessionId)) || String(sessionId || 'global')
96
103
  const effScope = vaultScope === 'global' ? 'global' : 'session'
@@ -120,8 +127,8 @@ export async function organizeArchivesWithChief(deps, {
120
127
  } else if (scope === 'all') {
121
128
  candidates = store.items.slice()
122
129
  } else {
123
- // Prefer unorganized / inbox / single-point items first; if all were already organized, take newest batch
124
- 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)
125
132
  candidates = unorg.length > 0 ? unorg : store.items.slice(0, 8)
126
133
  }
127
134
 
@@ -134,9 +141,15 @@ export async function organizeArchivesWithChief(deps, {
134
141
  const selected = candidates.slice(0, MAX_ITEMS_PER_RUN)
135
142
  const remainingCount = Math.max(0, candidates.length - selected.length)
136
143
 
144
+ const isDream = reasonKind === 'dream_roam' || Boolean(quiet)
137
145
  const orgWorkId = getChiefActiveWork(rootId)
138
146
  ? ''
139
- : beginChiefActiveWork(rootId, { tone: 'archive', tab: 'archive', label: '参谋长正在整理档案中...' })
147
+ : beginChiefActiveWork(
148
+ rootId,
149
+ isDream
150
+ ? { tone: 'dream', tab: 'archive', label: '🌙 参谋长正在梦境漫游 · 轻拢卷宗与织就钩子中...' }
151
+ : { tone: 'archive', tab: 'archive', label: '参谋长正在整理档案中...' },
152
+ )
140
153
  try {
141
154
  const folderLines = store.folders.map(f => `- "${f.id}": ${f.label}(${f.hint || ''})`)
142
155
  const allCurations = []
@@ -163,6 +176,7 @@ export async function organizeArchivesWithChief(deps, {
163
176
 
164
177
  const llmRes = await callChiefLlm(deps, {
165
178
  sessionId: rootId,
179
+ reasonKind,
166
180
  system: ORGANIZE_ARCHIVES_SYSTEM,
167
181
  prompt: promptParts.filter(Boolean).join('\n'),
168
182
  maxTokens: SUMMARY_MAX_TOKENS,
@@ -188,6 +202,8 @@ export async function organizeArchivesWithChief(deps, {
188
202
  summary: fb.summary,
189
203
  tags: orig.tags,
190
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),
191
207
  })
192
208
  }
193
209
  }
@@ -202,12 +218,19 @@ export async function organizeArchivesWithChief(deps, {
202
218
  summary: fb.summary,
203
219
  tags: orig.tags,
204
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),
205
223
  })
206
224
  }
207
225
  }
208
226
  }
209
227
 
210
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
+ }
211
234
  const refreshedList = listArchiveHeaders(rootId, { includePrecipitated: false }, targetOpt)
212
235
  const folderNameMap = new Map(refreshedList.folders.map(f => [f.id, f.label]))
213
236
 
@@ -217,32 +240,42 @@ export async function organizeArchivesWithChief(deps, {
217
240
  folderStats.set(fName, (folderStats.get(fName) || 0) + 1)
218
241
  }
219
242
  const statSummary = [...folderStats.entries()].map(([k, n]) => `「${k}」${n} 卷`).join('、')
220
- const reply = `- 【档案收纳完成】已${usedLlm ? '由参谋长模型深度提炼' : '按结构规则分拣'} **${applied.updatedCount} 份**工程卷宗(归入 ${statSummary}),每份均已拆解「记忆点 → 小点记忆」,原文 100% 无损封存。`
221
- + (remainingCount > 0 ? `\n- 【分批提示】柜内另有 ${remainingCount} 份卷宗待精修,可再点一次「请参谋长整理收纳」继续完成剩余部分。` : '')
222
-
223
- mutateChiefState((s) => {
224
- const ws = ensureWorkspace(s, rootId)
225
- ws.chat.push(
226
- {
227
- id: nextId('chat'),
228
- role: 'user',
229
- text: instruction ? `整理工程档案:${instruction}` : `请参谋长整理收纳工程档案(${applied.updatedCount} 卷)`,
230
- actions: [],
231
- at: Date.now(),
232
- },
233
- {
234
- id: nextId('chat'),
235
- role: 'chief',
236
- text: reply,
237
- actions: [`已收纳 ${applied.updatedCount} 卷档案`],
238
- at: Date.now(),
239
- },
240
- )
241
- if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
242
- })
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
+ }
243
270
 
244
271
  if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
245
- 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
+ )
246
279
  }
247
280
 
248
281
  return {
@@ -252,7 +285,7 @@ export async function organizeArchivesWithChief(deps, {
252
285
  usedLlm,
253
286
  reply,
254
287
  archives: refreshedList,
255
- view: await getChiefView(deps, rootId, { autoSummarize: false }),
288
+ view: quiet ? null : await getChiefView(deps, rootId, { autoSummarize: false }),
256
289
  }
257
290
  } finally {
258
291
  if (orgWorkId) endChiefActiveWork(rootId, orgWorkId)
@@ -387,6 +420,7 @@ export async function harvestTurnDetailsToArchive(deps, {
387
420
  try {
388
421
  const llmRes = await callChiefLlm(deps, {
389
422
  sessionId: rootId,
423
+ reasonKind: 'archive_harvest',
390
424
  system: HARVEST_ARCHIVE_SYSTEM,
391
425
  prompt: `触发模式:${trigger === 'pre-compaction' ? '上下文压缩前自动高保真抢救' : '用户手动抢救当前工作细节入柜'}\n\n${cleanMultiline(bodySource, 5200)}`,
392
426
  maxTokens: SUMMARY_MAX_TOKENS,
@@ -428,6 +462,7 @@ export async function harvestTurnDetailsToArchive(deps, {
428
462
  tags,
429
463
  points,
430
464
  body: bodySource,
465
+ organizedBy: 'chief',
431
466
  }, targetOpt)
432
467
 
433
468
  if (!saveRes || !saveRes.ok || !saveRes.item || !saveRes.item.id) {
@@ -530,6 +565,7 @@ export async function precipitateExperienceWithChief(deps, {
530
565
  try {
531
566
  const llmRes = await callChiefLlm(deps, {
532
567
  sessionId: rootId,
568
+ reasonKind: 'precipitate',
533
569
  system: PRECIPITATE_EXPERIENCE_SYSTEM,
534
570
  prompt: `待沉淀工程档案范围:${op === 'drawer' && folder ? `抽屉 ${folder}` : '整柜'}(共 ${selectedItems.length} 卷)\n\n${cleanMultiline(promptBody, 6400)}`,
535
571
  maxTokens: SUMMARY_MAX_TOKENS,
@@ -693,6 +729,7 @@ export async function distillSessionArchivesToGlobal(deps, {
693
729
  try {
694
730
  const llmRes = await callChiefLlm(deps, {
695
731
  sessionId: rootId,
732
+ reasonKind: 'distill',
696
733
  system: DISTILL_TO_GLOBAL_SYSTEM,
697
734
  prompt: [
698
735
  instruction ? `用户指定提炼侧重:${clamp(instruction, 240)}\n` : '',
@@ -761,6 +798,7 @@ export async function distillSessionArchivesToGlobal(deps, {
761
798
  points: Array.isArray(raw.points) ? raw.points : [],
762
799
  body: cleanMultiline(raw.body || raw.summary || title, 4000),
763
800
  by: 'DSH 参谋长萃取',
801
+ organizedBy: 'chief',
764
802
  rootSessionId: rootId,
765
803
  }, globalOpt)
766
804
  if (res && res.ok && res.item) savedEntries.push(res.item)
@@ -830,6 +868,7 @@ export function buildChiefArchiveUpsertFn(deps, rootId) {
830
868
  body: (arc && arc.body) || '',
831
869
  tags: Array.isArray(arc && arc.tags) ? arc.tags : [],
832
870
  by: 'chief',
871
+ organizedBy: 'chief',
833
872
  }, opt)
834
873
  }
835
874
  }
@@ -938,3 +977,92 @@ export async function relayArchivesWithChief(deps, { sessionId, items = [], inst
938
977
  view: await getChiefView(deps, rootId, { autoSummarize: false }),
939
978
  }
940
979
  }
980
+
981
+ /**
982
+ * Managed-mode background「🌙 梦境漫游」:
983
+ * Gently sweeps unhooked drafts & recently unpinned desktop watch entries in session/global vaults,
984
+ * sorts them into filing-cabinet drawers, and weaves lightweight keyword hooks (`hasHook=true`).
985
+ * Strictly forbidden from writing workspace code, pinning items back to Desktop, or pushing to Lead.
986
+ */
987
+ export async function runManagedDreamRoam(deps, { sessionId = '', maxPerVault = 6 } = {}) {
988
+ const rootId = (deps && deps.resolveRootSessionId && deps.resolveRootSessionId(sessionId)) || String(sessionId || 'global')
989
+ let sessionProcessed = 0
990
+ let globalProcessed = 0
991
+ const cap = Math.max(1, Math.min(12, Number(maxPerVault) || 6))
992
+
993
+ const hasOwnSession = Boolean(rootId && rootId !== 'global')
994
+ const sessOpt = hasOwnSession ? archiveTargetForRoot(deps, rootId, { vaultScope: 'session' }) : null
995
+ const globOpt = archiveTargetForRoot(deps, rootId, { vaultScope: 'global' })
996
+
997
+ const todoSessIds = []
998
+ const alreadyHookedWatchIds = []
999
+ if (sessOpt) {
1000
+ try {
1001
+ const sStore = loadArchiveStore(sessOpt)
1002
+ const watchSet = new Set((sStore.recentlyUnpinnedWatch || []).map(w => w.id))
1003
+ for (const it of (sStore.items || [])) {
1004
+ const needsWork = !it.hasHook || it.folder === 'inbox' || it.organizedBy !== 'chief' || (it.points || []).length <= 1
1005
+ if (needsWork || watchSet.has(it.id)) {
1006
+ if (needsWork) todoSessIds.push(it.id)
1007
+ else if (watchSet.has(it.id)) alreadyHookedWatchIds.push(it.id)
1008
+ }
1009
+ }
1010
+ } catch {}
1011
+ }
1012
+
1013
+ const todoGlobIds = []
1014
+ try {
1015
+ const gStore = loadArchiveStore(globOpt)
1016
+ for (const it of (gStore.items || [])) {
1017
+ if (!it.hasHook || it.folder === 'inbox' || it.organizedBy !== 'chief' || (it.points || []).length <= 1) {
1018
+ todoGlobIds.push(it.id)
1019
+ }
1020
+ }
1021
+ } catch {}
1022
+
1023
+ if (!todoSessIds.length && !todoGlobIds.length && !alreadyHookedWatchIds.length) {
1024
+ return { ok: true, roamed: 0, sessionProcessed: 0, globalProcessed: 0 }
1025
+ }
1026
+
1027
+ const dreamWorkId = getChiefActiveWork(rootId)
1028
+ ? ''
1029
+ : beginChiefActiveWork(rootId, { tone: 'dream', tab: 'archive', label: '🌙 参谋长正在梦境漫游 · 轻拢卷宗与织就钩子中...' })
1030
+
1031
+ try {
1032
+ if (alreadyHookedWatchIds.length && sessOpt) {
1033
+ try {
1034
+ mutateArchive({ op: 'clearUnpinnedWatch', ids: alreadyHookedWatchIds, vaultScope: 'session' }, sessOpt)
1035
+ } catch {}
1036
+ }
1037
+ if (todoSessIds.length && hasOwnSession) {
1038
+ const res = await organizeArchivesWithChief(deps, {
1039
+ sessionId: rootId,
1040
+ vaultScope: 'session',
1041
+ ids: todoSessIds.slice(0, cap),
1042
+ reasonKind: 'dream_roam',
1043
+ quiet: true,
1044
+ instruction: '🌙 梦境漫游归整:请仅对尚未分类/未织钩子或刚撤下桌面的本局卷宗进行分拣入屉并提炼 hookKeywords/hookCue,严禁擅自改代码或回推桌面。',
1045
+ }).catch(() => null)
1046
+ if (res && res.ok) sessionProcessed = Number(res.updatedCount) || 0
1047
+ }
1048
+ if (todoGlobIds.length) {
1049
+ const res = await organizeArchivesWithChief(deps, {
1050
+ sessionId: rootId,
1051
+ vaultScope: 'global',
1052
+ ids: todoGlobIds.slice(0, cap),
1053
+ reasonKind: 'dream_roam',
1054
+ quiet: true,
1055
+ instruction: '🌙 梦境漫游归整:请为新入全局柜的零散草稿轻拢分类并织就轻量钩子,供后续全局索引备查。',
1056
+ }).catch(() => null)
1057
+ if (res && res.ok) globalProcessed = Number(res.updatedCount) || 0
1058
+ }
1059
+ return {
1060
+ ok: true,
1061
+ roamed: sessionProcessed + globalProcessed,
1062
+ sessionProcessed,
1063
+ globalProcessed,
1064
+ }
1065
+ } finally {
1066
+ if (dreamWorkId) endChiefActiveWork(rootId, dreamWorkId)
1067
+ }
1068
+ }