dsh-chief 0.0.0-stage → 1.0.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 ADDED
@@ -0,0 +1,1157 @@
1
+ /**
2
+ * Engineering Memory Filing Cabinet (沉淀工程记忆档案库 · 严格懒加载 · 零主动注入)
3
+ *
4
+ * Persists structured long-term engineering dossiers at `%DSH_HOME%/chief/archives.json`.
5
+ *
6
+ * 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`.
19
+ */
20
+
21
+ import fs from 'node:fs'
22
+ import os from 'node:os'
23
+ import path from 'node:path'
24
+
25
+ const ARCHIVE_VERSION = 1
26
+ const ARCHIVE_CAP = 500
27
+ const POINTS_CAP = 32
28
+ 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
+
30
+ export const DEFAULT_ARCHIVE_FOLDERS = [
31
+ {
32
+ id: 'coords',
33
+ label: '工程坐标与部署锚点',
34
+ hint: '源码路径、热更口令、端口、部署验证命令与核心坐标',
35
+ accent: '#f59e0b',
36
+ order: 10,
37
+ },
38
+ {
39
+ id: 'incidents',
40
+ label: '排障实录与硬事实',
41
+ hint: '线上/本地故障症状、根因定位、踩坑教训与修复闭环',
42
+ accent: '#ef4444',
43
+ order: 20,
44
+ },
45
+ {
46
+ id: 'contracts',
47
+ label: '架构契约与方法论',
48
+ hint: '接口契约、参数宽容、截断交代、自检断言与工程纪律',
49
+ accent: '#0a84ff',
50
+ order: 30,
51
+ },
52
+ {
53
+ id: 'ops',
54
+ label: '运维链路与机器环境',
55
+ hint: '本机环境硬事实、服务器代理链路、容器与外部服务手册',
56
+ accent: '#10b981',
57
+ order: 40,
58
+ },
59
+ {
60
+ id: 'plans',
61
+ label: '阶段蓝图与归档计划',
62
+ hint: '官方能力对照、阶段性历史计划存档与里程碑复盘',
63
+ accent: '#8b5cf6',
64
+ order: 50,
65
+ },
66
+ {
67
+ id: 'inbox',
68
+ label: '待分拣工作便签',
69
+ hint: '新近沉淀或尚未归类的工程记录,可随时请参谋长整理收纳',
70
+ accent: '#64748b',
71
+ order: 60,
72
+ },
73
+ ]
74
+
75
+ const DEFAULT_FOLDER_MAP = new Map(DEFAULT_ARCHIVE_FOLDERS.map(f => [f.id, f]))
76
+
77
+ let seq = 0
78
+ function nextId(prefix) {
79
+ seq = (seq + 1) % 1000000
80
+ return prefix + '-' + Date.now().toString(36) + '-' + seq.toString(36)
81
+ }
82
+
83
+ function str(v, fb = '') {
84
+ return typeof v === 'string' ? v : fb
85
+ }
86
+
87
+ function clamp(v, max) {
88
+ const clean = String(v == null ? '' : v).replace(/\s+/g, ' ').trim()
89
+ if (clean.length <= max) return clean
90
+ return clean.slice(0, Math.max(0, max - 1)) + '…'
91
+ }
92
+
93
+ function cleanMultiline(v, max) {
94
+ const text = String(v == null ? '' : v).replace(/\r/g, '').trim()
95
+ if (text.length <= max) return text
96
+ return text.slice(0, Math.max(0, max - 1)) + '…'
97
+ }
98
+
99
+ export function archiveFilePath(customSharedBoardFile) {
100
+ if (customSharedBoardFile) {
101
+ return path.join(path.dirname(customSharedBoardFile), 'archives.json')
102
+ }
103
+ const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
104
+ return path.join(home, 'chief', 'archives.json')
105
+ }
106
+
107
+ /* ----------------------------------------------------------- Lock & Storage */
108
+
109
+ const heldArchiveLocks = new Set()
110
+ const lockSleeper = new Int32Array(new SharedArrayBuffer(4))
111
+
112
+ function sleepSync(ms) {
113
+ try {
114
+ Atomics.wait(lockSleeper, 0, 0, ms)
115
+ } catch {}
116
+ }
117
+
118
+ function acquireArchiveLock(file) {
119
+ if (heldArchiveLocks.has(file)) return () => {}
120
+ const lock = file + '.lock'
121
+ try {
122
+ fs.mkdirSync(path.dirname(lock), { recursive: true })
123
+ } catch {}
124
+ const deadline = Date.now() + 3000
125
+ for (;;) {
126
+ try {
127
+ const fd = fs.openSync(lock, 'wx')
128
+ try {
129
+ fs.writeSync(fd, String(process.pid))
130
+ } catch {}
131
+ fs.closeSync(fd)
132
+ heldArchiveLocks.add(file)
133
+ return () => {
134
+ heldArchiveLocks.delete(file)
135
+ try {
136
+ fs.unlinkSync(lock)
137
+ } catch {}
138
+ }
139
+ } catch (err) {
140
+ if (!err || err.code !== 'EEXIST' || Date.now() >= deadline) {
141
+ try {
142
+ if (Date.now() >= deadline) fs.unlinkSync(lock)
143
+ } catch {}
144
+ heldArchiveLocks.add(file)
145
+ return () => heldArchiveLocks.delete(file)
146
+ }
147
+ try {
148
+ const st = fs.statSync(lock)
149
+ if (Date.now() - st.mtimeMs > 10000) {
150
+ fs.unlinkSync(lock)
151
+ continue
152
+ }
153
+ } catch {}
154
+ sleepSync(3)
155
+ }
156
+ }
157
+ }
158
+
159
+ let archiveCache = { file: '', mtime: -1, store: null }
160
+
161
+ export function invalidateArchiveCache() {
162
+ archiveCache = { file: '', mtime: -1, store: null }
163
+ }
164
+
165
+ function normalizeFolder(raw, index = 0) {
166
+ if (!raw || typeof raw !== 'object') return null
167
+ const id = str(raw.id, '').trim().slice(0, 64)
168
+ if (!id) return null
169
+ const preset = DEFAULT_FOLDER_MAP.get(id)
170
+ return {
171
+ id,
172
+ label: clamp(raw.label || (preset && preset.label) || id, 40),
173
+ hint: clamp(raw.hint || (preset && preset.hint) || '', 100),
174
+ accent: str(raw.accent || (preset && preset.accent) || '#0a84ff', '#0a84ff').slice(0, 24),
175
+ order: Number.isFinite(Number(raw.order)) ? Number(raw.order) : ((preset && preset.order) || (70 + index * 5)),
176
+ }
177
+ }
178
+
179
+ function normalizePoint(raw, idx = 0) {
180
+ if (!raw || typeof raw !== 'object') return null
181
+ const title = clamp(raw.title || `要点 ${idx + 1}`, 90)
182
+ const detail = cleanMultiline(raw.detail || raw.text || raw.body || '', 6000)
183
+ if (!title && !detail) return null
184
+ const cueSource = str(raw.cue || raw.summary, '').trim()
185
+ const derivedCue = cueSource || firstMeaningfulSentence(detail)
186
+ return {
187
+ id: str(raw.id, '').trim() || ('pt-' + (idx + 1)),
188
+ title: title || clamp(derivedCue || `记忆点 ${idx + 1}`, 60),
189
+ cue: clamp(derivedCue, 110),
190
+ detail: detail || title,
191
+ }
192
+ }
193
+
194
+ function normalizeTags(list) {
195
+ if (!Array.isArray(list)) return []
196
+ const seen = new Set()
197
+ const out = []
198
+ for (const raw of list) {
199
+ const t = String(raw || '').trim().slice(0, 36)
200
+ if (!t) continue
201
+ // Strip internal routing tag 'anchor' from visual display tags while preserving paperclip='gold'
202
+ if (t.toLowerCase() === 'anchor') continue
203
+ const low = t.toLowerCase()
204
+ if (seen.has(low)) continue
205
+ seen.add(low)
206
+ out.push(t)
207
+ if (out.length >= 10) break
208
+ }
209
+ return out
210
+ }
211
+
212
+ function normalizeArchiveItem(raw) {
213
+ if (!raw || typeof raw !== 'object') return null
214
+ const body = cleanMultiline(raw.body || '', 30000)
215
+ const rawTitle = clamp(raw.title || '', 180)
216
+ if (!rawTitle && !body) return null
217
+
218
+ const parsedFallback = (!Array.isArray(raw.points) || !raw.points.length || !raw.folder || !raw.summary)
219
+ ? smartParseNoteToDossier(raw)
220
+ : null
221
+
222
+ const title = rawTitle || (parsedFallback && parsedFallback.title) || '未命名工程卷宗'
223
+ const folder = str(raw.folder, '').trim() || (parsedFallback && parsedFallback.folder) || 'inbox'
224
+ const validClips = ['gold', 'silver', 'copper']
225
+ const paperclip = validClips.includes(raw.paperclip)
226
+ ? raw.paperclip
227
+ : ((parsedFallback && parsedFallback.paperclip) || 'silver')
228
+
229
+ const pointsRaw = Array.isArray(raw.points) && raw.points.length
230
+ ? raw.points
231
+ : ((parsedFallback && parsedFallback.points) || [])
232
+ const points = pointsRaw.map((p, i) => normalizePoint(p, i)).filter(Boolean).slice(0, POINTS_CAP)
233
+
234
+ const summary = clamp(
235
+ raw.summary || (parsedFallback && parsedFallback.summary) || (points[0] && (points[0].cue || points[0].title)) || firstMeaningfulSentence(body) || title,
236
+ 140,
237
+ )
238
+
239
+ const takenOutSessions = Array.isArray(raw.takenOutSessions)
240
+ ? [...new Set(raw.takenOutSessions.map(s => String(s || '').trim()).filter(Boolean))].slice(0, 24)
241
+ : []
242
+
243
+ return {
244
+ id: str(raw.id, '').trim() || nextId('arch'),
245
+ sourceNoteId: str(raw.sourceNoteId, '').trim(),
246
+ title,
247
+ summary,
248
+ folder,
249
+ paperclip,
250
+ tags: normalizeTags(Array.isArray(raw.tags) ? raw.tags : []),
251
+ cold: raw.cold !== false,
252
+ takenOutSessions,
253
+ organizedBy: ['auto', 'chief', 'user'].includes(raw.organizedBy) ? raw.organizedBy : 'auto',
254
+ points,
255
+ body,
256
+ by: clamp(raw.by || 'agent', 40),
257
+ sourceSession: str(raw.sourceSession || raw.session, '').trim(),
258
+ createdAt: Number(raw.createdAt) || Date.now(),
259
+ updatedAt: Number(raw.updatedAt) || Number(raw.createdAt) || Date.now(),
260
+ }
261
+ }
262
+
263
+ function normalizeArchiveStore(raw) {
264
+ const src = raw && typeof raw === 'object' ? raw : {}
265
+ const folderMap = new Map()
266
+ for (const def of DEFAULT_ARCHIVE_FOLDERS) {
267
+ folderMap.set(def.id, { ...def })
268
+ }
269
+ if (Array.isArray(src.folders)) {
270
+ src.folders.forEach((f, idx) => {
271
+ const nf = normalizeFolder(f, idx)
272
+ if (nf) folderMap.set(nf.id, nf)
273
+ })
274
+ }
275
+
276
+ const items = (Array.isArray(src.items) ? src.items : [])
277
+ .map(normalizeArchiveItem)
278
+ .filter(Boolean)
279
+ .slice(0, ARCHIVE_CAP)
280
+
281
+ // Ensure any custom folder referenced by an item exists in `folders`
282
+ let customIdx = 0
283
+ for (const item of items) {
284
+ if (item.folder && !folderMap.has(item.folder)) {
285
+ customIdx += 1
286
+ folderMap.set(item.folder, {
287
+ id: item.folder,
288
+ label: clamp(item.folder, 40),
289
+ hint: '自定义工程档案抽屉',
290
+ accent: ['#06b6d4', '#ec4899', '#eab308', '#14b8a6'][customIdx % 4],
291
+ order: 55 + customIdx,
292
+ })
293
+ }
294
+ }
295
+
296
+ const folders = [...folderMap.values()].sort((a, b) => (a.order || 99) - (b.order || 99))
297
+
298
+ return {
299
+ version: ARCHIVE_VERSION,
300
+ migratedSharedAt: Number(src.migratedSharedAt) || 0,
301
+ updatedAt: Number(src.updatedAt) || Date.now(),
302
+ folders,
303
+ items,
304
+ }
305
+ }
306
+
307
+ export function loadArchiveStore(customSharedBoardFile) {
308
+ const file = archiveFilePath(customSharedBoardFile)
309
+ try {
310
+ const st = fs.statSync(file)
311
+ if (archiveCache.store && archiveCache.file === file && archiveCache.mtime === st.mtimeMs) {
312
+ return archiveCache.store
313
+ }
314
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
315
+ const store = normalizeArchiveStore(parsed)
316
+ archiveCache = { file, mtime: st.mtimeMs, store }
317
+ return store
318
+ } catch {
319
+ const empty = normalizeArchiveStore({})
320
+ return empty
321
+ }
322
+ }
323
+
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)
331
+ let mtime = Date.now()
332
+ try {
333
+ mtime = fs.statSync(file).mtimeMs
334
+ } catch {}
335
+ archiveCache = { file, mtime, store: normalized }
336
+ return normalized
337
+ }
338
+
339
+ export function withArchiveLock(customSharedBoardFile, fn) {
340
+ const file = archiveFilePath(customSharedBoardFile)
341
+ const release = acquireArchiveLock(file)
342
+ invalidateArchiveCache()
343
+ try {
344
+ return fn(file)
345
+ } finally {
346
+ release()
347
+ }
348
+ }
349
+
350
+ /* ------------------------------------------- Smart Note -> Dossier Parser */
351
+
352
+ function stripMarkdownDecorators(text) {
353
+ return String(text || '')
354
+ .replace(/^[#>*\-\d.)\s\u3000]+/, '')
355
+ .replace(/\*\*([^*]+)\*\*/g, '$1')
356
+ .replace(/`([^`]+)`/g, '$1')
357
+ .trim()
358
+ }
359
+
360
+ function firstMeaningfulSentence(text) {
361
+ const lines = String(text || '')
362
+ .split('\n')
363
+ .map(l => l.trim())
364
+ .filter(l => l && !/^\|[-:\s|]+\|$/.test(l) && !/^```/.test(l))
365
+ if (!lines.length) return ''
366
+ // Skip bare markdown heading if next line has substance
367
+ const candidate = (/^#{1,4}\s+/.test(lines[0]) && lines[1]) ? lines[1] : lines[0]
368
+ const clean = stripMarkdownDecorators(candidate)
369
+ const firstClause = clean.split(/[。;!?\n]/)[0] || clean
370
+ return clamp(firstClause, 115)
371
+ }
372
+
373
+ export function classifyNoteFolder(title, body, tags = []) {
374
+ const tagText = (Array.isArray(tags) ? tags : []).join(' ').toLowerCase()
375
+ const head = `${title || ''} ${tagText}`.toLowerCase()
376
+ const full = `${head} ${String(body || '').slice(0, 500)}`.toLowerCase()
377
+
378
+ if (/坐标|锚点|安装源|包体|目录结构|端口|热更|set_bundle|deployed/.test(head)) {
379
+ return 'coords'
380
+ }
381
+ if (/运维|环境|机器|硬事实|astrbot|claudia|sing-box|docker|服务器|tunnel|代理链路/.test(head) || /环境|运维/.test(tagText)) {
382
+ return 'ops'
383
+ }
384
+ if (/计划存档|蓝图|对照表|出图线|交接单三项|阶段|roadmap|archive|plan/.test(head)) {
385
+ return 'plans'
386
+ }
387
+ if (/症状|事故|已修|黑屏|坏了|排障|根因|死胡同|绕行|≠|不等于|踩坑|报错|unauthorized|eperm/.test(head)) {
388
+ return 'incidents'
389
+ }
390
+ if (/契约|方法论|自检|上限|截断|宽容|schema|继承规则|归属|注释|派生标题|具名|必须/.test(head) || /方法论|自检|设计/.test(tagText)) {
391
+ return 'contracts'
392
+ }
393
+ if (/坐标|路径|d:\\|%dsh_home%/.test(full) && /验证|pass/.test(full)) {
394
+ return 'coords'
395
+ }
396
+ if (/##\s*症状|##\s*根因|硬事实/.test(full)) {
397
+ return 'incidents'
398
+ }
399
+ return 'contracts'
400
+ }
401
+
402
+ function inferPaperclip(raw, folder) {
403
+ const tags = (Array.isArray(raw && raw.tags) ? raw.tags : []).map(t => String(t).toLowerCase())
404
+ if (raw && (raw.pinned === true || tags.includes('anchor') || raw.paperclip === 'gold')) {
405
+ return 'gold'
406
+ }
407
+ if (tags.includes('archive') || folder === 'plans') {
408
+ return 'copper'
409
+ }
410
+ return 'silver'
411
+ }
412
+
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
+ export function extractStructuredPoints(title, rawBody) {
418
+ const body = String(rawBody || '').replace(/\r/g, '').trim()
419
+ if (!body) {
420
+ return [
421
+ {
422
+ id: 'pt-1',
423
+ title: '归档标题备忘',
424
+ cue: '当前仅记录卷宗标题,尚未补充详细正文',
425
+ detail: `卷宗《${title || '未命名'}》当前无附加正文,可通过「编辑」随时补充工程细节。`,
426
+ },
427
+ ]
428
+ }
429
+
430
+ const lines = body.split('\n')
431
+
432
+ // Strategy 1: Markdown Headings (`## ...` or `### ...`)
433
+ const headingIndices = []
434
+ for (let i = 0; i < lines.length; i += 1) {
435
+ if (/^#{2,3}\s+\S/.test(lines[i].trim())) {
436
+ headingIndices.push(i)
437
+ }
438
+ }
439
+ if (headingIndices.length >= 1) {
440
+ 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()))
445
+ const preText = preLines.join('\n').trim()
446
+ if (preText.length >= 18) {
447
+ points.push({
448
+ id: `pt-${points.length + 1}`,
449
+ title: '背景与总览',
450
+ cue: firstMeaningfulSentence(preText),
451
+ detail: preText,
452
+ })
453
+ }
454
+ for (let hIdx = 0; hIdx < headingIndices.length; hIdx += 1) {
455
+ const start = headingIndices[hIdx]
456
+ const end = hIdx + 1 < headingIndices.length ? headingIndices[hIdx + 1] : lines.length
457
+ const rawHeading = lines[start].trim().replace(/^#{2,3}\s+/, '').trim()
458
+ const secBody = lines.slice(start + 1, end).join('\n').trim()
459
+ if (!secBody && !rawHeading) continue
460
+ points.push({
461
+ id: `pt-${points.length + 1}`,
462
+ title: clamp(stripMarkdownDecorators(rawHeading) || `要点 ${points.length + 1}`, 76),
463
+ cue: firstMeaningfulSentence(secBody) || clamp(rawHeading, 90),
464
+ detail: secBody || rawHeading,
465
+ })
466
+ }
467
+ if (points.length >= 1) return points.slice(0, POINTS_CAP)
468
+ }
469
+
470
+ // Strategy 2: Labeled Key-Value Blocks (`包体/源码:...`, `部署态验证:...`, `数据:...`, `坑:...`)
471
+ const kvBlocks = []
472
+ let currentKv = null
473
+ for (const rawLine of lines) {
474
+ const trimmed = rawLine.trim()
475
+ if (!trimmed) continue
476
+ const kvMatch = /^([^\s::|]{2,18}(?:[((][^))]{1,18}[))])?)\s*[::]\s*(.*)$/.exec(trimmed)
477
+ const numMatch = /^(\d+)\.\s+(?:\[[xX\s]\]\s*)?(.+)$/.exec(trimmed)
478
+ if (kvMatch) {
479
+ if (currentKv) kvBlocks.push(currentKv)
480
+ const rest = kvMatch[2].trim()
481
+ currentKv = {
482
+ title: stripMarkdownDecorators(kvMatch[1]),
483
+ lines: rest ? [rest] : [],
484
+ }
485
+ } else if (numMatch && !currentKv) {
486
+ kvBlocks.push({
487
+ title: clamp(stripMarkdownDecorators(numMatch[2]), 54),
488
+ lines: [trimmed],
489
+ })
490
+ } else if (currentKv) {
491
+ currentKv.lines.push(trimmed)
492
+ } else {
493
+ currentKv = {
494
+ title: clamp(firstMeaningfulSentence(trimmed), 46) || '背景说明',
495
+ lines: [trimmed],
496
+ }
497
+ }
498
+ }
499
+ if (currentKv) kvBlocks.push(currentKv)
500
+ if (kvBlocks.length >= 2) {
501
+ return kvBlocks.slice(0, POINTS_CAP).map((b, i) => {
502
+ const detail = b.lines.join('\n').trim() || b.title
503
+ return {
504
+ id: `pt-${i + 1}`,
505
+ title: clamp(b.title || `要点 ${i + 1}`, 72),
506
+ cue: firstMeaningfulSentence(detail),
507
+ detail,
508
+ }
509
+ })
510
+ }
511
+
512
+ // Strategy 3: Paragraph / Numbered-List / Sentence-Cluster Splitting
513
+ const paragraphs = body
514
+ .split(/\n{2,}/)
515
+ .map(p => p.trim())
516
+ .filter(p => p && !/^#\s+/.test(p))
517
+
518
+ if (paragraphs.length >= 2) {
519
+ return paragraphs.slice(0, POINTS_CAP).map((para, idx) => {
520
+ const first = firstMeaningfulSentence(para)
521
+ return {
522
+ id: `pt-${idx + 1}`,
523
+ title: clamp(first || `记忆点 ${idx + 1}`, 56),
524
+ cue: clamp(para.replace(/\s+/g, ' '), 105),
525
+ detail: para,
526
+ }
527
+ })
528
+ }
529
+
530
+ // Strategy 4: Dense single-paragraph prose -> split into logical clauses (`。` / `;`) if long
531
+ const sentences = body
532
+ .split(/(?<=[。!?;])\s*/)
533
+ .map(s => s.trim())
534
+ .filter(Boolean)
535
+
536
+ if (sentences.length >= 2 && body.length > 95) {
537
+ const labels = ['核心问题与诱因', '关键判据与机制', '落地规范与避坑', '补充细节']
538
+ const grouped = []
539
+ const chunkSize = sentences.length >= 5 ? 2 : 1
540
+ for (let i = 0; i < sentences.length; i += chunkSize) {
541
+ const slice = sentences.slice(i, i + chunkSize).join('')
542
+ const labelIdx = Math.min(grouped.length, labels.length - 1)
543
+ grouped.push({
544
+ id: `pt-${grouped.length + 1}`,
545
+ title: `${labels[labelIdx]}:${clamp(stripMarkdownDecorators(sentences[i]), 36)}`,
546
+ cue: clamp(stripMarkdownDecorators(slice), 100),
547
+ detail: slice,
548
+ })
549
+ }
550
+ return grouped.slice(0, POINTS_CAP)
551
+ }
552
+
553
+ return [
554
+ {
555
+ id: 'pt-1',
556
+ title: clamp(title || firstMeaningfulSentence(body) || '核心记忆点', 64),
557
+ cue: firstMeaningfulSentence(body),
558
+ detail: body,
559
+ },
560
+ ]
561
+ }
562
+
563
+ export function smartParseNoteToDossier(rawNote) {
564
+ const note = rawNote && typeof rawNote === 'object' ? rawNote : {}
565
+ const body = cleanMultiline(note.body || '', 30000)
566
+ const derivedTitle = clamp(
567
+ note.title || firstMeaningfulSentence(body) || '未命名工程卷宗',
568
+ 180,
569
+ )
570
+ const folder = str(note.folder, '').trim() || classifyNoteFolder(derivedTitle, body, note.tags)
571
+ const paperclip = inferPaperclip(note, folder)
572
+ const points = extractStructuredPoints(derivedTitle, body)
573
+ const summary = clamp(
574
+ note.summary || (points[0] && points[0].cue) || firstMeaningfulSentence(body) || derivedTitle,
575
+ 135,
576
+ )
577
+ return {
578
+ title: derivedTitle,
579
+ summary,
580
+ folder,
581
+ paperclip,
582
+ points,
583
+ }
584
+ }
585
+
586
+ /* ------------------------------------ Non-Destructive Bootstrap Migration */
587
+
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
+ export function bootstrapArchivesFromSharedBoard({ sharedFile, loadBoard, saveBoard, pushLog }) {
595
+ try {
596
+ 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
+ }
603
+ }
604
+
605
+ const sharedBoard = loadBoard(sharedFile)
606
+ const legacyNotes = Array.isArray(sharedBoard && sharedBoard.notes) ? sharedBoard.notes : []
607
+ if (!legacyNotes.length) {
608
+ withArchiveLock(sharedFile, () => {
609
+ const empty = loadArchiveStore(sharedFile)
610
+ empty.migratedSharedAt = Date.now()
611
+ saveArchiveStore(empty, sharedFile)
612
+ })
613
+ return { migrated: 0 }
614
+ }
615
+
616
+ // 1. Safety backup of `board.json` before touching anything
617
+ const backupFile = path.join(path.dirname(sharedFile), 'board.pre-archive-backup.json')
618
+ try {
619
+ if (!fs.existsSync(backupFile)) {
620
+ fs.copyFileSync(sharedFile, backupFile)
621
+ }
622
+ } catch {}
623
+
624
+ // 2. Precipitate all legacy notes into cold archives
625
+ let migratedCount = 0
626
+ withArchiveLock(sharedFile, () => {
627
+ const store = loadArchiveStore(sharedFile)
628
+ const existingSourceIds = new Set(store.items.map(it => it.sourceNoteId).filter(Boolean))
629
+ const existingTitles = new Set(store.items.map(it => it.title))
630
+
631
+ for (const note of legacyNotes) {
632
+ if (!note || (!note.title && !note.body)) continue
633
+ if (SECRET_PATTERN.test(String(note.body || ''))) continue
634
+ if ((note.id && existingSourceIds.has(note.id)) || (note.title && existingTitles.has(note.title))) {
635
+ continue
636
+ }
637
+ const parsed = smartParseNoteToDossier(note)
638
+ const item = normalizeArchiveItem({
639
+ id: nextId('arch'),
640
+ sourceNoteId: note.id || '',
641
+ title: parsed.title,
642
+ summary: parsed.summary,
643
+ folder: parsed.folder,
644
+ paperclip: parsed.paperclip,
645
+ tags: note.tags || [],
646
+ cold: true,
647
+ takenOutSessions: [],
648
+ organizedBy: 'auto',
649
+ points: parsed.points,
650
+ body: note.body || '',
651
+ by: note.by || 'agent',
652
+ sourceSession: note.session || '',
653
+ createdAt: note.createdAt || note.updatedAt || Date.now(),
654
+ updatedAt: note.updatedAt || Date.now(),
655
+ })
656
+ if (item) {
657
+ store.items.push(item)
658
+ migratedCount += 1
659
+ }
660
+ }
661
+
662
+ store.migratedSharedAt = Date.now()
663
+ saveArchiveStore(store, sharedFile)
664
+ })
665
+
666
+ // 3. Remove migrated long-term notes from shared `board.json` so prompt auto-injection drops to ZERO
667
+ if (migratedCount > 0 && typeof saveBoard === 'function') {
668
+ sharedBoard.notes = []
669
+ if (typeof pushLog === 'function') {
670
+ pushLog(
671
+ sharedBoard,
672
+ `🗄️ 已将 ${migratedCount} 篇历史工程笔记无损沉淀入「档案」柜(默认封存懒加载,不再每轮挤占上下文)`,
673
+ 'system',
674
+ '',
675
+ )
676
+ }
677
+ saveBoard(sharedBoard, sharedFile)
678
+ }
679
+
680
+ return { migrated: migratedCount }
681
+ } catch {
682
+ return { migrated: 0 }
683
+ }
684
+ }
685
+
686
+ /* ------------------------------------------- Lazy-Loading Query & Mutations */
687
+
688
+ /** Ultra-lightweight metadata (<80 bytes) for `/snapshot` polling — ZERO archive text/headers! */
689
+ export function getArchiveMeta(rootSessionId = '', customSharedBoardFile) {
690
+ const store = loadArchiveStore(customSharedBoardFile)
691
+ const sid = String(rootSessionId || '').trim()
692
+ const nonEmptyFolders = new Set(store.items.map(it => it.folder).filter(Boolean))
693
+ const takenOutCount = sid
694
+ ? store.items.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid)).length
695
+ : 0
696
+ return {
697
+ totalCount: store.items.length,
698
+ folderCount: nonEmptyFolders.size || DEFAULT_ARCHIVE_FOLDERS.length,
699
+ takenOutCount,
700
+ unorganizedCount: store.items.filter(it => it.folder === 'inbox' || it.organizedBy === 'auto').length,
701
+ }
702
+ }
703
+
704
+ /**
705
+ * Tier-1 Lazy Load (`GET /api/dsh-chief/archives`):
706
+ * Returns folder drawers + slim dossier headers ONLY (no `points` details, no `body`!).
707
+ */
708
+ export function listArchiveHeaders(rootSessionId = '', opts = {}, customSharedBoardFile) {
709
+ const store = loadArchiveStore(customSharedBoardFile)
710
+ const sid = String(rootSessionId || '').trim()
711
+ const needle = String((opts && opts.query) || '').trim().toLowerCase()
712
+ const folderFilter = String((opts && opts.folder) || '').trim()
713
+ const clipFilter = String((opts && opts.paperclip) || '').trim()
714
+
715
+ const clipRank = { gold: 0, silver: 1, copper: 2 }
716
+ const sorted = store.items.slice().sort((a, b) => {
717
+ const aOut = sid && a.takenOutSessions.includes(sid) ? 0 : 1
718
+ const bOut = sid && b.takenOutSessions.includes(sid) ? 0 : 1
719
+ if (aOut !== bOut) return aOut - bOut
720
+ const cDiff = (clipRank[a.paperclip] ?? 1) - (clipRank[b.paperclip] ?? 1)
721
+ if (cDiff !== 0) return cDiff
722
+ return (b.updatedAt || 0) - (a.updatedAt || 0)
723
+ })
724
+
725
+ const filtered = sorted.filter((it) => {
726
+ if (folderFilter && it.folder !== folderFilter) return false
727
+ if (clipFilter && it.paperclip !== clipFilter) return false
728
+ if (!needle) return true
729
+ const hay = [
730
+ it.title,
731
+ it.summary,
732
+ (it.tags || []).join(' '),
733
+ ...(it.points || []).map(p => `${p.title} ${p.cue}`),
734
+ it.body,
735
+ ].join('\n').toLowerCase()
736
+ return hay.includes(needle)
737
+ })
738
+
739
+ const countsByFolder = {}
740
+ const goldByFolder = {}
741
+ for (const it of store.items) {
742
+ countsByFolder[it.folder] = (countsByFolder[it.folder] || 0) + 1
743
+ if (it.paperclip === 'gold') {
744
+ goldByFolder[it.folder] = (goldByFolder[it.folder] || 0) + 1
745
+ }
746
+ }
747
+
748
+ const folders = store.folders.map(f => ({
749
+ ...f,
750
+ count: countsByFolder[f.id] || 0,
751
+ goldCount: goldByFolder[f.id] || 0,
752
+ }))
753
+
754
+ const headers = filtered.map(it => ({
755
+ id: it.id,
756
+ title: it.title,
757
+ summary: it.summary,
758
+ folder: it.folder,
759
+ paperclip: it.paperclip,
760
+ tags: it.tags,
761
+ cold: it.cold,
762
+ takenOut: Boolean(sid && it.takenOutSessions.includes(sid)),
763
+ organizedBy: it.organizedBy,
764
+ pointCount: Array.isArray(it.points) ? it.points.length : 0,
765
+ pointPreviews: (Array.isArray(it.points) ? it.points : []).slice(0, 4).map(p => p.title),
766
+ bodyLength: (it.body || '').length,
767
+ updatedAt: it.updatedAt,
768
+ createdAt: it.createdAt,
769
+ }))
770
+
771
+ return {
772
+ ok: true,
773
+ totalCount: store.items.length,
774
+ takenOutCount: sid ? store.items.filter(it => it.takenOutSessions.includes(sid)).length : 0,
775
+ folders,
776
+ items: headers,
777
+ }
778
+ }
779
+
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) {
785
+ const target = String(idOrTitle || '').trim()
786
+ if (!target) return { ok: false, error: 'archive id or title required' }
787
+ const store = loadArchiveStore(customSharedBoardFile)
788
+ const sid = String(rootSessionId || '').trim()
789
+ const hit = store.items.find(it => it.id === target)
790
+ || store.items.find(it => it.title === target)
791
+ || store.items.find(it => it.title.toLowerCase().includes(target.toLowerCase()))
792
+ if (!hit) return { ok: false, error: '未找到工程档案:' + target }
793
+
794
+ return {
795
+ ok: true,
796
+ item: {
797
+ id: hit.id,
798
+ title: hit.title,
799
+ summary: hit.summary,
800
+ folder: hit.folder,
801
+ paperclip: hit.paperclip,
802
+ tags: hit.tags,
803
+ cold: hit.cold,
804
+ takenOut: Boolean(sid && hit.takenOutSessions.includes(sid)),
805
+ organizedBy: hit.organizedBy,
806
+ points: hit.points,
807
+ body: hit.body,
808
+ by: hit.by,
809
+ createdAt: hit.createdAt,
810
+ updatedAt: hit.updatedAt,
811
+ },
812
+ }
813
+ }
814
+
815
+ /**
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!
818
+ */
819
+ export function getTakenOutArchivesForSession(rootSessionId = '', customSharedBoardFile) {
820
+ const sid = String(rootSessionId || '').trim()
821
+ if (!sid) return []
822
+ const store = loadArchiveStore(customSharedBoardFile)
823
+ return store.items.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid))
824
+ }
825
+
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)
829
+ const folder = String((opts && opts.folder) || '').trim()
830
+ const limit = Math.max(1, Math.min(Number(opts && opts.limit) || 8, 25))
831
+ const rawQ = String(query || '').trim().toLowerCase()
832
+ const terms = rawQ
833
+ .replace(/[??!!。,,、::“”"'()()[\]【】]/g, ' ')
834
+ .split(/\s+/)
835
+ .filter(Boolean)
836
+
837
+ const scored = []
838
+ for (const it of store.items) {
839
+ if (folder && it.folder !== folder) continue
840
+ if (!terms.length) {
841
+ scored.push({ score: it.paperclip === 'gold' ? 5 : 2, it })
842
+ continue
843
+ }
844
+ const titleLow = it.title.toLowerCase()
845
+ const sumLow = it.summary.toLowerCase()
846
+ const tagLow = (it.tags || []).join(' ').toLowerCase()
847
+ const ptsLow = (it.points || []).map(p => `${p.title} ${p.cue} ${p.detail}`).join('\n').toLowerCase()
848
+ const bodyLow = (it.body || '').toLowerCase()
849
+
850
+ let score = 0
851
+ for (const term of terms) {
852
+ if (titleLow.includes(term)) score += 8
853
+ if (tagLow.includes(term)) score += 5
854
+ if (sumLow.includes(term)) score += 4
855
+ if (ptsLow.includes(term)) score += 3
856
+ else if (bodyLow.includes(term)) score += 2
857
+ }
858
+ if (score > 0) {
859
+ if (it.paperclip === 'gold') score += 1
860
+ scored.push({ score, it })
861
+ }
862
+ }
863
+
864
+ scored.sort((a, b) => b.score - a.score || (b.it.updatedAt || 0) - (a.it.updatedAt || 0))
865
+ const folderLabelMap = new Map(store.folders.map(f => [f.id, f.label]))
866
+
867
+ return {
868
+ ok: true,
869
+ totalArchives: store.items.length,
870
+ matchCount: scored.length,
871
+ hits: scored.slice(0, limit).map(({ it }) => ({
872
+ id: it.id,
873
+ title: it.title,
874
+ folder: it.folder,
875
+ folderLabel: folderLabelMap.get(it.folder) || it.folder,
876
+ paperclip: it.paperclip,
877
+ summary: it.summary,
878
+ tags: it.tags,
879
+ points: (it.points || []).map(p => ({ id: p.id, title: p.title, cue: p.cue })),
880
+ updatedAt: it.updatedAt,
881
+ })),
882
+ }
883
+ }
884
+
885
+ export function mutateArchive(payload = {}, customSharedBoardFile) {
886
+ const op = str(payload.op, 'save').trim()
887
+ const rootSessionId = str(payload.rootSessionId || payload.session, '').trim()
888
+
889
+ return withArchiveLock(customSharedBoardFile, () => {
890
+ const store = loadArchiveStore(customSharedBoardFile)
891
+
892
+ if (op === 'createFolder' || op === 'saveFolder') {
893
+ const rawLabel = clamp(payload.label || payload.folderLabel || payload.folder, 40)
894
+ if (!rawLabel) return { ok: false, error: '请输入文件夹抽屉名称' }
895
+ const id = str(payload.folderId, '').trim()
896
+ || ('folder-' + rawLabel.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5_-]+/g, '-').slice(0, 24) + '-' + Date.now().toString(36).slice(-3))
897
+ const existing = store.folders.find(f => f.id === id || f.label === rawLabel)
898
+ if (existing) {
899
+ if (payload.hint !== undefined) existing.hint = clamp(payload.hint, 100)
900
+ if (payload.accent) existing.accent = str(payload.accent, existing.accent).slice(0, 24)
901
+ saveArchiveStore(store, customSharedBoardFile)
902
+ return { ok: true, folder: existing }
903
+ }
904
+ const created = normalizeFolder({
905
+ id,
906
+ label: rawLabel,
907
+ hint: payload.hint || '自定义工程记忆抽屉',
908
+ accent: payload.accent || '#06b6d4',
909
+ order: 55 + store.folders.length,
910
+ })
911
+ store.folders.push(created)
912
+ saveArchiveStore(store, customSharedBoardFile)
913
+ return { ok: true, folder: created }
914
+ }
915
+
916
+ if (op === 'save' || op === 'create' || op === 'update') {
917
+ const id = str(payload.archiveId || payload.id, '').trim()
918
+ const existing = id ? store.items.find(it => it.id === id) : null
919
+
920
+ const nextBody = typeof payload.body === 'string'
921
+ ? cleanMultiline(payload.body, 30000)
922
+ : (existing ? existing.body : '')
923
+ if (SECRET_PATTERN.test(nextBody)) {
924
+ return { ok: false, error: '档案内容疑似包含密钥或私密凭据,已拒绝入库' }
925
+ }
926
+
927
+ if (existing) {
928
+ const bodyChanged = typeof payload.body === 'string' && payload.body.trim() !== existing.body.trim()
929
+ if (typeof payload.title === 'string' && payload.title.trim()) {
930
+ existing.title = clamp(payload.title, 180)
931
+ }
932
+ if (typeof payload.body === 'string') {
933
+ existing.body = nextBody
934
+ }
935
+ if (typeof payload.folder === 'string' && payload.folder.trim()) {
936
+ existing.folder = payload.folder.trim()
937
+ }
938
+ if (['gold', 'silver', 'copper'].includes(payload.paperclip)) {
939
+ existing.paperclip = payload.paperclip
940
+ }
941
+ if (Array.isArray(payload.tags)) {
942
+ existing.tags = normalizeTags(payload.tags)
943
+ } else if (typeof payload.tags === 'string') {
944
+ existing.tags = normalizeTags(payload.tags.split(/[,,]/))
945
+ }
946
+ if (Array.isArray(payload.points) && payload.points.length) {
947
+ existing.points = payload.points.map((p, i) => normalizePoint(p, i)).filter(Boolean).slice(0, POINTS_CAP)
948
+ existing.organizedBy = payload.organizedBy || 'user'
949
+ } else if (bodyChanged) {
950
+ existing.points = extractStructuredPoints(existing.title, existing.body)
951
+ }
952
+ if (typeof payload.summary === 'string' && payload.summary.trim()) {
953
+ existing.summary = clamp(payload.summary, 140)
954
+ } else if (bodyChanged) {
955
+ existing.summary = clamp(
956
+ (existing.points[0] && existing.points[0].cue) || firstMeaningfulSentence(existing.body) || existing.title,
957
+ 140,
958
+ )
959
+ }
960
+ existing.updatedAt = Date.now()
961
+ saveArchiveStore(store, customSharedBoardFile)
962
+ return { ok: true, item: existing, meta: getArchiveMeta(rootSessionId, customSharedBoardFile) }
963
+ }
964
+
965
+ const rawTitle = clamp(payload.title || '', 180)
966
+ if (!rawTitle && !nextBody) {
967
+ return { ok: false, error: '新建工程档案需要填写标题或正文内容' }
968
+ }
969
+ // Dedupe if exact same title already archived and caller opted into upsert
970
+ const sameTitle = rawTitle ? store.items.find(it => it.title === rawTitle) : null
971
+ if (sameTitle && payload.upsertByTitle !== false) {
972
+ sameTitle.body = nextBody || sameTitle.body
973
+ if (payload.folder) sameTitle.folder = str(payload.folder, sameTitle.folder).trim()
974
+ if (['gold', 'silver', 'copper'].includes(payload.paperclip)) sameTitle.paperclip = payload.paperclip
975
+ if (payload.tags) {
976
+ sameTitle.tags = normalizeTags(Array.isArray(payload.tags) ? payload.tags : String(payload.tags).split(/[,,]/))
977
+ }
978
+ sameTitle.points = Array.isArray(payload.points) && payload.points.length
979
+ ? payload.points.map((p, i) => normalizePoint(p, i)).filter(Boolean).slice(0, POINTS_CAP)
980
+ : extractStructuredPoints(sameTitle.title, sameTitle.body)
981
+ sameTitle.summary = clamp(
982
+ payload.summary || (sameTitle.points[0] && sameTitle.points[0].cue) || firstMeaningfulSentence(sameTitle.body) || sameTitle.title,
983
+ 140,
984
+ )
985
+ sameTitle.updatedAt = Date.now()
986
+ saveArchiveStore(store, customSharedBoardFile)
987
+ return { ok: true, item: sameTitle, updatedExisting: true, meta: getArchiveMeta(rootSessionId, customSharedBoardFile) }
988
+ }
989
+
990
+ const parsed = smartParseNoteToDossier({
991
+ title: rawTitle,
992
+ body: nextBody,
993
+ folder: payload.folder,
994
+ paperclip: payload.paperclip,
995
+ tags: Array.isArray(payload.tags) ? payload.tags : (typeof payload.tags === 'string' ? payload.tags.split(/[,,]/) : []),
996
+ })
997
+ const created = normalizeArchiveItem({
998
+ id: nextId('arch'),
999
+ sourceNoteId: str(payload.sourceNoteId, ''),
1000
+ title: parsed.title,
1001
+ summary: payload.summary || parsed.summary,
1002
+ folder: payload.folder || parsed.folder,
1003
+ paperclip: payload.paperclip || parsed.paperclip,
1004
+ tags: Array.isArray(payload.tags) ? payload.tags : (typeof payload.tags === 'string' ? payload.tags.split(/[,,]/) : []),
1005
+ cold: true,
1006
+ takenOutSessions: payload.takeOutNow && rootSessionId ? [rootSessionId] : [],
1007
+ organizedBy: Array.isArray(payload.points) && payload.points.length ? 'user' : 'auto',
1008
+ points: Array.isArray(payload.points) && payload.points.length ? payload.points : parsed.points,
1009
+ body: nextBody,
1010
+ by: payload.by || 'user',
1011
+ sourceSession: rootSessionId,
1012
+ createdAt: Date.now(),
1013
+ updatedAt: Date.now(),
1014
+ })
1015
+ store.items.unshift(created)
1016
+ saveArchiveStore(store, customSharedBoardFile)
1017
+ return { ok: true, item: created, meta: getArchiveMeta(rootSessionId, customSharedBoardFile) }
1018
+ }
1019
+
1020
+ if (op === 'delete' || op === 'remove') {
1021
+ const id = str(payload.archiveId || payload.id, '').trim()
1022
+ const idx = store.items.findIndex(it => it.id === id)
1023
+ if (idx < 0) return { ok: false, error: '未找到要删除的档案:' + id }
1024
+ 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) }
1027
+ }
1028
+
1029
+ if (op === 'takeOut' || op === 'putBack') {
1030
+ const id = str(payload.archiveId || payload.id, '').trim()
1031
+ if (!rootSessionId) return { ok: false, error: '当前未绑定对话会话,无法取出挂到桌面' }
1032
+ const item = store.items.find(it => it.id === id)
1033
+ if (!item) return { ok: false, error: '未找到该工程档案:' + id }
1034
+ const set = new Set(item.takenOutSessions || [])
1035
+ if (op === 'takeOut') set.add(rootSessionId)
1036
+ else set.delete(rootSessionId)
1037
+ item.takenOutSessions = [...set]
1038
+ saveArchiveStore(store, customSharedBoardFile)
1039
+ return {
1040
+ ok: true,
1041
+ id: item.id,
1042
+ title: item.title,
1043
+ takenOut: op === 'takeOut',
1044
+ meta: getArchiveMeta(rootSessionId, customSharedBoardFile),
1045
+ }
1046
+ }
1047
+
1048
+ if (op === 'cycleClip' || op === 'setClip') {
1049
+ const id = str(payload.archiveId || payload.id, '').trim()
1050
+ const item = store.items.find(it => it.id === id)
1051
+ if (!item) return { ok: false, error: '未找到该工程档案:' + id }
1052
+ const order = ['gold', 'silver', 'copper']
1053
+ if (order.includes(payload.paperclip)) {
1054
+ item.paperclip = payload.paperclip
1055
+ } else {
1056
+ const nextIdx = (order.indexOf(item.paperclip) + 1) % order.length
1057
+ item.paperclip = order[nextIdx]
1058
+ }
1059
+ item.updatedAt = Date.now()
1060
+ saveArchiveStore(store, customSharedBoardFile)
1061
+ return { ok: true, id: item.id, paperclip: item.paperclip }
1062
+ }
1063
+
1064
+ if (op === 'moveFolder') {
1065
+ const id = str(payload.archiveId || payload.id, '').trim()
1066
+ const folder = str(payload.folder, '').trim()
1067
+ if (!folder) return { ok: false, error: '请选择目标文件夹抽屉' }
1068
+ const item = store.items.find(it => it.id === id)
1069
+ if (!item) return { ok: false, error: '未找到该工程档案:' + id }
1070
+ item.folder = folder
1071
+ if (payload.folderLabel && !store.folders.some(f => f.id === folder)) {
1072
+ store.folders.push(normalizeFolder({ id: folder, label: payload.folderLabel, order: 58 }))
1073
+ }
1074
+ item.updatedAt = Date.now()
1075
+ saveArchiveStore(store, customSharedBoardFile)
1076
+ return { ok: true, id: item.id, folder: item.folder }
1077
+ }
1078
+
1079
+ return { ok: false, error: '未知的档案操作:' + op }
1080
+ })
1081
+ }
1082
+
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) {
1088
+ if (!Array.isArray(curations) || !curations.length) return { updatedCount: 0 }
1089
+ return withArchiveLock(customSharedBoardFile, () => {
1090
+ const store = loadArchiveStore(customSharedBoardFile)
1091
+ if (Array.isArray(newFolders)) {
1092
+ newFolders.forEach((nf, idx) => {
1093
+ if (!nf || !nf.id) return
1094
+ const cleanId = String(nf.id).trim().slice(0, 48)
1095
+ if (!cleanId) return
1096
+ const existing = store.folders.find(f => f.id === cleanId)
1097
+ if (existing) {
1098
+ if (nf.label) existing.label = clamp(nf.label, 40)
1099
+ if (nf.hint) existing.hint = clamp(nf.hint, 100)
1100
+ } else {
1101
+ const created = normalizeFolder({
1102
+ id: cleanId,
1103
+ label: nf.label || cleanId,
1104
+ hint: nf.hint || '由 DSH 参谋长整理归纳的工程档案抽屉',
1105
+ accent: nf.accent || '#06b6d4',
1106
+ order: 52 + idx,
1107
+ })
1108
+ if (created) store.folders.push(created)
1109
+ }
1110
+ })
1111
+ }
1112
+
1113
+ let updatedCount = 0
1114
+ for (const c of curations) {
1115
+ if (!c || !c.id) continue
1116
+ const target = store.items.find(it => it.id === c.id)
1117
+ if (!target) continue
1118
+ if (typeof c.folder === 'string' && c.folder.trim()) {
1119
+ const fId = c.folder.trim().slice(0, 48)
1120
+ target.folder = fId
1121
+ if (c.folderLabel && !store.folders.some(f => f.id === fId)) {
1122
+ const created = normalizeFolder({
1123
+ id: fId,
1124
+ label: c.folderLabel,
1125
+ hint: '由 DSH 参谋长整理建立的工程抽屉',
1126
+ accent: '#06b6d4',
1127
+ })
1128
+ if (created) store.folders.push(created)
1129
+ }
1130
+ }
1131
+ if (['gold', 'silver', 'copper'].includes(c.paperclip)) {
1132
+ target.paperclip = c.paperclip
1133
+ }
1134
+ if (typeof c.summary === 'string' && c.summary.trim()) {
1135
+ target.summary = clamp(c.summary, 140)
1136
+ }
1137
+ if (Array.isArray(c.tags) && c.tags.length) {
1138
+ target.tags = normalizeTags(c.tags)
1139
+ }
1140
+ if (Array.isArray(c.points) && c.points.length) {
1141
+ const validPts = c.points.map((p, idx) => normalizePoint(p, idx)).filter(Boolean).slice(0, POINTS_CAP)
1142
+ if (validPts.length) {
1143
+ target.points = validPts
1144
+ }
1145
+ }
1146
+ // Raw `target.body` is NEVER overwritten by Chief curation — 100% lossless!
1147
+ target.organizedBy = 'chief'
1148
+ target.updatedAt = Date.now()
1149
+ updatedCount += 1
1150
+ }
1151
+
1152
+ if (updatedCount > 0) {
1153
+ saveArchiveStore(store, customSharedBoardFile)
1154
+ }
1155
+ return { updatedCount }
1156
+ })
1157
+ }