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,1185 @@
1
+ /**
2
+ * archive-dossiers.js
3
+ *
4
+ * Working dossier CRUD, session/global diffing, search, AI curations, and cross-session copy.
5
+ */
6
+
7
+ import fs from 'node:fs'
8
+ import {
9
+ POINTS_CAP,
10
+ SECRET_PATTERN,
11
+ DEFAULT_ARCHIVE_FOLDERS,
12
+ nextId,
13
+ str,
14
+ clamp,
15
+ cleanMultiline,
16
+ normalizeVaultScope,
17
+ cleanRootSessionId,
18
+ resolveTargetOpts,
19
+ withRootScope,
20
+ globalChiefVaultFilePath,
21
+ normalizeArchiveTitleKey,
22
+ computeEntryContentHash,
23
+ normalizeFolder,
24
+ normalizePoint,
25
+ normalizeTags,
26
+ normalizeArchiveItem,
27
+ normalizeGlobalVaultEntry,
28
+ firstMeaningfulSentence,
29
+ extractStructuredPoints,
30
+ smartParseNoteToDossier,
31
+ registerArchiveMutatorHook,
32
+ } from './archive-core.js'
33
+ import {
34
+ ensureProjectCabinet,
35
+ listProjectCabinets,
36
+ loadGlobalVaultRaw,
37
+ saveGlobalVaultRaw,
38
+ loadArchiveStore,
39
+ saveArchiveStore,
40
+ withArchiveLock,
41
+ mutateCabinetRegistry,
42
+ } from './archive-cabinets.js'
43
+ import { hasAnyPrecipitatedFilesOnDisk, loadPrecipitatedStoreRaw, listPrecipitatedHeaders } from './archive-precipitated.js'
44
+
45
+ /**
46
+ * 0-Token Guard for System Global Vault:
47
+ * Returns ONLY entries the User explicitly mounted for Chief in THIS conversation (`chiefMountedSessions`).
48
+ * By default returns `[]` without reading or leaking anything into conversation context.
49
+ */
50
+ export function getChiefMountedGlobalForSession(rootSessionId = '', targetOpt) {
51
+ const sid = cleanRootSessionId(rootSessionId)
52
+ if (!sid) return []
53
+ const file = globalChiefVaultFilePath(targetOpt)
54
+ if (!fs.existsSync(file)) return []
55
+ const store = loadGlobalVaultRaw(targetOpt)
56
+ return store.items.filter(it => Array.isArray(it.chiefMountedSessions) && it.chiefMountedSessions.includes(sid))
57
+ }
58
+
59
+ /**
60
+ * Returns ONLY System Global Vault entries explicitly placed onto THIS session's desk (`takenOutSessions`),
61
+ * so both Lead & Chief emphasize them in prompt context while sealed global entries stay hidden from Lead.
62
+ */
63
+ export function getTakenOutGlobalForSession(rootSessionId = '', targetOpt) {
64
+ const sid = cleanRootSessionId(rootSessionId)
65
+ if (!sid) return []
66
+ const file = globalChiefVaultFilePath(targetOpt)
67
+ if (!fs.existsSync(file)) return []
68
+ const store = loadGlobalVaultRaw(targetOpt)
69
+ return store.items.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid))
70
+ }
71
+
72
+ /**
73
+ * Computes bidirectional diff between the active conversation's Local Session Cabinet and the System Global Vault.
74
+ */
75
+ export function computeSessionGlobalDiff(sessionItems = [], globalItems = [], rootSessionId = '') {
76
+ const sid = cleanRootSessionId(rootSessionId)
77
+ const sArr = Array.isArray(sessionItems) ? sessionItems : []
78
+ const gArr = Array.isArray(globalItems) ? globalItems : []
79
+
80
+ const gById = new Map()
81
+ const gByOriginId = new Map()
82
+ const gByTitle = new Map()
83
+ for (const g of gArr) {
84
+ if (!g) continue
85
+ gById.set(g.id, g)
86
+ if (g.originId) gByOriginId.set(g.originId, g)
87
+ const tk = normalizeArchiveTitleKey(g.title)
88
+ if (tk && !gByTitle.has(tk)) gByTitle.set(tk, g)
89
+ }
90
+
91
+ const sById = new Map()
92
+ const sByOriginGlobal = new Map()
93
+ const sByTitle = new Map()
94
+ for (const s of sArr) {
95
+ if (!s) continue
96
+ sById.set(s.id, s)
97
+ if (s.originGlobalId) sByOriginGlobal.set(s.originGlobalId, s)
98
+ const tk = normalizeArchiveTitleKey(s.title)
99
+ if (tk && !sByTitle.has(tk)) sByTitle.set(tk, s)
100
+ }
101
+
102
+ const sessionDiffMap = new Map()
103
+ const globalDiffMap = new Map()
104
+ let localOnlyCount = 0
105
+ let globalOnlyCount = 0
106
+ let syncedCount = 0
107
+ let modifiedCount = 0
108
+ const localOnlyBriefs = []
109
+
110
+ if (sid) {
111
+ for (const s of sArr) {
112
+ if (!s) continue
113
+ const gMatch = (s.originGlobalId && gById.get(s.originGlobalId))
114
+ || gByOriginId.get(s.id)
115
+ || gByTitle.get(normalizeArchiveTitleKey(s.title))
116
+ || null
117
+ if (!gMatch) {
118
+ localOnlyCount += 1
119
+ sessionDiffMap.set(s.id, { diffStatus: 'local_only', matchedGlobalId: '' })
120
+ if (localOnlyBriefs.length < 25) {
121
+ localOnlyBriefs.push({
122
+ id: s.id,
123
+ title: s.title,
124
+ summary: s.summary,
125
+ folder: s.folder,
126
+ paperclip: s.paperclip,
127
+ diffStatus: 'local_only',
128
+ updatedAt: s.updatedAt,
129
+ })
130
+ }
131
+ } else {
132
+ const sHash = computeEntryContentHash(s)
133
+ const gHash = computeEntryContentHash(gMatch)
134
+ if (sHash === gHash) {
135
+ syncedCount += 1
136
+ sessionDiffMap.set(s.id, { diffStatus: 'synced', matchedGlobalId: gMatch.id })
137
+ } else {
138
+ modifiedCount += 1
139
+ sessionDiffMap.set(s.id, { diffStatus: 'local_modified', matchedGlobalId: gMatch.id })
140
+ if (localOnlyBriefs.length < 25) {
141
+ localOnlyBriefs.push({
142
+ id: s.id,
143
+ title: s.title,
144
+ summary: s.summary,
145
+ folder: s.folder,
146
+ paperclip: s.paperclip,
147
+ diffStatus: 'local_modified',
148
+ matchedGlobalId: gMatch.id,
149
+ updatedAt: s.updatedAt,
150
+ })
151
+ }
152
+ }
153
+ }
154
+ }
155
+ }
156
+
157
+ for (const g of gArr) {
158
+ if (!g) continue
159
+ if (!sid) {
160
+ globalDiffMap.set(g.id, { diffStatus: 'unbound', matchedSessionItemId: '' })
161
+ continue
162
+ }
163
+ const sMatch = sByOriginGlobal.get(g.id)
164
+ || (g.originId ? sById.get(g.originId) : null)
165
+ || sByTitle.get(normalizeArchiveTitleKey(g.title))
166
+ || null
167
+ if (!sMatch) {
168
+ globalOnlyCount += 1
169
+ globalDiffMap.set(g.id, { diffStatus: 'global_only', matchedSessionItemId: '' })
170
+ } else {
171
+ const sHash = computeEntryContentHash(sMatch)
172
+ const gHash = computeEntryContentHash(g)
173
+ globalDiffMap.set(g.id, {
174
+ diffStatus: sHash === gHash ? 'synced' : 'differs',
175
+ matchedSessionItemId: sMatch.id,
176
+ })
177
+ }
178
+ }
179
+
180
+ return {
181
+ sessionDiffMap,
182
+ globalDiffMap,
183
+ summary: {
184
+ unboundSession: !sid,
185
+ sessionTotal: sid ? sArr.length : 0,
186
+ globalTotal: gArr.length,
187
+ localOnlyCount,
188
+ globalOnlyCount: sid ? globalOnlyCount : gArr.length,
189
+ syncedCount,
190
+ modifiedCount,
191
+ localOnlyBriefs,
192
+ },
193
+ }
194
+ }
195
+
196
+ /** Ultra-lightweight metadata (<160 bytes) for `/snapshot` polling — ZERO archive text or precipitated reads! */
197
+ export function getArchiveMeta(rootSessionId = '', targetOpt) {
198
+ const effectiveTarget = withRootScope(targetOpt, rootSessionId)
199
+ const cabInfo = listProjectCabinets(effectiveTarget)
200
+ const store = loadArchiveStore(effectiveTarget)
201
+ const sid = cleanRootSessionId(rootSessionId)
202
+ const nonEmptyFolders = new Set(store.items.map(it => it.folder).filter(Boolean))
203
+ const takenOutCount = (sid && cabInfo.vaultScope !== 'global' && !cabInfo.unboundSession)
204
+ ? store.items.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid)).length
205
+ : 0
206
+ return {
207
+ totalCount: store.items.length,
208
+ folderCount: nonEmptyFolders.size || DEFAULT_ARCHIVE_FOLDERS.length,
209
+ takenOutCount,
210
+ unorganizedCount: store.items.filter(it => it.folder === 'inbox' || it.organizedBy === 'auto').length,
211
+ scope: cabInfo.vaultScope || cabInfo.scope || 'session',
212
+ vaultScope: cabInfo.vaultScope || cabInfo.scope || 'session',
213
+ isSystemGlobalVault: Boolean(cabInfo.isSystemGlobalVault),
214
+ unboundSession: Boolean(cabInfo.unboundSession),
215
+ projectKey: cabInfo.projectKey,
216
+ activeCabinetId: cabInfo.activeCabinetId,
217
+ cabinetCount: cabInfo.cabinets.length,
218
+ }
219
+ }
220
+
221
+ /** Counts across all 3 tiers (`session`, `global`, `precipitated`) for UI tabs & `/snapshot`. */
222
+ export function getThreeTierArchiveCounts(rootSessionId = '', flippedIds = [], targetOpt) {
223
+ const sid = cleanRootSessionId(rootSessionId)
224
+ const base = resolveTargetOpts(targetOpt)
225
+ const sessionStore = sid
226
+ ? loadArchiveStore({ customSharedBoardFile: base.customSharedBoardFile, cwd: base.cwd, projectKey: base.projectKey, rootSessionId: sid, vaultScope: 'session' })
227
+ : { items: [], unboundSession: true }
228
+ const globalStore = loadGlobalVaultRaw(base)
229
+ let precipitatedCount = 0
230
+ let flippedCount = Array.isArray(flippedIds) ? flippedIds.length : 0
231
+ if (hasAnyPrecipitatedFilesOnDisk(base)) {
232
+ const pStore = loadPrecipitatedStoreRaw(base.projectKey || 'proj-default', base)
233
+ precipitatedCount = pStore.items.length
234
+ if (sid) {
235
+ flippedCount = pStore.items.filter(it => Array.isArray(it.flippedOutSessions) && it.flippedOutSessions.includes(sid)).length
236
+ }
237
+ }
238
+ const globalMountedCount = sid
239
+ ? globalStore.items.filter(it => Array.isArray(it.chiefMountedSessions) && it.chiefMountedSessions.includes(sid)).length
240
+ : 0
241
+ const globalTakenOutCount = sid
242
+ ? globalStore.items.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid)).length
243
+ : 0
244
+ return {
245
+ sessionCount: Array.isArray(sessionStore.items) ? sessionStore.items.length : 0,
246
+ globalCount: Array.isArray(globalStore.items) ? globalStore.items.length : 0,
247
+ globalMountedCount,
248
+ globalTakenOutCount,
249
+ precipitatedCount,
250
+ flippedCount,
251
+ unboundSession: !sid,
252
+ }
253
+ }
254
+
255
+ /**
256
+ * Tier-1 Lazy Load (`GET /api/dsh-chief/archives`):
257
+ * - `scope === 'global'`: reads standalone System Global Cold Vault (`global-vault/vault-chief-global.json`),
258
+ * computes live diff against current conversation's Session Cabinet (when bound), and returns `isSystemGlobalVault: true`.
259
+ * - `scope === 'session'`: reads ONLY this root conversation's Local Session Cabinet (strictly isolated 1:1),
260
+ * computes diff against System Global Vault so each card knows whether it is local_only / synced / local_modified.
261
+ */
262
+ export function listArchiveHeaders(rootSessionId = '', opts = {}, targetOpt) {
263
+ const sid = cleanRootSessionId(rootSessionId || (opts && (opts.rootSessionId || opts.sessionId)))
264
+ const requestedScope = normalizeVaultScope((opts && (opts.vaultScope || opts.scope)) || (targetOpt && typeof targetOpt === 'object' && (targetOpt.vaultScope || targetOpt.scope)))
265
+ const baseTarget = targetOpt !== undefined
266
+ ? (typeof targetOpt === 'string'
267
+ ? { customSharedBoardFile: targetOpt, cwd: opts && opts.cwd, projectKey: opts && opts.projectKey, cabinetId: opts && opts.cabinetId, vaultScope: requestedScope }
268
+ : { ...opts, ...targetOpt, vaultScope: requestedScope })
269
+ : { ...(opts || {}), vaultScope: requestedScope }
270
+ const target = withRootScope(baseTarget, sid)
271
+ const isGlobalReq = requestedScope === 'global'
272
+ const cabInfo = listProjectCabinets(target)
273
+ const store = isGlobalReq ? loadGlobalVaultRaw(baseTarget) : loadArchiveStore(target)
274
+ const globalVault = isGlobalReq ? store : loadGlobalVaultRaw(baseTarget)
275
+ const sessionStore = isGlobalReq
276
+ ? (sid ? loadArchiveStore({ customSharedBoardFile: baseTarget.customSharedBoardFile, cwd: baseTarget.cwd, projectKey: baseTarget.projectKey, rootSessionId: sid, vaultScope: 'session' }) : { items: [], unboundSession: true })
277
+ : store
278
+ const diff = computeSessionGlobalDiff(
279
+ sessionStore && !sessionStore.unboundSession ? sessionStore.items : [],
280
+ globalVault.items,
281
+ sid,
282
+ )
283
+
284
+ const needle = String((opts && opts.query) || '').trim().toLowerCase()
285
+ const folderFilter = String((opts && opts.folder) || '').trim()
286
+ const clipFilter = String((opts && opts.paperclip) || '').trim()
287
+
288
+ const clipRank = { gold: 0, silver: 1, copper: 2 }
289
+ const sorted = store.items.slice().sort((a, b) => {
290
+ const aPinned = isGlobalReq
291
+ ? (sid && Array.isArray(a.chiefMountedSessions) && a.chiefMountedSessions.includes(sid) ? 0 : 1)
292
+ : (sid && Array.isArray(a.takenOutSessions) && a.takenOutSessions.includes(sid) ? 0 : 1)
293
+ const bPinned = isGlobalReq
294
+ ? (sid && Array.isArray(b.chiefMountedSessions) && b.chiefMountedSessions.includes(sid) ? 0 : 1)
295
+ : (sid && Array.isArray(b.takenOutSessions) && b.takenOutSessions.includes(sid) ? 0 : 1)
296
+ if (aPinned !== bPinned) return aPinned - bPinned
297
+ const cDiff = (clipRank[a.paperclip] ?? 1) - (clipRank[b.paperclip] ?? 1)
298
+ if (cDiff !== 0) return cDiff
299
+ return (b.updatedAt || 0) - (a.updatedAt || 0)
300
+ })
301
+
302
+ const filtered = sorted.filter((it) => {
303
+ if (folderFilter && it.folder !== folderFilter) return false
304
+ if (clipFilter && it.paperclip !== clipFilter) return false
305
+ if (!needle) return true
306
+ const hay = [
307
+ it.title,
308
+ it.summary,
309
+ (it.tags || []).join(' '),
310
+ ...(it.points || []).map(p => `${p.title} ${p.cue}`),
311
+ it.body,
312
+ ].join('\n').toLowerCase()
313
+ return hay.includes(needle)
314
+ })
315
+
316
+ const countsByFolder = {}
317
+ const goldByFolder = {}
318
+ for (const it of store.items) {
319
+ countsByFolder[it.folder] = (countsByFolder[it.folder] || 0) + 1
320
+ if (it.paperclip === 'gold') {
321
+ goldByFolder[it.folder] = (goldByFolder[it.folder] || 0) + 1
322
+ }
323
+ }
324
+
325
+ const folders = store.folders.map(f => ({
326
+ ...f,
327
+ count: countsByFolder[f.id] || 0,
328
+ goldCount: goldByFolder[f.id] || 0,
329
+ }))
330
+
331
+ const headers = filtered.map((it) => {
332
+ const diffEntry = (isGlobalReq ? diff.globalDiffMap.get(it.id) : diff.sessionDiffMap.get(it.id)) || {}
333
+ return {
334
+ id: it.id,
335
+ originId: it.originId || '',
336
+ originGlobalId: it.originGlobalId || '',
337
+ title: it.title,
338
+ summary: it.summary,
339
+ folder: it.folder,
340
+ paperclip: it.paperclip,
341
+ tags: it.tags,
342
+ cold: true,
343
+ takenOut: Boolean(sid && Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid)),
344
+ chiefMounted: Boolean(isGlobalReq && sid && Array.isArray(it.chiefMountedSessions) && it.chiefMountedSessions.includes(sid)),
345
+ diffStatus: diffEntry.diffStatus || (isGlobalReq ? (sid ? 'global_only' : 'unbound') : 'local_only'),
346
+ matchedGlobalId: !isGlobalReq ? (diffEntry.matchedGlobalId || '') : '',
347
+ matchedSessionItemId: isGlobalReq ? (diffEntry.matchedSessionItemId || '') : '',
348
+ contentHash: it.contentHash || computeEntryContentHash(it),
349
+ organizedBy: it.organizedBy,
350
+ pointCount: Array.isArray(it.points) ? it.points.length : 0,
351
+ pointPreviews: (Array.isArray(it.points) ? it.points : []).slice(0, 4).map(p => p.title),
352
+ bodyLength: (it.body || '').length,
353
+ updatedAt: it.updatedAt,
354
+ createdAt: it.createdAt,
355
+ }
356
+ })
357
+
358
+ const includePrecipitated = Boolean(opts && opts.includePrecipitated)
359
+ const precipitated = includePrecipitated
360
+ ? listPrecipitatedHeaders(cabInfo.projectKey, sid, target)
361
+ : undefined
362
+ const counts = (opts && opts.includeCounts !== false)
363
+ ? getThreeTierArchiveCounts(sid, (opts && opts.flippedIds) || [], baseTarget)
364
+ : undefined
365
+
366
+ return {
367
+ ok: true,
368
+ scope: isGlobalReq ? 'global' : (cabInfo.vaultScope || cabInfo.scope || 'session'),
369
+ vaultScope: isGlobalReq ? 'global' : (cabInfo.vaultScope || cabInfo.scope || 'session'),
370
+ isSystemGlobalVault: isGlobalReq,
371
+ unboundSession: isGlobalReq ? false : Boolean(cabInfo.unboundSession),
372
+ rootSessionId: sid,
373
+ projectKey: isGlobalReq ? 'global' : cabInfo.projectKey,
374
+ activeCabinetId: isGlobalReq ? '' : cabInfo.activeCabinetId,
375
+ cabinets: isGlobalReq ? [] : cabInfo.cabinets,
376
+ totalCount: store.items.length,
377
+ takenOutCount: sid
378
+ ? store.items.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid)).length
379
+ : 0,
380
+ diffSummary: diff.summary,
381
+ folders,
382
+ items: headers,
383
+ ...(precipitated !== undefined ? { precipitated } : {}),
384
+ ...(counts !== undefined ? { counts } : {}),
385
+ }
386
+ }
387
+
388
+ export function getArchiveDetail(idOrTitle = '', rootSessionId = '', targetOpt) {
389
+ const target = String(idOrTitle || '').trim()
390
+ if (!target) return { ok: false, error: 'archive id or title required' }
391
+ const sid = cleanRootSessionId(rootSessionId)
392
+ const base = resolveTargetOpts(targetOpt)
393
+ const isGlobal = base.vaultScope === 'global'
394
+ const resolved = ensureProjectCabinet(withRootScope(targetOpt, sid))
395
+ if (!isGlobal && resolved.unboundSession) {
396
+ return { ok: false, error: '当前为空白新对话,尚未建立本会话档案柜' }
397
+ }
398
+ const store = isGlobal ? loadGlobalVaultRaw(targetOpt) : loadArchiveStore(withRootScope(targetOpt, sid))
399
+ const hit = store.items.find(it => it.id === target)
400
+ || store.items.find(it => it.title === target)
401
+ || store.items.find(it => it.title.toLowerCase().includes(target.toLowerCase()))
402
+ if (!hit) return { ok: false, error: '未找到工程档案:' + target }
403
+
404
+ return {
405
+ ok: true,
406
+ vaultScope: isGlobal ? 'global' : (resolved.vaultScope || 'session'),
407
+ isSystemGlobalVault: isGlobal,
408
+ item: {
409
+ id: hit.id,
410
+ originId: hit.originId || '',
411
+ originGlobalId: hit.originGlobalId || '',
412
+ title: hit.title,
413
+ summary: hit.summary,
414
+ folder: hit.folder,
415
+ paperclip: hit.paperclip,
416
+ tags: hit.tags,
417
+ cold: hit.cold,
418
+ takenOut: Boolean(sid && Array.isArray(hit.takenOutSessions) && hit.takenOutSessions.includes(sid)),
419
+ chiefMounted: Boolean(isGlobal && sid && Array.isArray(hit.chiefMountedSessions) && hit.chiefMountedSessions.includes(sid)),
420
+ organizedBy: hit.organizedBy,
421
+ points: hit.points,
422
+ body: hit.body,
423
+ contentHash: hit.contentHash || computeEntryContentHash(hit),
424
+ by: hit.by,
425
+ createdAt: hit.createdAt,
426
+ updatedAt: hit.updatedAt,
427
+ },
428
+ }
429
+ }
430
+
431
+ /**
432
+ * Strictly returns ONLY dossiers explicitly taken out onto the current session desk
433
+ * FROM THIS CONVERSATION'S SESSION CABINET. NEVER reads Global Cabinet or `precipitated`!
434
+ */
435
+ export function getTakenOutArchivesForSession(rootSessionId = '', targetOpt) {
436
+ const sid = cleanRootSessionId(rootSessionId)
437
+ if (!sid) return []
438
+ const base = resolveTargetOpts(targetOpt)
439
+ const store = loadArchiveStore({
440
+ customSharedBoardFile: base.customSharedBoardFile,
441
+ cwd: base.cwd,
442
+ projectKey: base.projectKey,
443
+ cabinetId: base.cabinetId,
444
+ rootSessionId: sid,
445
+ vaultScope: 'session',
446
+ })
447
+ if (store.unboundSession) return []
448
+ return store.items.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid))
449
+ }
450
+
451
+ function scoreAndRankArchiveItems(store, query = '', opts = {}) {
452
+ const folder = String((opts && opts.folder) || '').trim()
453
+ const limit = Math.max(1, Math.min(Number(opts && opts.limit) || 8, 25))
454
+ const rawQ = String(query || '').trim().toLowerCase()
455
+ const terms = rawQ
456
+ .replace(/[??!!。,,、::“”"'()()[\]【】]/g, ' ')
457
+ .split(/\s+/)
458
+ .filter(Boolean)
459
+
460
+ const scored = []
461
+ for (const it of (store && Array.isArray(store.items) ? store.items : [])) {
462
+ if (folder && it.folder !== folder) continue
463
+ if (!terms.length) {
464
+ scored.push({ score: it.paperclip === 'gold' ? 5 : 2, it })
465
+ continue
466
+ }
467
+ const titleLow = it.title.toLowerCase()
468
+ const sumLow = it.summary.toLowerCase()
469
+ const tagLow = (it.tags || []).join(' ').toLowerCase()
470
+ const ptsLow = (it.points || []).map(p => `${p.title} ${p.cue} ${p.detail}`).join('\n').toLowerCase()
471
+ const bodyLow = (it.body || '').toLowerCase()
472
+
473
+ let score = 0
474
+ for (const term of terms) {
475
+ if (titleLow.includes(term)) score += 8
476
+ if (tagLow.includes(term)) score += 5
477
+ if (sumLow.includes(term)) score += 4
478
+ if (ptsLow.includes(term)) score += 3
479
+ else if (bodyLow.includes(term)) score += 2
480
+ }
481
+ if (score > 0) {
482
+ if (it.paperclip === 'gold') score += 1
483
+ scored.push({ score, it })
484
+ }
485
+ }
486
+
487
+ scored.sort((a, b) => b.score - a.score || (b.it.updatedAt || 0) - (a.it.updatedAt || 0))
488
+ const folderLabelMap = new Map((store && Array.isArray(store.folders) ? store.folders : []).map(f => [f.id, f.label]))
489
+
490
+ return {
491
+ totalArchives: store && Array.isArray(store.items) ? store.items.length : 0,
492
+ matchCount: scored.length,
493
+ hits: scored.slice(0, limit).map(({ it }) => ({
494
+ id: it.id,
495
+ title: it.title,
496
+ folder: it.folder,
497
+ folderLabel: folderLabelMap.get(it.folder) || it.folder,
498
+ paperclip: it.paperclip,
499
+ summary: it.summary,
500
+ tags: it.tags,
501
+ points: (it.points || []).map(p => ({ id: p.id, title: p.title, cue: p.cue })),
502
+ updatedAt: it.updatedAt,
503
+ })),
504
+ }
505
+ }
506
+
507
+ /** On-demand search for `chief_board({ action: "archive.search" })` inside THIS conversation's Session Cabinet.
508
+ * Strictly NEVER reads System Global Vault or `precipitated`! */
509
+ export function searchArchives(query = '', opts = {}, targetOpt) {
510
+ const rawTarget = targetOpt !== undefined
511
+ ? (typeof targetOpt === 'string'
512
+ ? { customSharedBoardFile: targetOpt, vaultScope: 'session' }
513
+ : { ...targetOpt, vaultScope: 'session' })
514
+ : (opts && (opts.cwd || opts.projectKey || opts.cabinetId || opts.customSharedBoardFile || opts.rootSessionId || opts.sessionId)
515
+ ? { ...opts, vaultScope: 'session' }
516
+ : { vaultScope: 'session' })
517
+ const store = loadArchiveStore(rawTarget)
518
+ if (store.unboundSession) {
519
+ return { ok: true, totalArchives: 0, matchCount: 0, hits: [], unboundSession: true }
520
+ }
521
+ return {
522
+ ok: true,
523
+ ...scoreAndRankArchiveItems(store, query, opts),
524
+ }
525
+ }
526
+
527
+ /** On-demand search strictly for Chief (`askChief`) across the System Global Cold Vault (`global-vault/vault-chief-global.json`).
528
+ * NEVER exposed to Lead/Subagent `chief_board` tools. */
529
+ export function searchGlobalVaultForChief(query = '', opts = {}, targetOpt) {
530
+ const rawTarget = targetOpt !== undefined
531
+ ? (typeof targetOpt === 'string' ? { customSharedBoardFile: targetOpt, vaultScope: 'global' } : { ...targetOpt, vaultScope: 'global' })
532
+ : { ...(opts || {}), vaultScope: 'global' }
533
+ const store = loadGlobalVaultRaw(rawTarget)
534
+ return {
535
+ ok: true,
536
+ vaultScope: 'global',
537
+ isSystemGlobalVault: true,
538
+ ...scoreAndRankArchiveItems(store, query, opts),
539
+ }
540
+ }
541
+
542
+ /* ------------------------------------------- Cabinet & Archive Mutations */
543
+
544
+ export function mutateArchive(payload = {}, targetOpt) {
545
+ const op = str(payload.op, 'save').trim()
546
+ const baseOpts = resolveTargetOpts(targetOpt)
547
+ const vaultScope = normalizeVaultScope(payload.vaultScope || payload.scope || baseOpts.vaultScope)
548
+ const rootSessionId = cleanRootSessionId(payload.rootSessionId || payload.session || baseOpts.rootSessionId)
549
+ const effectiveTarget = {
550
+ ...baseOpts,
551
+ cwd: str(payload.cwd, baseOpts.cwd),
552
+ projectKey: str(payload.projectKey, baseOpts.projectKey),
553
+ cabinetId: str(payload.cabinetId, baseOpts.cabinetId),
554
+ rootSessionId,
555
+ vaultScope,
556
+ }
557
+
558
+ if (['listCabinets', 'createCabinet', 'switchCabinet', 'renameCabinet', 'deleteCabinet'].includes(op)) {
559
+ return mutateCabinetRegistry({ ...payload, vaultScope }, effectiveTarget)
560
+ }
561
+
562
+ return withArchiveLock(effectiveTarget, (_file, resolved) => {
563
+ const store = loadArchiveStore({ ...effectiveTarget, cabinetId: resolved.cabinetId, rootSessionId: resolved.rootSessionId, vaultScope: resolved.vaultScope })
564
+ const lockTarget = { ...effectiveTarget, cabinetId: resolved.cabinetId, projectKey: resolved.projectKey, rootSessionId: resolved.rootSessionId, vaultScope: resolved.vaultScope }
565
+ const runOp = () => {
566
+
567
+ if (op === 'createFolder' || op === 'saveFolder') {
568
+ const rawLabel = clamp(payload.label || payload.folderLabel || payload.folder, 40)
569
+ if (!rawLabel) return { ok: false, error: '请输入文件夹抽屉名称' }
570
+ const id = str(payload.folderId, '').trim()
571
+ || ('folder-' + rawLabel.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5_-]+/g, '-').slice(0, 24) + '-' + Date.now().toString(36).slice(-3))
572
+ const existing = store.folders.find(f => f.id === id || f.label === rawLabel)
573
+ if (existing) {
574
+ if (payload.hint !== undefined) existing.hint = clamp(payload.hint, 100)
575
+ if (payload.accent) existing.accent = str(payload.accent, existing.accent).slice(0, 24)
576
+ saveArchiveStore(store, lockTarget)
577
+ return { ok: true, folder: existing }
578
+ }
579
+ const created = normalizeFolder({
580
+ id,
581
+ label: rawLabel,
582
+ hint: payload.hint || '自定义工程记忆抽屉',
583
+ accent: payload.accent || '#06b6d4',
584
+ order: 55 + store.folders.length,
585
+ })
586
+ store.folders.push(created)
587
+ saveArchiveStore(store, lockTarget)
588
+ return { ok: true, folder: created }
589
+ }
590
+
591
+ if (op === 'save' || op === 'create' || op === 'update') {
592
+ const id = str(payload.archiveId || payload.id, '').trim()
593
+ const existing = id ? store.items.find(it => it.id === id) : null
594
+
595
+ const nextBody = typeof payload.body === 'string'
596
+ ? cleanMultiline(payload.body, 30000)
597
+ : (existing ? existing.body : '')
598
+ if (SECRET_PATTERN.test(nextBody)) {
599
+ return { ok: false, error: '档案内容疑似包含密钥或私密凭据,已拒绝入库' }
600
+ }
601
+
602
+ if (existing) {
603
+ const bodyChanged = typeof payload.body === 'string' && payload.body.trim() !== existing.body.trim()
604
+ if (typeof payload.title === 'string' && payload.title.trim()) {
605
+ existing.title = clamp(payload.title, 180)
606
+ }
607
+ if (typeof payload.body === 'string') {
608
+ existing.body = nextBody
609
+ }
610
+ if (typeof payload.folder === 'string' && payload.folder.trim()) {
611
+ existing.folder = payload.folder.trim()
612
+ }
613
+ if (['gold', 'silver', 'copper'].includes(payload.paperclip)) {
614
+ existing.paperclip = payload.paperclip
615
+ }
616
+ if (Array.isArray(payload.tags)) {
617
+ existing.tags = normalizeTags(payload.tags)
618
+ } else if (typeof payload.tags === 'string') {
619
+ existing.tags = normalizeTags(payload.tags.split(/[,,]/))
620
+ }
621
+ if (Array.isArray(payload.points) && payload.points.length) {
622
+ existing.points = payload.points.map((p, i) => normalizePoint(p, i)).filter(Boolean).slice(0, POINTS_CAP)
623
+ existing.organizedBy = payload.organizedBy || 'user'
624
+ } else if (bodyChanged) {
625
+ existing.points = extractStructuredPoints(existing.title, existing.body)
626
+ }
627
+ if (typeof payload.summary === 'string' && payload.summary.trim()) {
628
+ existing.summary = clamp(payload.summary, 140)
629
+ } else if (bodyChanged) {
630
+ existing.summary = clamp(
631
+ (existing.points[0] && existing.points[0].cue) || firstMeaningfulSentence(existing.body) || existing.title,
632
+ 140,
633
+ )
634
+ }
635
+ existing.contentHash = computeEntryContentHash(existing)
636
+ existing.updatedAt = Date.now()
637
+ saveArchiveStore(store, lockTarget)
638
+ return {
639
+ ok: true,
640
+ isSystemGlobalVault: resolved.vaultScope === 'global',
641
+ item: existing,
642
+ meta: getArchiveMeta(rootSessionId, lockTarget),
643
+ }
644
+ }
645
+
646
+ const rawTitle = clamp(payload.title || '', 180)
647
+ if (!rawTitle && !nextBody) {
648
+ return { ok: false, error: '新建工程档案需要填写标题或正文内容' }
649
+ }
650
+ const titleKey = normalizeArchiveTitleKey(rawTitle)
651
+ const sameTitle = titleKey
652
+ ? store.items.find(it => normalizeArchiveTitleKey(it.title) === titleKey)
653
+ : null
654
+ if (sameTitle && payload.upsertByTitle !== false) {
655
+ sameTitle.body = nextBody || sameTitle.body
656
+ if (payload.folder) sameTitle.folder = str(payload.folder, sameTitle.folder).trim()
657
+ if (['gold', 'silver', 'copper'].includes(payload.paperclip)) sameTitle.paperclip = payload.paperclip
658
+ if (payload.tags) {
659
+ sameTitle.tags = normalizeTags(Array.isArray(payload.tags) ? payload.tags : String(payload.tags).split(/[,,]/))
660
+ }
661
+ sameTitle.points = Array.isArray(payload.points) && payload.points.length
662
+ ? payload.points.map((p, i) => normalizePoint(p, i)).filter(Boolean).slice(0, POINTS_CAP)
663
+ : extractStructuredPoints(sameTitle.title, sameTitle.body)
664
+ sameTitle.summary = clamp(
665
+ payload.summary || (sameTitle.points[0] && sameTitle.points[0].cue) || firstMeaningfulSentence(sameTitle.body) || sameTitle.title,
666
+ 140,
667
+ )
668
+ sameTitle.contentHash = computeEntryContentHash(sameTitle)
669
+ sameTitle.updatedAt = Date.now()
670
+ saveArchiveStore(store, lockTarget)
671
+ return {
672
+ ok: true,
673
+ isSystemGlobalVault: resolved.vaultScope === 'global',
674
+ item: sameTitle,
675
+ updatedExisting: true,
676
+ meta: getArchiveMeta(rootSessionId, lockTarget),
677
+ }
678
+ }
679
+
680
+ const parsed = smartParseNoteToDossier({
681
+ title: rawTitle,
682
+ body: nextBody,
683
+ folder: payload.folder,
684
+ paperclip: payload.paperclip,
685
+ tags: Array.isArray(payload.tags) ? payload.tags : (typeof payload.tags === 'string' ? payload.tags.split(/[,,]/) : []),
686
+ })
687
+ const baseCreated = {
688
+ id: nextId(resolved.vaultScope === 'global' ? 'glob' : 'arch'),
689
+ sourceNoteId: str(payload.sourceNoteId, ''),
690
+ originId: str(payload.originId, ''),
691
+ originGlobalId: str(payload.originGlobalId, ''),
692
+ title: parsed.title,
693
+ summary: payload.summary || parsed.summary,
694
+ folder: payload.folder || parsed.folder,
695
+ paperclip: payload.paperclip || parsed.paperclip,
696
+ tags: Array.isArray(payload.tags) ? payload.tags : (typeof payload.tags === 'string' ? payload.tags.split(/[,,]/) : []),
697
+ cold: true,
698
+ takenOutSessions: (payload.takeOutNow || payload.takeOut) && rootSessionId && resolved.vaultScope !== 'global' ? [rootSessionId] : [],
699
+ chiefMountedSessions: resolved.vaultScope === 'global' && payload.mountChief && rootSessionId ? [rootSessionId] : [],
700
+ organizedBy: ['auto', 'chief', 'user'].includes(payload.organizedBy)
701
+ ? payload.organizedBy
702
+ : (Array.isArray(payload.points) && payload.points.length ? 'user' : 'auto'),
703
+ points: Array.isArray(payload.points) && payload.points.length ? payload.points : parsed.points,
704
+ body: nextBody,
705
+ by: payload.by || 'user',
706
+ sourceSession: rootSessionId,
707
+ createdAt: Date.now(),
708
+ updatedAt: Date.now(),
709
+ }
710
+ const created = resolved.vaultScope === 'global'
711
+ ? normalizeGlobalVaultEntry(baseCreated)
712
+ : normalizeArchiveItem(baseCreated)
713
+ store.items.unshift(created)
714
+ saveArchiveStore(store, lockTarget)
715
+ return {
716
+ ok: true,
717
+ isSystemGlobalVault: resolved.vaultScope === 'global',
718
+ item: created,
719
+ meta: getArchiveMeta(rootSessionId, lockTarget),
720
+ }
721
+ }
722
+
723
+ if (op === 'delete' || op === 'remove') {
724
+ const id = str(payload.archiveId || payload.id, '').trim()
725
+ const idx = store.items.findIndex(it => it.id === id)
726
+ if (idx < 0) return { ok: false, error: '未找到要删除的档案:' + id }
727
+ const [removed] = store.items.splice(idx, 1)
728
+ saveArchiveStore(store, lockTarget)
729
+ return { ok: true, removedId: removed.id, title: removed.title, meta: getArchiveMeta(rootSessionId, lockTarget) }
730
+ }
731
+
732
+ if (op === 'clearByIds' || op === 'clearFolder') {
733
+ const ids = new Set(Array.isArray(payload.ids) ? payload.ids.map(x => String(x || '').trim()).filter(Boolean) : [])
734
+ const folder = str(payload.folder, '').trim()
735
+ const before = store.items.length
736
+ store.items = store.items.filter((it) => {
737
+ if (op === 'clearFolder') return it.folder !== folder
738
+ return !ids.has(it.id)
739
+ })
740
+ const removedCount = before - store.items.length
741
+ if (removedCount > 0) saveArchiveStore(store, lockTarget)
742
+ return { ok: true, removedCount, meta: getArchiveMeta(rootSessionId, lockTarget) }
743
+ }
744
+
745
+ if (op === 'mountChief' || op === 'unmountChief') {
746
+ if (resolved.vaultScope !== 'global') {
747
+ return { ok: false, error: '仅系统全局档案柜支持参谋长参阅挂载操作' }
748
+ }
749
+ if (!rootSessionId) {
750
+ return { ok: false, error: '当前为空白新对话(尚未绑定会话 ID),请先在主会话发送一条消息后再供参谋长参阅' }
751
+ }
752
+ const id = str(payload.archiveId || payload.id, '').trim()
753
+ const item = store.items.find(it => it.id === id)
754
+ if (!item) return { ok: false, error: '未找到该全局档案:' + id }
755
+ const set = new Set(item.chiefMountedSessions || [])
756
+ if (op === 'mountChief') set.add(rootSessionId)
757
+ else set.delete(rootSessionId)
758
+ item.chiefMountedSessions = [...set]
759
+ saveArchiveStore(store, lockTarget)
760
+ return {
761
+ ok: true,
762
+ id: item.id,
763
+ title: item.title,
764
+ chiefMounted: op === 'mountChief',
765
+ isSystemGlobalVault: true,
766
+ counts: getThreeTierArchiveCounts(rootSessionId, [], lockTarget),
767
+ }
768
+ }
769
+
770
+ if (op === 'takeOut' || op === 'putBack') {
771
+ const id = str(payload.archiveId || payload.id, '').trim()
772
+ if (!rootSessionId) return { ok: false, error: '当前未绑定对话会话,无法摆到桌面备选' }
773
+ const item = store.items.find(it => it.id === id)
774
+ if (!item) return { ok: false, error: '未找到该工程档案:' + id }
775
+ const set = new Set(item.takenOutSessions || [])
776
+ if (op === 'takeOut') set.add(rootSessionId)
777
+ else set.delete(rootSessionId)
778
+ item.takenOutSessions = [...set]
779
+ saveArchiveStore(store, lockTarget)
780
+ return {
781
+ ok: true,
782
+ id: item.id,
783
+ title: item.title,
784
+ takenOut: op === 'takeOut',
785
+ isSystemGlobalVault: resolved.vaultScope === 'global',
786
+ counts: getThreeTierArchiveCounts(rootSessionId, [], lockTarget),
787
+ meta: getArchiveMeta(rootSessionId, lockTarget),
788
+ }
789
+ }
790
+
791
+ if (op === 'cycleClip' || op === 'setClip') {
792
+ const id = str(payload.archiveId || payload.id, '').trim()
793
+ const item = store.items.find(it => it.id === id)
794
+ if (!item) return { ok: false, error: '未找到该工程档案:' + id }
795
+ const order = ['gold', 'silver', 'copper']
796
+ if (order.includes(payload.paperclip)) {
797
+ item.paperclip = payload.paperclip
798
+ } else {
799
+ const nextIdx = (order.indexOf(item.paperclip) + 1) % order.length
800
+ item.paperclip = order[nextIdx]
801
+ }
802
+ item.updatedAt = Date.now()
803
+ saveArchiveStore(store, lockTarget)
804
+ return { ok: true, id: item.id, paperclip: item.paperclip }
805
+ }
806
+
807
+ if (op === 'moveFolder') {
808
+ const id = str(payload.archiveId || payload.id, '').trim()
809
+ const folder = str(payload.folder, '').trim()
810
+ if (!folder) return { ok: false, error: '请选择目标文件夹抽屉' }
811
+ const item = store.items.find(it => it.id === id)
812
+ if (!item) return { ok: false, error: '未找到该工程档案:' + id }
813
+ item.folder = folder
814
+ if (payload.folderLabel && !store.folders.some(f => f.id === folder)) {
815
+ store.folders.push(normalizeFolder({ id: folder, label: payload.folderLabel, order: 58 }))
816
+ }
817
+ item.updatedAt = Date.now()
818
+ saveArchiveStore(store, lockTarget)
819
+ return { ok: true, id: item.id, folder: item.folder }
820
+ }
821
+
822
+ if (op === 'copyToGlobal' || op === 'copyToSession') {
823
+ const id = str(payload.archiveId || payload.id, '').trim()
824
+ const srcItem = store.items.find(it => it.id === id)
825
+ if (!srcItem) return { ok: false, error: '未找到要复制的工程档案:' + id }
826
+ const targetScope = op === 'copyToGlobal' ? 'global' : 'session'
827
+ if (targetScope === 'session' && !rootSessionId) {
828
+ return { ok: false, error: '当前为空白新对话,请先发送一条消息建立会话后再引入本会话档案柜' }
829
+ }
830
+ const dstBase = {
831
+ customSharedBoardFile: baseOpts.customSharedBoardFile,
832
+ cwd: effectiveTarget.cwd,
833
+ projectKey: effectiveTarget.projectKey,
834
+ rootSessionId: targetScope === 'session' ? rootSessionId : '',
835
+ vaultScope: targetScope,
836
+ cabinetId: '',
837
+ }
838
+ const titleKey = normalizeArchiveTitleKey(srcItem.title)
839
+ const copyRes = withArchiveLock(dstBase, (_dstFile, dstResolved) => {
840
+ const dstTarget = { ...dstBase, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey, vaultScope: targetScope }
841
+ const dstStore = targetScope === 'global' ? loadGlobalVaultRaw(dstTarget) : loadArchiveStore(dstTarget)
842
+ const now = Date.now()
843
+ let savedItem
844
+
845
+ if (targetScope === 'global') {
846
+ const existing = dstStore.items.find(g =>
847
+ (srcItem.originGlobalId && g.id === srcItem.originGlobalId)
848
+ || (g.originId && g.originId === srcItem.id)
849
+ || (titleKey && normalizeArchiveTitleKey(g.title) === titleKey)
850
+ )
851
+ const preservedChiefMounts = existing
852
+ ? (Array.isArray(existing.chiefMountedSessions) ? existing.chiefMountedSessions : [])
853
+ : (payload.mountChief && rootSessionId ? [rootSessionId] : [])
854
+ const nextEntry = normalizeGlobalVaultEntry({
855
+ ...srcItem,
856
+ id: existing ? existing.id : nextId('glob'),
857
+ originId: srcItem.id,
858
+ originGlobalId: '',
859
+ chiefMountedSessions: preservedChiefMounts,
860
+ sourceSession: srcItem.sourceSession || rootSessionId,
861
+ updatedAt: now,
862
+ })
863
+ if (existing) {
864
+ Object.assign(existing, nextEntry)
865
+ savedItem = existing
866
+ } else {
867
+ dstStore.items.unshift(nextEntry)
868
+ savedItem = nextEntry
869
+ }
870
+ saveGlobalVaultRaw(dstStore, dstTarget)
871
+ const sessSnapshot = resolved.vaultScope === 'session'
872
+ ? store.items.map(it => (it.id === srcItem.id && payload.removeSource !== true ? { ...it, originGlobalId: savedItem.id } : it))
873
+ : []
874
+ const diff = computeSessionGlobalDiff(sessSnapshot, dstStore.items, rootSessionId)
875
+ return {
876
+ ok: true,
877
+ targetScope: 'global',
878
+ isSystemGlobalVault: true,
879
+ targetCabinetId: '',
880
+ item: savedItem,
881
+ diffSummary: diff.summary,
882
+ counts: getThreeTierArchiveCounts(rootSessionId, [], dstBase),
883
+ }
884
+ }
885
+
886
+ // targetScope === 'session'
887
+ const mountOnSession = payload.takeOut === true
888
+ const existingSess = dstStore.items.find(s =>
889
+ s.originGlobalId === srcItem.id
890
+ || (srcItem.originId && s.id === srcItem.originId)
891
+ || (titleKey && normalizeArchiveTitleKey(s.title) === titleKey)
892
+ )
893
+ const nextSessItem = normalizeArchiveItem({
894
+ ...srcItem,
895
+ id: existingSess ? existingSess.id : nextId('arch'),
896
+ originGlobalId: srcItem.id,
897
+ originId: '',
898
+ takenOutSessions: mountOnSession
899
+ ? [...new Set([...(existingSess ? (existingSess.takenOutSessions || []) : []), rootSessionId])]
900
+ : (existingSess ? (existingSess.takenOutSessions || []) : []),
901
+ sourceSession: rootSessionId,
902
+ updatedAt: now,
903
+ })
904
+ if (existingSess) {
905
+ Object.assign(existingSess, nextSessItem)
906
+ savedItem = existingSess
907
+ } else {
908
+ dstStore.items.unshift(nextSessItem)
909
+ savedItem = nextSessItem
910
+ }
911
+ saveArchiveStore(dstStore, dstTarget)
912
+ const globalItems = resolved.vaultScope === 'global' ? store.items : loadGlobalVaultRaw(baseOpts).items
913
+ const diff = computeSessionGlobalDiff(dstStore.items, globalItems, rootSessionId)
914
+ return {
915
+ ok: true,
916
+ targetScope: 'session',
917
+ isSystemGlobalVault: false,
918
+ targetCabinetId: dstResolved.cabinetId,
919
+ item: savedItem,
920
+ diffSummary: diff.summary,
921
+ counts: getThreeTierArchiveCounts(rootSessionId, [], dstBase),
922
+ }
923
+ })
924
+
925
+ if (copyRes && copyRes.ok) {
926
+ if (payload.removeSource === true && resolved.vaultScope !== targetScope) {
927
+ const idx = store.items.findIndex(it => it.id === id)
928
+ if (idx >= 0) {
929
+ store.items.splice(idx, 1)
930
+ saveArchiveStore(store, lockTarget)
931
+ copyRes.counts = getThreeTierArchiveCounts(rootSessionId, [], dstBase)
932
+ }
933
+ } else if (targetScope === 'global' && resolved.vaultScope === 'session' && copyRes.item && srcItem.originGlobalId !== copyRes.item.id) {
934
+ srcItem.originGlobalId = copyRes.item.id
935
+ saveArchiveStore(store, lockTarget)
936
+ }
937
+ }
938
+ return copyRes
939
+ }
940
+
941
+ return { ok: false, error: '未知的档案操作:' + op }
942
+ }
943
+ const opRes = runOp()
944
+ return (opRes && opRes.ok && !opRes.cabinetId && !opRes.isSystemGlobalVault)
945
+ ? { cabinetId: resolved.cabinetId, isSystemGlobalVault: resolved.vaultScope === 'global', ...opRes }
946
+ : opRes
947
+ })
948
+ }
949
+
950
+ export function applyChiefArchiveCurations(curations = [], newFolders = [], targetOpt) {
951
+ if (!Array.isArray(curations) || !curations.length) return { updatedCount: 0 }
952
+ return withArchiveLock(targetOpt, (_file, resolved) => {
953
+ const base = resolveTargetOpts(targetOpt)
954
+ const lockTarget = {
955
+ ...base,
956
+ cabinetId: resolved.cabinetId,
957
+ projectKey: resolved.projectKey,
958
+ rootSessionId: resolved.rootSessionId || base.rootSessionId,
959
+ vaultScope: resolved.vaultScope || base.vaultScope,
960
+ }
961
+ const store = loadArchiveStore(lockTarget)
962
+ if (Array.isArray(newFolders)) {
963
+ newFolders.forEach((nf, idx) => {
964
+ if (!nf || !nf.id) return
965
+ const cleanId = String(nf.id).trim().slice(0, 48)
966
+ if (!cleanId) return
967
+ const existing = store.folders.find(f => f.id === cleanId)
968
+ if (existing) {
969
+ if (nf.label) existing.label = clamp(nf.label, 40)
970
+ if (nf.hint) existing.hint = clamp(nf.hint, 100)
971
+ } else {
972
+ const created = normalizeFolder({
973
+ id: cleanId,
974
+ label: nf.label || cleanId,
975
+ hint: nf.hint || '由 DSH 参谋长整理归纳的工程档案抽屉',
976
+ accent: nf.accent || '#06b6d4',
977
+ order: 52 + idx,
978
+ })
979
+ if (created) store.folders.push(created)
980
+ }
981
+ })
982
+ }
983
+
984
+ let updatedCount = 0
985
+ for (const c of curations) {
986
+ if (!c || !c.id) continue
987
+ const target = store.items.find(it => it.id === c.id)
988
+ if (!target) continue
989
+ if (typeof c.folder === 'string' && c.folder.trim()) {
990
+ const fId = c.folder.trim().slice(0, 48)
991
+ target.folder = fId
992
+ if (c.folderLabel && !store.folders.some(f => f.id === fId)) {
993
+ const created = normalizeFolder({
994
+ id: fId,
995
+ label: c.folderLabel,
996
+ hint: '由 DSH 参谋长整理建立的工程抽屉',
997
+ accent: '#06b6d4',
998
+ })
999
+ if (created) store.folders.push(created)
1000
+ }
1001
+ }
1002
+ if (['gold', 'silver', 'copper'].includes(c.paperclip)) {
1003
+ target.paperclip = c.paperclip
1004
+ }
1005
+ if (typeof c.summary === 'string' && c.summary.trim()) {
1006
+ target.summary = clamp(c.summary, 140)
1007
+ }
1008
+ if (Array.isArray(c.tags) && c.tags.length) {
1009
+ target.tags = normalizeTags(c.tags)
1010
+ }
1011
+ if (Array.isArray(c.points) && c.points.length) {
1012
+ const validPts = c.points.map((p, idx) => normalizePoint(p, idx)).filter(Boolean).slice(0, POINTS_CAP)
1013
+ if (validPts.length) {
1014
+ target.points = validPts
1015
+ }
1016
+ }
1017
+ target.organizedBy = 'chief'
1018
+ target.updatedAt = Date.now()
1019
+ updatedCount += 1
1020
+ }
1021
+
1022
+ if (updatedCount > 0) {
1023
+ saveArchiveStore(store, lockTarget)
1024
+ }
1025
+ return { updatedCount }
1026
+ })
1027
+ }
1028
+
1029
+ /* --------------------- Cross-Session Handoff Archive Copy (Never Precipitated) */
1030
+
1031
+ /**
1032
+ * Transfers ONLY active cabinet dossiers selected by `policy`:
1033
+ * - `'none'`: zero transfers
1034
+ * - `'mounted'`: only dossiers explicitly taken out on `fromRootSessionId` (`takenOutSessions`)
1035
+ * - `'drawer'`: dossiers inside `drawer` folder in source cabinet
1036
+ * - `'all'`: all dossiers in source active cabinet
1037
+ * Strictly NEVER reads or transfers `precipitated/<projectKey>.json`!
1038
+ */
1039
+ export function copyArchivesBetweenSessionsOrCabinets({
1040
+ fromRootSessionId = '',
1041
+ toRootSessionId = '',
1042
+ fromCwd = '',
1043
+ toCwd = '',
1044
+ fromCabinetId = '',
1045
+ toCabinetId = '',
1046
+ policy = 'none',
1047
+ drawer = '',
1048
+ customSharedBoardFile = '',
1049
+ }) {
1050
+ const mode = ['none', 'mounted', 'drawer', 'all'].includes(policy) ? policy : 'none'
1051
+ const fromSid = str(fromRootSessionId, '').trim()
1052
+ const toSid = str(toRootSessionId, '').trim()
1053
+ if (mode === 'none' || !fromSid || !toSid) {
1054
+ return { ok: true, policy: mode, transferredCount: 0, mountedCount: 0 }
1055
+ }
1056
+
1057
+ const srcTarget = {
1058
+ customSharedBoardFile,
1059
+ cwd: fromCwd,
1060
+ cabinetId: fromCabinetId,
1061
+ rootSessionId: fromSid,
1062
+ vaultScope: 'session',
1063
+ }
1064
+ const dstTarget = {
1065
+ customSharedBoardFile,
1066
+ cwd: toCwd || fromCwd,
1067
+ cabinetId: toCabinetId,
1068
+ rootSessionId: toSid,
1069
+ vaultScope: 'session',
1070
+ }
1071
+
1072
+ const srcResolved = ensureProjectCabinet(srcTarget)
1073
+ const dstResolved = ensureProjectCabinet(dstTarget)
1074
+ if (srcResolved.unboundSession || dstResolved.unboundSession) {
1075
+ return { ok: true, policy: mode, transferredCount: 0, mountedCount: 0 }
1076
+ }
1077
+ const srcStore = loadArchiveStore({ customSharedBoardFile, cabinetId: srcResolved.cabinetId, projectKey: srcResolved.projectKey, rootSessionId: fromSid, vaultScope: 'session' })
1078
+
1079
+ let selected = []
1080
+ if (mode === 'mounted') {
1081
+ selected = srcStore.items.filter(it => fromSid && Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(fromSid))
1082
+ } else if (mode === 'drawer') {
1083
+ const fId = str(drawer, '').trim()
1084
+ selected = srcStore.items.filter(it => !fId || it.folder === fId)
1085
+ } else if (mode === 'all') {
1086
+ selected = srcStore.items.slice()
1087
+ }
1088
+
1089
+ if (!selected.length) {
1090
+ return {
1091
+ ok: true,
1092
+ policy: mode,
1093
+ sameCabinet: srcResolved.cabinetId === dstResolved.cabinetId,
1094
+ targetCabinetId: dstResolved.cabinetId,
1095
+ transferredCount: 0,
1096
+ mountedCount: 0,
1097
+ }
1098
+ }
1099
+
1100
+ // Same cabinet: update `takenOutSessions` on selected items directly (mount mounted items or selected drawer items for target)
1101
+ if (srcResolved.cabinetId === dstResolved.cabinetId) {
1102
+ return withArchiveLock({ customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey, rootSessionId: toSid, vaultScope: 'session' }, () => {
1103
+ const store = loadArchiveStore({ customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey, rootSessionId: toSid, vaultScope: 'session' })
1104
+ let mountedCount = 0
1105
+ const selectedIds = new Set(selected.map(s => s.id))
1106
+ for (const it of store.items) {
1107
+ if (!selectedIds.has(it.id)) continue
1108
+ const shouldMount = mode === 'mounted' || (fromSid && Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(fromSid)) || mode === 'drawer'
1109
+ if (shouldMount) {
1110
+ const set = new Set(it.takenOutSessions || [])
1111
+ if (!set.has(toSid)) {
1112
+ set.add(toSid)
1113
+ it.takenOutSessions = [...set]
1114
+ mountedCount += 1
1115
+ }
1116
+ }
1117
+ }
1118
+ if (mountedCount > 0) {
1119
+ saveArchiveStore(store, { customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey, rootSessionId: toSid, vaultScope: 'session' })
1120
+ }
1121
+ return {
1122
+ ok: true,
1123
+ policy: mode,
1124
+ sameCabinet: true,
1125
+ targetCabinetId: dstResolved.cabinetId,
1126
+ transferredCount: selected.length,
1127
+ mountedCount,
1128
+ }
1129
+ })
1130
+ }
1131
+
1132
+ // Different cabinets: copy folders metadata & dossiers into destination cabinet
1133
+ return withArchiveLock({ customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey, rootSessionId: toSid, vaultScope: 'session' }, () => {
1134
+ const dstStore = loadArchiveStore({ customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey, rootSessionId: toSid, vaultScope: 'session' })
1135
+ const folderIds = new Set(dstStore.folders.map(f => f.id))
1136
+ for (const f of srcStore.folders) {
1137
+ if (!folderIds.has(f.id)) {
1138
+ dstStore.folders.push({ ...f })
1139
+ folderIds.add(f.id)
1140
+ }
1141
+ }
1142
+ const existingTitles = new Map(dstStore.items.map(it => [it.title, it]))
1143
+ let copiedCount = 0
1144
+ let mountedCount = 0
1145
+ for (const srcItem of selected) {
1146
+ const shouldMount = mode === 'mounted' || (fromSid && srcItem.takenOutSessions.includes(fromSid))
1147
+ const dup = existingTitles.get(srcItem.title)
1148
+ if (dup) {
1149
+ if (shouldMount && !dup.takenOutSessions.includes(toSid)) {
1150
+ dup.takenOutSessions.push(toSid)
1151
+ mountedCount += 1
1152
+ }
1153
+ dup.updatedAt = Date.now()
1154
+ copiedCount += 1
1155
+ continue
1156
+ }
1157
+ const cloned = normalizeArchiveItem({
1158
+ ...srcItem,
1159
+ id: nextId('arch'),
1160
+ takenOutSessions: shouldMount ? [toSid] : [],
1161
+ updatedAt: Date.now(),
1162
+ })
1163
+ if (cloned) {
1164
+ dstStore.items.unshift(cloned)
1165
+ copiedCount += 1
1166
+ if (shouldMount) mountedCount += 1
1167
+ }
1168
+ }
1169
+ if (copiedCount > 0 || mountedCount > 0) {
1170
+ saveArchiveStore(dstStore, { customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey, rootSessionId: toSid, vaultScope: 'session' })
1171
+ }
1172
+ return {
1173
+ ok: true,
1174
+ policy: mode,
1175
+ sameCabinet: false,
1176
+ targetCabinetId: dstResolved.cabinetId,
1177
+ transferredCount: copiedCount,
1178
+ mountedCount,
1179
+ }
1180
+ })
1181
+ }
1182
+
1183
+ /* --------------------- Precipitated Cross-Session Vault (STRICTLY 0 AUTO-READ) */
1184
+
1185
+ registerArchiveMutatorHook(mutateArchive)