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.
@@ -9,6 +9,8 @@ import {
9
9
  POINTS_CAP,
10
10
  SECRET_PATTERN,
11
11
  DEFAULT_ARCHIVE_FOLDERS,
12
+ DESKTOP_TOKEN_BUDGET,
13
+ DESKTOP_MAX_ITEMS,
12
14
  nextId,
13
15
  str,
14
16
  clamp,
@@ -23,6 +25,10 @@ import {
23
25
  normalizeFolder,
24
26
  normalizePoint,
25
27
  normalizeTags,
28
+ normalizeSessionIdList,
29
+ normalizeDesktopMeta,
30
+ estimateArchiveTokens,
31
+ deriveHookFromStructuredItem,
26
32
  normalizeArchiveItem,
27
33
  normalizeGlobalVaultEntry,
28
34
  firstMeaningfulSentence,
@@ -252,6 +258,111 @@ export function getThreeTierArchiveCounts(rootSessionId = '', flippedIds = [], t
252
258
  }
253
259
  }
254
260
 
261
+ export function computeArchiveViewerStatus(item, sid = '', vaultScope = 'session') {
262
+ const takenOut = Boolean(sid && Array.isArray(item?.takenOutSessions) && item.takenOutSessions.includes(sid))
263
+ if (takenOut) {
264
+ return {
265
+ code: 'on_desktop',
266
+ tone: 'amber',
267
+ label: vaultScope === 'global'
268
+ ? '📌 桌面在读(全局调入) · 主代理与参谋同看'
269
+ : '📌 桌面在读 · 主代理与参谋同看',
270
+ }
271
+ }
272
+ if (vaultScope === 'global') {
273
+ if (sid && Array.isArray(item?.chiefDeliveredSessions) && item.chiefDeliveredSessions.includes(sid)) {
274
+ return { code: 'global_delivered', tone: 'cyan', label: '📨 参谋已递交本局主代理' }
275
+ }
276
+ if (sid && (
277
+ (Array.isArray(item?.chiefMountedSessions) && item.chiefMountedSessions.includes(sid))
278
+ || (Array.isArray(item?.chiefPulledSessions) && item.chiefPulledSessions.includes(sid))
279
+ )) {
280
+ return { code: 'chief_reading', tone: 'accent', label: '👁️ 参谋参阅中' }
281
+ }
282
+ if (item?.hasHook) {
283
+ return { code: 'global_hooked', tone: 'purple', label: '🪝 参谋见钩可拉(主会话隔离)' }
284
+ }
285
+ return { code: 'human_only', tone: 'muted', label: '🔒 仅人类可见(待整理织钩)' }
286
+ }
287
+ if (sid && Array.isArray(item?.leadPulledSessions) && item.leadPulledSessions.includes(sid)) {
288
+ return { code: 'lead_pulled', tone: 'emerald', label: '📖 主代理已拉阅 · 参谋可读' }
289
+ }
290
+ if (sid && Array.isArray(item?.chiefDeliveredSessions) && item.chiefDeliveredSessions.includes(sid)) {
291
+ return { code: 'chief_delivered', tone: 'cyan', label: '📨 参谋已递交主代理 · 参谋可读' }
292
+ }
293
+ if (item?.hasHook) {
294
+ return { code: 'session_hooked', tone: 'teal', label: '🪝 主代理见钩可拉 · 参谋可读' }
295
+ }
296
+ return { code: 'chief_only', tone: 'blue', label: '👁️ 仅参谋可读(待整理织钩)' }
297
+ }
298
+
299
+ function buildDesktopSummary(sid, sessionStore, globalStore) {
300
+ const pinnedDocuments = []
301
+ if (sid) {
302
+ const pushDesk = (items, scope) => {
303
+ for (const it of (Array.isArray(items) ? items : [])) {
304
+ if (!Array.isArray(it.takenOutSessions) || !it.takenOutSessions.includes(sid)) continue
305
+ const meta = (it.desktopMeta && it.desktopMeta[sid]) || {}
306
+ pinnedDocuments.push({
307
+ id: it.id,
308
+ title: it.title,
309
+ summary: it.summary,
310
+ folder: it.folder,
311
+ paperclip: it.paperclip,
312
+ vaultScope: scope,
313
+ tags: it.tags || [],
314
+ hasHook: Boolean(it.hasHook),
315
+ hookKeywords: Array.isArray(it.hookKeywords) ? it.hookKeywords : [],
316
+ hookCue: it.hookCue || '',
317
+ estimatedTokens: estimateArchiveTokens(it),
318
+ pinnedAt: Number(meta.pinnedAt) || Number(it.updatedAt) || 0,
319
+ pinnedBy: meta.by || 'user',
320
+ viewerStatus: computeArchiveViewerStatus(it, sid, scope),
321
+ points: Array.isArray(it.points) ? it.points : [],
322
+ })
323
+ }
324
+ }
325
+ if (sessionStore && !sessionStore.unboundSession) pushDesk(sessionStore.items, 'session')
326
+ if (globalStore) pushDesk(globalStore.items, 'global')
327
+ }
328
+ pinnedDocuments.sort((a, b) => (b.pinnedAt || 0) - (a.pinnedAt || 0))
329
+ const usedTokens = pinnedDocuments.reduce((acc, it) => acc + (Number(it.estimatedTokens) || 0), 0)
330
+ return {
331
+ pinnedDocuments,
332
+ usedTokens,
333
+ tokenBudget: DESKTOP_TOKEN_BUDGET,
334
+ maxItems: DESKTOP_MAX_ITEMS,
335
+ usagePct: Math.min(100, Math.round((usedTokens / DESKTOP_TOKEN_BUDGET) * 100)),
336
+ recentlyUnpinnedWatch: (sessionStore && Array.isArray(sessionStore.recentlyUnpinnedWatch))
337
+ ? sessionStore.recentlyUnpinnedWatch
338
+ : [],
339
+ }
340
+ }
341
+
342
+ function buildPrecipitatedFolderMeta(precipList = []) {
343
+ const counts = {}
344
+ const golds = {}
345
+ const folderMap = new Map(DEFAULT_ARCHIVE_FOLDERS.map(f => [f.id, { ...f }]))
346
+ for (const p of (Array.isArray(precipList) ? precipList : [])) {
347
+ if (!p) continue
348
+ const fid = str(p.folder, 'ops').trim() || 'ops'
349
+ counts[fid] = (counts[fid] || 0) + 1
350
+ if (p.paperclip === 'gold') golds[fid] = (golds[fid] || 0) + 1
351
+ if (!folderMap.has(fid)) {
352
+ folderMap.set(fid, {
353
+ id: fid,
354
+ label: clamp(fid, 40),
355
+ hint: '冷藏沉淀分类抽屉',
356
+ accent: '#f59e0b',
357
+ order: 65,
358
+ })
359
+ }
360
+ }
361
+ return [...folderMap.values()]
362
+ .sort((a, b) => (a.order || 99) - (b.order || 99))
363
+ .map(f => ({ ...f, count: counts[f.id] || 0, goldCount: golds[f.id] || 0 }))
364
+ }
365
+
255
366
  /**
256
367
  * Tier-1 Lazy Load (`GET /api/dsh-chief/archives`):
257
368
  * - `scope === 'global'`: reads standalone System Global Cold Vault (`global-vault/vault-chief-global.json`),
@@ -306,6 +417,8 @@ export function listArchiveHeaders(rootSessionId = '', opts = {}, targetOpt) {
306
417
  const hay = [
307
418
  it.title,
308
419
  it.summary,
420
+ (it.hookKeywords || []).join(' '),
421
+ it.hookCue || '',
309
422
  (it.tags || []).join(' '),
310
423
  ...(it.points || []).map(p => `${p.title} ${p.cue}`),
311
424
  it.body,
@@ -328,6 +441,7 @@ export function listArchiveHeaders(rootSessionId = '', opts = {}, targetOpt) {
328
441
  goldCount: goldByFolder[f.id] || 0,
329
442
  }))
330
443
 
444
+ const activeScopeName = isGlobalReq ? 'global' : 'session'
331
445
  const headers = filtered.map((it) => {
332
446
  const diffEntry = (isGlobalReq ? diff.globalDiffMap.get(it.id) : diff.sessionDiffMap.get(it.id)) || {}
333
447
  return {
@@ -340,8 +454,16 @@ export function listArchiveHeaders(rootSessionId = '', opts = {}, targetOpt) {
340
454
  paperclip: it.paperclip,
341
455
  tags: it.tags,
342
456
  cold: true,
457
+ hasHook: Boolean(it.hasHook),
458
+ hookKeywords: Array.isArray(it.hookKeywords) ? it.hookKeywords : [],
459
+ hookCue: it.hookCue || '',
460
+ estimatedTokens: estimateArchiveTokens(it),
343
461
  takenOut: Boolean(sid && Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid)),
344
462
  chiefMounted: Boolean(isGlobalReq && sid && Array.isArray(it.chiefMountedSessions) && it.chiefMountedSessions.includes(sid)),
463
+ leadPulled: Boolean(!isGlobalReq && sid && Array.isArray(it.leadPulledSessions) && it.leadPulledSessions.includes(sid)),
464
+ chiefPulled: Boolean(sid && Array.isArray(it.chiefPulledSessions) && it.chiefPulledSessions.includes(sid)),
465
+ chiefDelivered: Boolean(sid && Array.isArray(it.chiefDeliveredSessions) && it.chiefDeliveredSessions.includes(sid)),
466
+ viewerStatus: computeArchiveViewerStatus(it, sid, activeScopeName),
345
467
  diffStatus: diffEntry.diffStatus || (isGlobalReq ? (sid ? 'global_only' : 'unbound') : 'local_only'),
346
468
  matchedGlobalId: !isGlobalReq ? (diffEntry.matchedGlobalId || '') : '',
347
469
  matchedSessionItemId: isGlobalReq ? (diffEntry.matchedSessionItemId || '') : '',
@@ -359,10 +481,27 @@ export function listArchiveHeaders(rootSessionId = '', opts = {}, targetOpt) {
359
481
  const precipitated = includePrecipitated
360
482
  ? listPrecipitatedHeaders(cabInfo.projectKey, sid, target)
361
483
  : undefined
484
+ const precipitatedFolders = includePrecipitated ? buildPrecipitatedFolderMeta(precipitated) : undefined
485
+ const desktop = buildDesktopSummary(sid, sessionStore, globalVault)
362
486
  const counts = (opts && opts.includeCounts !== false)
363
487
  ? getThreeTierArchiveCounts(sid, (opts && opts.flippedIds) || [], baseTarget)
364
488
  : undefined
365
489
 
490
+ const hookedCount = store.items.filter(it => it.hasHook).length
491
+ const viewerSummary = isGlobalReq
492
+ ? {
493
+ scope: 'global',
494
+ hookedCount,
495
+ totalCount: store.items.length,
496
+ label: `🌐 全局档案柜:主会话默认隔离 · ${hookedCount}/${store.items.length} 份已织就钩子(参谋见钩可拉)`,
497
+ }
498
+ : {
499
+ scope: 'session',
500
+ hookedCount,
501
+ totalCount: store.items.length,
502
+ label: `🗂️ 本局档案柜:参谋随时可读 · ${hookedCount}/${store.items.length} 份已织就钩子(主代理见钩可拉)`,
503
+ }
504
+
366
505
  return {
367
506
  ok: true,
368
507
  scope: isGlobalReq ? 'global' : (cabInfo.vaultScope || cabInfo.scope || 'session'),
@@ -374,13 +513,14 @@ export function listArchiveHeaders(rootSessionId = '', opts = {}, targetOpt) {
374
513
  activeCabinetId: isGlobalReq ? '' : cabInfo.activeCabinetId,
375
514
  cabinets: isGlobalReq ? [] : cabInfo.cabinets,
376
515
  totalCount: store.items.length,
377
- takenOutCount: sid
378
- ? store.items.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid)).length
379
- : 0,
516
+ takenOutCount: desktop.pinnedDocuments.length,
517
+ desktop,
518
+ viewerSummary,
519
+ recentlyUnpinnedWatch: desktop.recentlyUnpinnedWatch,
380
520
  diffSummary: diff.summary,
381
521
  folders,
382
522
  items: headers,
383
- ...(precipitated !== undefined ? { precipitated } : {}),
523
+ ...(precipitated !== undefined ? { precipitated, precipitatedFolders, precipitatedViewerSummary: { scope: 'precipitated', label: '🧊 冷藏档案柜:仅人类可见(钩子专供人类速览 · 主会话与参谋均 0 Token 隔离)' } } : {}),
384
524
  ...(counts !== undefined ? { counts } : {}),
385
525
  }
386
526
  }
@@ -417,6 +557,11 @@ export function getArchiveDetail(idOrTitle = '', rootSessionId = '', targetOpt)
417
557
  cold: hit.cold,
418
558
  takenOut: Boolean(sid && Array.isArray(hit.takenOutSessions) && hit.takenOutSessions.includes(sid)),
419
559
  chiefMounted: Boolean(isGlobal && sid && Array.isArray(hit.chiefMountedSessions) && hit.chiefMountedSessions.includes(sid)),
560
+ hasHook: Boolean(hit.hasHook),
561
+ hookKeywords: Array.isArray(hit.hookKeywords) ? hit.hookKeywords : [],
562
+ hookCue: hit.hookCue || '',
563
+ estimatedTokens: estimateArchiveTokens(hit),
564
+ viewerStatus: computeArchiveViewerStatus(hit, sid, isGlobal ? 'global' : 'session'),
420
565
  organizedBy: hit.organizedBy,
421
566
  points: hit.points,
422
567
  body: hit.body,
@@ -445,7 +590,14 @@ export function getTakenOutArchivesForSession(rootSessionId = '', targetOpt) {
445
590
  vaultScope: 'session',
446
591
  })
447
592
  if (store.unboundSession) return []
448
- return store.items.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid))
593
+ return store.items
594
+ .filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid))
595
+ .sort((a, b) => {
596
+ const aPin = Number(a?.desktopMeta?.[sid]?.pinnedAt || a.updatedAt || 0)
597
+ const bPin = Number(b?.desktopMeta?.[sid]?.pinnedAt || b.updatedAt || 0)
598
+ return bPin - aPin
599
+ })
600
+ .slice(0, DESKTOP_MAX_ITEMS)
449
601
  }
450
602
 
451
603
  function scoreAndRankArchiveItems(store, query = '', opts = {}) {
@@ -539,6 +691,161 @@ export function searchGlobalVaultForChief(query = '', opts = {}, targetOpt) {
539
691
  }
540
692
  }
541
693
 
694
+ function upsertWatchEntry(store, item, vaultScope, by = 'user') {
695
+ if (!store || !item || !item.id) return
696
+ const arr = Array.isArray(store.recentlyUnpinnedWatch) ? store.recentlyUnpinnedWatch.slice() : []
697
+ const filtered = arr.filter(x => !(x && x.id === item.id && x.vaultScope === vaultScope))
698
+ filtered.unshift({
699
+ id: item.id,
700
+ vaultScope: vaultScope === 'global' ? 'global' : 'session',
701
+ title: clamp(item.title || '未命名卷宗', 120),
702
+ folder: str(item.folder, 'inbox').trim() || 'inbox',
703
+ unpinnedAt: Date.now(),
704
+ by: clamp(by || 'user', 30),
705
+ })
706
+ store.recentlyUnpinnedWatch = filtered.slice(0, 12)
707
+ }
708
+
709
+ function removeWatchEntry(store, id, vaultScope = '') {
710
+ if (!store || !Array.isArray(store.recentlyUnpinnedWatch) || !id) return
711
+ store.recentlyUnpinnedWatch = store.recentlyUnpinnedWatch.filter(x =>
712
+ !(x && x.id === id && (!vaultScope || x.vaultScope === vaultScope))
713
+ )
714
+ }
715
+
716
+ function mutateDesktopPinState(op, payload, effectiveTarget, baseOpts) {
717
+ const sid = cleanRootSessionId(payload.rootSessionId || payload.session || effectiveTarget.rootSessionId)
718
+ if (!sid) return { ok: false, error: '当前未绑定对话会话,无法操作认知桌面' }
719
+ const id = str(payload.archiveId || payload.id, '').trim()
720
+ const targetScope = normalizeVaultScope(payload.vaultScope || payload.scope || effectiveTarget.vaultScope) === 'global' ? 'global' : 'session'
721
+ const by = clamp(payload.by || 'user', 30)
722
+ const isPin = op === 'takeOut' || op === 'pinToDesktop'
723
+
724
+ const sessionOpt = {
725
+ ...baseOpts,
726
+ cwd: effectiveTarget.cwd || baseOpts.cwd,
727
+ projectKey: effectiveTarget.projectKey || baseOpts.projectKey,
728
+ cabinetId: targetScope === 'session' ? (effectiveTarget.cabinetId || baseOpts.cabinetId) : '',
729
+ rootSessionId: sid,
730
+ vaultScope: 'session',
731
+ }
732
+ const globalOpt = {
733
+ ...baseOpts,
734
+ cwd: effectiveTarget.cwd || baseOpts.cwd,
735
+ projectKey: effectiveTarget.projectKey || baseOpts.projectKey,
736
+ cabinetId: '',
737
+ rootSessionId: sid,
738
+ vaultScope: 'global',
739
+ }
740
+
741
+ // Always lock session -> global to maintain strict single lock ordering
742
+ return withArchiveLock(sessionOpt, (_sFile, sResolved) => {
743
+ const sessTarget = { ...sessionOpt, cabinetId: sResolved.cabinetId, projectKey: sResolved.projectKey, vaultScope: 'session' }
744
+ const sessStore = loadArchiveStore(sessTarget)
745
+ return withArchiveLock(globalOpt, () => {
746
+ const globStore = loadGlobalVaultRaw(globalOpt)
747
+ const activeStore = targetScope === 'global' ? globStore : sessStore
748
+ const targetItem = activeStore.items.find(it => it.id === id)
749
+ || activeStore.items.find(it => normalizeArchiveTitleKey(it.title) === normalizeArchiveTitleKey(id))
750
+ if (!targetItem) return { ok: false, error: '未找到该工程档案:' + id }
751
+
752
+ let sessDirty = false
753
+ let globDirty = false
754
+ const evictedTitles = []
755
+ const evictedItems = []
756
+
757
+ if (isPin) {
758
+ const clipWeight = { copper: 1, silver: 2, gold: 3 }
759
+ const otherPinned = []
760
+ const pushOther = (items, sc) => {
761
+ for (const it of items) {
762
+ if (!Array.isArray(it.takenOutSessions) || !it.takenOutSessions.includes(sid)) continue
763
+ if (sc === targetScope && it.id === targetItem.id) continue
764
+ const meta = (it.desktopMeta && it.desktopMeta[sid]) || {}
765
+ otherPinned.push({
766
+ item: it,
767
+ scope: sc,
768
+ tokens: estimateArchiveTokens(it),
769
+ priority: (clipWeight[it.paperclip] || 2) * 10 + (Number(meta.priority) || 0),
770
+ pinnedAt: Number(meta.pinnedAt) || Number(it.updatedAt) || 0,
771
+ })
772
+ }
773
+ }
774
+ pushOther(sessStore.items, 'session')
775
+ pushOther(globStore.items, 'global')
776
+
777
+ const itemTokens = estimateArchiveTokens(targetItem)
778
+ let usedTokens = otherPinned.reduce((sum, x) => sum + x.tokens, 0)
779
+ otherPinned.sort((a, b) => a.priority - b.priority || a.pinnedAt - b.pinnedAt)
780
+
781
+ while ((otherPinned.length >= DESKTOP_MAX_ITEMS || (otherPinned.length > 0 && usedTokens + itemTokens > DESKTOP_TOKEN_BUDGET))) {
782
+ if (payload.autoEvict === false || payload.strictBudget === true) {
783
+ return {
784
+ ok: false,
785
+ overBudget: true,
786
+ usedTokens,
787
+ itemTokens,
788
+ tokenBudget: DESKTOP_TOKEN_BUDGET,
789
+ maxItems: DESKTOP_MAX_ITEMS,
790
+ error: `认知桌面容量已达上限(当前 ${usedTokens}/${DESKTOP_TOKEN_BUDGET} Tokens,${otherPinned.length}/${DESKTOP_MAX_ITEMS} 份),需先撤下旧文档或允许自动置换`,
791
+ }
792
+ }
793
+ const victim = otherPinned.shift()
794
+ if (!victim) break
795
+ victim.item.takenOutSessions = (victim.item.takenOutSessions || []).filter(s => s !== sid)
796
+ if (victim.item.desktopMeta && victim.item.desktopMeta[sid]) {
797
+ delete victim.item.desktopMeta[sid]
798
+ }
799
+ usedTokens = Math.max(0, usedTokens - victim.tokens)
800
+ evictedTitles.push(victim.item.title)
801
+ evictedItems.push({ id: victim.item.id, title: victim.item.title, vaultScope: victim.scope })
802
+ upsertWatchEntry(sessStore, victim.item, victim.scope, by)
803
+ if (victim.scope === 'global') globDirty = true
804
+ else sessDirty = true
805
+ }
806
+
807
+ targetItem.takenOutSessions = normalizeSessionIdList([...(targetItem.takenOutSessions || []), sid])
808
+ targetItem.desktopMeta = normalizeDesktopMeta({
809
+ ...(targetItem.desktopMeta || {}),
810
+ [sid]: {
811
+ pinnedAt: Date.now(),
812
+ by,
813
+ priority: clipWeight[targetItem.paperclip] || 2,
814
+ },
815
+ })
816
+ removeWatchEntry(sessStore, targetItem.id, targetScope)
817
+ sessDirty = true
818
+ if (targetScope === 'global') globDirty = true
819
+ } else {
820
+ targetItem.takenOutSessions = (targetItem.takenOutSessions || []).filter(s => s !== sid)
821
+ if (targetItem.desktopMeta && targetItem.desktopMeta[sid]) {
822
+ delete targetItem.desktopMeta[sid]
823
+ }
824
+ upsertWatchEntry(sessStore, targetItem, targetScope, by)
825
+ sessDirty = true
826
+ if (targetScope === 'global') globDirty = true
827
+ }
828
+
829
+ if (sessDirty) saveArchiveStore(sessStore, sessTarget)
830
+ if (globDirty) saveGlobalVaultRaw(globStore, globalOpt)
831
+
832
+ const desktop = buildDesktopSummary(sid, sessStore, globStore)
833
+ return {
834
+ ok: true,
835
+ id: targetItem.id,
836
+ title: targetItem.title,
837
+ takenOut: isPin,
838
+ evictedTitles,
839
+ evictedItems,
840
+ desktop,
841
+ isSystemGlobalVault: targetScope === 'global',
842
+ counts: getThreeTierArchiveCounts(sid, [], sessTarget),
843
+ meta: getArchiveMeta(sid, targetScope === 'global' ? globalOpt : sessTarget),
844
+ }
845
+ })
846
+ })
847
+ }
848
+
542
849
  /* ------------------------------------------- Cabinet & Archive Mutations */
543
850
 
544
851
  export function mutateArchive(payload = {}, targetOpt) {
@@ -559,6 +866,27 @@ export function mutateArchive(payload = {}, targetOpt) {
559
866
  return mutateCabinetRegistry({ ...payload, vaultScope }, effectiveTarget)
560
867
  }
561
868
 
869
+ if (op === 'takeOut' || op === 'pinToDesktop' || op === 'putBack' || op === 'unpinFromDesktop') {
870
+ return mutateDesktopPinState(op, payload, effectiveTarget, baseOpts)
871
+ }
872
+
873
+ if (op === 'desktopStatus') {
874
+ const sessStore = rootSessionId
875
+ ? loadArchiveStore({ ...effectiveTarget, vaultScope: 'session' })
876
+ : { items: [], unboundSession: true, recentlyUnpinnedWatch: [] }
877
+ const globStore = loadGlobalVaultRaw(effectiveTarget)
878
+ return {
879
+ ok: true,
880
+ desktop: buildDesktopSummary(rootSessionId, sessStore, globStore),
881
+ sessionHooks: (sessStore.items || []).filter(it => it.hasHook && !(it.takenOutSessions || []).includes(rootSessionId)).map(it => ({
882
+ id: it.id, title: it.title, folder: it.folder, hookKeywords: it.hookKeywords || [], hookCue: it.hookCue || '',
883
+ })),
884
+ globalHooks: (globStore.items || []).filter(it => it.hasHook && !(it.takenOutSessions || []).includes(rootSessionId)).map(it => ({
885
+ id: it.id, title: it.title, folder: it.folder, hookKeywords: it.hookKeywords || [], hookCue: it.hookCue || '',
886
+ })),
887
+ }
888
+ }
889
+
562
890
  return withArchiveLock(effectiveTarget, (_file, resolved) => {
563
891
  const store = loadArchiveStore({ ...effectiveTarget, cabinetId: resolved.cabinetId, rootSessionId: resolved.rootSessionId, vaultScope: resolved.vaultScope })
564
892
  const lockTarget = { ...effectiveTarget, cabinetId: resolved.cabinetId, projectKey: resolved.projectKey, rootSessionId: resolved.rootSessionId, vaultScope: resolved.vaultScope }
@@ -620,10 +948,13 @@ export function mutateArchive(payload = {}, targetOpt) {
620
948
  }
621
949
  if (Array.isArray(payload.points) && payload.points.length) {
622
950
  existing.points = payload.points.map((p, i) => normalizePoint(p, i)).filter(Boolean).slice(0, POINTS_CAP)
623
- existing.organizedBy = payload.organizedBy || 'user'
951
+ existing.organizedBy = ['auto', 'chief', 'user'].includes(payload.organizedBy) ? payload.organizedBy : 'user'
624
952
  } else if (bodyChanged) {
625
953
  existing.points = extractStructuredPoints(existing.title, existing.body)
626
954
  }
955
+ if (['auto', 'chief', 'user'].includes(payload.organizedBy)) {
956
+ existing.organizedBy = payload.organizedBy
957
+ }
627
958
  if (typeof payload.summary === 'string' && payload.summary.trim()) {
628
959
  existing.summary = clamp(payload.summary, 140)
629
960
  } else if (bodyChanged) {
@@ -632,6 +963,14 @@ export function mutateArchive(payload = {}, targetOpt) {
632
963
  140,
633
964
  )
634
965
  }
966
+ const hookNow = deriveHookFromStructuredItem({
967
+ ...existing,
968
+ ...(Array.isArray(payload.hookKeywords) ? { hookKeywords: payload.hookKeywords } : {}),
969
+ ...(typeof payload.hookCue === 'string' ? { hookCue: payload.hookCue } : {}),
970
+ }, existing.organizedBy === 'chief' || payload.hasHook === true || existing.hasHook === true)
971
+ existing.hasHook = hookNow.hasHook
972
+ existing.hookKeywords = hookNow.hookKeywords
973
+ existing.hookCue = hookNow.hookCue
635
974
  existing.contentHash = computeEntryContentHash(existing)
636
975
  existing.updatedAt = Date.now()
637
976
  saveArchiveStore(store, lockTarget)
@@ -697,6 +1036,9 @@ export function mutateArchive(payload = {}, targetOpt) {
697
1036
  cold: true,
698
1037
  takenOutSessions: (payload.takeOutNow || payload.takeOut) && rootSessionId && resolved.vaultScope !== 'global' ? [rootSessionId] : [],
699
1038
  chiefMountedSessions: resolved.vaultScope === 'global' && payload.mountChief && rootSessionId ? [rootSessionId] : [],
1039
+ hasHook: Boolean(payload.hasHook || payload.organizedBy === 'chief'),
1040
+ ...(Array.isArray(payload.hookKeywords) ? { hookKeywords: payload.hookKeywords } : {}),
1041
+ ...(typeof payload.hookCue === 'string' ? { hookCue: payload.hookCue } : {}),
700
1042
  organizedBy: ['auto', 'chief', 'user'].includes(payload.organizedBy)
701
1043
  ? payload.organizedBy
702
1044
  : (Array.isArray(payload.points) && payload.points.length ? 'user' : 'auto'),
@@ -767,27 +1109,101 @@ export function mutateArchive(payload = {}, targetOpt) {
767
1109
  }
768
1110
  }
769
1111
 
770
- if (op === 'takeOut' || op === 'putBack') {
771
- const id = str(payload.archiveId || payload.id, '').trim()
772
- if (!rootSessionId) return { ok: false, error: '当前未绑定对话会话,无法摆到桌面备选' }
773
- const item = store.items.find(it => it.id === id)
774
- if (!item) return { ok: false, error: '未找到该工程档案:' + id }
775
- const set = new Set(item.takenOutSessions || [])
776
- if (op === 'takeOut') set.add(rootSessionId)
777
- else set.delete(rootSessionId)
778
- item.takenOutSessions = [...set]
1112
+ if (op === 'pullByLead') {
1113
+ if (resolved.vaultScope === 'global') {
1114
+ return { ok: false, denied: true, error: '主代理不可直接拉取全局档案柜未上桌卷宗,请由参谋长整理呈递或摆上桌面' }
1115
+ }
1116
+ if (!rootSessionId) {
1117
+ return { ok: false, error: '当前为空白新对话,尚未建立本局档案柜' }
1118
+ }
1119
+ const q = str(payload.archiveId || payload.id || payload.title, '').trim()
1120
+ if (!q) return { ok: false, error: 'pullByLead 需要指定档案 id 或标题' }
1121
+ const qLow = q.toLowerCase()
1122
+ const item = store.items.find(it => it.id === q)
1123
+ || store.items.find(it => it.title === q)
1124
+ || store.items.find(it => it.title.toLowerCase().includes(qLow))
1125
+ if (!item) return { ok: false, error: '未找到本局工程档案:' + q }
1126
+ const isOnDesk = Array.isArray(item.takenOutSessions) && item.takenOutSessions.includes(rootSessionId)
1127
+ if (!item.hasHook && !isOnDesk && payload.allowUnorganized !== true) {
1128
+ return { ok: false, unhooked: true, error: `本局档案《${item.title}》尚未经过参谋长整理织就钩子,暂未向主代理开放拉阅` }
1129
+ }
1130
+ item.leadPulledSessions = normalizeSessionIdList([...(item.leadPulledSessions || []), rootSessionId])
779
1131
  saveArchiveStore(store, lockTarget)
780
1132
  return {
781
1133
  ok: true,
782
- id: item.id,
783
- title: item.title,
784
- takenOut: op === 'takeOut',
1134
+ vaultScope: 'session',
1135
+ item: {
1136
+ ...item,
1137
+ viewerStatus: computeArchiveViewerStatus(item, rootSessionId, 'session'),
1138
+ },
1139
+ }
1140
+ }
1141
+
1142
+ if (op === 'pullByChief') {
1143
+ const q = str(payload.archiveId || payload.id || payload.title, '').trim()
1144
+ if (!q) return { ok: false, error: 'pullByChief 需要指定档案 id 或标题' }
1145
+ const qLow = q.toLowerCase()
1146
+ const item = store.items.find(it => it.id === q)
1147
+ || store.items.find(it => it.title === q)
1148
+ || store.items.find(it => it.title.toLowerCase().includes(qLow))
1149
+ if (!item) return { ok: false, error: '未找到工程档案:' + q }
1150
+ if (resolved.vaultScope === 'global') {
1151
+ const mounted = Boolean(rootSessionId && Array.isArray(item.chiefMountedSessions) && item.chiefMountedSessions.includes(rootSessionId))
1152
+ if (!item.hasHook && !mounted && payload.allowUnhooked !== true) {
1153
+ return { ok: false, unhooked: true, error: `全局档案《${item.title}》尚未经过参谋整理织就钩子,请先由人类整理或开放参阅` }
1154
+ }
1155
+ }
1156
+ if (rootSessionId) {
1157
+ item.chiefPulledSessions = normalizeSessionIdList([...(item.chiefPulledSessions || []), rootSessionId])
1158
+ if (resolved.vaultScope === 'global') {
1159
+ item.chiefMountedSessions = normalizeSessionIdList([...(item.chiefMountedSessions || []), rootSessionId])
1160
+ }
1161
+ saveArchiveStore(store, lockTarget)
1162
+ }
1163
+ return {
1164
+ ok: true,
1165
+ vaultScope: resolved.vaultScope,
785
1166
  isSystemGlobalVault: resolved.vaultScope === 'global',
786
- counts: getThreeTierArchiveCounts(rootSessionId, [], lockTarget),
787
- meta: getArchiveMeta(rootSessionId, lockTarget),
1167
+ item: {
1168
+ ...item,
1169
+ viewerStatus: computeArchiveViewerStatus(item, rootSessionId, resolved.vaultScope),
1170
+ },
788
1171
  }
789
1172
  }
790
1173
 
1174
+ if (op === 'markDeliveredToLead') {
1175
+ if (!rootSessionId) return { ok: false, error: '当前为空白新对话,无法向主代理递交档案' }
1176
+ const q = str(payload.archiveId || payload.id || payload.title, '').trim()
1177
+ if (!q) return { ok: false, error: 'markDeliveredToLead 需要指定档案 id 或标题' }
1178
+ const qLow = q.toLowerCase()
1179
+ const item = store.items.find(it => it.id === q)
1180
+ || store.items.find(it => it.title === q)
1181
+ || store.items.find(it => it.title.toLowerCase().includes(qLow))
1182
+ if (!item) return { ok: false, error: '未找到工程档案:' + q }
1183
+ item.chiefDeliveredSessions = normalizeSessionIdList([...(item.chiefDeliveredSessions || []), rootSessionId])
1184
+ saveArchiveStore(store, lockTarget)
1185
+ return {
1186
+ ok: true,
1187
+ vaultScope: resolved.vaultScope,
1188
+ isSystemGlobalVault: resolved.vaultScope === 'global',
1189
+ item: {
1190
+ ...item,
1191
+ viewerStatus: computeArchiveViewerStatus(item, rootSessionId, resolved.vaultScope),
1192
+ },
1193
+ }
1194
+ }
1195
+
1196
+ if (op === 'clearUnpinnedWatch') {
1197
+ const targetIds = Array.isArray(payload.ids) ? new Set(payload.ids.map(String)) : null
1198
+ if (resolved.vaultScope === 'session') {
1199
+ store.recentlyUnpinnedWatch = targetIds
1200
+ ? (store.recentlyUnpinnedWatch || []).filter(w => w && !targetIds.has(w.id))
1201
+ : []
1202
+ saveArchiveStore(store, lockTarget)
1203
+ }
1204
+ return { ok: true, recentlyUnpinnedWatch: store.recentlyUnpinnedWatch || [] }
1205
+ }
1206
+
791
1207
  if (op === 'cycleClip' || op === 'setClip') {
792
1208
  const id = str(payload.archiveId || payload.id, '').trim()
793
1209
  const item = store.items.find(it => it.id === id)
@@ -814,6 +1230,9 @@ export function mutateArchive(payload = {}, targetOpt) {
814
1230
  if (payload.folderLabel && !store.folders.some(f => f.id === folder)) {
815
1231
  store.folders.push(normalizeFolder({ id: folder, label: payload.folderLabel, order: 58 }))
816
1232
  }
1233
+ if (resolved.vaultScope === 'session' && folder !== 'inbox') {
1234
+ removeWatchEntry(store, item.id, 'session')
1235
+ }
817
1236
  item.updatedAt = Date.now()
818
1237
  saveArchiveStore(store, lockTarget)
819
1238
  return { ok: true, id: item.id, folder: item.folder }
@@ -1014,8 +1433,19 @@ export function applyChiefArchiveCurations(curations = [], newFolders = [], targ
1014
1433
  target.points = validPts
1015
1434
  }
1016
1435
  }
1436
+ const hook = deriveHookFromStructuredItem({
1437
+ ...target,
1438
+ ...(Array.isArray(c.hookKeywords) ? { hookKeywords: c.hookKeywords } : {}),
1439
+ ...(typeof c.hookCue === 'string' && c.hookCue.trim() ? { hookCue: c.hookCue.trim() } : {}),
1440
+ }, true)
1441
+ target.hasHook = hook.hasHook
1442
+ target.hookKeywords = hook.hookKeywords
1443
+ target.hookCue = hook.hookCue
1017
1444
  target.organizedBy = 'chief'
1018
1445
  target.updatedAt = Date.now()
1446
+ if (target.folder !== 'inbox' || c.clearUnpinnedWatch) {
1447
+ removeWatchEntry(store, target.id)
1448
+ }
1019
1449
  updatedCount += 1
1020
1450
  }
1021
1451