dsh-chief 1.1.0 → 1.2.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/archives.js CHANGED
@@ -148,6 +148,18 @@ function chiefRootDir(targetOpt) {
148
148
  return path.join(home, 'chief')
149
149
  }
150
150
 
151
+ function normalizeVaultScope(raw) {
152
+ const s = str(raw, '').trim().toLowerCase()
153
+ if (s === 'global') return 'global'
154
+ if (s === 'precipitated' || s === 'cold' || s === 'vault') return 'precipitated'
155
+ return 'session'
156
+ }
157
+
158
+ function cleanRootSessionId(raw = '') {
159
+ const s = str(raw, '').trim()
160
+ return (!s || s === 'global') ? '' : s
161
+ }
162
+
151
163
  function resolveTargetOpts(targetOpt) {
152
164
  if (!targetOpt || typeof targetOpt === 'string') {
153
165
  return {
@@ -155,6 +167,8 @@ function resolveTargetOpts(targetOpt) {
155
167
  cwd: '',
156
168
  projectKey: '',
157
169
  cabinetId: '',
170
+ rootSessionId: '',
171
+ vaultScope: 'session',
158
172
  }
159
173
  }
160
174
  return {
@@ -162,7 +176,39 @@ function resolveTargetOpts(targetOpt) {
162
176
  cwd: str(targetOpt.cwd, ''),
163
177
  projectKey: str(targetOpt.projectKey, ''),
164
178
  cabinetId: str(targetOpt.cabinetId, ''),
179
+ rootSessionId: cleanRootSessionId(targetOpt.rootSessionId || targetOpt.sessionId || targetOpt.session),
180
+ vaultScope: normalizeVaultScope(targetOpt.vaultScope || targetOpt.scope),
181
+ }
182
+ }
183
+
184
+ function normalizeSessionScopeKey(rootSessionId = '') {
185
+ const sid = cleanRootSessionId(rootSessionId)
186
+ if (!sid) return ''
187
+ return 'sess:' + sid.replace(/[^a-zA-Z0-9._-]+/g, '-').slice(0, 72)
188
+ }
189
+
190
+ function sessionCabinetId(rootSessionId = '') {
191
+ const hash10 = crypto.createHash('sha1').update(String(rootSessionId || 'session')).digest('hex').slice(0, 10)
192
+ return `cab-s-${hash10}`
193
+ }
194
+
195
+ function withRootScope(targetOpt, rootSessionId = '') {
196
+ const sid = cleanRootSessionId(rootSessionId)
197
+ if (!targetOpt || typeof targetOpt === 'string') {
198
+ const base = { customSharedBoardFile: str(targetOpt, ''), vaultScope: 'session' }
199
+ return sid ? { ...base, rootSessionId: sid } : base
200
+ }
201
+ const vaultScope = normalizeVaultScope(targetOpt.vaultScope || targetOpt.scope)
202
+ if (vaultScope === 'global') {
203
+ return { ...targetOpt, vaultScope: 'global' }
204
+ }
205
+ if (!sid) {
206
+ return { ...targetOpt, vaultScope }
165
207
  }
208
+ if (cleanRootSessionId(targetOpt.rootSessionId || targetOpt.sessionId || targetOpt.session)) {
209
+ return { ...targetOpt, vaultScope }
210
+ }
211
+ return { ...targetOpt, rootSessionId: sid, vaultScope }
166
212
  }
167
213
 
168
214
  export function legacyArchiveFilePath(targetOpt) {
@@ -182,14 +228,32 @@ export function cabinetFilePath(cabinetId = 'cab-main', targetOpt) {
182
228
  return path.join(cabinetsDirPath(targetOpt), `${safe}.json`)
183
229
  }
184
230
 
185
- export function precipitatedFilePath(projectKey = 'proj-default', targetOpt) {
186
- const safe = resolveProjectKey(projectKey || 'proj-default').replace(/[^a-zA-Z0-9\u4e00-\u9fa5._-]+/g, '-').slice(0, 72) || 'proj-default'
187
- return path.join(chiefRootDir(targetOpt), 'precipitated', `${safe}.json`)
231
+ export function globalChiefVaultFilePath(targetOpt) {
232
+ return path.join(chiefRootDir(targetOpt), 'global-vault', 'vault-chief-global.json')
233
+ }
234
+
235
+ export function globalPrecipitatedFilePath(targetOpt) {
236
+ return path.join(chiefRootDir(targetOpt), 'precipitated', 'vault-global.json')
237
+ }
238
+
239
+ export function precipitatedFilePath(_projectKey = 'proj-default', targetOpt) {
240
+ return globalPrecipitatedFilePath(targetOpt)
188
241
  }
189
242
 
190
243
  export function archiveFilePath(targetOpt) {
191
244
  const resolved = ensureProjectCabinet(targetOpt)
192
- return resolved.cabinetFile
245
+ return resolved.cabinetFile || ''
246
+ }
247
+
248
+ function normalizeArchiveTitleKey(title) {
249
+ return String(title || '').trim().replace(/\s+/g, ' ').toLowerCase()
250
+ }
251
+
252
+ function computeEntryContentHash(raw) {
253
+ const title = String((raw && raw.title) || '').trim()
254
+ const summary = String((raw && raw.summary) || '').trim()
255
+ const body = cleanMultiline((raw && (raw.body !== undefined ? raw.body : raw.rawBody)) || '', 30000)
256
+ return crypto.createHash('sha1').update(`${title}\n${summary}\n${body}`).digest('hex').slice(0, 12)
193
257
  }
194
258
 
195
259
  /* ----------------------------------------------------------- Lock & Storage */
@@ -297,12 +361,69 @@ function normalizeRegistry(raw) {
297
361
  }
298
362
  }
299
363
  }
364
+ const sessions = {}
365
+ if (src.sessions && typeof src.sessions === 'object') {
366
+ for (const [rawKey, sess] of Object.entries(src.sessions)) {
367
+ if (!sess || typeof sess !== 'object') continue
368
+ const rSid = str(sess.rootSessionId || rawKey.replace(/^sess:/, ''), '').trim()
369
+ const sKey = normalizeSessionScopeKey(rSid)
370
+ if (!sKey) continue
371
+ const pKey = resolveProjectKey(sess.projectKey || sess.cwd || 'proj-default')
372
+ const cabinets = (Array.isArray(sess.cabinets) ? sess.cabinets : [])
373
+ .filter(c => c && typeof c === 'object' && str(c.id, '').trim())
374
+ .map(c => ({
375
+ id: str(c.id, '').trim().slice(0, 72),
376
+ name: clamp(c.name || '本对话工作档案柜', 40),
377
+ projectKey: pKey,
378
+ rootSessionId: rSid,
379
+ cwd: str(c.cwd, '').slice(0, 260),
380
+ createdAt: Number(c.createdAt) || Date.now(),
381
+ updatedAt: Number(c.updatedAt) || Number(c.createdAt) || Date.now(),
382
+ }))
383
+ if (!cabinets.length) continue
384
+ const activeCabinetId = cabinets.some(c => c.id === sess.activeCabinetId)
385
+ ? sess.activeCabinetId
386
+ : cabinets[0].id
387
+ sessions[sKey] = {
388
+ sessionKey: sKey,
389
+ rootSessionId: rSid,
390
+ projectKey: pKey,
391
+ cwd: str(sess.cwd, '').slice(0, 260),
392
+ activeCabinetId,
393
+ cabinets,
394
+ }
395
+ }
396
+ }
397
+ let globalEntry = null
398
+ if (src.global && typeof src.global === 'object') {
399
+ const gCabs = (Array.isArray(src.global.cabinets) ? src.global.cabinets : [])
400
+ .filter(c => c && typeof c === 'object' && str(c.id, '').trim())
401
+ .map(c => ({
402
+ id: str(c.id, '').trim().slice(0, 72),
403
+ name: clamp(c.name || '🌐 全局工作档案柜', 40),
404
+ projectKey: 'global',
405
+ cwd: '',
406
+ createdAt: Number(c.createdAt) || Date.now(),
407
+ updatedAt: Number(c.updatedAt) || Number(c.createdAt) || Date.now(),
408
+ }))
409
+ if (gCabs.length) {
410
+ globalEntry = {
411
+ projectKey: 'global',
412
+ cwd: '',
413
+ activeCabinetId: gCabs.some(c => c.id === src.global.activeCabinetId) ? src.global.activeCabinetId : gCabs[0].id,
414
+ cabinets: gCabs,
415
+ }
416
+ }
417
+ }
300
418
  return {
301
419
  version: ARCHIVE_VERSION,
302
420
  migratedLegacy: Boolean(src.migratedLegacy),
421
+ migratedGlobalAt: Number(src.migratedGlobalAt) || 0,
303
422
  migratedAt: Number(src.migratedAt) || 0,
304
423
  legacyOwnerProjectKey: str(src.legacyOwnerProjectKey, ''),
305
424
  projects,
425
+ sessions,
426
+ global: globalEntry,
306
427
  }
307
428
  }
308
429
 
@@ -310,11 +431,38 @@ function writeRegistryRaw(regFile, registry) {
310
431
  atomicWriteJson(regFile, normalizeRegistry(registry))
311
432
  }
312
433
 
434
+ function claimSessionOwnLegacyItems(reg, projectKey, rootSessionId, opts) {
435
+ const claimed = []
436
+ const seenTitles = new Set()
437
+ const candidateCabIds = new Set(['cab-main'])
438
+ const projEntry = reg.projects && reg.projects[projectKey]
439
+ if (projEntry && Array.isArray(projEntry.cabinets)) {
440
+ for (const c of projEntry.cabinets) {
441
+ if (c && c.id) candidateCabIds.add(c.id)
442
+ }
443
+ }
444
+ for (const cabId of candidateCabIds) {
445
+ const file = cabinetFilePath(cabId, opts.customSharedBoardFile)
446
+ const parsed = readJsonSafe(file, null)
447
+ const items = Array.isArray(parsed && parsed.items) ? parsed.items : []
448
+ for (const rawItem of items) {
449
+ if (!rawItem || str(rawItem.sourceSession, '').trim() !== rootSessionId) continue
450
+ const norm = normalizeArchiveItem(rawItem)
451
+ if (!norm || seenTitles.has(norm.title)) continue
452
+ seenTitles.add(norm.title)
453
+ claimed.push(norm)
454
+ }
455
+ }
456
+ return claimed
457
+ }
458
+
313
459
  function ensureProjectCabinet(targetOpt) {
314
460
  const opts = resolveTargetOpts(targetOpt)
315
461
  const regFile = cabinetRegistryPath(opts.customSharedBoardFile)
316
462
  const legacyFile = legacyArchiveFilePath(opts.customSharedBoardFile)
317
463
  const projectKey = opts.projectKey ? resolveProjectKey(opts.projectKey) : resolveProjectKey(opts.cwd)
464
+ const sessKey = normalizeSessionScopeKey(opts.rootSessionId)
465
+ const vaultScope = opts.vaultScope === 'global' ? 'global' : 'session'
318
466
 
319
467
  const release = acquireFileLock(regFile)
320
468
  try {
@@ -358,80 +506,135 @@ function ensureProjectCabinet(targetOpt) {
358
506
  dirty = true
359
507
  }
360
508
 
361
- // 2. Ensure requested projectKey exists in registry
362
- if (!reg.projects[projectKey]) {
363
- const now = Date.now()
364
- const hasMainAlready = Object.values(reg.projects).some(p => p.cabinets.some(c => c.id === 'cab-main'))
365
- const defaultCabId = hasMainAlready ? `cab-${projectKey.slice(-8)}-main` : 'cab-main'
366
- const labelPrefix = opts.cwd ? (path.basename(normalizeCwd(opts.cwd)) || '当前工程') : '默认'
367
- const cabFile = cabinetFilePath(defaultCabId, opts.customSharedBoardFile)
368
- if (!fs.existsSync(cabFile)) {
369
- atomicWriteJson(cabFile, normalizeArchiveStore({
370
- cabinetId: defaultCabId,
371
- cabinetName: `${labelPrefix} · 主档案柜`,
372
- projectKey,
373
- }))
509
+ // 2. SYSTEM GLOBAL COLD VAULT (`vaultScope === 'global'`):
510
+ // Mirrors Precipitated Vault's system-level cold storage: NEVER auto-populated from cab-main or project cabinets,
511
+ // NEVER follows conversation context automatically (0 Token until Chief-search hit or explicit mount/import).
512
+ if (vaultScope === 'global') {
513
+ const globalFile = globalChiefVaultFilePath(opts.customSharedBoardFile)
514
+ if (dirty) {
515
+ writeRegistryRaw(regFile, reg)
374
516
  }
375
- reg.projects[projectKey] = {
376
- projectKey,
377
- cwd: opts.cwd,
378
- activeCabinetId: defaultCabId,
379
- cabinets: [
380
- {
381
- id: defaultCabId,
382
- name: `${labelPrefix} · 主档案柜`,
383
- projectKey,
384
- cwd: opts.cwd,
385
- createdAt: now,
386
- updatedAt: now,
387
- },
388
- ],
517
+ return {
518
+ scope: 'global',
519
+ vaultScope: 'global',
520
+ isSystemGlobalVault: true,
521
+ unboundSession: false,
522
+ sessionKey: '',
523
+ rootSessionId: opts.rootSessionId || '',
524
+ projectKey: 'global',
525
+ cabinetId: '',
526
+ cabinetName: '🌐 系统全局档案柜(0 Token 冷封存 · 仅参谋与您可见)',
527
+ cabinetFile: globalFile,
528
+ registry: reg,
529
+ projectEntry: {
530
+ projectKey: 'global',
531
+ activeCabinetId: '',
532
+ cabinets: [],
533
+ },
389
534
  }
390
- dirty = true
391
- } else if (opts.cwd && !reg.projects[projectKey].cwd) {
392
- reg.projects[projectKey].cwd = opts.cwd
393
- dirty = true
394
535
  }
395
536
 
396
- const projEntry = reg.projects[projectKey]
397
- let selectedCabinet = null
398
- if (opts.cabinetId) {
399
- selectedCabinet = projEntry.cabinets.find(c => c.id === opts.cabinetId) || null
400
- if (!selectedCabinet) {
401
- // Also check across projects if an explicit cabinetId was passed
402
- for (const p of Object.values(reg.projects)) {
403
- const hit = p.cabinets.find(c => c.id === opts.cabinetId)
404
- if (hit) {
405
- selectedCabinet = hit
406
- break
407
- }
537
+ // 3B. STRICT SESSION-ISOLATED WORKING CABINET (`sess:<rootSessionId>`):
538
+ // Working cabinets are strictly 1-to-1 with ONE root conversation (never shared across sessions!).
539
+ if (sessKey) {
540
+ if (!reg.sessions[sessKey]) {
541
+ const now = Date.now()
542
+ const defaultCabId = sessionCabinetId(opts.rootSessionId)
543
+ const cabFile = cabinetFilePath(defaultCabId, opts.customSharedBoardFile)
544
+ if (!fs.existsSync(cabFile)) {
545
+ const ownItems = claimSessionOwnLegacyItems(reg, projectKey, opts.rootSessionId, opts)
546
+ atomicWriteJson(cabFile, normalizeArchiveStore({
547
+ cabinetId: defaultCabId,
548
+ cabinetName: '本对话工作档案柜',
549
+ projectKey,
550
+ items: ownItems,
551
+ }))
552
+ }
553
+ reg.sessions[sessKey] = {
554
+ sessionKey: sessKey,
555
+ rootSessionId: opts.rootSessionId,
556
+ projectKey,
557
+ cwd: opts.cwd,
558
+ activeCabinetId: defaultCabId,
559
+ cabinets: [
560
+ {
561
+ id: defaultCabId,
562
+ name: '本对话工作档案柜',
563
+ projectKey,
564
+ rootSessionId: opts.rootSessionId,
565
+ cwd: opts.cwd,
566
+ createdAt: now,
567
+ updatedAt: now,
568
+ },
569
+ ],
570
+ }
571
+ dirty = true
572
+ } else {
573
+ if (opts.cwd && !reg.sessions[sessKey].cwd) {
574
+ reg.sessions[sessKey].cwd = opts.cwd
575
+ dirty = true
576
+ }
577
+ if (projectKey && reg.sessions[sessKey].projectKey !== projectKey && opts.cwd) {
578
+ reg.sessions[sessKey].projectKey = projectKey
579
+ dirty = true
408
580
  }
409
581
  }
410
- }
411
- if (!selectedCabinet) {
412
- selectedCabinet = projEntry.cabinets.find(c => c.id === projEntry.activeCabinetId) || projEntry.cabinets[0]
413
- }
414
582
 
415
- const selectedFile = cabinetFilePath(selectedCabinet.id, opts.customSharedBoardFile)
416
- if (!fs.existsSync(selectedFile)) {
417
- atomicWriteJson(selectedFile, normalizeArchiveStore({
583
+ const sessEntry = reg.sessions[sessKey]
584
+ let selectedCabinet = null
585
+ // Strictly match ONLY within THIS session's own cabinets (never cross-mount cab-main/cab-global!)
586
+ if (opts.cabinetId) {
587
+ selectedCabinet = sessEntry.cabinets.find(c => c.id === opts.cabinetId) || null
588
+ }
589
+ if (!selectedCabinet) {
590
+ selectedCabinet = sessEntry.cabinets.find(c => c.id === sessEntry.activeCabinetId) || sessEntry.cabinets[0]
591
+ }
592
+ const selectedFile = cabinetFilePath(selectedCabinet.id, opts.customSharedBoardFile)
593
+ if (!fs.existsSync(selectedFile)) {
594
+ atomicWriteJson(selectedFile, normalizeArchiveStore({
595
+ cabinetId: selectedCabinet.id,
596
+ cabinetName: selectedCabinet.name,
597
+ projectKey,
598
+ }))
599
+ }
600
+ if (dirty || !fs.existsSync(regFile)) {
601
+ writeRegistryRaw(regFile, reg)
602
+ }
603
+ return {
604
+ scope: 'session',
605
+ vaultScope: 'session',
606
+ unboundSession: false,
607
+ sessionKey: sessKey,
608
+ rootSessionId: opts.rootSessionId,
609
+ projectKey: sessEntry.projectKey || projectKey,
418
610
  cabinetId: selectedCabinet.id,
419
611
  cabinetName: selectedCabinet.name,
420
- projectKey: selectedCabinet.projectKey,
421
- }))
612
+ cabinetFile: selectedFile,
613
+ registry: reg,
614
+ projectEntry: sessEntry,
615
+ }
422
616
  }
423
617
 
618
+ // 3C. Unbound / blank new conversation: MUST NOT fall back to cab-main or cab-global!
424
619
  if (dirty || !fs.existsSync(regFile)) {
425
620
  writeRegistryRaw(regFile, reg)
426
621
  }
427
-
428
622
  return {
623
+ scope: 'session',
624
+ vaultScope: 'session',
625
+ unboundSession: true,
626
+ sessionKey: '',
627
+ rootSessionId: '',
429
628
  projectKey,
430
- cabinetId: selectedCabinet.id,
431
- cabinetName: selectedCabinet.name,
432
- cabinetFile: selectedFile,
629
+ cabinetId: '',
630
+ cabinetName: '本会话尚未开始(空白新对话)',
631
+ cabinetFile: '',
433
632
  registry: reg,
434
- projectEntry: projEntry,
633
+ projectEntry: {
634
+ projectKey,
635
+ activeCabinetId: '',
636
+ cabinets: [],
637
+ },
435
638
  }
436
639
  } finally {
437
640
  release()
@@ -440,11 +643,19 @@ function ensureProjectCabinet(targetOpt) {
440
643
 
441
644
  export function listProjectCabinets(targetOpt) {
442
645
  const resolved = ensureProjectCabinet(targetOpt)
646
+ const isGlobal = Boolean(resolved.isSystemGlobalVault || resolved.vaultScope === 'global')
443
647
  return {
444
648
  ok: true,
649
+ scope: isGlobal ? 'global' : (resolved.scope || 'session'),
650
+ vaultScope: isGlobal ? 'global' : (resolved.vaultScope || resolved.scope || 'session'),
651
+ isSystemGlobalVault: isGlobal,
652
+ unboundSession: isGlobal ? false : Boolean(resolved.unboundSession),
653
+ rootSessionId: resolved.rootSessionId || '',
445
654
  projectKey: resolved.projectKey,
446
- activeCabinetId: resolved.projectEntry.activeCabinetId,
447
- cabinets: resolved.projectEntry.cabinets.map(c => ({ ...c })),
655
+ activeCabinetId: isGlobal ? '' : (resolved.projectEntry ? resolved.projectEntry.activeCabinetId : ''),
656
+ cabinets: isGlobal
657
+ ? []
658
+ : (resolved.projectEntry && Array.isArray(resolved.projectEntry.cabinets) ? resolved.projectEntry.cabinets : []).map(c => ({ ...c })),
448
659
  }
449
660
  }
450
661
 
@@ -526,10 +737,16 @@ function normalizeArchiveItem(raw) {
526
737
  const takenOutSessions = Array.isArray(raw.takenOutSessions)
527
738
  ? [...new Set(raw.takenOutSessions.map(s => String(s || '').trim()).filter(Boolean))].slice(0, 32)
528
739
  : []
740
+ const chiefMountedSessions = Array.isArray(raw.chiefMountedSessions)
741
+ ? [...new Set(raw.chiefMountedSessions.map(s => String(s || '').trim()).filter(Boolean))].slice(0, 32)
742
+ : []
743
+ const contentHash = str(raw.contentHash, '').trim() || computeEntryContentHash({ title, summary, body })
529
744
 
530
745
  return {
531
746
  id: str(raw.id, '').trim() || nextId('arch'),
532
747
  sourceNoteId: str(raw.sourceNoteId, '').trim(),
748
+ originId: str(raw.originId, '').trim(),
749
+ originGlobalId: str(raw.originGlobalId, '').trim(),
533
750
  title,
534
751
  summary,
535
752
  folder,
@@ -537,9 +754,11 @@ function normalizeArchiveItem(raw) {
537
754
  tags: normalizeTags(Array.isArray(raw.tags) ? raw.tags : []),
538
755
  cold: raw.cold !== false,
539
756
  takenOutSessions,
757
+ chiefMountedSessions,
540
758
  organizedBy: ['auto', 'chief', 'user'].includes(raw.organizedBy) ? raw.organizedBy : 'auto',
541
759
  points,
542
760
  body,
761
+ contentHash,
543
762
  by: clamp(raw.by || 'agent', 40),
544
763
  sourceSession: str(raw.sourceSession || raw.session, '').trim(),
545
764
  createdAt: Number(raw.createdAt) || Date.now(),
@@ -547,6 +766,21 @@ function normalizeArchiveItem(raw) {
547
766
  }
548
767
  }
549
768
 
769
+ function normalizeGlobalVaultEntry(raw) {
770
+ const norm = normalizeArchiveItem({
771
+ ...(raw || {}),
772
+ id: str(raw && raw.id, '').trim() || nextId('glob'),
773
+ cold: true,
774
+ })
775
+ if (!norm) return null
776
+ return {
777
+ ...norm,
778
+ takenOutSessions: Array.isArray(norm.takenOutSessions) ? norm.takenOutSessions : [],
779
+ cold: true,
780
+ chiefMountedSessions: Array.isArray(norm.chiefMountedSessions) ? norm.chiefMountedSessions : [],
781
+ }
782
+ }
783
+
550
784
  function normalizeArchiveStore(raw) {
551
785
  const src = raw && typeof raw === 'object' ? raw : {}
552
786
  const folderMap = new Map()
@@ -560,8 +794,9 @@ function normalizeArchiveStore(raw) {
560
794
  })
561
795
  }
562
796
 
797
+ const normalizer = src.isSystemGlobalVault ? normalizeGlobalVaultEntry : normalizeArchiveItem
563
798
  const items = (Array.isArray(src.items) ? src.items : [])
564
- .map(normalizeArchiveItem)
799
+ .map(normalizer)
565
800
  .filter(Boolean)
566
801
  .slice(0, ARCHIVE_CAP)
567
802
 
@@ -583,9 +818,12 @@ function normalizeArchiveStore(raw) {
583
818
 
584
819
  return {
585
820
  version: ARCHIVE_VERSION,
586
- cabinetId: str(src.cabinetId, 'cab-main').trim() || 'cab-main',
587
- cabinetName: clamp(src.cabinetName || '默认主档案柜', 40),
588
- projectKey: resolveProjectKey(src.projectKey || 'proj-default'),
821
+ isSystemGlobalVault: Boolean(src.isSystemGlobalVault),
822
+ cabinetId: src.isSystemGlobalVault ? '' : (str(src.cabinetId, 'cab-main').trim() || 'cab-main'),
823
+ cabinetName: src.isSystemGlobalVault
824
+ ? '🌐 系统全局档案柜'
825
+ : clamp(src.cabinetName || '默认主档案柜', 40),
826
+ projectKey: src.isSystemGlobalVault ? 'global' : resolveProjectKey(src.projectKey || 'proj-default'),
589
827
  migratedSharedAt: Number(src.migratedSharedAt) || 0,
590
828
  updatedAt: Number(src.updatedAt) || Date.now(),
591
829
  folders,
@@ -593,8 +831,207 @@ function normalizeArchiveStore(raw) {
593
831
  }
594
832
  }
595
833
 
834
+ /**
835
+ * Loads the standalone System Global Cold Vault (`global-vault/vault-chief-global.json`).
836
+ * Structurally peers with `precipitated/vault-global.json`: NEVER shares files with `cabinets/`,
837
+ * NEVER auto-follows conversation context (0 Token unless explicitly mounted or Chief-searched).
838
+ */
839
+ export function loadGlobalVaultRaw(targetOpt) {
840
+ const file = globalChiefVaultFilePath(targetOpt)
841
+ if (!fs.existsSync(file)) {
842
+ return normalizeArchiveStore({
843
+ isSystemGlobalVault: true,
844
+ projectKey: 'global',
845
+ updatedAt: 0,
846
+ items: [],
847
+ })
848
+ }
849
+ const parsed = readJsonSafe(file, null)
850
+ return normalizeArchiveStore({
851
+ ...(parsed && typeof parsed === 'object' ? parsed : {}),
852
+ isSystemGlobalVault: true,
853
+ projectKey: 'global',
854
+ })
855
+ }
856
+
857
+ export function saveGlobalVaultRaw(store, targetOpt) {
858
+ const file = globalChiefVaultFilePath(targetOpt)
859
+ const normalized = normalizeArchiveStore({
860
+ ...(store && typeof store === 'object' ? store : {}),
861
+ isSystemGlobalVault: true,
862
+ projectKey: 'global',
863
+ updatedAt: Date.now(),
864
+ })
865
+ atomicWriteJson(file, normalized)
866
+ return normalized
867
+ }
868
+
869
+ /**
870
+ * 0-Token Guard for System Global Vault:
871
+ * Returns ONLY entries the User explicitly mounted for Chief in THIS conversation (`chiefMountedSessions`).
872
+ * By default returns `[]` without reading or leaking anything into conversation context.
873
+ */
874
+ export function getChiefMountedGlobalForSession(rootSessionId = '', targetOpt) {
875
+ const sid = cleanRootSessionId(rootSessionId)
876
+ if (!sid) return []
877
+ const file = globalChiefVaultFilePath(targetOpt)
878
+ if (!fs.existsSync(file)) return []
879
+ const store = loadGlobalVaultRaw(targetOpt)
880
+ return store.items.filter(it => Array.isArray(it.chiefMountedSessions) && it.chiefMountedSessions.includes(sid))
881
+ }
882
+
883
+ /**
884
+ * Returns ONLY System Global Vault entries explicitly placed onto THIS session's desk (`takenOutSessions`),
885
+ * so both Lead & Chief emphasize them in prompt context while sealed global entries stay hidden from Lead.
886
+ */
887
+ export function getTakenOutGlobalForSession(rootSessionId = '', targetOpt) {
888
+ const sid = cleanRootSessionId(rootSessionId)
889
+ if (!sid) return []
890
+ const file = globalChiefVaultFilePath(targetOpt)
891
+ if (!fs.existsSync(file)) return []
892
+ const store = loadGlobalVaultRaw(targetOpt)
893
+ return store.items.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid))
894
+ }
895
+
896
+ /**
897
+ * Computes bidirectional diff between the active conversation's Local Session Cabinet and the System Global Vault.
898
+ */
899
+ export function computeSessionGlobalDiff(sessionItems = [], globalItems = [], rootSessionId = '') {
900
+ const sid = cleanRootSessionId(rootSessionId)
901
+ const sArr = Array.isArray(sessionItems) ? sessionItems : []
902
+ const gArr = Array.isArray(globalItems) ? globalItems : []
903
+
904
+ const gById = new Map()
905
+ const gByOriginId = new Map()
906
+ const gByTitle = new Map()
907
+ for (const g of gArr) {
908
+ if (!g) continue
909
+ gById.set(g.id, g)
910
+ if (g.originId) gByOriginId.set(g.originId, g)
911
+ const tk = normalizeArchiveTitleKey(g.title)
912
+ if (tk && !gByTitle.has(tk)) gByTitle.set(tk, g)
913
+ }
914
+
915
+ const sById = new Map()
916
+ const sByOriginGlobal = new Map()
917
+ const sByTitle = new Map()
918
+ for (const s of sArr) {
919
+ if (!s) continue
920
+ sById.set(s.id, s)
921
+ if (s.originGlobalId) sByOriginGlobal.set(s.originGlobalId, s)
922
+ const tk = normalizeArchiveTitleKey(s.title)
923
+ if (tk && !sByTitle.has(tk)) sByTitle.set(tk, s)
924
+ }
925
+
926
+ const sessionDiffMap = new Map()
927
+ const globalDiffMap = new Map()
928
+ let localOnlyCount = 0
929
+ let globalOnlyCount = 0
930
+ let syncedCount = 0
931
+ let modifiedCount = 0
932
+ const localOnlyBriefs = []
933
+
934
+ if (sid) {
935
+ for (const s of sArr) {
936
+ if (!s) continue
937
+ const gMatch = (s.originGlobalId && gById.get(s.originGlobalId))
938
+ || gByOriginId.get(s.id)
939
+ || gByTitle.get(normalizeArchiveTitleKey(s.title))
940
+ || null
941
+ if (!gMatch) {
942
+ localOnlyCount += 1
943
+ sessionDiffMap.set(s.id, { diffStatus: 'local_only', matchedGlobalId: '' })
944
+ if (localOnlyBriefs.length < 25) {
945
+ localOnlyBriefs.push({
946
+ id: s.id,
947
+ title: s.title,
948
+ summary: s.summary,
949
+ folder: s.folder,
950
+ paperclip: s.paperclip,
951
+ diffStatus: 'local_only',
952
+ updatedAt: s.updatedAt,
953
+ })
954
+ }
955
+ } else {
956
+ const sHash = computeEntryContentHash(s)
957
+ const gHash = computeEntryContentHash(gMatch)
958
+ if (sHash === gHash) {
959
+ syncedCount += 1
960
+ sessionDiffMap.set(s.id, { diffStatus: 'synced', matchedGlobalId: gMatch.id })
961
+ } else {
962
+ modifiedCount += 1
963
+ sessionDiffMap.set(s.id, { diffStatus: 'local_modified', matchedGlobalId: gMatch.id })
964
+ if (localOnlyBriefs.length < 25) {
965
+ localOnlyBriefs.push({
966
+ id: s.id,
967
+ title: s.title,
968
+ summary: s.summary,
969
+ folder: s.folder,
970
+ paperclip: s.paperclip,
971
+ diffStatus: 'local_modified',
972
+ matchedGlobalId: gMatch.id,
973
+ updatedAt: s.updatedAt,
974
+ })
975
+ }
976
+ }
977
+ }
978
+ }
979
+ }
980
+
981
+ for (const g of gArr) {
982
+ if (!g) continue
983
+ if (!sid) {
984
+ globalDiffMap.set(g.id, { diffStatus: 'unbound', matchedSessionItemId: '' })
985
+ continue
986
+ }
987
+ const sMatch = sByOriginGlobal.get(g.id)
988
+ || (g.originId ? sById.get(g.originId) : null)
989
+ || sByTitle.get(normalizeArchiveTitleKey(g.title))
990
+ || null
991
+ if (!sMatch) {
992
+ globalOnlyCount += 1
993
+ globalDiffMap.set(g.id, { diffStatus: 'global_only', matchedSessionItemId: '' })
994
+ } else {
995
+ const sHash = computeEntryContentHash(sMatch)
996
+ const gHash = computeEntryContentHash(g)
997
+ globalDiffMap.set(g.id, {
998
+ diffStatus: sHash === gHash ? 'synced' : 'differs',
999
+ matchedSessionItemId: sMatch.id,
1000
+ })
1001
+ }
1002
+ }
1003
+
1004
+ return {
1005
+ sessionDiffMap,
1006
+ globalDiffMap,
1007
+ summary: {
1008
+ unboundSession: !sid,
1009
+ sessionTotal: sid ? sArr.length : 0,
1010
+ globalTotal: gArr.length,
1011
+ localOnlyCount,
1012
+ globalOnlyCount: sid ? globalOnlyCount : gArr.length,
1013
+ syncedCount,
1014
+ modifiedCount,
1015
+ localOnlyBriefs,
1016
+ },
1017
+ }
1018
+ }
1019
+
596
1020
  export function loadArchiveStore(targetOpt) {
597
1021
  const resolved = ensureProjectCabinet(targetOpt)
1022
+ if (resolved.vaultScope === 'global') {
1023
+ return loadGlobalVaultRaw(targetOpt)
1024
+ }
1025
+ if (resolved.unboundSession || !resolved.cabinetFile) {
1026
+ return {
1027
+ ...normalizeArchiveStore({
1028
+ cabinetId: '',
1029
+ cabinetName: resolved.cabinetName || '本会话尚未开始(空白新对话)',
1030
+ projectKey: resolved.projectKey,
1031
+ }),
1032
+ unboundSession: true,
1033
+ }
1034
+ }
598
1035
  const file = resolved.cabinetFile
599
1036
  try {
600
1037
  const st = fs.statSync(file)
@@ -621,6 +1058,12 @@ export function loadArchiveStore(targetOpt) {
621
1058
 
622
1059
  export function saveArchiveStore(store, targetOpt) {
623
1060
  const resolved = ensureProjectCabinet(targetOpt)
1061
+ if (resolved.vaultScope === 'global') {
1062
+ return saveGlobalVaultRaw(store, targetOpt)
1063
+ }
1064
+ if (resolved.unboundSession || !resolved.cabinetFile) {
1065
+ throw new Error('当前未绑定具体对话(空白新对话),不能写入本会话档案柜')
1066
+ }
624
1067
  const file = resolved.cabinetFile
625
1068
  const normalized = normalizeArchiveStore({
626
1069
  ...store,
@@ -640,6 +1083,23 @@ export function saveArchiveStore(store, targetOpt) {
640
1083
 
641
1084
  export function withArchiveLock(targetOpt, fn) {
642
1085
  const resolved = ensureProjectCabinet(targetOpt)
1086
+ if (resolved.vaultScope === 'global') {
1087
+ const file = globalChiefVaultFilePath(targetOpt)
1088
+ const release = acquireFileLock(file)
1089
+ invalidateArchiveCache()
1090
+ try {
1091
+ return fn(file, resolved)
1092
+ } finally {
1093
+ release()
1094
+ }
1095
+ }
1096
+ if (resolved.unboundSession || !resolved.cabinetFile) {
1097
+ return {
1098
+ ok: false,
1099
+ unboundSession: true,
1100
+ error: '当前为空白新对话(尚未绑定会话 ID),请先在主会话发送一条消息,或切换到「🌐 全局档案柜」',
1101
+ }
1102
+ }
643
1103
  const file = resolved.cabinetFile
644
1104
  const release = acquireFileLock(file)
645
1105
  invalidateArchiveCache()
@@ -878,9 +1338,11 @@ export function smartParseNoteToDossier(rawNote) {
878
1338
  export function bootstrapArchivesFromSharedBoard({ sharedFile, loadBoard, saveBoard, pushLog }) {
879
1339
  try {
880
1340
  if (!sharedFile || !fs.existsSync(sharedFile)) return { migrated: 0 }
881
- // Ensure legacy `archives.json` is migrated to `cabinets/cab-main.json` first
882
- const resolved = ensureProjectCabinet({ customSharedBoardFile: sharedFile })
883
- const existing = loadArchiveStore({ customSharedBoardFile: sharedFile, cabinetId: resolved.cabinetId })
1341
+ // Ensure legacy `archives.json` & old board.notes migrate once into Global Cabinet (not into every blank chat!)
1342
+ const globalTarget = { customSharedBoardFile: sharedFile, vaultScope: 'global' }
1343
+ const resolved = ensureProjectCabinet(globalTarget)
1344
+ const storeTarget = { customSharedBoardFile: sharedFile, vaultScope: 'global', cabinetId: resolved.cabinetId }
1345
+ const existing = loadArchiveStore(storeTarget)
884
1346
  if (existing.migratedSharedAt > 0 && existing.items.length > 0) {
885
1347
  return { migrated: 0 }
886
1348
  }
@@ -889,10 +1351,10 @@ export function bootstrapArchivesFromSharedBoard({ sharedFile, loadBoard, saveBo
889
1351
  const legacyNotes = Array.isArray(sharedBoard && sharedBoard.notes) ? sharedBoard.notes : []
890
1352
  if (!legacyNotes.length) {
891
1353
  if (!existing.migratedSharedAt) {
892
- withArchiveLock({ customSharedBoardFile: sharedFile, cabinetId: resolved.cabinetId }, () => {
893
- const empty = loadArchiveStore({ customSharedBoardFile: sharedFile, cabinetId: resolved.cabinetId })
1354
+ withArchiveLock(storeTarget, () => {
1355
+ const empty = loadArchiveStore(storeTarget)
894
1356
  empty.migratedSharedAt = Date.now()
895
- saveArchiveStore(empty, { customSharedBoardFile: sharedFile, cabinetId: resolved.cabinetId })
1357
+ saveArchiveStore(empty, storeTarget)
896
1358
  })
897
1359
  }
898
1360
  return { migrated: 0 }
@@ -906,8 +1368,8 @@ export function bootstrapArchivesFromSharedBoard({ sharedFile, loadBoard, saveBo
906
1368
  } catch {}
907
1369
 
908
1370
  let migratedCount = 0
909
- withArchiveLock({ customSharedBoardFile: sharedFile, cabinetId: resolved.cabinetId }, () => {
910
- const store = loadArchiveStore({ customSharedBoardFile: sharedFile, cabinetId: resolved.cabinetId })
1371
+ withArchiveLock(storeTarget, () => {
1372
+ const store = loadArchiveStore(storeTarget)
911
1373
  const existingSourceIds = new Set(store.items.map(it => it.sourceNoteId).filter(Boolean))
912
1374
  const existingTitles = new Set(store.items.map(it => it.title))
913
1375
 
@@ -943,7 +1405,7 @@ export function bootstrapArchivesFromSharedBoard({ sharedFile, loadBoard, saveBo
943
1405
  }
944
1406
 
945
1407
  store.migratedSharedAt = Date.now()
946
- saveArchiveStore(store, { customSharedBoardFile: sharedFile, cabinetId: resolved.cabinetId })
1408
+ saveArchiveStore(store, storeTarget)
947
1409
  })
948
1410
 
949
1411
  if (migratedCount > 0 && typeof saveBoard === 'function') {
@@ -951,7 +1413,7 @@ export function bootstrapArchivesFromSharedBoard({ sharedFile, loadBoard, saveBo
951
1413
  if (typeof pushLog === 'function') {
952
1414
  pushLog(
953
1415
  sharedBoard,
954
- `🗄️ 已将 ${migratedCount} 篇历史工程笔记无损沉淀入「档案」柜(默认封存懒加载,不再每轮挤占上下文)`,
1416
+ `🗄️ 已将 ${migratedCount} 篇历史工程笔记无损沉淀入「全局档案柜」(默认封存懒加载,不再每轮挤占上下文)`,
955
1417
  'system',
956
1418
  '',
957
1419
  )
@@ -967,13 +1429,14 @@ export function bootstrapArchivesFromSharedBoard({ sharedFile, loadBoard, saveBo
967
1429
 
968
1430
  /* ------------------------------------------- Lazy-Loading Query & Mutations */
969
1431
 
970
- /** Ultra-lightweight metadata (<120 bytes) for `/snapshot` polling — ZERO archive text or precipitated reads! */
1432
+ /** Ultra-lightweight metadata (<160 bytes) for `/snapshot` polling — ZERO archive text or precipitated reads! */
971
1433
  export function getArchiveMeta(rootSessionId = '', targetOpt) {
972
- const cabInfo = listProjectCabinets(targetOpt)
973
- const store = loadArchiveStore(targetOpt)
974
- const sid = String(rootSessionId || '').trim()
1434
+ const effectiveTarget = withRootScope(targetOpt, rootSessionId)
1435
+ const cabInfo = listProjectCabinets(effectiveTarget)
1436
+ const store = loadArchiveStore(effectiveTarget)
1437
+ const sid = cleanRootSessionId(rootSessionId)
975
1438
  const nonEmptyFolders = new Set(store.items.map(it => it.folder).filter(Boolean))
976
- const takenOutCount = sid
1439
+ const takenOutCount = (sid && cabInfo.vaultScope !== 'global' && !cabInfo.unboundSession)
977
1440
  ? store.items.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid)).length
978
1441
  : 0
979
1442
  return {
@@ -981,35 +1444,104 @@ export function getArchiveMeta(rootSessionId = '', targetOpt) {
981
1444
  folderCount: nonEmptyFolders.size || DEFAULT_ARCHIVE_FOLDERS.length,
982
1445
  takenOutCount,
983
1446
  unorganizedCount: store.items.filter(it => it.folder === 'inbox' || it.organizedBy === 'auto').length,
1447
+ scope: cabInfo.vaultScope || cabInfo.scope || 'session',
1448
+ vaultScope: cabInfo.vaultScope || cabInfo.scope || 'session',
1449
+ isSystemGlobalVault: Boolean(cabInfo.isSystemGlobalVault),
1450
+ unboundSession: Boolean(cabInfo.unboundSession),
984
1451
  projectKey: cabInfo.projectKey,
985
1452
  activeCabinetId: cabInfo.activeCabinetId,
986
1453
  cabinetCount: cabInfo.cabinets.length,
987
1454
  }
988
1455
  }
989
1456
 
1457
+ function hasAnyPrecipitatedFilesOnDisk(targetOpt) {
1458
+ const globalFile = globalPrecipitatedFilePath(targetOpt)
1459
+ if (fs.existsSync(globalFile)) return true
1460
+ const dir = path.dirname(globalFile)
1461
+ try {
1462
+ if (!fs.existsSync(dir)) return false
1463
+ return fs.readdirSync(dir).some(name => name.endsWith('.json'))
1464
+ } catch {
1465
+ return false
1466
+ }
1467
+ }
1468
+
1469
+ /** Counts across all 3 tiers (`session`, `global`, `precipitated`) for UI tabs & `/snapshot`. */
1470
+ export function getThreeTierArchiveCounts(rootSessionId = '', flippedIds = [], targetOpt) {
1471
+ const sid = cleanRootSessionId(rootSessionId)
1472
+ const base = resolveTargetOpts(targetOpt)
1473
+ const sessionStore = sid
1474
+ ? loadArchiveStore({ customSharedBoardFile: base.customSharedBoardFile, cwd: base.cwd, projectKey: base.projectKey, rootSessionId: sid, vaultScope: 'session' })
1475
+ : { items: [], unboundSession: true }
1476
+ const globalStore = loadGlobalVaultRaw(base)
1477
+ let precipitatedCount = 0
1478
+ let flippedCount = Array.isArray(flippedIds) ? flippedIds.length : 0
1479
+ if (hasAnyPrecipitatedFilesOnDisk(base)) {
1480
+ const pStore = loadPrecipitatedStoreRaw(base.projectKey || 'proj-default', base)
1481
+ precipitatedCount = pStore.items.length
1482
+ if (sid) {
1483
+ flippedCount = pStore.items.filter(it => Array.isArray(it.flippedOutSessions) && it.flippedOutSessions.includes(sid)).length
1484
+ }
1485
+ }
1486
+ const globalMountedCount = sid
1487
+ ? globalStore.items.filter(it => Array.isArray(it.chiefMountedSessions) && it.chiefMountedSessions.includes(sid)).length
1488
+ : 0
1489
+ const globalTakenOutCount = sid
1490
+ ? globalStore.items.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid)).length
1491
+ : 0
1492
+ return {
1493
+ sessionCount: Array.isArray(sessionStore.items) ? sessionStore.items.length : 0,
1494
+ globalCount: Array.isArray(globalStore.items) ? globalStore.items.length : 0,
1495
+ globalMountedCount,
1496
+ globalTakenOutCount,
1497
+ precipitatedCount,
1498
+ flippedCount,
1499
+ unboundSession: !sid,
1500
+ }
1501
+ }
1502
+
990
1503
  /**
991
1504
  * Tier-1 Lazy Load (`GET /api/dsh-chief/archives`):
992
- * Returns active cabinet drawers + dossier headers + project cabinets list
993
- * (+ precipitated vault headers ONLY for the Archives tab UI when caller asks for them).
1505
+ * - `scope === 'global'`: reads standalone System Global Cold Vault (`global-vault/vault-chief-global.json`),
1506
+ * computes live diff against current conversation's Session Cabinet (when bound), and returns `isSystemGlobalVault: true`.
1507
+ * - `scope === 'session'`: reads ONLY this root conversation's Local Session Cabinet (strictly isolated 1:1),
1508
+ * computes diff against System Global Vault so each card knows whether it is local_only / synced / local_modified.
994
1509
  */
995
1510
  export function listArchiveHeaders(rootSessionId = '', opts = {}, targetOpt) {
996
- const target = targetOpt !== undefined
1511
+ const sid = cleanRootSessionId(rootSessionId || (opts && (opts.rootSessionId || opts.sessionId)))
1512
+ const requestedScope = normalizeVaultScope((opts && (opts.vaultScope || opts.scope)) || (targetOpt && typeof targetOpt === 'object' && (targetOpt.vaultScope || targetOpt.scope)))
1513
+ const baseTarget = targetOpt !== undefined
997
1514
  ? (typeof targetOpt === 'string'
998
- ? { customSharedBoardFile: targetOpt, cwd: opts && opts.cwd, projectKey: opts && opts.projectKey, cabinetId: opts && opts.cabinetId }
999
- : { ...opts, ...targetOpt })
1000
- : opts
1515
+ ? { customSharedBoardFile: targetOpt, cwd: opts && opts.cwd, projectKey: opts && opts.projectKey, cabinetId: opts && opts.cabinetId, vaultScope: requestedScope }
1516
+ : { ...opts, ...targetOpt, vaultScope: requestedScope })
1517
+ : { ...(opts || {}), vaultScope: requestedScope }
1518
+ const target = withRootScope(baseTarget, sid)
1519
+ const isGlobalReq = requestedScope === 'global'
1001
1520
  const cabInfo = listProjectCabinets(target)
1002
- const store = loadArchiveStore(target)
1003
- const sid = String(rootSessionId || '').trim()
1521
+ const store = isGlobalReq ? loadGlobalVaultRaw(baseTarget) : loadArchiveStore(target)
1522
+ const globalVault = isGlobalReq ? store : loadGlobalVaultRaw(baseTarget)
1523
+ const sessionStore = isGlobalReq
1524
+ ? (sid ? loadArchiveStore({ customSharedBoardFile: baseTarget.customSharedBoardFile, cwd: baseTarget.cwd, projectKey: baseTarget.projectKey, rootSessionId: sid, vaultScope: 'session' }) : { items: [], unboundSession: true })
1525
+ : store
1526
+ const diff = computeSessionGlobalDiff(
1527
+ sessionStore && !sessionStore.unboundSession ? sessionStore.items : [],
1528
+ globalVault.items,
1529
+ sid,
1530
+ )
1531
+
1004
1532
  const needle = String((opts && opts.query) || '').trim().toLowerCase()
1005
1533
  const folderFilter = String((opts && opts.folder) || '').trim()
1006
1534
  const clipFilter = String((opts && opts.paperclip) || '').trim()
1007
1535
 
1008
1536
  const clipRank = { gold: 0, silver: 1, copper: 2 }
1009
1537
  const sorted = store.items.slice().sort((a, b) => {
1010
- const aOut = sid && a.takenOutSessions.includes(sid) ? 0 : 1
1011
- const bOut = sid && b.takenOutSessions.includes(sid) ? 0 : 1
1012
- if (aOut !== bOut) return aOut - bOut
1538
+ const aPinned = isGlobalReq
1539
+ ? (sid && Array.isArray(a.chiefMountedSessions) && a.chiefMountedSessions.includes(sid) ? 0 : 1)
1540
+ : (sid && Array.isArray(a.takenOutSessions) && a.takenOutSessions.includes(sid) ? 0 : 1)
1541
+ const bPinned = isGlobalReq
1542
+ ? (sid && Array.isArray(b.chiefMountedSessions) && b.chiefMountedSessions.includes(sid) ? 0 : 1)
1543
+ : (sid && Array.isArray(b.takenOutSessions) && b.takenOutSessions.includes(sid) ? 0 : 1)
1544
+ if (aPinned !== bPinned) return aPinned - bPinned
1013
1545
  const cDiff = (clipRank[a.paperclip] ?? 1) - (clipRank[b.paperclip] ?? 1)
1014
1546
  if (cDiff !== 0) return cDiff
1015
1547
  return (b.updatedAt || 0) - (a.updatedAt || 0)
@@ -1044,46 +1576,74 @@ export function listArchiveHeaders(rootSessionId = '', opts = {}, targetOpt) {
1044
1576
  goldCount: goldByFolder[f.id] || 0,
1045
1577
  }))
1046
1578
 
1047
- const headers = filtered.map(it => ({
1048
- id: it.id,
1049
- title: it.title,
1050
- summary: it.summary,
1051
- folder: it.folder,
1052
- paperclip: it.paperclip,
1053
- tags: it.tags,
1054
- cold: it.cold,
1055
- takenOut: Boolean(sid && it.takenOutSessions.includes(sid)),
1056
- organizedBy: it.organizedBy,
1057
- pointCount: Array.isArray(it.points) ? it.points.length : 0,
1058
- pointPreviews: (Array.isArray(it.points) ? it.points : []).slice(0, 4).map(p => p.title),
1059
- bodyLength: (it.body || '').length,
1060
- updatedAt: it.updatedAt,
1061
- createdAt: it.createdAt,
1062
- }))
1579
+ const headers = filtered.map((it) => {
1580
+ const diffEntry = (isGlobalReq ? diff.globalDiffMap.get(it.id) : diff.sessionDiffMap.get(it.id)) || {}
1581
+ return {
1582
+ id: it.id,
1583
+ originId: it.originId || '',
1584
+ originGlobalId: it.originGlobalId || '',
1585
+ title: it.title,
1586
+ summary: it.summary,
1587
+ folder: it.folder,
1588
+ paperclip: it.paperclip,
1589
+ tags: it.tags,
1590
+ cold: true,
1591
+ takenOut: Boolean(sid && Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid)),
1592
+ chiefMounted: Boolean(isGlobalReq && sid && Array.isArray(it.chiefMountedSessions) && it.chiefMountedSessions.includes(sid)),
1593
+ diffStatus: diffEntry.diffStatus || (isGlobalReq ? (sid ? 'global_only' : 'unbound') : 'local_only'),
1594
+ matchedGlobalId: !isGlobalReq ? (diffEntry.matchedGlobalId || '') : '',
1595
+ matchedSessionItemId: isGlobalReq ? (diffEntry.matchedSessionItemId || '') : '',
1596
+ contentHash: it.contentHash || computeEntryContentHash(it),
1597
+ organizedBy: it.organizedBy,
1598
+ pointCount: Array.isArray(it.points) ? it.points.length : 0,
1599
+ pointPreviews: (Array.isArray(it.points) ? it.points : []).slice(0, 4).map(p => p.title),
1600
+ bodyLength: (it.body || '').length,
1601
+ updatedAt: it.updatedAt,
1602
+ createdAt: it.createdAt,
1603
+ }
1604
+ })
1063
1605
 
1064
1606
  const includePrecipitated = Boolean(opts && opts.includePrecipitated)
1065
1607
  const precipitated = includePrecipitated
1066
1608
  ? listPrecipitatedHeaders(cabInfo.projectKey, sid, target)
1067
1609
  : undefined
1610
+ const counts = (opts && opts.includeCounts !== false)
1611
+ ? getThreeTierArchiveCounts(sid, (opts && opts.flippedIds) || [], baseTarget)
1612
+ : undefined
1068
1613
 
1069
1614
  return {
1070
1615
  ok: true,
1071
- projectKey: cabInfo.projectKey,
1072
- activeCabinetId: cabInfo.activeCabinetId,
1073
- cabinets: cabInfo.cabinets,
1616
+ scope: isGlobalReq ? 'global' : (cabInfo.vaultScope || cabInfo.scope || 'session'),
1617
+ vaultScope: isGlobalReq ? 'global' : (cabInfo.vaultScope || cabInfo.scope || 'session'),
1618
+ isSystemGlobalVault: isGlobalReq,
1619
+ unboundSession: isGlobalReq ? false : Boolean(cabInfo.unboundSession),
1620
+ rootSessionId: sid,
1621
+ projectKey: isGlobalReq ? 'global' : cabInfo.projectKey,
1622
+ activeCabinetId: isGlobalReq ? '' : cabInfo.activeCabinetId,
1623
+ cabinets: isGlobalReq ? [] : cabInfo.cabinets,
1074
1624
  totalCount: store.items.length,
1075
- takenOutCount: sid ? store.items.filter(it => it.takenOutSessions.includes(sid)).length : 0,
1625
+ takenOutCount: sid
1626
+ ? store.items.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid)).length
1627
+ : 0,
1628
+ diffSummary: diff.summary,
1076
1629
  folders,
1077
1630
  items: headers,
1078
1631
  ...(precipitated !== undefined ? { precipitated } : {}),
1632
+ ...(counts !== undefined ? { counts } : {}),
1079
1633
  }
1080
1634
  }
1081
1635
 
1082
1636
  export function getArchiveDetail(idOrTitle = '', rootSessionId = '', targetOpt) {
1083
1637
  const target = String(idOrTitle || '').trim()
1084
1638
  if (!target) return { ok: false, error: 'archive id or title required' }
1085
- const store = loadArchiveStore(targetOpt)
1086
- const sid = String(rootSessionId || '').trim()
1639
+ const sid = cleanRootSessionId(rootSessionId)
1640
+ const base = resolveTargetOpts(targetOpt)
1641
+ const isGlobal = base.vaultScope === 'global'
1642
+ const resolved = ensureProjectCabinet(withRootScope(targetOpt, sid))
1643
+ if (!isGlobal && resolved.unboundSession) {
1644
+ return { ok: false, error: '当前为空白新对话,尚未建立本会话档案柜' }
1645
+ }
1646
+ const store = isGlobal ? loadGlobalVaultRaw(targetOpt) : loadArchiveStore(withRootScope(targetOpt, sid))
1087
1647
  const hit = store.items.find(it => it.id === target)
1088
1648
  || store.items.find(it => it.title === target)
1089
1649
  || store.items.find(it => it.title.toLowerCase().includes(target.toLowerCase()))
@@ -1091,18 +1651,24 @@ export function getArchiveDetail(idOrTitle = '', rootSessionId = '', targetOpt)
1091
1651
 
1092
1652
  return {
1093
1653
  ok: true,
1654
+ vaultScope: isGlobal ? 'global' : (resolved.vaultScope || 'session'),
1655
+ isSystemGlobalVault: isGlobal,
1094
1656
  item: {
1095
1657
  id: hit.id,
1658
+ originId: hit.originId || '',
1659
+ originGlobalId: hit.originGlobalId || '',
1096
1660
  title: hit.title,
1097
1661
  summary: hit.summary,
1098
1662
  folder: hit.folder,
1099
1663
  paperclip: hit.paperclip,
1100
1664
  tags: hit.tags,
1101
1665
  cold: hit.cold,
1102
- takenOut: Boolean(sid && hit.takenOutSessions.includes(sid)),
1666
+ takenOut: Boolean(sid && Array.isArray(hit.takenOutSessions) && hit.takenOutSessions.includes(sid)),
1667
+ chiefMounted: Boolean(isGlobal && sid && Array.isArray(hit.chiefMountedSessions) && hit.chiefMountedSessions.includes(sid)),
1103
1668
  organizedBy: hit.organizedBy,
1104
1669
  points: hit.points,
1105
1670
  body: hit.body,
1671
+ contentHash: hit.contentHash || computeEntryContentHash(hit),
1106
1672
  by: hit.by,
1107
1673
  createdAt: hit.createdAt,
1108
1674
  updatedAt: hit.updatedAt,
@@ -1111,23 +1677,26 @@ export function getArchiveDetail(idOrTitle = '', rootSessionId = '', targetOpt)
1111
1677
  }
1112
1678
 
1113
1679
  /**
1114
- * Strictly returns ONLY dossiers explicitly taken out onto the current session desk.
1115
- * NEVER reads `precipitated/<projectKey>.json`!
1680
+ * Strictly returns ONLY dossiers explicitly taken out onto the current session desk
1681
+ * FROM THIS CONVERSATION'S SESSION CABINET. NEVER reads Global Cabinet or `precipitated`!
1116
1682
  */
1117
1683
  export function getTakenOutArchivesForSession(rootSessionId = '', targetOpt) {
1118
- const sid = String(rootSessionId || '').trim()
1684
+ const sid = cleanRootSessionId(rootSessionId)
1119
1685
  if (!sid) return []
1120
- const store = loadArchiveStore(targetOpt)
1686
+ const base = resolveTargetOpts(targetOpt)
1687
+ const store = loadArchiveStore({
1688
+ customSharedBoardFile: base.customSharedBoardFile,
1689
+ cwd: base.cwd,
1690
+ projectKey: base.projectKey,
1691
+ cabinetId: base.cabinetId,
1692
+ rootSessionId: sid,
1693
+ vaultScope: 'session',
1694
+ })
1695
+ if (store.unboundSession) return []
1121
1696
  return store.items.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid))
1122
1697
  }
1123
1698
 
1124
- /** On-demand search for `chief_board({ action: "archive.search" })` or Chief explicit lookup.
1125
- * Strictly searches ONLY working cabinets — NEVER reads `precipitated/<projectKey>.json`! */
1126
- export function searchArchives(query = '', opts = {}, targetOpt) {
1127
- const effectiveTarget = targetOpt !== undefined
1128
- ? targetOpt
1129
- : (opts && (opts.cwd || opts.projectKey || opts.cabinetId || opts.customSharedBoardFile) ? opts : undefined)
1130
- const store = loadArchiveStore(effectiveTarget)
1699
+ function scoreAndRankArchiveItems(store, query = '', opts = {}) {
1131
1700
  const folder = String((opts && opts.folder) || '').trim()
1132
1701
  const limit = Math.max(1, Math.min(Number(opts && opts.limit) || 8, 25))
1133
1702
  const rawQ = String(query || '').trim().toLowerCase()
@@ -1137,7 +1706,7 @@ export function searchArchives(query = '', opts = {}, targetOpt) {
1137
1706
  .filter(Boolean)
1138
1707
 
1139
1708
  const scored = []
1140
- for (const it of store.items) {
1709
+ for (const it of (store && Array.isArray(store.items) ? store.items : [])) {
1141
1710
  if (folder && it.folder !== folder) continue
1142
1711
  if (!terms.length) {
1143
1712
  scored.push({ score: it.paperclip === 'gold' ? 5 : 2, it })
@@ -1164,11 +1733,10 @@ export function searchArchives(query = '', opts = {}, targetOpt) {
1164
1733
  }
1165
1734
 
1166
1735
  scored.sort((a, b) => b.score - a.score || (b.it.updatedAt || 0) - (a.it.updatedAt || 0))
1167
- const folderLabelMap = new Map(store.folders.map(f => [f.id, f.label]))
1736
+ const folderLabelMap = new Map((store && Array.isArray(store.folders) ? store.folders : []).map(f => [f.id, f.label]))
1168
1737
 
1169
1738
  return {
1170
- ok: true,
1171
- totalArchives: store.items.length,
1739
+ totalArchives: store && Array.isArray(store.items) ? store.items.length : 0,
1172
1740
  matchCount: scored.length,
1173
1741
  hits: scored.slice(0, limit).map(({ it }) => ({
1174
1742
  id: it.id,
@@ -1184,41 +1752,109 @@ export function searchArchives(query = '', opts = {}, targetOpt) {
1184
1752
  }
1185
1753
  }
1186
1754
 
1755
+ /** On-demand search for `chief_board({ action: "archive.search" })` inside THIS conversation's Session Cabinet.
1756
+ * Strictly NEVER reads System Global Vault or `precipitated`! */
1757
+ export function searchArchives(query = '', opts = {}, targetOpt) {
1758
+ const rawTarget = targetOpt !== undefined
1759
+ ? (typeof targetOpt === 'string'
1760
+ ? { customSharedBoardFile: targetOpt, vaultScope: 'session' }
1761
+ : { ...targetOpt, vaultScope: 'session' })
1762
+ : (opts && (opts.cwd || opts.projectKey || opts.cabinetId || opts.customSharedBoardFile || opts.rootSessionId || opts.sessionId)
1763
+ ? { ...opts, vaultScope: 'session' }
1764
+ : { vaultScope: 'session' })
1765
+ const store = loadArchiveStore(rawTarget)
1766
+ if (store.unboundSession) {
1767
+ return { ok: true, totalArchives: 0, matchCount: 0, hits: [], unboundSession: true }
1768
+ }
1769
+ return {
1770
+ ok: true,
1771
+ ...scoreAndRankArchiveItems(store, query, opts),
1772
+ }
1773
+ }
1774
+
1775
+ /** On-demand search strictly for Chief (`askChief`) across the System Global Cold Vault (`global-vault/vault-chief-global.json`).
1776
+ * NEVER exposed to Lead/Subagent `chief_board` tools. */
1777
+ export function searchGlobalVaultForChief(query = '', opts = {}, targetOpt) {
1778
+ const rawTarget = targetOpt !== undefined
1779
+ ? (typeof targetOpt === 'string' ? { customSharedBoardFile: targetOpt, vaultScope: 'global' } : { ...targetOpt, vaultScope: 'global' })
1780
+ : { ...(opts || {}), vaultScope: 'global' }
1781
+ const store = loadGlobalVaultRaw(rawTarget)
1782
+ return {
1783
+ ok: true,
1784
+ vaultScope: 'global',
1785
+ isSystemGlobalVault: true,
1786
+ ...scoreAndRankArchiveItems(store, query, opts),
1787
+ }
1788
+ }
1789
+
1187
1790
  /* ------------------------------------------- Cabinet & Archive Mutations */
1188
1791
 
1189
1792
  function mutateCabinetRegistry(payload = {}, targetOpt) {
1190
1793
  const op = str(payload.op, '').trim()
1191
1794
  const opts = resolveTargetOpts(targetOpt)
1795
+ const vaultScope = normalizeVaultScope(payload.vaultScope || payload.scope || opts.vaultScope)
1796
+ if (vaultScope === 'global') {
1797
+ if (op === 'listCabinets') {
1798
+ return {
1799
+ ok: true,
1800
+ scope: 'global',
1801
+ vaultScope: 'global',
1802
+ isSystemGlobalVault: true,
1803
+ projectKey: 'global',
1804
+ activeCabinetId: '',
1805
+ cabinets: [],
1806
+ }
1807
+ }
1808
+ return {
1809
+ ok: false,
1810
+ isSystemGlobalVault: true,
1811
+ error: '系统全局档案柜采用单一冷存储卷(与沉淀库同构),不支持多分柜创建、切换或删除',
1812
+ }
1813
+ }
1814
+ const rootSid = cleanRootSessionId(payload.rootSessionId || payload.session || opts.rootSessionId)
1192
1815
  const resolvedInit = ensureProjectCabinet({
1193
1816
  ...opts,
1194
1817
  cwd: str(payload.cwd, opts.cwd),
1195
1818
  projectKey: str(payload.projectKey, opts.projectKey),
1819
+ rootSessionId: rootSid,
1820
+ vaultScope,
1196
1821
  })
1197
1822
  const regFile = cabinetRegistryPath(opts.customSharedBoardFile)
1198
1823
  const projectKey = resolvedInit.projectKey
1824
+ const sessKey = normalizeSessionScopeKey(rootSid)
1199
1825
 
1200
1826
  if (op === 'listCabinets') {
1201
- return listProjectCabinets({ ...opts, projectKey })
1827
+ return listProjectCabinets({ ...opts, projectKey, rootSessionId: rootSid, vaultScope })
1828
+ }
1829
+
1830
+ if (resolvedInit.unboundSession || !sessKey) {
1831
+ return {
1832
+ ok: false,
1833
+ unboundSession: true,
1834
+ error: '当前为空白新对话(尚未绑定会话 ID),请先在主会话发送一条消息,或切换到「🌐 全局档案柜」',
1835
+ }
1202
1836
  }
1203
1837
 
1204
1838
  const release = acquireFileLock(regFile)
1205
1839
  try {
1206
1840
  const reg = normalizeRegistry(readJsonSafe(regFile, null))
1207
- const proj = reg.projects[projectKey] || resolvedInit.projectEntry
1208
- reg.projects[projectKey] = proj
1841
+ if (!reg.sessions[sessKey]) reg.sessions[sessKey] = resolvedInit.projectEntry
1842
+ const container = reg.sessions[sessKey]
1843
+ const scopeMeta = { scope: 'session', vaultScope: 'session', rootSessionId: rootSid }
1209
1844
 
1210
1845
  if (op === 'createCabinet') {
1211
- const name = clamp(payload.name || payload.label || `工作档案柜 ${proj.cabinets.length + 1}`, 40)
1212
- const dup = proj.cabinets.find(c => c.name === name)
1846
+ const name = clamp(payload.name || payload.label || `工作档案柜 ${container.cabinets.length + 1}`, 40)
1847
+ const dup = container.cabinets.find(c => c.name === name)
1213
1848
  if (dup) {
1214
- proj.activeCabinetId = dup.id
1849
+ container.activeCabinetId = dup.id
1215
1850
  writeRegistryRaw(regFile, reg)
1216
1851
  invalidateArchiveCache()
1217
1852
  return {
1218
1853
  ok: true,
1854
+ ...scopeMeta,
1219
1855
  cabinet: dup,
1220
- activeCabinetId: proj.activeCabinetId,
1221
- cabinets: proj.cabinets,
1856
+ activeCabinetId: container.activeCabinetId,
1857
+ cabinets: container.cabinets,
1222
1858
  projectKey,
1223
1859
  }
1224
1860
  }
@@ -1228,7 +1864,8 @@ function mutateCabinetRegistry(payload = {}, targetOpt) {
1228
1864
  id,
1229
1865
  name,
1230
1866
  projectKey,
1231
- cwd: proj.cwd || str(payload.cwd, opts.cwd),
1867
+ ...(rootSid && sessKey ? { rootSessionId: rootSid } : {}),
1868
+ cwd: container.cwd || str(payload.cwd, opts.cwd),
1232
1869
  createdAt: now,
1233
1870
  updatedAt: now,
1234
1871
  }
@@ -1238,41 +1875,43 @@ function mutateCabinetRegistry(payload = {}, targetOpt) {
1238
1875
  cabinetName: name,
1239
1876
  projectKey,
1240
1877
  }))
1241
- proj.cabinets.push(cabMeta)
1242
- proj.activeCabinetId = id
1878
+ container.cabinets.push(cabMeta)
1879
+ container.activeCabinetId = id
1243
1880
  writeRegistryRaw(regFile, reg)
1244
1881
  invalidateArchiveCache()
1245
1882
  return {
1246
1883
  ok: true,
1884
+ ...scopeMeta,
1247
1885
  cabinet: cabMeta,
1248
- activeCabinetId: proj.activeCabinetId,
1249
- cabinets: proj.cabinets,
1886
+ activeCabinetId: container.activeCabinetId,
1887
+ cabinets: container.cabinets,
1250
1888
  projectKey,
1251
1889
  }
1252
1890
  }
1253
1891
 
1254
1892
  if (op === 'switchCabinet') {
1255
1893
  const targetId = str(payload.cabinetId || payload.id, '').trim()
1256
- const hit = proj.cabinets.find(c => c.id === targetId)
1257
- if (!hit) return { ok: false, error: '未找到目标档案柜:' + targetId }
1258
- proj.activeCabinetId = hit.id
1894
+ const hit = container.cabinets.find(c => c.id === targetId)
1895
+ if (!hit) return { ok: false, error: '当前范围下未找到目标档案柜:' + targetId }
1896
+ container.activeCabinetId = hit.id
1259
1897
  hit.updatedAt = Date.now()
1260
1898
  writeRegistryRaw(regFile, reg)
1261
1899
  invalidateArchiveCache()
1262
1900
  return {
1263
1901
  ok: true,
1902
+ ...scopeMeta,
1264
1903
  cabinet: hit,
1265
- activeCabinetId: proj.activeCabinetId,
1266
- cabinets: proj.cabinets,
1904
+ activeCabinetId: container.activeCabinetId,
1905
+ cabinets: container.cabinets,
1267
1906
  projectKey,
1268
1907
  }
1269
1908
  }
1270
1909
 
1271
1910
  if (op === 'renameCabinet') {
1272
- const targetId = str(payload.cabinetId || payload.id, proj.activeCabinetId).trim()
1911
+ const targetId = str(payload.cabinetId || payload.id, container.activeCabinetId).trim()
1273
1912
  const name = clamp(payload.name || payload.label, 40)
1274
1913
  if (!name) return { ok: false, error: '请输入档案柜新名称' }
1275
- const hit = proj.cabinets.find(c => c.id === targetId)
1914
+ const hit = container.cabinets.find(c => c.id === targetId)
1276
1915
  if (!hit) return { ok: false, error: '未找到档案柜:' + targetId }
1277
1916
  hit.name = name
1278
1917
  hit.updatedAt = Date.now()
@@ -1284,23 +1923,24 @@ function mutateCabinetRegistry(payload = {}, targetOpt) {
1284
1923
  invalidateArchiveCache()
1285
1924
  return {
1286
1925
  ok: true,
1926
+ ...scopeMeta,
1287
1927
  cabinet: hit,
1288
- activeCabinetId: proj.activeCabinetId,
1289
- cabinets: proj.cabinets,
1928
+ activeCabinetId: container.activeCabinetId,
1929
+ cabinets: container.cabinets,
1290
1930
  projectKey,
1291
1931
  }
1292
1932
  }
1293
1933
 
1294
1934
  if (op === 'deleteCabinet') {
1295
1935
  const targetId = str(payload.cabinetId || payload.id, '').trim()
1296
- if (proj.cabinets.length <= 1) {
1297
- return { ok: false, error: '每个工程至少需保留一个主档案柜,不可删除最后一个档案柜' }
1936
+ if (container.cabinets.length <= 1) {
1937
+ return { ok: false, error: '每个范围至少需保留一个工作档案柜,不可删除最后一个档案柜' }
1298
1938
  }
1299
- const idx = proj.cabinets.findIndex(c => c.id === targetId)
1939
+ const idx = container.cabinets.findIndex(c => c.id === targetId)
1300
1940
  if (idx < 0) return { ok: false, error: '未找到要删除的档案柜:' + targetId }
1301
- const [removed] = proj.cabinets.splice(idx, 1)
1302
- if (proj.activeCabinetId === removed.id) {
1303
- proj.activeCabinetId = proj.cabinets[0].id
1941
+ const [removed] = container.cabinets.splice(idx, 1)
1942
+ if (container.activeCabinetId === removed.id) {
1943
+ container.activeCabinetId = container.cabinets[0].id
1304
1944
  }
1305
1945
  writeRegistryRaw(regFile, reg)
1306
1946
  try {
@@ -1310,9 +1950,10 @@ function mutateCabinetRegistry(payload = {}, targetOpt) {
1310
1950
  invalidateArchiveCache()
1311
1951
  return {
1312
1952
  ok: true,
1953
+ ...scopeMeta,
1313
1954
  removedId: removed.id,
1314
- activeCabinetId: proj.activeCabinetId,
1315
- cabinets: proj.cabinets,
1955
+ activeCabinetId: container.activeCabinetId,
1956
+ cabinets: container.cabinets,
1316
1957
  projectKey,
1317
1958
  }
1318
1959
  }
@@ -1325,22 +1966,25 @@ function mutateCabinetRegistry(payload = {}, targetOpt) {
1325
1966
 
1326
1967
  export function mutateArchive(payload = {}, targetOpt) {
1327
1968
  const op = str(payload.op, 'save').trim()
1328
- const rootSessionId = str(payload.rootSessionId || payload.session, '').trim()
1329
1969
  const baseOpts = resolveTargetOpts(targetOpt)
1970
+ const vaultScope = normalizeVaultScope(payload.vaultScope || payload.scope || baseOpts.vaultScope)
1971
+ const rootSessionId = cleanRootSessionId(payload.rootSessionId || payload.session || baseOpts.rootSessionId)
1330
1972
  const effectiveTarget = {
1331
1973
  ...baseOpts,
1332
1974
  cwd: str(payload.cwd, baseOpts.cwd),
1333
1975
  projectKey: str(payload.projectKey, baseOpts.projectKey),
1334
1976
  cabinetId: str(payload.cabinetId, baseOpts.cabinetId),
1977
+ rootSessionId,
1978
+ vaultScope,
1335
1979
  }
1336
1980
 
1337
1981
  if (['listCabinets', 'createCabinet', 'switchCabinet', 'renameCabinet', 'deleteCabinet'].includes(op)) {
1338
- return mutateCabinetRegistry(payload, effectiveTarget)
1982
+ return mutateCabinetRegistry({ ...payload, vaultScope }, effectiveTarget)
1339
1983
  }
1340
1984
 
1341
1985
  return withArchiveLock(effectiveTarget, (_file, resolved) => {
1342
- const store = loadArchiveStore({ ...effectiveTarget, cabinetId: resolved.cabinetId })
1343
- const lockTarget = { ...effectiveTarget, cabinetId: resolved.cabinetId, projectKey: resolved.projectKey }
1986
+ const store = loadArchiveStore({ ...effectiveTarget, cabinetId: resolved.cabinetId, rootSessionId: resolved.rootSessionId, vaultScope: resolved.vaultScope })
1987
+ const lockTarget = { ...effectiveTarget, cabinetId: resolved.cabinetId, projectKey: resolved.projectKey, rootSessionId: resolved.rootSessionId, vaultScope: resolved.vaultScope }
1344
1988
  const runOp = () => {
1345
1989
 
1346
1990
  if (op === 'createFolder' || op === 'saveFolder') {
@@ -1411,16 +2055,25 @@ export function mutateArchive(payload = {}, targetOpt) {
1411
2055
  140,
1412
2056
  )
1413
2057
  }
2058
+ existing.contentHash = computeEntryContentHash(existing)
1414
2059
  existing.updatedAt = Date.now()
1415
2060
  saveArchiveStore(store, lockTarget)
1416
- return { ok: true, item: existing, meta: getArchiveMeta(rootSessionId, lockTarget) }
2061
+ return {
2062
+ ok: true,
2063
+ isSystemGlobalVault: resolved.vaultScope === 'global',
2064
+ item: existing,
2065
+ meta: getArchiveMeta(rootSessionId, lockTarget),
2066
+ }
1417
2067
  }
1418
2068
 
1419
2069
  const rawTitle = clamp(payload.title || '', 180)
1420
2070
  if (!rawTitle && !nextBody) {
1421
2071
  return { ok: false, error: '新建工程档案需要填写标题或正文内容' }
1422
2072
  }
1423
- const sameTitle = rawTitle ? store.items.find(it => it.title === rawTitle) : null
2073
+ const titleKey = normalizeArchiveTitleKey(rawTitle)
2074
+ const sameTitle = titleKey
2075
+ ? store.items.find(it => normalizeArchiveTitleKey(it.title) === titleKey)
2076
+ : null
1424
2077
  if (sameTitle && payload.upsertByTitle !== false) {
1425
2078
  sameTitle.body = nextBody || sameTitle.body
1426
2079
  if (payload.folder) sameTitle.folder = str(payload.folder, sameTitle.folder).trim()
@@ -1435,9 +2088,16 @@ export function mutateArchive(payload = {}, targetOpt) {
1435
2088
  payload.summary || (sameTitle.points[0] && sameTitle.points[0].cue) || firstMeaningfulSentence(sameTitle.body) || sameTitle.title,
1436
2089
  140,
1437
2090
  )
2091
+ sameTitle.contentHash = computeEntryContentHash(sameTitle)
1438
2092
  sameTitle.updatedAt = Date.now()
1439
2093
  saveArchiveStore(store, lockTarget)
1440
- return { ok: true, item: sameTitle, updatedExisting: true, meta: getArchiveMeta(rootSessionId, lockTarget) }
2094
+ return {
2095
+ ok: true,
2096
+ isSystemGlobalVault: resolved.vaultScope === 'global',
2097
+ item: sameTitle,
2098
+ updatedExisting: true,
2099
+ meta: getArchiveMeta(rootSessionId, lockTarget),
2100
+ }
1441
2101
  }
1442
2102
 
1443
2103
  const parsed = smartParseNoteToDossier({
@@ -1447,16 +2107,19 @@ export function mutateArchive(payload = {}, targetOpt) {
1447
2107
  paperclip: payload.paperclip,
1448
2108
  tags: Array.isArray(payload.tags) ? payload.tags : (typeof payload.tags === 'string' ? payload.tags.split(/[,,]/) : []),
1449
2109
  })
1450
- const created = normalizeArchiveItem({
1451
- id: nextId('arch'),
2110
+ const baseCreated = {
2111
+ id: nextId(resolved.vaultScope === 'global' ? 'glob' : 'arch'),
1452
2112
  sourceNoteId: str(payload.sourceNoteId, ''),
2113
+ originId: str(payload.originId, ''),
2114
+ originGlobalId: str(payload.originGlobalId, ''),
1453
2115
  title: parsed.title,
1454
2116
  summary: payload.summary || parsed.summary,
1455
2117
  folder: payload.folder || parsed.folder,
1456
2118
  paperclip: payload.paperclip || parsed.paperclip,
1457
2119
  tags: Array.isArray(payload.tags) ? payload.tags : (typeof payload.tags === 'string' ? payload.tags.split(/[,,]/) : []),
1458
2120
  cold: true,
1459
- takenOutSessions: (payload.takeOutNow || payload.takeOut) && rootSessionId ? [rootSessionId] : [],
2121
+ takenOutSessions: (payload.takeOutNow || payload.takeOut) && rootSessionId && resolved.vaultScope !== 'global' ? [rootSessionId] : [],
2122
+ chiefMountedSessions: resolved.vaultScope === 'global' && payload.mountChief && rootSessionId ? [rootSessionId] : [],
1460
2123
  organizedBy: ['auto', 'chief', 'user'].includes(payload.organizedBy)
1461
2124
  ? payload.organizedBy
1462
2125
  : (Array.isArray(payload.points) && payload.points.length ? 'user' : 'auto'),
@@ -1466,10 +2129,18 @@ export function mutateArchive(payload = {}, targetOpt) {
1466
2129
  sourceSession: rootSessionId,
1467
2130
  createdAt: Date.now(),
1468
2131
  updatedAt: Date.now(),
1469
- })
2132
+ }
2133
+ const created = resolved.vaultScope === 'global'
2134
+ ? normalizeGlobalVaultEntry(baseCreated)
2135
+ : normalizeArchiveItem(baseCreated)
1470
2136
  store.items.unshift(created)
1471
2137
  saveArchiveStore(store, lockTarget)
1472
- return { ok: true, item: created, meta: getArchiveMeta(rootSessionId, lockTarget) }
2138
+ return {
2139
+ ok: true,
2140
+ isSystemGlobalVault: resolved.vaultScope === 'global',
2141
+ item: created,
2142
+ meta: getArchiveMeta(rootSessionId, lockTarget),
2143
+ }
1473
2144
  }
1474
2145
 
1475
2146
  if (op === 'delete' || op === 'remove') {
@@ -1494,9 +2165,34 @@ export function mutateArchive(payload = {}, targetOpt) {
1494
2165
  return { ok: true, removedCount, meta: getArchiveMeta(rootSessionId, lockTarget) }
1495
2166
  }
1496
2167
 
2168
+ if (op === 'mountChief' || op === 'unmountChief') {
2169
+ if (resolved.vaultScope !== 'global') {
2170
+ return { ok: false, error: '仅系统全局档案柜支持参谋长参阅挂载操作' }
2171
+ }
2172
+ if (!rootSessionId) {
2173
+ return { ok: false, error: '当前为空白新对话(尚未绑定会话 ID),请先在主会话发送一条消息后再供参谋长参阅' }
2174
+ }
2175
+ const id = str(payload.archiveId || payload.id, '').trim()
2176
+ const item = store.items.find(it => it.id === id)
2177
+ if (!item) return { ok: false, error: '未找到该全局档案:' + id }
2178
+ const set = new Set(item.chiefMountedSessions || [])
2179
+ if (op === 'mountChief') set.add(rootSessionId)
2180
+ else set.delete(rootSessionId)
2181
+ item.chiefMountedSessions = [...set]
2182
+ saveArchiveStore(store, lockTarget)
2183
+ return {
2184
+ ok: true,
2185
+ id: item.id,
2186
+ title: item.title,
2187
+ chiefMounted: op === 'mountChief',
2188
+ isSystemGlobalVault: true,
2189
+ counts: getThreeTierArchiveCounts(rootSessionId, [], lockTarget),
2190
+ }
2191
+ }
2192
+
1497
2193
  if (op === 'takeOut' || op === 'putBack') {
1498
2194
  const id = str(payload.archiveId || payload.id, '').trim()
1499
- if (!rootSessionId) return { ok: false, error: '当前未绑定对话会话,无法取出挂到桌面' }
2195
+ if (!rootSessionId) return { ok: false, error: '当前未绑定对话会话,无法摆到桌面备选' }
1500
2196
  const item = store.items.find(it => it.id === id)
1501
2197
  if (!item) return { ok: false, error: '未找到该工程档案:' + id }
1502
2198
  const set = new Set(item.takenOutSessions || [])
@@ -1509,6 +2205,8 @@ export function mutateArchive(payload = {}, targetOpt) {
1509
2205
  id: item.id,
1510
2206
  title: item.title,
1511
2207
  takenOut: op === 'takeOut',
2208
+ isSystemGlobalVault: resolved.vaultScope === 'global',
2209
+ counts: getThreeTierArchiveCounts(rootSessionId, [], lockTarget),
1512
2210
  meta: getArchiveMeta(rootSessionId, lockTarget),
1513
2211
  }
1514
2212
  }
@@ -1544,11 +2242,130 @@ export function mutateArchive(payload = {}, targetOpt) {
1544
2242
  return { ok: true, id: item.id, folder: item.folder }
1545
2243
  }
1546
2244
 
2245
+ if (op === 'copyToGlobal' || op === 'copyToSession') {
2246
+ const id = str(payload.archiveId || payload.id, '').trim()
2247
+ const srcItem = store.items.find(it => it.id === id)
2248
+ if (!srcItem) return { ok: false, error: '未找到要复制的工程档案:' + id }
2249
+ const targetScope = op === 'copyToGlobal' ? 'global' : 'session'
2250
+ if (targetScope === 'session' && !rootSessionId) {
2251
+ return { ok: false, error: '当前为空白新对话,请先发送一条消息建立会话后再引入本会话档案柜' }
2252
+ }
2253
+ const dstBase = {
2254
+ customSharedBoardFile: baseOpts.customSharedBoardFile,
2255
+ cwd: effectiveTarget.cwd,
2256
+ projectKey: effectiveTarget.projectKey,
2257
+ rootSessionId: targetScope === 'session' ? rootSessionId : '',
2258
+ vaultScope: targetScope,
2259
+ cabinetId: '',
2260
+ }
2261
+ const titleKey = normalizeArchiveTitleKey(srcItem.title)
2262
+ const copyRes = withArchiveLock(dstBase, (_dstFile, dstResolved) => {
2263
+ const dstTarget = { ...dstBase, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey, vaultScope: targetScope }
2264
+ const dstStore = targetScope === 'global' ? loadGlobalVaultRaw(dstTarget) : loadArchiveStore(dstTarget)
2265
+ const now = Date.now()
2266
+ let savedItem
2267
+
2268
+ if (targetScope === 'global') {
2269
+ const existing = dstStore.items.find(g =>
2270
+ (srcItem.originGlobalId && g.id === srcItem.originGlobalId)
2271
+ || (g.originId && g.originId === srcItem.id)
2272
+ || (titleKey && normalizeArchiveTitleKey(g.title) === titleKey)
2273
+ )
2274
+ const preservedChiefMounts = existing
2275
+ ? (Array.isArray(existing.chiefMountedSessions) ? existing.chiefMountedSessions : [])
2276
+ : (payload.mountChief && rootSessionId ? [rootSessionId] : [])
2277
+ const nextEntry = normalizeGlobalVaultEntry({
2278
+ ...srcItem,
2279
+ id: existing ? existing.id : nextId('glob'),
2280
+ originId: srcItem.id,
2281
+ originGlobalId: '',
2282
+ chiefMountedSessions: preservedChiefMounts,
2283
+ sourceSession: srcItem.sourceSession || rootSessionId,
2284
+ updatedAt: now,
2285
+ })
2286
+ if (existing) {
2287
+ Object.assign(existing, nextEntry)
2288
+ savedItem = existing
2289
+ } else {
2290
+ dstStore.items.unshift(nextEntry)
2291
+ savedItem = nextEntry
2292
+ }
2293
+ saveGlobalVaultRaw(dstStore, dstTarget)
2294
+ const sessSnapshot = resolved.vaultScope === 'session'
2295
+ ? store.items.map(it => (it.id === srcItem.id && payload.removeSource !== true ? { ...it, originGlobalId: savedItem.id } : it))
2296
+ : []
2297
+ const diff = computeSessionGlobalDiff(sessSnapshot, dstStore.items, rootSessionId)
2298
+ return {
2299
+ ok: true,
2300
+ targetScope: 'global',
2301
+ isSystemGlobalVault: true,
2302
+ targetCabinetId: '',
2303
+ item: savedItem,
2304
+ diffSummary: diff.summary,
2305
+ counts: getThreeTierArchiveCounts(rootSessionId, [], dstBase),
2306
+ }
2307
+ }
2308
+
2309
+ // targetScope === 'session'
2310
+ const mountOnSession = payload.takeOut === true
2311
+ const existingSess = dstStore.items.find(s =>
2312
+ s.originGlobalId === srcItem.id
2313
+ || (srcItem.originId && s.id === srcItem.originId)
2314
+ || (titleKey && normalizeArchiveTitleKey(s.title) === titleKey)
2315
+ )
2316
+ const nextSessItem = normalizeArchiveItem({
2317
+ ...srcItem,
2318
+ id: existingSess ? existingSess.id : nextId('arch'),
2319
+ originGlobalId: srcItem.id,
2320
+ originId: '',
2321
+ takenOutSessions: mountOnSession
2322
+ ? [...new Set([...(existingSess ? (existingSess.takenOutSessions || []) : []), rootSessionId])]
2323
+ : (existingSess ? (existingSess.takenOutSessions || []) : []),
2324
+ sourceSession: rootSessionId,
2325
+ updatedAt: now,
2326
+ })
2327
+ if (existingSess) {
2328
+ Object.assign(existingSess, nextSessItem)
2329
+ savedItem = existingSess
2330
+ } else {
2331
+ dstStore.items.unshift(nextSessItem)
2332
+ savedItem = nextSessItem
2333
+ }
2334
+ saveArchiveStore(dstStore, dstTarget)
2335
+ const globalItems = resolved.vaultScope === 'global' ? store.items : loadGlobalVaultRaw(baseOpts).items
2336
+ const diff = computeSessionGlobalDiff(dstStore.items, globalItems, rootSessionId)
2337
+ return {
2338
+ ok: true,
2339
+ targetScope: 'session',
2340
+ isSystemGlobalVault: false,
2341
+ targetCabinetId: dstResolved.cabinetId,
2342
+ item: savedItem,
2343
+ diffSummary: diff.summary,
2344
+ counts: getThreeTierArchiveCounts(rootSessionId, [], dstBase),
2345
+ }
2346
+ })
2347
+
2348
+ if (copyRes && copyRes.ok) {
2349
+ if (payload.removeSource === true && resolved.vaultScope !== targetScope) {
2350
+ const idx = store.items.findIndex(it => it.id === id)
2351
+ if (idx >= 0) {
2352
+ store.items.splice(idx, 1)
2353
+ saveArchiveStore(store, lockTarget)
2354
+ copyRes.counts = getThreeTierArchiveCounts(rootSessionId, [], dstBase)
2355
+ }
2356
+ } else if (targetScope === 'global' && resolved.vaultScope === 'session' && copyRes.item && srcItem.originGlobalId !== copyRes.item.id) {
2357
+ srcItem.originGlobalId = copyRes.item.id
2358
+ saveArchiveStore(store, lockTarget)
2359
+ }
2360
+ }
2361
+ return copyRes
2362
+ }
2363
+
1547
2364
  return { ok: false, error: '未知的档案操作:' + op }
1548
2365
  }
1549
2366
  const opRes = runOp()
1550
- return (opRes && opRes.ok && !opRes.cabinetId)
1551
- ? { cabinetId: resolved.cabinetId, ...opRes }
2367
+ return (opRes && opRes.ok && !opRes.cabinetId && !opRes.isSystemGlobalVault)
2368
+ ? { cabinetId: resolved.cabinetId, isSystemGlobalVault: resolved.vaultScope === 'global', ...opRes }
1552
2369
  : opRes
1553
2370
  })
1554
2371
  }
@@ -1557,7 +2374,13 @@ export function applyChiefArchiveCurations(curations = [], newFolders = [], targ
1557
2374
  if (!Array.isArray(curations) || !curations.length) return { updatedCount: 0 }
1558
2375
  return withArchiveLock(targetOpt, (_file, resolved) => {
1559
2376
  const base = resolveTargetOpts(targetOpt)
1560
- const lockTarget = { ...base, cabinetId: resolved.cabinetId, projectKey: resolved.projectKey }
2377
+ const lockTarget = {
2378
+ ...base,
2379
+ cabinetId: resolved.cabinetId,
2380
+ projectKey: resolved.projectKey,
2381
+ rootSessionId: resolved.rootSessionId || base.rootSessionId,
2382
+ vaultScope: resolved.vaultScope || base.vaultScope,
2383
+ }
1561
2384
  const store = loadArchiveStore(lockTarget)
1562
2385
  if (Array.isArray(newFolders)) {
1563
2386
  newFolders.forEach((nf, idx) => {
@@ -1650,7 +2473,7 @@ export function copyArchivesBetweenSessionsOrCabinets({
1650
2473
  const mode = ['none', 'mounted', 'drawer', 'all'].includes(policy) ? policy : 'none'
1651
2474
  const fromSid = str(fromRootSessionId, '').trim()
1652
2475
  const toSid = str(toRootSessionId, '').trim()
1653
- if (mode === 'none' || !toSid) {
2476
+ if (mode === 'none' || !fromSid || !toSid) {
1654
2477
  return { ok: true, policy: mode, transferredCount: 0, mountedCount: 0 }
1655
2478
  }
1656
2479
 
@@ -1658,16 +2481,23 @@ export function copyArchivesBetweenSessionsOrCabinets({
1658
2481
  customSharedBoardFile,
1659
2482
  cwd: fromCwd,
1660
2483
  cabinetId: fromCabinetId,
2484
+ rootSessionId: fromSid,
2485
+ vaultScope: 'session',
1661
2486
  }
1662
2487
  const dstTarget = {
1663
2488
  customSharedBoardFile,
1664
2489
  cwd: toCwd || fromCwd,
1665
2490
  cabinetId: toCabinetId,
2491
+ rootSessionId: toSid,
2492
+ vaultScope: 'session',
1666
2493
  }
1667
2494
 
1668
2495
  const srcResolved = ensureProjectCabinet(srcTarget)
1669
2496
  const dstResolved = ensureProjectCabinet(dstTarget)
1670
- const srcStore = loadArchiveStore({ customSharedBoardFile, cabinetId: srcResolved.cabinetId, projectKey: srcResolved.projectKey })
2497
+ if (srcResolved.unboundSession || dstResolved.unboundSession) {
2498
+ return { ok: true, policy: mode, transferredCount: 0, mountedCount: 0 }
2499
+ }
2500
+ const srcStore = loadArchiveStore({ customSharedBoardFile, cabinetId: srcResolved.cabinetId, projectKey: srcResolved.projectKey, rootSessionId: fromSid, vaultScope: 'session' })
1671
2501
 
1672
2502
  let selected = []
1673
2503
  if (mode === 'mounted') {
@@ -1692,8 +2522,8 @@ export function copyArchivesBetweenSessionsOrCabinets({
1692
2522
 
1693
2523
  // Same cabinet: update `takenOutSessions` on selected items directly (mount mounted items or selected drawer items for target)
1694
2524
  if (srcResolved.cabinetId === dstResolved.cabinetId) {
1695
- return withArchiveLock({ customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey }, () => {
1696
- const store = loadArchiveStore({ customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey })
2525
+ return withArchiveLock({ customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey, rootSessionId: toSid, vaultScope: 'session' }, () => {
2526
+ const store = loadArchiveStore({ customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey, rootSessionId: toSid, vaultScope: 'session' })
1697
2527
  let mountedCount = 0
1698
2528
  const selectedIds = new Set(selected.map(s => s.id))
1699
2529
  for (const it of store.items) {
@@ -1709,7 +2539,7 @@ export function copyArchivesBetweenSessionsOrCabinets({
1709
2539
  }
1710
2540
  }
1711
2541
  if (mountedCount > 0) {
1712
- saveArchiveStore(store, { customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey })
2542
+ saveArchiveStore(store, { customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey, rootSessionId: toSid, vaultScope: 'session' })
1713
2543
  }
1714
2544
  return {
1715
2545
  ok: true,
@@ -1723,8 +2553,8 @@ export function copyArchivesBetweenSessionsOrCabinets({
1723
2553
  }
1724
2554
 
1725
2555
  // Different cabinets: copy folders metadata & dossiers into destination cabinet
1726
- return withArchiveLock({ customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey }, () => {
1727
- const dstStore = loadArchiveStore({ customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey })
2556
+ return withArchiveLock({ customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey, rootSessionId: toSid, vaultScope: 'session' }, () => {
2557
+ const dstStore = loadArchiveStore({ customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey, rootSessionId: toSid, vaultScope: 'session' })
1728
2558
  const folderIds = new Set(dstStore.folders.map(f => f.id))
1729
2559
  for (const f of srcStore.folders) {
1730
2560
  if (!folderIds.has(f.id)) {
@@ -1760,7 +2590,7 @@ export function copyArchivesBetweenSessionsOrCabinets({
1760
2590
  }
1761
2591
  }
1762
2592
  if (copiedCount > 0 || mountedCount > 0) {
1763
- saveArchiveStore(dstStore, { customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey })
2593
+ saveArchiveStore(dstStore, { customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey, rootSessionId: toSid, vaultScope: 'session' })
1764
2594
  }
1765
2595
  return {
1766
2596
  ok: true,
@@ -1784,7 +2614,7 @@ function normalizePrecipitatedEntry(raw) {
1784
2614
  .map((p, idx) => normalizePoint(p, idx))
1785
2615
  .filter(Boolean)
1786
2616
  .slice(0, POINTS_CAP)
1787
- const validCategories = ['architecture', 'env', 'contract', 'troubleshooting', 'workflow', 'general']
2617
+ const validCategories = ['coords', 'incidents', 'contracts', 'ops', 'plans', 'architecture', 'env', 'contract', 'troubleshooting', 'workflow', 'general']
1788
2618
  const category = validCategories.includes(raw.category) ? raw.category : 'general'
1789
2619
  const flippedOutSessions = Array.isArray(raw.flippedOutSessions)
1790
2620
  ? [...new Set(raw.flippedOutSessions.map(s => str(s, '').trim()).filter(Boolean))].slice(0, 32)
@@ -1798,8 +2628,9 @@ function normalizePrecipitatedEntry(raw) {
1798
2628
  points: points.length ? points : extractStructuredPoints(title, rawBody),
1799
2629
  rawBody,
1800
2630
  purified: raw.purified !== false,
1801
- sourceCabinetId: str(raw.sourceCabinetId, '').trim(),
2631
+ sourceCabinetId: str(raw.sourceCabinetId || raw.sourceCabinet, '').trim(),
1802
2632
  sourceDrawer: str(raw.sourceDrawer, '').trim(),
2633
+ sourceSession: str(raw.sourceSession, '').trim(),
1803
2634
  sourceTitles: Array.isArray(raw.sourceTitles) ? raw.sourceTitles.map(t => clamp(t, 80)).slice(0, 40) : [],
1804
2635
  tags: normalizeTags(Array.isArray(raw.tags) ? raw.tags : []),
1805
2636
  flippedOutSessions,
@@ -1809,12 +2640,55 @@ function normalizePrecipitatedEntry(raw) {
1809
2640
  }
1810
2641
  }
1811
2642
 
1812
- function loadPrecipitatedStoreRaw(projectKey = 'proj-default', targetOpt) {
1813
- const file = precipitatedFilePath(projectKey, targetOpt)
2643
+ /** One-time lossless merge from legacy per-project `precipitated/*.json` files into unified `precipitated/vault-global.json`. */
2644
+ function ensureGlobalPrecipitatedVault(targetOpt) {
2645
+ const globalFile = globalPrecipitatedFilePath(targetOpt)
2646
+ if (fs.existsSync(globalFile)) return globalFile
2647
+ const dir = path.dirname(globalFile)
2648
+ if (!fs.existsSync(dir)) return globalFile
2649
+ let legacyFiles = []
2650
+ try {
2651
+ legacyFiles = fs.readdirSync(dir)
2652
+ .filter(name => name.endsWith('.json') && name !== 'vault-global.json')
2653
+ .map(name => path.join(dir, name))
2654
+ } catch {
2655
+ legacyFiles = []
2656
+ }
2657
+ if (!legacyFiles.length) return globalFile
2658
+
2659
+ const merged = []
2660
+ const seenIds = new Set()
2661
+ const seenKeys = new Set()
2662
+ for (const lf of legacyFiles) {
2663
+ const parsed = readJsonSafe(lf, null)
2664
+ const rawItems = Array.isArray(parsed && parsed.items) ? parsed.items : []
2665
+ for (const rawItem of rawItems) {
2666
+ const norm = normalizePrecipitatedEntry(rawItem)
2667
+ if (!norm) continue
2668
+ const dedupeKey = `${norm.title}::${norm.createdAt || 0}`
2669
+ if (seenIds.has(norm.id) || seenKeys.has(dedupeKey)) continue
2670
+ seenIds.add(norm.id)
2671
+ seenKeys.add(dedupeKey)
2672
+ merged.push(norm)
2673
+ }
2674
+ }
2675
+ if (!merged.length) return globalFile
2676
+ merged.sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0))
2677
+ atomicWriteJson(globalFile, {
2678
+ version: 1,
2679
+ projectKey: 'global',
2680
+ updatedAt: Date.now(),
2681
+ items: merged.slice(0, PRECIPITATED_CAP),
2682
+ })
2683
+ return globalFile
2684
+ }
2685
+
2686
+ function loadPrecipitatedStoreRaw(_projectKey = 'proj-default', targetOpt) {
2687
+ const file = ensureGlobalPrecipitatedVault(targetOpt)
1814
2688
  if (!fs.existsSync(file)) {
1815
2689
  return {
1816
2690
  version: 1,
1817
- projectKey: resolveProjectKey(projectKey),
2691
+ projectKey: 'global',
1818
2692
  updatedAt: 0,
1819
2693
  items: [],
1820
2694
  }
@@ -1826,17 +2700,17 @@ function loadPrecipitatedStoreRaw(projectKey = 'proj-default', targetOpt) {
1826
2700
  .slice(0, PRECIPITATED_CAP)
1827
2701
  return {
1828
2702
  version: 1,
1829
- projectKey: resolveProjectKey(projectKey),
2703
+ projectKey: 'global',
1830
2704
  updatedAt: Number(parsed && parsed.updatedAt) || Date.now(),
1831
2705
  items,
1832
2706
  }
1833
2707
  }
1834
2708
 
1835
- function savePrecipitatedStoreRaw(projectKey = 'proj-default', store, targetOpt) {
1836
- const file = precipitatedFilePath(projectKey, targetOpt)
2709
+ function savePrecipitatedStoreRaw(_projectKey = 'proj-default', store, targetOpt) {
2710
+ const file = globalPrecipitatedFilePath(targetOpt)
1837
2711
  const normalized = {
1838
2712
  version: 1,
1839
- projectKey: resolveProjectKey(projectKey),
2713
+ projectKey: 'global',
1840
2714
  updatedAt: Date.now(),
1841
2715
  items: (Array.isArray(store && store.items) ? store.items : [])
1842
2716
  .map(normalizePrecipitatedEntry)
@@ -1861,9 +2735,136 @@ export function getFlippedOutPrecipitatedForSession(projectKey = 'proj-default',
1861
2735
  return store.items.filter(it => Array.isArray(it.flippedOutSessions) && it.flippedOutSessions.includes(sid))
1862
2736
  }
1863
2737
 
2738
+ /**
2739
+ * Losslessly copy a precipitated cold-vault entry into `session` or `global` vault WITHOUT deleting the precipitated item.
2740
+ * Reads & releases precipitated lock BEFORE calling `mutateArchive` to strictly prevent lock-order inversion.
2741
+ */
2742
+ export function copyPrecipitatedToVault(projectKey = 'proj-default', payload = {}, targetOpt) {
2743
+ const pid = str(payload.id || payload.precipitatedId, '').trim()
2744
+ if (!pid) return { ok: false, error: 'missing precipitated id' }
2745
+ const targetScope = normalizeVaultScope(payload.targetScope || payload.toScope || 'session') === 'global' ? 'global' : 'session'
2746
+ const rootSid = cleanRootSessionId(payload.rootSessionId || payload.session || (targetOpt && targetOpt.rootSessionId))
2747
+ if (targetScope === 'session' && !rootSid) {
2748
+ return { ok: false, error: '当前为空白新对话,请先发送一条消息建立会话后再调入本局档案库' }
2749
+ }
2750
+
2751
+ const base = resolveTargetOpts(targetOpt)
2752
+ const file = globalPrecipitatedFilePath(base)
2753
+ const release = acquireFileLock(file)
2754
+ let snapshot = null
2755
+ try {
2756
+ const pStore = loadPrecipitatedStoreRaw(projectKey, base)
2757
+ const hit = pStore.items.find(it => it.id === pid)
2758
+ if (!hit) return { ok: false, error: '未找到沉淀条目:' + pid }
2759
+ snapshot = {
2760
+ id: hit.id,
2761
+ title: hit.title,
2762
+ category: hit.category || '经验',
2763
+ summary: hit.summary || '',
2764
+ points: Array.isArray(hit.points) ? hit.points.map(p => ({ ...p })) : [],
2765
+ body: hit.body || '',
2766
+ tags: Array.isArray(hit.tags) ? hit.tags.slice() : [],
2767
+ }
2768
+ } finally {
2769
+ release()
2770
+ }
2771
+
2772
+ const catFolderMap = {
2773
+ contracts: 'contracts',
2774
+ architecture: 'architecture',
2775
+ patterns: 'ops',
2776
+ pitfalls: 'pitfalls',
2777
+ toolchain: 'ops',
2778
+ }
2779
+ const folder = catFolderMap[snapshot.category] || 'ops'
2780
+ const pointText = snapshot.points.map(pt => `- ${pt.title}:${pt.detail || pt.cue || ''}`).join('\n')
2781
+ const fullBody = [
2782
+ snapshot.body || snapshot.summary,
2783
+ pointText ? '\n### 精炼要点\n' + pointText : '',
2784
+ ].filter(Boolean).join('\n')
2785
+
2786
+ const saveRes = mutateArchive({
2787
+ op: 'save',
2788
+ vaultScope: targetScope,
2789
+ rootSessionId: rootSid,
2790
+ folder,
2791
+ paperclip: 'silver',
2792
+ title: snapshot.title,
2793
+ summary: snapshot.summary,
2794
+ points: snapshot.points,
2795
+ body: fullBody || snapshot.title,
2796
+ tags: [...new Set(['沉淀调入', snapshot.category, ...snapshot.tags].filter(Boolean))],
2797
+ by: 'user',
2798
+ takeOutNow: Boolean(payload.takeOutNow && targetScope === 'session'),
2799
+ }, {
2800
+ ...base,
2801
+ vaultScope: targetScope,
2802
+ rootSessionId: targetScope === 'session' ? rootSid : '',
2803
+ cabinetId: '',
2804
+ })
2805
+
2806
+ if (!saveRes || !saveRes.ok) return saveRes || { ok: false, error: '调入目标档案库失败' }
2807
+ return {
2808
+ ...saveRes,
2809
+ copiedFromPrecipitatedId: snapshot.id,
2810
+ targetScope,
2811
+ lossless: true,
2812
+ }
2813
+ }
2814
+
2815
+ /** Listed ONLY for Chief background sealed-archive watch (never injected into Lead prompt unless placed on desk). */
2816
+ export function collectSealedWatchSummary(rootSessionId = '', projectKey = 'proj-default', targetOpt, opts = {}) {
2817
+ const sid = cleanRootSessionId(rootSessionId)
2818
+ const base = resolveTargetOpts(targetOpt)
2819
+ const capPerVault = Math.max(2, Math.min(Number(opts.limitPerVault) || 8, 16))
2820
+
2821
+ let sessionSealed = []
2822
+ let globalSealed = []
2823
+ let precipSealed = []
2824
+
2825
+ if (sid) {
2826
+ try {
2827
+ const sStore = loadArchiveStore({
2828
+ customSharedBoardFile: base.customSharedBoardFile,
2829
+ cwd: base.cwd,
2830
+ projectKey: base.projectKey,
2831
+ cabinetId: base.cabinetId,
2832
+ rootSessionId: sid,
2833
+ vaultScope: 'session',
2834
+ })
2835
+ if (!sStore.unboundSession) {
2836
+ sessionSealed = (sStore.items || [])
2837
+ .filter(it => !Array.isArray(it.takenOutSessions) || !it.takenOutSessions.includes(sid))
2838
+ .slice(0, capPerVault)
2839
+ .map(it => ({ id: it.id, scope: 'session', title: it.title, folder: it.folder, summary: it.summary }))
2840
+ }
2841
+ } catch {}
2842
+ }
2843
+
2844
+ try {
2845
+ const gStore = loadGlobalVaultRaw(base)
2846
+ globalSealed = (gStore.items || [])
2847
+ .filter(it => !sid || !Array.isArray(it.takenOutSessions) || !it.takenOutSessions.includes(sid))
2848
+ .slice(0, capPerVault)
2849
+ .map(it => ({ id: it.id, scope: 'global', title: it.title, folder: it.folder, summary: it.summary, chiefMounted: Boolean(sid && Array.isArray(it.chiefMountedSessions) && it.chiefMountedSessions.includes(sid)) }))
2850
+ } catch {}
2851
+
2852
+ if (hasAnyPrecipitatedFilesOnDisk(base)) {
2853
+ try {
2854
+ const pStore = loadPrecipitatedStoreRaw(projectKey || base.projectKey || 'proj-default', base)
2855
+ precipSealed = (pStore.items || [])
2856
+ .filter(it => !sid || !Array.isArray(it.flippedOutSessions) || !it.flippedOutSessions.includes(sid))
2857
+ .slice(0, capPerVault)
2858
+ .map(it => ({ id: it.id, scope: 'precipitated', title: it.title, category: it.category, summary: it.summary }))
2859
+ } catch {}
2860
+ }
2861
+
2862
+ return { sessionSealed, globalSealed, precipSealed }
2863
+ }
2864
+
1864
2865
  /** Listed ONLY when user opens the `档案` tab in Web UI (`GET /api/dsh-chief/archives`). */
1865
2866
  export function listPrecipitatedHeaders(projectKey = 'proj-default', rootSessionId = '', targetOpt) {
1866
- const file = precipitatedFilePath(projectKey, targetOpt)
2867
+ const file = ensureGlobalPrecipitatedVault(targetOpt)
1867
2868
  if (!fs.existsSync(file)) return []
1868
2869
  const sid = str(rootSessionId, '').trim()
1869
2870
  const store = loadPrecipitatedStoreRaw(projectKey, targetOpt)
@@ -1903,7 +2904,7 @@ export function getPrecipitatedDetail(projectKey = 'proj-default', id = '', root
1903
2904
 
1904
2905
  export function savePrecipitatedEntry(projectKey = 'proj-default', entry = {}, targetOpt) {
1905
2906
  const resolvedKey = resolveProjectKey(projectKey)
1906
- const file = precipitatedFilePath(resolvedKey, targetOpt)
2907
+ const file = globalPrecipitatedFilePath(targetOpt)
1907
2908
  const release = acquireFileLock(file)
1908
2909
  try {
1909
2910
  const store = loadPrecipitatedStoreRaw(resolvedKey, targetOpt)
@@ -1916,7 +2917,7 @@ export function savePrecipitatedEntry(projectKey = 'proj-default', entry = {}, t
1916
2917
  const updated = normalizePrecipitatedEntry({ ...existing, ...entry, id: existing.id, updatedAt: Date.now() })
1917
2918
  Object.assign(existing, updated)
1918
2919
  savePrecipitatedStoreRaw(resolvedKey, store, targetOpt)
1919
- return { ok: true, item: existing, file }
2920
+ return { ok: true, item: existing, entry: existing, file }
1920
2921
  }
1921
2922
  const created = normalizePrecipitatedEntry({
1922
2923
  ...entry,
@@ -1928,7 +2929,7 @@ export function savePrecipitatedEntry(projectKey = 'proj-default', entry = {}, t
1928
2929
  if (!created) return { ok: false, error: '无法写入空的沉淀经验' }
1929
2930
  store.items.unshift(created)
1930
2931
  savePrecipitatedStoreRaw(resolvedKey, store, targetOpt)
1931
- return { ok: true, item: created, file }
2932
+ return { ok: true, item: created, entry: created, file }
1932
2933
  } finally {
1933
2934
  release()
1934
2935
  }
@@ -1936,7 +2937,7 @@ export function savePrecipitatedEntry(projectKey = 'proj-default', entry = {}, t
1936
2937
 
1937
2938
  export function mutatePrecipitated(projectKey = 'proj-default', payload = {}, targetOpt) {
1938
2939
  const resolvedKey = resolveProjectKey(projectKey || payload.projectKey || payload.cwd || 'proj-default')
1939
- const file = precipitatedFilePath(resolvedKey, targetOpt)
2940
+ const file = globalPrecipitatedFilePath(targetOpt)
1940
2941
  const op = str(payload.op, '').trim()
1941
2942
  const sid = str(payload.rootSessionId || payload.session, '').trim()
1942
2943
  const id = str(payload.precipitatedId || payload.id, '').trim()