dsh-chief 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,761 @@
1
+ /**
2
+ * archive-core.js
3
+ *
4
+ * Core archive paths, single file locks, cache accessors, atomic IO, text parsing, and normalization.
5
+ */
6
+
7
+ import crypto from 'node:crypto'
8
+ import fs from 'node:fs'
9
+ import os from 'node:os'
10
+ import path from 'node:path'
11
+ import { threadId } from 'node:worker_threads'
12
+
13
+ export const ARCHIVE_VERSION = 2
14
+
15
+ const ARCHIVE_CAP = 500
16
+
17
+ export const POINTS_CAP = 32
18
+
19
+ export const PRECIPITATED_CAP = 300
20
+
21
+ export 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-----)/
22
+
23
+ export const DEFAULT_ARCHIVE_FOLDERS = [
24
+ {
25
+ id: 'coords',
26
+ label: '工程坐标与部署锚点',
27
+ hint: '源码路径、热更口令、端口、部署验证命令与核心坐标',
28
+ accent: '#f59e0b',
29
+ order: 10,
30
+ },
31
+ {
32
+ id: 'incidents',
33
+ label: '排障实录与硬事实',
34
+ hint: '线上/本地故障症状、根因定位、踩坑教训与修复闭环',
35
+ accent: '#ef4444',
36
+ order: 20,
37
+ },
38
+ {
39
+ id: 'contracts',
40
+ label: '架构契约与方法论',
41
+ hint: '接口契约、参数宽容、截断交代、自检断言与工程纪律',
42
+ accent: '#0a84ff',
43
+ order: 30,
44
+ },
45
+ {
46
+ id: 'ops',
47
+ label: '运维链路与机器环境',
48
+ hint: '本机环境硬事实、服务器代理链路、容器与外部服务手册',
49
+ accent: '#10b981',
50
+ order: 40,
51
+ },
52
+ {
53
+ id: 'plans',
54
+ label: '阶段蓝图与归档计划',
55
+ hint: '官方能力对照、阶段性历史计划存档与里程碑复盘',
56
+ accent: '#8b5cf6',
57
+ order: 50,
58
+ },
59
+ {
60
+ id: 'inbox',
61
+ label: '待分拣工作便签',
62
+ hint: '新近沉淀或尚未归类的工程记录,可随时请参谋长整理收纳',
63
+ accent: '#64748b',
64
+ order: 60,
65
+ },
66
+ ]
67
+
68
+ const DEFAULT_FOLDER_MAP = new Map(DEFAULT_ARCHIVE_FOLDERS.map(f => [f.id, f]))
69
+
70
+ let seq = 0
71
+
72
+ export function nextId(prefix) {
73
+ seq = (seq + 1) % 1000000
74
+ return prefix + '-' + Date.now().toString(36) + '-' + seq.toString(36)
75
+ }
76
+
77
+ export function str(v, fb = '') {
78
+ return typeof v === 'string' ? v : fb
79
+ }
80
+
81
+ export function clamp(v, max) {
82
+ const clean = String(v == null ? '' : v).replace(/\s+/g, ' ').trim()
83
+ if (clean.length <= max) return clean
84
+ return clean.slice(0, Math.max(0, max - 1)) + '…'
85
+ }
86
+
87
+ export function cleanMultiline(v, max) {
88
+ const text = String(v == null ? '' : v).replace(/\r/g, '').trim()
89
+ if (text.length <= max) return text
90
+ return text.slice(0, Math.max(0, max - 1)) + '…'
91
+ }
92
+
93
+ /* ------------------------------------------- Paths, Project Key & Registry */
94
+
95
+ export function normalizeCwd(cwd) {
96
+ const raw = str(cwd, '').trim()
97
+ if (!raw) return ''
98
+ try {
99
+ let resolved = path.resolve(raw)
100
+ if (resolved.length > 3) {
101
+ resolved = resolved.replace(/[\\/]+$/, '')
102
+ }
103
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved
104
+ } catch {
105
+ return raw.replace(/[\\/]+$/, '').toLowerCase()
106
+ }
107
+ }
108
+
109
+ export function resolveProjectKey(cwd = '') {
110
+ const raw = str(cwd, '').trim()
111
+ if (!raw) return 'proj-default'
112
+ if (/^proj-[a-z0-9._-]+$/i.test(raw) && !raw.includes('\\') && !raw.includes('/')) {
113
+ return raw.slice(0, 64)
114
+ }
115
+ const norm = normalizeCwd(raw)
116
+ if (!norm) return 'proj-default'
117
+ const baseRaw = path.basename(norm) || 'workspace'
118
+ const safeBase = baseRaw
119
+ .toLowerCase()
120
+ .replace(/[^a-z0-9\u4e00-\u9fa5._-]+/g, '-')
121
+ .replace(/^-+|-+$/g, '')
122
+ .slice(0, 22) || 'ws'
123
+ const hash8 = crypto.createHash('sha1').update(norm).digest('hex').slice(0, 8)
124
+ return `proj-${safeBase}-${hash8}`
125
+ }
126
+
127
+ function chiefRootDir(targetOpt) {
128
+ let sharedFile = ''
129
+ if (typeof targetOpt === 'string') {
130
+ sharedFile = targetOpt
131
+ } else if (targetOpt && typeof targetOpt === 'object') {
132
+ sharedFile = str(targetOpt.customSharedBoardFile || targetOpt.sharedFile, '').trim()
133
+ }
134
+ if (sharedFile) {
135
+ return path.dirname(sharedFile)
136
+ }
137
+ const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
138
+ return path.join(home, 'chief')
139
+ }
140
+
141
+ export function normalizeVaultScope(raw) {
142
+ const s = str(raw, '').trim().toLowerCase()
143
+ if (s === 'global') return 'global'
144
+ if (s === 'precipitated' || s === 'cold' || s === 'vault') return 'precipitated'
145
+ return 'session'
146
+ }
147
+
148
+ export function cleanRootSessionId(raw = '') {
149
+ const s = str(raw, '').trim()
150
+ return (!s || s === 'global') ? '' : s
151
+ }
152
+
153
+ export function resolveTargetOpts(targetOpt) {
154
+ if (!targetOpt || typeof targetOpt === 'string') {
155
+ return {
156
+ customSharedBoardFile: str(targetOpt, ''),
157
+ cwd: '',
158
+ projectKey: '',
159
+ cabinetId: '',
160
+ rootSessionId: '',
161
+ vaultScope: 'session',
162
+ }
163
+ }
164
+ return {
165
+ customSharedBoardFile: str(targetOpt.customSharedBoardFile || targetOpt.sharedFile, ''),
166
+ cwd: str(targetOpt.cwd, ''),
167
+ projectKey: str(targetOpt.projectKey, ''),
168
+ cabinetId: str(targetOpt.cabinetId, ''),
169
+ rootSessionId: cleanRootSessionId(targetOpt.rootSessionId || targetOpt.sessionId || targetOpt.session),
170
+ vaultScope: normalizeVaultScope(targetOpt.vaultScope || targetOpt.scope),
171
+ }
172
+ }
173
+
174
+ export function normalizeSessionScopeKey(rootSessionId = '') {
175
+ const sid = cleanRootSessionId(rootSessionId)
176
+ if (!sid) return ''
177
+ return 'sess:' + sid.replace(/[^a-zA-Z0-9._-]+/g, '-').slice(0, 72)
178
+ }
179
+
180
+ export function sessionCabinetId(rootSessionId = '') {
181
+ const hash10 = crypto.createHash('sha1').update(String(rootSessionId || 'session')).digest('hex').slice(0, 10)
182
+ return `cab-s-${hash10}`
183
+ }
184
+
185
+ export function withRootScope(targetOpt, rootSessionId = '') {
186
+ const sid = cleanRootSessionId(rootSessionId)
187
+ if (!targetOpt || typeof targetOpt === 'string') {
188
+ const base = { customSharedBoardFile: str(targetOpt, ''), vaultScope: 'session' }
189
+ return sid ? { ...base, rootSessionId: sid } : base
190
+ }
191
+ const vaultScope = normalizeVaultScope(targetOpt.vaultScope || targetOpt.scope)
192
+ if (vaultScope === 'global') {
193
+ return { ...targetOpt, vaultScope: 'global' }
194
+ }
195
+ if (!sid) {
196
+ return { ...targetOpt, vaultScope }
197
+ }
198
+ if (cleanRootSessionId(targetOpt.rootSessionId || targetOpt.sessionId || targetOpt.session)) {
199
+ return { ...targetOpt, vaultScope }
200
+ }
201
+ return { ...targetOpt, rootSessionId: sid, vaultScope }
202
+ }
203
+
204
+ export function legacyArchiveFilePath(targetOpt) {
205
+ return path.join(chiefRootDir(targetOpt), 'archives.json')
206
+ }
207
+
208
+ export function cabinetsDirPath(targetOpt) {
209
+ return path.join(chiefRootDir(targetOpt), 'cabinets')
210
+ }
211
+
212
+ export function cabinetRegistryPath(targetOpt) {
213
+ return path.join(cabinetsDirPath(targetOpt), 'registry.json')
214
+ }
215
+
216
+ export function cabinetFilePath(cabinetId = 'cab-main', targetOpt) {
217
+ const safe = String(cabinetId || 'cab-main').replace(/[^a-zA-Z0-9._-]+/g, '-').slice(0, 72) || 'cab-main'
218
+ return path.join(cabinetsDirPath(targetOpt), `${safe}.json`)
219
+ }
220
+
221
+ export function globalChiefVaultFilePath(targetOpt) {
222
+ return path.join(chiefRootDir(targetOpt), 'global-vault', 'vault-chief-global.json')
223
+ }
224
+
225
+ export function globalPrecipitatedFilePath(targetOpt) {
226
+ return path.join(chiefRootDir(targetOpt), 'precipitated', 'vault-global.json')
227
+ }
228
+
229
+ export function precipitatedFilePath(_projectKey = 'proj-default', targetOpt) {
230
+ return globalPrecipitatedFilePath(targetOpt)
231
+ }
232
+
233
+ export function normalizeArchiveTitleKey(title) {
234
+ return String(title || '').trim().replace(/\s+/g, ' ').toLowerCase()
235
+ }
236
+
237
+ export function computeEntryContentHash(raw) {
238
+ const title = String((raw && raw.title) || '').trim()
239
+ const summary = String((raw && raw.summary) || '').trim()
240
+ const body = cleanMultiline((raw && (raw.body !== undefined ? raw.body : raw.rawBody)) || '', 30000)
241
+ return crypto.createHash('sha1').update(`${title}\n${summary}\n${body}`).digest('hex').slice(0, 12)
242
+ }
243
+
244
+ /* ----------------------------------------------------------- Lock & Storage */
245
+
246
+ const heldArchiveLocks = new Set()
247
+
248
+ const lockSleeper = new Int32Array(new SharedArrayBuffer(4))
249
+
250
+ function sleepSync(ms) {
251
+ try {
252
+ Atomics.wait(lockSleeper, 0, 0, ms)
253
+ } catch {}
254
+ }
255
+
256
+ const CONTENDED_ARCHIVE_LOCK_CODES = new Set(['EEXIST', 'EPERM', 'EACCES', 'EBUSY'])
257
+
258
+ export function acquireFileLock(file) {
259
+ if (heldArchiveLocks.has(file)) return () => {}
260
+ const lock = file + '.lock'
261
+ try {
262
+ fs.mkdirSync(path.dirname(lock), { recursive: true })
263
+ } catch {}
264
+ const deadline = Date.now() + 10000
265
+ for (;;) {
266
+ try {
267
+ const fd = fs.openSync(lock, 'wx')
268
+ try {
269
+ fs.writeSync(fd, `${process.pid}:${threadId}`)
270
+ } catch {}
271
+ fs.closeSync(fd)
272
+ heldArchiveLocks.add(file)
273
+ return () => {
274
+ heldArchiveLocks.delete(file)
275
+ try {
276
+ fs.unlinkSync(lock)
277
+ } catch {}
278
+ }
279
+ } catch (err) {
280
+ const code = err && err.code
281
+ if (code === 'ENOENT' && Date.now() < deadline) {
282
+ try {
283
+ fs.mkdirSync(path.dirname(lock), { recursive: true })
284
+ } catch {}
285
+ sleepSync(2)
286
+ continue
287
+ }
288
+ if (!err || !CONTENDED_ARCHIVE_LOCK_CODES.has(code) || Date.now() >= deadline) {
289
+ try {
290
+ if (Date.now() >= deadline) fs.unlinkSync(lock)
291
+ } catch {}
292
+ heldArchiveLocks.add(file)
293
+ return () => heldArchiveLocks.delete(file)
294
+ }
295
+ if (code === 'EEXIST') {
296
+ try {
297
+ const st = fs.statSync(lock)
298
+ if (Date.now() - st.mtimeMs > 15000) {
299
+ fs.unlinkSync(lock)
300
+ continue
301
+ }
302
+ } catch {}
303
+ }
304
+ sleepSync(2 + Math.floor(Math.random() * 4))
305
+ }
306
+ }
307
+ }
308
+
309
+ let archiveCache = { file: '', mtime: -1, store: null }
310
+
311
+ export function invalidateArchiveCache() {
312
+ archiveCache = { file: '', mtime: -1, store: null }
313
+ }
314
+
315
+ export function atomicWriteJson(file, data) {
316
+ fs.mkdirSync(path.dirname(file), { recursive: true })
317
+ const tmp = `${file}.${process.pid}.${threadId}.${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}.tmp`
318
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf8')
319
+ let lastErr = null
320
+ for (let attempt = 0; attempt < 8; attempt += 1) {
321
+ try {
322
+ fs.renameSync(tmp, file)
323
+ return
324
+ } catch (err) {
325
+ lastErr = err
326
+ const code = err && err.code
327
+ if (code !== 'EPERM' && code !== 'EACCES' && code !== 'EBUSY') break
328
+ sleepSync(2 + attempt * 2)
329
+ }
330
+ }
331
+ try { if (fs.existsSync(tmp)) fs.unlinkSync(tmp) } catch {}
332
+ if (lastErr) throw lastErr
333
+ }
334
+
335
+ export function readJsonSafe(file, fallback = null) {
336
+ try {
337
+ if (!fs.existsSync(file)) return fallback
338
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
339
+ } catch {
340
+ return fallback
341
+ }
342
+ }
343
+
344
+ /* ------------------------------------------- Registry & Legacy Migration */
345
+
346
+ function stripMarkdownDecorators(text) {
347
+ return String(text || '')
348
+ .replace(/^[#>*\-\d.)\s\u3000]+/, '')
349
+ .replace(/\*\*([^*]+)\*\*/g, '$1')
350
+ .replace(/`([^`]+)`/g, '$1')
351
+ .trim()
352
+ }
353
+
354
+ export function firstMeaningfulSentence(text) {
355
+ const lines = String(text || '')
356
+ .split('\n')
357
+ .map(l => l.trim())
358
+ .filter(l => l && !/^\|[-:\s|]+\|$/.test(l) && !/^```/.test(l))
359
+ if (!lines.length) return ''
360
+ const candidate = (/^#{1,4}\s+/.test(lines[0]) && lines[1]) ? lines[1] : lines[0]
361
+ const clean = stripMarkdownDecorators(candidate)
362
+ const firstClause = clean.split(/[。;!?\n]/)[0] || clean
363
+ return clamp(firstClause, 115)
364
+ }
365
+
366
+ export function classifyNoteFolder(title, body, tags = []) {
367
+ const tagText = (Array.isArray(tags) ? tags : []).join(' ').toLowerCase()
368
+ const head = `${title || ''} ${tagText}`.toLowerCase()
369
+ const full = `${head} ${String(body || '').slice(0, 500)}`.toLowerCase()
370
+
371
+ if (/坐标|锚点|安装源|包体|目录结构|端口|热更|set_bundle|deployed/.test(head)) {
372
+ return 'coords'
373
+ }
374
+ if (/运维|环境|机器|硬事实|astrbot|claudia|sing-box|docker|服务器|tunnel|代理链路/.test(head) || /环境|运维/.test(tagText)) {
375
+ return 'ops'
376
+ }
377
+ if (/计划存档|蓝图|对照表|出图线|交接单三项|阶段|roadmap|archive|plan/.test(head)) {
378
+ return 'plans'
379
+ }
380
+ if (/症状|事故|已修|黑屏|坏了|排障|根因|死胡同|绕行|≠|不等于|踩坑|报错|unauthorized|eperm/.test(head)) {
381
+ return 'incidents'
382
+ }
383
+ if (/契约|方法论|自检|上限|截断|宽容|schema|继承规则|归属|注释|派生标题|具名|必须/.test(head) || /方法论|自检|设计/.test(tagText)) {
384
+ return 'contracts'
385
+ }
386
+ if (/坐标|路径|d:\\|%dsh_home%/.test(full) && /验证|pass/.test(full)) {
387
+ return 'coords'
388
+ }
389
+ if (/##\s*症状|##\s*根因|硬事实/.test(full)) {
390
+ return 'incidents'
391
+ }
392
+ return 'contracts'
393
+ }
394
+
395
+ function inferPaperclip(raw, folder) {
396
+ const tags = (Array.isArray(raw && raw.tags) ? raw.tags : []).map(t => String(t).toLowerCase())
397
+ if (raw && (raw.pinned === true || tags.includes('anchor') || raw.paperclip === 'gold')) {
398
+ return 'gold'
399
+ }
400
+ if (tags.includes('archive') || folder === 'plans') {
401
+ return 'copper'
402
+ }
403
+ return 'silver'
404
+ }
405
+
406
+ export function extractStructuredPoints(title, rawBody) {
407
+ const body = String(rawBody || '').replace(/\r/g, '').trim()
408
+ if (!body) {
409
+ return [
410
+ {
411
+ id: 'pt-1',
412
+ title: '归档标题备忘',
413
+ cue: '当前仅记录卷宗标题,尚未补充详细正文',
414
+ detail: `卷宗《${title || '未命名'}》当前无附加正文,可通过「编辑」随时补充工程细节。`,
415
+ },
416
+ ]
417
+ }
418
+
419
+ const lines = body.split('\n')
420
+ const headingIndices = []
421
+ for (let i = 0; i < lines.length; i += 1) {
422
+ if (/^#{2,3}\s+\S/.test(lines[i].trim())) {
423
+ headingIndices.push(i)
424
+ }
425
+ }
426
+ if (headingIndices.length >= 1) {
427
+ const points = []
428
+ const preLines = lines.slice(0, headingIndices[0]).filter(l => !/^#\s+/.test(l.trim()))
429
+ const preText = preLines.join('\n').trim()
430
+ if (preText.length >= 18) {
431
+ points.push({
432
+ id: `pt-${points.length + 1}`,
433
+ title: '背景与总览',
434
+ cue: firstMeaningfulSentence(preText),
435
+ detail: preText,
436
+ })
437
+ }
438
+ for (let hIdx = 0; hIdx < headingIndices.length; hIdx += 1) {
439
+ const start = headingIndices[hIdx]
440
+ const end = hIdx + 1 < headingIndices.length ? headingIndices[hIdx + 1] : lines.length
441
+ const rawHeading = lines[start].trim().replace(/^#{2,3}\s+/, '').trim()
442
+ const secBody = lines.slice(start + 1, end).join('\n').trim()
443
+ if (!secBody && !rawHeading) continue
444
+ points.push({
445
+ id: `pt-${points.length + 1}`,
446
+ title: clamp(stripMarkdownDecorators(rawHeading) || `要点 ${points.length + 1}`, 76),
447
+ cue: firstMeaningfulSentence(secBody) || clamp(rawHeading, 90),
448
+ detail: secBody || rawHeading,
449
+ })
450
+ }
451
+ if (points.length >= 1) return points.slice(0, POINTS_CAP)
452
+ }
453
+
454
+ const kvBlocks = []
455
+ let currentKv = null
456
+ for (const rawLine of lines) {
457
+ const trimmed = rawLine.trim()
458
+ if (!trimmed) continue
459
+ const kvMatch = /^([^\s::|]{2,18}(?:[((][^))]{1,18}[))])?)\s*[::]\s*(.*)$/.exec(trimmed)
460
+ const numMatch = /^(\d+)\.\s+(?:\[[xX\s]\]\s*)?(.+)$/.exec(trimmed)
461
+ if (kvMatch) {
462
+ if (currentKv) kvBlocks.push(currentKv)
463
+ const rest = kvMatch[2].trim()
464
+ currentKv = {
465
+ title: stripMarkdownDecorators(kvMatch[1]),
466
+ lines: rest ? [rest] : [],
467
+ }
468
+ } else if (numMatch && !currentKv) {
469
+ kvBlocks.push({
470
+ title: clamp(stripMarkdownDecorators(numMatch[2]), 54),
471
+ lines: [trimmed],
472
+ })
473
+ } else if (currentKv) {
474
+ currentKv.lines.push(trimmed)
475
+ } else {
476
+ currentKv = {
477
+ title: clamp(firstMeaningfulSentence(trimmed), 46) || '背景说明',
478
+ lines: [trimmed],
479
+ }
480
+ }
481
+ }
482
+ if (currentKv) kvBlocks.push(currentKv)
483
+ if (kvBlocks.length >= 2) {
484
+ return kvBlocks.slice(0, POINTS_CAP).map((b, i) => {
485
+ const detail = b.lines.join('\n').trim() || b.title
486
+ return {
487
+ id: `pt-${i + 1}`,
488
+ title: clamp(b.title || `要点 ${i + 1}`, 72),
489
+ cue: firstMeaningfulSentence(detail),
490
+ detail,
491
+ }
492
+ })
493
+ }
494
+
495
+ const paragraphs = body
496
+ .split(/\n{2,}/)
497
+ .map(p => p.trim())
498
+ .filter(p => p && !/^#\s+/.test(p))
499
+
500
+ if (paragraphs.length >= 2) {
501
+ return paragraphs.slice(0, POINTS_CAP).map((para, idx) => {
502
+ const first = firstMeaningfulSentence(para)
503
+ return {
504
+ id: `pt-${idx + 1}`,
505
+ title: clamp(first || `记忆点 ${idx + 1}`, 56),
506
+ cue: clamp(para.replace(/\s+/g, ' '), 105),
507
+ detail: para,
508
+ }
509
+ })
510
+ }
511
+
512
+ const sentences = body
513
+ .split(/(?<=[。!?;])\s*/)
514
+ .map(s => s.trim())
515
+ .filter(Boolean)
516
+
517
+ if (sentences.length >= 2 && body.length > 95) {
518
+ const labels = ['核心问题与诱因', '关键判据与机制', '落地规范与避坑', '补充细节']
519
+ const grouped = []
520
+ const chunkSize = sentences.length >= 5 ? 2 : 1
521
+ for (let i = 0; i < sentences.length; i += chunkSize) {
522
+ const slice = sentences.slice(i, i + chunkSize).join('')
523
+ const labelIdx = Math.min(grouped.length, labels.length - 1)
524
+ grouped.push({
525
+ id: `pt-${grouped.length + 1}`,
526
+ title: `${labels[labelIdx]}:${clamp(stripMarkdownDecorators(sentences[i]), 36)}`,
527
+ cue: clamp(stripMarkdownDecorators(slice), 100),
528
+ detail: slice,
529
+ })
530
+ }
531
+ return grouped.slice(0, POINTS_CAP)
532
+ }
533
+
534
+ return [
535
+ {
536
+ id: 'pt-1',
537
+ title: clamp(title || firstMeaningfulSentence(body) || '核心记忆点', 64),
538
+ cue: firstMeaningfulSentence(body),
539
+ detail: body,
540
+ },
541
+ ]
542
+ }
543
+
544
+ export function smartParseNoteToDossier(rawNote) {
545
+ const note = rawNote && typeof rawNote === 'object' ? rawNote : {}
546
+ const body = cleanMultiline(note.body || '', 30000)
547
+ const derivedTitle = clamp(
548
+ note.title || firstMeaningfulSentence(body) || '未命名工程卷宗',
549
+ 180,
550
+ )
551
+ const folder = str(note.folder, '').trim() || classifyNoteFolder(derivedTitle, body, note.tags)
552
+ const paperclip = inferPaperclip(note, folder)
553
+ const points = extractStructuredPoints(derivedTitle, body)
554
+ const summary = clamp(
555
+ note.summary || (points[0] && points[0].cue) || firstMeaningfulSentence(body) || derivedTitle,
556
+ 135,
557
+ )
558
+ return {
559
+ title: derivedTitle,
560
+ summary,
561
+ folder,
562
+ paperclip,
563
+ points,
564
+ }
565
+ }
566
+
567
+ /* ------------------------------------ Non-Destructive Bootstrap Migration */
568
+
569
+ export function normalizeFolder(raw, index = 0) {
570
+ if (!raw || typeof raw !== 'object') return null
571
+ const id = str(raw.id, '').trim().slice(0, 64)
572
+ if (!id) return null
573
+ const preset = DEFAULT_FOLDER_MAP.get(id)
574
+ return {
575
+ id,
576
+ label: clamp(raw.label || (preset && preset.label) || id, 40),
577
+ hint: clamp(raw.hint || (preset && preset.hint) || '', 100),
578
+ accent: str(raw.accent || (preset && preset.accent) || '#0a84ff', '#0a84ff').slice(0, 24),
579
+ order: Number.isFinite(Number(raw.order)) ? Number(raw.order) : ((preset && preset.order) || (70 + index * 5)),
580
+ }
581
+ }
582
+
583
+ export function normalizePoint(raw, idx = 0) {
584
+ if (!raw || typeof raw !== 'object') return null
585
+ const title = clamp(raw.title || `要点 ${idx + 1}`, 90)
586
+ const detail = cleanMultiline(raw.detail || raw.text || raw.body || '', 6000)
587
+ if (!title && !detail) return null
588
+ const cueSource = str(raw.cue || raw.summary, '').trim()
589
+ const derivedCue = cueSource || firstMeaningfulSentence(detail)
590
+ return {
591
+ id: str(raw.id, '').trim() || ('pt-' + (idx + 1)),
592
+ title: title || clamp(derivedCue || `记忆点 ${idx + 1}`, 60),
593
+ cue: clamp(derivedCue, 110),
594
+ detail: detail || title,
595
+ }
596
+ }
597
+
598
+ export function normalizeTags(list) {
599
+ if (!Array.isArray(list)) return []
600
+ const seen = new Set()
601
+ const out = []
602
+ for (const raw of list) {
603
+ const t = String(raw || '').trim().slice(0, 36)
604
+ if (!t) continue
605
+ if (t.toLowerCase() === 'anchor') continue
606
+ const low = t.toLowerCase()
607
+ if (seen.has(low)) continue
608
+ seen.add(low)
609
+ out.push(t)
610
+ if (out.length >= 10) break
611
+ }
612
+ return out
613
+ }
614
+
615
+ export function normalizeArchiveItem(raw) {
616
+ if (!raw || typeof raw !== 'object') return null
617
+ const body = cleanMultiline(raw.body || '', 30000)
618
+ const rawTitle = clamp(raw.title || '', 180)
619
+ if (!rawTitle && !body) return null
620
+
621
+ const parsedFallback = (!Array.isArray(raw.points) || !raw.points.length || !raw.folder || !raw.summary)
622
+ ? smartParseNoteToDossier(raw)
623
+ : null
624
+
625
+ const title = rawTitle || (parsedFallback && parsedFallback.title) || '未命名工程卷宗'
626
+ const folder = str(raw.folder, '').trim() || (parsedFallback && parsedFallback.folder) || 'inbox'
627
+ const validClips = ['gold', 'silver', 'copper']
628
+ const paperclip = validClips.includes(raw.paperclip)
629
+ ? raw.paperclip
630
+ : ((parsedFallback && parsedFallback.paperclip) || 'silver')
631
+
632
+ const pointsRaw = Array.isArray(raw.points) && raw.points.length
633
+ ? raw.points
634
+ : ((parsedFallback && parsedFallback.points) || [])
635
+ const points = pointsRaw.map((p, i) => normalizePoint(p, i)).filter(Boolean).slice(0, POINTS_CAP)
636
+
637
+ const summary = clamp(
638
+ raw.summary || (parsedFallback && parsedFallback.summary) || (points[0] && (points[0].cue || points[0].title)) || firstMeaningfulSentence(body) || title,
639
+ 140,
640
+ )
641
+
642
+ const takenOutSessions = Array.isArray(raw.takenOutSessions)
643
+ ? [...new Set(raw.takenOutSessions.map(s => String(s || '').trim()).filter(Boolean))].slice(0, 32)
644
+ : []
645
+ const chiefMountedSessions = Array.isArray(raw.chiefMountedSessions)
646
+ ? [...new Set(raw.chiefMountedSessions.map(s => String(s || '').trim()).filter(Boolean))].slice(0, 32)
647
+ : []
648
+ const contentHash = str(raw.contentHash, '').trim() || computeEntryContentHash({ title, summary, body })
649
+
650
+ return {
651
+ id: str(raw.id, '').trim() || nextId('arch'),
652
+ sourceNoteId: str(raw.sourceNoteId, '').trim(),
653
+ originId: str(raw.originId, '').trim(),
654
+ originGlobalId: str(raw.originGlobalId, '').trim(),
655
+ title,
656
+ summary,
657
+ folder,
658
+ paperclip,
659
+ tags: normalizeTags(Array.isArray(raw.tags) ? raw.tags : []),
660
+ cold: raw.cold !== false,
661
+ takenOutSessions,
662
+ chiefMountedSessions,
663
+ organizedBy: ['auto', 'chief', 'user'].includes(raw.organizedBy) ? raw.organizedBy : 'auto',
664
+ points,
665
+ body,
666
+ contentHash,
667
+ by: clamp(raw.by || 'agent', 40),
668
+ sourceSession: str(raw.sourceSession || raw.session, '').trim(),
669
+ createdAt: Number(raw.createdAt) || Date.now(),
670
+ updatedAt: Number(raw.updatedAt) || Number(raw.createdAt) || Date.now(),
671
+ }
672
+ }
673
+
674
+ export function normalizeGlobalVaultEntry(raw) {
675
+ const norm = normalizeArchiveItem({
676
+ ...(raw || {}),
677
+ id: str(raw && raw.id, '').trim() || nextId('glob'),
678
+ cold: true,
679
+ })
680
+ if (!norm) return null
681
+ return {
682
+ ...norm,
683
+ takenOutSessions: Array.isArray(norm.takenOutSessions) ? norm.takenOutSessions : [],
684
+ cold: true,
685
+ chiefMountedSessions: Array.isArray(norm.chiefMountedSessions) ? norm.chiefMountedSessions : [],
686
+ }
687
+ }
688
+
689
+ export function normalizeArchiveStore(raw) {
690
+ const src = raw && typeof raw === 'object' ? raw : {}
691
+ const folderMap = new Map()
692
+ for (const def of DEFAULT_ARCHIVE_FOLDERS) {
693
+ folderMap.set(def.id, { ...def })
694
+ }
695
+ if (Array.isArray(src.folders)) {
696
+ src.folders.forEach((f, idx) => {
697
+ const nf = normalizeFolder(f, idx)
698
+ if (nf) folderMap.set(nf.id, nf)
699
+ })
700
+ }
701
+
702
+ const normalizer = src.isSystemGlobalVault ? normalizeGlobalVaultEntry : normalizeArchiveItem
703
+ const items = (Array.isArray(src.items) ? src.items : [])
704
+ .map(normalizer)
705
+ .filter(Boolean)
706
+ .slice(0, ARCHIVE_CAP)
707
+
708
+ let customIdx = 0
709
+ for (const item of items) {
710
+ if (item.folder && !folderMap.has(item.folder)) {
711
+ customIdx += 1
712
+ folderMap.set(item.folder, {
713
+ id: item.folder,
714
+ label: clamp(item.folder, 40),
715
+ hint: '自定义工程档案抽屉',
716
+ accent: ['#06b6d4', '#ec4899', '#eab308', '#14b8a6'][customIdx % 4],
717
+ order: 55 + customIdx,
718
+ })
719
+ }
720
+ }
721
+
722
+ const folders = [...folderMap.values()].sort((a, b) => (a.order || 99) - (b.order || 99))
723
+
724
+ return {
725
+ version: ARCHIVE_VERSION,
726
+ isSystemGlobalVault: Boolean(src.isSystemGlobalVault),
727
+ cabinetId: src.isSystemGlobalVault ? '' : (str(src.cabinetId, 'cab-main').trim() || 'cab-main'),
728
+ cabinetName: src.isSystemGlobalVault
729
+ ? '🌐 系统全局档案柜'
730
+ : clamp(src.cabinetName || '默认主档案柜', 40),
731
+ projectKey: src.isSystemGlobalVault ? 'global' : resolveProjectKey(src.projectKey || 'proj-default'),
732
+ migratedSharedAt: Number(src.migratedSharedAt) || 0,
733
+ updatedAt: Number(src.updatedAt) || Date.now(),
734
+ folders,
735
+ items,
736
+ }
737
+ }
738
+
739
+ export function getCachedArchiveStore(file, mtime) {
740
+ if (archiveCache.store && archiveCache.file === file && archiveCache.mtime === mtime) {
741
+ return archiveCache.store
742
+ }
743
+ return null
744
+ }
745
+
746
+ export function setCachedArchiveStore(file, mtime, store) {
747
+ archiveCache = { file, mtime, store }
748
+ }
749
+
750
+ let archiveMutatorHook = null
751
+
752
+ export function registerArchiveMutatorHook(fn) {
753
+ archiveMutatorHook = typeof fn === 'function' ? fn : null
754
+ }
755
+
756
+ export function invokeArchiveMutatorHook(payload, targetOpt) {
757
+ if (!archiveMutatorHook) {
758
+ return { ok: false, error: 'archive mutator hook not registered' }
759
+ }
760
+ return archiveMutatorHook(payload, targetOpt)
761
+ }