dsh-chief 1.4.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.
@@ -42,9 +42,9 @@ import { deliverCrossMessage } from './chief-network.js'
42
42
  import { getChiefView } from './chief-view.js'
43
43
  import { buildChiefArchiveUpsertFn } from './chief-archives.js'
44
44
  import { buildChiefCompactFn, recordSmartCompactionChatReceipt } from './chief-compaction.js'
45
- import { askOrCommandChief } from './chief-commands.js'
45
+ import { askOrCommandChief, executeChiefArchiveInjectionOp } from './chief-commands.js'
46
46
 
47
- export async function handleSuggestionDecision(deps, { sessionId, suggestionId, decision, editedText, boundField, pinGlobal, _suppressChatReceipt = false }) {
47
+ export async function handleSuggestionDecision(deps, { sessionId, suggestionId, decision, editedText, boundField, pinGlobal, _suppressChatReceipt = false, _byUserClick = true }) {
48
48
  const rootId = deps.resolveRootSessionId(sessionId) || String(sessionId || 'global')
49
49
  let found = null
50
50
  mutateChiefState((state) => {
@@ -186,6 +186,60 @@ export async function handleSuggestionDecision(deps, { sessionId, suggestionId,
186
186
  }
187
187
  }
188
188
 
189
+ if (decision === 'approve' && found.kind === 'wall_removal') {
190
+ const cwdNow = resolveSessionWorkspaceCwd(deps, rootId)
191
+ const spec = (found.wallRemovalSpec && typeof found.wallRemovalSpec === 'object') ? found.wallRemovalSpec : {}
192
+ const targetWallId = String(spec.wallId || '').trim()
193
+ const opType = spec.action === 'remove' ? 'remove' : 'set_scope'
194
+ if (!targetWallId) {
195
+ return { ok: false, error: '拆墙申请缺少有效的目标物理驻墙 ID (wallId)' }
196
+ }
197
+ const wallRes = mutateGuardWalls({
198
+ op: opType,
199
+ wallId: targetWallId,
200
+ ...(opType === 'set_scope' ? { scope: 'paused' } : {}),
201
+ cwd: cwdNow,
202
+ callerOrigin: 'human_approval',
203
+ humanConfirmToken: HUMAN_BOUNDS_CONFIRM_TOKEN,
204
+ })
205
+ if (!wallRes || !wallRes.ok) {
206
+ return { ok: false, error: (wallRes && wallRes.error) || '按人工批复调整物理驻墙失败' }
207
+ }
208
+ const wallTitle = spec.wallTitle || (wallRes.wall && wallRes.wall.title) || targetWallId
209
+ const actVerb = opType === 'remove' ? '拆除移除' : '暂挂休眠'
210
+ mutateChiefState((state) => {
211
+ const ws = ensureWorkspace(state, rootId)
212
+ if (!_suppressChatReceipt) {
213
+ ws.chat.push({
214
+ id: nextId('chat'),
215
+ role: 'chief',
216
+ kind: 'receipt',
217
+ text: `- 【🧱 已按人工批示${actVerb}物理驻墙】${wallTitle} (\`${targetWallId}\`)\n- 【代理上报与拆墙依据】${clamp(spec.blockerEvidence || found.reason || '主/子代理撞墙无法绕过,参谋呈报经人类批准后执行', 180)}`,
218
+ actions: [`已${actVerb}驻墙`],
219
+ at: Date.now(),
220
+ })
221
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
222
+ }
223
+ pushAuditToWs(ws, {
224
+ mode: resolveWorkspaceConfig(state, rootId).permissionMode,
225
+ stage: 'guard_wall',
226
+ rule: 'wall_removal_approved',
227
+ decision: 'executed',
228
+ operation: `人工批复${actVerb}物理驻墙`,
229
+ target: `${wallTitle} (${targetWallId})`,
230
+ reason: clamp(spec.reason || found.reason || '代理撞墙无法绕过,经人类显式审批后放行', 180),
231
+ outcome: 'ok',
232
+ by: 'operator',
233
+ }, rootId)
234
+ })
235
+ return {
236
+ ok: true,
237
+ wallRemoved: { wallId: targetWallId, title: wallTitle, action: opType === 'remove' ? 'remove' : 'pause' },
238
+ guardWalls: wallRes.walls,
239
+ view: _suppressChatReceipt ? null : await getChiefView(deps, rootId, { autoSummarize: false }),
240
+ }
241
+ }
242
+
189
243
  if (decision === 'approve' && found.kind === 'goal_approval') {
190
244
  const res = deps.runAction
191
245
  ? deps.runAction({ action: 'goal.approve', session: rootId, by: 'user' })
@@ -213,6 +267,53 @@ export async function handleSuggestionDecision(deps, { sessionId, suggestionId,
213
267
  }
214
268
  }
215
269
 
270
+ if (decision === 'approve' && found.kind === 'archive_op') {
271
+ const spec = (found.archiveSpec && typeof found.archiveSpec === 'object')
272
+ ? found.archiveSpec
273
+ : ((found.archiveOp && typeof found.archiveOp === 'object') ? found.archiveOp : {})
274
+ const archRes = await executeChiefArchiveInjectionOp(deps, rootId, {
275
+ op: spec.op || 'pin_to_desktop',
276
+ vaultScope: spec.vaultScope || 'session',
277
+ id: spec.id || '',
278
+ title: spec.title || found.title || '',
279
+ target: spec.target || found.target || 'lead',
280
+ instruction: editedText || spec.instruction || found.reason || '',
281
+ }, { byLabel: 'DSH 参谋长 (获批档案调配)' }).catch(e => ({ ok: false, error: (e && e.message) || 'archive-op-failed' }))
282
+ return {
283
+ ok: Boolean(archRes && archRes.ok),
284
+ archiveApplied: archRes,
285
+ error: archRes && !archRes.ok ? archRes.error : '',
286
+ view: _suppressChatReceipt ? null : await getChiefView(deps, rootId, { autoSummarize: false }),
287
+ }
288
+ }
289
+
290
+ if (decision === 'approve' && found.kind === 'model_effort') {
291
+ const spec = (found.effortSpec && typeof found.effortSpec === 'object')
292
+ ? found.effortSpec
293
+ : ((found.effortOp && typeof found.effortOp === 'object') ? found.effortOp : {})
294
+ const target = spec.target || found.target || 'lead'
295
+ const eff = spec.effort || 'medium'
296
+ const effReason = spec.reason || found.reason || '按参谋建议调整思考强度'
297
+ const effRes = deps && typeof deps.controlMainAgent === 'function'
298
+ ? await deps.controlMainAgent({
299
+ rootId,
300
+ sessionId: rootId,
301
+ op: 'set_effort',
302
+ target,
303
+ reasoningEffort: eff,
304
+ reason: effReason,
305
+ byUser: Boolean(_byUserClick !== false),
306
+ }).catch(e => ({ ok: false, error: (e && e.message) || 'effort-failed' }))
307
+ : { ok: false, error: '当前宿主未绑定会话控制接口' }
308
+ return {
309
+ ok: Boolean(effRes && effRes.ok),
310
+ effortApplied: effRes,
311
+ lockedByUser: Boolean(effRes && effRes.lockedByUser),
312
+ error: effRes && !effRes.ok ? effRes.error : '',
313
+ view: _suppressChatReceipt ? null : await getChiefView(deps, rootId, { autoSummarize: false }),
314
+ }
315
+ }
316
+
216
317
  if (decision === 'approve' && (found.kind === 'relay' || found.kind === 'advice')) {
217
318
  const body = editedText ? cleanMultiline(editedText, 1200) : found.draftText
218
319
  const deliverTarget = found.target || 'lead'
@@ -250,6 +351,10 @@ export async function executeBatchSuggestions(deps, {
250
351
  ids = [],
251
352
  includeGoalApproval = false,
252
353
  pinGlobalDefault = undefined,
354
+ skipGuardWalls = false,
355
+ skipGlobalBounds = false,
356
+ byAutoRunner = false,
357
+ skipChatReceipt = false,
253
358
  } = {}) {
254
359
  const rootId = (deps && typeof deps.resolveRootSessionId === 'function' ? deps.resolveRootSessionId(sessionId) : '') || String(sessionId || 'global')
255
360
  const stateSnap = loadChiefState()
@@ -276,7 +381,7 @@ export async function executeBatchSuggestions(deps, {
276
381
  blocked: [],
277
382
  skippedGoals: [],
278
383
  summaries: ['当前没有待执行的参谋长建议。'],
279
- view: await getChiefView(deps, rootId, { autoSummarize: false }),
384
+ view: skipChatReceipt ? null : await getChiefView(deps, rootId, { autoSummarize: false }),
280
385
  }
281
386
  }
282
387
 
@@ -291,8 +396,20 @@ export async function executeBatchSuggestions(deps, {
291
396
  skippedGoals.push({ id: sug.id, title: sug.title })
292
397
  continue
293
398
  }
399
+ if (skipGuardWalls && (sug.kind === 'guard_wall' || sug.kind === 'wall_removal')) {
400
+ skippedGoals.push({ id: sug.id, title: sug.title })
401
+ continue
402
+ }
403
+ if (sug.kind === 'wall_removal' && byAutoRunner) {
404
+ skippedGoals.push({ id: sug.id, title: sug.title })
405
+ continue
406
+ }
407
+ if (skipGlobalBounds && sug.kind === 'bound' && sug.pinGlobal) {
408
+ skippedGoals.push({ id: sug.id, title: sug.title })
409
+ continue
410
+ }
294
411
 
295
- if (sug.kind !== 'bound' && sug.kind !== 'goal_approval' && sug.kind !== 'guard_wall') {
412
+ if (sug.kind !== 'bound' && sug.kind !== 'goal_approval' && sug.kind !== 'guard_wall' && sug.kind !== 'wall_removal') {
296
413
  const cmdSample = `${sug.draftText || ''}\n${sug.title || ''}`.trim()
297
414
  const guardRes = evaluateSafetyGuardHardRules({
298
415
  tool: 'relay',
@@ -314,7 +431,7 @@ export async function executeBatchSuggestions(deps, {
314
431
  target: clamp(sug.title, 80),
315
432
  reason: guardRes.reason,
316
433
  outcome: 'blocked',
317
- by: 'operator',
434
+ by: byAutoRunner ? 'chief' : 'operator',
318
435
  }, rootId)
319
436
  })
320
437
  blocked.push({ id: sug.id, title: sug.title, reason: guardRes.reason })
@@ -329,6 +446,7 @@ export async function executeBatchSuggestions(deps, {
329
446
  decision: 'approve',
330
447
  pinGlobal: sug.kind === 'bound' && typeof pinGlobalDefault === 'boolean' ? pinGlobalDefault : undefined,
331
448
  _suppressChatReceipt: true,
449
+ _byUserClick: !byAutoRunner,
332
450
  })
333
451
 
334
452
  if (res && res.ok) {
@@ -340,8 +458,15 @@ export async function executeBatchSuggestions(deps, {
340
458
  const scopeLabel = w.scope === 'workspace' ? '仅本工程' : '🌐全局随身'
341
459
  const patPreview = Array.isArray(w.patterns) ? clamp(w.patterns.join(', '), 60) : ''
342
460
  summaries.push(`🧱 已落锁物理驻墙「${clamp(w.title, 36)}」(${scopeLabel}${patPreview ? ` · \`${patPreview}\`` : ''})`)
461
+ } else if (res.wallRemoved) {
462
+ const r = res.wallRemoved
463
+ summaries.push(`🧱 已按人工批复${r.action === 'remove' ? '拆除' : '暂挂'}物理驻墙「${clamp(r.title || r.wallId, 36)}」`)
343
464
  } else if (res.goalApproved) {
344
465
  summaries.push('✅ 已批准并结项当前核心目标')
466
+ } else if (res.archiveApplied && res.archiveApplied.actionText) {
467
+ summaries.push(`✅ ${res.archiveApplied.actionText}`)
468
+ } else if (res.effortApplied && res.effortApplied.reasoningEffort) {
469
+ summaries.push(`✅ 🧠 已调挡 @${res.effortApplied.target || 'lead'} → ${res.effortApplied.reasoningEffort}`)
345
470
  } else if (res.delivery && res.delivery.target) {
346
471
  summaries.push(`✅ 已采纳并递话给 @${res.delivery.target}:「${clamp(sug.title, 36)}」`)
347
472
  } else {
@@ -350,7 +475,7 @@ export async function executeBatchSuggestions(deps, {
350
475
  } else {
351
476
  const errMsg = (res && res.error) || '执行未完成'
352
477
  failed.push({ id: sug.id, title: sug.title, error: errMsg })
353
- summaries.push(`⚠️ 未完成「${clamp(sug.title, 36)}」:${errMsg}`)
478
+ summaries.push(`${res && res.lockedByUser ? '🔒' : '⚠️'} ${res && res.lockedByUser ? '用户已锁挡跳过' : '未完成'}「${clamp(sug.title, 36)}」:${errMsg}`)
354
479
  }
355
480
  }
356
481
 
@@ -360,14 +485,14 @@ export async function executeBatchSuggestions(deps, {
360
485
  mode: permMode,
361
486
  stage: 'executor',
362
487
  decision: executed.length > 0 ? 'executed' : (blocked.length > 0 ? 'blocked' : 'noop'),
363
- operation: '统一执行参谋建议',
488
+ operation: byAutoRunner ? 'L3强介入一站式执行建议' : '统一执行参谋建议',
364
489
  target: `${executed.length} 项执行 / ${blocked.length} 项拦截 / ${skippedGoals.length} 项跳过`,
365
490
  reason: clamp(summaries.slice(0, 3).join(';'), 200) || '批量执行建议',
366
491
  outcome: blocked.length > 0 && executed.length === 0 ? 'blocked' : 'ok',
367
- by: 'operator',
492
+ by: byAutoRunner ? 'chief' : 'operator',
368
493
  }, rootId)
369
- if (executed.length > 0 || blocked.length > 0 || failed.length > 0) {
370
- const header = `- 【📋 统一执行参谋建议回执】完成 ${executed.length} 项${blocked.length ? ` · 拦截 ${blocked.length} 项` : ''}${failed.length ? ` · 异常 ${failed.length} 项` : ''}${skippedGoals.length ? ` · 保留目标结项请示 ${skippedGoals.length} 项单独拍板` : ''}`
494
+ if (!skipChatReceipt && (executed.length > 0 || blocked.length > 0 || failed.length > 0)) {
495
+ const header = `- 【📋 统一执行参谋建议回执】完成 ${executed.length} 项${blocked.length ? ` · 拦截 ${blocked.length} 项` : ''}${failed.length ? ` · 异常 ${failed.length} 项` : ''}${skippedGoals.length ? ` · 保留需单独拍板项 ${skippedGoals.length} 项` : ''}`
371
496
  const actionTags = [`📋 执行建议 ×${executed.length}`]
372
497
  if (blocked.length) actionTags.push(`🛡️ 红线拦截 ×${blocked.length}`)
373
498
  ws.chat.push({
@@ -393,7 +518,7 @@ export async function executeBatchSuggestions(deps, {
393
518
  failed,
394
519
  skippedGoals,
395
520
  summaries,
396
- view: await getChiefView(deps, rootId, { autoSummarize: executed.some(e => e.kind === 'bound') }),
521
+ view: skipChatReceipt ? null : await getChiefView(deps, rootId, { autoSummarize: executed.some(e => e.kind === 'bound') }),
397
522
  }
398
523
  }
399
524
 
@@ -648,6 +773,46 @@ export async function handleApprovalDecision(deps, {
648
773
  : ((execRes && execRes.error) || '压缩未完成')
649
774
  appendChiefAuditLog(rootId, { mode: currentMode, stage: 'executor', rule: 'approved_once', decision: 'executed_approved', operation: found.operationLabel, target: found.targetLabel, reason: clamp(resultMsg, 120), outcome: execOk ? 'ok' : 'error', by: 'operator' })
650
775
  }
776
+ } else if (found.kind === 'archive_op') {
777
+ const scopeCheck = verifyCapabilityScope(resolvedScope, { kind: 'archive_op', tool: 'archive_op', target: payload.title || payload.id || found.targetLabel || '' })
778
+ if (!scopeCheck.ok) {
779
+ execOk = false
780
+ execRes = { ok: false, deniedByScopeMismatch: true, error: scopeCheck.error }
781
+ resultMsg = scopeCheck.error
782
+ appendChiefAuditLog(rootId, { mode: currentMode, stage: 'scope_guard', rule: scopeCheck.rule, decision: 'rejected', operation: found.operationLabel, target: found.targetLabel, reason: scopeCheck.error, outcome: 'rejected', by: 'operator' })
783
+ } else {
784
+ execRes = await executeChiefArchiveInjectionOp(deps, rootId, payload, { input: found.reason || '', byLabel: 'DSH 参谋 (逐项授权档案调配)' })
785
+ execOk = Boolean(execRes && execRes.ok)
786
+ resultMsg = execOk ? (execRes.actionText || '已完成授权档案调配') : ((execRes && execRes.error) || '档案调配失败')
787
+ appendChiefAuditLog(rootId, { mode: currentMode, stage: 'executor', rule: 'approved_once', decision: 'executed_approved', operation: found.operationLabel, target: found.targetLabel, reason: clamp(resultMsg, 120), outcome: execOk ? 'ok' : 'error', by: 'operator' })
788
+ }
789
+ } else if (found.kind === 'model_effort') {
790
+ const effTarget = payload.target || 'lead'
791
+ const scopeCheck = verifyCapabilityScope(resolvedScope, { kind: 'model_effort', tool: 'model_effort', target: effTarget })
792
+ if (!scopeCheck.ok) {
793
+ execOk = false
794
+ execRes = { ok: false, deniedByScopeMismatch: true, error: scopeCheck.error }
795
+ resultMsg = scopeCheck.error
796
+ appendChiefAuditLog(rootId, { mode: currentMode, stage: 'scope_guard', rule: scopeCheck.rule, decision: 'rejected', operation: found.operationLabel, target: found.targetLabel, reason: scopeCheck.error, outcome: 'rejected', by: 'operator' })
797
+ } else if (deps && typeof deps.controlMainAgent === 'function') {
798
+ execRes = await deps.controlMainAgent({
799
+ rootId,
800
+ sessionId: rootId,
801
+ op: 'set_effort',
802
+ target: effTarget,
803
+ reasoningEffort: payload.reasoningEffort || payload.effort || 'medium',
804
+ reason: payload.reason || found.reason || '',
805
+ byUser: false,
806
+ })
807
+ execOk = Boolean(execRes && execRes.ok)
808
+ resultMsg = execOk
809
+ ? `已将 @${effTarget} 思考强度调为 ${execRes.reasoningEffort || payload.reasoningEffort || 'medium'}`
810
+ : ((execRes && execRes.error) || '思考强度调配未成功')
811
+ appendChiefAuditLog(rootId, { mode: currentMode, stage: execRes && execRes.lockedByUser ? 'model_effort_lock' : 'executor', rule: execRes && execRes.lockedByUser ? 'user_effort_lock' : 'approved_once', decision: execOk ? 'executed_approved' : 'blocked', operation: found.operationLabel, target: found.targetLabel, reason: clamp(resultMsg, 120), outcome: execOk ? 'ok' : 'blocked', by: 'operator' })
812
+ } else {
813
+ execOk = false
814
+ resultMsg = '当前宿主未提供代理思考强度控制接口'
815
+ }
651
816
  } else if (found.kind === 'auto_continue') {
652
817
  if (deps && typeof deps.triggerAutoContinueNow === 'function') {
653
818
  execRes = await deps.triggerAutoContinueNow(payload.sessionId || rootId, payload.trigger || 'turn/end:approved', { detail: payload.detail || '' })
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)
@@ -428,6 +461,7 @@ export async function harvestTurnDetailsToArchive(deps, {
428
461
  tags,
429
462
  points,
430
463
  body: bodySource,
464
+ organizedBy: 'chief',
431
465
  }, targetOpt)
432
466
 
433
467
  if (!saveRes || !saveRes.ok || !saveRes.item || !saveRes.item.id) {
@@ -530,6 +564,7 @@ export async function precipitateExperienceWithChief(deps, {
530
564
  try {
531
565
  const llmRes = await callChiefLlm(deps, {
532
566
  sessionId: rootId,
567
+ reasonKind: 'precipitate',
533
568
  system: PRECIPITATE_EXPERIENCE_SYSTEM,
534
569
  prompt: `待沉淀工程档案范围:${op === 'drawer' && folder ? `抽屉 ${folder}` : '整柜'}(共 ${selectedItems.length} 卷)\n\n${cleanMultiline(promptBody, 6400)}`,
535
570
  maxTokens: SUMMARY_MAX_TOKENS,
@@ -693,6 +728,7 @@ export async function distillSessionArchivesToGlobal(deps, {
693
728
  try {
694
729
  const llmRes = await callChiefLlm(deps, {
695
730
  sessionId: rootId,
731
+ reasonKind: 'distill',
696
732
  system: DISTILL_TO_GLOBAL_SYSTEM,
697
733
  prompt: [
698
734
  instruction ? `用户指定提炼侧重:${clamp(instruction, 240)}\n` : '',
@@ -761,6 +797,7 @@ export async function distillSessionArchivesToGlobal(deps, {
761
797
  points: Array.isArray(raw.points) ? raw.points : [],
762
798
  body: cleanMultiline(raw.body || raw.summary || title, 4000),
763
799
  by: 'DSH 参谋长萃取',
800
+ organizedBy: 'chief',
764
801
  rootSessionId: rootId,
765
802
  }, globalOpt)
766
803
  if (res && res.ok && res.item) savedEntries.push(res.item)
@@ -830,6 +867,7 @@ export function buildChiefArchiveUpsertFn(deps, rootId) {
830
867
  body: (arc && arc.body) || '',
831
868
  tags: Array.isArray(arc && arc.tags) ? arc.tags : [],
832
869
  by: 'chief',
870
+ organizedBy: 'chief',
833
871
  }, opt)
834
872
  }
835
873
  }
@@ -938,3 +976,92 @@ export async function relayArchivesWithChief(deps, { sessionId, items = [], inst
938
976
  view: await getChiefView(deps, rootId, { autoSummarize: false }),
939
977
  }
940
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
+ }