dsh-chief 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/archives.js CHANGED
@@ -1,30 +1,34 @@
1
1
  /**
2
- * Engineering Memory Filing Cabinet (沉淀工程记忆档案库 · 严格懒加载 · 零主动注入)
2
+ * Engineering Memory Filing Cabinet v2 (单工程多档案柜 + 跨会话沉淀冷库 · 物理零偷读)
3
3
  *
4
- * Persists structured long-term engineering dossiers at `%DSH_HOME%/chief/archives.json`.
4
+ * Storage Layout under `%DSH_HOME%/chief/` (or `path.dirname(customSharedBoardFile)`):
5
+ * - `cabinets/registry.json` : Project -> activeCabinetId & cabinets list
6
+ * - `cabinets/<cabinetId>.json` : Active working filing cabinet (folders + paperclipped dossiers)
7
+ * - `archives.json` : Legacy v1 single cabinet (losslessly migrated to `cab-main` on first read)
8
+ * - `precipitated/<projectKey>.json` : Cross-session reusable experience cold vault (ZERO auto-read!)
5
9
  *
6
10
  * Core Contracts:
7
- * 1. Cold Vault (`cold: true`, `takenOutSessions: []` by default):
8
- * Never auto-injected into system prompts (`renderDigest`), handoff packets (`renderHandoff`),
9
- * or background chief reviews. Zero token burn until explicitly requested or taken out by user.
10
- * 2. Two-Stage Lazy Loading for Web UI:
11
- * - `/snapshot` carries ONLY `archiveMeta` counts (<80 bytes).
12
- * - `GET /archives` (when clicking `档案` tab) returns folder drawers + lightweight dossier headers
13
- * (NO `points` details and NO `body` text).
14
- * - `GET /archives/detail?id=...` (when opening a dossier) lazy-loads structured `points` + lossless `body`.
15
- * 3. Three-Tier Filing Hierarchy:
16
- * - Tier 1: Filing Cabinet Folders (`folders`: drawer tabs with color spine & counts)
17
- * - Tier 2: Paperclipped Dossier Files (`paperclip`: 'gold' | 'silver' | 'copper', title, summary, tags)
18
- * - Tier 3: Structured Memory Points (`points`: `{ id, title, cue, detail }`) -> click point to expand sub-point detail (`小点记忆`), while 100% preserving raw `body`.
11
+ * 1. Multi-Cabinet per Project (`projectKey = resolveProjectKey(cwd)`):
12
+ * Allows creating, switching, renaming, and removing isolated filing cabinets per workspace project.
13
+ * 2. Working Cabinet Cold Vault (`cold: true`, `takenOutSessions: []` by default):
14
+ * Never auto-injected into system prompts unless explicitly taken out onto the session desk (`takenOutSessions`)
15
+ * or queried via on-demand `searchArchives`.
16
+ * 3. Precipitated Cross-Session Cold Vault (`precipitated/<projectKey>.json`):
17
+ * Stores purified cross-session reusable architecture rules, env coords, contracts, and troubleshooting laws.
18
+ * STRICTLY 0-TOKEN ISOLATED: `renderDigest`, `renderHandoff`, `runTurnReview`, `searchArchives`, and
19
+ * cross-session handoff copy NEVER read `precipitated/<projectKey>.json` unless a user explicitly triggers
20
+ * `flipOut` on a precipitated entry to inspect/co-organize it inside the current session!
19
21
  */
20
22
 
23
+ import crypto from 'node:crypto'
21
24
  import fs from 'node:fs'
22
25
  import os from 'node:os'
23
26
  import path from 'node:path'
24
27
 
25
- const ARCHIVE_VERSION = 1
28
+ const ARCHIVE_VERSION = 2
26
29
  const ARCHIVE_CAP = 500
27
30
  const POINTS_CAP = 32
31
+ const PRECIPITATED_CAP = 300
28
32
  const SECRET_PATTERN = /(?:sk-[a-zA-Z0-9_-]{16,}|ghp_[a-zA-Z0-9]{20,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{30,}|Bearer\s+[A-Za-z0-9._~+/=-]{20,}|-----BEGIN [A-Z ]*PRIVATE KEY-----)/
29
33
 
30
34
  export const DEFAULT_ARCHIVE_FOLDERS = [
@@ -96,12 +100,96 @@ function cleanMultiline(v, max) {
96
100
  return text.slice(0, Math.max(0, max - 1)) + '…'
97
101
  }
98
102
 
99
- export function archiveFilePath(customSharedBoardFile) {
100
- if (customSharedBoardFile) {
101
- return path.join(path.dirname(customSharedBoardFile), 'archives.json')
103
+ /* ------------------------------------------- Paths, Project Key & Registry */
104
+
105
+ export function normalizeCwd(cwd) {
106
+ const raw = str(cwd, '').trim()
107
+ if (!raw) return ''
108
+ try {
109
+ let resolved = path.resolve(raw)
110
+ if (resolved.length > 3) {
111
+ resolved = resolved.replace(/[\\/]+$/, '')
112
+ }
113
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved
114
+ } catch {
115
+ return raw.replace(/[\\/]+$/, '').toLowerCase()
116
+ }
117
+ }
118
+
119
+ export function resolveProjectKey(cwd = '') {
120
+ const raw = str(cwd, '').trim()
121
+ if (!raw) return 'proj-default'
122
+ if (/^proj-[a-z0-9._-]+$/i.test(raw) && !raw.includes('\\') && !raw.includes('/')) {
123
+ return raw.slice(0, 64)
124
+ }
125
+ const norm = normalizeCwd(raw)
126
+ if (!norm) return 'proj-default'
127
+ const baseRaw = path.basename(norm) || 'workspace'
128
+ const safeBase = baseRaw
129
+ .toLowerCase()
130
+ .replace(/[^a-z0-9\u4e00-\u9fa5._-]+/g, '-')
131
+ .replace(/^-+|-+$/g, '')
132
+ .slice(0, 22) || 'ws'
133
+ const hash8 = crypto.createHash('sha1').update(norm).digest('hex').slice(0, 8)
134
+ return `proj-${safeBase}-${hash8}`
135
+ }
136
+
137
+ function chiefRootDir(targetOpt) {
138
+ let sharedFile = ''
139
+ if (typeof targetOpt === 'string') {
140
+ sharedFile = targetOpt
141
+ } else if (targetOpt && typeof targetOpt === 'object') {
142
+ sharedFile = str(targetOpt.customSharedBoardFile || targetOpt.sharedFile, '').trim()
143
+ }
144
+ if (sharedFile) {
145
+ return path.dirname(sharedFile)
102
146
  }
103
147
  const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
104
- return path.join(home, 'chief', 'archives.json')
148
+ return path.join(home, 'chief')
149
+ }
150
+
151
+ function resolveTargetOpts(targetOpt) {
152
+ if (!targetOpt || typeof targetOpt === 'string') {
153
+ return {
154
+ customSharedBoardFile: str(targetOpt, ''),
155
+ cwd: '',
156
+ projectKey: '',
157
+ cabinetId: '',
158
+ }
159
+ }
160
+ return {
161
+ customSharedBoardFile: str(targetOpt.customSharedBoardFile || targetOpt.sharedFile, ''),
162
+ cwd: str(targetOpt.cwd, ''),
163
+ projectKey: str(targetOpt.projectKey, ''),
164
+ cabinetId: str(targetOpt.cabinetId, ''),
165
+ }
166
+ }
167
+
168
+ export function legacyArchiveFilePath(targetOpt) {
169
+ return path.join(chiefRootDir(targetOpt), 'archives.json')
170
+ }
171
+
172
+ export function cabinetsDirPath(targetOpt) {
173
+ return path.join(chiefRootDir(targetOpt), 'cabinets')
174
+ }
175
+
176
+ export function cabinetRegistryPath(targetOpt) {
177
+ return path.join(cabinetsDirPath(targetOpt), 'registry.json')
178
+ }
179
+
180
+ export function cabinetFilePath(cabinetId = 'cab-main', targetOpt) {
181
+ const safe = String(cabinetId || 'cab-main').replace(/[^a-zA-Z0-9._-]+/g, '-').slice(0, 72) || 'cab-main'
182
+ return path.join(cabinetsDirPath(targetOpt), `${safe}.json`)
183
+ }
184
+
185
+ export function precipitatedFilePath(projectKey = 'proj-default', targetOpt) {
186
+ const safe = resolveProjectKey(projectKey || 'proj-default').replace(/[^a-zA-Z0-9\u4e00-\u9fa5._-]+/g, '-').slice(0, 72) || 'proj-default'
187
+ return path.join(chiefRootDir(targetOpt), 'precipitated', `${safe}.json`)
188
+ }
189
+
190
+ export function archiveFilePath(targetOpt) {
191
+ const resolved = ensureProjectCabinet(targetOpt)
192
+ return resolved.cabinetFile
105
193
  }
106
194
 
107
195
  /* ----------------------------------------------------------- Lock & Storage */
@@ -115,7 +203,7 @@ function sleepSync(ms) {
115
203
  } catch {}
116
204
  }
117
205
 
118
- function acquireArchiveLock(file) {
206
+ function acquireFileLock(file) {
119
207
  if (heldArchiveLocks.has(file)) return () => {}
120
208
  const lock = file + '.lock'
121
209
  try {
@@ -162,6 +250,206 @@ export function invalidateArchiveCache() {
162
250
  archiveCache = { file: '', mtime: -1, store: null }
163
251
  }
164
252
 
253
+ function atomicWriteJson(file, data) {
254
+ fs.mkdirSync(path.dirname(file), { recursive: true })
255
+ const tmp = file + '.' + process.pid + '.' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 6) + '.tmp'
256
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf8')
257
+ fs.renameSync(tmp, file)
258
+ }
259
+
260
+ function readJsonSafe(file, fallback = null) {
261
+ try {
262
+ if (!fs.existsSync(file)) return fallback
263
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
264
+ } catch {
265
+ return fallback
266
+ }
267
+ }
268
+
269
+ /* ------------------------------------------- Registry & Legacy Migration */
270
+
271
+ function normalizeRegistry(raw) {
272
+ const src = raw && typeof raw === 'object' ? raw : {}
273
+ const projects = {}
274
+ if (src.projects && typeof src.projects === 'object') {
275
+ for (const [k, proj] of Object.entries(src.projects)) {
276
+ if (!proj || typeof proj !== 'object') continue
277
+ const pKey = resolveProjectKey(k)
278
+ const cabinets = (Array.isArray(proj.cabinets) ? proj.cabinets : [])
279
+ .filter(c => c && typeof c === 'object' && str(c.id, '').trim())
280
+ .map(c => ({
281
+ id: str(c.id, '').trim().slice(0, 72),
282
+ name: clamp(c.name || '默认档案柜', 40),
283
+ projectKey: pKey,
284
+ cwd: str(c.cwd, '').slice(0, 260),
285
+ createdAt: Number(c.createdAt) || Date.now(),
286
+ updatedAt: Number(c.updatedAt) || Number(c.createdAt) || Date.now(),
287
+ }))
288
+ if (!cabinets.length) continue
289
+ const activeCabinetId = cabinets.some(c => c.id === proj.activeCabinetId)
290
+ ? proj.activeCabinetId
291
+ : cabinets[0].id
292
+ projects[pKey] = {
293
+ projectKey: pKey,
294
+ cwd: str(proj.cwd, '').slice(0, 260),
295
+ activeCabinetId,
296
+ cabinets,
297
+ }
298
+ }
299
+ }
300
+ return {
301
+ version: ARCHIVE_VERSION,
302
+ migratedLegacy: Boolean(src.migratedLegacy),
303
+ migratedAt: Number(src.migratedAt) || 0,
304
+ legacyOwnerProjectKey: str(src.legacyOwnerProjectKey, ''),
305
+ projects,
306
+ }
307
+ }
308
+
309
+ function writeRegistryRaw(regFile, registry) {
310
+ atomicWriteJson(regFile, normalizeRegistry(registry))
311
+ }
312
+
313
+ function ensureProjectCabinet(targetOpt) {
314
+ const opts = resolveTargetOpts(targetOpt)
315
+ const regFile = cabinetRegistryPath(opts.customSharedBoardFile)
316
+ const legacyFile = legacyArchiveFilePath(opts.customSharedBoardFile)
317
+ const projectKey = opts.projectKey ? resolveProjectKey(opts.projectKey) : resolveProjectKey(opts.cwd)
318
+
319
+ const release = acquireFileLock(regFile)
320
+ try {
321
+ let reg = normalizeRegistry(readJsonSafe(regFile, null))
322
+ let dirty = false
323
+
324
+ // 1. One-time lossless migration from legacy `%DSH_HOME%/chief/archives.json` -> `cabinets/cab-main.json`
325
+ if (!reg.migratedLegacy && fs.existsSync(legacyFile)) {
326
+ const legacyParsed = readJsonSafe(legacyFile, null)
327
+ const cabMainFile = cabinetFilePath('cab-main', opts.customSharedBoardFile)
328
+ if (legacyParsed && !fs.existsSync(cabMainFile)) {
329
+ const normalizedLegacy = normalizeArchiveStore({
330
+ ...legacyParsed,
331
+ cabinetId: 'cab-main',
332
+ cabinetName: '默认主档案柜',
333
+ projectKey,
334
+ })
335
+ atomicWriteJson(cabMainFile, normalizedLegacy)
336
+ }
337
+ if (!reg.projects[projectKey]) {
338
+ const now = Date.now()
339
+ reg.projects[projectKey] = {
340
+ projectKey,
341
+ cwd: opts.cwd,
342
+ activeCabinetId: 'cab-main',
343
+ cabinets: [
344
+ {
345
+ id: 'cab-main',
346
+ name: opts.cwd ? `${path.basename(opts.cwd) || '当前工程'} · 主档案柜` : '默认主档案柜',
347
+ projectKey,
348
+ cwd: opts.cwd,
349
+ createdAt: now,
350
+ updatedAt: now,
351
+ },
352
+ ],
353
+ }
354
+ reg.legacyOwnerProjectKey = projectKey
355
+ }
356
+ reg.migratedLegacy = true
357
+ reg.migratedAt = Date.now()
358
+ dirty = true
359
+ }
360
+
361
+ // 2. Ensure requested projectKey exists in registry
362
+ if (!reg.projects[projectKey]) {
363
+ const now = Date.now()
364
+ const hasMainAlready = Object.values(reg.projects).some(p => p.cabinets.some(c => c.id === 'cab-main'))
365
+ const defaultCabId = hasMainAlready ? `cab-${projectKey.slice(-8)}-main` : 'cab-main'
366
+ const labelPrefix = opts.cwd ? (path.basename(normalizeCwd(opts.cwd)) || '当前工程') : '默认'
367
+ const cabFile = cabinetFilePath(defaultCabId, opts.customSharedBoardFile)
368
+ if (!fs.existsSync(cabFile)) {
369
+ atomicWriteJson(cabFile, normalizeArchiveStore({
370
+ cabinetId: defaultCabId,
371
+ cabinetName: `${labelPrefix} · 主档案柜`,
372
+ projectKey,
373
+ }))
374
+ }
375
+ reg.projects[projectKey] = {
376
+ projectKey,
377
+ cwd: opts.cwd,
378
+ activeCabinetId: defaultCabId,
379
+ cabinets: [
380
+ {
381
+ id: defaultCabId,
382
+ name: `${labelPrefix} · 主档案柜`,
383
+ projectKey,
384
+ cwd: opts.cwd,
385
+ createdAt: now,
386
+ updatedAt: now,
387
+ },
388
+ ],
389
+ }
390
+ dirty = true
391
+ } else if (opts.cwd && !reg.projects[projectKey].cwd) {
392
+ reg.projects[projectKey].cwd = opts.cwd
393
+ dirty = true
394
+ }
395
+
396
+ const projEntry = reg.projects[projectKey]
397
+ let selectedCabinet = null
398
+ if (opts.cabinetId) {
399
+ selectedCabinet = projEntry.cabinets.find(c => c.id === opts.cabinetId) || null
400
+ if (!selectedCabinet) {
401
+ // Also check across projects if an explicit cabinetId was passed
402
+ for (const p of Object.values(reg.projects)) {
403
+ const hit = p.cabinets.find(c => c.id === opts.cabinetId)
404
+ if (hit) {
405
+ selectedCabinet = hit
406
+ break
407
+ }
408
+ }
409
+ }
410
+ }
411
+ if (!selectedCabinet) {
412
+ selectedCabinet = projEntry.cabinets.find(c => c.id === projEntry.activeCabinetId) || projEntry.cabinets[0]
413
+ }
414
+
415
+ const selectedFile = cabinetFilePath(selectedCabinet.id, opts.customSharedBoardFile)
416
+ if (!fs.existsSync(selectedFile)) {
417
+ atomicWriteJson(selectedFile, normalizeArchiveStore({
418
+ cabinetId: selectedCabinet.id,
419
+ cabinetName: selectedCabinet.name,
420
+ projectKey: selectedCabinet.projectKey,
421
+ }))
422
+ }
423
+
424
+ if (dirty || !fs.existsSync(regFile)) {
425
+ writeRegistryRaw(regFile, reg)
426
+ }
427
+
428
+ return {
429
+ projectKey,
430
+ cabinetId: selectedCabinet.id,
431
+ cabinetName: selectedCabinet.name,
432
+ cabinetFile: selectedFile,
433
+ registry: reg,
434
+ projectEntry: projEntry,
435
+ }
436
+ } finally {
437
+ release()
438
+ }
439
+ }
440
+
441
+ export function listProjectCabinets(targetOpt) {
442
+ const resolved = ensureProjectCabinet(targetOpt)
443
+ return {
444
+ ok: true,
445
+ projectKey: resolved.projectKey,
446
+ activeCabinetId: resolved.projectEntry.activeCabinetId,
447
+ cabinets: resolved.projectEntry.cabinets.map(c => ({ ...c })),
448
+ }
449
+ }
450
+
451
+ /* ------------------------------------------- Normalization */
452
+
165
453
  function normalizeFolder(raw, index = 0) {
166
454
  if (!raw || typeof raw !== 'object') return null
167
455
  const id = str(raw.id, '').trim().slice(0, 64)
@@ -198,7 +486,6 @@ function normalizeTags(list) {
198
486
  for (const raw of list) {
199
487
  const t = String(raw || '').trim().slice(0, 36)
200
488
  if (!t) continue
201
- // Strip internal routing tag 'anchor' from visual display tags while preserving paperclip='gold'
202
489
  if (t.toLowerCase() === 'anchor') continue
203
490
  const low = t.toLowerCase()
204
491
  if (seen.has(low)) continue
@@ -237,7 +524,7 @@ function normalizeArchiveItem(raw) {
237
524
  )
238
525
 
239
526
  const takenOutSessions = Array.isArray(raw.takenOutSessions)
240
- ? [...new Set(raw.takenOutSessions.map(s => String(s || '').trim()).filter(Boolean))].slice(0, 24)
527
+ ? [...new Set(raw.takenOutSessions.map(s => String(s || '').trim()).filter(Boolean))].slice(0, 32)
241
528
  : []
242
529
 
243
530
  return {
@@ -278,7 +565,6 @@ function normalizeArchiveStore(raw) {
278
565
  .filter(Boolean)
279
566
  .slice(0, ARCHIVE_CAP)
280
567
 
281
- // Ensure any custom folder referenced by an item exists in `folders`
282
568
  let customIdx = 0
283
569
  for (const item of items) {
284
570
  if (item.folder && !folderMap.has(item.folder)) {
@@ -297,6 +583,9 @@ function normalizeArchiveStore(raw) {
297
583
 
298
584
  return {
299
585
  version: ARCHIVE_VERSION,
586
+ cabinetId: str(src.cabinetId, 'cab-main').trim() || 'cab-main',
587
+ cabinetName: clamp(src.cabinetName || '默认主档案柜', 40),
588
+ projectKey: resolveProjectKey(src.projectKey || 'proj-default'),
300
589
  migratedSharedAt: Number(src.migratedSharedAt) || 0,
301
590
  updatedAt: Number(src.updatedAt) || Date.now(),
302
591
  folders,
@@ -304,30 +593,43 @@ function normalizeArchiveStore(raw) {
304
593
  }
305
594
  }
306
595
 
307
- export function loadArchiveStore(customSharedBoardFile) {
308
- const file = archiveFilePath(customSharedBoardFile)
596
+ export function loadArchiveStore(targetOpt) {
597
+ const resolved = ensureProjectCabinet(targetOpt)
598
+ const file = resolved.cabinetFile
309
599
  try {
310
600
  const st = fs.statSync(file)
311
601
  if (archiveCache.store && archiveCache.file === file && archiveCache.mtime === st.mtimeMs) {
312
602
  return archiveCache.store
313
603
  }
314
604
  const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
315
- const store = normalizeArchiveStore(parsed)
605
+ const store = normalizeArchiveStore({
606
+ ...parsed,
607
+ cabinetId: resolved.cabinetId,
608
+ cabinetName: resolved.cabinetName,
609
+ projectKey: resolved.projectKey,
610
+ })
316
611
  archiveCache = { file, mtime: st.mtimeMs, store }
317
612
  return store
318
613
  } catch {
319
- const empty = normalizeArchiveStore({})
320
- return empty
614
+ return normalizeArchiveStore({
615
+ cabinetId: resolved.cabinetId,
616
+ cabinetName: resolved.cabinetName,
617
+ projectKey: resolved.projectKey,
618
+ })
321
619
  }
322
620
  }
323
621
 
324
- export function saveArchiveStore(store, customSharedBoardFile) {
325
- const file = archiveFilePath(customSharedBoardFile)
326
- const normalized = normalizeArchiveStore({ ...store, updatedAt: Date.now() })
327
- fs.mkdirSync(path.dirname(file), { recursive: true })
328
- const tmp = file + '.' + process.pid + '.' + Date.now().toString(36) + '.tmp'
329
- fs.writeFileSync(tmp, JSON.stringify(normalized, null, 2), 'utf8')
330
- fs.renameSync(tmp, file)
622
+ export function saveArchiveStore(store, targetOpt) {
623
+ const resolved = ensureProjectCabinet(targetOpt)
624
+ const file = resolved.cabinetFile
625
+ const normalized = normalizeArchiveStore({
626
+ ...store,
627
+ cabinetId: resolved.cabinetId,
628
+ cabinetName: resolved.cabinetName,
629
+ projectKey: resolved.projectKey,
630
+ updatedAt: Date.now(),
631
+ })
632
+ atomicWriteJson(file, normalized)
331
633
  let mtime = Date.now()
332
634
  try {
333
635
  mtime = fs.statSync(file).mtimeMs
@@ -336,12 +638,13 @@ export function saveArchiveStore(store, customSharedBoardFile) {
336
638
  return normalized
337
639
  }
338
640
 
339
- export function withArchiveLock(customSharedBoardFile, fn) {
340
- const file = archiveFilePath(customSharedBoardFile)
341
- const release = acquireArchiveLock(file)
641
+ export function withArchiveLock(targetOpt, fn) {
642
+ const resolved = ensureProjectCabinet(targetOpt)
643
+ const file = resolved.cabinetFile
644
+ const release = acquireFileLock(file)
342
645
  invalidateArchiveCache()
343
646
  try {
344
- return fn(file)
647
+ return fn(file, resolved)
345
648
  } finally {
346
649
  release()
347
650
  }
@@ -363,7 +666,6 @@ function firstMeaningfulSentence(text) {
363
666
  .map(l => l.trim())
364
667
  .filter(l => l && !/^\|[-:\s|]+\|$/.test(l) && !/^```/.test(l))
365
668
  if (!lines.length) return ''
366
- // Skip bare markdown heading if next line has substance
367
669
  const candidate = (/^#{1,4}\s+/.test(lines[0]) && lines[1]) ? lines[1] : lines[0]
368
670
  const clean = stripMarkdownDecorators(candidate)
369
671
  const firstClause = clean.split(/[。;!?\n]/)[0] || clean
@@ -410,10 +712,6 @@ function inferPaperclip(raw, folder) {
410
712
  return 'silver'
411
713
  }
412
714
 
413
- /**
414
- * Parse raw Markdown/prose engineering notes into structured Memory Points (`记忆点 -> 小点记忆`),
415
- * while keeping raw `body` 100% intact on the parent dossier.
416
- */
417
715
  export function extractStructuredPoints(title, rawBody) {
418
716
  const body = String(rawBody || '').replace(/\r/g, '').trim()
419
717
  if (!body) {
@@ -428,8 +726,6 @@ export function extractStructuredPoints(title, rawBody) {
428
726
  }
429
727
 
430
728
  const lines = body.split('\n')
431
-
432
- // Strategy 1: Markdown Headings (`## ...` or `### ...`)
433
729
  const headingIndices = []
434
730
  for (let i = 0; i < lines.length; i += 1) {
435
731
  if (/^#{2,3}\s+\S/.test(lines[i].trim())) {
@@ -438,10 +734,7 @@ export function extractStructuredPoints(title, rawBody) {
438
734
  }
439
735
  if (headingIndices.length >= 1) {
440
736
  const points = []
441
- // Capture preface before first ## heading if substantial (excluding redundant `# Title`)
442
- const preLines = lines
443
- .slice(0, headingIndices[0])
444
- .filter(l => !/^#\s+/.test(l.trim()))
737
+ const preLines = lines.slice(0, headingIndices[0]).filter(l => !/^#\s+/.test(l.trim()))
445
738
  const preText = preLines.join('\n').trim()
446
739
  if (preText.length >= 18) {
447
740
  points.push({
@@ -467,7 +760,6 @@ export function extractStructuredPoints(title, rawBody) {
467
760
  if (points.length >= 1) return points.slice(0, POINTS_CAP)
468
761
  }
469
762
 
470
- // Strategy 2: Labeled Key-Value Blocks (`包体/源码:...`, `部署态验证:...`, `数据:...`, `坑:...`)
471
763
  const kvBlocks = []
472
764
  let currentKv = null
473
765
  for (const rawLine of lines) {
@@ -509,7 +801,6 @@ export function extractStructuredPoints(title, rawBody) {
509
801
  })
510
802
  }
511
803
 
512
- // Strategy 3: Paragraph / Numbered-List / Sentence-Cluster Splitting
513
804
  const paragraphs = body
514
805
  .split(/\n{2,}/)
515
806
  .map(p => p.trim())
@@ -527,7 +818,6 @@ export function extractStructuredPoints(title, rawBody) {
527
818
  })
528
819
  }
529
820
 
530
- // Strategy 4: Dense single-paragraph prose -> split into logical clauses (`。` / `;`) if long
531
821
  const sentences = body
532
822
  .split(/(?<=[。!?;])\s*/)
533
823
  .map(s => s.trim())
@@ -585,35 +875,29 @@ export function smartParseNoteToDossier(rawNote) {
585
875
 
586
876
  /* ------------------------------------ Non-Destructive Bootstrap Migration */
587
877
 
588
- /**
589
- * One-time lossless migration of legacy shared-board engineering notes into `archives.json`.
590
- * 1. Writes a full backup of `board.json` to `board.pre-archive-backup.json` (never overwrites).
591
- * 2. Converts every existing note on the shared board into a cold-stored structured dossier in `archives.json`.
592
- * 3. Clears those migrated notes off `sharedBoard.notes` so they stop polluting every turn's prompt digest!
593
- */
594
878
  export function bootstrapArchivesFromSharedBoard({ sharedFile, loadBoard, saveBoard, pushLog }) {
595
879
  try {
596
880
  if (!sharedFile || !fs.existsSync(sharedFile)) return { migrated: 0 }
597
- const archFile = archiveFilePath(sharedFile)
598
- if (fs.existsSync(archFile)) {
599
- const existing = loadArchiveStore(sharedFile)
600
- if (existing.migratedSharedAt > 0 || existing.items.length > 0) {
601
- return { migrated: 0 }
602
- }
881
+ // Ensure legacy `archives.json` is migrated to `cabinets/cab-main.json` first
882
+ const resolved = ensureProjectCabinet({ customSharedBoardFile: sharedFile })
883
+ const existing = loadArchiveStore({ customSharedBoardFile: sharedFile, cabinetId: resolved.cabinetId })
884
+ if (existing.migratedSharedAt > 0 && existing.items.length > 0) {
885
+ return { migrated: 0 }
603
886
  }
604
887
 
605
888
  const sharedBoard = loadBoard(sharedFile)
606
889
  const legacyNotes = Array.isArray(sharedBoard && sharedBoard.notes) ? sharedBoard.notes : []
607
890
  if (!legacyNotes.length) {
608
- withArchiveLock(sharedFile, () => {
609
- const empty = loadArchiveStore(sharedFile)
610
- empty.migratedSharedAt = Date.now()
611
- saveArchiveStore(empty, sharedFile)
612
- })
891
+ if (!existing.migratedSharedAt) {
892
+ withArchiveLock({ customSharedBoardFile: sharedFile, cabinetId: resolved.cabinetId }, () => {
893
+ const empty = loadArchiveStore({ customSharedBoardFile: sharedFile, cabinetId: resolved.cabinetId })
894
+ empty.migratedSharedAt = Date.now()
895
+ saveArchiveStore(empty, { customSharedBoardFile: sharedFile, cabinetId: resolved.cabinetId })
896
+ })
897
+ }
613
898
  return { migrated: 0 }
614
899
  }
615
900
 
616
- // 1. Safety backup of `board.json` before touching anything
617
901
  const backupFile = path.join(path.dirname(sharedFile), 'board.pre-archive-backup.json')
618
902
  try {
619
903
  if (!fs.existsSync(backupFile)) {
@@ -621,10 +905,9 @@ export function bootstrapArchivesFromSharedBoard({ sharedFile, loadBoard, saveBo
621
905
  }
622
906
  } catch {}
623
907
 
624
- // 2. Precipitate all legacy notes into cold archives
625
908
  let migratedCount = 0
626
- withArchiveLock(sharedFile, () => {
627
- const store = loadArchiveStore(sharedFile)
909
+ withArchiveLock({ customSharedBoardFile: sharedFile, cabinetId: resolved.cabinetId }, () => {
910
+ const store = loadArchiveStore({ customSharedBoardFile: sharedFile, cabinetId: resolved.cabinetId })
628
911
  const existingSourceIds = new Set(store.items.map(it => it.sourceNoteId).filter(Boolean))
629
912
  const existingTitles = new Set(store.items.map(it => it.title))
630
913
 
@@ -660,10 +943,9 @@ export function bootstrapArchivesFromSharedBoard({ sharedFile, loadBoard, saveBo
660
943
  }
661
944
 
662
945
  store.migratedSharedAt = Date.now()
663
- saveArchiveStore(store, sharedFile)
946
+ saveArchiveStore(store, { customSharedBoardFile: sharedFile, cabinetId: resolved.cabinetId })
664
947
  })
665
948
 
666
- // 3. Remove migrated long-term notes from shared `board.json` so prompt auto-injection drops to ZERO
667
949
  if (migratedCount > 0 && typeof saveBoard === 'function') {
668
950
  sharedBoard.notes = []
669
951
  if (typeof pushLog === 'function') {
@@ -685,9 +967,10 @@ export function bootstrapArchivesFromSharedBoard({ sharedFile, loadBoard, saveBo
685
967
 
686
968
  /* ------------------------------------------- Lazy-Loading Query & Mutations */
687
969
 
688
- /** Ultra-lightweight metadata (<80 bytes) for `/snapshot` polling — ZERO archive text/headers! */
689
- export function getArchiveMeta(rootSessionId = '', customSharedBoardFile) {
690
- const store = loadArchiveStore(customSharedBoardFile)
970
+ /** Ultra-lightweight metadata (<120 bytes) for `/snapshot` polling — ZERO archive text or precipitated reads! */
971
+ export function getArchiveMeta(rootSessionId = '', targetOpt) {
972
+ const cabInfo = listProjectCabinets(targetOpt)
973
+ const store = loadArchiveStore(targetOpt)
691
974
  const sid = String(rootSessionId || '').trim()
692
975
  const nonEmptyFolders = new Set(store.items.map(it => it.folder).filter(Boolean))
693
976
  const takenOutCount = sid
@@ -698,15 +981,25 @@ export function getArchiveMeta(rootSessionId = '', customSharedBoardFile) {
698
981
  folderCount: nonEmptyFolders.size || DEFAULT_ARCHIVE_FOLDERS.length,
699
982
  takenOutCount,
700
983
  unorganizedCount: store.items.filter(it => it.folder === 'inbox' || it.organizedBy === 'auto').length,
984
+ projectKey: cabInfo.projectKey,
985
+ activeCabinetId: cabInfo.activeCabinetId,
986
+ cabinetCount: cabInfo.cabinets.length,
701
987
  }
702
988
  }
703
989
 
704
990
  /**
705
991
  * Tier-1 Lazy Load (`GET /api/dsh-chief/archives`):
706
- * Returns folder drawers + slim dossier headers ONLY (no `points` details, no `body`!).
992
+ * Returns active cabinet drawers + dossier headers + project cabinets list
993
+ * (+ precipitated vault headers ONLY for the Archives tab UI when caller asks for them).
707
994
  */
708
- export function listArchiveHeaders(rootSessionId = '', opts = {}, customSharedBoardFile) {
709
- const store = loadArchiveStore(customSharedBoardFile)
995
+ export function listArchiveHeaders(rootSessionId = '', opts = {}, targetOpt) {
996
+ const target = targetOpt !== undefined
997
+ ? (typeof targetOpt === 'string'
998
+ ? { customSharedBoardFile: targetOpt, cwd: opts && opts.cwd, projectKey: opts && opts.projectKey, cabinetId: opts && opts.cabinetId }
999
+ : { ...opts, ...targetOpt })
1000
+ : opts
1001
+ const cabInfo = listProjectCabinets(target)
1002
+ const store = loadArchiveStore(target)
710
1003
  const sid = String(rootSessionId || '').trim()
711
1004
  const needle = String((opts && opts.query) || '').trim().toLowerCase()
712
1005
  const folderFilter = String((opts && opts.folder) || '').trim()
@@ -768,23 +1061,28 @@ export function listArchiveHeaders(rootSessionId = '', opts = {}, customSharedBo
768
1061
  createdAt: it.createdAt,
769
1062
  }))
770
1063
 
1064
+ const includePrecipitated = Boolean(opts && opts.includePrecipitated)
1065
+ const precipitated = includePrecipitated
1066
+ ? listPrecipitatedHeaders(cabInfo.projectKey, sid, target)
1067
+ : undefined
1068
+
771
1069
  return {
772
1070
  ok: true,
1071
+ projectKey: cabInfo.projectKey,
1072
+ activeCabinetId: cabInfo.activeCabinetId,
1073
+ cabinets: cabInfo.cabinets,
773
1074
  totalCount: store.items.length,
774
1075
  takenOutCount: sid ? store.items.filter(it => it.takenOutSessions.includes(sid)).length : 0,
775
1076
  folders,
776
1077
  items: headers,
1078
+ ...(precipitated !== undefined ? { precipitated } : {}),
777
1079
  }
778
1080
  }
779
1081
 
780
- /**
781
- * Tier-2 Lazy Load (`GET /api/dsh-chief/archives/detail?id=...`):
782
- * Loaded ONLY when a user clicks a dossier file or an agent calls `archive.read`.
783
- */
784
- export function getArchiveDetail(idOrTitle = '', rootSessionId = '', customSharedBoardFile) {
1082
+ export function getArchiveDetail(idOrTitle = '', rootSessionId = '', targetOpt) {
785
1083
  const target = String(idOrTitle || '').trim()
786
1084
  if (!target) return { ok: false, error: 'archive id or title required' }
787
- const store = loadArchiveStore(customSharedBoardFile)
1085
+ const store = loadArchiveStore(targetOpt)
788
1086
  const sid = String(rootSessionId || '').trim()
789
1087
  const hit = store.items.find(it => it.id === target)
790
1088
  || store.items.find(it => it.title === target)
@@ -813,19 +1111,23 @@ export function getArchiveDetail(idOrTitle = '', rootSessionId = '', customShare
813
1111
  }
814
1112
 
815
1113
  /**
816
- * Strictly returns ONLY dossiers that the user has EXPLICITLY taken out onto the current session desk.
817
- * Sealed/cold dossiers (`takenOutSessions` without `rootSessionId`) NEVER appear here!
1114
+ * Strictly returns ONLY dossiers explicitly taken out onto the current session desk.
1115
+ * NEVER reads `precipitated/<projectKey>.json`!
818
1116
  */
819
- export function getTakenOutArchivesForSession(rootSessionId = '', customSharedBoardFile) {
1117
+ export function getTakenOutArchivesForSession(rootSessionId = '', targetOpt) {
820
1118
  const sid = String(rootSessionId || '').trim()
821
1119
  if (!sid) return []
822
- const store = loadArchiveStore(customSharedBoardFile)
1120
+ const store = loadArchiveStore(targetOpt)
823
1121
  return store.items.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid))
824
1122
  }
825
1123
 
826
- /** On-demand search for `chief_board({ action: "archive.search" })` or Chief explicit lookup. */
827
- export function searchArchives(query = '', opts = {}, customSharedBoardFile) {
828
- const store = loadArchiveStore(customSharedBoardFile)
1124
+ /** On-demand search for `chief_board({ action: "archive.search" })` or Chief explicit lookup.
1125
+ * Strictly searches ONLY working cabinets — NEVER reads `precipitated/<projectKey>.json`! */
1126
+ export function searchArchives(query = '', opts = {}, targetOpt) {
1127
+ const effectiveTarget = targetOpt !== undefined
1128
+ ? targetOpt
1129
+ : (opts && (opts.cwd || opts.projectKey || opts.cabinetId || opts.customSharedBoardFile) ? opts : undefined)
1130
+ const store = loadArchiveStore(effectiveTarget)
829
1131
  const folder = String((opts && opts.folder) || '').trim()
830
1132
  const limit = Math.max(1, Math.min(Number(opts && opts.limit) || 8, 25))
831
1133
  const rawQ = String(query || '').trim().toLowerCase()
@@ -882,12 +1184,164 @@ export function searchArchives(query = '', opts = {}, customSharedBoardFile) {
882
1184
  }
883
1185
  }
884
1186
 
885
- export function mutateArchive(payload = {}, customSharedBoardFile) {
1187
+ /* ------------------------------------------- Cabinet & Archive Mutations */
1188
+
1189
+ function mutateCabinetRegistry(payload = {}, targetOpt) {
1190
+ const op = str(payload.op, '').trim()
1191
+ const opts = resolveTargetOpts(targetOpt)
1192
+ const resolvedInit = ensureProjectCabinet({
1193
+ ...opts,
1194
+ cwd: str(payload.cwd, opts.cwd),
1195
+ projectKey: str(payload.projectKey, opts.projectKey),
1196
+ })
1197
+ const regFile = cabinetRegistryPath(opts.customSharedBoardFile)
1198
+ const projectKey = resolvedInit.projectKey
1199
+
1200
+ if (op === 'listCabinets') {
1201
+ return listProjectCabinets({ ...opts, projectKey })
1202
+ }
1203
+
1204
+ const release = acquireFileLock(regFile)
1205
+ try {
1206
+ const reg = normalizeRegistry(readJsonSafe(regFile, null))
1207
+ const proj = reg.projects[projectKey] || resolvedInit.projectEntry
1208
+ reg.projects[projectKey] = proj
1209
+
1210
+ if (op === 'createCabinet') {
1211
+ const name = clamp(payload.name || payload.label || `工作档案柜 ${proj.cabinets.length + 1}`, 40)
1212
+ const dup = proj.cabinets.find(c => c.name === name)
1213
+ if (dup) {
1214
+ proj.activeCabinetId = dup.id
1215
+ writeRegistryRaw(regFile, reg)
1216
+ invalidateArchiveCache()
1217
+ return {
1218
+ ok: true,
1219
+ cabinet: dup,
1220
+ activeCabinetId: proj.activeCabinetId,
1221
+ cabinets: proj.cabinets,
1222
+ projectKey,
1223
+ }
1224
+ }
1225
+ const id = nextId('cab')
1226
+ const now = Date.now()
1227
+ const cabMeta = {
1228
+ id,
1229
+ name,
1230
+ projectKey,
1231
+ cwd: proj.cwd || str(payload.cwd, opts.cwd),
1232
+ createdAt: now,
1233
+ updatedAt: now,
1234
+ }
1235
+ const cabFile = cabinetFilePath(id, opts.customSharedBoardFile)
1236
+ atomicWriteJson(cabFile, normalizeArchiveStore({
1237
+ cabinetId: id,
1238
+ cabinetName: name,
1239
+ projectKey,
1240
+ }))
1241
+ proj.cabinets.push(cabMeta)
1242
+ proj.activeCabinetId = id
1243
+ writeRegistryRaw(regFile, reg)
1244
+ invalidateArchiveCache()
1245
+ return {
1246
+ ok: true,
1247
+ cabinet: cabMeta,
1248
+ activeCabinetId: proj.activeCabinetId,
1249
+ cabinets: proj.cabinets,
1250
+ projectKey,
1251
+ }
1252
+ }
1253
+
1254
+ if (op === 'switchCabinet') {
1255
+ const targetId = str(payload.cabinetId || payload.id, '').trim()
1256
+ const hit = proj.cabinets.find(c => c.id === targetId)
1257
+ if (!hit) return { ok: false, error: '未找到目标档案柜:' + targetId }
1258
+ proj.activeCabinetId = hit.id
1259
+ hit.updatedAt = Date.now()
1260
+ writeRegistryRaw(regFile, reg)
1261
+ invalidateArchiveCache()
1262
+ return {
1263
+ ok: true,
1264
+ cabinet: hit,
1265
+ activeCabinetId: proj.activeCabinetId,
1266
+ cabinets: proj.cabinets,
1267
+ projectKey,
1268
+ }
1269
+ }
1270
+
1271
+ if (op === 'renameCabinet') {
1272
+ const targetId = str(payload.cabinetId || payload.id, proj.activeCabinetId).trim()
1273
+ const name = clamp(payload.name || payload.label, 40)
1274
+ if (!name) return { ok: false, error: '请输入档案柜新名称' }
1275
+ const hit = proj.cabinets.find(c => c.id === targetId)
1276
+ if (!hit) return { ok: false, error: '未找到档案柜:' + targetId }
1277
+ hit.name = name
1278
+ hit.updatedAt = Date.now()
1279
+ writeRegistryRaw(regFile, reg)
1280
+ const cabFile = cabinetFilePath(hit.id, opts.customSharedBoardFile)
1281
+ const cabStore = normalizeArchiveStore(readJsonSafe(cabFile, { cabinetId: hit.id, projectKey }))
1282
+ cabStore.cabinetName = name
1283
+ atomicWriteJson(cabFile, cabStore)
1284
+ invalidateArchiveCache()
1285
+ return {
1286
+ ok: true,
1287
+ cabinet: hit,
1288
+ activeCabinetId: proj.activeCabinetId,
1289
+ cabinets: proj.cabinets,
1290
+ projectKey,
1291
+ }
1292
+ }
1293
+
1294
+ if (op === 'deleteCabinet') {
1295
+ const targetId = str(payload.cabinetId || payload.id, '').trim()
1296
+ if (proj.cabinets.length <= 1) {
1297
+ return { ok: false, error: '每个工程至少需保留一个主档案柜,不可删除最后一个档案柜' }
1298
+ }
1299
+ const idx = proj.cabinets.findIndex(c => c.id === targetId)
1300
+ if (idx < 0) return { ok: false, error: '未找到要删除的档案柜:' + targetId }
1301
+ const [removed] = proj.cabinets.splice(idx, 1)
1302
+ if (proj.activeCabinetId === removed.id) {
1303
+ proj.activeCabinetId = proj.cabinets[0].id
1304
+ }
1305
+ writeRegistryRaw(regFile, reg)
1306
+ try {
1307
+ const rmFile = cabinetFilePath(removed.id, opts.customSharedBoardFile)
1308
+ if (fs.existsSync(rmFile)) fs.unlinkSync(rmFile)
1309
+ } catch {}
1310
+ invalidateArchiveCache()
1311
+ return {
1312
+ ok: true,
1313
+ removedId: removed.id,
1314
+ activeCabinetId: proj.activeCabinetId,
1315
+ cabinets: proj.cabinets,
1316
+ projectKey,
1317
+ }
1318
+ }
1319
+
1320
+ return { ok: false, error: '未知的档案柜操作:' + op }
1321
+ } finally {
1322
+ release()
1323
+ }
1324
+ }
1325
+
1326
+ export function mutateArchive(payload = {}, targetOpt) {
886
1327
  const op = str(payload.op, 'save').trim()
887
1328
  const rootSessionId = str(payload.rootSessionId || payload.session, '').trim()
1329
+ const baseOpts = resolveTargetOpts(targetOpt)
1330
+ const effectiveTarget = {
1331
+ ...baseOpts,
1332
+ cwd: str(payload.cwd, baseOpts.cwd),
1333
+ projectKey: str(payload.projectKey, baseOpts.projectKey),
1334
+ cabinetId: str(payload.cabinetId, baseOpts.cabinetId),
1335
+ }
888
1336
 
889
- return withArchiveLock(customSharedBoardFile, () => {
890
- const store = loadArchiveStore(customSharedBoardFile)
1337
+ if (['listCabinets', 'createCabinet', 'switchCabinet', 'renameCabinet', 'deleteCabinet'].includes(op)) {
1338
+ return mutateCabinetRegistry(payload, effectiveTarget)
1339
+ }
1340
+
1341
+ return withArchiveLock(effectiveTarget, (_file, resolved) => {
1342
+ const store = loadArchiveStore({ ...effectiveTarget, cabinetId: resolved.cabinetId })
1343
+ const lockTarget = { ...effectiveTarget, cabinetId: resolved.cabinetId, projectKey: resolved.projectKey }
1344
+ const runOp = () => {
891
1345
 
892
1346
  if (op === 'createFolder' || op === 'saveFolder') {
893
1347
  const rawLabel = clamp(payload.label || payload.folderLabel || payload.folder, 40)
@@ -898,7 +1352,7 @@ export function mutateArchive(payload = {}, customSharedBoardFile) {
898
1352
  if (existing) {
899
1353
  if (payload.hint !== undefined) existing.hint = clamp(payload.hint, 100)
900
1354
  if (payload.accent) existing.accent = str(payload.accent, existing.accent).slice(0, 24)
901
- saveArchiveStore(store, customSharedBoardFile)
1355
+ saveArchiveStore(store, lockTarget)
902
1356
  return { ok: true, folder: existing }
903
1357
  }
904
1358
  const created = normalizeFolder({
@@ -909,7 +1363,7 @@ export function mutateArchive(payload = {}, customSharedBoardFile) {
909
1363
  order: 55 + store.folders.length,
910
1364
  })
911
1365
  store.folders.push(created)
912
- saveArchiveStore(store, customSharedBoardFile)
1366
+ saveArchiveStore(store, lockTarget)
913
1367
  return { ok: true, folder: created }
914
1368
  }
915
1369
 
@@ -958,15 +1412,14 @@ export function mutateArchive(payload = {}, customSharedBoardFile) {
958
1412
  )
959
1413
  }
960
1414
  existing.updatedAt = Date.now()
961
- saveArchiveStore(store, customSharedBoardFile)
962
- return { ok: true, item: existing, meta: getArchiveMeta(rootSessionId, customSharedBoardFile) }
1415
+ saveArchiveStore(store, lockTarget)
1416
+ return { ok: true, item: existing, meta: getArchiveMeta(rootSessionId, lockTarget) }
963
1417
  }
964
1418
 
965
1419
  const rawTitle = clamp(payload.title || '', 180)
966
1420
  if (!rawTitle && !nextBody) {
967
1421
  return { ok: false, error: '新建工程档案需要填写标题或正文内容' }
968
1422
  }
969
- // Dedupe if exact same title already archived and caller opted into upsert
970
1423
  const sameTitle = rawTitle ? store.items.find(it => it.title === rawTitle) : null
971
1424
  if (sameTitle && payload.upsertByTitle !== false) {
972
1425
  sameTitle.body = nextBody || sameTitle.body
@@ -983,8 +1436,8 @@ export function mutateArchive(payload = {}, customSharedBoardFile) {
983
1436
  140,
984
1437
  )
985
1438
  sameTitle.updatedAt = Date.now()
986
- saveArchiveStore(store, customSharedBoardFile)
987
- return { ok: true, item: sameTitle, updatedExisting: true, meta: getArchiveMeta(rootSessionId, customSharedBoardFile) }
1439
+ saveArchiveStore(store, lockTarget)
1440
+ return { ok: true, item: sameTitle, updatedExisting: true, meta: getArchiveMeta(rootSessionId, lockTarget) }
988
1441
  }
989
1442
 
990
1443
  const parsed = smartParseNoteToDossier({
@@ -1003,8 +1456,10 @@ export function mutateArchive(payload = {}, customSharedBoardFile) {
1003
1456
  paperclip: payload.paperclip || parsed.paperclip,
1004
1457
  tags: Array.isArray(payload.tags) ? payload.tags : (typeof payload.tags === 'string' ? payload.tags.split(/[,,]/) : []),
1005
1458
  cold: true,
1006
- takenOutSessions: payload.takeOutNow && rootSessionId ? [rootSessionId] : [],
1007
- organizedBy: Array.isArray(payload.points) && payload.points.length ? 'user' : 'auto',
1459
+ takenOutSessions: (payload.takeOutNow || payload.takeOut) && rootSessionId ? [rootSessionId] : [],
1460
+ organizedBy: ['auto', 'chief', 'user'].includes(payload.organizedBy)
1461
+ ? payload.organizedBy
1462
+ : (Array.isArray(payload.points) && payload.points.length ? 'user' : 'auto'),
1008
1463
  points: Array.isArray(payload.points) && payload.points.length ? payload.points : parsed.points,
1009
1464
  body: nextBody,
1010
1465
  by: payload.by || 'user',
@@ -1013,8 +1468,8 @@ export function mutateArchive(payload = {}, customSharedBoardFile) {
1013
1468
  updatedAt: Date.now(),
1014
1469
  })
1015
1470
  store.items.unshift(created)
1016
- saveArchiveStore(store, customSharedBoardFile)
1017
- return { ok: true, item: created, meta: getArchiveMeta(rootSessionId, customSharedBoardFile) }
1471
+ saveArchiveStore(store, lockTarget)
1472
+ return { ok: true, item: created, meta: getArchiveMeta(rootSessionId, lockTarget) }
1018
1473
  }
1019
1474
 
1020
1475
  if (op === 'delete' || op === 'remove') {
@@ -1022,8 +1477,21 @@ export function mutateArchive(payload = {}, customSharedBoardFile) {
1022
1477
  const idx = store.items.findIndex(it => it.id === id)
1023
1478
  if (idx < 0) return { ok: false, error: '未找到要删除的档案:' + id }
1024
1479
  const [removed] = store.items.splice(idx, 1)
1025
- saveArchiveStore(store, customSharedBoardFile)
1026
- return { ok: true, removedId: removed.id, title: removed.title, meta: getArchiveMeta(rootSessionId, customSharedBoardFile) }
1480
+ saveArchiveStore(store, lockTarget)
1481
+ return { ok: true, removedId: removed.id, title: removed.title, meta: getArchiveMeta(rootSessionId, lockTarget) }
1482
+ }
1483
+
1484
+ if (op === 'clearByIds' || op === 'clearFolder') {
1485
+ const ids = new Set(Array.isArray(payload.ids) ? payload.ids.map(x => String(x || '').trim()).filter(Boolean) : [])
1486
+ const folder = str(payload.folder, '').trim()
1487
+ const before = store.items.length
1488
+ store.items = store.items.filter((it) => {
1489
+ if (op === 'clearFolder') return it.folder !== folder
1490
+ return !ids.has(it.id)
1491
+ })
1492
+ const removedCount = before - store.items.length
1493
+ if (removedCount > 0) saveArchiveStore(store, lockTarget)
1494
+ return { ok: true, removedCount, meta: getArchiveMeta(rootSessionId, lockTarget) }
1027
1495
  }
1028
1496
 
1029
1497
  if (op === 'takeOut' || op === 'putBack') {
@@ -1035,13 +1503,13 @@ export function mutateArchive(payload = {}, customSharedBoardFile) {
1035
1503
  if (op === 'takeOut') set.add(rootSessionId)
1036
1504
  else set.delete(rootSessionId)
1037
1505
  item.takenOutSessions = [...set]
1038
- saveArchiveStore(store, customSharedBoardFile)
1506
+ saveArchiveStore(store, lockTarget)
1039
1507
  return {
1040
1508
  ok: true,
1041
1509
  id: item.id,
1042
1510
  title: item.title,
1043
1511
  takenOut: op === 'takeOut',
1044
- meta: getArchiveMeta(rootSessionId, customSharedBoardFile),
1512
+ meta: getArchiveMeta(rootSessionId, lockTarget),
1045
1513
  }
1046
1514
  }
1047
1515
 
@@ -1057,7 +1525,7 @@ export function mutateArchive(payload = {}, customSharedBoardFile) {
1057
1525
  item.paperclip = order[nextIdx]
1058
1526
  }
1059
1527
  item.updatedAt = Date.now()
1060
- saveArchiveStore(store, customSharedBoardFile)
1528
+ saveArchiveStore(store, lockTarget)
1061
1529
  return { ok: true, id: item.id, paperclip: item.paperclip }
1062
1530
  }
1063
1531
 
@@ -1072,22 +1540,25 @@ export function mutateArchive(payload = {}, customSharedBoardFile) {
1072
1540
  store.folders.push(normalizeFolder({ id: folder, label: payload.folderLabel, order: 58 }))
1073
1541
  }
1074
1542
  item.updatedAt = Date.now()
1075
- saveArchiveStore(store, customSharedBoardFile)
1543
+ saveArchiveStore(store, lockTarget)
1076
1544
  return { ok: true, id: item.id, folder: item.folder }
1077
1545
  }
1078
1546
 
1079
- return { ok: false, error: '未知的档案操作:' + op }
1547
+ return { ok: false, error: '未知的档案操作:' + op }
1548
+ }
1549
+ const opRes = runOp()
1550
+ return (opRes && opRes.ok && !opRes.cabinetId)
1551
+ ? { cabinetId: resolved.cabinetId, ...opRes }
1552
+ : opRes
1080
1553
  })
1081
1554
  }
1082
1555
 
1083
- /**
1084
- * Batch-apply Chief LLM organization results (`folder`, `folderLabel`, `paperclip`, `summary`, `tags`, `points`)
1085
- * while 100% preserving each dossier's raw `body` lossless!
1086
- */
1087
- export function applyChiefArchiveCurations(curations = [], newFolders = [], customSharedBoardFile) {
1556
+ export function applyChiefArchiveCurations(curations = [], newFolders = [], targetOpt) {
1088
1557
  if (!Array.isArray(curations) || !curations.length) return { updatedCount: 0 }
1089
- return withArchiveLock(customSharedBoardFile, () => {
1090
- const store = loadArchiveStore(customSharedBoardFile)
1558
+ return withArchiveLock(targetOpt, (_file, resolved) => {
1559
+ const base = resolveTargetOpts(targetOpt)
1560
+ const lockTarget = { ...base, cabinetId: resolved.cabinetId, projectKey: resolved.projectKey }
1561
+ const store = loadArchiveStore(lockTarget)
1091
1562
  if (Array.isArray(newFolders)) {
1092
1563
  newFolders.forEach((nf, idx) => {
1093
1564
  if (!nf || !nf.id) return
@@ -1143,15 +1614,377 @@ export function applyChiefArchiveCurations(curations = [], newFolders = [], cust
1143
1614
  target.points = validPts
1144
1615
  }
1145
1616
  }
1146
- // Raw `target.body` is NEVER overwritten by Chief curation — 100% lossless!
1147
1617
  target.organizedBy = 'chief'
1148
1618
  target.updatedAt = Date.now()
1149
1619
  updatedCount += 1
1150
1620
  }
1151
1621
 
1152
1622
  if (updatedCount > 0) {
1153
- saveArchiveStore(store, customSharedBoardFile)
1623
+ saveArchiveStore(store, lockTarget)
1154
1624
  }
1155
1625
  return { updatedCount }
1156
1626
  })
1157
1627
  }
1628
+
1629
+ /* --------------------- Cross-Session Handoff Archive Copy (Never Precipitated) */
1630
+
1631
+ /**
1632
+ * Transfers ONLY active cabinet dossiers selected by `policy`:
1633
+ * - `'none'`: zero transfers
1634
+ * - `'mounted'`: only dossiers explicitly taken out on `fromRootSessionId` (`takenOutSessions`)
1635
+ * - `'drawer'`: dossiers inside `drawer` folder in source cabinet
1636
+ * - `'all'`: all dossiers in source active cabinet
1637
+ * Strictly NEVER reads or transfers `precipitated/<projectKey>.json`!
1638
+ */
1639
+ export function copyArchivesBetweenSessionsOrCabinets({
1640
+ fromRootSessionId = '',
1641
+ toRootSessionId = '',
1642
+ fromCwd = '',
1643
+ toCwd = '',
1644
+ fromCabinetId = '',
1645
+ toCabinetId = '',
1646
+ policy = 'none',
1647
+ drawer = '',
1648
+ customSharedBoardFile = '',
1649
+ }) {
1650
+ const mode = ['none', 'mounted', 'drawer', 'all'].includes(policy) ? policy : 'none'
1651
+ const fromSid = str(fromRootSessionId, '').trim()
1652
+ const toSid = str(toRootSessionId, '').trim()
1653
+ if (mode === 'none' || !toSid) {
1654
+ return { ok: true, policy: mode, transferredCount: 0, mountedCount: 0 }
1655
+ }
1656
+
1657
+ const srcTarget = {
1658
+ customSharedBoardFile,
1659
+ cwd: fromCwd,
1660
+ cabinetId: fromCabinetId,
1661
+ }
1662
+ const dstTarget = {
1663
+ customSharedBoardFile,
1664
+ cwd: toCwd || fromCwd,
1665
+ cabinetId: toCabinetId,
1666
+ }
1667
+
1668
+ const srcResolved = ensureProjectCabinet(srcTarget)
1669
+ const dstResolved = ensureProjectCabinet(dstTarget)
1670
+ const srcStore = loadArchiveStore({ customSharedBoardFile, cabinetId: srcResolved.cabinetId, projectKey: srcResolved.projectKey })
1671
+
1672
+ let selected = []
1673
+ if (mode === 'mounted') {
1674
+ selected = srcStore.items.filter(it => fromSid && Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(fromSid))
1675
+ } else if (mode === 'drawer') {
1676
+ const fId = str(drawer, '').trim()
1677
+ selected = srcStore.items.filter(it => !fId || it.folder === fId)
1678
+ } else if (mode === 'all') {
1679
+ selected = srcStore.items.slice()
1680
+ }
1681
+
1682
+ if (!selected.length) {
1683
+ return {
1684
+ ok: true,
1685
+ policy: mode,
1686
+ sameCabinet: srcResolved.cabinetId === dstResolved.cabinetId,
1687
+ targetCabinetId: dstResolved.cabinetId,
1688
+ transferredCount: 0,
1689
+ mountedCount: 0,
1690
+ }
1691
+ }
1692
+
1693
+ // Same cabinet: update `takenOutSessions` on selected items directly (mount mounted items or selected drawer items for target)
1694
+ if (srcResolved.cabinetId === dstResolved.cabinetId) {
1695
+ return withArchiveLock({ customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey }, () => {
1696
+ const store = loadArchiveStore({ customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey })
1697
+ let mountedCount = 0
1698
+ const selectedIds = new Set(selected.map(s => s.id))
1699
+ for (const it of store.items) {
1700
+ if (!selectedIds.has(it.id)) continue
1701
+ const shouldMount = mode === 'mounted' || (fromSid && Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(fromSid)) || mode === 'drawer'
1702
+ if (shouldMount) {
1703
+ const set = new Set(it.takenOutSessions || [])
1704
+ if (!set.has(toSid)) {
1705
+ set.add(toSid)
1706
+ it.takenOutSessions = [...set]
1707
+ mountedCount += 1
1708
+ }
1709
+ }
1710
+ }
1711
+ if (mountedCount > 0) {
1712
+ saveArchiveStore(store, { customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey })
1713
+ }
1714
+ return {
1715
+ ok: true,
1716
+ policy: mode,
1717
+ sameCabinet: true,
1718
+ targetCabinetId: dstResolved.cabinetId,
1719
+ transferredCount: selected.length,
1720
+ mountedCount,
1721
+ }
1722
+ })
1723
+ }
1724
+
1725
+ // Different cabinets: copy folders metadata & dossiers into destination cabinet
1726
+ return withArchiveLock({ customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey }, () => {
1727
+ const dstStore = loadArchiveStore({ customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey })
1728
+ const folderIds = new Set(dstStore.folders.map(f => f.id))
1729
+ for (const f of srcStore.folders) {
1730
+ if (!folderIds.has(f.id)) {
1731
+ dstStore.folders.push({ ...f })
1732
+ folderIds.add(f.id)
1733
+ }
1734
+ }
1735
+ const existingTitles = new Map(dstStore.items.map(it => [it.title, it]))
1736
+ let copiedCount = 0
1737
+ let mountedCount = 0
1738
+ for (const srcItem of selected) {
1739
+ const shouldMount = mode === 'mounted' || (fromSid && srcItem.takenOutSessions.includes(fromSid))
1740
+ const dup = existingTitles.get(srcItem.title)
1741
+ if (dup) {
1742
+ if (shouldMount && !dup.takenOutSessions.includes(toSid)) {
1743
+ dup.takenOutSessions.push(toSid)
1744
+ mountedCount += 1
1745
+ }
1746
+ dup.updatedAt = Date.now()
1747
+ copiedCount += 1
1748
+ continue
1749
+ }
1750
+ const cloned = normalizeArchiveItem({
1751
+ ...srcItem,
1752
+ id: nextId('arch'),
1753
+ takenOutSessions: shouldMount ? [toSid] : [],
1754
+ updatedAt: Date.now(),
1755
+ })
1756
+ if (cloned) {
1757
+ dstStore.items.unshift(cloned)
1758
+ copiedCount += 1
1759
+ if (shouldMount) mountedCount += 1
1760
+ }
1761
+ }
1762
+ if (copiedCount > 0 || mountedCount > 0) {
1763
+ saveArchiveStore(dstStore, { customSharedBoardFile, cabinetId: dstResolved.cabinetId, projectKey: dstResolved.projectKey })
1764
+ }
1765
+ return {
1766
+ ok: true,
1767
+ policy: mode,
1768
+ sameCabinet: false,
1769
+ targetCabinetId: dstResolved.cabinetId,
1770
+ transferredCount: copiedCount,
1771
+ mountedCount,
1772
+ }
1773
+ })
1774
+ }
1775
+
1776
+ /* --------------------- Precipitated Cross-Session Vault (STRICTLY 0 AUTO-READ) */
1777
+
1778
+ function normalizePrecipitatedEntry(raw) {
1779
+ if (!raw || typeof raw !== 'object') return null
1780
+ const title = clamp(raw.title || '', 180)
1781
+ const rawBody = cleanMultiline(raw.rawBody || raw.body || '', 30000)
1782
+ if (!title && !rawBody) return null
1783
+ const points = (Array.isArray(raw.points) ? raw.points : [])
1784
+ .map((p, idx) => normalizePoint(p, idx))
1785
+ .filter(Boolean)
1786
+ .slice(0, POINTS_CAP)
1787
+ const validCategories = ['architecture', 'env', 'contract', 'troubleshooting', 'workflow', 'general']
1788
+ const category = validCategories.includes(raw.category) ? raw.category : 'general'
1789
+ const flippedOutSessions = Array.isArray(raw.flippedOutSessions)
1790
+ ? [...new Set(raw.flippedOutSessions.map(s => str(s, '').trim()).filter(Boolean))].slice(0, 32)
1791
+ : []
1792
+
1793
+ return {
1794
+ id: str(raw.id, '').trim() || nextId('prec'),
1795
+ title: title || '跨会话可复用工程经验',
1796
+ category,
1797
+ summary: clamp(raw.summary || (points[0] && points[0].cue) || firstMeaningfulSentence(rawBody) || title, 180),
1798
+ points: points.length ? points : extractStructuredPoints(title, rawBody),
1799
+ rawBody,
1800
+ purified: raw.purified !== false,
1801
+ sourceCabinetId: str(raw.sourceCabinetId, '').trim(),
1802
+ sourceDrawer: str(raw.sourceDrawer, '').trim(),
1803
+ sourceTitles: Array.isArray(raw.sourceTitles) ? raw.sourceTitles.map(t => clamp(t, 80)).slice(0, 40) : [],
1804
+ tags: normalizeTags(Array.isArray(raw.tags) ? raw.tags : []),
1805
+ flippedOutSessions,
1806
+ by: clamp(raw.by || 'chief', 40),
1807
+ createdAt: Number(raw.createdAt) || Date.now(),
1808
+ updatedAt: Number(raw.updatedAt) || Number(raw.createdAt) || Date.now(),
1809
+ }
1810
+ }
1811
+
1812
+ function loadPrecipitatedStoreRaw(projectKey = 'proj-default', targetOpt) {
1813
+ const file = precipitatedFilePath(projectKey, targetOpt)
1814
+ if (!fs.existsSync(file)) {
1815
+ return {
1816
+ version: 1,
1817
+ projectKey: resolveProjectKey(projectKey),
1818
+ updatedAt: 0,
1819
+ items: [],
1820
+ }
1821
+ }
1822
+ const parsed = readJsonSafe(file, null)
1823
+ const items = (Array.isArray(parsed && parsed.items) ? parsed.items : [])
1824
+ .map(normalizePrecipitatedEntry)
1825
+ .filter(Boolean)
1826
+ .slice(0, PRECIPITATED_CAP)
1827
+ return {
1828
+ version: 1,
1829
+ projectKey: resolveProjectKey(projectKey),
1830
+ updatedAt: Number(parsed && parsed.updatedAt) || Date.now(),
1831
+ items,
1832
+ }
1833
+ }
1834
+
1835
+ function savePrecipitatedStoreRaw(projectKey = 'proj-default', store, targetOpt) {
1836
+ const file = precipitatedFilePath(projectKey, targetOpt)
1837
+ const normalized = {
1838
+ version: 1,
1839
+ projectKey: resolveProjectKey(projectKey),
1840
+ updatedAt: Date.now(),
1841
+ items: (Array.isArray(store && store.items) ? store.items : [])
1842
+ .map(normalizePrecipitatedEntry)
1843
+ .filter(Boolean)
1844
+ .slice(0, PRECIPITATED_CAP),
1845
+ }
1846
+ atomicWriteJson(file, normalized)
1847
+ return normalized
1848
+ }
1849
+
1850
+ /**
1851
+ * STRICT 0-TOKEN GUARD:
1852
+ * Unless `hasExplicitFlipOutFlag === true` (tracked independently per session in `chief-state.json`
1853
+ * `ws.flippedPrecipitatedIds`), this function returns `[]` IMMEDIATELY without touching disk at all!
1854
+ */
1855
+ export function getFlippedOutPrecipitatedForSession(projectKey = 'proj-default', rootSessionId = '', hasExplicitFlipOutFlag = false, targetOpt) {
1856
+ if (!hasExplicitFlipOutFlag || !str(rootSessionId, '').trim()) {
1857
+ return []
1858
+ }
1859
+ const sid = str(rootSessionId, '').trim()
1860
+ const store = loadPrecipitatedStoreRaw(projectKey, targetOpt)
1861
+ return store.items.filter(it => Array.isArray(it.flippedOutSessions) && it.flippedOutSessions.includes(sid))
1862
+ }
1863
+
1864
+ /** Listed ONLY when user opens the `档案` tab in Web UI (`GET /api/dsh-chief/archives`). */
1865
+ export function listPrecipitatedHeaders(projectKey = 'proj-default', rootSessionId = '', targetOpt) {
1866
+ const file = precipitatedFilePath(projectKey, targetOpt)
1867
+ if (!fs.existsSync(file)) return []
1868
+ const sid = str(rootSessionId, '').trim()
1869
+ const store = loadPrecipitatedStoreRaw(projectKey, targetOpt)
1870
+ return store.items.map(it => ({
1871
+ id: it.id,
1872
+ title: it.title,
1873
+ category: it.category,
1874
+ summary: it.summary,
1875
+ purified: it.purified,
1876
+ sourceCabinetId: it.sourceCabinetId,
1877
+ sourceDrawer: it.sourceDrawer,
1878
+ sourceTitles: it.sourceTitles,
1879
+ tags: it.tags,
1880
+ pointCount: Array.isArray(it.points) ? it.points.length : 0,
1881
+ flippedOut: Boolean(sid && Array.isArray(it.flippedOutSessions) && it.flippedOutSessions.includes(sid)),
1882
+ points: (it.points || []).map(p => ({ id: p.id, title: p.title, cue: p.cue, detail: p.detail })),
1883
+ createdAt: it.createdAt,
1884
+ updatedAt: it.updatedAt,
1885
+ }))
1886
+ }
1887
+
1888
+ export function getPrecipitatedDetail(projectKey = 'proj-default', id = '', rootSessionId = '', targetOpt) {
1889
+ const target = str(id, '').trim()
1890
+ if (!target) return { ok: false, error: 'missing precipitated id' }
1891
+ const store = loadPrecipitatedStoreRaw(projectKey, targetOpt)
1892
+ const hit = store.items.find(it => it.id === target)
1893
+ if (!hit) return { ok: false, error: '未找到沉淀经验条目:' + target }
1894
+ const sid = str(rootSessionId, '').trim()
1895
+ return {
1896
+ ok: true,
1897
+ item: {
1898
+ ...hit,
1899
+ flippedOut: Boolean(sid && hit.flippedOutSessions.includes(sid)),
1900
+ },
1901
+ }
1902
+ }
1903
+
1904
+ export function savePrecipitatedEntry(projectKey = 'proj-default', entry = {}, targetOpt) {
1905
+ const resolvedKey = resolveProjectKey(projectKey)
1906
+ const file = precipitatedFilePath(resolvedKey, targetOpt)
1907
+ const release = acquireFileLock(file)
1908
+ try {
1909
+ const store = loadPrecipitatedStoreRaw(resolvedKey, targetOpt)
1910
+ const bodyCheck = cleanMultiline(entry.rawBody || entry.body || '', 30000)
1911
+ if (SECRET_PATTERN.test(bodyCheck)) {
1912
+ return { ok: false, error: '沉淀内容疑似包含敏感密钥或私密凭据,已拒绝写入冷库' }
1913
+ }
1914
+ const existing = entry.id ? store.items.find(it => it.id === entry.id) : null
1915
+ if (existing) {
1916
+ const updated = normalizePrecipitatedEntry({ ...existing, ...entry, id: existing.id, updatedAt: Date.now() })
1917
+ Object.assign(existing, updated)
1918
+ savePrecipitatedStoreRaw(resolvedKey, store, targetOpt)
1919
+ return { ok: true, item: existing, file }
1920
+ }
1921
+ const created = normalizePrecipitatedEntry({
1922
+ ...entry,
1923
+ id: str(entry.id, '').trim() || nextId('prec'),
1924
+ flippedOutSessions: [], // Strictly cold-isolated by default!
1925
+ createdAt: Date.now(),
1926
+ updatedAt: Date.now(),
1927
+ })
1928
+ if (!created) return { ok: false, error: '无法写入空的沉淀经验' }
1929
+ store.items.unshift(created)
1930
+ savePrecipitatedStoreRaw(resolvedKey, store, targetOpt)
1931
+ return { ok: true, item: created, file }
1932
+ } finally {
1933
+ release()
1934
+ }
1935
+ }
1936
+
1937
+ export function mutatePrecipitated(projectKey = 'proj-default', payload = {}, targetOpt) {
1938
+ const resolvedKey = resolveProjectKey(projectKey || payload.projectKey || payload.cwd || 'proj-default')
1939
+ const file = precipitatedFilePath(resolvedKey, targetOpt)
1940
+ const op = str(payload.op, '').trim()
1941
+ const sid = str(payload.rootSessionId || payload.session, '').trim()
1942
+ const id = str(payload.precipitatedId || payload.id, '').trim()
1943
+
1944
+ const release = acquireFileLock(file)
1945
+ try {
1946
+ const store = loadPrecipitatedStoreRaw(resolvedKey, targetOpt)
1947
+
1948
+ if (op === 'flipOut' || op === 'sealBack') {
1949
+ if (!sid) return { ok: false, error: '当前未绑定对话会话' }
1950
+ const item = store.items.find(it => it.id === id)
1951
+ if (!item) return { ok: false, error: '未找到沉淀经验:' + id }
1952
+ const set = new Set(item.flippedOutSessions || [])
1953
+ if (op === 'flipOut') set.add(sid)
1954
+ else set.delete(sid)
1955
+ item.flippedOutSessions = [...set]
1956
+ item.updatedAt = Date.now()
1957
+ savePrecipitatedStoreRaw(resolvedKey, store, targetOpt)
1958
+ return {
1959
+ ok: true,
1960
+ id: item.id,
1961
+ title: item.title,
1962
+ flippedOut: op === 'flipOut',
1963
+ flippedIdsForSession: store.items
1964
+ .filter(it => it.flippedOutSessions.includes(sid))
1965
+ .map(it => it.id),
1966
+ }
1967
+ }
1968
+
1969
+ if (op === 'deletePrecipitated') {
1970
+ const idx = store.items.findIndex(it => it.id === id)
1971
+ if (idx < 0) return { ok: false, error: '未找到沉淀经验:' + id }
1972
+ const [removed] = store.items.splice(idx, 1)
1973
+ savePrecipitatedStoreRaw(resolvedKey, store, targetOpt)
1974
+ return { ok: true, removedId: removed.id, title: removed.title }
1975
+ }
1976
+
1977
+ if (op === 'updatePrecipitated') {
1978
+ const item = store.items.find(it => it.id === id)
1979
+ if (!item) return { ok: false, error: '未找到沉淀经验:' + id }
1980
+ const next = normalizePrecipitatedEntry({ ...item, ...payload, id: item.id, updatedAt: Date.now() })
1981
+ Object.assign(item, next)
1982
+ savePrecipitatedStoreRaw(resolvedKey, store, targetOpt)
1983
+ return { ok: true, item }
1984
+ }
1985
+
1986
+ return { ok: false, error: '未知的沉淀库操作:' + op }
1987
+ } finally {
1988
+ release()
1989
+ }
1990
+ }