dsh-chief 1.2.0 → 1.3.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.
@@ -0,0 +1,766 @@
1
+ /**
2
+ * archive-cabinets.js
3
+ *
4
+ * Project cabinet registry, legacy shared-board migration, and locked Global/Session vault IO.
5
+ */
6
+
7
+ import fs from 'node:fs'
8
+ import path from 'node:path'
9
+ import {
10
+ ARCHIVE_VERSION,
11
+ SECRET_PATTERN,
12
+ nextId,
13
+ str,
14
+ clamp,
15
+ resolveProjectKey,
16
+ normalizeVaultScope,
17
+ cleanRootSessionId,
18
+ resolveTargetOpts,
19
+ normalizeSessionScopeKey,
20
+ sessionCabinetId,
21
+ legacyArchiveFilePath,
22
+ cabinetRegistryPath,
23
+ cabinetFilePath,
24
+ globalChiefVaultFilePath,
25
+ acquireFileLock,
26
+ invalidateArchiveCache,
27
+ atomicWriteJson,
28
+ readJsonSafe,
29
+ normalizeArchiveItem,
30
+ normalizeArchiveStore,
31
+ smartParseNoteToDossier,
32
+ getCachedArchiveStore,
33
+ setCachedArchiveStore,
34
+ } from './archive-core.js'
35
+
36
+ function normalizeRegistry(raw) {
37
+ const src = raw && typeof raw === 'object' ? raw : {}
38
+ const projects = {}
39
+ if (src.projects && typeof src.projects === 'object') {
40
+ for (const [k, proj] of Object.entries(src.projects)) {
41
+ if (!proj || typeof proj !== 'object') continue
42
+ const pKey = resolveProjectKey(k)
43
+ const cabinets = (Array.isArray(proj.cabinets) ? proj.cabinets : [])
44
+ .filter(c => c && typeof c === 'object' && str(c.id, '').trim())
45
+ .map(c => ({
46
+ id: str(c.id, '').trim().slice(0, 72),
47
+ name: clamp(c.name || '默认档案柜', 40),
48
+ projectKey: pKey,
49
+ cwd: str(c.cwd, '').slice(0, 260),
50
+ createdAt: Number(c.createdAt) || Date.now(),
51
+ updatedAt: Number(c.updatedAt) || Number(c.createdAt) || Date.now(),
52
+ }))
53
+ if (!cabinets.length) continue
54
+ const activeCabinetId = cabinets.some(c => c.id === proj.activeCabinetId)
55
+ ? proj.activeCabinetId
56
+ : cabinets[0].id
57
+ projects[pKey] = {
58
+ projectKey: pKey,
59
+ cwd: str(proj.cwd, '').slice(0, 260),
60
+ activeCabinetId,
61
+ cabinets,
62
+ }
63
+ }
64
+ }
65
+ const sessions = {}
66
+ if (src.sessions && typeof src.sessions === 'object') {
67
+ for (const [rawKey, sess] of Object.entries(src.sessions)) {
68
+ if (!sess || typeof sess !== 'object') continue
69
+ const rSid = str(sess.rootSessionId || rawKey.replace(/^sess:/, ''), '').trim()
70
+ const sKey = normalizeSessionScopeKey(rSid)
71
+ if (!sKey) continue
72
+ const pKey = resolveProjectKey(sess.projectKey || sess.cwd || 'proj-default')
73
+ const cabinets = (Array.isArray(sess.cabinets) ? sess.cabinets : [])
74
+ .filter(c => c && typeof c === 'object' && str(c.id, '').trim())
75
+ .map(c => ({
76
+ id: str(c.id, '').trim().slice(0, 72),
77
+ name: clamp(c.name || '本对话工作档案柜', 40),
78
+ projectKey: pKey,
79
+ rootSessionId: rSid,
80
+ cwd: str(c.cwd, '').slice(0, 260),
81
+ createdAt: Number(c.createdAt) || Date.now(),
82
+ updatedAt: Number(c.updatedAt) || Number(c.createdAt) || Date.now(),
83
+ }))
84
+ if (!cabinets.length) continue
85
+ const activeCabinetId = cabinets.some(c => c.id === sess.activeCabinetId)
86
+ ? sess.activeCabinetId
87
+ : cabinets[0].id
88
+ sessions[sKey] = {
89
+ sessionKey: sKey,
90
+ rootSessionId: rSid,
91
+ projectKey: pKey,
92
+ cwd: str(sess.cwd, '').slice(0, 260),
93
+ activeCabinetId,
94
+ cabinets,
95
+ }
96
+ }
97
+ }
98
+ let globalEntry = null
99
+ if (src.global && typeof src.global === 'object') {
100
+ const gCabs = (Array.isArray(src.global.cabinets) ? src.global.cabinets : [])
101
+ .filter(c => c && typeof c === 'object' && str(c.id, '').trim())
102
+ .map(c => ({
103
+ id: str(c.id, '').trim().slice(0, 72),
104
+ name: clamp(c.name || '🌐 全局工作档案柜', 40),
105
+ projectKey: 'global',
106
+ cwd: '',
107
+ createdAt: Number(c.createdAt) || Date.now(),
108
+ updatedAt: Number(c.updatedAt) || Number(c.createdAt) || Date.now(),
109
+ }))
110
+ if (gCabs.length) {
111
+ globalEntry = {
112
+ projectKey: 'global',
113
+ cwd: '',
114
+ activeCabinetId: gCabs.some(c => c.id === src.global.activeCabinetId) ? src.global.activeCabinetId : gCabs[0].id,
115
+ cabinets: gCabs,
116
+ }
117
+ }
118
+ }
119
+ return {
120
+ version: ARCHIVE_VERSION,
121
+ migratedLegacy: Boolean(src.migratedLegacy),
122
+ migratedGlobalAt: Number(src.migratedGlobalAt) || 0,
123
+ migratedAt: Number(src.migratedAt) || 0,
124
+ legacyOwnerProjectKey: str(src.legacyOwnerProjectKey, ''),
125
+ projects,
126
+ sessions,
127
+ global: globalEntry,
128
+ }
129
+ }
130
+
131
+ function writeRegistryRaw(regFile, registry) {
132
+ atomicWriteJson(regFile, normalizeRegistry(registry))
133
+ }
134
+
135
+ function claimSessionOwnLegacyItems(reg, projectKey, rootSessionId, opts) {
136
+ const claimed = []
137
+ const seenTitles = new Set()
138
+ const candidateCabIds = new Set(['cab-main'])
139
+ const projEntry = reg.projects && reg.projects[projectKey]
140
+ if (projEntry && Array.isArray(projEntry.cabinets)) {
141
+ for (const c of projEntry.cabinets) {
142
+ if (c && c.id) candidateCabIds.add(c.id)
143
+ }
144
+ }
145
+ for (const cabId of candidateCabIds) {
146
+ const file = cabinetFilePath(cabId, opts.customSharedBoardFile)
147
+ const parsed = readJsonSafe(file, null)
148
+ const items = Array.isArray(parsed && parsed.items) ? parsed.items : []
149
+ for (const rawItem of items) {
150
+ if (!rawItem || str(rawItem.sourceSession, '').trim() !== rootSessionId) continue
151
+ const norm = normalizeArchiveItem(rawItem)
152
+ if (!norm || seenTitles.has(norm.title)) continue
153
+ seenTitles.add(norm.title)
154
+ claimed.push(norm)
155
+ }
156
+ }
157
+ return claimed
158
+ }
159
+
160
+ export function ensureProjectCabinet(targetOpt) {
161
+ const opts = resolveTargetOpts(targetOpt)
162
+ const regFile = cabinetRegistryPath(opts.customSharedBoardFile)
163
+ const legacyFile = legacyArchiveFilePath(opts.customSharedBoardFile)
164
+ const projectKey = opts.projectKey ? resolveProjectKey(opts.projectKey) : resolveProjectKey(opts.cwd)
165
+ const sessKey = normalizeSessionScopeKey(opts.rootSessionId)
166
+ const vaultScope = opts.vaultScope === 'global' ? 'global' : 'session'
167
+
168
+ const release = acquireFileLock(regFile)
169
+ try {
170
+ let reg = normalizeRegistry(readJsonSafe(regFile, null))
171
+ let dirty = false
172
+
173
+ // 1. One-time lossless migration from legacy `%DSH_HOME%/chief/archives.json` -> `cabinets/cab-main.json`
174
+ if (!reg.migratedLegacy && fs.existsSync(legacyFile)) {
175
+ const legacyParsed = readJsonSafe(legacyFile, null)
176
+ const cabMainFile = cabinetFilePath('cab-main', opts.customSharedBoardFile)
177
+ if (legacyParsed && !fs.existsSync(cabMainFile)) {
178
+ const normalizedLegacy = normalizeArchiveStore({
179
+ ...legacyParsed,
180
+ cabinetId: 'cab-main',
181
+ cabinetName: '默认主档案柜',
182
+ projectKey,
183
+ })
184
+ atomicWriteJson(cabMainFile, normalizedLegacy)
185
+ }
186
+ if (!reg.projects[projectKey]) {
187
+ const now = Date.now()
188
+ reg.projects[projectKey] = {
189
+ projectKey,
190
+ cwd: opts.cwd,
191
+ activeCabinetId: 'cab-main',
192
+ cabinets: [
193
+ {
194
+ id: 'cab-main',
195
+ name: opts.cwd ? `${path.basename(opts.cwd) || '当前工程'} · 主档案柜` : '默认主档案柜',
196
+ projectKey,
197
+ cwd: opts.cwd,
198
+ createdAt: now,
199
+ updatedAt: now,
200
+ },
201
+ ],
202
+ }
203
+ reg.legacyOwnerProjectKey = projectKey
204
+ }
205
+ reg.migratedLegacy = true
206
+ reg.migratedAt = Date.now()
207
+ dirty = true
208
+ }
209
+
210
+ // 2. SYSTEM GLOBAL COLD VAULT (`vaultScope === 'global'`):
211
+ // Mirrors Precipitated Vault's system-level cold storage: NEVER auto-populated from cab-main or project cabinets,
212
+ // NEVER follows conversation context automatically (0 Token until Chief-search hit or explicit mount/import).
213
+ if (vaultScope === 'global') {
214
+ const globalFile = globalChiefVaultFilePath(opts.customSharedBoardFile)
215
+ if (dirty) {
216
+ writeRegistryRaw(regFile, reg)
217
+ }
218
+ return {
219
+ scope: 'global',
220
+ vaultScope: 'global',
221
+ isSystemGlobalVault: true,
222
+ unboundSession: false,
223
+ sessionKey: '',
224
+ rootSessionId: opts.rootSessionId || '',
225
+ projectKey: 'global',
226
+ cabinetId: '',
227
+ cabinetName: '🌐 系统全局档案柜(0 Token 冷封存 · 仅参谋与您可见)',
228
+ cabinetFile: globalFile,
229
+ registry: reg,
230
+ projectEntry: {
231
+ projectKey: 'global',
232
+ activeCabinetId: '',
233
+ cabinets: [],
234
+ },
235
+ }
236
+ }
237
+
238
+ // 3B. STRICT SESSION-ISOLATED WORKING CABINET (`sess:<rootSessionId>`):
239
+ // Working cabinets are strictly 1-to-1 with ONE root conversation (never shared across sessions!).
240
+ if (sessKey) {
241
+ if (!reg.sessions[sessKey]) {
242
+ const now = Date.now()
243
+ const defaultCabId = sessionCabinetId(opts.rootSessionId)
244
+ const cabFile = cabinetFilePath(defaultCabId, opts.customSharedBoardFile)
245
+ if (!fs.existsSync(cabFile)) {
246
+ const ownItems = claimSessionOwnLegacyItems(reg, projectKey, opts.rootSessionId, opts)
247
+ atomicWriteJson(cabFile, normalizeArchiveStore({
248
+ cabinetId: defaultCabId,
249
+ cabinetName: '本对话工作档案柜',
250
+ projectKey,
251
+ items: ownItems,
252
+ }))
253
+ }
254
+ reg.sessions[sessKey] = {
255
+ sessionKey: sessKey,
256
+ rootSessionId: opts.rootSessionId,
257
+ projectKey,
258
+ cwd: opts.cwd,
259
+ activeCabinetId: defaultCabId,
260
+ cabinets: [
261
+ {
262
+ id: defaultCabId,
263
+ name: '本对话工作档案柜',
264
+ projectKey,
265
+ rootSessionId: opts.rootSessionId,
266
+ cwd: opts.cwd,
267
+ createdAt: now,
268
+ updatedAt: now,
269
+ },
270
+ ],
271
+ }
272
+ dirty = true
273
+ } else {
274
+ if (opts.cwd && !reg.sessions[sessKey].cwd) {
275
+ reg.sessions[sessKey].cwd = opts.cwd
276
+ dirty = true
277
+ }
278
+ if (projectKey && reg.sessions[sessKey].projectKey !== projectKey && opts.cwd) {
279
+ reg.sessions[sessKey].projectKey = projectKey
280
+ dirty = true
281
+ }
282
+ }
283
+
284
+ const sessEntry = reg.sessions[sessKey]
285
+ let selectedCabinet = null
286
+ // Strictly match ONLY within THIS session's own cabinets (never cross-mount cab-main/cab-global!)
287
+ if (opts.cabinetId) {
288
+ selectedCabinet = sessEntry.cabinets.find(c => c.id === opts.cabinetId) || null
289
+ }
290
+ if (!selectedCabinet) {
291
+ selectedCabinet = sessEntry.cabinets.find(c => c.id === sessEntry.activeCabinetId) || sessEntry.cabinets[0]
292
+ }
293
+ const selectedFile = cabinetFilePath(selectedCabinet.id, opts.customSharedBoardFile)
294
+ if (!fs.existsSync(selectedFile)) {
295
+ atomicWriteJson(selectedFile, normalizeArchiveStore({
296
+ cabinetId: selectedCabinet.id,
297
+ cabinetName: selectedCabinet.name,
298
+ projectKey,
299
+ }))
300
+ }
301
+ if (dirty || !fs.existsSync(regFile)) {
302
+ writeRegistryRaw(regFile, reg)
303
+ }
304
+ return {
305
+ scope: 'session',
306
+ vaultScope: 'session',
307
+ unboundSession: false,
308
+ sessionKey: sessKey,
309
+ rootSessionId: opts.rootSessionId,
310
+ projectKey: sessEntry.projectKey || projectKey,
311
+ cabinetId: selectedCabinet.id,
312
+ cabinetName: selectedCabinet.name,
313
+ cabinetFile: selectedFile,
314
+ registry: reg,
315
+ projectEntry: sessEntry,
316
+ }
317
+ }
318
+
319
+ // 3C. Unbound / blank new conversation: MUST NOT fall back to cab-main or cab-global!
320
+ if (dirty || !fs.existsSync(regFile)) {
321
+ writeRegistryRaw(regFile, reg)
322
+ }
323
+ return {
324
+ scope: 'session',
325
+ vaultScope: 'session',
326
+ unboundSession: true,
327
+ sessionKey: '',
328
+ rootSessionId: '',
329
+ projectKey,
330
+ cabinetId: '',
331
+ cabinetName: '本会话尚未开始(空白新对话)',
332
+ cabinetFile: '',
333
+ registry: reg,
334
+ projectEntry: {
335
+ projectKey,
336
+ activeCabinetId: '',
337
+ cabinets: [],
338
+ },
339
+ }
340
+ } finally {
341
+ release()
342
+ }
343
+ }
344
+
345
+ export function archiveFilePath(targetOpt) {
346
+ const resolved = ensureProjectCabinet(targetOpt)
347
+ return resolved.cabinetFile || ''
348
+ }
349
+
350
+ export function listProjectCabinets(targetOpt) {
351
+ const resolved = ensureProjectCabinet(targetOpt)
352
+ const isGlobal = Boolean(resolved.isSystemGlobalVault || resolved.vaultScope === 'global')
353
+ return {
354
+ ok: true,
355
+ scope: isGlobal ? 'global' : (resolved.scope || 'session'),
356
+ vaultScope: isGlobal ? 'global' : (resolved.vaultScope || resolved.scope || 'session'),
357
+ isSystemGlobalVault: isGlobal,
358
+ unboundSession: isGlobal ? false : Boolean(resolved.unboundSession),
359
+ rootSessionId: resolved.rootSessionId || '',
360
+ projectKey: resolved.projectKey,
361
+ activeCabinetId: isGlobal ? '' : (resolved.projectEntry ? resolved.projectEntry.activeCabinetId : ''),
362
+ cabinets: isGlobal
363
+ ? []
364
+ : (resolved.projectEntry && Array.isArray(resolved.projectEntry.cabinets) ? resolved.projectEntry.cabinets : []).map(c => ({ ...c })),
365
+ }
366
+ }
367
+
368
+ /* ------------------------------------------- Normalization */
369
+
370
+ export function mutateCabinetRegistry(payload = {}, targetOpt) {
371
+ const op = str(payload.op, '').trim()
372
+ const opts = resolveTargetOpts(targetOpt)
373
+ const vaultScope = normalizeVaultScope(payload.vaultScope || payload.scope || opts.vaultScope)
374
+ if (vaultScope === 'global') {
375
+ if (op === 'listCabinets') {
376
+ return {
377
+ ok: true,
378
+ scope: 'global',
379
+ vaultScope: 'global',
380
+ isSystemGlobalVault: true,
381
+ projectKey: 'global',
382
+ activeCabinetId: '',
383
+ cabinets: [],
384
+ }
385
+ }
386
+ return {
387
+ ok: false,
388
+ isSystemGlobalVault: true,
389
+ error: '系统全局档案柜采用单一冷存储卷(与沉淀库同构),不支持多分柜创建、切换或删除',
390
+ }
391
+ }
392
+ const rootSid = cleanRootSessionId(payload.rootSessionId || payload.session || opts.rootSessionId)
393
+ const resolvedInit = ensureProjectCabinet({
394
+ ...opts,
395
+ cwd: str(payload.cwd, opts.cwd),
396
+ projectKey: str(payload.projectKey, opts.projectKey),
397
+ rootSessionId: rootSid,
398
+ vaultScope,
399
+ })
400
+ const regFile = cabinetRegistryPath(opts.customSharedBoardFile)
401
+ const projectKey = resolvedInit.projectKey
402
+ const sessKey = normalizeSessionScopeKey(rootSid)
403
+
404
+ if (op === 'listCabinets') {
405
+ return listProjectCabinets({ ...opts, projectKey, rootSessionId: rootSid, vaultScope })
406
+ }
407
+
408
+ if (resolvedInit.unboundSession || !sessKey) {
409
+ return {
410
+ ok: false,
411
+ unboundSession: true,
412
+ error: '当前为空白新对话(尚未绑定会话 ID),请先在主会话发送一条消息,或切换到「🌐 全局档案柜」',
413
+ }
414
+ }
415
+
416
+ const release = acquireFileLock(regFile)
417
+ try {
418
+ const reg = normalizeRegistry(readJsonSafe(regFile, null))
419
+ if (!reg.sessions[sessKey]) reg.sessions[sessKey] = resolvedInit.projectEntry
420
+ const container = reg.sessions[sessKey]
421
+ const scopeMeta = { scope: 'session', vaultScope: 'session', rootSessionId: rootSid }
422
+
423
+ if (op === 'createCabinet') {
424
+ const name = clamp(payload.name || payload.label || `工作档案柜 ${container.cabinets.length + 1}`, 40)
425
+ const dup = container.cabinets.find(c => c.name === name)
426
+ if (dup) {
427
+ container.activeCabinetId = dup.id
428
+ writeRegistryRaw(regFile, reg)
429
+ invalidateArchiveCache()
430
+ return {
431
+ ok: true,
432
+ ...scopeMeta,
433
+ cabinet: dup,
434
+ activeCabinetId: container.activeCabinetId,
435
+ cabinets: container.cabinets,
436
+ projectKey,
437
+ }
438
+ }
439
+ const id = nextId('cab')
440
+ const now = Date.now()
441
+ const cabMeta = {
442
+ id,
443
+ name,
444
+ projectKey,
445
+ ...(rootSid && sessKey ? { rootSessionId: rootSid } : {}),
446
+ cwd: container.cwd || str(payload.cwd, opts.cwd),
447
+ createdAt: now,
448
+ updatedAt: now,
449
+ }
450
+ const cabFile = cabinetFilePath(id, opts.customSharedBoardFile)
451
+ atomicWriteJson(cabFile, normalizeArchiveStore({
452
+ cabinetId: id,
453
+ cabinetName: name,
454
+ projectKey,
455
+ }))
456
+ container.cabinets.push(cabMeta)
457
+ container.activeCabinetId = id
458
+ writeRegistryRaw(regFile, reg)
459
+ invalidateArchiveCache()
460
+ return {
461
+ ok: true,
462
+ ...scopeMeta,
463
+ cabinet: cabMeta,
464
+ activeCabinetId: container.activeCabinetId,
465
+ cabinets: container.cabinets,
466
+ projectKey,
467
+ }
468
+ }
469
+
470
+ if (op === 'switchCabinet') {
471
+ const targetId = str(payload.cabinetId || payload.id, '').trim()
472
+ const hit = container.cabinets.find(c => c.id === targetId)
473
+ if (!hit) return { ok: false, error: '当前范围下未找到目标档案柜:' + targetId }
474
+ container.activeCabinetId = hit.id
475
+ hit.updatedAt = Date.now()
476
+ writeRegistryRaw(regFile, reg)
477
+ invalidateArchiveCache()
478
+ return {
479
+ ok: true,
480
+ ...scopeMeta,
481
+ cabinet: hit,
482
+ activeCabinetId: container.activeCabinetId,
483
+ cabinets: container.cabinets,
484
+ projectKey,
485
+ }
486
+ }
487
+
488
+ if (op === 'renameCabinet') {
489
+ const targetId = str(payload.cabinetId || payload.id, container.activeCabinetId).trim()
490
+ const name = clamp(payload.name || payload.label, 40)
491
+ if (!name) return { ok: false, error: '请输入档案柜新名称' }
492
+ const hit = container.cabinets.find(c => c.id === targetId)
493
+ if (!hit) return { ok: false, error: '未找到档案柜:' + targetId }
494
+ hit.name = name
495
+ hit.updatedAt = Date.now()
496
+ writeRegistryRaw(regFile, reg)
497
+ const cabFile = cabinetFilePath(hit.id, opts.customSharedBoardFile)
498
+ const cabStore = normalizeArchiveStore(readJsonSafe(cabFile, { cabinetId: hit.id, projectKey }))
499
+ cabStore.cabinetName = name
500
+ atomicWriteJson(cabFile, cabStore)
501
+ invalidateArchiveCache()
502
+ return {
503
+ ok: true,
504
+ ...scopeMeta,
505
+ cabinet: hit,
506
+ activeCabinetId: container.activeCabinetId,
507
+ cabinets: container.cabinets,
508
+ projectKey,
509
+ }
510
+ }
511
+
512
+ if (op === 'deleteCabinet') {
513
+ const targetId = str(payload.cabinetId || payload.id, '').trim()
514
+ if (container.cabinets.length <= 1) {
515
+ return { ok: false, error: '每个范围至少需保留一个工作档案柜,不可删除最后一个档案柜' }
516
+ }
517
+ const idx = container.cabinets.findIndex(c => c.id === targetId)
518
+ if (idx < 0) return { ok: false, error: '未找到要删除的档案柜:' + targetId }
519
+ const [removed] = container.cabinets.splice(idx, 1)
520
+ if (container.activeCabinetId === removed.id) {
521
+ container.activeCabinetId = container.cabinets[0].id
522
+ }
523
+ writeRegistryRaw(regFile, reg)
524
+ try {
525
+ const rmFile = cabinetFilePath(removed.id, opts.customSharedBoardFile)
526
+ if (fs.existsSync(rmFile)) fs.unlinkSync(rmFile)
527
+ } catch {}
528
+ invalidateArchiveCache()
529
+ return {
530
+ ok: true,
531
+ ...scopeMeta,
532
+ removedId: removed.id,
533
+ activeCabinetId: container.activeCabinetId,
534
+ cabinets: container.cabinets,
535
+ projectKey,
536
+ }
537
+ }
538
+
539
+ return { ok: false, error: '未知的档案柜操作:' + op }
540
+ } finally {
541
+ release()
542
+ }
543
+ }
544
+
545
+ export function bootstrapArchivesFromSharedBoard({ sharedFile, loadBoard, saveBoard, pushLog }) {
546
+ try {
547
+ if (!sharedFile || !fs.existsSync(sharedFile)) return { migrated: 0 }
548
+ // Ensure legacy `archives.json` & old board.notes migrate once into Global Cabinet (not into every blank chat!)
549
+ const globalTarget = { customSharedBoardFile: sharedFile, vaultScope: 'global' }
550
+ const resolved = ensureProjectCabinet(globalTarget)
551
+ const storeTarget = { customSharedBoardFile: sharedFile, vaultScope: 'global', cabinetId: resolved.cabinetId }
552
+ const existing = loadArchiveStore(storeTarget)
553
+ if (existing.migratedSharedAt > 0 && existing.items.length > 0) {
554
+ return { migrated: 0 }
555
+ }
556
+
557
+ const sharedBoard = loadBoard(sharedFile)
558
+ const legacyNotes = Array.isArray(sharedBoard && sharedBoard.notes) ? sharedBoard.notes : []
559
+ if (!legacyNotes.length) {
560
+ if (!existing.migratedSharedAt) {
561
+ withArchiveLock(storeTarget, () => {
562
+ const empty = loadArchiveStore(storeTarget)
563
+ empty.migratedSharedAt = Date.now()
564
+ saveArchiveStore(empty, storeTarget)
565
+ })
566
+ }
567
+ return { migrated: 0 }
568
+ }
569
+
570
+ const backupFile = path.join(path.dirname(sharedFile), 'board.pre-archive-backup.json')
571
+ try {
572
+ if (!fs.existsSync(backupFile)) {
573
+ fs.copyFileSync(sharedFile, backupFile)
574
+ }
575
+ } catch {}
576
+
577
+ let migratedCount = 0
578
+ withArchiveLock(storeTarget, () => {
579
+ const store = loadArchiveStore(storeTarget)
580
+ const existingSourceIds = new Set(store.items.map(it => it.sourceNoteId).filter(Boolean))
581
+ const existingTitles = new Set(store.items.map(it => it.title))
582
+
583
+ for (const note of legacyNotes) {
584
+ if (!note || (!note.title && !note.body)) continue
585
+ if (SECRET_PATTERN.test(String(note.body || ''))) continue
586
+ if ((note.id && existingSourceIds.has(note.id)) || (note.title && existingTitles.has(note.title))) {
587
+ continue
588
+ }
589
+ const parsed = smartParseNoteToDossier(note)
590
+ const item = normalizeArchiveItem({
591
+ id: nextId('arch'),
592
+ sourceNoteId: note.id || '',
593
+ title: parsed.title,
594
+ summary: parsed.summary,
595
+ folder: parsed.folder,
596
+ paperclip: parsed.paperclip,
597
+ tags: note.tags || [],
598
+ cold: true,
599
+ takenOutSessions: [],
600
+ organizedBy: 'auto',
601
+ points: parsed.points,
602
+ body: note.body || '',
603
+ by: note.by || 'agent',
604
+ sourceSession: note.session || '',
605
+ createdAt: note.createdAt || note.updatedAt || Date.now(),
606
+ updatedAt: note.updatedAt || Date.now(),
607
+ })
608
+ if (item) {
609
+ store.items.push(item)
610
+ migratedCount += 1
611
+ }
612
+ }
613
+
614
+ store.migratedSharedAt = Date.now()
615
+ saveArchiveStore(store, storeTarget)
616
+ })
617
+
618
+ if (migratedCount > 0 && typeof saveBoard === 'function') {
619
+ sharedBoard.notes = []
620
+ if (typeof pushLog === 'function') {
621
+ pushLog(
622
+ sharedBoard,
623
+ `🗄️ 已将 ${migratedCount} 篇历史工程笔记无损沉淀入「全局档案柜」(默认封存懒加载,不再每轮挤占上下文)`,
624
+ 'system',
625
+ '',
626
+ )
627
+ }
628
+ saveBoard(sharedBoard, sharedFile)
629
+ }
630
+
631
+ return { migrated: migratedCount }
632
+ } catch {
633
+ return { migrated: 0 }
634
+ }
635
+ }
636
+
637
+ /* ------------------------------------------- Lazy-Loading Query & Mutations */
638
+
639
+ /**
640
+ * Loads the standalone System Global Cold Vault (`global-vault/vault-chief-global.json`).
641
+ * Structurally peers with `precipitated/vault-global.json`: NEVER shares files with `cabinets/`,
642
+ * NEVER auto-follows conversation context (0 Token unless explicitly mounted or Chief-searched).
643
+ */
644
+ export function loadGlobalVaultRaw(targetOpt) {
645
+ const file = globalChiefVaultFilePath(targetOpt)
646
+ if (!fs.existsSync(file)) {
647
+ return normalizeArchiveStore({
648
+ isSystemGlobalVault: true,
649
+ projectKey: 'global',
650
+ updatedAt: 0,
651
+ items: [],
652
+ })
653
+ }
654
+ const parsed = readJsonSafe(file, null)
655
+ return normalizeArchiveStore({
656
+ ...(parsed && typeof parsed === 'object' ? parsed : {}),
657
+ isSystemGlobalVault: true,
658
+ projectKey: 'global',
659
+ })
660
+ }
661
+
662
+ export function saveGlobalVaultRaw(store, targetOpt) {
663
+ const file = globalChiefVaultFilePath(targetOpt)
664
+ const normalized = normalizeArchiveStore({
665
+ ...(store && typeof store === 'object' ? store : {}),
666
+ isSystemGlobalVault: true,
667
+ projectKey: 'global',
668
+ updatedAt: Date.now(),
669
+ })
670
+ atomicWriteJson(file, normalized)
671
+ return normalized
672
+ }
673
+
674
+ export function loadArchiveStore(targetOpt) {
675
+ const resolved = ensureProjectCabinet(targetOpt)
676
+ if (resolved.vaultScope === 'global') {
677
+ return loadGlobalVaultRaw(targetOpt)
678
+ }
679
+ if (resolved.unboundSession || !resolved.cabinetFile) {
680
+ return {
681
+ ...normalizeArchiveStore({
682
+ cabinetId: '',
683
+ cabinetName: resolved.cabinetName || '本会话尚未开始(空白新对话)',
684
+ projectKey: resolved.projectKey,
685
+ }),
686
+ unboundSession: true,
687
+ }
688
+ }
689
+ const file = resolved.cabinetFile
690
+ try {
691
+ const st = fs.statSync(file)
692
+ const cached = getCachedArchiveStore(file, st.mtimeMs)
693
+ if (cached) return cached
694
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
695
+ const store = normalizeArchiveStore({
696
+ ...parsed,
697
+ cabinetId: resolved.cabinetId,
698
+ cabinetName: resolved.cabinetName,
699
+ projectKey: resolved.projectKey,
700
+ })
701
+ setCachedArchiveStore(file, st.mtimeMs, store)
702
+ return store
703
+ } catch {
704
+ return normalizeArchiveStore({
705
+ cabinetId: resolved.cabinetId,
706
+ cabinetName: resolved.cabinetName,
707
+ projectKey: resolved.projectKey,
708
+ })
709
+ }
710
+ }
711
+
712
+ export function saveArchiveStore(store, targetOpt) {
713
+ const resolved = ensureProjectCabinet(targetOpt)
714
+ if (resolved.vaultScope === 'global') {
715
+ return saveGlobalVaultRaw(store, targetOpt)
716
+ }
717
+ if (resolved.unboundSession || !resolved.cabinetFile) {
718
+ throw new Error('当前未绑定具体对话(空白新对话),不能写入本会话档案柜')
719
+ }
720
+ const file = resolved.cabinetFile
721
+ const normalized = normalizeArchiveStore({
722
+ ...store,
723
+ cabinetId: resolved.cabinetId,
724
+ cabinetName: resolved.cabinetName,
725
+ projectKey: resolved.projectKey,
726
+ updatedAt: Date.now(),
727
+ })
728
+ atomicWriteJson(file, normalized)
729
+ let mtime = Date.now()
730
+ try {
731
+ mtime = fs.statSync(file).mtimeMs
732
+ } catch {}
733
+ setCachedArchiveStore(file, mtime, normalized)
734
+ return normalized
735
+ }
736
+
737
+ export function withArchiveLock(targetOpt, fn) {
738
+ const resolved = ensureProjectCabinet(targetOpt)
739
+ if (resolved.vaultScope === 'global') {
740
+ const file = globalChiefVaultFilePath(targetOpt)
741
+ const release = acquireFileLock(file)
742
+ invalidateArchiveCache()
743
+ try {
744
+ return fn(file, resolved)
745
+ } finally {
746
+ release()
747
+ }
748
+ }
749
+ if (resolved.unboundSession || !resolved.cabinetFile) {
750
+ return {
751
+ ok: false,
752
+ unboundSession: true,
753
+ error: '当前为空白新对话(尚未绑定会话 ID),请先在主会话发送一条消息,或切换到「🌐 全局档案柜」',
754
+ }
755
+ }
756
+ const file = resolved.cabinetFile
757
+ const release = acquireFileLock(file)
758
+ invalidateArchiveCache()
759
+ try {
760
+ return fn(file, resolved)
761
+ } finally {
762
+ release()
763
+ }
764
+ }
765
+
766
+ /* ------------------------------------------- Smart Note -> Dossier Parser */