@asd2233996/dsh-auto-context 0.0.0-stage → 1.15.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,1427 @@
1
+ /**
2
+ * context-manager — 信息库的项目级持久化层(派生长期记忆,不是真相源)。
3
+ *
4
+ * 背景:`lib/extract.js` 从阶段卡里抽出项目级持久事实(FACT),`lib/graph.js`
5
+ * 在内存里做去重/连边/检索/BFS。本模块只负责**落盘**:
6
+ *
7
+ * - **每项目一个 JSON 图文件**:`$DSH_HOME/context-manager/kg/graphs/<key>.json`,
8
+ * 其中 `key = sha256(规范化 cwd)` 的前 32 位(无 cwd 时回退会话 id)。
9
+ * 同一个项目(同一工作目录)跨会话共享一份图谱;临时会话(无 cwd)按会话隔离。
10
+ * - **原子写**:先写 `<file>.tmp-<pid>-<rand>`,fsync 后 rename 覆盖;rename 前把
11
+ * 旧主文件复制成 `.bak`(保留一份上一版);跨设备 rename 失败时退化为
12
+ * `copyFileSync`(非原子但内容完整)。
13
+ * - **坏文件隔离**:主文件坏 JSON / 版本不符 / 结构非法时,先尝试 `.bak`;
14
+ * 备份可用则标记 `recovered` 并写回主文件;主备都坏则把坏文件改名为
15
+ * `<file>.corrupt-<ts>` 隔离,返回空图(绝不因为派生缓存损坏而拖垮宿主)。
16
+ * - **上限与淘汰**:facts 默认上限 3000(可配),超限按
17
+ * importance / confidence / hitCount / updatedAt 淘汰“低价值、非 pinned、
18
+ * 非 high”的事实,并同步清理 turns.factIds 里对已淘汰事实的引用。
19
+ * - **轮次索引**:`turns` 记录每轮抽取状态(status/hash/factIds/at/model/error),
20
+ * 供上层按内容哈希做幂等去重(内容没变不重复花钱调用模型)。
21
+ * - **防御式归一化**:所有读入数据都过白名单校验(字段类型/枚举/长度/条数),
22
+ * 脏字段丢弃、可选字段补默认,未知字段不落盘。
23
+ *
24
+ * 与 `lib/graph.js` 的接线(供 lib/actions.js 集成):
25
+ * ```js
26
+ * // 读:state → graph
27
+ * const { state } = loadKgState(key, project.label)
28
+ * const graph = deserializeGraph({ version: 1, facts: state.facts, meta: { createdAt: state.createdAt, updatedAt: state.updatedAt, revision: state.revision } })
29
+ * // 写:graph → state → 原子落盘
30
+ * const snap = serializeGraph(graph)
31
+ * state.facts = Object.fromEntries(snap.facts.map(fact => [fact.id, fact]))
32
+ * saveKgState(key, state)
33
+ * ```
34
+ * 因此落盘事实的 confidence 用 extract/graph 的字符串标签
35
+ * ('high' | 'medium' | 'low'),边用 graph 展开后的扁平形状
36
+ * `{from,to,type,weight,reason}`——直接喂给 `deserializeGraph` 即可。
37
+ *
38
+ * 设计约束(与 lib/store.js 保持一致):
39
+ * - 同步 fs(宿主单进程、项目图文件较小,几十 KB 量级);
40
+ * - 无第三方依赖,不访问 Cordis `ctx`,可直接在 `node --test` 里覆盖;
41
+ * - 只读写自己的目录,不碰会话日志;坏文件只隔离不删除。
42
+ *
43
+ * 独立测试:`node --test tests/kg-store.test.mjs`。
44
+ * @module context-manager/kg-store
45
+ */
46
+
47
+ import { createHash, randomBytes } from 'node:crypto'
48
+ import {
49
+ closeSync,
50
+ copyFileSync,
51
+ existsSync,
52
+ fsyncSync,
53
+ mkdirSync,
54
+ openSync,
55
+ readFileSync,
56
+ renameSync,
57
+ rmSync,
58
+ writeFileSync,
59
+ } from 'node:fs'
60
+ import { homedir } from 'node:os'
61
+ import { dirname, join, posix } from 'node:path'
62
+
63
+ import { dataDir } from './store.js'
64
+
65
+ /* -------------------------------------------------------------------------- */
66
+ /* 契约常量 */
67
+ /* -------------------------------------------------------------------------- */
68
+
69
+ /** 项目图状态文件格式版本;字段语义变化时 +1(旧文件会被安全隔离/重置)。 */
70
+ export const KG_VERSION = 1
71
+
72
+ /** 事实种类(与 lib/extract.js 的 FACT_KINDS 对齐;非法种类的事实直接丢弃)。 */
73
+ export const KG_FACT_KINDS = Object.freeze([
74
+ 'requirement',
75
+ 'constraint',
76
+ 'structure',
77
+ 'decision',
78
+ 'result',
79
+ 'interface',
80
+ 'convention',
81
+ ])
82
+
83
+ /** 事实状态:active 现行;superseded 被替代;rejected 被否决;archived 归档。 */
84
+ export const KG_FACT_STATUSES = Object.freeze(['active', 'superseded', 'rejected', 'archived'])
85
+
86
+ /** 轮次索引状态:done 已完成;pending 待抽取;failed 抽取失败;skipped 跳过。 */
87
+ export const KG_TURN_STATUSES = Object.freeze(['done', 'pending', 'failed', 'skipped'])
88
+
89
+ /**
90
+ * 置信度标签(与 `lib/extract.js` / `lib/graph.js` 完全一致)。
91
+ *
92
+ * 注意:落盘格式就是这三个字符串,**不是** 0..1 数值——图谱层的
93
+ * `normalizeConfidence` 只认字符串,数值会被降级成 'medium'。数值输入(0..1)
94
+ * 会在归一化时映射到标签(≥0.75 high / ≥0.4 medium / 其余 low),淘汰排序时
95
+ * 再映射回 1 / 0.6 / 0.3。
96
+ */
97
+ export const KG_CONFIDENCES = Object.freeze(['high', 'medium', 'low'])
98
+
99
+ /**
100
+ * 默认上限。全部可被 `options.limits` / `options.maxFacts` 覆盖。
101
+ * - maxFacts:单个项目图的事实上限(默认 3000);
102
+ * - maxTurns:轮次索引条目上限;
103
+ * - maxShadowedSeqs:archive.shadowedSeqs 上限;
104
+ * - maxStatementChars:statement 字符上限;
105
+ * - maxScopeSegments / maxEntities:单事实的路径段数 / 实体数上限。
106
+ */
107
+ export const DEFAULT_KG_LIMITS = Object.freeze({
108
+ maxFacts: 3000,
109
+ maxTurns: 1000,
110
+ maxShadowedSeqs: 5000,
111
+ maxStatementChars: 240,
112
+ maxScopeSegments: 8,
113
+ maxEntities: 8,
114
+ })
115
+
116
+ /** 置信度标签 → 数值(图谱排序/淘汰统一用数值)。 */
117
+ const CONFIDENCE_BY_LABEL = Object.freeze({ high: 1, medium: 0.6, low: 0.3 })
118
+
119
+ /** 置信度标签集合。 */
120
+ const CONFIDENCE_LABEL_SET = new Set(KG_CONFIDENCES)
121
+
122
+ /** 达到该数值的 confidence/importance 视为“high”,淘汰时永不优先丢弃。 */
123
+ const HIGH_VALUE_THRESHOLD = 0.8
124
+
125
+ /** 单条事实 source.seqs / turn.factIds / 关系引用的条数上限。 */
126
+ const MAX_FACT_ID_REFS = 500
127
+
128
+ /** 单条事实 supersededBy / conflictsWith / aliases / sources 的条数上限。 */
129
+ const MAX_FACT_REFS = 20
130
+ const MAX_FACT_ALIASES = 8
131
+ const MAX_FACT_SOURCES = 4
132
+
133
+ /** 计数器上限,防止脏数据把 JSON 撑爆。 */
134
+ const MAX_COUNTER = 1_000_000_000
135
+
136
+ /** 边端点字段别名(graph 输出 from/to;兼容 source/target、a/b、left/right)。 */
137
+ const EDGE_FROM_KEYS = Object.freeze(['from', 'source', 'a', 'left'])
138
+ const EDGE_TO_KEYS = Object.freeze(['to', 'target', 'b', 'right'])
139
+
140
+ /** 合法边类型集合。 */
141
+
142
+ /** 危险的 Record 键(防原型污染:模型/文件给的 id 不能直接当对象键写入)。 */
143
+ const UNSAFE_RECORD_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
144
+
145
+ /** 是否可作为普通 Record 的自有键(非空且不是危险键)。 */
146
+ function isSafeRecordKey(value) {
147
+ return typeof value === 'string' && value !== '' && !UNSAFE_RECORD_KEYS.has(value)
148
+ }
149
+
150
+ /** 事实状态对“当前价值”的修正项(rejected 最先被淘汰,active 最保值)。 */
151
+ const STATUS_VALUE = Object.freeze({ active: 0.3, superseded: 0, archived: -0.1, rejected: -0.4 })
152
+
153
+ /* -------------------------------------------------------------------------- */
154
+ /* 基础工具 */
155
+ /* -------------------------------------------------------------------------- */
156
+
157
+ /**
158
+ * 是否为普通对象(排除 null / 数组)。
159
+ * @param {unknown} value - 待判定值。
160
+ * @returns {boolean} 是否普通对象。
161
+ */
162
+ function isRecord(value) {
163
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
164
+ }
165
+
166
+ /**
167
+ * 折叠空白(换行/制表/连续空格 → 单个空格)并去首尾空白。
168
+ * @param {string} text - 原始文本。
169
+ * @returns {string} 折叠后的文本。
170
+ */
171
+ function collapseWhitespace(text) {
172
+ return text.replace(/\s+/gu, ' ').trim()
173
+ }
174
+
175
+ /**
176
+ * 按 code point 截断字符串(中文/emoji 不会被截半)。
177
+ * @param {string} text - 原始文本。
178
+ * @param {number} max - 最大字符数。
179
+ * @returns {string} 截断后的文本。
180
+ */
181
+ function truncateCodePoints(text, max) {
182
+ if (max <= 0) return ''
183
+ const chars = Array.from(text)
184
+ return chars.length <= max ? text : chars.slice(0, max).join('')
185
+ }
186
+
187
+ /**
188
+ * 清洗任意值为单行短文本:数字转字符串、折叠空白、截断;非法/空返回 fallback。
189
+ * @param {unknown} value - 原始值。
190
+ * @param {number} max - 最大字符数。
191
+ * @param {string} [fallback] - 非法/空时的兜底。
192
+ * @returns {string} 清洗后的文本。
193
+ */
194
+ function cleanText(value, max, fallback = '') {
195
+ if (typeof value !== 'string') {
196
+ if (typeof value === 'number' && Number.isFinite(value)) value = String(value)
197
+ else return fallback
198
+ }
199
+ const text = collapseWhitespace(value)
200
+ if (text === '') return fallback
201
+ return truncateCodePoints(text, max)
202
+ }
203
+
204
+ /** 测试/日志用:把错误压成一行短文本。 */
205
+ function describeError(error) {
206
+ if (error === null || error === undefined) return '未知错误'
207
+ const message = error instanceof Error ? error.message : String(error)
208
+ return truncateCodePoints(collapseWhitespace(message), 240)
209
+ }
210
+
211
+ /* -------------------------------------------------------------------------- */
212
+ /* 目录与文件名 */
213
+ /* -------------------------------------------------------------------------- */
214
+
215
+ /** 项目图目录:`$DSH_HOME/context-manager/kg/graphs/`。 */
216
+ export function kgGraphsDir() {
217
+ return join(dataDir(), 'kg', 'graphs')
218
+ }
219
+
220
+ /**
221
+ * 清洗项目 key:合法 16~32 位十六进制原样(小写)返回;其它值(空串、路径穿越、
222
+ * 超长 id)统一安全哈希成 32 位十六进制,保证不会越出图谱目录。
223
+ * @param {unknown} key - 原始 key。
224
+ * @returns {string} 安全 key。
225
+ */
226
+ export function sanitizeKgKey(key) {
227
+ const raw = typeof key === 'string'
228
+ ? key.trim()
229
+ : (typeof key === 'number' && Number.isFinite(key) ? String(key) : '')
230
+ if (/^[0-9a-f]{16,32}$/iu.test(raw)) return raw.toLowerCase()
231
+ return createHash('sha256')
232
+ .update(raw === '' ? 'context-manager/kg' : `context-manager/kg\u0000${raw}`)
233
+ .digest('hex')
234
+ .slice(0, 32)
235
+ }
236
+
237
+ /**
238
+ * 项目图主文件:`.../kg/graphs/<key>.json`。
239
+ * @param {unknown} key - 项目 key。
240
+ * @returns {string} 文件路径。
241
+ */
242
+ export function kgFile(key) {
243
+ return join(kgGraphsDir(), `${sanitizeKgKey(key)}.json`)
244
+ }
245
+
246
+ /**
247
+ * 项目图备份文件:`<key>.json.bak`(保存时保留一份上一版)。
248
+ * @param {unknown} key - 项目 key。
249
+ * @returns {string} 文件路径。
250
+ */
251
+ export function kgBackupFile(key) {
252
+ return `${kgFile(key)}.bak`
253
+ }
254
+
255
+ /**
256
+ * 损坏文件隔离路径:`<key>.json.corrupt-<ts>`。
257
+ * @param {unknown} key - 项目 key。
258
+ * @param {number|string} [ts] - 时间戳(数字毫秒或安全字符串;缺省当前时间)。
259
+ * @returns {string} 隔离文件路径。
260
+ */
261
+ export function kgQuarantineFile(key, ts) {
262
+ const base = kgFile(key)
263
+ const stamp = typeof ts === 'number' && Number.isFinite(ts)
264
+ ? String(Math.max(0, Math.trunc(ts)))
265
+ : (typeof ts === 'string' && ts.replace(/[^0-9A-Za-z_-]/gu, '') !== ''
266
+ ? ts.replace(/[^0-9A-Za-z_-]/gu, '').slice(0, 64)
267
+ : String(Date.now()))
268
+ return `${base}.corrupt-${stamp}`
269
+ }
270
+
271
+ /* -------------------------------------------------------------------------- */
272
+ /* 会话 → 项目 key */
273
+ /* -------------------------------------------------------------------------- */
274
+
275
+ /**
276
+ * 规范化工作目录:反斜杠转 `/`、折叠重复分隔符、小写盘符、消解 `.`/`..`、
277
+ * 去尾部斜杠;`~` 展开为用户主目录;相对路径按 `process.cwd()` 解析。
278
+ *
279
+ * 结论稳定性很重要:同一个项目(同一 cwd)跨进程/跨会话必须得到同一个字符串,
280
+ * 否则会分裂成多份图谱。因此这里不依赖平台 `path.resolve`,而是用 posix 语义
281
+ * 做确定性归一。
282
+ *
283
+ * @param {unknown} value - 原始 cwd。
284
+ * @returns {string|null} 规范化后的绝对路径;非法/空返回 null。
285
+ */
286
+ export function normalizeProjectCwd(value) {
287
+ if (typeof value !== 'string') return null
288
+ let text = value.trim()
289
+ if (text === '') return null
290
+ if (text === '~' || text.startsWith('~/') || text.startsWith('~\\')) {
291
+ text = join(homedir(), text.slice(1).replace(/^[\\/]+/u, ''))
292
+ }
293
+ text = text.replace(/\\/gu, '/')
294
+ const unc = text.startsWith('//')
295
+ text = text.replace(/\/{2,}/gu, '/')
296
+ if (unc) text = `/${text}`
297
+ const drive = /^([A-Za-z]):(?:\/|$)/u.exec(text)
298
+ if (drive !== null) {
299
+ // Windows 盘符路径:小写盘符 + posix 语义消解;不做 resolve(避免被 cwd 污染)。
300
+ text = posix.normalize(`${drive[1].toLowerCase()}:${text.slice(2)}`)
301
+ } else if (unc) {
302
+ // UNC 路径(//server/share):只折叠分隔符,不交给 posix.normalize(它会吃掉前导 //)。
303
+ } else if (text.startsWith('/')) {
304
+ text = posix.normalize(text)
305
+ } else {
306
+ text = posix.resolve(text)
307
+ }
308
+ if (text === '/' || text === '//' || /^[a-z]:\/$/u.test(text)) return text
309
+ return text.replace(/\/+$/u, '')
310
+ }
311
+
312
+ /** 从规范化 cwd 取项目展示名(最后一段路径;根目录则用路径本身)。 */
313
+ function projectLabelFromCwd(cwd) {
314
+ if (typeof cwd !== 'string' || cwd === '') return 'project'
315
+ if (cwd === '/' || cwd === '//' || /^[a-z]:\/$/u.test(cwd)) return cwd
316
+ const trimmed = cwd.replace(/\/+$/u, '')
317
+ const index = trimmed.lastIndexOf('/')
318
+ const base = index >= 0 ? trimmed.slice(index + 1) : trimmed
319
+ const label = cleanText(base, 120)
320
+ return label === '' ? cwd : label
321
+ }
322
+
323
+ /**
324
+ * 从会话对象推导项目 key/label/cwd。
325
+ *
326
+ * 取值顺序:`session.header.cwd` → `session.meta.cwd` → `session.cwd`;
327
+ * 有 cwd 时 `key = sha256(规范化 cwd).slice(0, 32)`、`label` 为目录名;
328
+ * 无 cwd(临时会话)时回退 `session.id`(或 `sessionId`),`label = 'session'`。
329
+ *
330
+ * @param {unknown} session - 宿主会话对象(也接受字符串会话 id)。
331
+ * @returns {{ key: string, label: string, cwd: string|null }} 项目标识。
332
+ */
333
+ export function projectKeyOf(session) {
334
+ const record = isRecord(session) ? session : (typeof session === 'string' ? { id: session } : {})
335
+ const header = isRecord(record.header) ? record.header : {}
336
+ const meta = isRecord(record.meta) ? record.meta : {}
337
+ const candidates = [header.cwd, meta.cwd, record.cwd]
338
+ let cwd = null
339
+ for (const candidate of candidates) {
340
+ const normalized = normalizeProjectCwd(candidate)
341
+ if (normalized !== null) {
342
+ cwd = normalized
343
+ break
344
+ }
345
+ }
346
+ if (cwd !== null) {
347
+ return {
348
+ key: createHash('sha256').update(cwd).digest('hex').slice(0, 32),
349
+ label: projectLabelFromCwd(cwd),
350
+ cwd,
351
+ }
352
+ }
353
+ const sessionId = cleanText(record.id ?? record.sessionId, 200)
354
+ const source = sessionId === ''
355
+ ? 'context-manager/session/unknown'
356
+ : `context-manager/session/${sessionId}`
357
+ return {
358
+ key: createHash('sha256').update(source).digest('hex').slice(0, 32),
359
+ label: 'session',
360
+ cwd: null,
361
+ }
362
+ }
363
+
364
+ /* -------------------------------------------------------------------------- */
365
+ /* 上限解析 */
366
+ /* -------------------------------------------------------------------------- */
367
+
368
+ /**
369
+ * 解析调用方传入的上限/选项:支持 `options.limits` 嵌套,也支持 `options.maxFacts`
370
+ * 这类直接覆盖;非法值忽略、回退默认。
371
+ * @param {unknown} options - 调用选项。
372
+ * @returns {typeof DEFAULT_KG_LIMITS} 完整上限对象。
373
+ */
374
+ function resolveLimits(options) {
375
+ const source = isRecord(options) ? options : {}
376
+ const nested = isRecord(source.limits) ? source.limits : {}
377
+ const limits = { ...DEFAULT_KG_LIMITS }
378
+ for (const target of [nested, source]) {
379
+ for (const key of Object.keys(DEFAULT_KG_LIMITS)) {
380
+ const value = target[key]
381
+ if (Number.isFinite(value) && value >= 0) limits[key] = Math.trunc(value)
382
+ }
383
+ }
384
+ return limits
385
+ }
386
+
387
+ /* -------------------------------------------------------------------------- */
388
+ /* 标量归一化 */
389
+ /* -------------------------------------------------------------------------- */
390
+
391
+ /** 非负整数(可选 null);非法返回 fallback。 */
392
+ function normalizeNonNegativeInt(value, fallback = null) {
393
+ let number = null
394
+ if (typeof value === 'number' && Number.isFinite(value)) number = value
395
+ else if (typeof value === 'string' && value.trim() !== '') {
396
+ const parsed = Number(value.trim())
397
+ if (Number.isFinite(parsed)) number = parsed
398
+ }
399
+ if (number === null) return fallback
400
+ return Math.min(MAX_COUNTER, Math.max(0, Math.trunc(number)))
401
+ }
402
+
403
+ /** 是否为合法的非负数字/数字字符串(helper 的“非法值忽略”语义用)。 */
404
+ function isNonNegativeNumeric(value) {
405
+ if (typeof value === 'number') return Number.isFinite(value) && value >= 0
406
+ if (typeof value === 'string' && value.trim() !== '') {
407
+ const numeric = Number(value.trim())
408
+ return Number.isFinite(numeric) && numeric >= 0
409
+ }
410
+ return false
411
+ }
412
+
413
+ /** 时间戳归一化:毫秒数字 / 秒级数字(10 位自动 ×1000)/ ISO 字符串 → 毫秒;非法回退。 */
414
+ function normalizeTimestamp(value, fallback) {
415
+ if (typeof value === 'number' && Number.isFinite(value) && value >= 0) {
416
+ return Math.round(value < 1e12 ? value * 1000 : value)
417
+ }
418
+ if (typeof value === 'string' && value.trim() !== '') {
419
+ const text = value.trim()
420
+ const parsed = Date.parse(text)
421
+ if (Number.isFinite(parsed)) return parsed
422
+ const numeric = Number(text)
423
+ if (Number.isFinite(numeric) && numeric >= 0) {
424
+ return Math.round(numeric < 1e12 ? numeric * 1000 : numeric)
425
+ }
426
+ }
427
+ return fallback
428
+ }
429
+
430
+ /**
431
+ * 置信度归一化:落盘格式是 'high' | 'medium' | 'low'(与 extract/graph 一致)。
432
+ * 数值输入(0..1)按 ≥0.75 high / ≥0.4 medium / 其余 low 映射;非法/缺失 → 'medium'。
433
+ * @param {unknown} value - 原始值。
434
+ * @returns {'high'|'medium'|'low'} 置信度标签。
435
+ */
436
+ function normalizeConfidence(value) {
437
+ if (typeof value === 'number' && Number.isFinite(value)) return confidenceLabelOfNumber(value)
438
+ if (typeof value === 'string' && value.trim() !== '') {
439
+ const text = value.trim().toLowerCase()
440
+ if (CONFIDENCE_LABEL_SET.has(text)) return text
441
+ const numeric = Number(text)
442
+ if (Number.isFinite(numeric)) return confidenceLabelOfNumber(numeric)
443
+ }
444
+ return 'medium'
445
+ }
446
+
447
+ /** 0..1 数值 → 置信度标签。 */
448
+ function confidenceLabelOfNumber(value) {
449
+ const number = Math.min(1, Math.max(0, value))
450
+ if (number >= 0.75) return 'high'
451
+ if (number >= 0.4) return 'medium'
452
+ return 'low'
453
+ }
454
+
455
+ /** 置信度 → 数值(淘汰排序用:high=1 / medium=0.6 / low=0.3)。 */
456
+ function confidenceRank(value) {
457
+ return CONFIDENCE_BY_LABEL[normalizeConfidence(value)]
458
+ }
459
+
460
+ /** importance 归一化(可选):0..1 数值或 high/medium/low;缺失/非法 → null。 */
461
+ function normalizeImportance(value) {
462
+ if (typeof value === 'number' && Number.isFinite(value)) return Math.min(1, Math.max(0, value))
463
+ if (typeof value === 'string' && value.trim() !== '') {
464
+ const text = value.trim().toLowerCase()
465
+ if (Object.hasOwn(CONFIDENCE_BY_LABEL, text)) return CONFIDENCE_BY_LABEL[text]
466
+ const numeric = Number(text)
467
+ if (Number.isFinite(numeric)) return Math.min(1, Math.max(0, numeric))
468
+ }
469
+ return null
470
+ }
471
+
472
+ /** 事实种类归一化:大小写不敏感;不在词表内返回空串(调用方丢弃该事实)。 */
473
+ function normalizeFactKind(value) {
474
+ const text = cleanText(value, 40).toLowerCase()
475
+ return KG_FACT_KINDS.includes(text) ? text : ''
476
+ }
477
+
478
+ /** 事实状态归一化:合法枚举原样;缺失/非法回退 active。 */
479
+ function normalizeFactStatus(value) {
480
+ const text = cleanText(value, 40).toLowerCase()
481
+ return KG_FACT_STATUSES.includes(text) ? text : 'active'
482
+ }
483
+
484
+ /**
485
+ * seqs 归一化:数组 / 逗号分隔字符串 → 去重升序的非负整数数组。
486
+ * @param {unknown} value - 原始值。
487
+ * @param {number} [maxItems] - 条数上限。
488
+ * @returns {number[]} 归一化后的序号数组。
489
+ */
490
+ function normalizeSeqList(value, maxItems = MAX_FACT_ID_REFS) {
491
+ const list = Array.isArray(value)
492
+ ? value
493
+ : (typeof value === 'string' ? value.split(/[,,、;;\s]+/u) : [])
494
+ const out = []
495
+ for (const item of list) {
496
+ // 负数/非数字是脏数据,直接丢弃(normalizeNonNegativeInt 会把 -1 clamp 成 0)。
497
+ if (typeof item === 'number' && (!Number.isFinite(item) || item < 0)) continue
498
+ if (typeof item === 'string') {
499
+ const text = item.trim()
500
+ if (text === '') continue
501
+ const numeric = Number(text)
502
+ if (!Number.isFinite(numeric) || numeric < 0) continue
503
+ }
504
+ const number = normalizeNonNegativeInt(item)
505
+ if (number === null || out.includes(number)) continue
506
+ out.push(number)
507
+ if (out.length >= maxItems) break
508
+ }
509
+ return out.sort((left, right) => left - right)
510
+ }
511
+
512
+ /** 项目内相对层级路径归一化:数组或 `/` 分隔字符串;段数/单段长度受限。 */
513
+ function normalizeScopePath(value, limits) {
514
+ let segments = []
515
+ if (Array.isArray(value)) segments = value
516
+ else if (typeof value === 'string' && value.trim() !== '') segments = value.split(/[\\/>]+/u)
517
+ const out = []
518
+ for (const segment of segments) {
519
+ const text = cleanText(segment, 120)
520
+ if (text === '') continue
521
+ out.push(text)
522
+ if (out.length >= limits.maxScopeSegments) break
523
+ }
524
+ return out
525
+ }
526
+
527
+ /** 实体列表归一化:数组或分隔字符串;去重(大小写不敏感、保留首次写法)且 ≤8。 */
528
+ function normalizeEntities(value, limits) {
529
+ const list = Array.isArray(value)
530
+ ? value
531
+ : (typeof value === 'string' && value.trim() !== ''
532
+ ? value.split(/[,,、;;\n]+/u)
533
+ : [])
534
+ const out = []
535
+ const seen = new Set()
536
+ for (const item of list) {
537
+ const text = cleanText(item, 80)
538
+ if (text === '') continue
539
+ const key = text.toLowerCase()
540
+ if (seen.has(key)) continue
541
+ seen.add(key)
542
+ out.push(text)
543
+ if (out.length >= limits.maxEntities) break
544
+ }
545
+ return out
546
+ }
547
+
548
+ /** 轮次索引的 key 归一化:数字 turn 或字符串 key;非法返回空串。 */
549
+ function normalizeTurnKey(turn) {
550
+ if (typeof turn === 'number' && Number.isFinite(turn)) return String(Math.max(0, Math.trunc(turn)))
551
+ const key = cleanText(turn, 200)
552
+ return isSafeRecordKey(key) ? key : ''
553
+ }
554
+
555
+ /** label 归一化(空/非法回退)。 */
556
+ function normalizeLabel(value, fallback = 'project') {
557
+ const text = cleanText(value, 120)
558
+ return text === '' ? fallback : text
559
+ }
560
+
561
+ /** 更新 updatedAt(严格递增,避免同毫秒连续写时时间戳不变)。 */
562
+ function stampUpdatedAt(state) {
563
+ if (!isRecord(state)) return state
564
+ const previous = Number.isFinite(state.updatedAt) ? state.updatedAt : 0
565
+ state.updatedAt = Math.max(Date.now(), previous + 1)
566
+ return state
567
+ }
568
+
569
+ /* -------------------------------------------------------------------------- */
570
+ /* 空状态 */
571
+ /* -------------------------------------------------------------------------- */
572
+
573
+ /** 新建 stats 段。 */
574
+ function emptyKgStats() {
575
+ return { extractions: 0, failures: 0, accesses: 0, lastHitAt: null }
576
+ }
577
+
578
+ /** 新建 archive 段(替换/影子化轮次的状态机)。 */
579
+ function emptyKgArchive() {
580
+ return {
581
+ archivedThroughTurn: null,
582
+ replacementSeq: null,
583
+ shadowedSeqs: [],
584
+ tokensSaved: 0,
585
+ at: null,
586
+ paused: false,
587
+ lastError: null,
588
+ }
589
+ }
590
+
591
+ /**
592
+ * 新建一份空的项目图状态。
593
+ * @param {unknown} key - 项目 key(会做安全清洗)。
594
+ * @param {unknown} [label] - 项目展示名。
595
+ * @returns {object} 空状态(version=1,revision=0)。
596
+ */
597
+ export function emptyKgState(key, label) {
598
+ const now = Date.now()
599
+ return {
600
+ version: KG_VERSION,
601
+ key: sanitizeKgKey(key),
602
+ label: normalizeLabel(label, 'project'),
603
+ revision: 0,
604
+ createdAt: now,
605
+ updatedAt: now,
606
+ facts: {},
607
+ turns: {},
608
+ stats: emptyKgStats(),
609
+ archive: emptyKgArchive(),
610
+ }
611
+ }
612
+
613
+ /* -------------------------------------------------------------------------- */
614
+ /* 单事实归一化 */
615
+ /* -------------------------------------------------------------------------- */
616
+
617
+ /**
618
+ * 归一化一条事实(FACT 白名单校验,与 lib/graph.js 的 Fact 契约对齐)。
619
+ *
620
+ * 保留字段:id / statement / kind / scopePath / entities / confidence / source /
621
+ * status / projectId / validFrom / validUntil / supersededBy / conflictsWith /
622
+ * createdAt / updatedAt / lastUsedAt / hitCount / aliases / sources,
623
+ * 以及存储层可选的 pinned / importance(0..1,淘汰排序用);其它字段全部丢弃。
624
+ *
625
+ * 必填:id(可用记录 key 兜底)、statement、kind。缺失或 kind 非法 → 返回 null。
626
+ * confidence 落盘为 'high' | 'medium' | 'low'(数值输入映射到标签)。
627
+ * 可空字段(validUntil/lastUsedAt)保留 null;引用字段统一为 string[]。
628
+ *
629
+ * @param {unknown} raw - 原始事实(来自 extract / graph / 旧文件)。
630
+ * @param {object} [options] - `{ limits?, now?, id? }`。
631
+ * @returns {object|null} 归一化事实;非法返回 null。
632
+ */
633
+ export function normalizeKgFact(raw, options = {}) {
634
+ const limits = resolveLimits(options)
635
+ const now = Number.isFinite(options.now) ? Math.round(options.now) : Date.now()
636
+ if (!isRecord(raw)) return null
637
+ const id = cleanText(raw.id ?? raw.factId ?? options.id, 200)
638
+ if (!isSafeRecordKey(id)) return null
639
+ const statement = cleanText(raw.statement ?? raw.text ?? raw.fact, limits.maxStatementChars)
640
+ if (statement === '') return null
641
+ const kind = normalizeFactKind(raw.kind)
642
+ if (kind === '') return null
643
+ const scopePath = normalizeScopePath(raw.scopePath ?? raw.scope ?? raw.path, limits)
644
+ const entities = normalizeEntities(raw.entities ?? raw.entity, limits)
645
+ const source = normalizeFactSource(raw.source, now)
646
+ const createdAt = normalizeTimestamp(raw.createdAt, now)
647
+ const updatedAt = Math.max(createdAt, normalizeTimestamp(raw.updatedAt, createdAt))
648
+
649
+ const fact = {
650
+ id,
651
+ statement,
652
+ kind,
653
+ scopePath,
654
+ entities,
655
+ confidence: normalizeConfidence(raw.confidence),
656
+ source,
657
+ status: normalizeFactStatus(raw.status),
658
+ validFrom: normalizeTimestamp(raw.validFrom, createdAt),
659
+ createdAt,
660
+ updatedAt,
661
+ hitCount: normalizeNonNegativeInt(raw.hitCount ?? raw.hits, 0) ?? 0,
662
+ }
663
+ const projectId = cleanText(raw.projectId ?? raw.project, 200)
664
+ if (projectId !== '') fact.projectId = projectId
665
+ // 可空时间字段:字段存在时保留 null 语义(graph 快照固定包含这两项)。
666
+ if (raw.validUntil !== undefined) fact.validUntil = normalizeTimestamp(raw.validUntil, null)
667
+ if (raw.lastUsedAt !== undefined) fact.lastUsedAt = normalizeTimestamp(raw.lastUsedAt, null)
668
+ // 关系字段:extract 可能给单个字符串,graph 统一为 string[]。
669
+ if (raw.supersededBy !== undefined) fact.supersededBy = normalizeIdRefs(raw.supersededBy, id)
670
+ if (raw.conflictsWith !== undefined) fact.conflictsWith = normalizeIdRefs(raw.conflictsWith, id)
671
+ if (raw.aliases !== undefined) fact.aliases = normalizeAliases(raw.aliases, statement)
672
+ if (raw.sources !== undefined) fact.sources = normalizeSourceList(raw.sources, now)
673
+ if (raw.pinned === true) fact.pinned = true
674
+ const importance = normalizeImportance(raw.importance)
675
+ if (importance !== null) fact.importance = importance
676
+ return fact
677
+ }
678
+
679
+ /**
680
+ * 归一化事实 id 引用列表(supersededBy / conflictsWith):字符串或数组 →
681
+ * 去重、去自引用、截断的 string[]。
682
+ * @param {unknown} value - 原始值。
683
+ * @param {string} selfId - 自身 id(过滤自引用)。
684
+ * @returns {string[]} 归一化引用列表。
685
+ */
686
+ function normalizeIdRefs(value, selfId) {
687
+ const list = Array.isArray(value)
688
+ ? value
689
+ : (typeof value === 'string' && value.trim() !== '' ? [value] : [])
690
+ const out = []
691
+ for (const item of list) {
692
+ const id = cleanText(typeof item === 'string' ? item : (isRecord(item) ? item.id : ''), 200)
693
+ if (id === '' || id === selfId || out.includes(id)) continue
694
+ out.push(id)
695
+ if (out.length >= MAX_FACT_REFS) break
696
+ }
697
+ return out
698
+ }
699
+
700
+ /** 归一化事实别名列表:字符串/数组 → 去重、去掉与 statement 相同的项。 */
701
+ function normalizeAliases(value, statement) {
702
+ const list = Array.isArray(value)
703
+ ? value
704
+ : (typeof value === 'string' && value.trim() !== '' ? value.split(/[,,、;;\n]+/u) : [])
705
+ const out = []
706
+ const seen = new Set([statement])
707
+ for (const item of list) {
708
+ const text = cleanText(item, 120)
709
+ if (text === '' || seen.has(text)) continue
710
+ seen.add(text)
711
+ out.push(text)
712
+ if (out.length >= MAX_FACT_ALIASES) break
713
+ }
714
+ return out
715
+ }
716
+
717
+ /** 归一化事实多来源列表(graph 的 sources[],主来源在最前)。 */
718
+ function normalizeSourceList(value, now) {
719
+ if (!Array.isArray(value)) return []
720
+ const out = []
721
+ for (const item of value) {
722
+ if (!isRecord(item)) continue
723
+ out.push(normalizeFactSource(item, now))
724
+ if (out.length >= MAX_FACT_SOURCES) break
725
+ }
726
+ return out
727
+ }
728
+
729
+ /**
730
+ * 归一化事实来源(source 白名单):cardId/turn/at 必有(可空),血缘扩展可选。
731
+ * @param {unknown} raw - 原始 source。
732
+ * @param {number} now - 抽取时间兜底。
733
+ * @returns {{ cardId: string, turn: number|null, at: number, lineageKey?: string, seqs?: number[], projectId?: string, sessionId?: string }} 归一化来源。
734
+ */
735
+ function normalizeFactSource(raw, now) {
736
+ const source = isRecord(raw) ? raw : {}
737
+ const out = {
738
+ cardId: cleanText(source.cardId ?? source.cardid ?? source.sourceCardId ?? source.card, 200),
739
+ turn: normalizeNonNegativeInt(source.turn ?? source.turnIndex),
740
+ at: normalizeTimestamp(source.at, now),
741
+ }
742
+ const lineageKey = cleanText(source.lineageKey ?? source.lineage, 200)
743
+ if (lineageKey !== '') out.lineageKey = lineageKey
744
+ const seqs = normalizeSeqList(source.seqs)
745
+ if (seqs.length > 0) out.seqs = seqs
746
+ const projectId = cleanText(source.projectId ?? source.project, 200)
747
+ if (projectId !== '') out.projectId = projectId
748
+ const sessionId = cleanText(source.sessionId ?? source.session, 200)
749
+ if (sessionId !== '') out.sessionId = sessionId
750
+ return out
751
+ }
752
+
753
+ /* -------------------------------------------------------------------------- */
754
+ /* 事实淘汰评分 */
755
+ /* -------------------------------------------------------------------------- */
756
+
757
+ /** 是否为受保护事实(pinned 或 confidence/importance 达到 high 档)。 */
758
+ function isProtectedFact(fact) {
759
+ if (!isRecord(fact)) return false
760
+ if (fact.pinned === true) return true
761
+ if (fact.confidence === 'high') return true
762
+ if (confidenceRank(fact.confidence) >= HIGH_VALUE_THRESHOLD) return true
763
+ const importance = normalizeImportance(fact.importance)
764
+ return importance !== null && importance >= HIGH_VALUE_THRESHOLD
765
+ }
766
+
767
+ /**
768
+ * 事实价值分:importance(×2) + confidence + hitCount 饱和度(×0.5) + 状态修正。
769
+ * 分数越低越先被淘汰;只用于上限淘汰的排序,不参与展示。
770
+ */
771
+ function factValueScore(fact) {
772
+ if (!isRecord(fact)) return Number.NEGATIVE_INFINITY
773
+ const importance = normalizeImportance(fact.importance) ?? 0.5
774
+ const confidence = confidenceRank(fact.confidence)
775
+ const hitCount = Number.isFinite(fact.hitCount) ? Math.max(0, fact.hitCount) : 0
776
+ const hits = Math.min(hitCount, 20) / 20
777
+ const status = STATUS_VALUE[fact.status] ?? 0
778
+ return importance * 2 + confidence + hits * 0.5 + status
779
+ }
780
+
781
+ /** 淘汰排序:价值低者在前;同分时 updatedAt 更旧者先;再按 id 保证确定性。 */
782
+ function compareEvictionFacts(left, right) {
783
+ const diff = factValueScore(left) - factValueScore(right)
784
+ if (diff !== 0) return diff
785
+ const leftAt = Number.isFinite(left?.updatedAt) ? left.updatedAt : 0
786
+ const rightAt = Number.isFinite(right?.updatedAt) ? right.updatedAt : 0
787
+ if (leftAt !== rightAt) return leftAt - rightAt
788
+ const leftId = String(left?.id ?? '')
789
+ const rightId = String(right?.id ?? '')
790
+ if (leftId === rightId) return 0
791
+ return leftId < rightId ? -1 : 1
792
+ }
793
+
794
+ /**
795
+ * 事实记录按上限淘汰。
796
+ *
797
+ * 第一轮只淘汰“非 pinned、非 high”的低价值事实;若受保护事实本身已超过上限,
798
+ * `hard=true` 时再按价值保留最好的 `maxFacts` 条(防御性硬上限),`hard=false`
799
+ * 时保留全部受保护事实(prune 语义:绝不丢弃 pinned/high)。
800
+ *
801
+ * @param {Record<string, object>} facts - 事实记录(原地删除)。
802
+ * @param {number} maxFacts - 上限。
803
+ * @param {{ hard?: boolean }} [options] - hard 模式。
804
+ * @returns {{ evicted: string[] }} 被淘汰的 fact id(按淘汰顺序)。
805
+ */
806
+ function capFactRecord(facts, maxFacts, options = {}) {
807
+ const ids = Object.keys(facts)
808
+ const evicted = []
809
+ if (ids.length <= maxFacts) return { evicted }
810
+ const evictable = ids
811
+ .filter(id => !isProtectedFact(facts[id]))
812
+ .sort((left, right) => compareEvictionFacts(facts[left], facts[right]))
813
+ let count = ids.length
814
+ for (const id of evictable) {
815
+ if (count <= maxFacts) break
816
+ delete facts[id]
817
+ evicted.push(id)
818
+ count -= 1
819
+ }
820
+ if (count > maxFacts && options.hard === true) {
821
+ // 极端情况(受保护事实超过上限):按价值从高到低保留,其余硬淘汰。
822
+ // 注意 maxFacts=0 时 slice(-0) 会保留全部,必须单独处理。
823
+ const keep = maxFacts <= 0
824
+ ? []
825
+ : Object.keys(facts)
826
+ .sort((left, right) => compareEvictionFacts(facts[left], facts[right]))
827
+ .slice(-maxFacts)
828
+ const keepSet = new Set(keep)
829
+ for (const id of Object.keys(facts)) {
830
+ if (keepSet.has(id)) continue
831
+ delete facts[id]
832
+ evicted.push(id)
833
+ }
834
+ }
835
+ return { evicted }
836
+ }
837
+
838
+ /* -------------------------------------------------------------------------- */
839
+ /* 边 / scope / turns 归一化 */
840
+ /* -------------------------------------------------------------------------- */
841
+
842
+ /**
843
+ * 归一化单条轮次索引记录。
844
+ * @param {unknown} raw - 原始记录。
845
+ * @param {{ now?: number }} [options] - 时间兜底。
846
+ * @returns {{ status: string, hash: string, factIds: string[], at: number, model?: string, error?: string }|null} 归一化记录。
847
+ */
848
+ export function normalizeKgTurnRecord(raw, options = {}) {
849
+ const now = Number.isFinite(options.now) ? Math.round(options.now) : Date.now()
850
+ if (!isRecord(raw)) return null
851
+ const statusText = cleanText(raw.status, 40).toLowerCase()
852
+ const status = KG_TURN_STATUSES.includes(statusText) ? statusText : 'pending'
853
+ const hash = cleanText(raw.hash ?? raw.digest, 200)
854
+ const factIds = []
855
+ const seen = new Set()
856
+ const sourceList = Array.isArray(raw.factIds)
857
+ ? raw.factIds
858
+ : (Array.isArray(raw.facts) ? raw.facts : [])
859
+ for (const item of sourceList) {
860
+ const id = cleanText(typeof item === 'string' ? item : (isRecord(item) ? item.id : ''), 200)
861
+ if (id === '' || seen.has(id)) continue
862
+ seen.add(id)
863
+ factIds.push(id)
864
+ if (factIds.length >= MAX_FACT_ID_REFS) break
865
+ }
866
+ const record = { status, hash, factIds, at: normalizeTimestamp(raw.at, now) }
867
+ const model = cleanText(raw.model, 200)
868
+ if (model !== '') record.model = model
869
+ const error = cleanText(raw.error, 300)
870
+ if (error !== '') record.error = error
871
+ return record
872
+ }
873
+
874
+ /** 轮次索引归一化:坏记录丢弃;超过 maxTurns 时保留最近抽取的记录。 */
875
+ function normalizeTurns(raw, limits, now) {
876
+ const turns = {}
877
+ if (!isRecord(raw)) return turns
878
+ const entries = []
879
+ for (const [rawKey, rawValue] of Object.entries(raw)) {
880
+ const key = normalizeTurnKey(rawKey)
881
+ if (key === '') continue
882
+ const record = normalizeKgTurnRecord(rawValue, { now })
883
+ if (record === null) continue
884
+ entries.push([key, record])
885
+ }
886
+ if (entries.length > limits.maxTurns) {
887
+ entries.sort((left, right) => {
888
+ if (right[1].at !== left[1].at) return right[1].at - left[1].at
889
+ return left[0] < right[0] ? -1 : (left[0] > right[0] ? 1 : 0)
890
+ })
891
+ entries.length = limits.maxTurns
892
+ }
893
+ for (const [key, record] of entries) turns[key] = record
894
+ return turns
895
+ }
896
+
897
+ /* -------------------------------------------------------------------------- */
898
+ /* stats / archive 归一化 */
899
+ /* -------------------------------------------------------------------------- */
900
+
901
+ /** stats 段归一化(计数器非负、lastHitAt 可空)。 */
902
+ function normalizeKgStats(raw) {
903
+ const record = isRecord(raw) ? raw : {}
904
+ const stats = emptyKgStats()
905
+ stats.extractions = normalizeNonNegativeInt(record.extractions, 0) ?? 0
906
+ stats.failures = normalizeNonNegativeInt(record.failures, 0) ?? 0
907
+ stats.accesses = normalizeNonNegativeInt(record.accesses, 0) ?? 0
908
+ stats.lastHitAt = record.lastHitAt === undefined || record.lastHitAt === null
909
+ ? null
910
+ : normalizeTimestamp(record.lastHitAt, null)
911
+ return stats
912
+ }
913
+
914
+ /** archive 段归一化(替换/影子化状态机;未知字段丢弃)。 */
915
+ function normalizeKgArchive(raw, limits) {
916
+ const record = isRecord(raw) ? raw : {}
917
+ const archive = emptyKgArchive()
918
+ archive.archivedThroughTurn = record.archivedThroughTurn === undefined || record.archivedThroughTurn === null
919
+ ? null
920
+ : normalizeNonNegativeInt(record.archivedThroughTurn)
921
+ archive.replacementSeq = record.replacementSeq === undefined || record.replacementSeq === null
922
+ ? null
923
+ : normalizeNonNegativeInt(record.replacementSeq)
924
+ archive.shadowedSeqs = normalizeSeqList(record.shadowedSeqs, limits.maxShadowedSeqs)
925
+ archive.tokensSaved = normalizeNonNegativeInt(record.tokensSaved, 0) ?? 0
926
+ archive.at = record.at === undefined || record.at === null ? null : normalizeTimestamp(record.at, null)
927
+ archive.paused = record.paused === true
928
+ archive.lastError = cleanText(record.lastError, 300) || null
929
+ return archive
930
+ }
931
+
932
+ /* -------------------------------------------------------------------------- */
933
+ /* 引用一致性 */
934
+ /* -------------------------------------------------------------------------- */
935
+
936
+ /**
937
+ * 事实被淘汰后同步清理引用:从 turns.factIds 里移除已淘汰的 fact id。
938
+ * @param {{ turns?: unknown }} state - 状态(原地修改)。
939
+ * @param {Set<string>} removedIds - 已淘汰事实 id。
940
+ */
941
+ function reconcileFactReferences(state, removedIds) {
942
+ if (!isRecord(state) || !(removedIds instanceof Set) || removedIds.size === 0) return
943
+ if (isRecord(state.turns)) {
944
+ for (const record of Object.values(state.turns)) {
945
+ if (isRecord(record) && Array.isArray(record.factIds)) {
946
+ record.factIds = record.factIds.filter(id => !removedIds.has(id))
947
+ }
948
+ }
949
+ }
950
+ }
951
+
952
+ /* -------------------------------------------------------------------------- */
953
+ /* 状态归一化 */
954
+ /* -------------------------------------------------------------------------- */
955
+
956
+ /**
957
+ * 归一化一份项目图状态(读文件 / 保存前共用)。
958
+ *
959
+ * 规则:
960
+ * - `raw` 不是普通对象、`version` 不是 1、`key` 与调用方 key 不一致 → 空状态;
961
+ * - facts 逐条白名单校验(非法事实丢弃),总数超限按“低价值优先”淘汰并清理引用;
962
+ * - turns/stats/archive 补默认、限长、上限;未知字段不保留(旧数据的 edges/scopes 被忽略)。
963
+ *
964
+ * 注意:本函数**不抛错**;调用方负责隔离磁盘上的坏文件(见 `loadKgState`)。
965
+ *
966
+ * @param {unknown} key - 项目 key。
967
+ * @param {unknown} raw - 原始状态。
968
+ * @param {unknown} [label] - 项目展示名(raw.label 非法时兜底)。
969
+ * @param {object} [options] - `{ limits?, maxFacts? }`。
970
+ * @returns {object} 归一化状态。
971
+ */
972
+ export function normalizeKgState(key, raw, label, options = {}) {
973
+ const limits = resolveLimits(options)
974
+ const safeKey = sanitizeKgKey(key)
975
+ const fallback = emptyKgState(safeKey, label)
976
+ if (!isRecord(raw)) return fallback
977
+ if (raw.version !== KG_VERSION) return fallback
978
+ if (raw.key !== undefined
979
+ && (typeof raw.key !== 'string' || sanitizeKgKey(raw.key) !== safeKey)) {
980
+ return fallback
981
+ }
982
+ const now = Date.now()
983
+ const createdAt = normalizeTimestamp(raw.createdAt, now)
984
+ const updatedAt = Math.max(createdAt, normalizeTimestamp(raw.updatedAt, createdAt))
985
+
986
+ // facts:逐条校验 + 上限淘汰。
987
+ // 兼容 graph serialize 快照的 `facts: Fact[]` 形态(Record 是 canonical 落盘形态)。
988
+ const rawFacts = Array.isArray(raw.facts)
989
+ ? raw.facts.map(item => [isRecord(item) ? item.id : undefined, item])
990
+ : (isRecord(raw.facts) ? Object.entries(raw.facts) : [])
991
+ const facts = {}
992
+ for (const [rawId, rawFact] of rawFacts) {
993
+ const fact = normalizeKgFact(rawFact, { limits, now, id: cleanText(rawId, 200) })
994
+ if (fact === null) continue
995
+ if (!Object.hasOwn(facts, fact.id)) facts[fact.id] = fact
996
+ }
997
+ const { evicted } = capFactRecord(facts, limits.maxFacts, { hard: true })
998
+ const evictedIds = new Set(evicted)
999
+
1000
+ const state = {
1001
+ version: KG_VERSION,
1002
+ key: safeKey,
1003
+ label: normalizeLabel(raw.label, normalizeLabel(label, 'project')),
1004
+ revision: normalizeNonNegativeInt(raw.revision, 0) ?? 0,
1005
+ createdAt,
1006
+ updatedAt,
1007
+ facts,
1008
+ turns: normalizeTurns(raw.turns, limits, now),
1009
+ stats: normalizeKgStats(raw.stats),
1010
+ archive: normalizeKgArchive(raw.archive, limits),
1011
+ }
1012
+ if (evictedIds.size > 0) reconcileFactReferences(state, evictedIds)
1013
+ return state
1014
+ }
1015
+
1016
+ /* -------------------------------------------------------------------------- */
1017
+ /* 读写 */
1018
+ /* -------------------------------------------------------------------------- */
1019
+
1020
+ const CROSS_DEVICE_CODES = new Set(['EXDEV', 'ENOTSUP'])
1021
+
1022
+ /** rename 失败是否属于“跨设备/不支持”的兜底场景。 */
1023
+ function isCrossDeviceError(error) {
1024
+ const code = isRecord(error) || error instanceof Error ? error.code : undefined
1025
+ return typeof code === 'string' && CROSS_DEVICE_CODES.has(code)
1026
+ }
1027
+
1028
+ /** 尽量 fsync 临时文件(失败不阻塞:rename 后即使掉电也只会丢派生缓存)。 */
1029
+ function syncFile(file) {
1030
+ try {
1031
+ const fd = openSync(file, 'r+')
1032
+ try {
1033
+ fsyncSync(fd)
1034
+ } finally {
1035
+ closeSync(fd)
1036
+ }
1037
+ } catch {
1038
+ /* fsync 失败不影响正确性 */
1039
+ }
1040
+ }
1041
+
1042
+ /** 读取并解析 JSON 文件(不抛错;区分“文件不存在”和“读取/解析失败”)。 */
1043
+ function readKgRawFile(file) {
1044
+ try {
1045
+ if (!existsSync(file)) return { ok: false, missing: true, raw: null, error: null }
1046
+ return { ok: true, missing: false, raw: JSON.parse(readFileSync(file, 'utf8')), error: null }
1047
+ } catch (error) {
1048
+ return { ok: false, missing: false, raw: null, error }
1049
+ }
1050
+ }
1051
+
1052
+ /** 判断磁盘上的原始状态是否可用(版本/项目 key 都对得上)。 */
1053
+ function isUsableKgRaw(raw, safeKey) {
1054
+ return isRecord(raw)
1055
+ && raw.version === KG_VERSION
1056
+ && typeof raw.key === 'string'
1057
+ && sanitizeKgKey(raw.key) === safeKey
1058
+ }
1059
+
1060
+ /** 把损坏文件改名隔离(唯一路径;失败返回 null,不抛错)。 */
1061
+ function quarantineArtifact(file) {
1062
+ const stamp = Date.now()
1063
+ let target = `${file}.corrupt-${stamp}`
1064
+ let suffix = 1
1065
+ while (existsSync(target)) {
1066
+ target = `${file}.corrupt-${stamp}-${suffix}`
1067
+ suffix += 1
1068
+ }
1069
+ try {
1070
+ renameSync(file, target)
1071
+ return target
1072
+ } catch {
1073
+ return null
1074
+ }
1075
+ }
1076
+
1077
+ /**
1078
+ * 读取项目图状态,坏文件自动降级。
1079
+ *
1080
+ * 顺序:主文件 → `.bak` → 空状态。主文件坏 JSON / 版本不符 / key 不一致时先把
1081
+ * 它改名为 `.corrupt-<ts>` 隔离;备份可用则 `recovered=true` 并写回主文件;
1082
+ * 主备都坏则返回空状态(主备都隔离),绝不抛错。
1083
+ *
1084
+ * @param {unknown} key - 项目 key。
1085
+ * @param {unknown} [label] - 项目展示名(文件内 label 非法时兜底)。
1086
+ * @param {object} [options] - `{ limits?, maxFacts? }`。
1087
+ * @returns {{ state: object, recovered: boolean, warning: string|null, quarantined: string[] }} 读取结果。
1088
+ */
1089
+ export function loadKgState(key, label, options = {}) {
1090
+ const limits = resolveLimits(options)
1091
+ const safeKey = sanitizeKgKey(key)
1092
+ const fallbackLabel = normalizeLabel(label, 'project')
1093
+ const file = kgFile(safeKey)
1094
+ const backup = kgBackupFile(safeKey)
1095
+ const quarantined = []
1096
+
1097
+ const primary = readKgRawFile(file)
1098
+ let primaryProblem = null
1099
+ if (primary.ok && isUsableKgRaw(primary.raw, safeKey)) {
1100
+ return {
1101
+ state: normalizeKgState(safeKey, primary.raw, fallbackLabel, { limits }),
1102
+ recovered: false,
1103
+ warning: null,
1104
+ quarantined,
1105
+ }
1106
+ }
1107
+ if (primary.ok) primaryProblem = '主图文件版本不符或结构非法'
1108
+ else if (!primary.missing) primaryProblem = `主图文件读取失败:${describeError(primary.error)}`
1109
+ if (primaryProblem !== null) {
1110
+ const isolated = quarantineArtifact(file)
1111
+ if (isolated !== null) quarantined.push(isolated)
1112
+ }
1113
+
1114
+ const saved = readKgRawFile(backup)
1115
+ if (saved.ok && isUsableKgRaw(saved.raw, safeKey)) {
1116
+ const recoveredState = normalizeKgState(safeKey, saved.raw, fallbackLabel, { limits })
1117
+ let warning = primaryProblem === null
1118
+ ? '主图文件缺失,已从备份恢复'
1119
+ : '主图文件损坏,已从备份恢复'
1120
+ let state = recoveredState
1121
+ try {
1122
+ state = saveKgState(safeKey, recoveredState, { limits })
1123
+ } catch (error) {
1124
+ warning = `${warning}(写回主文件失败:${describeError(error)})`
1125
+ }
1126
+ return { state, recovered: true, warning, quarantined }
1127
+ }
1128
+ if (!saved.missing) {
1129
+ const isolated = quarantineArtifact(backup)
1130
+ if (isolated !== null) quarantined.push(isolated)
1131
+ }
1132
+
1133
+ let warning = null
1134
+ if (primaryProblem !== null) {
1135
+ warning = saved.missing
1136
+ ? `${primaryProblem},且无可用备份,已重置项目图(图谱会重新抽取,会话日志不受影响)`
1137
+ : `${primaryProblem},备份也不可用,已重置项目图(图谱会重新抽取,会话日志不受影响)`
1138
+ }
1139
+ return {
1140
+ state: emptyKgState(safeKey, fallbackLabel),
1141
+ recovered: false,
1142
+ warning,
1143
+ quarantined,
1144
+ }
1145
+ }
1146
+
1147
+ /**
1148
+ * 原子保存项目图状态。
1149
+ *
1150
+ * 流程:normalize → 写 `<file>.tmp-<pid>-<rand>` → fsync → 复制旧主文件到 `.bak`
1151
+ * → rename 覆盖。失败时抛错并尽力清理临时文件,旧主文件保持不变。
1152
+ *
1153
+ * @param {unknown} key - 项目 key。
1154
+ * @param {unknown} state - 要保存的状态(保存前会 normalize;revision 自增)。
1155
+ * @param {{ limits?: object, maxFacts?: number, io?: object }} [options] - 上限;`io` 仅供测试注入故障。
1156
+ * @returns {object} 实际写入磁盘的状态(含自增后的 revision)。
1157
+ * @throws {TypeError} state 非对象 / state.key 与目标 key 不一致 / 版本不兼容。
1158
+ * @throws {Error} 写盘失败(此时旧主文件保持不变,临时文件会被清理)。
1159
+ */
1160
+ export function saveKgState(key, state, options = {}) {
1161
+ if (!isRecord(state)) throw new TypeError('saveKgState(key, state):state 必须是普通对象')
1162
+ const safeKey = sanitizeKgKey(key)
1163
+ // 防呆:拿错项目的状态/旧版本状态直接写入会静默清空主文件,这里显式拒绝。
1164
+ if (state.key !== undefined && sanitizeKgKey(state.key) !== safeKey) {
1165
+ throw new TypeError('saveKgState(key, state):state.key 与目标 key 不一致')
1166
+ }
1167
+ if (state.version !== undefined && state.version !== KG_VERSION) {
1168
+ throw new TypeError(`saveKgState(key, state):不支持的 state.version=${String(state.version)}`)
1169
+ }
1170
+ const limits = resolveLimits(options)
1171
+ const normalized = normalizeKgState(safeKey, state, state.label, { limits })
1172
+ normalized.revision = (normalizeNonNegativeInt(normalized.revision, 0) ?? 0) + 1
1173
+ normalized.updatedAt = Math.max(Date.now(), normalized.updatedAt + 1)
1174
+
1175
+ const io = isRecord(options) && isRecord(options.io) ? options.io : {}
1176
+ const writeImpl = typeof io.writeFileSync === 'function' ? io.writeFileSync : writeFileSync
1177
+ const renameImpl = typeof io.renameSync === 'function' ? io.renameSync : renameSync
1178
+ const copyImpl = typeof io.copyFileSync === 'function' ? io.copyFileSync : copyFileSync
1179
+
1180
+ const file = kgFile(safeKey)
1181
+ const backup = kgBackupFile(safeKey)
1182
+ const payload = `${JSON.stringify(normalized)}\n`
1183
+ mkdirSync(dirname(file), { recursive: true })
1184
+ const temp = `${file}.tmp-${process.pid}-${randomBytes(4).toString('hex')}`
1185
+ try {
1186
+ writeImpl(temp, payload, 'utf8')
1187
+ syncFile(temp)
1188
+ if (existsSync(file)) {
1189
+ try {
1190
+ copyImpl(file, backup)
1191
+ } catch {
1192
+ /* 备份失败不阻塞主写入(最坏情况是少一份恢复副本) */
1193
+ }
1194
+ }
1195
+ try {
1196
+ renameImpl(temp, file)
1197
+ } catch (error) {
1198
+ if (!isCrossDeviceError(error)) throw error
1199
+ // 跨设备兜底:copyFileSync 非原子,但保证内容完整(temp 与目标同目录时几乎不会走到)。
1200
+ copyImpl(temp, file)
1201
+ try {
1202
+ rmSync(temp, { force: true })
1203
+ } catch {
1204
+ /* 临时文件残留不影响本次写入结果 */
1205
+ }
1206
+ }
1207
+ } catch (error) {
1208
+ try {
1209
+ rmSync(temp, { force: true })
1210
+ } catch {
1211
+ /* 清理失败忽略 */
1212
+ }
1213
+ throw error
1214
+ }
1215
+ return normalized
1216
+ }
1217
+
1218
+ /* -------------------------------------------------------------------------- */
1219
+ /* 小 helper(供 lib/actions.js 使用) */
1220
+ /* -------------------------------------------------------------------------- */
1221
+
1222
+ /**
1223
+ * 累加 stats 计数器(原地修改并返回 state)。
1224
+ *
1225
+ * 语义:`extractions`/`failures`/`accesses` 是**增量**(传 1 表示 +1);
1226
+ * `lastHitAt` 是**绝对值**(传时间戳,传 null 清空)。
1227
+ *
1228
+ * @param {object} state - 项目图状态(原地修改)。
1229
+ * @param {{ extractions?: number, failures?: number, accesses?: number, lastHitAt?: number|string|null }} [patch] - 增量/值。
1230
+ * @returns {object} 同一个 state。
1231
+ */
1232
+ export function touchKgStats(state, patch = {}) {
1233
+ if (!isRecord(state)) return state
1234
+ if (!isRecord(state.stats)) state.stats = emptyKgStats()
1235
+ const stats = state.stats
1236
+ const source = isRecord(patch) ? patch : {}
1237
+ for (const counter of ['extractions', 'failures', 'accesses']) {
1238
+ if (source[counter] === undefined) continue
1239
+ const delta = normalizeNonNegativeInt(source[counter], 0) ?? 0
1240
+ stats[counter] = Math.min(MAX_COUNTER, (normalizeNonNegativeInt(stats[counter], 0) ?? 0) + delta)
1241
+ }
1242
+ if (source.lastHitAt === null) {
1243
+ stats.lastHitAt = null
1244
+ } else if (source.lastHitAt !== undefined) {
1245
+ const at = normalizeTimestamp(source.lastHitAt, null)
1246
+ if (at !== null) stats.lastHitAt = at
1247
+ }
1248
+ return stampUpdatedAt(state)
1249
+ }
1250
+
1251
+ /**
1252
+ * 记录一轮抽取结果(原地修改并返回 state)。
1253
+ *
1254
+ * - 写入/覆盖 `turns[turn]`(记录 status/hash/factIds/at/model/error);
1255
+ * - 状态统计幂等:同一轮从非 done 变为 done 时 `stats.extractions +1`,
1256
+ * 从非 failed 变为 failed 时 `stats.failures +1`(重复记录不会重复计数)。
1257
+ *
1258
+ * @param {object} state - 项目图状态(原地修改)。
1259
+ * @param {number|string} turn - 轮次(turn 号或自定义 key)。
1260
+ * @param {object|string} result - 记录(`{status, hash, factIds, at, model, error}`)或状态字符串。
1261
+ * @returns {object} 同一个 state。
1262
+ */
1263
+ export function recordTurnResult(state, turn, result = {}) {
1264
+ if (!isRecord(state)) return state
1265
+ const turnKey = normalizeTurnKey(turn)
1266
+ if (turnKey === '') return state
1267
+ const payload = typeof result === 'string' ? { status: result } : (isRecord(result) ? result : {})
1268
+ const record = normalizeKgTurnRecord(payload, { now: Date.now() })
1269
+ if (record === null) return state
1270
+ if (!isRecord(state.turns)) state.turns = {}
1271
+ const previous = isRecord(state.turns[turnKey]) ? state.turns[turnKey].status : null
1272
+ state.turns[turnKey] = record
1273
+ if (!isRecord(state.stats)) state.stats = emptyKgStats()
1274
+ const stats = state.stats
1275
+ if (record.status === 'done' && previous !== 'done') {
1276
+ stats.extractions = Math.min(MAX_COUNTER, (normalizeNonNegativeInt(stats.extractions, 0) ?? 0) + 1)
1277
+ }
1278
+ if (record.status === 'failed' && previous !== 'failed') {
1279
+ stats.failures = Math.min(MAX_COUNTER, (normalizeNonNegativeInt(stats.failures, 0) ?? 0) + 1)
1280
+ }
1281
+ return stampUpdatedAt(state)
1282
+ }
1283
+
1284
+ /**
1285
+ * 更新 archive 段(替换/影子化/暂停状态;原地修改并返回 state)。
1286
+ *
1287
+ * 白名单字段:archivedThroughTurn / replacementSeq / shadowedSeqs / tokensSaved /
1288
+ * at / paused / lastError。传 `null` 表示清空可空字段;未传的字段保持原值;
1289
+ * 非法值忽略。
1290
+ *
1291
+ * @param {object} state - 项目图状态(原地修改)。
1292
+ * @param {object} [patch] - 要更新的 archive 字段。
1293
+ * @returns {object} 同一个 state。
1294
+ */
1295
+ export function setArchiveState(state, patch = {}) {
1296
+ if (!isRecord(state)) return state
1297
+ if (!isRecord(state.archive)) state.archive = emptyKgArchive()
1298
+ const archive = state.archive
1299
+ const source = isRecord(patch) ? patch : {}
1300
+ for (const field of ['archivedThroughTurn', 'replacementSeq']) {
1301
+ if (!Object.hasOwn(source, field)) continue
1302
+ if (source[field] === null) archive[field] = null
1303
+ else if (isNonNegativeNumeric(source[field])) archive[field] = normalizeNonNegativeInt(source[field])
1304
+ }
1305
+ if (Object.hasOwn(source, 'shadowedSeqs') && source.shadowedSeqs !== null
1306
+ && (Array.isArray(source.shadowedSeqs) || typeof source.shadowedSeqs === 'string')) {
1307
+ archive.shadowedSeqs = normalizeSeqList(source.shadowedSeqs, DEFAULT_KG_LIMITS.maxShadowedSeqs)
1308
+ }
1309
+ if (Object.hasOwn(source, 'tokensSaved') && isNonNegativeNumeric(source.tokensSaved)) {
1310
+ archive.tokensSaved = normalizeNonNegativeInt(source.tokensSaved) ?? archive.tokensSaved
1311
+ }
1312
+ if (Object.hasOwn(source, 'at')) {
1313
+ if (source.at === null) archive.at = null
1314
+ else {
1315
+ const value = normalizeTimestamp(source.at, null)
1316
+ if (value !== null) archive.at = value
1317
+ }
1318
+ }
1319
+ if (Object.hasOwn(source, 'paused')) archive.paused = source.paused === true
1320
+ if (Object.hasOwn(source, 'lastError')) {
1321
+ archive.lastError = source.lastError === null ? null : (cleanText(source.lastError, 300) || null)
1322
+ }
1323
+ return stampUpdatedAt(state)
1324
+ }
1325
+
1326
+ /* -------------------------------------------------------------------------- */
1327
+ /* 上限淘汰与统计 */
1328
+ /* -------------------------------------------------------------------------- */
1329
+
1330
+ /**
1331
+ * 按事实上限淘汰低价值事实(原地修改并返回 `{state, evicted}`)。
1332
+ *
1333
+ * 只淘汰“非 pinned、非 confidence/importance high”的事实;同一档内按
1334
+ * importance / confidence / hitCount 低者先淘汰,再按 updatedAt 旧者先淘汰,
1335
+ * 最后按 id 保证确定性。淘汰后同步清理 turns.factIds 引用。
1336
+ *
1337
+ * @param {object} state - 项目图状态(原地修改)。
1338
+ * @param {{ maxFacts?: number, limits?: object }} [options] - 上限(默认 3000)。
1339
+ * @returns {{ state: object, evicted: string[] }} 淘汰结果(evicted 为 fact id 列表)。
1340
+ */
1341
+ export function pruneKgState(state, options = {}) {
1342
+ const source = isRecord(options) ? options : {}
1343
+ const limits = resolveLimits(source)
1344
+ const maxFacts = Number.isFinite(source.maxFacts)
1345
+ ? Math.max(0, Math.trunc(source.maxFacts))
1346
+ : limits.maxFacts
1347
+ if (!isRecord(state)) return { state, evicted: [] }
1348
+ if (!isRecord(state.facts)) state.facts = {}
1349
+ if (Object.keys(state.facts).length <= maxFacts) return { state, evicted: [] }
1350
+ const { evicted } = capFactRecord(state.facts, maxFacts, { hard: false })
1351
+ if (evicted.length > 0) {
1352
+ reconcileFactReferences(state, new Set(evicted))
1353
+ stampUpdatedAt(state)
1354
+ }
1355
+ return { state, evicted }
1356
+ }
1357
+
1358
+ /**
1359
+ * 项目图概览统计(只返回计数/元信息,**不返回事实正文**)。
1360
+ *
1361
+ * @param {object} state - 项目图状态(容忍未归一化数据)。
1362
+ * @returns {object} 统计对象。
1363
+ */
1364
+ export function kgStats(state) {
1365
+ const record = isRecord(state) ? state : {}
1366
+ const facts = isRecord(record.facts) ? record.facts : {}
1367
+ const turns = isRecord(record.turns) ? record.turns : {}
1368
+ const archive = isRecord(record.archive) ? record.archive : {}
1369
+ const stats = isRecord(record.stats) ? record.stats : {}
1370
+
1371
+ const statusCounts = { active: 0, superseded: 0, rejected: 0, archived: 0 }
1372
+ const byKind = {}
1373
+ let factCount = 0
1374
+ for (const fact of Object.values(facts)) {
1375
+ if (!isRecord(fact)) continue
1376
+ factCount += 1
1377
+ const status = KG_FACT_STATUSES.includes(fact.status) ? fact.status : 'active'
1378
+ statusCounts[status] += 1
1379
+ const kind = cleanText(fact.kind, 40)
1380
+ const key = kind === '' ? 'unknown' : kind
1381
+ byKind[key] = (byKind[key] ?? 0) + 1
1382
+ }
1383
+
1384
+ const turnCounts = { done: 0, pending: 0, failed: 0, skipped: 0 }
1385
+ let turnCount = 0
1386
+ for (const value of Object.values(turns)) {
1387
+ if (!isRecord(value)) continue
1388
+ turnCount += 1
1389
+ const status = KG_TURN_STATUSES.includes(value.status) ? value.status : 'pending'
1390
+ turnCounts[status] += 1
1391
+ }
1392
+
1393
+ return {
1394
+ version: KG_VERSION,
1395
+ key: typeof record.key === 'string' ? record.key : '',
1396
+ label: typeof record.label === 'string' ? record.label : '',
1397
+ revision: normalizeNonNegativeInt(record.revision, 0) ?? 0,
1398
+ createdAt: normalizeTimestamp(record.createdAt, null),
1399
+ updatedAt: normalizeTimestamp(record.updatedAt, null),
1400
+ facts: factCount,
1401
+ active: statusCounts.active,
1402
+ superseded: statusCounts.superseded,
1403
+ rejected: statusCounts.rejected,
1404
+ archived: statusCounts.archived,
1405
+ byKind,
1406
+ turnsIndexed: turnCount,
1407
+ pendingTurns: turnCounts.pending,
1408
+ failedTurns: turnCounts.failed,
1409
+ doneTurns: turnCounts.done,
1410
+ skippedTurns: turnCounts.skipped,
1411
+ archive: {
1412
+ archivedThroughTurn: normalizeNonNegativeInt(archive.archivedThroughTurn),
1413
+ replacementSeq: normalizeNonNegativeInt(archive.replacementSeq),
1414
+ shadowedSeqs: Array.isArray(archive.shadowedSeqs) ? archive.shadowedSeqs.length : 0,
1415
+ tokensSaved: normalizeNonNegativeInt(archive.tokensSaved, 0) ?? 0,
1416
+ at: normalizeTimestamp(archive.at, null),
1417
+ paused: archive.paused === true,
1418
+ lastError: typeof archive.lastError === 'string' ? archive.lastError : null,
1419
+ },
1420
+ stats: {
1421
+ extractions: normalizeNonNegativeInt(stats.extractions, 0) ?? 0,
1422
+ failures: normalizeNonNegativeInt(stats.failures, 0) ?? 0,
1423
+ accesses: normalizeNonNegativeInt(stats.accesses, 0) ?? 0,
1424
+ lastHitAt: normalizeTimestamp(stats.lastHitAt, null),
1425
+ },
1426
+ }
1427
+ }