dsh-chief 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/archives.js CHANGED
@@ -1,2991 +1,63 @@
1
- /**
2
- * Engineering Memory Filing Cabinet v2 (单工程多档案柜 + 跨会话沉淀冷库 · 物理零偷读)
3
- *
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!)
9
- *
10
- * Core Contracts:
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!
21
- */
22
-
23
- import crypto from 'node:crypto'
24
- import fs from 'node:fs'
25
- import os from 'node:os'
26
- import path from 'node:path'
27
-
28
- const ARCHIVE_VERSION = 2
29
- const ARCHIVE_CAP = 500
30
- const POINTS_CAP = 32
31
- const PRECIPITATED_CAP = 300
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-----)/
33
-
34
- export const DEFAULT_ARCHIVE_FOLDERS = [
35
- {
36
- id: 'coords',
37
- label: '工程坐标与部署锚点',
38
- hint: '源码路径、热更口令、端口、部署验证命令与核心坐标',
39
- accent: '#f59e0b',
40
- order: 10,
41
- },
42
- {
43
- id: 'incidents',
44
- label: '排障实录与硬事实',
45
- hint: '线上/本地故障症状、根因定位、踩坑教训与修复闭环',
46
- accent: '#ef4444',
47
- order: 20,
48
- },
49
- {
50
- id: 'contracts',
51
- label: '架构契约与方法论',
52
- hint: '接口契约、参数宽容、截断交代、自检断言与工程纪律',
53
- accent: '#0a84ff',
54
- order: 30,
55
- },
56
- {
57
- id: 'ops',
58
- label: '运维链路与机器环境',
59
- hint: '本机环境硬事实、服务器代理链路、容器与外部服务手册',
60
- accent: '#10b981',
61
- order: 40,
62
- },
63
- {
64
- id: 'plans',
65
- label: '阶段蓝图与归档计划',
66
- hint: '官方能力对照、阶段性历史计划存档与里程碑复盘',
67
- accent: '#8b5cf6',
68
- order: 50,
69
- },
70
- {
71
- id: 'inbox',
72
- label: '待分拣工作便签',
73
- hint: '新近沉淀或尚未归类的工程记录,可随时请参谋长整理收纳',
74
- accent: '#64748b',
75
- order: 60,
76
- },
77
- ]
78
-
79
- const DEFAULT_FOLDER_MAP = new Map(DEFAULT_ARCHIVE_FOLDERS.map(f => [f.id, f]))
80
-
81
- let seq = 0
82
- function nextId(prefix) {
83
- seq = (seq + 1) % 1000000
84
- return prefix + '-' + Date.now().toString(36) + '-' + seq.toString(36)
85
- }
86
-
87
- function str(v, fb = '') {
88
- return typeof v === 'string' ? v : fb
89
- }
90
-
91
- function clamp(v, max) {
92
- const clean = String(v == null ? '' : v).replace(/\s+/g, ' ').trim()
93
- if (clean.length <= max) return clean
94
- return clean.slice(0, Math.max(0, max - 1)) + '…'
95
- }
96
-
97
- function cleanMultiline(v, max) {
98
- const text = String(v == null ? '' : v).replace(/\r/g, '').trim()
99
- if (text.length <= max) return text
100
- return text.slice(0, Math.max(0, max - 1)) + '…'
101
- }
102
-
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)
146
- }
147
- const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
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)
257
- }
258
-
259
- /* ----------------------------------------------------------- Lock & Storage */
260
-
261
- const heldArchiveLocks = new Set()
262
- const lockSleeper = new Int32Array(new SharedArrayBuffer(4))
263
-
264
- function sleepSync(ms) {
265
- try {
266
- Atomics.wait(lockSleeper, 0, 0, ms)
267
- } catch {}
268
- }
269
-
270
- function acquireFileLock(file) {
271
- if (heldArchiveLocks.has(file)) return () => {}
272
- const lock = file + '.lock'
273
- try {
274
- fs.mkdirSync(path.dirname(lock), { recursive: true })
275
- } catch {}
276
- const deadline = Date.now() + 3000
277
- for (;;) {
278
- try {
279
- const fd = fs.openSync(lock, 'wx')
280
- try {
281
- fs.writeSync(fd, String(process.pid))
282
- } catch {}
283
- fs.closeSync(fd)
284
- heldArchiveLocks.add(file)
285
- return () => {
286
- heldArchiveLocks.delete(file)
287
- try {
288
- fs.unlinkSync(lock)
289
- } catch {}
290
- }
291
- } catch (err) {
292
- if (!err || err.code !== 'EEXIST' || Date.now() >= deadline) {
293
- try {
294
- if (Date.now() >= deadline) fs.unlinkSync(lock)
295
- } catch {}
296
- heldArchiveLocks.add(file)
297
- return () => heldArchiveLocks.delete(file)
298
- }
299
- try {
300
- const st = fs.statSync(lock)
301
- if (Date.now() - st.mtimeMs > 10000) {
302
- fs.unlinkSync(lock)
303
- continue
304
- }
305
- } catch {}
306
- sleepSync(3)
307
- }
308
- }
309
- }
310
-
311
- let archiveCache = { file: '', mtime: -1, store: null }
312
-
313
- export function invalidateArchiveCache() {
314
- archiveCache = { file: '', mtime: -1, store: null }
315
- }
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
-
664
- function normalizeFolder(raw, index = 0) {
665
- if (!raw || typeof raw !== 'object') return null
666
- const id = str(raw.id, '').trim().slice(0, 64)
667
- if (!id) return null
668
- const preset = DEFAULT_FOLDER_MAP.get(id)
669
- return {
670
- id,
671
- label: clamp(raw.label || (preset && preset.label) || id, 40),
672
- hint: clamp(raw.hint || (preset && preset.hint) || '', 100),
673
- accent: str(raw.accent || (preset && preset.accent) || '#0a84ff', '#0a84ff').slice(0, 24),
674
- order: Number.isFinite(Number(raw.order)) ? Number(raw.order) : ((preset && preset.order) || (70 + index * 5)),
675
- }
676
- }
677
-
678
- function normalizePoint(raw, idx = 0) {
679
- if (!raw || typeof raw !== 'object') return null
680
- const title = clamp(raw.title || `要点 ${idx + 1}`, 90)
681
- const detail = cleanMultiline(raw.detail || raw.text || raw.body || '', 6000)
682
- if (!title && !detail) return null
683
- const cueSource = str(raw.cue || raw.summary, '').trim()
684
- const derivedCue = cueSource || firstMeaningfulSentence(detail)
685
- return {
686
- id: str(raw.id, '').trim() || ('pt-' + (idx + 1)),
687
- title: title || clamp(derivedCue || `记忆点 ${idx + 1}`, 60),
688
- cue: clamp(derivedCue, 110),
689
- detail: detail || title,
690
- }
691
- }
692
-
693
- function normalizeTags(list) {
694
- if (!Array.isArray(list)) return []
695
- const seen = new Set()
696
- const out = []
697
- for (const raw of list) {
698
- const t = String(raw || '').trim().slice(0, 36)
699
- if (!t) continue
700
- if (t.toLowerCase() === 'anchor') continue
701
- const low = t.toLowerCase()
702
- if (seen.has(low)) continue
703
- seen.add(low)
704
- out.push(t)
705
- if (out.length >= 10) break
706
- }
707
- return out
708
- }
709
-
710
- function normalizeArchiveItem(raw) {
711
- if (!raw || typeof raw !== 'object') return null
712
- const body = cleanMultiline(raw.body || '', 30000)
713
- const rawTitle = clamp(raw.title || '', 180)
714
- if (!rawTitle && !body) return null
715
-
716
- const parsedFallback = (!Array.isArray(raw.points) || !raw.points.length || !raw.folder || !raw.summary)
717
- ? smartParseNoteToDossier(raw)
718
- : null
719
-
720
- const title = rawTitle || (parsedFallback && parsedFallback.title) || '未命名工程卷宗'
721
- const folder = str(raw.folder, '').trim() || (parsedFallback && parsedFallback.folder) || 'inbox'
722
- const validClips = ['gold', 'silver', 'copper']
723
- const paperclip = validClips.includes(raw.paperclip)
724
- ? raw.paperclip
725
- : ((parsedFallback && parsedFallback.paperclip) || 'silver')
726
-
727
- const pointsRaw = Array.isArray(raw.points) && raw.points.length
728
- ? raw.points
729
- : ((parsedFallback && parsedFallback.points) || [])
730
- const points = pointsRaw.map((p, i) => normalizePoint(p, i)).filter(Boolean).slice(0, POINTS_CAP)
731
-
732
- const summary = clamp(
733
- raw.summary || (parsedFallback && parsedFallback.summary) || (points[0] && (points[0].cue || points[0].title)) || firstMeaningfulSentence(body) || title,
734
- 140,
735
- )
736
-
737
- const takenOutSessions = Array.isArray(raw.takenOutSessions)
738
- ? [...new Set(raw.takenOutSessions.map(s => String(s || '').trim()).filter(Boolean))].slice(0, 32)
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 })
744
-
745
- return {
746
- id: str(raw.id, '').trim() || nextId('arch'),
747
- sourceNoteId: str(raw.sourceNoteId, '').trim(),
748
- originId: str(raw.originId, '').trim(),
749
- originGlobalId: str(raw.originGlobalId, '').trim(),
750
- title,
751
- summary,
752
- folder,
753
- paperclip,
754
- tags: normalizeTags(Array.isArray(raw.tags) ? raw.tags : []),
755
- cold: raw.cold !== false,
756
- takenOutSessions,
757
- chiefMountedSessions,
758
- organizedBy: ['auto', 'chief', 'user'].includes(raw.organizedBy) ? raw.organizedBy : 'auto',
759
- points,
760
- body,
761
- contentHash,
762
- by: clamp(raw.by || 'agent', 40),
763
- sourceSession: str(raw.sourceSession || raw.session, '').trim(),
764
- createdAt: Number(raw.createdAt) || Date.now(),
765
- updatedAt: Number(raw.updatedAt) || Number(raw.createdAt) || Date.now(),
766
- }
767
- }
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
-
784
- function normalizeArchiveStore(raw) {
785
- const src = raw && typeof raw === 'object' ? raw : {}
786
- const folderMap = new Map()
787
- for (const def of DEFAULT_ARCHIVE_FOLDERS) {
788
- folderMap.set(def.id, { ...def })
789
- }
790
- if (Array.isArray(src.folders)) {
791
- src.folders.forEach((f, idx) => {
792
- const nf = normalizeFolder(f, idx)
793
- if (nf) folderMap.set(nf.id, nf)
794
- })
795
- }
796
-
797
- const normalizer = src.isSystemGlobalVault ? normalizeGlobalVaultEntry : normalizeArchiveItem
798
- const items = (Array.isArray(src.items) ? src.items : [])
799
- .map(normalizer)
800
- .filter(Boolean)
801
- .slice(0, ARCHIVE_CAP)
802
-
803
- let customIdx = 0
804
- for (const item of items) {
805
- if (item.folder && !folderMap.has(item.folder)) {
806
- customIdx += 1
807
- folderMap.set(item.folder, {
808
- id: item.folder,
809
- label: clamp(item.folder, 40),
810
- hint: '自定义工程档案抽屉',
811
- accent: ['#06b6d4', '#ec4899', '#eab308', '#14b8a6'][customIdx % 4],
812
- order: 55 + customIdx,
813
- })
814
- }
815
- }
816
-
817
- const folders = [...folderMap.values()].sort((a, b) => (a.order || 99) - (b.order || 99))
818
-
819
- return {
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'),
827
- migratedSharedAt: Number(src.migratedSharedAt) || 0,
828
- updatedAt: Number(src.updatedAt) || Date.now(),
829
- folders,
830
- items,
831
- }
832
- }
833
-
834
- /**
835
- * Loads the standalone System Global Cold Vault (`global-vault/vault-chief-global.json`).
836
- * Structurally peers with `precipitated/vault-global.json`: NEVER shares files with `cabinets/`,
837
- * NEVER auto-follows conversation context (0 Token unless explicitly mounted or Chief-searched).
838
- */
839
- export function loadGlobalVaultRaw(targetOpt) {
840
- const file = globalChiefVaultFilePath(targetOpt)
841
- if (!fs.existsSync(file)) {
842
- return normalizeArchiveStore({
843
- isSystemGlobalVault: true,
844
- projectKey: 'global',
845
- updatedAt: 0,
846
- items: [],
847
- })
848
- }
849
- const parsed = readJsonSafe(file, null)
850
- return normalizeArchiveStore({
851
- ...(parsed && typeof parsed === 'object' ? parsed : {}),
852
- isSystemGlobalVault: true,
853
- projectKey: 'global',
854
- })
855
- }
856
-
857
- export function saveGlobalVaultRaw(store, targetOpt) {
858
- const file = globalChiefVaultFilePath(targetOpt)
859
- const normalized = normalizeArchiveStore({
860
- ...(store && typeof store === 'object' ? store : {}),
861
- isSystemGlobalVault: true,
862
- projectKey: 'global',
863
- updatedAt: Date.now(),
864
- })
865
- atomicWriteJson(file, normalized)
866
- return normalized
867
- }
868
-
869
- /**
870
- * 0-Token Guard for System Global Vault:
871
- * Returns ONLY entries the User explicitly mounted for Chief in THIS conversation (`chiefMountedSessions`).
872
- * By default returns `[]` without reading or leaking anything into conversation context.
873
- */
874
- export function getChiefMountedGlobalForSession(rootSessionId = '', targetOpt) {
875
- const sid = cleanRootSessionId(rootSessionId)
876
- if (!sid) return []
877
- const file = globalChiefVaultFilePath(targetOpt)
878
- if (!fs.existsSync(file)) return []
879
- const store = loadGlobalVaultRaw(targetOpt)
880
- return store.items.filter(it => Array.isArray(it.chiefMountedSessions) && it.chiefMountedSessions.includes(sid))
881
- }
882
-
883
- /**
884
- * Returns ONLY System Global Vault entries explicitly placed onto THIS session's desk (`takenOutSessions`),
885
- * so both Lead & Chief emphasize them in prompt context while sealed global entries stay hidden from Lead.
886
- */
887
- export function getTakenOutGlobalForSession(rootSessionId = '', targetOpt) {
888
- const sid = cleanRootSessionId(rootSessionId)
889
- if (!sid) return []
890
- const file = globalChiefVaultFilePath(targetOpt)
891
- if (!fs.existsSync(file)) return []
892
- const store = loadGlobalVaultRaw(targetOpt)
893
- return store.items.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid))
894
- }
895
-
896
- /**
897
- * Computes bidirectional diff between the active conversation's Local Session Cabinet and the System Global Vault.
898
- */
899
- export function computeSessionGlobalDiff(sessionItems = [], globalItems = [], rootSessionId = '') {
900
- const sid = cleanRootSessionId(rootSessionId)
901
- const sArr = Array.isArray(sessionItems) ? sessionItems : []
902
- const gArr = Array.isArray(globalItems) ? globalItems : []
903
-
904
- const gById = new Map()
905
- const gByOriginId = new Map()
906
- const gByTitle = new Map()
907
- for (const g of gArr) {
908
- if (!g) continue
909
- gById.set(g.id, g)
910
- if (g.originId) gByOriginId.set(g.originId, g)
911
- const tk = normalizeArchiveTitleKey(g.title)
912
- if (tk && !gByTitle.has(tk)) gByTitle.set(tk, g)
913
- }
914
-
915
- const sById = new Map()
916
- const sByOriginGlobal = new Map()
917
- const sByTitle = new Map()
918
- for (const s of sArr) {
919
- if (!s) continue
920
- sById.set(s.id, s)
921
- if (s.originGlobalId) sByOriginGlobal.set(s.originGlobalId, s)
922
- const tk = normalizeArchiveTitleKey(s.title)
923
- if (tk && !sByTitle.has(tk)) sByTitle.set(tk, s)
924
- }
925
-
926
- const sessionDiffMap = new Map()
927
- const globalDiffMap = new Map()
928
- let localOnlyCount = 0
929
- let globalOnlyCount = 0
930
- let syncedCount = 0
931
- let modifiedCount = 0
932
- const localOnlyBriefs = []
933
-
934
- if (sid) {
935
- for (const s of sArr) {
936
- if (!s) continue
937
- const gMatch = (s.originGlobalId && gById.get(s.originGlobalId))
938
- || gByOriginId.get(s.id)
939
- || gByTitle.get(normalizeArchiveTitleKey(s.title))
940
- || null
941
- if (!gMatch) {
942
- localOnlyCount += 1
943
- sessionDiffMap.set(s.id, { diffStatus: 'local_only', matchedGlobalId: '' })
944
- if (localOnlyBriefs.length < 25) {
945
- localOnlyBriefs.push({
946
- id: s.id,
947
- title: s.title,
948
- summary: s.summary,
949
- folder: s.folder,
950
- paperclip: s.paperclip,
951
- diffStatus: 'local_only',
952
- updatedAt: s.updatedAt,
953
- })
954
- }
955
- } else {
956
- const sHash = computeEntryContentHash(s)
957
- const gHash = computeEntryContentHash(gMatch)
958
- if (sHash === gHash) {
959
- syncedCount += 1
960
- sessionDiffMap.set(s.id, { diffStatus: 'synced', matchedGlobalId: gMatch.id })
961
- } else {
962
- modifiedCount += 1
963
- sessionDiffMap.set(s.id, { diffStatus: 'local_modified', matchedGlobalId: gMatch.id })
964
- if (localOnlyBriefs.length < 25) {
965
- localOnlyBriefs.push({
966
- id: s.id,
967
- title: s.title,
968
- summary: s.summary,
969
- folder: s.folder,
970
- paperclip: s.paperclip,
971
- diffStatus: 'local_modified',
972
- matchedGlobalId: gMatch.id,
973
- updatedAt: s.updatedAt,
974
- })
975
- }
976
- }
977
- }
978
- }
979
- }
980
-
981
- for (const g of gArr) {
982
- if (!g) continue
983
- if (!sid) {
984
- globalDiffMap.set(g.id, { diffStatus: 'unbound', matchedSessionItemId: '' })
985
- continue
986
- }
987
- const sMatch = sByOriginGlobal.get(g.id)
988
- || (g.originId ? sById.get(g.originId) : null)
989
- || sByTitle.get(normalizeArchiveTitleKey(g.title))
990
- || null
991
- if (!sMatch) {
992
- globalOnlyCount += 1
993
- globalDiffMap.set(g.id, { diffStatus: 'global_only', matchedSessionItemId: '' })
994
- } else {
995
- const sHash = computeEntryContentHash(sMatch)
996
- const gHash = computeEntryContentHash(g)
997
- globalDiffMap.set(g.id, {
998
- diffStatus: sHash === gHash ? 'synced' : 'differs',
999
- matchedSessionItemId: sMatch.id,
1000
- })
1001
- }
1002
- }
1003
-
1004
- return {
1005
- sessionDiffMap,
1006
- globalDiffMap,
1007
- summary: {
1008
- unboundSession: !sid,
1009
- sessionTotal: sid ? sArr.length : 0,
1010
- globalTotal: gArr.length,
1011
- localOnlyCount,
1012
- globalOnlyCount: sid ? globalOnlyCount : gArr.length,
1013
- syncedCount,
1014
- modifiedCount,
1015
- localOnlyBriefs,
1016
- },
1017
- }
1018
- }
1019
-
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
1036
- try {
1037
- const st = fs.statSync(file)
1038
- if (archiveCache.store && archiveCache.file === file && archiveCache.mtime === st.mtimeMs) {
1039
- return archiveCache.store
1040
- }
1041
- const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
1042
- const store = normalizeArchiveStore({
1043
- ...parsed,
1044
- cabinetId: resolved.cabinetId,
1045
- cabinetName: resolved.cabinetName,
1046
- projectKey: resolved.projectKey,
1047
- })
1048
- archiveCache = { file, mtime: st.mtimeMs, store }
1049
- return store
1050
- } catch {
1051
- return normalizeArchiveStore({
1052
- cabinetId: resolved.cabinetId,
1053
- cabinetName: resolved.cabinetName,
1054
- projectKey: resolved.projectKey,
1055
- })
1056
- }
1057
- }
1058
-
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)
1076
- let mtime = Date.now()
1077
- try {
1078
- mtime = fs.statSync(file).mtimeMs
1079
- } catch {}
1080
- archiveCache = { file, mtime, store: normalized }
1081
- return normalized
1082
- }
1083
-
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)
1105
- invalidateArchiveCache()
1106
- try {
1107
- return fn(file, resolved)
1108
- } finally {
1109
- release()
1110
- }
1111
- }
1112
-
1113
- /* ------------------------------------------- Smart Note -> Dossier Parser */
1114
-
1115
- function stripMarkdownDecorators(text) {
1116
- return String(text || '')
1117
- .replace(/^[#>*\-\d.)\s\u3000]+/, '')
1118
- .replace(/\*\*([^*]+)\*\*/g, '$1')
1119
- .replace(/`([^`]+)`/g, '$1')
1120
- .trim()
1121
- }
1122
-
1123
- function firstMeaningfulSentence(text) {
1124
- const lines = String(text || '')
1125
- .split('\n')
1126
- .map(l => l.trim())
1127
- .filter(l => l && !/^\|[-:\s|]+\|$/.test(l) && !/^```/.test(l))
1128
- if (!lines.length) return ''
1129
- const candidate = (/^#{1,4}\s+/.test(lines[0]) && lines[1]) ? lines[1] : lines[0]
1130
- const clean = stripMarkdownDecorators(candidate)
1131
- const firstClause = clean.split(/[。;!?\n]/)[0] || clean
1132
- return clamp(firstClause, 115)
1133
- }
1134
-
1135
- export function classifyNoteFolder(title, body, tags = []) {
1136
- const tagText = (Array.isArray(tags) ? tags : []).join(' ').toLowerCase()
1137
- const head = `${title || ''} ${tagText}`.toLowerCase()
1138
- const full = `${head} ${String(body || '').slice(0, 500)}`.toLowerCase()
1139
-
1140
- if (/坐标|锚点|安装源|包体|目录结构|端口|热更|set_bundle|deployed/.test(head)) {
1141
- return 'coords'
1142
- }
1143
- if (/运维|环境|机器|硬事实|astrbot|claudia|sing-box|docker|服务器|tunnel|代理链路/.test(head) || /环境|运维/.test(tagText)) {
1144
- return 'ops'
1145
- }
1146
- if (/计划存档|蓝图|对照表|出图线|交接单三项|阶段|roadmap|archive|plan/.test(head)) {
1147
- return 'plans'
1148
- }
1149
- if (/症状|事故|已修|黑屏|坏了|排障|根因|死胡同|绕行|≠|不等于|踩坑|报错|unauthorized|eperm/.test(head)) {
1150
- return 'incidents'
1151
- }
1152
- if (/契约|方法论|自检|上限|截断|宽容|schema|继承规则|归属|注释|派生标题|具名|必须/.test(head) || /方法论|自检|设计/.test(tagText)) {
1153
- return 'contracts'
1154
- }
1155
- if (/坐标|路径|d:\\|%dsh_home%/.test(full) && /验证|pass/.test(full)) {
1156
- return 'coords'
1157
- }
1158
- if (/##\s*症状|##\s*根因|硬事实/.test(full)) {
1159
- return 'incidents'
1160
- }
1161
- return 'contracts'
1162
- }
1163
-
1164
- function inferPaperclip(raw, folder) {
1165
- const tags = (Array.isArray(raw && raw.tags) ? raw.tags : []).map(t => String(t).toLowerCase())
1166
- if (raw && (raw.pinned === true || tags.includes('anchor') || raw.paperclip === 'gold')) {
1167
- return 'gold'
1168
- }
1169
- if (tags.includes('archive') || folder === 'plans') {
1170
- return 'copper'
1171
- }
1172
- return 'silver'
1173
- }
1174
-
1175
- export function extractStructuredPoints(title, rawBody) {
1176
- const body = String(rawBody || '').replace(/\r/g, '').trim()
1177
- if (!body) {
1178
- return [
1179
- {
1180
- id: 'pt-1',
1181
- title: '归档标题备忘',
1182
- cue: '当前仅记录卷宗标题,尚未补充详细正文',
1183
- detail: `卷宗《${title || '未命名'}》当前无附加正文,可通过「编辑」随时补充工程细节。`,
1184
- },
1185
- ]
1186
- }
1187
-
1188
- const lines = body.split('\n')
1189
- const headingIndices = []
1190
- for (let i = 0; i < lines.length; i += 1) {
1191
- if (/^#{2,3}\s+\S/.test(lines[i].trim())) {
1192
- headingIndices.push(i)
1193
- }
1194
- }
1195
- if (headingIndices.length >= 1) {
1196
- const points = []
1197
- const preLines = lines.slice(0, headingIndices[0]).filter(l => !/^#\s+/.test(l.trim()))
1198
- const preText = preLines.join('\n').trim()
1199
- if (preText.length >= 18) {
1200
- points.push({
1201
- id: `pt-${points.length + 1}`,
1202
- title: '背景与总览',
1203
- cue: firstMeaningfulSentence(preText),
1204
- detail: preText,
1205
- })
1206
- }
1207
- for (let hIdx = 0; hIdx < headingIndices.length; hIdx += 1) {
1208
- const start = headingIndices[hIdx]
1209
- const end = hIdx + 1 < headingIndices.length ? headingIndices[hIdx + 1] : lines.length
1210
- const rawHeading = lines[start].trim().replace(/^#{2,3}\s+/, '').trim()
1211
- const secBody = lines.slice(start + 1, end).join('\n').trim()
1212
- if (!secBody && !rawHeading) continue
1213
- points.push({
1214
- id: `pt-${points.length + 1}`,
1215
- title: clamp(stripMarkdownDecorators(rawHeading) || `要点 ${points.length + 1}`, 76),
1216
- cue: firstMeaningfulSentence(secBody) || clamp(rawHeading, 90),
1217
- detail: secBody || rawHeading,
1218
- })
1219
- }
1220
- if (points.length >= 1) return points.slice(0, POINTS_CAP)
1221
- }
1222
-
1223
- const kvBlocks = []
1224
- let currentKv = null
1225
- for (const rawLine of lines) {
1226
- const trimmed = rawLine.trim()
1227
- if (!trimmed) continue
1228
- const kvMatch = /^([^\s::|]{2,18}(?:[((][^))]{1,18}[))])?)\s*[::]\s*(.*)$/.exec(trimmed)
1229
- const numMatch = /^(\d+)\.\s+(?:\[[xX\s]\]\s*)?(.+)$/.exec(trimmed)
1230
- if (kvMatch) {
1231
- if (currentKv) kvBlocks.push(currentKv)
1232
- const rest = kvMatch[2].trim()
1233
- currentKv = {
1234
- title: stripMarkdownDecorators(kvMatch[1]),
1235
- lines: rest ? [rest] : [],
1236
- }
1237
- } else if (numMatch && !currentKv) {
1238
- kvBlocks.push({
1239
- title: clamp(stripMarkdownDecorators(numMatch[2]), 54),
1240
- lines: [trimmed],
1241
- })
1242
- } else if (currentKv) {
1243
- currentKv.lines.push(trimmed)
1244
- } else {
1245
- currentKv = {
1246
- title: clamp(firstMeaningfulSentence(trimmed), 46) || '背景说明',
1247
- lines: [trimmed],
1248
- }
1249
- }
1250
- }
1251
- if (currentKv) kvBlocks.push(currentKv)
1252
- if (kvBlocks.length >= 2) {
1253
- return kvBlocks.slice(0, POINTS_CAP).map((b, i) => {
1254
- const detail = b.lines.join('\n').trim() || b.title
1255
- return {
1256
- id: `pt-${i + 1}`,
1257
- title: clamp(b.title || `要点 ${i + 1}`, 72),
1258
- cue: firstMeaningfulSentence(detail),
1259
- detail,
1260
- }
1261
- })
1262
- }
1263
-
1264
- const paragraphs = body
1265
- .split(/\n{2,}/)
1266
- .map(p => p.trim())
1267
- .filter(p => p && !/^#\s+/.test(p))
1268
-
1269
- if (paragraphs.length >= 2) {
1270
- return paragraphs.slice(0, POINTS_CAP).map((para, idx) => {
1271
- const first = firstMeaningfulSentence(para)
1272
- return {
1273
- id: `pt-${idx + 1}`,
1274
- title: clamp(first || `记忆点 ${idx + 1}`, 56),
1275
- cue: clamp(para.replace(/\s+/g, ' '), 105),
1276
- detail: para,
1277
- }
1278
- })
1279
- }
1280
-
1281
- const sentences = body
1282
- .split(/(?<=[。!?;])\s*/)
1283
- .map(s => s.trim())
1284
- .filter(Boolean)
1285
-
1286
- if (sentences.length >= 2 && body.length > 95) {
1287
- const labels = ['核心问题与诱因', '关键判据与机制', '落地规范与避坑', '补充细节']
1288
- const grouped = []
1289
- const chunkSize = sentences.length >= 5 ? 2 : 1
1290
- for (let i = 0; i < sentences.length; i += chunkSize) {
1291
- const slice = sentences.slice(i, i + chunkSize).join('')
1292
- const labelIdx = Math.min(grouped.length, labels.length - 1)
1293
- grouped.push({
1294
- id: `pt-${grouped.length + 1}`,
1295
- title: `${labels[labelIdx]}:${clamp(stripMarkdownDecorators(sentences[i]), 36)}`,
1296
- cue: clamp(stripMarkdownDecorators(slice), 100),
1297
- detail: slice,
1298
- })
1299
- }
1300
- return grouped.slice(0, POINTS_CAP)
1301
- }
1302
-
1303
- return [
1304
- {
1305
- id: 'pt-1',
1306
- title: clamp(title || firstMeaningfulSentence(body) || '核心记忆点', 64),
1307
- cue: firstMeaningfulSentence(body),
1308
- detail: body,
1309
- },
1310
- ]
1311
- }
1312
-
1313
- export function smartParseNoteToDossier(rawNote) {
1314
- const note = rawNote && typeof rawNote === 'object' ? rawNote : {}
1315
- const body = cleanMultiline(note.body || '', 30000)
1316
- const derivedTitle = clamp(
1317
- note.title || firstMeaningfulSentence(body) || '未命名工程卷宗',
1318
- 180,
1319
- )
1320
- const folder = str(note.folder, '').trim() || classifyNoteFolder(derivedTitle, body, note.tags)
1321
- const paperclip = inferPaperclip(note, folder)
1322
- const points = extractStructuredPoints(derivedTitle, body)
1323
- const summary = clamp(
1324
- note.summary || (points[0] && points[0].cue) || firstMeaningfulSentence(body) || derivedTitle,
1325
- 135,
1326
- )
1327
- return {
1328
- title: derivedTitle,
1329
- summary,
1330
- folder,
1331
- paperclip,
1332
- points,
1333
- }
1334
- }
1335
-
1336
- /* ------------------------------------ Non-Destructive Bootstrap Migration */
1337
-
1338
- export function bootstrapArchivesFromSharedBoard({ sharedFile, loadBoard, saveBoard, pushLog }) {
1339
- try {
1340
- if (!sharedFile || !fs.existsSync(sharedFile)) return { migrated: 0 }
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 }
1348
- }
1349
-
1350
- const sharedBoard = loadBoard(sharedFile)
1351
- const legacyNotes = Array.isArray(sharedBoard && sharedBoard.notes) ? sharedBoard.notes : []
1352
- if (!legacyNotes.length) {
1353
- if (!existing.migratedSharedAt) {
1354
- withArchiveLock(storeTarget, () => {
1355
- const empty = loadArchiveStore(storeTarget)
1356
- empty.migratedSharedAt = Date.now()
1357
- saveArchiveStore(empty, storeTarget)
1358
- })
1359
- }
1360
- return { migrated: 0 }
1361
- }
1362
-
1363
- const backupFile = path.join(path.dirname(sharedFile), 'board.pre-archive-backup.json')
1364
- try {
1365
- if (!fs.existsSync(backupFile)) {
1366
- fs.copyFileSync(sharedFile, backupFile)
1367
- }
1368
- } catch {}
1369
-
1370
- let migratedCount = 0
1371
- withArchiveLock(storeTarget, () => {
1372
- const store = loadArchiveStore(storeTarget)
1373
- const existingSourceIds = new Set(store.items.map(it => it.sourceNoteId).filter(Boolean))
1374
- const existingTitles = new Set(store.items.map(it => it.title))
1375
-
1376
- for (const note of legacyNotes) {
1377
- if (!note || (!note.title && !note.body)) continue
1378
- if (SECRET_PATTERN.test(String(note.body || ''))) continue
1379
- if ((note.id && existingSourceIds.has(note.id)) || (note.title && existingTitles.has(note.title))) {
1380
- continue
1381
- }
1382
- const parsed = smartParseNoteToDossier(note)
1383
- const item = normalizeArchiveItem({
1384
- id: nextId('arch'),
1385
- sourceNoteId: note.id || '',
1386
- title: parsed.title,
1387
- summary: parsed.summary,
1388
- folder: parsed.folder,
1389
- paperclip: parsed.paperclip,
1390
- tags: note.tags || [],
1391
- cold: true,
1392
- takenOutSessions: [],
1393
- organizedBy: 'auto',
1394
- points: parsed.points,
1395
- body: note.body || '',
1396
- by: note.by || 'agent',
1397
- sourceSession: note.session || '',
1398
- createdAt: note.createdAt || note.updatedAt || Date.now(),
1399
- updatedAt: note.updatedAt || Date.now(),
1400
- })
1401
- if (item) {
1402
- store.items.push(item)
1403
- migratedCount += 1
1404
- }
1405
- }
1406
-
1407
- store.migratedSharedAt = Date.now()
1408
- saveArchiveStore(store, storeTarget)
1409
- })
1410
-
1411
- if (migratedCount > 0 && typeof saveBoard === 'function') {
1412
- sharedBoard.notes = []
1413
- if (typeof pushLog === 'function') {
1414
- pushLog(
1415
- sharedBoard,
1416
- `🗄️ 已将 ${migratedCount} 篇历史工程笔记无损沉淀入「全局档案柜」(默认封存懒加载,不再每轮挤占上下文)`,
1417
- 'system',
1418
- '',
1419
- )
1420
- }
1421
- saveBoard(sharedBoard, sharedFile)
1422
- }
1423
-
1424
- return { migrated: migratedCount }
1425
- } catch {
1426
- return { migrated: 0 }
1427
- }
1428
- }
1429
-
1430
- /* ------------------------------------------- Lazy-Loading Query & Mutations */
1431
-
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)
1438
- const nonEmptyFolders = new Set(store.items.map(it => it.folder).filter(Boolean))
1439
- const takenOutCount = (sid && cabInfo.vaultScope !== 'global' && !cabInfo.unboundSession)
1440
- ? store.items.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid)).length
1441
- : 0
1442
- return {
1443
- totalCount: store.items.length,
1444
- folderCount: nonEmptyFolders.size || DEFAULT_ARCHIVE_FOLDERS.length,
1445
- takenOutCount,
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,
1500
- }
1501
- }
1502
-
1503
- /**
1504
- * Tier-1 Lazy Load (`GET /api/dsh-chief/archives`):
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.
1509
- */
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
-
1532
- const needle = String((opts && opts.query) || '').trim().toLowerCase()
1533
- const folderFilter = String((opts && opts.folder) || '').trim()
1534
- const clipFilter = String((opts && opts.paperclip) || '').trim()
1535
-
1536
- const clipRank = { gold: 0, silver: 1, copper: 2 }
1537
- const sorted = store.items.slice().sort((a, b) => {
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
1545
- const cDiff = (clipRank[a.paperclip] ?? 1) - (clipRank[b.paperclip] ?? 1)
1546
- if (cDiff !== 0) return cDiff
1547
- return (b.updatedAt || 0) - (a.updatedAt || 0)
1548
- })
1549
-
1550
- const filtered = sorted.filter((it) => {
1551
- if (folderFilter && it.folder !== folderFilter) return false
1552
- if (clipFilter && it.paperclip !== clipFilter) return false
1553
- if (!needle) return true
1554
- const hay = [
1555
- it.title,
1556
- it.summary,
1557
- (it.tags || []).join(' '),
1558
- ...(it.points || []).map(p => `${p.title} ${p.cue}`),
1559
- it.body,
1560
- ].join('\n').toLowerCase()
1561
- return hay.includes(needle)
1562
- })
1563
-
1564
- const countsByFolder = {}
1565
- const goldByFolder = {}
1566
- for (const it of store.items) {
1567
- countsByFolder[it.folder] = (countsByFolder[it.folder] || 0) + 1
1568
- if (it.paperclip === 'gold') {
1569
- goldByFolder[it.folder] = (goldByFolder[it.folder] || 0) + 1
1570
- }
1571
- }
1572
-
1573
- const folders = store.folders.map(f => ({
1574
- ...f,
1575
- count: countsByFolder[f.id] || 0,
1576
- goldCount: goldByFolder[f.id] || 0,
1577
- }))
1578
-
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
1613
-
1614
- return {
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,
1624
- totalCount: store.items.length,
1625
- takenOutCount: sid
1626
- ? store.items.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid)).length
1627
- : 0,
1628
- diffSummary: diff.summary,
1629
- folders,
1630
- items: headers,
1631
- ...(precipitated !== undefined ? { precipitated } : {}),
1632
- ...(counts !== undefined ? { counts } : {}),
1633
- }
1634
- }
1635
-
1636
- export function getArchiveDetail(idOrTitle = '', rootSessionId = '', targetOpt) {
1637
- const target = String(idOrTitle || '').trim()
1638
- if (!target) return { ok: false, error: 'archive id or title required' }
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))
1647
- const hit = store.items.find(it => it.id === target)
1648
- || store.items.find(it => it.title === target)
1649
- || store.items.find(it => it.title.toLowerCase().includes(target.toLowerCase()))
1650
- if (!hit) return { ok: false, error: '未找到工程档案:' + target }
1651
-
1652
- return {
1653
- ok: true,
1654
- vaultScope: isGlobal ? 'global' : (resolved.vaultScope || 'session'),
1655
- isSystemGlobalVault: isGlobal,
1656
- item: {
1657
- id: hit.id,
1658
- originId: hit.originId || '',
1659
- originGlobalId: hit.originGlobalId || '',
1660
- title: hit.title,
1661
- summary: hit.summary,
1662
- folder: hit.folder,
1663
- paperclip: hit.paperclip,
1664
- tags: hit.tags,
1665
- cold: hit.cold,
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)),
1668
- organizedBy: hit.organizedBy,
1669
- points: hit.points,
1670
- body: hit.body,
1671
- contentHash: hit.contentHash || computeEntryContentHash(hit),
1672
- by: hit.by,
1673
- createdAt: hit.createdAt,
1674
- updatedAt: hit.updatedAt,
1675
- },
1676
- }
1677
- }
1678
-
1679
- /**
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`!
1682
- */
1683
- export function getTakenOutArchivesForSession(rootSessionId = '', targetOpt) {
1684
- const sid = cleanRootSessionId(rootSessionId)
1685
- if (!sid) return []
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 []
1696
- return store.items.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid))
1697
- }
1698
-
1699
- function scoreAndRankArchiveItems(store, query = '', opts = {}) {
1700
- const folder = String((opts && opts.folder) || '').trim()
1701
- const limit = Math.max(1, Math.min(Number(opts && opts.limit) || 8, 25))
1702
- const rawQ = String(query || '').trim().toLowerCase()
1703
- const terms = rawQ
1704
- .replace(/[??!!。,,、::“”"'()()[\]【】]/g, ' ')
1705
- .split(/\s+/)
1706
- .filter(Boolean)
1707
-
1708
- const scored = []
1709
- for (const it of (store && Array.isArray(store.items) ? store.items : [])) {
1710
- if (folder && it.folder !== folder) continue
1711
- if (!terms.length) {
1712
- scored.push({ score: it.paperclip === 'gold' ? 5 : 2, it })
1713
- continue
1714
- }
1715
- const titleLow = it.title.toLowerCase()
1716
- const sumLow = it.summary.toLowerCase()
1717
- const tagLow = (it.tags || []).join(' ').toLowerCase()
1718
- const ptsLow = (it.points || []).map(p => `${p.title} ${p.cue} ${p.detail}`).join('\n').toLowerCase()
1719
- const bodyLow = (it.body || '').toLowerCase()
1720
-
1721
- let score = 0
1722
- for (const term of terms) {
1723
- if (titleLow.includes(term)) score += 8
1724
- if (tagLow.includes(term)) score += 5
1725
- if (sumLow.includes(term)) score += 4
1726
- if (ptsLow.includes(term)) score += 3
1727
- else if (bodyLow.includes(term)) score += 2
1728
- }
1729
- if (score > 0) {
1730
- if (it.paperclip === 'gold') score += 1
1731
- scored.push({ score, it })
1732
- }
1733
- }
1734
-
1735
- scored.sort((a, b) => b.score - a.score || (b.it.updatedAt || 0) - (a.it.updatedAt || 0))
1736
- const folderLabelMap = new Map((store && Array.isArray(store.folders) ? store.folders : []).map(f => [f.id, f.label]))
1737
-
1738
- return {
1739
- totalArchives: store && Array.isArray(store.items) ? store.items.length : 0,
1740
- matchCount: scored.length,
1741
- hits: scored.slice(0, limit).map(({ it }) => ({
1742
- id: it.id,
1743
- title: it.title,
1744
- folder: it.folder,
1745
- folderLabel: folderLabelMap.get(it.folder) || it.folder,
1746
- paperclip: it.paperclip,
1747
- summary: it.summary,
1748
- tags: it.tags,
1749
- points: (it.points || []).map(p => ({ id: p.id, title: p.title, cue: p.cue })),
1750
- updatedAt: it.updatedAt,
1751
- })),
1752
- }
1753
- }
1754
-
1755
- /** On-demand search for `chief_board({ action: "archive.search" })` inside THIS conversation's Session Cabinet.
1756
- * Strictly NEVER reads System Global Vault or `precipitated`! */
1757
- export function searchArchives(query = '', opts = {}, targetOpt) {
1758
- const rawTarget = targetOpt !== undefined
1759
- ? (typeof targetOpt === 'string'
1760
- ? { customSharedBoardFile: targetOpt, vaultScope: 'session' }
1761
- : { ...targetOpt, vaultScope: 'session' })
1762
- : (opts && (opts.cwd || opts.projectKey || opts.cabinetId || opts.customSharedBoardFile || opts.rootSessionId || opts.sessionId)
1763
- ? { ...opts, vaultScope: 'session' }
1764
- : { vaultScope: 'session' })
1765
- const store = loadArchiveStore(rawTarget)
1766
- if (store.unboundSession) {
1767
- return { ok: true, totalArchives: 0, matchCount: 0, hits: [], unboundSession: true }
1768
- }
1769
- return {
1770
- ok: true,
1771
- ...scoreAndRankArchiveItems(store, query, opts),
1772
- }
1773
- }
1774
-
1775
- /** On-demand search strictly for Chief (`askChief`) across the System Global Cold Vault (`global-vault/vault-chief-global.json`).
1776
- * NEVER exposed to Lead/Subagent `chief_board` tools. */
1777
- export function searchGlobalVaultForChief(query = '', opts = {}, targetOpt) {
1778
- const rawTarget = targetOpt !== undefined
1779
- ? (typeof targetOpt === 'string' ? { customSharedBoardFile: targetOpt, vaultScope: 'global' } : { ...targetOpt, vaultScope: 'global' })
1780
- : { ...(opts || {}), vaultScope: 'global' }
1781
- const store = loadGlobalVaultRaw(rawTarget)
1782
- return {
1783
- ok: true,
1784
- vaultScope: 'global',
1785
- isSystemGlobalVault: true,
1786
- ...scoreAndRankArchiveItems(store, query, opts),
1787
- }
1788
- }
1789
-
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') {
1991
- const rawLabel = clamp(payload.label || payload.folderLabel || payload.folder, 40)
1992
- if (!rawLabel) return { ok: false, error: '请输入文件夹抽屉名称' }
1993
- const id = str(payload.folderId, '').trim()
1994
- || ('folder-' + rawLabel.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5_-]+/g, '-').slice(0, 24) + '-' + Date.now().toString(36).slice(-3))
1995
- const existing = store.folders.find(f => f.id === id || f.label === rawLabel)
1996
- if (existing) {
1997
- if (payload.hint !== undefined) existing.hint = clamp(payload.hint, 100)
1998
- if (payload.accent) existing.accent = str(payload.accent, existing.accent).slice(0, 24)
1999
- saveArchiveStore(store, lockTarget)
2000
- return { ok: true, folder: existing }
2001
- }
2002
- const created = normalizeFolder({
2003
- id,
2004
- label: rawLabel,
2005
- hint: payload.hint || '自定义工程记忆抽屉',
2006
- accent: payload.accent || '#06b6d4',
2007
- order: 55 + store.folders.length,
2008
- })
2009
- store.folders.push(created)
2010
- saveArchiveStore(store, lockTarget)
2011
- return { ok: true, folder: created }
2012
- }
2013
-
2014
- if (op === 'save' || op === 'create' || op === 'update') {
2015
- const id = str(payload.archiveId || payload.id, '').trim()
2016
- const existing = id ? store.items.find(it => it.id === id) : null
2017
-
2018
- const nextBody = typeof payload.body === 'string'
2019
- ? cleanMultiline(payload.body, 30000)
2020
- : (existing ? existing.body : '')
2021
- if (SECRET_PATTERN.test(nextBody)) {
2022
- return { ok: false, error: '档案内容疑似包含密钥或私密凭据,已拒绝入库' }
2023
- }
2024
-
2025
- if (existing) {
2026
- const bodyChanged = typeof payload.body === 'string' && payload.body.trim() !== existing.body.trim()
2027
- if (typeof payload.title === 'string' && payload.title.trim()) {
2028
- existing.title = clamp(payload.title, 180)
2029
- }
2030
- if (typeof payload.body === 'string') {
2031
- existing.body = nextBody
2032
- }
2033
- if (typeof payload.folder === 'string' && payload.folder.trim()) {
2034
- existing.folder = payload.folder.trim()
2035
- }
2036
- if (['gold', 'silver', 'copper'].includes(payload.paperclip)) {
2037
- existing.paperclip = payload.paperclip
2038
- }
2039
- if (Array.isArray(payload.tags)) {
2040
- existing.tags = normalizeTags(payload.tags)
2041
- } else if (typeof payload.tags === 'string') {
2042
- existing.tags = normalizeTags(payload.tags.split(/[,,]/))
2043
- }
2044
- if (Array.isArray(payload.points) && payload.points.length) {
2045
- existing.points = payload.points.map((p, i) => normalizePoint(p, i)).filter(Boolean).slice(0, POINTS_CAP)
2046
- existing.organizedBy = payload.organizedBy || 'user'
2047
- } else if (bodyChanged) {
2048
- existing.points = extractStructuredPoints(existing.title, existing.body)
2049
- }
2050
- if (typeof payload.summary === 'string' && payload.summary.trim()) {
2051
- existing.summary = clamp(payload.summary, 140)
2052
- } else if (bodyChanged) {
2053
- existing.summary = clamp(
2054
- (existing.points[0] && existing.points[0].cue) || firstMeaningfulSentence(existing.body) || existing.title,
2055
- 140,
2056
- )
2057
- }
2058
- existing.contentHash = computeEntryContentHash(existing)
2059
- existing.updatedAt = Date.now()
2060
- saveArchiveStore(store, lockTarget)
2061
- return {
2062
- ok: true,
2063
- isSystemGlobalVault: resolved.vaultScope === 'global',
2064
- item: existing,
2065
- meta: getArchiveMeta(rootSessionId, lockTarget),
2066
- }
2067
- }
2068
-
2069
- const rawTitle = clamp(payload.title || '', 180)
2070
- if (!rawTitle && !nextBody) {
2071
- return { ok: false, error: '新建工程档案需要填写标题或正文内容' }
2072
- }
2073
- const titleKey = normalizeArchiveTitleKey(rawTitle)
2074
- const sameTitle = titleKey
2075
- ? store.items.find(it => normalizeArchiveTitleKey(it.title) === titleKey)
2076
- : null
2077
- if (sameTitle && payload.upsertByTitle !== false) {
2078
- sameTitle.body = nextBody || sameTitle.body
2079
- if (payload.folder) sameTitle.folder = str(payload.folder, sameTitle.folder).trim()
2080
- if (['gold', 'silver', 'copper'].includes(payload.paperclip)) sameTitle.paperclip = payload.paperclip
2081
- if (payload.tags) {
2082
- sameTitle.tags = normalizeTags(Array.isArray(payload.tags) ? payload.tags : String(payload.tags).split(/[,,]/))
2083
- }
2084
- sameTitle.points = Array.isArray(payload.points) && payload.points.length
2085
- ? payload.points.map((p, i) => normalizePoint(p, i)).filter(Boolean).slice(0, POINTS_CAP)
2086
- : extractStructuredPoints(sameTitle.title, sameTitle.body)
2087
- sameTitle.summary = clamp(
2088
- payload.summary || (sameTitle.points[0] && sameTitle.points[0].cue) || firstMeaningfulSentence(sameTitle.body) || sameTitle.title,
2089
- 140,
2090
- )
2091
- sameTitle.contentHash = computeEntryContentHash(sameTitle)
2092
- sameTitle.updatedAt = Date.now()
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
- }
2101
- }
2102
-
2103
- const parsed = smartParseNoteToDossier({
2104
- title: rawTitle,
2105
- body: nextBody,
2106
- folder: payload.folder,
2107
- paperclip: payload.paperclip,
2108
- tags: Array.isArray(payload.tags) ? payload.tags : (typeof payload.tags === 'string' ? payload.tags.split(/[,,]/) : []),
2109
- })
2110
- const baseCreated = {
2111
- id: nextId(resolved.vaultScope === 'global' ? 'glob' : 'arch'),
2112
- sourceNoteId: str(payload.sourceNoteId, ''),
2113
- originId: str(payload.originId, ''),
2114
- originGlobalId: str(payload.originGlobalId, ''),
2115
- title: parsed.title,
2116
- summary: payload.summary || parsed.summary,
2117
- folder: payload.folder || parsed.folder,
2118
- paperclip: payload.paperclip || parsed.paperclip,
2119
- tags: Array.isArray(payload.tags) ? payload.tags : (typeof payload.tags === 'string' ? payload.tags.split(/[,,]/) : []),
2120
- cold: true,
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'),
2126
- points: Array.isArray(payload.points) && payload.points.length ? payload.points : parsed.points,
2127
- body: nextBody,
2128
- by: payload.by || 'user',
2129
- sourceSession: rootSessionId,
2130
- createdAt: Date.now(),
2131
- updatedAt: Date.now(),
2132
- }
2133
- const created = resolved.vaultScope === 'global'
2134
- ? normalizeGlobalVaultEntry(baseCreated)
2135
- : normalizeArchiveItem(baseCreated)
2136
- store.items.unshift(created)
2137
- saveArchiveStore(store, lockTarget)
2138
- return {
2139
- ok: true,
2140
- isSystemGlobalVault: resolved.vaultScope === 'global',
2141
- item: created,
2142
- meta: getArchiveMeta(rootSessionId, lockTarget),
2143
- }
2144
- }
2145
-
2146
- if (op === 'delete' || op === 'remove') {
2147
- const id = str(payload.archiveId || payload.id, '').trim()
2148
- const idx = store.items.findIndex(it => it.id === id)
2149
- if (idx < 0) return { ok: false, error: '未找到要删除的档案:' + id }
2150
- const [removed] = store.items.splice(idx, 1)
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
- }
2191
- }
2192
-
2193
- if (op === 'takeOut' || op === 'putBack') {
2194
- const id = str(payload.archiveId || payload.id, '').trim()
2195
- if (!rootSessionId) return { ok: false, error: '当前未绑定对话会话,无法摆到桌面备选' }
2196
- const item = store.items.find(it => it.id === id)
2197
- if (!item) return { ok: false, error: '未找到该工程档案:' + id }
2198
- const set = new Set(item.takenOutSessions || [])
2199
- if (op === 'takeOut') set.add(rootSessionId)
2200
- else set.delete(rootSessionId)
2201
- item.takenOutSessions = [...set]
2202
- saveArchiveStore(store, lockTarget)
2203
- return {
2204
- ok: true,
2205
- id: item.id,
2206
- title: item.title,
2207
- takenOut: op === 'takeOut',
2208
- isSystemGlobalVault: resolved.vaultScope === 'global',
2209
- counts: getThreeTierArchiveCounts(rootSessionId, [], lockTarget),
2210
- meta: getArchiveMeta(rootSessionId, lockTarget),
2211
- }
2212
- }
2213
-
2214
- if (op === 'cycleClip' || op === 'setClip') {
2215
- const id = str(payload.archiveId || payload.id, '').trim()
2216
- const item = store.items.find(it => it.id === id)
2217
- if (!item) return { ok: false, error: '未找到该工程档案:' + id }
2218
- const order = ['gold', 'silver', 'copper']
2219
- if (order.includes(payload.paperclip)) {
2220
- item.paperclip = payload.paperclip
2221
- } else {
2222
- const nextIdx = (order.indexOf(item.paperclip) + 1) % order.length
2223
- item.paperclip = order[nextIdx]
2224
- }
2225
- item.updatedAt = Date.now()
2226
- saveArchiveStore(store, lockTarget)
2227
- return { ok: true, id: item.id, paperclip: item.paperclip }
2228
- }
2229
-
2230
- if (op === 'moveFolder') {
2231
- const id = str(payload.archiveId || payload.id, '').trim()
2232
- const folder = str(payload.folder, '').trim()
2233
- if (!folder) return { ok: false, error: '请选择目标文件夹抽屉' }
2234
- const item = store.items.find(it => it.id === id)
2235
- if (!item) return { ok: false, error: '未找到该工程档案:' + id }
2236
- item.folder = folder
2237
- if (payload.folderLabel && !store.folders.some(f => f.id === folder)) {
2238
- store.folders.push(normalizeFolder({ id: folder, label: payload.folderLabel, order: 58 }))
2239
- }
2240
- item.updatedAt = Date.now()
2241
- saveArchiveStore(store, lockTarget)
2242
- return { ok: true, id: item.id, folder: item.folder }
2243
- }
2244
-
2245
- if (op === 'copyToGlobal' || op === 'copyToSession') {
2246
- const id = str(payload.archiveId || payload.id, '').trim()
2247
- const srcItem = store.items.find(it => it.id === id)
2248
- if (!srcItem) return { ok: false, error: '未找到要复制的工程档案:' + id }
2249
- const targetScope = op === 'copyToGlobal' ? 'global' : 'session'
2250
- if (targetScope === 'session' && !rootSessionId) {
2251
- return { ok: false, error: '当前为空白新对话,请先发送一条消息建立会话后再引入本会话档案柜' }
2252
- }
2253
- const dstBase = {
2254
- customSharedBoardFile: baseOpts.customSharedBoardFile,
2255
- cwd: effectiveTarget.cwd,
2256
- projectKey: effectiveTarget.projectKey,
2257
- rootSessionId: targetScope === 'session' ? rootSessionId : '',
2258
- vaultScope: targetScope,
2259
- cabinetId: '',
2260
- }
2261
- const titleKey = normalizeArchiveTitleKey(srcItem.title)
2262
- const copyRes = withArchiveLock(dstBase, (_dstFile, dstResolved) => {
2263
- const dstTarget = { ...dstBase, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey, vaultScope: targetScope }
2264
- const dstStore = targetScope === 'global' ? loadGlobalVaultRaw(dstTarget) : loadArchiveStore(dstTarget)
2265
- const now = Date.now()
2266
- let savedItem
2267
-
2268
- if (targetScope === 'global') {
2269
- const existing = dstStore.items.find(g =>
2270
- (srcItem.originGlobalId && g.id === srcItem.originGlobalId)
2271
- || (g.originId && g.originId === srcItem.id)
2272
- || (titleKey && normalizeArchiveTitleKey(g.title) === titleKey)
2273
- )
2274
- const preservedChiefMounts = existing
2275
- ? (Array.isArray(existing.chiefMountedSessions) ? existing.chiefMountedSessions : [])
2276
- : (payload.mountChief && rootSessionId ? [rootSessionId] : [])
2277
- const nextEntry = normalizeGlobalVaultEntry({
2278
- ...srcItem,
2279
- id: existing ? existing.id : nextId('glob'),
2280
- originId: srcItem.id,
2281
- originGlobalId: '',
2282
- chiefMountedSessions: preservedChiefMounts,
2283
- sourceSession: srcItem.sourceSession || rootSessionId,
2284
- updatedAt: now,
2285
- })
2286
- if (existing) {
2287
- Object.assign(existing, nextEntry)
2288
- savedItem = existing
2289
- } else {
2290
- dstStore.items.unshift(nextEntry)
2291
- savedItem = nextEntry
2292
- }
2293
- saveGlobalVaultRaw(dstStore, dstTarget)
2294
- const sessSnapshot = resolved.vaultScope === 'session'
2295
- ? store.items.map(it => (it.id === srcItem.id && payload.removeSource !== true ? { ...it, originGlobalId: savedItem.id } : it))
2296
- : []
2297
- const diff = computeSessionGlobalDiff(sessSnapshot, dstStore.items, rootSessionId)
2298
- return {
2299
- ok: true,
2300
- targetScope: 'global',
2301
- isSystemGlobalVault: true,
2302
- targetCabinetId: '',
2303
- item: savedItem,
2304
- diffSummary: diff.summary,
2305
- counts: getThreeTierArchiveCounts(rootSessionId, [], dstBase),
2306
- }
2307
- }
2308
-
2309
- // targetScope === 'session'
2310
- const mountOnSession = payload.takeOut === true
2311
- const existingSess = dstStore.items.find(s =>
2312
- s.originGlobalId === srcItem.id
2313
- || (srcItem.originId && s.id === srcItem.originId)
2314
- || (titleKey && normalizeArchiveTitleKey(s.title) === titleKey)
2315
- )
2316
- const nextSessItem = normalizeArchiveItem({
2317
- ...srcItem,
2318
- id: existingSess ? existingSess.id : nextId('arch'),
2319
- originGlobalId: srcItem.id,
2320
- originId: '',
2321
- takenOutSessions: mountOnSession
2322
- ? [...new Set([...(existingSess ? (existingSess.takenOutSessions || []) : []), rootSessionId])]
2323
- : (existingSess ? (existingSess.takenOutSessions || []) : []),
2324
- sourceSession: rootSessionId,
2325
- updatedAt: now,
2326
- })
2327
- if (existingSess) {
2328
- Object.assign(existingSess, nextSessItem)
2329
- savedItem = existingSess
2330
- } else {
2331
- dstStore.items.unshift(nextSessItem)
2332
- savedItem = nextSessItem
2333
- }
2334
- saveArchiveStore(dstStore, dstTarget)
2335
- const globalItems = resolved.vaultScope === 'global' ? store.items : loadGlobalVaultRaw(baseOpts).items
2336
- const diff = computeSessionGlobalDiff(dstStore.items, globalItems, rootSessionId)
2337
- return {
2338
- ok: true,
2339
- targetScope: 'session',
2340
- isSystemGlobalVault: false,
2341
- targetCabinetId: dstResolved.cabinetId,
2342
- item: savedItem,
2343
- diffSummary: diff.summary,
2344
- counts: getThreeTierArchiveCounts(rootSessionId, [], dstBase),
2345
- }
2346
- })
2347
-
2348
- if (copyRes && copyRes.ok) {
2349
- if (payload.removeSource === true && resolved.vaultScope !== targetScope) {
2350
- const idx = store.items.findIndex(it => it.id === id)
2351
- if (idx >= 0) {
2352
- store.items.splice(idx, 1)
2353
- saveArchiveStore(store, lockTarget)
2354
- copyRes.counts = getThreeTierArchiveCounts(rootSessionId, [], dstBase)
2355
- }
2356
- } else if (targetScope === 'global' && resolved.vaultScope === 'session' && copyRes.item && srcItem.originGlobalId !== copyRes.item.id) {
2357
- srcItem.originGlobalId = copyRes.item.id
2358
- saveArchiveStore(store, lockTarget)
2359
- }
2360
- }
2361
- return copyRes
2362
- }
2363
-
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
2370
- })
2371
- }
2372
-
2373
- export function applyChiefArchiveCurations(curations = [], newFolders = [], targetOpt) {
2374
- if (!Array.isArray(curations) || !curations.length) return { updatedCount: 0 }
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)
2385
- if (Array.isArray(newFolders)) {
2386
- newFolders.forEach((nf, idx) => {
2387
- if (!nf || !nf.id) return
2388
- const cleanId = String(nf.id).trim().slice(0, 48)
2389
- if (!cleanId) return
2390
- const existing = store.folders.find(f => f.id === cleanId)
2391
- if (existing) {
2392
- if (nf.label) existing.label = clamp(nf.label, 40)
2393
- if (nf.hint) existing.hint = clamp(nf.hint, 100)
2394
- } else {
2395
- const created = normalizeFolder({
2396
- id: cleanId,
2397
- label: nf.label || cleanId,
2398
- hint: nf.hint || '由 DSH 参谋长整理归纳的工程档案抽屉',
2399
- accent: nf.accent || '#06b6d4',
2400
- order: 52 + idx,
2401
- })
2402
- if (created) store.folders.push(created)
2403
- }
2404
- })
2405
- }
2406
-
2407
- let updatedCount = 0
2408
- for (const c of curations) {
2409
- if (!c || !c.id) continue
2410
- const target = store.items.find(it => it.id === c.id)
2411
- if (!target) continue
2412
- if (typeof c.folder === 'string' && c.folder.trim()) {
2413
- const fId = c.folder.trim().slice(0, 48)
2414
- target.folder = fId
2415
- if (c.folderLabel && !store.folders.some(f => f.id === fId)) {
2416
- const created = normalizeFolder({
2417
- id: fId,
2418
- label: c.folderLabel,
2419
- hint: '由 DSH 参谋长整理建立的工程抽屉',
2420
- accent: '#06b6d4',
2421
- })
2422
- if (created) store.folders.push(created)
2423
- }
2424
- }
2425
- if (['gold', 'silver', 'copper'].includes(c.paperclip)) {
2426
- target.paperclip = c.paperclip
2427
- }
2428
- if (typeof c.summary === 'string' && c.summary.trim()) {
2429
- target.summary = clamp(c.summary, 140)
2430
- }
2431
- if (Array.isArray(c.tags) && c.tags.length) {
2432
- target.tags = normalizeTags(c.tags)
2433
- }
2434
- if (Array.isArray(c.points) && c.points.length) {
2435
- const validPts = c.points.map((p, idx) => normalizePoint(p, idx)).filter(Boolean).slice(0, POINTS_CAP)
2436
- if (validPts.length) {
2437
- target.points = validPts
2438
- }
2439
- }
2440
- target.organizedBy = 'chief'
2441
- target.updatedAt = Date.now()
2442
- updatedCount += 1
2443
- }
2444
-
2445
- if (updatedCount > 0) {
2446
- saveArchiveStore(store, lockTarget)
2447
- }
2448
- return { updatedCount }
2449
- })
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
- }
1
+ /**
2
+ * 三层工程档案系统对外门面 (Three-Tier Archive Store Facade · 详契见 ./ARCHITECTURE.md)
3
+ *
4
+ * 模块:archives.js
5
+ * 职责:聚合三层档案系统(Session 档案柜 / Project Global 档案库 / 沉淀冷库),完整保留 42 个历史公共导出。
6
+ * 允许依赖:./archive-core.js → ./archive-cabinets.js → ./archive-precipitated.js → ./archive-dossiers.js
7
+ * 禁止依赖:./index.js / ./chief.js / ./board-*.js (严禁 4 个 archive-* 子模块反向导入 ./archives.js)
8
+ * 公开 API:42 个统一重导出 (`mutateArchive`, `mutatePrecipitated`, `copyPrecipitatedToVault`, `loadArchiveStore`, ...)
9
+ * 持有状态:无 (唯一 `heldArchiveLocks`、`archiveCache` 与 `seq` 集中于 archive-core.js)
10
+ * 副作用:读写 `~/.dsh/notebook/archives/` 与工作区冷库文件,使用独占 `.lock` 与原子临时文件重命名。
11
+ * 安全边界:`SECRET_PATTERN` 拦截凭据落库;沉淀冷库默认 0-token 封存 (`flipOut` 门控);`copyPrecipitatedToVault` 先释锁再写目标库防死锁。
12
+ */
13
+
14
+ export {
15
+ DEFAULT_ARCHIVE_FOLDERS,
16
+ normalizeCwd,
17
+ resolveProjectKey,
18
+ legacyArchiveFilePath,
19
+ cabinetsDirPath,
20
+ cabinetRegistryPath,
21
+ cabinetFilePath,
22
+ globalChiefVaultFilePath,
23
+ globalPrecipitatedFilePath,
24
+ precipitatedFilePath,
25
+ invalidateArchiveCache,
26
+ classifyNoteFolder,
27
+ extractStructuredPoints,
28
+ smartParseNoteToDossier,
29
+ } from './archive-core.js'
30
+ export {
31
+ archiveFilePath,
32
+ listProjectCabinets,
33
+ bootstrapArchivesFromSharedBoard,
34
+ loadGlobalVaultRaw,
35
+ saveGlobalVaultRaw,
36
+ loadArchiveStore,
37
+ saveArchiveStore,
38
+ withArchiveLock,
39
+ } from './archive-cabinets.js'
40
+ export {
41
+ getFlippedOutPrecipitatedForSession,
42
+ copyPrecipitatedToVault,
43
+ collectSealedWatchSummary,
44
+ listPrecipitatedHeaders,
45
+ getPrecipitatedDetail,
46
+ savePrecipitatedEntry,
47
+ mutatePrecipitated,
48
+ } from './archive-precipitated.js'
49
+ export {
50
+ getChiefMountedGlobalForSession,
51
+ getTakenOutGlobalForSession,
52
+ computeSessionGlobalDiff,
53
+ getArchiveMeta,
54
+ getThreeTierArchiveCounts,
55
+ listArchiveHeaders,
56
+ getArchiveDetail,
57
+ getTakenOutArchivesForSession,
58
+ searchArchives,
59
+ searchGlobalVaultForChief,
60
+ mutateArchive,
61
+ applyChiefArchiveCurations,
62
+ copyArchivesBetweenSessionsOrCabinets,
63
+ } from './archive-dossiers.js'