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/api-routes.js CHANGED
@@ -34,6 +34,17 @@ import {
34
34
  handleApprovalDecision,
35
35
  handleElevationDecision,
36
36
  } from './chief.js'
37
+ import {
38
+ getChiefActiveWork,
39
+ mutateChiefState,
40
+ ensureWorkspace,
41
+ queueChiefApproval,
42
+ normalizeSuggestion,
43
+ hasValidChiefRiskAck,
44
+ SUGGESTIONS_CAP,
45
+ CHAT_CAP,
46
+ nextId,
47
+ } from './chief-state.js'
37
48
  import {
38
49
  resolveProjectKey,
39
50
  getArchiveMeta,
@@ -48,7 +59,14 @@ import {
48
59
  mutatePrecipitated,
49
60
  copyPrecipitatedToVault,
50
61
  } from './archives.js'
51
- import { DEFAULT_CHIEF_PERMISSION_MODE } from './chief-executor.js'
62
+ import {
63
+ DEFAULT_CHIEF_PERMISSION_MODE,
64
+ HUMAN_BOUNDS_CONFIRM_TOKEN,
65
+ listGuardWalls,
66
+ normalizePermissionMode,
67
+ permissionRank,
68
+ buildCapabilityScope,
69
+ } from './chief-executor.js'
52
70
  import {
53
71
  API,
54
72
  BACKEND_BUILD,
@@ -262,11 +280,19 @@ export function createApiRoutes(deps) {
262
280
  backendBuild: BACKEND_BUILD,
263
281
  hostCompat,
264
282
  paceMode: effCfg.paceMode || 'manual',
283
+ runMode: effCfg.runMode || 'off',
284
+ managedIdleTimeoutMs: effCfg.managedIdleTimeoutMs || 15 * 60 * 1000,
285
+ thinkingEffort: effCfg.thinkingEffort || 'auto',
286
+ teamEffortMode: effCfg.teamEffortMode || 'auto',
287
+ lockedModelEfforts: effCfg.lockedModelEfforts || {},
265
288
  stopped: Boolean(effCfg.stopped || effCfg.paceMode === 'stopped'),
266
289
  permissionMode: effCfg.permissionMode || DEFAULT_CHIEF_PERMISSION_MODE,
290
+ capabilities: effCfg.capabilities || {},
291
+ policyPluginsCount: Array.isArray(effCfg.policyPlugins) ? effCfg.policyPlugins.length : 0,
267
292
  chiefRiskAcknowledged: Boolean(effCfg.chiefRiskVerified),
268
293
  pendingApprovalsCount: ((rootWs && Array.isArray(rootWs.pendingApprovals)) ? rootWs.pendingApprovals : []).filter(a => a && a.status === 'pending').length,
269
294
  hasPendingElevation: Boolean(rootWs && rootWs.pendingElevation && rootWs.pendingElevation.status === 'pending'),
295
+ auditLog: ((rootWs && Array.isArray(rootWs.auditLog)) ? rootWs.auditLog : []).slice(-50).reverse(),
270
296
  autoPilot: Boolean(effCfg.autoPilot),
271
297
  tacticalModes,
272
298
  runtimeGuard: (rootWs && rootWs.runtimeGuard) || {},
@@ -278,9 +304,11 @@ export function createApiRoutes(deps) {
278
304
  factsCount,
279
305
  mailboxCount,
280
306
  linkedPeersCount: Math.max(0, cluster.length - 1),
307
+ activeWork: getChiefActiveWork(rootSid),
281
308
  contextUsage: sessionId ? getSessionContextBreakdown(runtime, sessionId) : null,
282
309
  },
283
310
  archiveMeta,
311
+ guardWalls: listGuardWalls({ cwd: sessionArchOpt.cwd }),
284
312
  })
285
313
  } catch (error) {
286
314
  sendJson(res, 500, { ok: false, error: String(error && error.message ? error.message : error) })
@@ -310,7 +338,8 @@ export function createApiRoutes(deps) {
310
338
  agentIdentity,
311
339
  teamTasks: sessionId ? fetchTeamTasks(runtime, { id: sessionId }) : undefined,
312
340
  takenOutArchives: archCtx.takenOutArchives,
313
- sessionArchiveBriefs: archCtx.sessionArchiveBriefs,
341
+ sessionHookedArchives: archCtx.sessionHookedArchives,
342
+ desktopUsedTokens: archCtx.desktopUsedTokens,
314
343
  smartCompactActive: archCtx.smartCompactActive,
315
344
  chiefPermissionMode: archCtx.chiefPermissionMode,
316
345
  linkedPeersCount: linked.linkedPeersCount,
@@ -471,14 +500,21 @@ export function createApiRoutes(deps) {
471
500
  })
472
501
  return
473
502
  }
474
- const result = runAction(body)
503
+ const result = runAction({
504
+ ...(body && typeof body === 'object' ? body : {}),
505
+ _callerOrigin: 'human_ui',
506
+ _humanConfirmToken: HUMAN_BOUNDS_CONFIRM_TOKEN,
507
+ })
475
508
  const mergedBoard = result.ok && result.board && sessionId
476
509
  ? boardForSession(boardFileFor(sessionId))
477
510
  : result.board
478
511
  const subagents = sessionId && mergedBoard ? await refreshSubagentTree(runtime, sessionId, mergedBoard) : []
512
+ let actionCwd = process.cwd()
513
+ try { actionCwd = archiveTarget(runtime, sessionId, { vaultScope: 'session' }).cwd || actionCwd } catch {}
479
514
  sendJson(res, result.ok ? 200 : 400, {
480
515
  ...result,
481
516
  ...(mergedBoard ? { board: mergedBoard } : {}),
517
+ ...(Array.isArray(result.guardWalls) ? {} : { guardWalls: listGuardWalls({ cwd: actionCwd }) }),
482
518
  subagents,
483
519
  boundaries: boundaries(runtime, sessionId),
484
520
  })
@@ -526,6 +562,7 @@ export function createApiRoutes(deps) {
526
562
  text: typeof body.text === 'string' ? body.text : '',
527
563
  forcedTarget: typeof body.target === 'string' ? body.target : '',
528
564
  forcedMode: typeof body.mode === 'string' ? body.mode : 'steer',
565
+ quickAction: typeof body.quickAction === 'string' ? body.quickAction.trim().slice(0, 40) : '',
529
566
  images: Array.isArray(body.images) ? body.images : [],
530
567
  })
531
568
  const board = out.ok && sessionId ? boardForSession(boardFileFor(sessionId)) : undefined
@@ -603,7 +640,46 @@ export function createApiRoutes(deps) {
603
640
  const body = await readBody(req)
604
641
  const sessionId = typeof body?.session === 'string' ? body.session : ''
605
642
  const rootSid = resolveRootSessionId(sessionId) || sessionId || 'global'
606
- const updated = updateChiefConfig({ ...(body || {}), sessionId: rootSid })
643
+ const cleanBody = (body && typeof body === 'object') ? { ...body } : {}
644
+ delete cleanBody._fromUiPanel
645
+ if (cleanBody.toggleLockAgentEffort && typeof cleanBody.toggleLockAgentEffort === 'object') {
646
+ const lkTarget = String(cleanBody.toggleLockAgentEffort.target || 'lead').trim().slice(0, 64)
647
+ const lkVal = Boolean(cleanBody.toggleLockAgentEffort.locked)
648
+ const rawAliases = Array.isArray(cleanBody.toggleLockAgentEffort.aliases)
649
+ ? cleanBody.toggleLockAgentEffort.aliases.map(x => String(x || '').trim().slice(0, 64)).filter(Boolean)
650
+ : []
651
+ const shortT = lkTarget.includes('/') ? lkTarget.split('/').pop() : ''
652
+ const allKeys = Array.from(new Set([lkTarget, shortT, ...rawAliases].filter(Boolean)))
653
+ if (allKeys.length) {
654
+ const nextLocks = {
655
+ ...((cleanBody.lockedModelEfforts && typeof cleanBody.lockedModelEfforts === 'object') ? cleanBody.lockedModelEfforts : {}),
656
+ }
657
+ for (const k of allKeys) nextLocks[k] = lkVal
658
+ cleanBody.lockedModelEfforts = nextLocks
659
+ }
660
+ }
661
+ const updated = updateChiefConfig({
662
+ ...cleanBody,
663
+ sessionId: rootSid,
664
+ _fromUiPanel: true,
665
+ byUser: true,
666
+ by: 'operator',
667
+ })
668
+ let effortRes = null
669
+ if (updated && updated.ok !== false && body && body.directSetAgentEffort && typeof body.directSetAgentEffort === 'object') {
670
+ const chiefDeps = makeChiefDeps(runtime)
671
+ if (typeof chiefDeps.controlMainAgent === 'function') {
672
+ effortRes = await chiefDeps.controlMainAgent({
673
+ rootId: rootSid,
674
+ sessionId: sessionId || rootSid,
675
+ op: 'set_effort',
676
+ target: body.directSetAgentEffort.target || 'lead',
677
+ reasoningEffort: body.directSetAgentEffort.effort || 'medium',
678
+ reason: '用户从参谋面板手动调节模型思考强度',
679
+ byUser: true,
680
+ }).catch(err => ({ ok: false, error: String(err && err.message || err) }))
681
+ }
682
+ }
607
683
  const wantsInterventionOn = Boolean(body && body.tacticalModes && body.tacticalModes.intervention === true)
608
684
  const coreObjDraft = typeof body?.coreObjective === 'string' ? body.coreObjective.trim() : ''
609
685
  const targetSessionForBoard = sessionId || (rootSid !== 'global' ? rootSid : '')
@@ -622,10 +698,112 @@ export function createApiRoutes(deps) {
622
698
  if (rootSid && rootSid !== sessionId) deps.hostState.activeAutoContinue.cancelSession(rootSid, 'chief stopped')
623
699
  }
624
700
  }
701
+ let immediateKickoff = null
702
+ if (updated && updated.ok !== false && wantsInterventionOn && targetSessionForBoard && body && body.startImmediately === true) {
703
+ const boardNow = boardForSession(boardFileFor(targetSessionForBoard))
704
+ const lockedGoal = coreObjDraft || String((boardNow && boardNow.objective) || '').trim()
705
+ const stateNow = loadChiefState()
706
+ const ownWsNow = stateNow.workspaces && stateNow.workspaces[rootSid]
707
+ const cfgNow = resolveWorkspaceConfig(stateNow, rootSid)
708
+ const effectivePerm = normalizePermissionMode(cfgNow.permissionMode || DEFAULT_CHIEF_PERMISSION_MODE, {
709
+ requireAck: true,
710
+ hasChiefRiskAck: hasValidChiefRiskAck(ownWsNow),
711
+ })
712
+ const permRk = permissionRank(effectivePerm)
713
+ const agentsSvc = runtime && typeof runtime.get === 'function' ? runtime.get('agents') : null
714
+ const leadAg = agentsSvc && typeof agentsSvc.get === 'function' ? agentsSvc.get(targetSessionForBoard) : null
715
+ const leadRunning = Boolean(leadAg && leadAg.status === 'running')
716
+ if (lockedGoal && !cfgNow.stopped) {
717
+ const kickoffText = [
718
+ '【强介入已开启并锁定核心总目标 — 立即开始推进】',
719
+ `🎯 锁定核心总目标:${lockedGoal}`,
720
+ '请立即围绕上述已锁定的核心总目标核对当前看板任务与未完成项并直接推进执行(若已有待办先继续推进并在收尾时提交实测验证),无需等待用户再次手动输入“继续”。',
721
+ ].join('\n')
722
+ if (leadRunning) {
723
+ immediateKickoff = { triggered: false, alreadyRunning: true, mode: effectivePerm }
724
+ } else if (permRk >= 3) {
725
+ const chiefDeps = makeChiefDeps(runtime)
726
+ const delivRes = await deliverCrossMessage(chiefDeps, {
727
+ fromSession: rootSid,
728
+ fromLabel: 'DSH 参谋长 (强介入锁定目标立即推进)',
729
+ target: 'lead',
730
+ subject: '强介入已开启 · 立即围绕总目标推进',
731
+ text: kickoffText,
732
+ mode: 'followup',
733
+ envelopeKind: 'execution_request',
734
+ }).catch(err => ({ ok: false, error: String(err && err.message || err) }))
735
+ mutateChiefState((st) => {
736
+ const ws = ensureWorkspace(st, rootSid)
737
+ ws.chat.push({
738
+ id: nextId('chat'),
739
+ role: 'chief',
740
+ kind: 'receipt',
741
+ text: `- 【⚡ 强介入已锁定目标并立即推进】已自动向 \`@lead\` 下发首轮推进请求\n- 【🎯 锁定总目标】${lockedGoal.slice(0, 180)}`,
742
+ actions: [delivRes && delivRes.ok ? '⚡ 已立即唤醒推进' : '⚠️ 唤醒未送达'],
743
+ at: Date.now(),
744
+ })
745
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
746
+ })
747
+ immediateKickoff = { triggered: Boolean(delivRes && delivRes.ok), mode: effectivePerm }
748
+ } else if (permRk === 2) {
749
+ queueChiefApproval(rootSid, {
750
+ category: 'main_workflow',
751
+ operationLabel: '强介入开启 · 立即唤醒主对话推进',
752
+ targetLabel: '主对话 (@lead)',
753
+ reason: '强介入已锁定核心总目标,按 L2 参谋模式请您一键放行首轮推进执行请求(之后无需手动发“继续”)',
754
+ impact: '允许后立即向 @lead 投递首轮强介入推进指令',
755
+ preview: lockedGoal.slice(0, 220),
756
+ kind: 'relay',
757
+ capabilityScope: buildCapabilityScope({ kind: 'relay', tool: 'relay', target: 'lead' }),
758
+ payload: {
759
+ fromSession: rootSid,
760
+ fromLabel: 'DSH 参谋 (强介入锁定目标立即推进)',
761
+ target: 'lead',
762
+ subject: '强介入已开启 · 立即推进',
763
+ text: kickoffText,
764
+ mode: 'followup',
765
+ envelopeKind: 'execution_request',
766
+ },
767
+ by: 'chief',
768
+ })
769
+ immediateKickoff = { triggered: false, queuedApproval: true, mode: effectivePerm }
770
+ } else {
771
+ mutateChiefState((st) => {
772
+ const ws = ensureWorkspace(st, rootSid)
773
+ const sug = normalizeSuggestion({
774
+ kind: 'relay',
775
+ fromAgent: '⚡ 强介入首轮就绪',
776
+ title: '立即向主对话发首轮强介入推进指令',
777
+ reason: `已锁定核心总目标并开启强介入(当前 ${effectivePerm === 'assistant' ? 'L1 助手档' : 'L0 顾问档'},无权直改主对话工作流;升至 L2/L3 即可全自动推跑)。`,
778
+ target: 'lead',
779
+ targetLabel: '主对话 (@lead)',
780
+ mode: 'followup',
781
+ draftText: kickoffText,
782
+ })
783
+ if (sug) {
784
+ ws.suggestions.push(sug)
785
+ if (ws.suggestions.length > SUGGESTIONS_CAP) ws.suggestions = ws.suggestions.slice(-SUGGESTIONS_CAP)
786
+ }
787
+ ws.chat.push({
788
+ id: nextId('chat'),
789
+ role: 'chief',
790
+ kind: 'receipt',
791
+ text: `- 【⚡ 强介入已锁定核心总目标(当前 ${effectivePerm === 'assistant' ? 'L1' : 'L0'} 仅监督待命)】已生成首轮推进建议,升至 L2/L3 即可直接自动推动 \`@lead\`。\n- 【🎯 锁定总目标】${lockedGoal.slice(0, 180)}`,
792
+ actions: ['🎯 目标已锁定'],
793
+ at: Date.now(),
794
+ })
795
+ if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
796
+ })
797
+ immediateKickoff = { triggered: false, queuedSuggestion: true, mode: effectivePerm }
798
+ }
799
+ }
800
+ }
625
801
  const view = await getChiefView(makeChiefDeps(runtime), sessionId, { autoSummarize: false })
626
802
  const latestBoard = targetSessionForBoard ? boardForSession(boardFileFor(targetSessionForBoard)) : null
627
803
  sendJson(res, updated && updated.ok === false ? 400 : 200, {
628
804
  ...updated,
805
+ ...(effortRes ? { effortRes } : {}),
806
+ ...(immediateKickoff ? { immediateKickoff } : {}),
629
807
  ...(latestBoard ? { board: latestBoard } : {}),
630
808
  view,
631
809
  })
@@ -1142,6 +1320,7 @@ export function createApiRoutes(deps) {
1142
1320
  folder: typeof body.folder === 'string' ? body.folder : '',
1143
1321
  scope: typeof body.scope === 'string' ? body.scope : 'unorganized',
1144
1322
  instruction: typeof body.instruction === 'string' ? body.instruction : '',
1323
+ ...(typeof body.reasonKind === 'string' && body.reasonKind ? { reasonKind: body.reasonKind } : {}),
1145
1324
  })
1146
1325
  const stNow = loadChiefState()
1147
1326
  const wsNow = rootSid && stNow.workspaces ? stNow.workspaces[rootSid] : null
package/archive-core.js CHANGED
@@ -18,6 +18,10 @@ export const POINTS_CAP = 32
18
18
 
19
19
  export const PRECIPITATED_CAP = 300
20
20
 
21
+ export const DESKTOP_TOKEN_BUDGET = 2400
22
+
23
+ export const DESKTOP_MAX_ITEMS = 6
24
+
21
25
  export const SECRET_PATTERN = /(?:sk-[a-zA-Z0-9_-]{16,}|ghp_[a-zA-Z0-9]{20,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{30,}|Bearer\s+[A-Za-z0-9._~+/=-]{20,}|-----BEGIN [A-Z ]*PRIVATE KEY-----)/
22
26
 
23
27
  export const DEFAULT_ARCHIVE_FOLDERS = [
@@ -612,6 +616,86 @@ export function normalizeTags(list) {
612
616
  return out
613
617
  }
614
618
 
619
+ export function normalizeSessionIdList(list, cap = 32) {
620
+ if (!Array.isArray(list)) return []
621
+ return [...new Set(list.map(s => String(s || '').trim()).filter(Boolean))].slice(0, cap)
622
+ }
623
+
624
+ export function normalizeDesktopMeta(raw) {
625
+ const out = {}
626
+ if (!raw || typeof raw !== 'object') return out
627
+ for (const [k, v] of Object.entries(raw)) {
628
+ const sid = String(k || '').trim()
629
+ if (!sid || !v || typeof v !== 'object') continue
630
+ out[sid] = {
631
+ pinnedAt: Number(v.pinnedAt) || Date.now(),
632
+ by: clamp(v.by || 'user', 30),
633
+ priority: Number.isFinite(Number(v.priority)) ? Number(v.priority) : 0,
634
+ }
635
+ }
636
+ return out
637
+ }
638
+
639
+ export function estimateArchiveTokens(item) {
640
+ if (!item || typeof item !== 'object') return 40
641
+ const pts = (Array.isArray(item.points) ? item.points : []).slice(0, 3)
642
+ const ptText = pts.map(p => `${p.title || ''} ${p.cue || p.detail || ''}`).join(' ')
643
+ const combined = `${item.title || ''}\n${item.summary || ''}\n${ptText || (item.body || '').slice(0, 480)}`
644
+ let cjkCount = 0
645
+ let asciiCount = 0
646
+ for (let i = 0; i < combined.length; i += 1) {
647
+ if (combined.charCodeAt(i) > 127) cjkCount += 1
648
+ else asciiCount += 1
649
+ }
650
+ const est = Math.ceil(cjkCount * 0.85 + asciiCount * 0.28) + 18
651
+ return Math.max(40, est)
652
+ }
653
+
654
+ export function deriveHookFromStructuredItem(raw, forceOrganized = false) {
655
+ const src = raw && typeof raw === 'object' ? raw : {}
656
+ const isOrganized = Boolean(forceOrganized || src.organizedBy === 'chief' || src.hasHook === true)
657
+ if (!isOrganized) {
658
+ return { hasHook: false, hookKeywords: [], hookCue: '' }
659
+ }
660
+ const candidates = []
661
+ if (Array.isArray(src.hookKeywords)) candidates.push(...src.hookKeywords)
662
+ if (Array.isArray(src.tags)) candidates.push(...src.tags)
663
+ if (Array.isArray(src.points)) {
664
+ for (const pt of src.points.slice(0, 4)) {
665
+ if (pt && pt.title) candidates.push(String(pt.title).split(/[::·—]/)[0])
666
+ }
667
+ }
668
+ if (!candidates.length && src.title) {
669
+ const words = String(src.title).split(/[\s/·::()()]+/).filter(w => w.length >= 2)
670
+ candidates.push(...words.slice(0, 3))
671
+ }
672
+ const seen = new Set()
673
+ const hookKeywords = []
674
+ for (const cand of candidates) {
675
+ const kw = clamp(String(cand || '').replace(/^#+/, '').trim(), 16)
676
+ if (!kw || kw === 'anchor') continue
677
+ const low = kw.toLowerCase()
678
+ if (seen.has(low)) continue
679
+ seen.add(low)
680
+ hookKeywords.push(kw)
681
+ if (hookKeywords.length >= 5) break
682
+ }
683
+ if (!hookKeywords.length && src.folder) {
684
+ hookKeywords.push(clamp(src.folder, 16))
685
+ }
686
+ const rawCue = str(src.hookCue, '').trim()
687
+ || (Array.isArray(src.points) && src.points[0] && (src.points[0].cue || src.points[0].title))
688
+ || src.summary
689
+ || firstMeaningfulSentence(src.body || '')
690
+ || src.title
691
+ const hookCue = clamp(rawCue, 40)
692
+ return {
693
+ hasHook: true,
694
+ hookKeywords,
695
+ hookCue,
696
+ }
697
+ }
698
+
615
699
  export function normalizeArchiveItem(raw) {
616
700
  if (!raw || typeof raw !== 'object') return null
617
701
  const body = cleanMultiline(raw.body || '', 30000)
@@ -639,12 +723,23 @@ export function normalizeArchiveItem(raw) {
639
723
  140,
640
724
  )
641
725
 
642
- const takenOutSessions = Array.isArray(raw.takenOutSessions)
643
- ? [...new Set(raw.takenOutSessions.map(s => String(s || '').trim()).filter(Boolean))].slice(0, 32)
644
- : []
645
- const chiefMountedSessions = Array.isArray(raw.chiefMountedSessions)
646
- ? [...new Set(raw.chiefMountedSessions.map(s => String(s || '').trim()).filter(Boolean))].slice(0, 32)
647
- : []
726
+ const takenOutSessions = normalizeSessionIdList(raw.takenOutSessions)
727
+ const chiefMountedSessions = normalizeSessionIdList(raw.chiefMountedSessions)
728
+ const leadPulledSessions = normalizeSessionIdList(raw.leadPulledSessions)
729
+ const chiefPulledSessions = normalizeSessionIdList(raw.chiefPulledSessions)
730
+ const chiefDeliveredSessions = normalizeSessionIdList(raw.chiefDeliveredSessions)
731
+ const organizedBy = ['auto', 'chief', 'user'].includes(raw.organizedBy) ? raw.organizedBy : 'auto'
732
+ const tags = normalizeTags(Array.isArray(raw.tags) ? raw.tags : [])
733
+ const hook = deriveHookFromStructuredItem({
734
+ ...raw,
735
+ title,
736
+ summary,
737
+ folder,
738
+ tags,
739
+ points,
740
+ body,
741
+ organizedBy,
742
+ }, organizedBy === 'chief' || raw.hasHook === true)
648
743
  const contentHash = str(raw.contentHash, '').trim() || computeEntryContentHash({ title, summary, body })
649
744
 
650
745
  return {
@@ -656,11 +751,18 @@ export function normalizeArchiveItem(raw) {
656
751
  summary,
657
752
  folder,
658
753
  paperclip,
659
- tags: normalizeTags(Array.isArray(raw.tags) ? raw.tags : []),
754
+ tags,
660
755
  cold: raw.cold !== false,
661
756
  takenOutSessions,
662
757
  chiefMountedSessions,
663
- organizedBy: ['auto', 'chief', 'user'].includes(raw.organizedBy) ? raw.organizedBy : 'auto',
758
+ leadPulledSessions,
759
+ chiefPulledSessions,
760
+ chiefDeliveredSessions,
761
+ desktopMeta: normalizeDesktopMeta(raw.desktopMeta),
762
+ hasHook: hook.hasHook,
763
+ hookKeywords: hook.hookKeywords,
764
+ hookCue: hook.hookCue,
765
+ organizedBy,
664
766
  points,
665
767
  body,
666
768
  contentHash,
@@ -686,6 +788,31 @@ export function normalizeGlobalVaultEntry(raw) {
686
788
  }
687
789
  }
688
790
 
791
+ function normalizeRecentlyUnpinnedWatch(raw) {
792
+ if (!Array.isArray(raw)) return []
793
+ const out = []
794
+ const seen = new Set()
795
+ for (const item of raw) {
796
+ if (!item || typeof item !== 'object') continue
797
+ const id = str(item.id, '').trim()
798
+ const vaultScope = item.vaultScope === 'global' ? 'global' : 'session'
799
+ if (!id) continue
800
+ const key = `${vaultScope}:${id}`
801
+ if (seen.has(key)) continue
802
+ seen.add(key)
803
+ out.push({
804
+ id,
805
+ vaultScope,
806
+ title: clamp(item.title || '未命名卷宗', 120),
807
+ folder: str(item.folder, 'inbox').trim() || 'inbox',
808
+ unpinnedAt: Number(item.unpinnedAt) || Date.now(),
809
+ by: clamp(item.by || 'user', 30),
810
+ })
811
+ if (out.length >= 12) break
812
+ }
813
+ return out
814
+ }
815
+
689
816
  export function normalizeArchiveStore(raw) {
690
817
  const src = raw && typeof raw === 'object' ? raw : {}
691
818
  const folderMap = new Map()
@@ -733,6 +860,7 @@ export function normalizeArchiveStore(raw) {
733
860
  updatedAt: Number(src.updatedAt) || Date.now(),
734
861
  folders,
735
862
  items,
863
+ recentlyUnpinnedWatch: src.isSystemGlobalVault ? [] : normalizeRecentlyUnpinnedWatch(src.recentlyUnpinnedWatch),
736
864
  }
737
865
  }
738
866