dsh-chief 1.0.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
@@ -1,30 +1,34 @@
1
1
  /**
2
- * Engineering Memory Filing Cabinet (沉淀工程记忆档案库 · 严格懒加载 · 零主动注入)
2
+ * Engineering Memory Filing Cabinet v2 (单工程多档案柜 + 跨会话沉淀冷库 · 物理零偷读)
3
3
  *
4
- * Persists structured long-term engineering dossiers at `%DSH_HOME%/chief/archives.json`.
4
+ * Storage Layout under `%DSH_HOME%/chief/` (or `path.dirname(customSharedBoardFile)`):
5
+ * - `cabinets/registry.json` : Project -> activeCabinetId & cabinets list
6
+ * - `cabinets/<cabinetId>.json` : Active working filing cabinet (folders + paperclipped dossiers)
7
+ * - `archives.json` : Legacy v1 single cabinet (losslessly migrated to `cab-main` on first read)
8
+ * - `precipitated/<projectKey>.json` : Cross-session reusable experience cold vault (ZERO auto-read!)
5
9
  *
6
10
  * Core Contracts:
7
- * 1. Cold Vault (`cold: true`, `takenOutSessions: []` by default):
8
- * Never auto-injected into system prompts (`renderDigest`), handoff packets (`renderHandoff`),
9
- * or background chief reviews. Zero token burn until explicitly requested or taken out by user.
10
- * 2. Two-Stage Lazy Loading for Web UI:
11
- * - `/snapshot` carries ONLY `archiveMeta` counts (<80 bytes).
12
- * - `GET /archives` (when clicking `档案` tab) returns folder drawers + lightweight dossier headers
13
- * (NO `points` details and NO `body` text).
14
- * - `GET /archives/detail?id=...` (when opening a dossier) lazy-loads structured `points` + lossless `body`.
15
- * 3. Three-Tier Filing Hierarchy:
16
- * - Tier 1: Filing Cabinet Folders (`folders`: drawer tabs with color spine & counts)
17
- * - Tier 2: Paperclipped Dossier Files (`paperclip`: 'gold' | 'silver' | 'copper', title, summary, tags)
18
- * - Tier 3: Structured Memory Points (`points`: `{ id, title, cue, detail }`) -> click point to expand sub-point detail (`小点记忆`), while 100% preserving raw `body`.
11
+ * 1. Multi-Cabinet per Project (`projectKey = resolveProjectKey(cwd)`):
12
+ * Allows creating, switching, renaming, and removing isolated filing cabinets per workspace project.
13
+ * 2. Working Cabinet Cold Vault (`cold: true`, `takenOutSessions: []` by default):
14
+ * Never auto-injected into system prompts unless explicitly taken out onto the session desk (`takenOutSessions`)
15
+ * or queried via on-demand `searchArchives`.
16
+ * 3. Precipitated Cross-Session Cold Vault (`precipitated/<projectKey>.json`):
17
+ * Stores purified cross-session reusable architecture rules, env coords, contracts, and troubleshooting laws.
18
+ * STRICTLY 0-TOKEN ISOLATED: `renderDigest`, `renderHandoff`, `runTurnReview`, `searchArchives`, and
19
+ * cross-session handoff copy NEVER read `precipitated/<projectKey>.json` unless a user explicitly triggers
20
+ * `flipOut` on a precipitated entry to inspect/co-organize it inside the current session!
19
21
  */
20
22
 
23
+ import crypto from 'node:crypto'
21
24
  import fs from 'node:fs'
22
25
  import os from 'node:os'
23
26
  import path from 'node:path'
24
27
 
25
- const ARCHIVE_VERSION = 1
28
+ const ARCHIVE_VERSION = 2
26
29
  const ARCHIVE_CAP = 500
27
30
  const POINTS_CAP = 32
31
+ const PRECIPITATED_CAP = 300
28
32
  const SECRET_PATTERN = /(?:sk-[a-zA-Z0-9_-]{16,}|ghp_[a-zA-Z0-9]{20,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{30,}|Bearer\s+[A-Za-z0-9._~+/=-]{20,}|-----BEGIN [A-Z ]*PRIVATE KEY-----)/
29
33
 
30
34
  export const DEFAULT_ARCHIVE_FOLDERS = [
@@ -96,12 +100,160 @@ function cleanMultiline(v, max) {
96
100
  return text.slice(0, Math.max(0, max - 1)) + '…'
97
101
  }
98
102
 
99
- export function archiveFilePath(customSharedBoardFile) {
100
- if (customSharedBoardFile) {
101
- return path.join(path.dirname(customSharedBoardFile), 'archives.json')
103
+ /* ------------------------------------------- Paths, Project Key & Registry */
104
+
105
+ export function normalizeCwd(cwd) {
106
+ const raw = str(cwd, '').trim()
107
+ if (!raw) return ''
108
+ try {
109
+ let resolved = path.resolve(raw)
110
+ if (resolved.length > 3) {
111
+ resolved = resolved.replace(/[\\/]+$/, '')
112
+ }
113
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved
114
+ } catch {
115
+ return raw.replace(/[\\/]+$/, '').toLowerCase()
116
+ }
117
+ }
118
+
119
+ export function resolveProjectKey(cwd = '') {
120
+ const raw = str(cwd, '').trim()
121
+ if (!raw) return 'proj-default'
122
+ if (/^proj-[a-z0-9._-]+$/i.test(raw) && !raw.includes('\\') && !raw.includes('/')) {
123
+ return raw.slice(0, 64)
124
+ }
125
+ const norm = normalizeCwd(raw)
126
+ if (!norm) return 'proj-default'
127
+ const baseRaw = path.basename(norm) || 'workspace'
128
+ const safeBase = baseRaw
129
+ .toLowerCase()
130
+ .replace(/[^a-z0-9\u4e00-\u9fa5._-]+/g, '-')
131
+ .replace(/^-+|-+$/g, '')
132
+ .slice(0, 22) || 'ws'
133
+ const hash8 = crypto.createHash('sha1').update(norm).digest('hex').slice(0, 8)
134
+ return `proj-${safeBase}-${hash8}`
135
+ }
136
+
137
+ function chiefRootDir(targetOpt) {
138
+ let sharedFile = ''
139
+ if (typeof targetOpt === 'string') {
140
+ sharedFile = targetOpt
141
+ } else if (targetOpt && typeof targetOpt === 'object') {
142
+ sharedFile = str(targetOpt.customSharedBoardFile || targetOpt.sharedFile, '').trim()
143
+ }
144
+ if (sharedFile) {
145
+ return path.dirname(sharedFile)
102
146
  }
103
147
  const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
104
- return path.join(home, 'chief', 'archives.json')
148
+ return path.join(home, 'chief')
149
+ }
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
+
163
+ function resolveTargetOpts(targetOpt) {
164
+ if (!targetOpt || typeof targetOpt === 'string') {
165
+ return {
166
+ customSharedBoardFile: str(targetOpt, ''),
167
+ cwd: '',
168
+ projectKey: '',
169
+ cabinetId: '',
170
+ rootSessionId: '',
171
+ vaultScope: 'session',
172
+ }
173
+ }
174
+ return {
175
+ customSharedBoardFile: str(targetOpt.customSharedBoardFile || targetOpt.sharedFile, ''),
176
+ cwd: str(targetOpt.cwd, ''),
177
+ projectKey: str(targetOpt.projectKey, ''),
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 }
207
+ }
208
+ if (cleanRootSessionId(targetOpt.rootSessionId || targetOpt.sessionId || targetOpt.session)) {
209
+ return { ...targetOpt, vaultScope }
210
+ }
211
+ return { ...targetOpt, rootSessionId: sid, vaultScope }
212
+ }
213
+
214
+ export function legacyArchiveFilePath(targetOpt) {
215
+ return path.join(chiefRootDir(targetOpt), 'archives.json')
216
+ }
217
+
218
+ export function cabinetsDirPath(targetOpt) {
219
+ return path.join(chiefRootDir(targetOpt), 'cabinets')
220
+ }
221
+
222
+ export function cabinetRegistryPath(targetOpt) {
223
+ return path.join(cabinetsDirPath(targetOpt), 'registry.json')
224
+ }
225
+
226
+ export function cabinetFilePath(cabinetId = 'cab-main', targetOpt) {
227
+ const safe = String(cabinetId || 'cab-main').replace(/[^a-zA-Z0-9._-]+/g, '-').slice(0, 72) || 'cab-main'
228
+ return path.join(cabinetsDirPath(targetOpt), `${safe}.json`)
229
+ }
230
+
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)
241
+ }
242
+
243
+ export function archiveFilePath(targetOpt) {
244
+ const resolved = ensureProjectCabinet(targetOpt)
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)
105
257
  }
106
258
 
107
259
  /* ----------------------------------------------------------- Lock & Storage */
@@ -115,7 +267,7 @@ function sleepSync(ms) {
115
267
  } catch {}
116
268
  }
117
269
 
118
- function acquireArchiveLock(file) {
270
+ function acquireFileLock(file) {
119
271
  if (heldArchiveLocks.has(file)) return () => {}
120
272
  const lock = file + '.lock'
121
273
  try {
@@ -162,6 +314,353 @@ export function invalidateArchiveCache() {
162
314
  archiveCache = { file: '', mtime: -1, store: null }
163
315
  }
164
316
 
317
+ function atomicWriteJson(file, data) {
318
+ fs.mkdirSync(path.dirname(file), { recursive: true })
319
+ const tmp = file + '.' + process.pid + '.' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 6) + '.tmp'
320
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf8')
321
+ fs.renameSync(tmp, file)
322
+ }
323
+
324
+ function readJsonSafe(file, fallback = null) {
325
+ try {
326
+ if (!fs.existsSync(file)) return fallback
327
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
328
+ } catch {
329
+ return fallback
330
+ }
331
+ }
332
+
333
+ /* ------------------------------------------- Registry & Legacy Migration */
334
+
335
+ function normalizeRegistry(raw) {
336
+ const src = raw && typeof raw === 'object' ? raw : {}
337
+ const projects = {}
338
+ if (src.projects && typeof src.projects === 'object') {
339
+ for (const [k, proj] of Object.entries(src.projects)) {
340
+ if (!proj || typeof proj !== 'object') continue
341
+ const pKey = resolveProjectKey(k)
342
+ const cabinets = (Array.isArray(proj.cabinets) ? proj.cabinets : [])
343
+ .filter(c => c && typeof c === 'object' && str(c.id, '').trim())
344
+ .map(c => ({
345
+ id: str(c.id, '').trim().slice(0, 72),
346
+ name: clamp(c.name || '默认档案柜', 40),
347
+ projectKey: pKey,
348
+ cwd: str(c.cwd, '').slice(0, 260),
349
+ createdAt: Number(c.createdAt) || Date.now(),
350
+ updatedAt: Number(c.updatedAt) || Number(c.createdAt) || Date.now(),
351
+ }))
352
+ if (!cabinets.length) continue
353
+ const activeCabinetId = cabinets.some(c => c.id === proj.activeCabinetId)
354
+ ? proj.activeCabinetId
355
+ : cabinets[0].id
356
+ projects[pKey] = {
357
+ projectKey: pKey,
358
+ cwd: str(proj.cwd, '').slice(0, 260),
359
+ activeCabinetId,
360
+ cabinets,
361
+ }
362
+ }
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
+ }
418
+ return {
419
+ version: ARCHIVE_VERSION,
420
+ migratedLegacy: Boolean(src.migratedLegacy),
421
+ migratedGlobalAt: Number(src.migratedGlobalAt) || 0,
422
+ migratedAt: Number(src.migratedAt) || 0,
423
+ legacyOwnerProjectKey: str(src.legacyOwnerProjectKey, ''),
424
+ projects,
425
+ sessions,
426
+ global: globalEntry,
427
+ }
428
+ }
429
+
430
+ function writeRegistryRaw(regFile, registry) {
431
+ atomicWriteJson(regFile, normalizeRegistry(registry))
432
+ }
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
+
459
+ function ensureProjectCabinet(targetOpt) {
460
+ const opts = resolveTargetOpts(targetOpt)
461
+ const regFile = cabinetRegistryPath(opts.customSharedBoardFile)
462
+ const legacyFile = legacyArchiveFilePath(opts.customSharedBoardFile)
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'
466
+
467
+ const release = acquireFileLock(regFile)
468
+ try {
469
+ let reg = normalizeRegistry(readJsonSafe(regFile, null))
470
+ let dirty = false
471
+
472
+ // 1. One-time lossless migration from legacy `%DSH_HOME%/chief/archives.json` -> `cabinets/cab-main.json`
473
+ if (!reg.migratedLegacy && fs.existsSync(legacyFile)) {
474
+ const legacyParsed = readJsonSafe(legacyFile, null)
475
+ const cabMainFile = cabinetFilePath('cab-main', opts.customSharedBoardFile)
476
+ if (legacyParsed && !fs.existsSync(cabMainFile)) {
477
+ const normalizedLegacy = normalizeArchiveStore({
478
+ ...legacyParsed,
479
+ cabinetId: 'cab-main',
480
+ cabinetName: '默认主档案柜',
481
+ projectKey,
482
+ })
483
+ atomicWriteJson(cabMainFile, normalizedLegacy)
484
+ }
485
+ if (!reg.projects[projectKey]) {
486
+ const now = Date.now()
487
+ reg.projects[projectKey] = {
488
+ projectKey,
489
+ cwd: opts.cwd,
490
+ activeCabinetId: 'cab-main',
491
+ cabinets: [
492
+ {
493
+ id: 'cab-main',
494
+ name: opts.cwd ? `${path.basename(opts.cwd) || '当前工程'} · 主档案柜` : '默认主档案柜',
495
+ projectKey,
496
+ cwd: opts.cwd,
497
+ createdAt: now,
498
+ updatedAt: now,
499
+ },
500
+ ],
501
+ }
502
+ reg.legacyOwnerProjectKey = projectKey
503
+ }
504
+ reg.migratedLegacy = true
505
+ reg.migratedAt = Date.now()
506
+ dirty = true
507
+ }
508
+
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)
516
+ }
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
+ },
534
+ }
535
+ }
536
+
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
580
+ }
581
+ }
582
+
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,
610
+ cabinetId: selectedCabinet.id,
611
+ cabinetName: selectedCabinet.name,
612
+ cabinetFile: selectedFile,
613
+ registry: reg,
614
+ projectEntry: sessEntry,
615
+ }
616
+ }
617
+
618
+ // 3C. Unbound / blank new conversation: MUST NOT fall back to cab-main or cab-global!
619
+ if (dirty || !fs.existsSync(regFile)) {
620
+ writeRegistryRaw(regFile, reg)
621
+ }
622
+ return {
623
+ scope: 'session',
624
+ vaultScope: 'session',
625
+ unboundSession: true,
626
+ sessionKey: '',
627
+ rootSessionId: '',
628
+ projectKey,
629
+ cabinetId: '',
630
+ cabinetName: '本会话尚未开始(空白新对话)',
631
+ cabinetFile: '',
632
+ registry: reg,
633
+ projectEntry: {
634
+ projectKey,
635
+ activeCabinetId: '',
636
+ cabinets: [],
637
+ },
638
+ }
639
+ } finally {
640
+ release()
641
+ }
642
+ }
643
+
644
+ export function listProjectCabinets(targetOpt) {
645
+ const resolved = ensureProjectCabinet(targetOpt)
646
+ const isGlobal = Boolean(resolved.isSystemGlobalVault || resolved.vaultScope === 'global')
647
+ return {
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 || '',
654
+ projectKey: resolved.projectKey,
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 })),
659
+ }
660
+ }
661
+
662
+ /* ------------------------------------------- Normalization */
663
+
165
664
  function normalizeFolder(raw, index = 0) {
166
665
  if (!raw || typeof raw !== 'object') return null
167
666
  const id = str(raw.id, '').trim().slice(0, 64)
@@ -198,7 +697,6 @@ function normalizeTags(list) {
198
697
  for (const raw of list) {
199
698
  const t = String(raw || '').trim().slice(0, 36)
200
699
  if (!t) continue
201
- // Strip internal routing tag 'anchor' from visual display tags while preserving paperclip='gold'
202
700
  if (t.toLowerCase() === 'anchor') continue
203
701
  const low = t.toLowerCase()
204
702
  if (seen.has(low)) continue
@@ -237,12 +735,18 @@ function normalizeArchiveItem(raw) {
237
735
  )
238
736
 
239
737
  const takenOutSessions = Array.isArray(raw.takenOutSessions)
240
- ? [...new Set(raw.takenOutSessions.map(s => String(s || '').trim()).filter(Boolean))].slice(0, 24)
738
+ ? [...new Set(raw.takenOutSessions.map(s => String(s || '').trim()).filter(Boolean))].slice(0, 32)
241
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 })
242
744
 
243
745
  return {
244
746
  id: str(raw.id, '').trim() || nextId('arch'),
245
747
  sourceNoteId: str(raw.sourceNoteId, '').trim(),
748
+ originId: str(raw.originId, '').trim(),
749
+ originGlobalId: str(raw.originGlobalId, '').trim(),
246
750
  title,
247
751
  summary,
248
752
  folder,
@@ -250,9 +754,11 @@ function normalizeArchiveItem(raw) {
250
754
  tags: normalizeTags(Array.isArray(raw.tags) ? raw.tags : []),
251
755
  cold: raw.cold !== false,
252
756
  takenOutSessions,
757
+ chiefMountedSessions,
253
758
  organizedBy: ['auto', 'chief', 'user'].includes(raw.organizedBy) ? raw.organizedBy : 'auto',
254
759
  points,
255
760
  body,
761
+ contentHash,
256
762
  by: clamp(raw.by || 'agent', 40),
257
763
  sourceSession: str(raw.sourceSession || raw.session, '').trim(),
258
764
  createdAt: Number(raw.createdAt) || Date.now(),
@@ -260,6 +766,21 @@ function normalizeArchiveItem(raw) {
260
766
  }
261
767
  }
262
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
+
263
784
  function normalizeArchiveStore(raw) {
264
785
  const src = raw && typeof raw === 'object' ? raw : {}
265
786
  const folderMap = new Map()
@@ -273,12 +794,12 @@ function normalizeArchiveStore(raw) {
273
794
  })
274
795
  }
275
796
 
797
+ const normalizer = src.isSystemGlobalVault ? normalizeGlobalVaultEntry : normalizeArchiveItem
276
798
  const items = (Array.isArray(src.items) ? src.items : [])
277
- .map(normalizeArchiveItem)
799
+ .map(normalizer)
278
800
  .filter(Boolean)
279
801
  .slice(0, ARCHIVE_CAP)
280
802
 
281
- // Ensure any custom folder referenced by an item exists in `folders`
282
803
  let customIdx = 0
283
804
  for (const item of items) {
284
805
  if (item.folder && !folderMap.has(item.folder)) {
@@ -297,6 +818,12 @@ function normalizeArchiveStore(raw) {
297
818
 
298
819
  return {
299
820
  version: ARCHIVE_VERSION,
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'),
300
827
  migratedSharedAt: Number(src.migratedSharedAt) || 0,
301
828
  updatedAt: Number(src.updatedAt) || Date.now(),
302
829
  folders,
@@ -304,30 +831,248 @@ function normalizeArchiveStore(raw) {
304
831
  }
305
832
  }
306
833
 
307
- export function loadArchiveStore(customSharedBoardFile) {
308
- const file = archiveFilePath(customSharedBoardFile)
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
+
1020
+ export function loadArchiveStore(targetOpt) {
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
+ }
1035
+ const file = resolved.cabinetFile
309
1036
  try {
310
1037
  const st = fs.statSync(file)
311
1038
  if (archiveCache.store && archiveCache.file === file && archiveCache.mtime === st.mtimeMs) {
312
1039
  return archiveCache.store
313
1040
  }
314
1041
  const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
315
- const store = normalizeArchiveStore(parsed)
1042
+ const store = normalizeArchiveStore({
1043
+ ...parsed,
1044
+ cabinetId: resolved.cabinetId,
1045
+ cabinetName: resolved.cabinetName,
1046
+ projectKey: resolved.projectKey,
1047
+ })
316
1048
  archiveCache = { file, mtime: st.mtimeMs, store }
317
1049
  return store
318
1050
  } catch {
319
- const empty = normalizeArchiveStore({})
320
- return empty
1051
+ return normalizeArchiveStore({
1052
+ cabinetId: resolved.cabinetId,
1053
+ cabinetName: resolved.cabinetName,
1054
+ projectKey: resolved.projectKey,
1055
+ })
321
1056
  }
322
1057
  }
323
1058
 
324
- export function saveArchiveStore(store, customSharedBoardFile) {
325
- const file = archiveFilePath(customSharedBoardFile)
326
- const normalized = normalizeArchiveStore({ ...store, updatedAt: Date.now() })
327
- fs.mkdirSync(path.dirname(file), { recursive: true })
328
- const tmp = file + '.' + process.pid + '.' + Date.now().toString(36) + '.tmp'
329
- fs.writeFileSync(tmp, JSON.stringify(normalized, null, 2), 'utf8')
330
- fs.renameSync(tmp, file)
1059
+ export function saveArchiveStore(store, targetOpt) {
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
+ }
1067
+ const file = resolved.cabinetFile
1068
+ const normalized = normalizeArchiveStore({
1069
+ ...store,
1070
+ cabinetId: resolved.cabinetId,
1071
+ cabinetName: resolved.cabinetName,
1072
+ projectKey: resolved.projectKey,
1073
+ updatedAt: Date.now(),
1074
+ })
1075
+ atomicWriteJson(file, normalized)
331
1076
  let mtime = Date.now()
332
1077
  try {
333
1078
  mtime = fs.statSync(file).mtimeMs
@@ -336,12 +1081,30 @@ export function saveArchiveStore(store, customSharedBoardFile) {
336
1081
  return normalized
337
1082
  }
338
1083
 
339
- export function withArchiveLock(customSharedBoardFile, fn) {
340
- const file = archiveFilePath(customSharedBoardFile)
341
- const release = acquireArchiveLock(file)
1084
+ export function withArchiveLock(targetOpt, fn) {
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
+ }
1103
+ const file = resolved.cabinetFile
1104
+ const release = acquireFileLock(file)
342
1105
  invalidateArchiveCache()
343
1106
  try {
344
- return fn(file)
1107
+ return fn(file, resolved)
345
1108
  } finally {
346
1109
  release()
347
1110
  }
@@ -363,7 +1126,6 @@ function firstMeaningfulSentence(text) {
363
1126
  .map(l => l.trim())
364
1127
  .filter(l => l && !/^\|[-:\s|]+\|$/.test(l) && !/^```/.test(l))
365
1128
  if (!lines.length) return ''
366
- // Skip bare markdown heading if next line has substance
367
1129
  const candidate = (/^#{1,4}\s+/.test(lines[0]) && lines[1]) ? lines[1] : lines[0]
368
1130
  const clean = stripMarkdownDecorators(candidate)
369
1131
  const firstClause = clean.split(/[。;!?\n]/)[0] || clean
@@ -410,10 +1172,6 @@ function inferPaperclip(raw, folder) {
410
1172
  return 'silver'
411
1173
  }
412
1174
 
413
- /**
414
- * Parse raw Markdown/prose engineering notes into structured Memory Points (`记忆点 -> 小点记忆`),
415
- * while keeping raw `body` 100% intact on the parent dossier.
416
- */
417
1175
  export function extractStructuredPoints(title, rawBody) {
418
1176
  const body = String(rawBody || '').replace(/\r/g, '').trim()
419
1177
  if (!body) {
@@ -428,8 +1186,6 @@ export function extractStructuredPoints(title, rawBody) {
428
1186
  }
429
1187
 
430
1188
  const lines = body.split('\n')
431
-
432
- // Strategy 1: Markdown Headings (`## ...` or `### ...`)
433
1189
  const headingIndices = []
434
1190
  for (let i = 0; i < lines.length; i += 1) {
435
1191
  if (/^#{2,3}\s+\S/.test(lines[i].trim())) {
@@ -438,10 +1194,7 @@ export function extractStructuredPoints(title, rawBody) {
438
1194
  }
439
1195
  if (headingIndices.length >= 1) {
440
1196
  const points = []
441
- // Capture preface before first ## heading if substantial (excluding redundant `# Title`)
442
- const preLines = lines
443
- .slice(0, headingIndices[0])
444
- .filter(l => !/^#\s+/.test(l.trim()))
1197
+ const preLines = lines.slice(0, headingIndices[0]).filter(l => !/^#\s+/.test(l.trim()))
445
1198
  const preText = preLines.join('\n').trim()
446
1199
  if (preText.length >= 18) {
447
1200
  points.push({
@@ -467,7 +1220,6 @@ export function extractStructuredPoints(title, rawBody) {
467
1220
  if (points.length >= 1) return points.slice(0, POINTS_CAP)
468
1221
  }
469
1222
 
470
- // Strategy 2: Labeled Key-Value Blocks (`包体/源码:...`, `部署态验证:...`, `数据:...`, `坑:...`)
471
1223
  const kvBlocks = []
472
1224
  let currentKv = null
473
1225
  for (const rawLine of lines) {
@@ -509,7 +1261,6 @@ export function extractStructuredPoints(title, rawBody) {
509
1261
  })
510
1262
  }
511
1263
 
512
- // Strategy 3: Paragraph / Numbered-List / Sentence-Cluster Splitting
513
1264
  const paragraphs = body
514
1265
  .split(/\n{2,}/)
515
1266
  .map(p => p.trim())
@@ -527,7 +1278,6 @@ export function extractStructuredPoints(title, rawBody) {
527
1278
  })
528
1279
  }
529
1280
 
530
- // Strategy 4: Dense single-paragraph prose -> split into logical clauses (`。` / `;`) if long
531
1281
  const sentences = body
532
1282
  .split(/(?<=[。!?;])\s*/)
533
1283
  .map(s => s.trim())
@@ -585,35 +1335,31 @@ export function smartParseNoteToDossier(rawNote) {
585
1335
 
586
1336
  /* ------------------------------------ Non-Destructive Bootstrap Migration */
587
1337
 
588
- /**
589
- * One-time lossless migration of legacy shared-board engineering notes into `archives.json`.
590
- * 1. Writes a full backup of `board.json` to `board.pre-archive-backup.json` (never overwrites).
591
- * 2. Converts every existing note on the shared board into a cold-stored structured dossier in `archives.json`.
592
- * 3. Clears those migrated notes off `sharedBoard.notes` so they stop polluting every turn's prompt digest!
593
- */
594
1338
  export function bootstrapArchivesFromSharedBoard({ sharedFile, loadBoard, saveBoard, pushLog }) {
595
1339
  try {
596
1340
  if (!sharedFile || !fs.existsSync(sharedFile)) return { migrated: 0 }
597
- const archFile = archiveFilePath(sharedFile)
598
- if (fs.existsSync(archFile)) {
599
- const existing = loadArchiveStore(sharedFile)
600
- if (existing.migratedSharedAt > 0 || existing.items.length > 0) {
601
- return { migrated: 0 }
602
- }
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)
1346
+ if (existing.migratedSharedAt > 0 && existing.items.length > 0) {
1347
+ return { migrated: 0 }
603
1348
  }
604
1349
 
605
1350
  const sharedBoard = loadBoard(sharedFile)
606
1351
  const legacyNotes = Array.isArray(sharedBoard && sharedBoard.notes) ? sharedBoard.notes : []
607
1352
  if (!legacyNotes.length) {
608
- withArchiveLock(sharedFile, () => {
609
- const empty = loadArchiveStore(sharedFile)
610
- empty.migratedSharedAt = Date.now()
611
- saveArchiveStore(empty, sharedFile)
612
- })
1353
+ if (!existing.migratedSharedAt) {
1354
+ withArchiveLock(storeTarget, () => {
1355
+ const empty = loadArchiveStore(storeTarget)
1356
+ empty.migratedSharedAt = Date.now()
1357
+ saveArchiveStore(empty, storeTarget)
1358
+ })
1359
+ }
613
1360
  return { migrated: 0 }
614
1361
  }
615
1362
 
616
- // 1. Safety backup of `board.json` before touching anything
617
1363
  const backupFile = path.join(path.dirname(sharedFile), 'board.pre-archive-backup.json')
618
1364
  try {
619
1365
  if (!fs.existsSync(backupFile)) {
@@ -621,10 +1367,9 @@ export function bootstrapArchivesFromSharedBoard({ sharedFile, loadBoard, saveBo
621
1367
  }
622
1368
  } catch {}
623
1369
 
624
- // 2. Precipitate all legacy notes into cold archives
625
1370
  let migratedCount = 0
626
- withArchiveLock(sharedFile, () => {
627
- const store = loadArchiveStore(sharedFile)
1371
+ withArchiveLock(storeTarget, () => {
1372
+ const store = loadArchiveStore(storeTarget)
628
1373
  const existingSourceIds = new Set(store.items.map(it => it.sourceNoteId).filter(Boolean))
629
1374
  const existingTitles = new Set(store.items.map(it => it.title))
630
1375
 
@@ -660,16 +1405,15 @@ export function bootstrapArchivesFromSharedBoard({ sharedFile, loadBoard, saveBo
660
1405
  }
661
1406
 
662
1407
  store.migratedSharedAt = Date.now()
663
- saveArchiveStore(store, sharedFile)
1408
+ saveArchiveStore(store, storeTarget)
664
1409
  })
665
1410
 
666
- // 3. Remove migrated long-term notes from shared `board.json` so prompt auto-injection drops to ZERO
667
1411
  if (migratedCount > 0 && typeof saveBoard === 'function') {
668
1412
  sharedBoard.notes = []
669
1413
  if (typeof pushLog === 'function') {
670
1414
  pushLog(
671
1415
  sharedBoard,
672
- `🗄️ 已将 ${migratedCount} 篇历史工程笔记无损沉淀入「档案」柜(默认封存懒加载,不再每轮挤占上下文)`,
1416
+ `🗄️ 已将 ${migratedCount} 篇历史工程笔记无损沉淀入「全局档案柜」(默认封存懒加载,不再每轮挤占上下文)`,
673
1417
  'system',
674
1418
  '',
675
1419
  )
@@ -685,12 +1429,14 @@ export function bootstrapArchivesFromSharedBoard({ sharedFile, loadBoard, saveBo
685
1429
 
686
1430
  /* ------------------------------------------- Lazy-Loading Query & Mutations */
687
1431
 
688
- /** Ultra-lightweight metadata (<80 bytes) for `/snapshot` polling — ZERO archive text/headers! */
689
- export function getArchiveMeta(rootSessionId = '', customSharedBoardFile) {
690
- const store = loadArchiveStore(customSharedBoardFile)
691
- const sid = String(rootSessionId || '').trim()
1432
+ /** Ultra-lightweight metadata (<160 bytes) for `/snapshot` polling — ZERO archive text or precipitated reads! */
1433
+ export function getArchiveMeta(rootSessionId = '', targetOpt) {
1434
+ const effectiveTarget = withRootScope(targetOpt, rootSessionId)
1435
+ const cabInfo = listProjectCabinets(effectiveTarget)
1436
+ const store = loadArchiveStore(effectiveTarget)
1437
+ const sid = cleanRootSessionId(rootSessionId)
692
1438
  const nonEmptyFolders = new Set(store.items.map(it => it.folder).filter(Boolean))
693
- const takenOutCount = sid
1439
+ const takenOutCount = (sid && cabInfo.vaultScope !== 'global' && !cabInfo.unboundSession)
694
1440
  ? store.items.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid)).length
695
1441
  : 0
696
1442
  return {
@@ -698,25 +1444,104 @@ export function getArchiveMeta(rootSessionId = '', customSharedBoardFile) {
698
1444
  folderCount: nonEmptyFolders.size || DEFAULT_ARCHIVE_FOLDERS.length,
699
1445
  takenOutCount,
700
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),
1451
+ projectKey: cabInfo.projectKey,
1452
+ activeCabinetId: cabInfo.activeCabinetId,
1453
+ cabinetCount: cabInfo.cabinets.length,
1454
+ }
1455
+ }
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,
701
1500
  }
702
1501
  }
703
1502
 
704
1503
  /**
705
1504
  * Tier-1 Lazy Load (`GET /api/dsh-chief/archives`):
706
- * Returns folder drawers + slim dossier headers ONLY (no `points` details, no `body`!).
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.
707
1509
  */
708
- export function listArchiveHeaders(rootSessionId = '', opts = {}, customSharedBoardFile) {
709
- const store = loadArchiveStore(customSharedBoardFile)
710
- const sid = String(rootSessionId || '').trim()
1510
+ export function listArchiveHeaders(rootSessionId = '', opts = {}, targetOpt) {
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
1514
+ ? (typeof targetOpt === 'string'
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'
1520
+ const cabInfo = listProjectCabinets(target)
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
+
711
1532
  const needle = String((opts && opts.query) || '').trim().toLowerCase()
712
1533
  const folderFilter = String((opts && opts.folder) || '').trim()
713
1534
  const clipFilter = String((opts && opts.paperclip) || '').trim()
714
1535
 
715
1536
  const clipRank = { gold: 0, silver: 1, copper: 2 }
716
1537
  const sorted = store.items.slice().sort((a, b) => {
717
- const aOut = sid && a.takenOutSessions.includes(sid) ? 0 : 1
718
- const bOut = sid && b.takenOutSessions.includes(sid) ? 0 : 1
719
- 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
720
1545
  const cDiff = (clipRank[a.paperclip] ?? 1) - (clipRank[b.paperclip] ?? 1)
721
1546
  if (cDiff !== 0) return cDiff
722
1547
  return (b.updatedAt || 0) - (a.updatedAt || 0)
@@ -751,41 +1576,74 @@ export function listArchiveHeaders(rootSessionId = '', opts = {}, customSharedBo
751
1576
  goldCount: goldByFolder[f.id] || 0,
752
1577
  }))
753
1578
 
754
- const headers = filtered.map(it => ({
755
- id: it.id,
756
- title: it.title,
757
- summary: it.summary,
758
- folder: it.folder,
759
- paperclip: it.paperclip,
760
- tags: it.tags,
761
- cold: it.cold,
762
- takenOut: Boolean(sid && it.takenOutSessions.includes(sid)),
763
- organizedBy: it.organizedBy,
764
- pointCount: Array.isArray(it.points) ? it.points.length : 0,
765
- pointPreviews: (Array.isArray(it.points) ? it.points : []).slice(0, 4).map(p => p.title),
766
- bodyLength: (it.body || '').length,
767
- updatedAt: it.updatedAt,
768
- createdAt: it.createdAt,
769
- }))
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
+ })
1605
+
1606
+ const includePrecipitated = Boolean(opts && opts.includePrecipitated)
1607
+ const precipitated = includePrecipitated
1608
+ ? listPrecipitatedHeaders(cabInfo.projectKey, sid, target)
1609
+ : undefined
1610
+ const counts = (opts && opts.includeCounts !== false)
1611
+ ? getThreeTierArchiveCounts(sid, (opts && opts.flippedIds) || [], baseTarget)
1612
+ : undefined
770
1613
 
771
1614
  return {
772
1615
  ok: true,
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,
773
1624
  totalCount: store.items.length,
774
- 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,
775
1629
  folders,
776
1630
  items: headers,
1631
+ ...(precipitated !== undefined ? { precipitated } : {}),
1632
+ ...(counts !== undefined ? { counts } : {}),
777
1633
  }
778
1634
  }
779
1635
 
780
- /**
781
- * Tier-2 Lazy Load (`GET /api/dsh-chief/archives/detail?id=...`):
782
- * Loaded ONLY when a user clicks a dossier file or an agent calls `archive.read`.
783
- */
784
- export function getArchiveDetail(idOrTitle = '', rootSessionId = '', customSharedBoardFile) {
1636
+ export function getArchiveDetail(idOrTitle = '', rootSessionId = '', targetOpt) {
785
1637
  const target = String(idOrTitle || '').trim()
786
1638
  if (!target) return { ok: false, error: 'archive id or title required' }
787
- const store = loadArchiveStore(customSharedBoardFile)
788
- 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))
789
1647
  const hit = store.items.find(it => it.id === target)
790
1648
  || store.items.find(it => it.title === target)
791
1649
  || store.items.find(it => it.title.toLowerCase().includes(target.toLowerCase()))
@@ -793,18 +1651,24 @@ export function getArchiveDetail(idOrTitle = '', rootSessionId = '', customShare
793
1651
 
794
1652
  return {
795
1653
  ok: true,
1654
+ vaultScope: isGlobal ? 'global' : (resolved.vaultScope || 'session'),
1655
+ isSystemGlobalVault: isGlobal,
796
1656
  item: {
797
1657
  id: hit.id,
1658
+ originId: hit.originId || '',
1659
+ originGlobalId: hit.originGlobalId || '',
798
1660
  title: hit.title,
799
1661
  summary: hit.summary,
800
1662
  folder: hit.folder,
801
1663
  paperclip: hit.paperclip,
802
1664
  tags: hit.tags,
803
1665
  cold: hit.cold,
804
- 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)),
805
1668
  organizedBy: hit.organizedBy,
806
1669
  points: hit.points,
807
1670
  body: hit.body,
1671
+ contentHash: hit.contentHash || computeEntryContentHash(hit),
808
1672
  by: hit.by,
809
1673
  createdAt: hit.createdAt,
810
1674
  updatedAt: hit.updatedAt,
@@ -813,19 +1677,26 @@ export function getArchiveDetail(idOrTitle = '', rootSessionId = '', customShare
813
1677
  }
814
1678
 
815
1679
  /**
816
- * Strictly returns ONLY dossiers that the user has EXPLICITLY taken out onto the current session desk.
817
- * Sealed/cold dossiers (`takenOutSessions` without `rootSessionId`) NEVER appear here!
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`!
818
1682
  */
819
- export function getTakenOutArchivesForSession(rootSessionId = '', customSharedBoardFile) {
820
- const sid = String(rootSessionId || '').trim()
1683
+ export function getTakenOutArchivesForSession(rootSessionId = '', targetOpt) {
1684
+ const sid = cleanRootSessionId(rootSessionId)
821
1685
  if (!sid) return []
822
- const store = loadArchiveStore(customSharedBoardFile)
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 []
823
1696
  return store.items.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid))
824
1697
  }
825
1698
 
826
- /** On-demand search for `chief_board({ action: "archive.search" })` or Chief explicit lookup. */
827
- export function searchArchives(query = '', opts = {}, customSharedBoardFile) {
828
- const store = loadArchiveStore(customSharedBoardFile)
1699
+ function scoreAndRankArchiveItems(store, query = '', opts = {}) {
829
1700
  const folder = String((opts && opts.folder) || '').trim()
830
1701
  const limit = Math.max(1, Math.min(Number(opts && opts.limit) || 8, 25))
831
1702
  const rawQ = String(query || '').trim().toLowerCase()
@@ -835,7 +1706,7 @@ export function searchArchives(query = '', opts = {}, customSharedBoardFile) {
835
1706
  .filter(Boolean)
836
1707
 
837
1708
  const scored = []
838
- for (const it of store.items) {
1709
+ for (const it of (store && Array.isArray(store.items) ? store.items : [])) {
839
1710
  if (folder && it.folder !== folder) continue
840
1711
  if (!terms.length) {
841
1712
  scored.push({ score: it.paperclip === 'gold' ? 5 : 2, it })
@@ -862,11 +1733,10 @@ export function searchArchives(query = '', opts = {}, customSharedBoardFile) {
862
1733
  }
863
1734
 
864
1735
  scored.sort((a, b) => b.score - a.score || (b.it.updatedAt || 0) - (a.it.updatedAt || 0))
865
- 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]))
866
1737
 
867
1738
  return {
868
- ok: true,
869
- totalArchives: store.items.length,
1739
+ totalArchives: store && Array.isArray(store.items) ? store.items.length : 0,
870
1740
  matchCount: scored.length,
871
1741
  hits: scored.slice(0, limit).map(({ it }) => ({
872
1742
  id: it.id,
@@ -882,14 +1752,242 @@ export function searchArchives(query = '', opts = {}, customSharedBoardFile) {
882
1752
  }
883
1753
  }
884
1754
 
885
- export function mutateArchive(payload = {}, customSharedBoardFile) {
886
- const op = str(payload.op, 'save').trim()
887
- const rootSessionId = str(payload.rootSessionId || payload.session, '').trim()
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
+ }
888
1774
 
889
- return withArchiveLock(customSharedBoardFile, () => {
890
- const store = loadArchiveStore(customSharedBoardFile)
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
+ }
891
1789
 
892
- if (op === 'createFolder' || op === 'saveFolder') {
1790
+ /* ------------------------------------------- Cabinet & Archive Mutations */
1791
+
1792
+ function mutateCabinetRegistry(payload = {}, targetOpt) {
1793
+ const op = str(payload.op, '').trim()
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)
1815
+ const resolvedInit = ensureProjectCabinet({
1816
+ ...opts,
1817
+ cwd: str(payload.cwd, opts.cwd),
1818
+ projectKey: str(payload.projectKey, opts.projectKey),
1819
+ rootSessionId: rootSid,
1820
+ vaultScope,
1821
+ })
1822
+ const regFile = cabinetRegistryPath(opts.customSharedBoardFile)
1823
+ const projectKey = resolvedInit.projectKey
1824
+ const sessKey = normalizeSessionScopeKey(rootSid)
1825
+
1826
+ if (op === 'listCabinets') {
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
+ }
1836
+ }
1837
+
1838
+ const release = acquireFileLock(regFile)
1839
+ try {
1840
+ const reg = normalizeRegistry(readJsonSafe(regFile, null))
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 }
1844
+
1845
+ if (op === 'createCabinet') {
1846
+ const name = clamp(payload.name || payload.label || `工作档案柜 ${container.cabinets.length + 1}`, 40)
1847
+ const dup = container.cabinets.find(c => c.name === name)
1848
+ if (dup) {
1849
+ container.activeCabinetId = dup.id
1850
+ writeRegistryRaw(regFile, reg)
1851
+ invalidateArchiveCache()
1852
+ return {
1853
+ ok: true,
1854
+ ...scopeMeta,
1855
+ cabinet: dup,
1856
+ activeCabinetId: container.activeCabinetId,
1857
+ cabinets: container.cabinets,
1858
+ projectKey,
1859
+ }
1860
+ }
1861
+ const id = nextId('cab')
1862
+ const now = Date.now()
1863
+ const cabMeta = {
1864
+ id,
1865
+ name,
1866
+ projectKey,
1867
+ ...(rootSid && sessKey ? { rootSessionId: rootSid } : {}),
1868
+ cwd: container.cwd || str(payload.cwd, opts.cwd),
1869
+ createdAt: now,
1870
+ updatedAt: now,
1871
+ }
1872
+ const cabFile = cabinetFilePath(id, opts.customSharedBoardFile)
1873
+ atomicWriteJson(cabFile, normalizeArchiveStore({
1874
+ cabinetId: id,
1875
+ cabinetName: name,
1876
+ projectKey,
1877
+ }))
1878
+ container.cabinets.push(cabMeta)
1879
+ container.activeCabinetId = id
1880
+ writeRegistryRaw(regFile, reg)
1881
+ invalidateArchiveCache()
1882
+ return {
1883
+ ok: true,
1884
+ ...scopeMeta,
1885
+ cabinet: cabMeta,
1886
+ activeCabinetId: container.activeCabinetId,
1887
+ cabinets: container.cabinets,
1888
+ projectKey,
1889
+ }
1890
+ }
1891
+
1892
+ if (op === 'switchCabinet') {
1893
+ const targetId = str(payload.cabinetId || payload.id, '').trim()
1894
+ const hit = container.cabinets.find(c => c.id === targetId)
1895
+ if (!hit) return { ok: false, error: '当前范围下未找到目标档案柜:' + targetId }
1896
+ container.activeCabinetId = hit.id
1897
+ hit.updatedAt = Date.now()
1898
+ writeRegistryRaw(regFile, reg)
1899
+ invalidateArchiveCache()
1900
+ return {
1901
+ ok: true,
1902
+ ...scopeMeta,
1903
+ cabinet: hit,
1904
+ activeCabinetId: container.activeCabinetId,
1905
+ cabinets: container.cabinets,
1906
+ projectKey,
1907
+ }
1908
+ }
1909
+
1910
+ if (op === 'renameCabinet') {
1911
+ const targetId = str(payload.cabinetId || payload.id, container.activeCabinetId).trim()
1912
+ const name = clamp(payload.name || payload.label, 40)
1913
+ if (!name) return { ok: false, error: '请输入档案柜新名称' }
1914
+ const hit = container.cabinets.find(c => c.id === targetId)
1915
+ if (!hit) return { ok: false, error: '未找到档案柜:' + targetId }
1916
+ hit.name = name
1917
+ hit.updatedAt = Date.now()
1918
+ writeRegistryRaw(regFile, reg)
1919
+ const cabFile = cabinetFilePath(hit.id, opts.customSharedBoardFile)
1920
+ const cabStore = normalizeArchiveStore(readJsonSafe(cabFile, { cabinetId: hit.id, projectKey }))
1921
+ cabStore.cabinetName = name
1922
+ atomicWriteJson(cabFile, cabStore)
1923
+ invalidateArchiveCache()
1924
+ return {
1925
+ ok: true,
1926
+ ...scopeMeta,
1927
+ cabinet: hit,
1928
+ activeCabinetId: container.activeCabinetId,
1929
+ cabinets: container.cabinets,
1930
+ projectKey,
1931
+ }
1932
+ }
1933
+
1934
+ if (op === 'deleteCabinet') {
1935
+ const targetId = str(payload.cabinetId || payload.id, '').trim()
1936
+ if (container.cabinets.length <= 1) {
1937
+ return { ok: false, error: '每个范围至少需保留一个工作档案柜,不可删除最后一个档案柜' }
1938
+ }
1939
+ const idx = container.cabinets.findIndex(c => c.id === targetId)
1940
+ if (idx < 0) return { ok: false, error: '未找到要删除的档案柜:' + targetId }
1941
+ const [removed] = container.cabinets.splice(idx, 1)
1942
+ if (container.activeCabinetId === removed.id) {
1943
+ container.activeCabinetId = container.cabinets[0].id
1944
+ }
1945
+ writeRegistryRaw(regFile, reg)
1946
+ try {
1947
+ const rmFile = cabinetFilePath(removed.id, opts.customSharedBoardFile)
1948
+ if (fs.existsSync(rmFile)) fs.unlinkSync(rmFile)
1949
+ } catch {}
1950
+ invalidateArchiveCache()
1951
+ return {
1952
+ ok: true,
1953
+ ...scopeMeta,
1954
+ removedId: removed.id,
1955
+ activeCabinetId: container.activeCabinetId,
1956
+ cabinets: container.cabinets,
1957
+ projectKey,
1958
+ }
1959
+ }
1960
+
1961
+ return { ok: false, error: '未知的档案柜操作:' + op }
1962
+ } finally {
1963
+ release()
1964
+ }
1965
+ }
1966
+
1967
+ export function mutateArchive(payload = {}, targetOpt) {
1968
+ const op = str(payload.op, 'save').trim()
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)
1972
+ const effectiveTarget = {
1973
+ ...baseOpts,
1974
+ cwd: str(payload.cwd, baseOpts.cwd),
1975
+ projectKey: str(payload.projectKey, baseOpts.projectKey),
1976
+ cabinetId: str(payload.cabinetId, baseOpts.cabinetId),
1977
+ rootSessionId,
1978
+ vaultScope,
1979
+ }
1980
+
1981
+ if (['listCabinets', 'createCabinet', 'switchCabinet', 'renameCabinet', 'deleteCabinet'].includes(op)) {
1982
+ return mutateCabinetRegistry({ ...payload, vaultScope }, effectiveTarget)
1983
+ }
1984
+
1985
+ return withArchiveLock(effectiveTarget, (_file, resolved) => {
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 }
1988
+ const runOp = () => {
1989
+
1990
+ if (op === 'createFolder' || op === 'saveFolder') {
893
1991
  const rawLabel = clamp(payload.label || payload.folderLabel || payload.folder, 40)
894
1992
  if (!rawLabel) return { ok: false, error: '请输入文件夹抽屉名称' }
895
1993
  const id = str(payload.folderId, '').trim()
@@ -898,7 +1996,7 @@ export function mutateArchive(payload = {}, customSharedBoardFile) {
898
1996
  if (existing) {
899
1997
  if (payload.hint !== undefined) existing.hint = clamp(payload.hint, 100)
900
1998
  if (payload.accent) existing.accent = str(payload.accent, existing.accent).slice(0, 24)
901
- saveArchiveStore(store, customSharedBoardFile)
1999
+ saveArchiveStore(store, lockTarget)
902
2000
  return { ok: true, folder: existing }
903
2001
  }
904
2002
  const created = normalizeFolder({
@@ -909,7 +2007,7 @@ export function mutateArchive(payload = {}, customSharedBoardFile) {
909
2007
  order: 55 + store.folders.length,
910
2008
  })
911
2009
  store.folders.push(created)
912
- saveArchiveStore(store, customSharedBoardFile)
2010
+ saveArchiveStore(store, lockTarget)
913
2011
  return { ok: true, folder: created }
914
2012
  }
915
2013
 
@@ -957,17 +2055,25 @@ export function mutateArchive(payload = {}, customSharedBoardFile) {
957
2055
  140,
958
2056
  )
959
2057
  }
2058
+ existing.contentHash = computeEntryContentHash(existing)
960
2059
  existing.updatedAt = Date.now()
961
- saveArchiveStore(store, customSharedBoardFile)
962
- return { ok: true, item: existing, meta: getArchiveMeta(rootSessionId, customSharedBoardFile) }
2060
+ saveArchiveStore(store, lockTarget)
2061
+ return {
2062
+ ok: true,
2063
+ isSystemGlobalVault: resolved.vaultScope === 'global',
2064
+ item: existing,
2065
+ meta: getArchiveMeta(rootSessionId, lockTarget),
2066
+ }
963
2067
  }
964
2068
 
965
2069
  const rawTitle = clamp(payload.title || '', 180)
966
2070
  if (!rawTitle && !nextBody) {
967
2071
  return { ok: false, error: '新建工程档案需要填写标题或正文内容' }
968
2072
  }
969
- // Dedupe if exact same title already archived and caller opted into upsert
970
- 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
971
2077
  if (sameTitle && payload.upsertByTitle !== false) {
972
2078
  sameTitle.body = nextBody || sameTitle.body
973
2079
  if (payload.folder) sameTitle.folder = str(payload.folder, sameTitle.folder).trim()
@@ -982,9 +2088,16 @@ export function mutateArchive(payload = {}, customSharedBoardFile) {
982
2088
  payload.summary || (sameTitle.points[0] && sameTitle.points[0].cue) || firstMeaningfulSentence(sameTitle.body) || sameTitle.title,
983
2089
  140,
984
2090
  )
2091
+ sameTitle.contentHash = computeEntryContentHash(sameTitle)
985
2092
  sameTitle.updatedAt = Date.now()
986
- saveArchiveStore(store, customSharedBoardFile)
987
- return { ok: true, item: sameTitle, updatedExisting: true, meta: getArchiveMeta(rootSessionId, customSharedBoardFile) }
2093
+ saveArchiveStore(store, lockTarget)
2094
+ return {
2095
+ ok: true,
2096
+ isSystemGlobalVault: resolved.vaultScope === 'global',
2097
+ item: sameTitle,
2098
+ updatedExisting: true,
2099
+ meta: getArchiveMeta(rootSessionId, lockTarget),
2100
+ }
988
2101
  }
989
2102
 
990
2103
  const parsed = smartParseNoteToDossier({
@@ -994,27 +2107,40 @@ export function mutateArchive(payload = {}, customSharedBoardFile) {
994
2107
  paperclip: payload.paperclip,
995
2108
  tags: Array.isArray(payload.tags) ? payload.tags : (typeof payload.tags === 'string' ? payload.tags.split(/[,,]/) : []),
996
2109
  })
997
- const created = normalizeArchiveItem({
998
- id: nextId('arch'),
2110
+ const baseCreated = {
2111
+ id: nextId(resolved.vaultScope === 'global' ? 'glob' : 'arch'),
999
2112
  sourceNoteId: str(payload.sourceNoteId, ''),
2113
+ originId: str(payload.originId, ''),
2114
+ originGlobalId: str(payload.originGlobalId, ''),
1000
2115
  title: parsed.title,
1001
2116
  summary: payload.summary || parsed.summary,
1002
2117
  folder: payload.folder || parsed.folder,
1003
2118
  paperclip: payload.paperclip || parsed.paperclip,
1004
2119
  tags: Array.isArray(payload.tags) ? payload.tags : (typeof payload.tags === 'string' ? payload.tags.split(/[,,]/) : []),
1005
2120
  cold: true,
1006
- takenOutSessions: payload.takeOutNow && rootSessionId ? [rootSessionId] : [],
1007
- organizedBy: Array.isArray(payload.points) && payload.points.length ? 'user' : 'auto',
2121
+ takenOutSessions: (payload.takeOutNow || payload.takeOut) && rootSessionId && resolved.vaultScope !== 'global' ? [rootSessionId] : [],
2122
+ chiefMountedSessions: resolved.vaultScope === 'global' && payload.mountChief && rootSessionId ? [rootSessionId] : [],
2123
+ organizedBy: ['auto', 'chief', 'user'].includes(payload.organizedBy)
2124
+ ? payload.organizedBy
2125
+ : (Array.isArray(payload.points) && payload.points.length ? 'user' : 'auto'),
1008
2126
  points: Array.isArray(payload.points) && payload.points.length ? payload.points : parsed.points,
1009
2127
  body: nextBody,
1010
2128
  by: payload.by || 'user',
1011
2129
  sourceSession: rootSessionId,
1012
2130
  createdAt: Date.now(),
1013
2131
  updatedAt: Date.now(),
1014
- })
2132
+ }
2133
+ const created = resolved.vaultScope === 'global'
2134
+ ? normalizeGlobalVaultEntry(baseCreated)
2135
+ : normalizeArchiveItem(baseCreated)
1015
2136
  store.items.unshift(created)
1016
- saveArchiveStore(store, customSharedBoardFile)
1017
- return { ok: true, item: created, meta: getArchiveMeta(rootSessionId, customSharedBoardFile) }
2137
+ saveArchiveStore(store, lockTarget)
2138
+ return {
2139
+ ok: true,
2140
+ isSystemGlobalVault: resolved.vaultScope === 'global',
2141
+ item: created,
2142
+ meta: getArchiveMeta(rootSessionId, lockTarget),
2143
+ }
1018
2144
  }
1019
2145
 
1020
2146
  if (op === 'delete' || op === 'remove') {
@@ -1022,26 +2148,66 @@ export function mutateArchive(payload = {}, customSharedBoardFile) {
1022
2148
  const idx = store.items.findIndex(it => it.id === id)
1023
2149
  if (idx < 0) return { ok: false, error: '未找到要删除的档案:' + id }
1024
2150
  const [removed] = store.items.splice(idx, 1)
1025
- saveArchiveStore(store, customSharedBoardFile)
1026
- return { ok: true, removedId: removed.id, title: removed.title, meta: getArchiveMeta(rootSessionId, customSharedBoardFile) }
2151
+ saveArchiveStore(store, lockTarget)
2152
+ return { ok: true, removedId: removed.id, title: removed.title, meta: getArchiveMeta(rootSessionId, lockTarget) }
2153
+ }
2154
+
2155
+ if (op === 'clearByIds' || op === 'clearFolder') {
2156
+ const ids = new Set(Array.isArray(payload.ids) ? payload.ids.map(x => String(x || '').trim()).filter(Boolean) : [])
2157
+ const folder = str(payload.folder, '').trim()
2158
+ const before = store.items.length
2159
+ store.items = store.items.filter((it) => {
2160
+ if (op === 'clearFolder') return it.folder !== folder
2161
+ return !ids.has(it.id)
2162
+ })
2163
+ const removedCount = before - store.items.length
2164
+ if (removedCount > 0) saveArchiveStore(store, lockTarget)
2165
+ return { ok: true, removedCount, meta: getArchiveMeta(rootSessionId, lockTarget) }
2166
+ }
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
+ }
1027
2191
  }
1028
2192
 
1029
2193
  if (op === 'takeOut' || op === 'putBack') {
1030
2194
  const id = str(payload.archiveId || payload.id, '').trim()
1031
- if (!rootSessionId) return { ok: false, error: '当前未绑定对话会话,无法取出挂到桌面' }
2195
+ if (!rootSessionId) return { ok: false, error: '当前未绑定对话会话,无法摆到桌面备选' }
1032
2196
  const item = store.items.find(it => it.id === id)
1033
2197
  if (!item) return { ok: false, error: '未找到该工程档案:' + id }
1034
2198
  const set = new Set(item.takenOutSessions || [])
1035
2199
  if (op === 'takeOut') set.add(rootSessionId)
1036
2200
  else set.delete(rootSessionId)
1037
2201
  item.takenOutSessions = [...set]
1038
- saveArchiveStore(store, customSharedBoardFile)
2202
+ saveArchiveStore(store, lockTarget)
1039
2203
  return {
1040
2204
  ok: true,
1041
2205
  id: item.id,
1042
2206
  title: item.title,
1043
2207
  takenOut: op === 'takeOut',
1044
- meta: getArchiveMeta(rootSessionId, customSharedBoardFile),
2208
+ isSystemGlobalVault: resolved.vaultScope === 'global',
2209
+ counts: getThreeTierArchiveCounts(rootSessionId, [], lockTarget),
2210
+ meta: getArchiveMeta(rootSessionId, lockTarget),
1045
2211
  }
1046
2212
  }
1047
2213
 
@@ -1057,7 +2223,7 @@ export function mutateArchive(payload = {}, customSharedBoardFile) {
1057
2223
  item.paperclip = order[nextIdx]
1058
2224
  }
1059
2225
  item.updatedAt = Date.now()
1060
- saveArchiveStore(store, customSharedBoardFile)
2226
+ saveArchiveStore(store, lockTarget)
1061
2227
  return { ok: true, id: item.id, paperclip: item.paperclip }
1062
2228
  }
1063
2229
 
@@ -1072,22 +2238,150 @@ export function mutateArchive(payload = {}, customSharedBoardFile) {
1072
2238
  store.folders.push(normalizeFolder({ id: folder, label: payload.folderLabel, order: 58 }))
1073
2239
  }
1074
2240
  item.updatedAt = Date.now()
1075
- saveArchiveStore(store, customSharedBoardFile)
2241
+ saveArchiveStore(store, lockTarget)
1076
2242
  return { ok: true, id: item.id, folder: item.folder }
1077
2243
  }
1078
2244
 
1079
- return { ok: false, error: '未知的档案操作:' + op }
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
+
2364
+ return { ok: false, error: '未知的档案操作:' + op }
2365
+ }
2366
+ const opRes = runOp()
2367
+ return (opRes && opRes.ok && !opRes.cabinetId && !opRes.isSystemGlobalVault)
2368
+ ? { cabinetId: resolved.cabinetId, isSystemGlobalVault: resolved.vaultScope === 'global', ...opRes }
2369
+ : opRes
1080
2370
  })
1081
2371
  }
1082
2372
 
1083
- /**
1084
- * Batch-apply Chief LLM organization results (`folder`, `folderLabel`, `paperclip`, `summary`, `tags`, `points`)
1085
- * while 100% preserving each dossier's raw `body` lossless!
1086
- */
1087
- export function applyChiefArchiveCurations(curations = [], newFolders = [], customSharedBoardFile) {
2373
+ export function applyChiefArchiveCurations(curations = [], newFolders = [], targetOpt) {
1088
2374
  if (!Array.isArray(curations) || !curations.length) return { updatedCount: 0 }
1089
- return withArchiveLock(customSharedBoardFile, () => {
1090
- const store = loadArchiveStore(customSharedBoardFile)
2375
+ return withArchiveLock(targetOpt, (_file, resolved) => {
2376
+ const base = resolveTargetOpts(targetOpt)
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
+ }
2384
+ const store = loadArchiveStore(lockTarget)
1091
2385
  if (Array.isArray(newFolders)) {
1092
2386
  newFolders.forEach((nf, idx) => {
1093
2387
  if (!nf || !nf.id) return
@@ -1143,15 +2437,555 @@ export function applyChiefArchiveCurations(curations = [], newFolders = [], cust
1143
2437
  target.points = validPts
1144
2438
  }
1145
2439
  }
1146
- // Raw `target.body` is NEVER overwritten by Chief curation — 100% lossless!
1147
2440
  target.organizedBy = 'chief'
1148
2441
  target.updatedAt = Date.now()
1149
2442
  updatedCount += 1
1150
2443
  }
1151
2444
 
1152
2445
  if (updatedCount > 0) {
1153
- saveArchiveStore(store, customSharedBoardFile)
2446
+ saveArchiveStore(store, lockTarget)
1154
2447
  }
1155
2448
  return { updatedCount }
1156
2449
  })
1157
2450
  }
2451
+
2452
+ /* --------------------- Cross-Session Handoff Archive Copy (Never Precipitated) */
2453
+
2454
+ /**
2455
+ * Transfers ONLY active cabinet dossiers selected by `policy`:
2456
+ * - `'none'`: zero transfers
2457
+ * - `'mounted'`: only dossiers explicitly taken out on `fromRootSessionId` (`takenOutSessions`)
2458
+ * - `'drawer'`: dossiers inside `drawer` folder in source cabinet
2459
+ * - `'all'`: all dossiers in source active cabinet
2460
+ * Strictly NEVER reads or transfers `precipitated/<projectKey>.json`!
2461
+ */
2462
+ export function copyArchivesBetweenSessionsOrCabinets({
2463
+ fromRootSessionId = '',
2464
+ toRootSessionId = '',
2465
+ fromCwd = '',
2466
+ toCwd = '',
2467
+ fromCabinetId = '',
2468
+ toCabinetId = '',
2469
+ policy = 'none',
2470
+ drawer = '',
2471
+ customSharedBoardFile = '',
2472
+ }) {
2473
+ const mode = ['none', 'mounted', 'drawer', 'all'].includes(policy) ? policy : 'none'
2474
+ const fromSid = str(fromRootSessionId, '').trim()
2475
+ const toSid = str(toRootSessionId, '').trim()
2476
+ if (mode === 'none' || !fromSid || !toSid) {
2477
+ return { ok: true, policy: mode, transferredCount: 0, mountedCount: 0 }
2478
+ }
2479
+
2480
+ const srcTarget = {
2481
+ customSharedBoardFile,
2482
+ cwd: fromCwd,
2483
+ cabinetId: fromCabinetId,
2484
+ rootSessionId: fromSid,
2485
+ vaultScope: 'session',
2486
+ }
2487
+ const dstTarget = {
2488
+ customSharedBoardFile,
2489
+ cwd: toCwd || fromCwd,
2490
+ cabinetId: toCabinetId,
2491
+ rootSessionId: toSid,
2492
+ vaultScope: 'session',
2493
+ }
2494
+
2495
+ const srcResolved = ensureProjectCabinet(srcTarget)
2496
+ const dstResolved = ensureProjectCabinet(dstTarget)
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' })
2501
+
2502
+ let selected = []
2503
+ if (mode === 'mounted') {
2504
+ selected = srcStore.items.filter(it => fromSid && Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(fromSid))
2505
+ } else if (mode === 'drawer') {
2506
+ const fId = str(drawer, '').trim()
2507
+ selected = srcStore.items.filter(it => !fId || it.folder === fId)
2508
+ } else if (mode === 'all') {
2509
+ selected = srcStore.items.slice()
2510
+ }
2511
+
2512
+ if (!selected.length) {
2513
+ return {
2514
+ ok: true,
2515
+ policy: mode,
2516
+ sameCabinet: srcResolved.cabinetId === dstResolved.cabinetId,
2517
+ targetCabinetId: dstResolved.cabinetId,
2518
+ transferredCount: 0,
2519
+ mountedCount: 0,
2520
+ }
2521
+ }
2522
+
2523
+ // Same cabinet: update `takenOutSessions` on selected items directly (mount mounted items or selected drawer items for target)
2524
+ if (srcResolved.cabinetId === dstResolved.cabinetId) {
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' })
2527
+ let mountedCount = 0
2528
+ const selectedIds = new Set(selected.map(s => s.id))
2529
+ for (const it of store.items) {
2530
+ if (!selectedIds.has(it.id)) continue
2531
+ const shouldMount = mode === 'mounted' || (fromSid && Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(fromSid)) || mode === 'drawer'
2532
+ if (shouldMount) {
2533
+ const set = new Set(it.takenOutSessions || [])
2534
+ if (!set.has(toSid)) {
2535
+ set.add(toSid)
2536
+ it.takenOutSessions = [...set]
2537
+ mountedCount += 1
2538
+ }
2539
+ }
2540
+ }
2541
+ if (mountedCount > 0) {
2542
+ saveArchiveStore(store, { customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey, rootSessionId: toSid, vaultScope: 'session' })
2543
+ }
2544
+ return {
2545
+ ok: true,
2546
+ policy: mode,
2547
+ sameCabinet: true,
2548
+ targetCabinetId: dstResolved.cabinetId,
2549
+ transferredCount: selected.length,
2550
+ mountedCount,
2551
+ }
2552
+ })
2553
+ }
2554
+
2555
+ // Different cabinets: copy folders metadata & dossiers into destination cabinet
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' })
2558
+ const folderIds = new Set(dstStore.folders.map(f => f.id))
2559
+ for (const f of srcStore.folders) {
2560
+ if (!folderIds.has(f.id)) {
2561
+ dstStore.folders.push({ ...f })
2562
+ folderIds.add(f.id)
2563
+ }
2564
+ }
2565
+ const existingTitles = new Map(dstStore.items.map(it => [it.title, it]))
2566
+ let copiedCount = 0
2567
+ let mountedCount = 0
2568
+ for (const srcItem of selected) {
2569
+ const shouldMount = mode === 'mounted' || (fromSid && srcItem.takenOutSessions.includes(fromSid))
2570
+ const dup = existingTitles.get(srcItem.title)
2571
+ if (dup) {
2572
+ if (shouldMount && !dup.takenOutSessions.includes(toSid)) {
2573
+ dup.takenOutSessions.push(toSid)
2574
+ mountedCount += 1
2575
+ }
2576
+ dup.updatedAt = Date.now()
2577
+ copiedCount += 1
2578
+ continue
2579
+ }
2580
+ const cloned = normalizeArchiveItem({
2581
+ ...srcItem,
2582
+ id: nextId('arch'),
2583
+ takenOutSessions: shouldMount ? [toSid] : [],
2584
+ updatedAt: Date.now(),
2585
+ })
2586
+ if (cloned) {
2587
+ dstStore.items.unshift(cloned)
2588
+ copiedCount += 1
2589
+ if (shouldMount) mountedCount += 1
2590
+ }
2591
+ }
2592
+ if (copiedCount > 0 || mountedCount > 0) {
2593
+ saveArchiveStore(dstStore, { customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey, rootSessionId: toSid, vaultScope: 'session' })
2594
+ }
2595
+ return {
2596
+ ok: true,
2597
+ policy: mode,
2598
+ sameCabinet: false,
2599
+ targetCabinetId: dstResolved.cabinetId,
2600
+ transferredCount: copiedCount,
2601
+ mountedCount,
2602
+ }
2603
+ })
2604
+ }
2605
+
2606
+ /* --------------------- Precipitated Cross-Session Vault (STRICTLY 0 AUTO-READ) */
2607
+
2608
+ function normalizePrecipitatedEntry(raw) {
2609
+ if (!raw || typeof raw !== 'object') return null
2610
+ const title = clamp(raw.title || '', 180)
2611
+ const rawBody = cleanMultiline(raw.rawBody || raw.body || '', 30000)
2612
+ if (!title && !rawBody) return null
2613
+ const points = (Array.isArray(raw.points) ? raw.points : [])
2614
+ .map((p, idx) => normalizePoint(p, idx))
2615
+ .filter(Boolean)
2616
+ .slice(0, POINTS_CAP)
2617
+ const validCategories = ['coords', 'incidents', 'contracts', 'ops', 'plans', 'architecture', 'env', 'contract', 'troubleshooting', 'workflow', 'general']
2618
+ const category = validCategories.includes(raw.category) ? raw.category : 'general'
2619
+ const flippedOutSessions = Array.isArray(raw.flippedOutSessions)
2620
+ ? [...new Set(raw.flippedOutSessions.map(s => str(s, '').trim()).filter(Boolean))].slice(0, 32)
2621
+ : []
2622
+
2623
+ return {
2624
+ id: str(raw.id, '').trim() || nextId('prec'),
2625
+ title: title || '跨会话可复用工程经验',
2626
+ category,
2627
+ summary: clamp(raw.summary || (points[0] && points[0].cue) || firstMeaningfulSentence(rawBody) || title, 180),
2628
+ points: points.length ? points : extractStructuredPoints(title, rawBody),
2629
+ rawBody,
2630
+ purified: raw.purified !== false,
2631
+ sourceCabinetId: str(raw.sourceCabinetId || raw.sourceCabinet, '').trim(),
2632
+ sourceDrawer: str(raw.sourceDrawer, '').trim(),
2633
+ sourceSession: str(raw.sourceSession, '').trim(),
2634
+ sourceTitles: Array.isArray(raw.sourceTitles) ? raw.sourceTitles.map(t => clamp(t, 80)).slice(0, 40) : [],
2635
+ tags: normalizeTags(Array.isArray(raw.tags) ? raw.tags : []),
2636
+ flippedOutSessions,
2637
+ by: clamp(raw.by || 'chief', 40),
2638
+ createdAt: Number(raw.createdAt) || Date.now(),
2639
+ updatedAt: Number(raw.updatedAt) || Number(raw.createdAt) || Date.now(),
2640
+ }
2641
+ }
2642
+
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)
2688
+ if (!fs.existsSync(file)) {
2689
+ return {
2690
+ version: 1,
2691
+ projectKey: 'global',
2692
+ updatedAt: 0,
2693
+ items: [],
2694
+ }
2695
+ }
2696
+ const parsed = readJsonSafe(file, null)
2697
+ const items = (Array.isArray(parsed && parsed.items) ? parsed.items : [])
2698
+ .map(normalizePrecipitatedEntry)
2699
+ .filter(Boolean)
2700
+ .slice(0, PRECIPITATED_CAP)
2701
+ return {
2702
+ version: 1,
2703
+ projectKey: 'global',
2704
+ updatedAt: Number(parsed && parsed.updatedAt) || Date.now(),
2705
+ items,
2706
+ }
2707
+ }
2708
+
2709
+ function savePrecipitatedStoreRaw(_projectKey = 'proj-default', store, targetOpt) {
2710
+ const file = globalPrecipitatedFilePath(targetOpt)
2711
+ const normalized = {
2712
+ version: 1,
2713
+ projectKey: 'global',
2714
+ updatedAt: Date.now(),
2715
+ items: (Array.isArray(store && store.items) ? store.items : [])
2716
+ .map(normalizePrecipitatedEntry)
2717
+ .filter(Boolean)
2718
+ .slice(0, PRECIPITATED_CAP),
2719
+ }
2720
+ atomicWriteJson(file, normalized)
2721
+ return normalized
2722
+ }
2723
+
2724
+ /**
2725
+ * STRICT 0-TOKEN GUARD:
2726
+ * Unless `hasExplicitFlipOutFlag === true` (tracked independently per session in `chief-state.json`
2727
+ * `ws.flippedPrecipitatedIds`), this function returns `[]` IMMEDIATELY without touching disk at all!
2728
+ */
2729
+ export function getFlippedOutPrecipitatedForSession(projectKey = 'proj-default', rootSessionId = '', hasExplicitFlipOutFlag = false, targetOpt) {
2730
+ if (!hasExplicitFlipOutFlag || !str(rootSessionId, '').trim()) {
2731
+ return []
2732
+ }
2733
+ const sid = str(rootSessionId, '').trim()
2734
+ const store = loadPrecipitatedStoreRaw(projectKey, targetOpt)
2735
+ return store.items.filter(it => Array.isArray(it.flippedOutSessions) && it.flippedOutSessions.includes(sid))
2736
+ }
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
+
2865
+ /** Listed ONLY when user opens the `档案` tab in Web UI (`GET /api/dsh-chief/archives`). */
2866
+ export function listPrecipitatedHeaders(projectKey = 'proj-default', rootSessionId = '', targetOpt) {
2867
+ const file = ensureGlobalPrecipitatedVault(targetOpt)
2868
+ if (!fs.existsSync(file)) return []
2869
+ const sid = str(rootSessionId, '').trim()
2870
+ const store = loadPrecipitatedStoreRaw(projectKey, targetOpt)
2871
+ return store.items.map(it => ({
2872
+ id: it.id,
2873
+ title: it.title,
2874
+ category: it.category,
2875
+ summary: it.summary,
2876
+ purified: it.purified,
2877
+ sourceCabinetId: it.sourceCabinetId,
2878
+ sourceDrawer: it.sourceDrawer,
2879
+ sourceTitles: it.sourceTitles,
2880
+ tags: it.tags,
2881
+ pointCount: Array.isArray(it.points) ? it.points.length : 0,
2882
+ flippedOut: Boolean(sid && Array.isArray(it.flippedOutSessions) && it.flippedOutSessions.includes(sid)),
2883
+ points: (it.points || []).map(p => ({ id: p.id, title: p.title, cue: p.cue, detail: p.detail })),
2884
+ createdAt: it.createdAt,
2885
+ updatedAt: it.updatedAt,
2886
+ }))
2887
+ }
2888
+
2889
+ export function getPrecipitatedDetail(projectKey = 'proj-default', id = '', rootSessionId = '', targetOpt) {
2890
+ const target = str(id, '').trim()
2891
+ if (!target) return { ok: false, error: 'missing precipitated id' }
2892
+ const store = loadPrecipitatedStoreRaw(projectKey, targetOpt)
2893
+ const hit = store.items.find(it => it.id === target)
2894
+ if (!hit) return { ok: false, error: '未找到沉淀经验条目:' + target }
2895
+ const sid = str(rootSessionId, '').trim()
2896
+ return {
2897
+ ok: true,
2898
+ item: {
2899
+ ...hit,
2900
+ flippedOut: Boolean(sid && hit.flippedOutSessions.includes(sid)),
2901
+ },
2902
+ }
2903
+ }
2904
+
2905
+ export function savePrecipitatedEntry(projectKey = 'proj-default', entry = {}, targetOpt) {
2906
+ const resolvedKey = resolveProjectKey(projectKey)
2907
+ const file = globalPrecipitatedFilePath(targetOpt)
2908
+ const release = acquireFileLock(file)
2909
+ try {
2910
+ const store = loadPrecipitatedStoreRaw(resolvedKey, targetOpt)
2911
+ const bodyCheck = cleanMultiline(entry.rawBody || entry.body || '', 30000)
2912
+ if (SECRET_PATTERN.test(bodyCheck)) {
2913
+ return { ok: false, error: '沉淀内容疑似包含敏感密钥或私密凭据,已拒绝写入冷库' }
2914
+ }
2915
+ const existing = entry.id ? store.items.find(it => it.id === entry.id) : null
2916
+ if (existing) {
2917
+ const updated = normalizePrecipitatedEntry({ ...existing, ...entry, id: existing.id, updatedAt: Date.now() })
2918
+ Object.assign(existing, updated)
2919
+ savePrecipitatedStoreRaw(resolvedKey, store, targetOpt)
2920
+ return { ok: true, item: existing, entry: existing, file }
2921
+ }
2922
+ const created = normalizePrecipitatedEntry({
2923
+ ...entry,
2924
+ id: str(entry.id, '').trim() || nextId('prec'),
2925
+ flippedOutSessions: [], // Strictly cold-isolated by default!
2926
+ createdAt: Date.now(),
2927
+ updatedAt: Date.now(),
2928
+ })
2929
+ if (!created) return { ok: false, error: '无法写入空的沉淀经验' }
2930
+ store.items.unshift(created)
2931
+ savePrecipitatedStoreRaw(resolvedKey, store, targetOpt)
2932
+ return { ok: true, item: created, entry: created, file }
2933
+ } finally {
2934
+ release()
2935
+ }
2936
+ }
2937
+
2938
+ export function mutatePrecipitated(projectKey = 'proj-default', payload = {}, targetOpt) {
2939
+ const resolvedKey = resolveProjectKey(projectKey || payload.projectKey || payload.cwd || 'proj-default')
2940
+ const file = globalPrecipitatedFilePath(targetOpt)
2941
+ const op = str(payload.op, '').trim()
2942
+ const sid = str(payload.rootSessionId || payload.session, '').trim()
2943
+ const id = str(payload.precipitatedId || payload.id, '').trim()
2944
+
2945
+ const release = acquireFileLock(file)
2946
+ try {
2947
+ const store = loadPrecipitatedStoreRaw(resolvedKey, targetOpt)
2948
+
2949
+ if (op === 'flipOut' || op === 'sealBack') {
2950
+ if (!sid) return { ok: false, error: '当前未绑定对话会话' }
2951
+ const item = store.items.find(it => it.id === id)
2952
+ if (!item) return { ok: false, error: '未找到沉淀经验:' + id }
2953
+ const set = new Set(item.flippedOutSessions || [])
2954
+ if (op === 'flipOut') set.add(sid)
2955
+ else set.delete(sid)
2956
+ item.flippedOutSessions = [...set]
2957
+ item.updatedAt = Date.now()
2958
+ savePrecipitatedStoreRaw(resolvedKey, store, targetOpt)
2959
+ return {
2960
+ ok: true,
2961
+ id: item.id,
2962
+ title: item.title,
2963
+ flippedOut: op === 'flipOut',
2964
+ flippedIdsForSession: store.items
2965
+ .filter(it => it.flippedOutSessions.includes(sid))
2966
+ .map(it => it.id),
2967
+ }
2968
+ }
2969
+
2970
+ if (op === 'deletePrecipitated') {
2971
+ const idx = store.items.findIndex(it => it.id === id)
2972
+ if (idx < 0) return { ok: false, error: '未找到沉淀经验:' + id }
2973
+ const [removed] = store.items.splice(idx, 1)
2974
+ savePrecipitatedStoreRaw(resolvedKey, store, targetOpt)
2975
+ return { ok: true, removedId: removed.id, title: removed.title }
2976
+ }
2977
+
2978
+ if (op === 'updatePrecipitated') {
2979
+ const item = store.items.find(it => it.id === id)
2980
+ if (!item) return { ok: false, error: '未找到沉淀经验:' + id }
2981
+ const next = normalizePrecipitatedEntry({ ...item, ...payload, id: item.id, updatedAt: Date.now() })
2982
+ Object.assign(item, next)
2983
+ savePrecipitatedStoreRaw(resolvedKey, store, targetOpt)
2984
+ return { ok: true, item }
2985
+ }
2986
+
2987
+ return { ok: false, error: '未知的沉淀库操作:' + op }
2988
+ } finally {
2989
+ release()
2990
+ }
2991
+ }