@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.
package/lib/graph.js ADDED
@@ -0,0 +1,1628 @@
1
+ /**
2
+ * context-manager — 信息库数据核心(facts 存储/合并/序列化)。
3
+ *
4
+ * 数据形状:
5
+ * { version, facts: { [id]: Fact }, meta: { createdAt, updatedAt, revision } }
6
+ *
7
+ * 说明:原「信息库」的 edges(关系边)与 scopes(层级索引)已删除——
8
+ * 信息库(lib/kb.js)只按 fact.scopePath 的层级路径组织页面,不消费边/scope 索引。
9
+ *
10
+ * 分层:
11
+ * 归一化 normalizeFact / normalizeFactWithConfig
12
+ * 事实操作 mergeFacts / pruneFacts(容量淘汰)
13
+ * 序列化 serializeGraph / deserializeGraph(旧数据里的 edges/scopes 字段被忽略)
14
+ */
15
+
16
+ import { CONFIDENCES, FACT_KINDS, FACT_STATUSES, factId } from './extract.js'
17
+
18
+ /* -------------------------------------------------------------------------- */
19
+ /* 常量 */
20
+ /* -------------------------------------------------------------------------- */
21
+
22
+ /** 图状态结构版本(结构不兼容变更时递增;serialize/deserialize 据此校验)。 */
23
+ export const GRAPH_VERSION = 1
24
+
25
+ /** 图边类型(按 type 优先级从高到低排列;same-turn 最低)。 */
26
+
27
+ /** 默认图配置(宿主可只覆盖其中几项;非法值自动回退默认)。 */
28
+ /** 默认信息库配置(宿主可只覆盖其中几项;非法值自动回退默认)。 */
29
+ export const DEFAULT_GRAPH_CONFIG = Object.freeze({
30
+ // ── 容量上限 ──
31
+ maxFacts: 2000, // 事实条目上限(merge 超限时按重要度淘汰)
32
+ maxScopeDepth: 8, // scopePath 最多保留层数
33
+ maxStatementChars: 80, // statement 最多 code point 数
34
+ maxScopeSegmentChars: 48, // scopePath 单段字符上限
35
+ maxEntities: 8, // entities 最多个数
36
+ maxEntityChars: 48, // 单个 entity 字符上限
37
+ maxIdChars: 128, // 事实 id 字符上限
38
+ maxProjectIdChars: 120, // projectId 字符上限
39
+ maxLineageKeyChars: 120, // source.lineageKey 字符上限
40
+ maxSeqs: 500, // source.seqs 最多保留序号数
41
+ maxAliases: 4, // 近似合并保留的别名上限
42
+ maxSources: 8, // 合并保留的来源上限
43
+ maxSupersedeRefs: 8, // supersededBy 引用上限
44
+ maxConflictRefs: 4, // conflictsWith 引用上限
45
+
46
+ // ── 近似去重(merge)──
47
+ mergeDiceThreshold: 0.8, // 同 scope 内 statement 归一化 Dice 阈值
48
+ mergeEntityThreshold: 0.75, // 同 scope 内 entity Jaccard 阈值
49
+ mergeEntityDiceFloor: 0.5, // 走实体通道时 statement Dice 的下限
50
+ conflictDiceMin: 0.35, // 链接冲突关系时的最低 Dice
51
+ approxScanLimit: 200, // 同 scope 近似去重最多扫描的最近事实数
52
+ })
53
+
54
+ /* -------------------------------------------------------------------------- */
55
+ /* 内部词表 */
56
+ /* -------------------------------------------------------------------------- */
57
+
58
+ /** 合法事实种类集合。 */
59
+ const FACT_KIND_SET = new Set(FACT_KINDS.map(kind => kind.id))
60
+
61
+ /** kind → 中文标签。 */
62
+ const FACT_KIND_LABEL = new Map(FACT_KINDS.map(kind => [kind.id, kind.label]))
63
+
64
+ /** 合法置信度集合。 */
65
+ const CONFIDENCE_SET = new Set(CONFIDENCES.map(confidence => confidence.id))
66
+
67
+ /** 置信度权重(排序用)。 */
68
+ const CONFIDENCE_RANK = new Map([
69
+ ['high', 3],
70
+ ['medium', 2],
71
+ ['low', 1],
72
+ ])
73
+
74
+ /** 合法状态集合(active / superseded / archived,以及 kg-store 的 rejected)。 */
75
+ const STATUS_SET = new Set([...FACT_STATUSES, 'rejected'])
76
+
77
+ /** 状态别名 → id。 */
78
+ const STATUS_ALIASES = new Map([
79
+ ['当前', 'active'],
80
+ ['有效', 'active'],
81
+ ['过时', 'superseded'],
82
+ ['已过时', 'superseded'],
83
+ ['已取代', 'superseded'],
84
+ ['被取代', 'superseded'],
85
+ ['deprecated', 'superseded'],
86
+ ['obsolete', 'superseded'],
87
+ ['replaced', 'superseded'],
88
+ ['archive', 'archived'],
89
+ ['archived', 'archived'],
90
+ ['归档', 'archived'],
91
+ ['已归档', 'archived'],
92
+ ['reject', 'rejected'],
93
+ ['rejected', 'rejected'],
94
+ ['否决', 'rejected'],
95
+ ['已否决', 'rejected'],
96
+ ])
97
+
98
+ /** kind 中文/同义写法 → id。 */
99
+ const KIND_ALIASES = new Map([
100
+ ['goal', 'requirement'],
101
+ ['需求', 'requirement'],
102
+ ['目标', 'requirement'],
103
+ ['要求', 'requirement'],
104
+ ['rule', 'constraint'],
105
+ ['约束', 'constraint'],
106
+ ['规则', 'constraint'],
107
+ ['限制', 'constraint'],
108
+ ['architecture', 'structure'],
109
+ ['结构', 'structure'],
110
+ ['架构', 'structure'],
111
+ ['选择', 'decision'],
112
+ ['决定', 'decision'],
113
+ ['方案', 'decision'],
114
+ ['决策', 'decision'],
115
+ ['deliverable', 'result'],
116
+ ['交付', 'result'],
117
+ ['结果', 'result'],
118
+ ['结论', 'result'],
119
+ ['outcome', 'result'],
120
+ ['api', 'interface'],
121
+ ['接口', 'interface'],
122
+ ['契约', 'interface'],
123
+ ['contract', 'interface'],
124
+ ['约定', 'convention'],
125
+ ['规范', 'convention'],
126
+ ['惯例', 'convention'],
127
+ ])
128
+
129
+ /** confidence 中文/同义写法 → id。 */
130
+ const CONFIDENCE_ALIASES = new Map([
131
+ ['高', 'high'],
132
+ ['中', 'medium'],
133
+ ['低', 'low'],
134
+ ['mid', 'medium'],
135
+ ['normal', 'medium'],
136
+ ['strong', 'high'],
137
+ ['weak', 'low'],
138
+ ])
139
+
140
+ /* -------------------------------------------------------------------------- */
141
+ /* 字段别名(大小写/下划线/连字符不敏感) */
142
+ /* -------------------------------------------------------------------------- */
143
+
144
+ const STATEMENT_KEYS = ['statement', 'text', 'fact', 'content', 'claim', '事实', '陈述']
145
+ const KIND_KEYS = ['kind', 'factKind', 'factType', 'type', 'category', '种类', '类型']
146
+ const SCOPE_KEYS = ['scopePath', 'scope', 'path', 'hierarchy', '层级', '作用域', '路径']
147
+ const ENTITY_KEYS = ['entities', 'entity', 'keywords', 'tags', '实体', '关键实体']
148
+ const CONFIDENCE_KEYS = ['confidence', 'certainty', 'level', '置信度', '可信度']
149
+ const STATUS_KEYS = ['status', 'state', '状态']
150
+ const SOURCE_KEYS = ['source', '来源卡片']
151
+ const ID_KEYS = ['id', 'factId', 'fact_id', '事实id']
152
+ const PROJECT_KEYS = ['projectId', 'project', '项目id', '项目']
153
+ const VALID_FROM_KEYS = ['validFrom', 'validFromAt', '生效时间', '起始时间']
154
+ const VALID_UNTIL_KEYS = ['validUntil', 'validTo', '失效时间', '结束时间']
155
+ const SUPERSEDED_BY_KEYS = ['supersededBy', 'replacedBy', '取代者', '被取代为']
156
+ const CONFLICTS_KEYS = ['conflictsWith', 'conflictWith', 'contradicts', '冲突', '冲突事实']
157
+ const CREATED_AT_KEYS = ['createdAt', 'created', '创建时间']
158
+ const UPDATED_AT_KEYS = ['updatedAt', 'updated', '更新时间']
159
+ const LAST_USED_AT_KEYS = ['lastUsedAt', 'lastUsed', '最近使用时间']
160
+ const HIT_COUNT_KEYS = ['hitCount', 'hits', 'hitTimes', '命中次数']
161
+ const ALIASES_KEYS = ['aliases', 'alias', '同义表述', '别名']
162
+
163
+ /* -------------------------------------------------------------------------- */
164
+ /* 通用小工具 */
165
+ /* -------------------------------------------------------------------------- */
166
+
167
+ /**
168
+ * 是否为普通对象(排除 null / 数组)。
169
+ * @param {unknown} value - 任意值。
170
+ * @returns {boolean} 判断结果。
171
+ */
172
+ function isRecord(value) {
173
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
174
+ }
175
+
176
+ /**
177
+ * 把任意值压成一行文本:换行/制表符/连续空白折叠为单个空格并 trim。
178
+ * @param {unknown} value - 任意值。
179
+ * @returns {string} 一行文本。
180
+ */
181
+ function cleanInline(value) {
182
+ if (typeof value !== 'string') return ''
183
+ return value.replace(/\s+/gu, ' ').trim()
184
+ }
185
+
186
+ /**
187
+ * 按 code point 安全截断(不拆分代理对,不加省略号)。
188
+ * @param {string} text - 文本。
189
+ * @param {number} maxChars - 最大 code point 数。
190
+ * @returns {string} 截断结果。
191
+ */
192
+ function truncateCodePoints(text, maxChars) {
193
+ if (typeof text !== 'string' || text === '') return ''
194
+ if (!Number.isFinite(maxChars) || maxChars <= 0) return ''
195
+ let count = 0
196
+ let index = 0
197
+ while (index < text.length && count < maxChars) {
198
+ const code = text.codePointAt(index)
199
+ index += code !== undefined && code > 0xffff ? 2 : 1
200
+ count += 1
201
+ }
202
+ return index >= text.length ? text : text.slice(0, index)
203
+ }
204
+
205
+ /**
206
+ * 把文本折叠成一行并按 code point 截断。
207
+ * @param {unknown} value - 任意值(非字符串/数字返回空串)。
208
+ * @param {number} maxChars - 字符上限。
209
+ * @returns {string} 清洗结果。
210
+ */
211
+ function cleanText(value, maxChars) {
212
+ if (typeof value !== 'string' && typeof value !== 'number') return ''
213
+ return truncateCodePoints(cleanInline(String(value)), maxChars)
214
+ }
215
+
216
+ /**
217
+ * 取第一个非空字符串(数字会转成字符串)。
218
+ * @param {...unknown} values - 候选值。
219
+ * @returns {string} 结果或空串。
220
+ */
221
+ function pickString(...values) {
222
+ for (const value of values) {
223
+ if (typeof value === 'string' && value.trim() !== '') return value
224
+ if (typeof value === 'number' && Number.isFinite(value)) return String(value)
225
+ }
226
+ return ''
227
+ }
228
+
229
+ /**
230
+ * 读取有限数字(数字或纯数字字符串),非法返回 null。
231
+ * @param {unknown} value - 任意值。
232
+ * @returns {number | null} 数字或 null。
233
+ */
234
+ function readNumber(value) {
235
+ let number = NaN
236
+ if (typeof value === 'number') number = value
237
+ else if (typeof value === 'string' && value.trim() !== '') number = Number(value.trim())
238
+ if (!Number.isFinite(number)) return null
239
+ return number
240
+ }
241
+
242
+ /**
243
+ * 读取时间戳(毫秒,非负,四舍五入),非法/缺失返回 null。
244
+ * @param {unknown} value - 任意值。
245
+ * @returns {number | null} 时间戳或 null。
246
+ */
247
+ function readTimestamp(value) {
248
+ if (value instanceof Date) {
249
+ const time = value.getTime()
250
+ return Number.isFinite(time) && time >= 0 ? Math.round(time) : null
251
+ }
252
+ const number = readNumber(value)
253
+ if (number === null || number < 0) return null
254
+ return Math.round(number)
255
+ }
256
+
257
+ /**
258
+ * 读取非负整数(数字或数字字符串),非法返回 null。
259
+ * @param {unknown} value - 任意值。
260
+ * @returns {number | null} 整数或 null。
261
+ */
262
+ function readNonNegativeInt(value) {
263
+ const number = readNumber(value)
264
+ if (number === null || number < 0) return null
265
+ return Math.round(number)
266
+ }
267
+
268
+ /**
269
+ * 读取正整数,非法回退默认值。
270
+ * @param {unknown} value - 任意值。
271
+ * @param {number} fallback - 默认值。
272
+ * @returns {number} 正整数。
273
+ */
274
+ function readPositiveInt(value, fallback) {
275
+ const number = readNumber(value)
276
+ return number !== null && number >= 1 ? Math.floor(number) : fallback
277
+ }
278
+
279
+ /**
280
+ * 读取闭区间浮点数,非法回退默认值。
281
+ * @param {unknown} value - 任意值。
282
+ * @param {number} fallback - 默认值。
283
+ * @param {number} min - 下界。
284
+ * @param {number} max - 上界。
285
+ * @returns {number} 合法数字。
286
+ */
287
+ function readBoundedNumber(value, fallback, min, max) {
288
+ const number = readNumber(value)
289
+ return number !== null && number >= min && number <= max ? number : fallback
290
+ }
291
+
292
+ /**
293
+ * 读取整数并夹紧到 [min, max];非法时返回 fallback。
294
+ * @param {unknown} value - 任意值。
295
+ * @param {number} fallback - 默认值。
296
+ * @param {number} min - 下界。
297
+ * @param {number} max - 上界。
298
+ * @returns {number} 夹紧后的整数。
299
+ */
300
+ function clampInt(value, fallback, min, max) {
301
+ const number = readNonNegativeInt(value)
302
+ if (number === null) return fallback
303
+ return Math.min(max, Math.max(min, number))
304
+ }
305
+
306
+ /**
307
+ * 保留 3 位小数(避免浮点噪声影响确定性比较)。
308
+ * @param {number} value - 数字。
309
+ * @returns {number} 四舍五入后的数字。
310
+ */
311
+ function round3(value) {
312
+ if (!Number.isFinite(value)) return 0
313
+ return Math.round(value * 1000) / 1000
314
+ }
315
+
316
+ /**
317
+ * 夹紧到 [0, 1] 并保留 3 位小数。
318
+ * @param {number} value - 数字。
319
+ * @returns {number} 夹紧后的权重。
320
+ */
321
+ function clampWeight(value) {
322
+ if (!Number.isFinite(value)) return 0
323
+ return round3(Math.min(1, Math.max(0, value)))
324
+ }
325
+
326
+ /**
327
+ * 与 locale 无关的字符串比较(确定性排序的基础)。
328
+ * @param {string} a - 左值。
329
+ * @param {string} b - 右值。
330
+ * @returns {number} -1 / 0 / 1。
331
+ */
332
+ function compareStrings(a, b) {
333
+ if (a === b) return 0
334
+ return a < b ? -1 : 1
335
+ }
336
+
337
+ /**
338
+ * 比较两个 scopePath 数组(父在前、同层按段字典序)。
339
+ * @param {string[]} a - 左路径。
340
+ * @param {string[]} b - 右路径。
341
+ * @returns {number} 比较结果。
342
+ */
343
+ function compareScopePaths(a, b) {
344
+ const length = Math.min(a.length, b.length)
345
+ for (let index = 0; index < length; index += 1) {
346
+ const compared = compareStrings(a[index], b[index])
347
+ if (compared !== 0) return compared
348
+ }
349
+ return a.length - b.length
350
+ }
351
+
352
+ /**
353
+ * 计算两个数组的公共前缀长度。
354
+ * @param {string[]} a - 左数组。
355
+ * @param {string[]} b - 右数组。
356
+ * @returns {number} 公共前缀长度。
357
+ */
358
+ function commonPrefixLength(a, b) {
359
+ const length = Math.min(a.length, b.length)
360
+ let index = 0
361
+ while (index < length && a[index] === b[index]) index += 1
362
+ return index
363
+ }
364
+
365
+ /**
366
+ * 判断路径是否以指定前缀开头(含相等)。
367
+ * @param {string[]} prefix - 前缀路径。
368
+ * @param {string[]} path - 待判断路径。
369
+ * @returns {boolean} 是否前缀匹配。
370
+ */
371
+ function isScopePrefix(prefix, path) {
372
+ if (prefix.length > path.length) return false
373
+ for (let index = 0; index < prefix.length; index += 1) {
374
+ if (prefix[index] !== path[index]) return false
375
+ }
376
+ return true
377
+ }
378
+
379
+ /**
380
+ * scopePath 数组 → 稳定的字符串键。
381
+ * @param {string[]} path - 路径。
382
+ * @returns {string} 键。
383
+ */
384
+ function scopeKeyOf(path) {
385
+ return path.join('/')
386
+ }
387
+
388
+ /**
389
+ * 深比较两个归一化事实是否完全一致(字段顺序固定,可直接 JSON 比较)。
390
+ * @param {object} a - 事实 A。
391
+ * @param {object} b - 事实 B。
392
+ * @returns {boolean} 是否一致。
393
+ */
394
+ function factsEqual(a, b) {
395
+ if (a === b) return true
396
+ try {
397
+ return JSON.stringify(a) === JSON.stringify(b)
398
+ } catch {
399
+ return false
400
+ }
401
+ }
402
+
403
+ /**
404
+ * 把任意异常/输入安全转成字符串(绝不抛出)。
405
+ * @param {unknown} value - 任意值。
406
+ * @returns {string} 文本。
407
+ */
408
+ function safeString(value) {
409
+ if (typeof value === 'string') return value
410
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value)
411
+ return ''
412
+ }
413
+
414
+ /* -------------------------------------------------------------------------- */
415
+ /* 配置解析 */
416
+ /* -------------------------------------------------------------------------- */
417
+
418
+ /**
419
+ * 合并默认配置与调用方覆盖项,逐项校验非法值(坏值一律回退默认)。
420
+ * @param {unknown} overrides - 调用方传入的部分配置(可为 undefined)。
421
+ * @returns {typeof DEFAULT_GRAPH_CONFIG} 完整且合法的配置。
422
+ */
423
+ function resolveConfig(overrides) {
424
+ const source = isRecord(overrides) ? overrides : {}
425
+ const d = DEFAULT_GRAPH_CONFIG
426
+ return {
427
+ maxFacts: readPositiveInt(source.maxFacts, d.maxFacts),
428
+ maxScopeDepth: readPositiveInt(source.maxScopeDepth, d.maxScopeDepth),
429
+ maxStatementChars: readPositiveInt(source.maxStatementChars, d.maxStatementChars),
430
+ maxScopeSegmentChars: readPositiveInt(source.maxScopeSegmentChars, d.maxScopeSegmentChars),
431
+ maxEntities: readPositiveInt(source.maxEntities, d.maxEntities),
432
+ maxEntityChars: readPositiveInt(source.maxEntityChars, d.maxEntityChars),
433
+ maxIdChars: readPositiveInt(source.maxIdChars, d.maxIdChars),
434
+ maxProjectIdChars: readPositiveInt(source.maxProjectIdChars, d.maxProjectIdChars),
435
+ maxLineageKeyChars: readPositiveInt(source.maxLineageKeyChars, d.maxLineageKeyChars),
436
+ maxSeqs: readPositiveInt(source.maxSeqs, d.maxSeqs),
437
+ maxAliases: readPositiveInt(source.maxAliases, d.maxAliases),
438
+ maxSources: readPositiveInt(source.maxSources, d.maxSources),
439
+ maxSupersedeRefs: readPositiveInt(source.maxSupersedeRefs, d.maxSupersedeRefs),
440
+ maxConflictRefs: readPositiveInt(source.maxConflictRefs, d.maxConflictRefs),
441
+ mergeDiceThreshold: readBoundedNumber(source.mergeDiceThreshold, d.mergeDiceThreshold, 0, 1),
442
+ mergeEntityThreshold: readBoundedNumber(source.mergeEntityThreshold, d.mergeEntityThreshold, 0, 1),
443
+ mergeEntityDiceFloor: readBoundedNumber(source.mergeEntityDiceFloor, d.mergeEntityDiceFloor, 0, 1),
444
+ conflictDiceMin: readBoundedNumber(source.conflictDiceMin, d.conflictDiceMin, 0, 1),
445
+ approxScanLimit: readPositiveInt(source.approxScanLimit, d.approxScanLimit),
446
+ }
447
+ }
448
+
449
+ /* -------------------------------------------------------------------------- */
450
+ /* 字段归一化 */
451
+ /* -------------------------------------------------------------------------- */
452
+
453
+ /**
454
+ * 归一化字段名:大小写、空格、下划线、连字符都不敏感。
455
+ * @param {string} key - 原始字段名。
456
+ * @returns {string} 归一化字段名。
457
+ */
458
+ function normalizeFieldKey(key) {
459
+ return String(key).toLowerCase().replace(/[\s_-]+/gu, '')
460
+ }
461
+
462
+ /**
463
+ * 按别名读取条目字段(大小写/下划线/连字符不敏感,取第一个命中的别名)。
464
+ * @param {Record<string, unknown>} record - 原始对象。
465
+ * @param {string[]} keys - 字段别名(优先顺序)。
466
+ * @returns {unknown} 字段值。
467
+ */
468
+ function readFieldValue(record, keys) {
469
+ if (!isRecord(record)) return undefined
470
+ // 快路径:规范字段名直接命中(绝大多数事实走这里)。
471
+ for (const key of keys) {
472
+ if (Object.prototype.hasOwnProperty.call(record, key)) return record[key]
473
+ }
474
+ const normalized = new Map()
475
+ for (const [key, value] of Object.entries(record)) {
476
+ const canonical = normalizeFieldKey(key)
477
+ if (!normalized.has(canonical)) normalized.set(canonical, value)
478
+ }
479
+ for (const key of keys) {
480
+ const canonical = normalizeFieldKey(key)
481
+ if (normalized.has(canonical)) return normalized.get(canonical)
482
+ }
483
+ return undefined
484
+ }
485
+
486
+ /**
487
+ * 归一化 statement:折叠空白 + 按 code point 截断。
488
+ * @param {unknown} value - 原始值。
489
+ * @param {number} maxChars - 字符上限。
490
+ * @returns {string} 归一化后陈述(空串表示非法)。
491
+ */
492
+ function normalizeStatement(value, maxChars) {
493
+ if (typeof value !== 'string' && typeof value !== 'number') return ''
494
+ return truncateCodePoints(cleanInline(String(value)), maxChars)
495
+ }
496
+
497
+ /**
498
+ * 把 kind 映射到合法 id;非法返回 null(调用方跳过该条)。
499
+ * @param {unknown} value - 原始 kind。
500
+ * @returns {string | null} 合法 kind 或 null。
501
+ */
502
+ function normalizeKind(value) {
503
+ if (typeof value !== 'string') return null
504
+ const text = value.trim()
505
+ if (text === '') return null
506
+ const lower = text.toLowerCase()
507
+ if (FACT_KIND_SET.has(lower)) return lower
508
+ const compact = lower.replace(/[\s_-]+/gu, '')
509
+ if (FACT_KIND_SET.has(compact)) return compact
510
+ return KIND_ALIASES.get(lower) ?? KIND_ALIASES.get(compact) ?? null
511
+ }
512
+
513
+ /**
514
+ * 归一化 confidence:非法/缺失 → 'medium'。
515
+ * @param {unknown} value - 原始值。
516
+ * @returns {'high' | 'medium' | 'low'} 置信度。
517
+ */
518
+ function normalizeConfidence(value) {
519
+ if (typeof value !== 'string') return 'medium'
520
+ const text = value.trim()
521
+ if (text === '') return 'medium'
522
+ const lower = text.toLowerCase()
523
+ if (CONFIDENCE_SET.has(lower)) return lower
524
+ const compact = lower.replace(/[\s_-]+/gu, '')
525
+ if (CONFIDENCE_SET.has(compact)) return compact
526
+ return CONFIDENCE_ALIASES.get(text) ?? CONFIDENCE_ALIASES.get(lower) ?? CONFIDENCE_ALIASES.get(compact) ?? 'medium'
527
+ }
528
+
529
+ /**
530
+ * 归一化 status:合法值 active/superseded/archived;非法/缺失 → 'active'。
531
+ * @param {unknown} value - 原始值。
532
+ * @returns {'active' | 'superseded' | 'archived'} 状态。
533
+ */
534
+ function normalizeStatus(value) {
535
+ if (typeof value !== 'string') return 'active'
536
+ const lower = value.trim().toLowerCase()
537
+ if (lower === '') return 'active'
538
+ if (STATUS_SET.has(lower)) return lower
539
+ const compact = lower.replace(/[\s_-]+/gu, '')
540
+ if (STATUS_SET.has(compact)) return compact
541
+ return STATUS_ALIASES.get(lower) ?? STATUS_ALIASES.get(compact) ?? 'active'
542
+ }
543
+
544
+ /**
545
+ * 归一化 scopePath:数组或带分隔符字符串 → 干净的相对层级路径。
546
+ * @param {unknown} value - 原始值。
547
+ * @param {number} maxDepth - 最多保留层数。
548
+ * @param {number} maxSegmentChars - 单段字符上限。
549
+ * @returns {string[]} 路径段数组。
550
+ */
551
+ function normalizeScopePath(value, maxDepth, maxSegmentChars) {
552
+ let parts = []
553
+ if (Array.isArray(value)) {
554
+ parts = value
555
+ } else if (typeof value === 'string' && value.trim() !== '') {
556
+ parts = value.trim().split(/\s*(?:\/|>|→|::|、|,|,|;|;|\|)\s*/u)
557
+ } else if (typeof value === 'number' && Number.isFinite(value)) {
558
+ parts = [String(value)]
559
+ }
560
+ const path = []
561
+ for (const part of parts) {
562
+ if (typeof part !== 'string' && typeof part !== 'number') continue
563
+ let segment = cleanInline(String(part))
564
+ segment = segment.replace(/^(?:\.?\/+)+/u, '').replace(/\/+$/u, '')
565
+ segment = truncateCodePoints(segment, maxSegmentChars)
566
+ if (segment === '' || segment === '.' || segment === '..') continue
567
+ if (path.includes(segment)) continue
568
+ path.push(segment)
569
+ if (path.length >= maxDepth) break
570
+ }
571
+ return path
572
+ }
573
+
574
+ /**
575
+ * 归一化 entities:字符串/数组 → 去重(大小写不敏感)、清洗、限量。
576
+ * @param {unknown} value - 原始值。
577
+ * @param {number} maxCount - 最多保留个数。
578
+ * @param {number} maxChars - 单个实体的字符上限。
579
+ * @returns {string[]} 实体数组(保留首次出现的写法)。
580
+ */
581
+ function normalizeEntities(value, maxCount, maxChars) {
582
+ const entities = []
583
+ const seen = new Set()
584
+ /**
585
+ * 追加一个实体(大小写不敏感去重)。
586
+ * @param {unknown} raw - 原始实体。
587
+ */
588
+ const push = raw => {
589
+ if (typeof raw !== 'string' && typeof raw !== 'number') return
590
+ const text = truncateCodePoints(cleanInline(String(raw)), maxChars)
591
+ if (text === '') return
592
+ const key = text.toLowerCase()
593
+ if (seen.has(key)) return
594
+ seen.add(key)
595
+ entities.push(text)
596
+ }
597
+ const walk = raw => {
598
+ if (typeof raw === 'string') {
599
+ for (const part of raw.split(/[,,、;;|/]+/u)) push(part)
600
+ return
601
+ }
602
+ if (Array.isArray(raw)) {
603
+ for (const item of raw) walk(item)
604
+ return
605
+ }
606
+ if (isRecord(raw)) push(pickString(raw.name, raw.text, raw.id))
607
+ }
608
+ walk(value)
609
+ return entities.slice(0, maxCount)
610
+ }
611
+
612
+ /**
613
+ * 归一化 projectId(顶层与 source 共用)。
614
+ * @param {unknown} value - 原始值。
615
+ * @param {number} maxChars - 字符上限。
616
+ * @returns {string} projectId(缺失为空串)。
617
+ */
618
+ function normalizeProjectId(value, maxChars) {
619
+ if (typeof value !== 'string' && typeof value !== 'number') return ''
620
+ return truncateCodePoints(cleanInline(String(value)), maxChars)
621
+ }
622
+
623
+ /**
624
+ * 归一化 lineageKey(卡片血统稳定标识)。
625
+ * @param {unknown} value - 原始值。
626
+ * @param {number} maxChars - 字符上限。
627
+ * @returns {string} lineageKey(缺失为空串)。
628
+ */
629
+ function normalizeLineageKey(value, maxChars) {
630
+ if (typeof value !== 'string' && typeof value !== 'number') return ''
631
+ return truncateCodePoints(cleanInline(String(value)), maxChars)
632
+ }
633
+
634
+ /**
635
+ * 归一化 seqs(对话序号数组):去重升序、限量。
636
+ * @param {unknown} value - 原始值(数组 / 逗号分隔字符串 / 数字)。
637
+ * @param {number} maxCount - 最多保留个数。
638
+ * @returns {number[]} 序号数组。
639
+ */
640
+ function normalizeSeqs(value, maxCount) {
641
+ const seqs = []
642
+ const push = raw => {
643
+ const number = readNonNegativeInt(raw)
644
+ if (number === null || seqs.includes(number)) return
645
+ seqs.push(number)
646
+ }
647
+ if (Array.isArray(value)) {
648
+ for (const item of value) push(item)
649
+ } else if (typeof value === 'string') {
650
+ for (const part of value.split(/[,,、;;\s]+/u)) push(part)
651
+ } else if (typeof value === 'number') {
652
+ push(value)
653
+ }
654
+ return seqs.sort((a, b) => a - b).slice(0, maxCount)
655
+ }
656
+
657
+ /**
658
+ * 归一化 importance(存储层排序用,0~1);非法/缺失返回 null。
659
+ * @param {unknown} value - 原始值。
660
+ * @returns {number | null} importance 或 null。
661
+ */
662
+ function normalizeImportance(value) {
663
+ const number = readNumber(value)
664
+ if (number === null || number < 0 || number > 1) return null
665
+ return round3(number)
666
+ }
667
+
668
+ /**
669
+ * 归一化事实 id:字符串/数字 → 清洗后的非空 id;非法返回 null。
670
+ * @param {unknown} value - 原始值。
671
+ * @param {number} maxChars - 字符上限。
672
+ * @returns {string | null} 事实 id 或 null。
673
+ */
674
+ function normalizeFactId(value, maxChars) {
675
+ let text = ''
676
+ if (typeof value === 'string') text = value
677
+ else if (typeof value === 'number' && Number.isFinite(value)) text = String(Math.round(value))
678
+ if (text === '') return null
679
+ const cleaned = text.trim().replace(/[\u0000-\u001f\u007f]+/gu, '')
680
+ if (cleaned === '') return null
681
+ return truncateCodePoints(cleaned, maxChars)
682
+ }
683
+
684
+ /**
685
+ * 归一化 id 引用列表(supersededBy / conflictsWith)。
686
+ * @param {unknown} value - 字符串 / 数组 / 对象数组。
687
+ * @param {number} maxCount - 最多保留个数。
688
+ * @returns {string[]} id 数组(去重、保序)。
689
+ */
690
+ function normalizeIdList(value, maxCount) {
691
+ const list = []
692
+ const push = raw => {
693
+ if (typeof raw === 'string') {
694
+ const id = raw.trim()
695
+ if (id !== '' && !list.includes(id)) list.push(id)
696
+ return
697
+ }
698
+ if (typeof raw === 'number' && Number.isFinite(raw)) {
699
+ const id = String(Math.round(raw))
700
+ if (!list.includes(id)) list.push(id)
701
+ return
702
+ }
703
+ if (isRecord(raw)) push(raw.id ?? raw.factId ?? raw.fact_id)
704
+ }
705
+ if (Array.isArray(value)) {
706
+ for (const item of value) push(item)
707
+ } else {
708
+ push(value)
709
+ }
710
+ return list.slice(0, maxCount)
711
+ }
712
+
713
+ /**
714
+ * 归一化来源对象(source):容忍对象/字符串/数字,扩展字段可选。
715
+ * @param {unknown} value - 原始来源值。
716
+ * @param {typeof DEFAULT_GRAPH_CONFIG} cfg - 已解析配置。
717
+ * @returns {object} 归一化来源对象。
718
+ */
719
+ function normalizeSourceRecord(value, cfg) {
720
+ let cardId = ''
721
+ let turn = null
722
+ let at = null
723
+ let lineageKey = ''
724
+ let seqs = []
725
+ let projectId = ''
726
+ let sessionId = ''
727
+ if (isRecord(value)) {
728
+ cardId = pickString(value.cardId, value.cardid, value.sourceCardId, value.id, value.card)
729
+ turn = readNonNegativeInt(value.turn)
730
+ at = readTimestamp(value.at) ?? readTimestamp(value.time) ?? readTimestamp(value.createdAt)
731
+ lineageKey = normalizeLineageKey(value.lineageKey ?? value.lineage, cfg.maxLineageKeyChars)
732
+ seqs = normalizeSeqs(value.seqs ?? value.sequences, cfg.maxSeqs)
733
+ projectId = normalizeProjectId(value.projectId ?? value.project, cfg.maxProjectIdChars)
734
+ sessionId = normalizeProjectId(value.sessionId ?? value.session, cfg.maxProjectIdChars)
735
+ } else if (typeof value === 'string') {
736
+ cardId = cleanInline(value)
737
+ } else if (typeof value === 'number' && Number.isFinite(value)) {
738
+ cardId = String(Math.round(value))
739
+ }
740
+ const source = { cardId, turn, at: at ?? 0 }
741
+ if (lineageKey !== '') source.lineageKey = lineageKey
742
+ if (seqs.length > 0) source.seqs = seqs
743
+ if (projectId !== '') source.projectId = projectId
744
+ if (sessionId !== '') source.sessionId = sessionId
745
+ return source
746
+ }
747
+
748
+ /**
749
+ * 来源对象的稳定去重键。
750
+ * @param {object} source - 归一化来源。
751
+ * @returns {string} 键。
752
+ */
753
+ function sourceKeyOf(source) {
754
+ return `${source.cardId}\u0000${source.turn === null ? '' : source.turn}\u0000${source.at}`
755
+ }
756
+
757
+ /**
758
+ * 合并来源列表:去重、保序、限量。
759
+ * @param {object[]} list - 来源列表。
760
+ * @param {number} maxCount - 上限。
761
+ * @returns {object[]} 合并结果。
762
+ */
763
+ function dedupeSources(list, maxCount) {
764
+ const result = []
765
+ const seen = new Set()
766
+ for (const source of list) {
767
+ if (!isRecord(source)) continue
768
+ const key = sourceKeyOf(source)
769
+ if (seen.has(key)) continue
770
+ seen.add(key)
771
+ result.push(source)
772
+ if (result.length >= maxCount) break
773
+ }
774
+ return result
775
+ }
776
+
777
+ /**
778
+ * 归一化别名列表:清洗成 statement 形态、去重、排除主陈述、限量。
779
+ * @param {unknown} value - 原始值。
780
+ * @param {string} primary - 主 statement。
781
+ * @param {typeof DEFAULT_GRAPH_CONFIG} cfg - 已解析配置。
782
+ * @returns {string[]} 别名数组。
783
+ */
784
+ function normalizeAliases(value, primary, cfg) {
785
+ const list = []
786
+ const push = raw => {
787
+ const text = normalizeStatement(raw, cfg.maxStatementChars)
788
+ if (text === '' || text === primary) return
789
+ if (list.includes(text)) return
790
+ list.push(text)
791
+ }
792
+ if (Array.isArray(value)) {
793
+ for (const item of value) push(item)
794
+ } else {
795
+ push(value)
796
+ }
797
+ return list.slice(0, cfg.maxAliases)
798
+ }
799
+
800
+ /* -------------------------------------------------------------------------- */
801
+ /* 事实归一化 */
802
+ /* -------------------------------------------------------------------------- */
803
+
804
+ /**
805
+ * 归一化一条事实(内部版本,复用已解析配置)。
806
+ *
807
+ * 规则(与 lib/extract.js 一致并向后兼容其 v15.1 扩展字段):
808
+ * - statement 折叠空白并截断;kind 必须合法(否则返回 null 由调用方跳过);
809
+ * - scopePath 清洗为相对层级路径(≤ maxScopeDepth 段);
810
+ * - entities 去重(大小写不敏感)≤ maxEntities;
811
+ * - confidence 非法 → medium;status 缺省 active(支持 archived);
812
+ * - source 校验/扩展(cardId/turn/at/lineageKey/seqs/projectId/sessionId);
813
+ * - projectId / validFrom / validUntil / supersededBy / conflictsWith /
814
+ * createdAt / updatedAt / lastUsedAt / hitCount / aliases / sources 透传并容错;
815
+ * - 缺 id 时用 `statement + scopePath + sourceCardId` 稳定派生(与 extract.factId 一致)。
816
+ *
817
+ * @param {unknown} raw - 原始事实。
818
+ * @param {typeof DEFAULT_GRAPH_CONFIG} cfg - 已解析配置。
819
+ * @returns {object | null} 归一化事实或 null(非法输入)。
820
+ */
821
+ function normalizeFactWithConfig(raw, cfg) {
822
+ if (!isRecord(raw)) return null
823
+
824
+ const statement = normalizeStatement(readFieldValue(raw, STATEMENT_KEYS), cfg.maxStatementChars)
825
+ if (statement === '') return null
826
+
827
+ const kind = normalizeKind(readFieldValue(raw, KIND_KEYS))
828
+ if (kind === null) return null
829
+
830
+ const scopePath = normalizeScopePath(readFieldValue(raw, SCOPE_KEYS), cfg.maxScopeDepth, cfg.maxScopeSegmentChars)
831
+ const entities = normalizeEntities(readFieldValue(raw, ENTITY_KEYS), cfg.maxEntities, cfg.maxEntityChars)
832
+ const confidence = normalizeConfidence(readFieldValue(raw, CONFIDENCE_KEYS))
833
+ const status = normalizeStatus(readFieldValue(raw, STATUS_KEYS))
834
+
835
+ // ── source(主来源 + 全部来源)──
836
+ const rawSource = readFieldValue(raw, SOURCE_KEYS)
837
+ const primary = normalizeSourceRecord(rawSource, cfg)
838
+ if (primary.cardId === '') primary.cardId = pickString(raw.cardId, raw.sourceCardId, raw.sourceId)
839
+ if (primary.turn === null) primary.turn = readNonNegativeInt(raw.turn)
840
+ if (primary.at === 0) primary.at = readTimestamp(raw.at) ?? 0
841
+ const rawSources = Array.isArray(raw.sources) ? raw.sources.map(item => normalizeSourceRecord(item, cfg)) : []
842
+ const sources = dedupeSources([primary, ...rawSources], cfg.maxSources)
843
+
844
+ // ── 时间/生存字段 ──
845
+ const createdAt = readTimestamp(readFieldValue(raw, CREATED_AT_KEYS)) ?? primary.at
846
+ const updatedAt = readTimestamp(readFieldValue(raw, UPDATED_AT_KEYS)) ?? createdAt
847
+ const validFrom = readTimestamp(readFieldValue(raw, VALID_FROM_KEYS)) ?? createdAt
848
+ const rawValidUntil = readFieldValue(raw, VALID_UNTIL_KEYS)
849
+ const validUntil = rawValidUntil === undefined || rawValidUntil === null || rawValidUntil === ''
850
+ ? null
851
+ : readTimestamp(rawValidUntil)
852
+ const rawLastUsedAt = readFieldValue(raw, LAST_USED_AT_KEYS)
853
+ const lastUsedAt = rawLastUsedAt === undefined || rawLastUsedAt === null || rawLastUsedAt === ''
854
+ ? null
855
+ : readTimestamp(rawLastUsedAt)
856
+ const hitCount = readNonNegativeInt(readFieldValue(raw, HIT_COUNT_KEYS)) ?? 0
857
+
858
+ // ── 项目与关系字段 ──
859
+ const projectId = normalizeProjectId(readFieldValue(raw, PROJECT_KEYS), cfg.maxProjectIdChars)
860
+ || normalizeProjectId(primary.projectId, cfg.maxProjectIdChars)
861
+ const id = normalizeFactId(readFieldValue(raw, ID_KEYS), cfg.maxIdChars)
862
+ ?? factId(statement, scopePath, primary.cardId)
863
+ const supersededBy = normalizeIdList(readFieldValue(raw, SUPERSEDED_BY_KEYS), cfg.maxSupersedeRefs)
864
+ .filter(ref => ref !== id)
865
+ const conflictsWith = normalizeIdList(readFieldValue(raw, CONFLICTS_KEYS), cfg.maxConflictRefs)
866
+ .filter(ref => ref !== id)
867
+
868
+ const aliases = normalizeAliases(readFieldValue(raw, ALIASES_KEYS), statement, cfg)
869
+
870
+ // 字段顺序固定:serialize / 深比较依赖该顺序。
871
+ const fact = {
872
+ id,
873
+ statement,
874
+ kind,
875
+ scopePath,
876
+ entities,
877
+ confidence,
878
+ source: sources[0],
879
+ status,
880
+ projectId,
881
+ validFrom,
882
+ validUntil,
883
+ supersededBy,
884
+ conflictsWith,
885
+ createdAt,
886
+ updatedAt,
887
+ lastUsedAt,
888
+ hitCount,
889
+ aliases,
890
+ sources,
891
+ }
892
+ // 存储层可选字段(kg-store 的 pinned/importance):有值才出现,保证往返不丢。
893
+ if (raw.pinned === true) fact.pinned = true
894
+ const importance = normalizeImportance(raw.importance)
895
+ if (importance !== null) fact.importance = importance
896
+ return fact
897
+ }
898
+
899
+ /**
900
+ * 归一化一条事实(公开版本):非法输入(非对象、缺 statement、非法 kind 等)返回 null。
901
+ *
902
+ * 绝不抛出;对 `lib/extract.js` 产出的 v15.1 事实向后兼容(缺失字段走安全缺省)。
903
+ *
904
+ * @param {unknown} fact - 原始事实。
905
+ * @param {object} [opts] - 可覆盖 maxScopeDepth / maxEntities / maxStatementChars 等配置。
906
+ * @returns {object | null} 归一化事实或 null。
907
+ */
908
+ export function normalizeFact(fact, opts = {}) {
909
+ try {
910
+ return normalizeFactWithConfig(fact, resolveConfig(opts))
911
+ } catch {
912
+ return null
913
+ }
914
+ }
915
+
916
+ /* -------------------------------------------------------------------------- */
917
+ /* 图容器 */
918
+ /* -------------------------------------------------------------------------- */
919
+
920
+ /**
921
+ * 归一化 meta 对象。
922
+ * @param {unknown} raw - 原始 meta。
923
+ * @returns {{ createdAt: number, updatedAt: number, revision: number }} 归一化 meta。
924
+ */
925
+ function normalizeMeta(raw) {
926
+ const source = isRecord(raw) ? raw : {}
927
+ const createdAt = readTimestamp(source.createdAt) ?? 0
928
+ const updatedAt = readTimestamp(source.updatedAt) ?? createdAt
929
+ const revision = readNonNegativeInt(source.revision) ?? 0
930
+ return { createdAt, updatedAt, revision }
931
+ }
932
+
933
+ /**
934
+ * 创建空图。
935
+ * @param {{ now?: number }} [opts] - 可选创建时间(缺省 0,保证确定性)。
936
+ * @returns {{ version: number, facts: object, edges: object, scopes: object, meta: object }} 空图。
937
+ */
938
+ export function emptyGraph(opts = {}) {
939
+ const source = isRecord(opts) ? opts : {}
940
+ const now = readTimestamp(source.now) ?? 0
941
+ return {
942
+ version: GRAPH_VERSION,
943
+ facts: {},
944
+ meta: { createdAt: now, updatedAt: now, revision: 0 },
945
+ }
946
+ }
947
+
948
+ /**
949
+ * 把任意输入整理成合法图(坏输入回退空图,不抛错)。
950
+ *
951
+ * 事实逐条归一化(非法跳过);edges/scopes 字段(旧图谱数据)直接忽略。
952
+ *
953
+ * @param {unknown} raw - 任意图对象。
954
+ * @returns {{ version: number, facts: object, meta: object }} 合法信息库数据。
955
+ */
956
+ function ensureGraph(raw) {
957
+ if (!isRecord(raw)) return emptyGraph()
958
+ const cfg = resolveConfig()
959
+ const factsSource = isRecord(raw.facts) ? Object.values(raw.facts) : Array.isArray(raw.facts) ? raw.facts : []
960
+ const facts = {}
961
+ let processed = 0
962
+ const processLimit = Math.max(1, cfg.maxFacts * 4) // 防止畸形输入无限处理
963
+ for (const item of factsSource) {
964
+ if (processed >= processLimit) break
965
+ processed += 1
966
+ const fact = normalizeFactWithConfig(item, cfg)
967
+ if (fact === null) continue
968
+ if (facts[fact.id] === undefined) facts[fact.id] = fact
969
+ }
970
+ return {
971
+ version: GRAPH_VERSION,
972
+ facts,
973
+ meta: normalizeMeta(raw.meta),
974
+ }
975
+ }
976
+
977
+ /* -------------------------------------------------------------------------- */
978
+ /* 邻接/度数工具 */
979
+ /* -------------------------------------------------------------------------- */
980
+
981
+ /* -------------------------------------------------------------------------- */
982
+ /* 合并事实 */
983
+ /* -------------------------------------------------------------------------- */
984
+
985
+ /**
986
+ * 把「疑似同一事实」的输入整理成事实数组(容忍数组/可迭代/单对象/空值)。
987
+ * @param {unknown} value - 输入。
988
+ * @returns {unknown[]} 待归一化的事实数组。
989
+ */
990
+ function toFactInputList(value) {
991
+ if (value === null || value === undefined) return []
992
+ if (Array.isArray(value)) return value
993
+ if (typeof value === 'string') return []
994
+ if (typeof value === 'object' && typeof value[Symbol.iterator] === 'function') {
995
+ try {
996
+ return Array.from(value)
997
+ } catch {
998
+ return []
999
+ }
1000
+ }
1001
+ return [value]
1002
+ }
1003
+
1004
+ /**
1005
+ * 计算 statement 归一化键(小写、去标点/空白),用于完全重复与近似去重。
1006
+ * @param {string} statement - 陈述。
1007
+ * @returns {string} 归一化键。
1008
+ */
1009
+ function normalizeStatementKey(statement) {
1010
+ if (typeof statement !== 'string') return ''
1011
+ return statement
1012
+ .toLowerCase()
1013
+ .replace(/[\s,,。.;;::!!??、"'“”‘’()()[\]【】{}<>《》/\\|_-]+/gu, '')
1014
+ }
1015
+
1016
+ /**
1017
+ * 计算 statement 的字符 bigram 频次表(中文/英文通用,确定性)。
1018
+ * @param {string} statement - 陈述。
1019
+ * @returns {Map<string, number>} bigram → 次数。
1020
+ */
1021
+ function statementBigrams(statement) {
1022
+ const text = normalizeStatementKey(statement)
1023
+ const grams = new Map()
1024
+ if (text === '') return grams
1025
+ if (text.length === 1) {
1026
+ grams.set(text, 1)
1027
+ return grams
1028
+ }
1029
+ for (let index = 0; index + 1 < text.length; index += 1) {
1030
+ const gram = text.slice(index, index + 2)
1031
+ grams.set(gram, (grams.get(gram) ?? 0) + 1)
1032
+ }
1033
+ return grams
1034
+ }
1035
+
1036
+ /**
1037
+ * 提取 statement 归一化键中的数字签名(逗号分隔)。
1038
+ *
1039
+ * 近似合并时用于保护「只差数字」的事实(如「端口 8080」vs「端口 9090」)不被误并。
1040
+ * @param {string} statement - 陈述。
1041
+ * @returns {string} 数字签名(无数字为空串)。
1042
+ */
1043
+ function statementDigitKey(statement) {
1044
+ const numbers = normalizeStatementKey(statement).match(/\d+/gu)
1045
+ return numbers === null ? '' : numbers.join(',')
1046
+ }
1047
+
1048
+ /**
1049
+ * 由 bigram 频次表计算 Dice 系数(2|A∩B| / (|A|+|B|))。
1050
+ * @param {Map<string, number>} a - A 的 bigram 表。
1051
+ * @param {Map<string, number>} b - B 的 bigram 表。
1052
+ * @returns {number} Dice 系数(0~1)。
1053
+ */
1054
+ function diceFromBigrams(a, b) {
1055
+ if (a.size === 0 || b.size === 0) return 0
1056
+ const [small, large] = a.size <= b.size ? [a, b] : [b, a]
1057
+ let intersection = 0
1058
+ for (const [gram, count] of small) {
1059
+ const other = large.get(gram)
1060
+ if (other !== undefined) intersection += Math.min(count, other)
1061
+ }
1062
+ const total = [...a.values()].reduce((sum, count) => sum + count, 0)
1063
+ + [...b.values()].reduce((sum, count) => sum + count, 0)
1064
+ return total === 0 ? 0 : (2 * intersection) / total
1065
+ }
1066
+
1067
+ /**
1068
+ * 计算两个实体集合的 Jaccard 系数(大小写不敏感)。
1069
+ * @param {Set<string>} a - 实体集合 A。
1070
+ * @param {Set<string>} b - 实体集合 B。
1071
+ * @returns {number} Jaccard 系数(0~1)。
1072
+ */
1073
+ function jaccardOfSets(a, b) {
1074
+ if (a.size === 0 || b.size === 0) return 0
1075
+ const [small, large] = a.size <= b.size ? [a, b] : [b, a]
1076
+ let intersection = 0
1077
+ for (const item of small) if (large.has(item)) intersection += 1
1078
+ const union = a.size + b.size - intersection
1079
+ return union === 0 ? 0 : intersection / union
1080
+ }
1081
+
1082
+ /**
1083
+ * 合并两条「同一事实」记录(保留既有 id/statement/kind/scopePath)。
1084
+ *
1085
+ * @param {object} existing - 图中既有事实。
1086
+ * @param {object} incoming - 新归一化事实。
1087
+ * @param {typeof DEFAULT_GRAPH_CONFIG} cfg - 已解析配置。
1088
+ * @returns {{ fact: object, changed: boolean, supersededNow: boolean }} 合并结果。
1089
+ */
1090
+ function mergeFactRecords(existing, incoming, cfg) {
1091
+ // 实体并集(大小写不敏感去重,保留既有写法优先)。
1092
+ const entities = existing.entities.slice()
1093
+ const entitySeen = new Set(entities.map(entity => entity.toLowerCase()))
1094
+ for (const entity of incoming.entities) {
1095
+ if (entities.length >= cfg.maxEntities) break
1096
+ const key = entity.toLowerCase()
1097
+ if (entitySeen.has(key)) continue
1098
+ entitySeen.add(key)
1099
+ entities.push(entity)
1100
+ }
1101
+
1102
+ // 别名并集:既有别名 + 新陈述 + 新别名(排除主陈述)。
1103
+ const aliases = []
1104
+ const aliasSeen = new Set()
1105
+ const pushAlias = raw => {
1106
+ const text = normalizeStatement(raw, cfg.maxStatementChars)
1107
+ if (text === '' || text === existing.statement || aliasSeen.has(text)) return
1108
+ aliasSeen.add(text)
1109
+ aliases.push(text)
1110
+ }
1111
+ for (const alias of existing.aliases) pushAlias(alias)
1112
+ pushAlias(incoming.statement)
1113
+ for (const alias of incoming.aliases) pushAlias(alias)
1114
+
1115
+ // 来源并集(既有来源在前)。
1116
+ const sources = dedupeSources(
1117
+ [...existing.sources, ...incoming.sources, incoming.source],
1118
+ cfg.maxSources,
1119
+ )
1120
+
1121
+ // 置信度取高者;状态非 active 粘滞(archived/superseded 不会被一次 active 覆盖)。
1122
+ const confidence = (CONFIDENCE_RANK.get(incoming.confidence) ?? 0) > (CONFIDENCE_RANK.get(existing.confidence) ?? 0)
1123
+ ? incoming.confidence
1124
+ : existing.confidence
1125
+ const status = existing.status !== 'active' ? existing.status : incoming.status
1126
+ const supersededNow = existing.status === 'active' && status !== 'active'
1127
+
1128
+ // 引用并集(去重、排除自身)。
1129
+ const mergeRefs = (left, right, max) => {
1130
+ const list = []
1131
+ for (const ref of [...left, ...right]) {
1132
+ if (typeof ref !== 'string' || ref === '' || ref === existing.id || list.includes(ref)) continue
1133
+ list.push(ref)
1134
+ if (list.length >= max) break
1135
+ }
1136
+ return list
1137
+ }
1138
+
1139
+ // 时间字段:createdAt/validFrom 取最早已知值(0 视为未知),updatedAt 取最新。
1140
+ const minKnown = (left, right) => {
1141
+ if (left === 0 || left === null || left === undefined) return right ?? 0
1142
+ if (right === 0 || right === null || right === undefined) return left
1143
+ return Math.min(left, right)
1144
+ }
1145
+ const maxKnown = (left, right) => Math.max(left ?? 0, right ?? 0)
1146
+ let validUntil = null
1147
+ if (existing.validUntil !== null && incoming.validUntil !== null) {
1148
+ validUntil = Math.max(existing.validUntil, incoming.validUntil)
1149
+ }
1150
+ let lastUsedAt = null
1151
+ if (existing.lastUsedAt !== null || incoming.lastUsedAt !== null) {
1152
+ lastUsedAt = Math.max(existing.lastUsedAt ?? 0, incoming.lastUsedAt ?? 0)
1153
+ }
1154
+
1155
+ const fact = {
1156
+ id: existing.id,
1157
+ statement: existing.statement,
1158
+ kind: existing.kind,
1159
+ scopePath: existing.scopePath,
1160
+ entities,
1161
+ confidence,
1162
+ source: sources[0],
1163
+ status,
1164
+ projectId: existing.projectId !== '' ? existing.projectId : incoming.projectId,
1165
+ validFrom: minKnown(existing.validFrom, incoming.validFrom),
1166
+ validUntil,
1167
+ supersededBy: mergeRefs(existing.supersededBy, incoming.supersededBy, cfg.maxSupersedeRefs),
1168
+ conflictsWith: mergeRefs(existing.conflictsWith, incoming.conflictsWith, cfg.maxConflictRefs),
1169
+ createdAt: minKnown(existing.createdAt, incoming.createdAt),
1170
+ updatedAt: maxKnown(existing.updatedAt, incoming.updatedAt),
1171
+ lastUsedAt,
1172
+ hitCount: Math.max(existing.hitCount ?? 0, incoming.hitCount ?? 0),
1173
+ aliases: aliases.slice(0, cfg.maxAliases),
1174
+ sources,
1175
+ }
1176
+ const existingImportance = normalizeImportance(existing.importance)
1177
+ const incomingImportance = normalizeImportance(incoming.importance)
1178
+ if (existing.pinned === true || incoming.pinned === true) fact.pinned = true
1179
+ if (existingImportance !== null || incomingImportance !== null) {
1180
+ fact.importance = Math.max(existingImportance ?? 0, incomingImportance ?? 0)
1181
+ }
1182
+ return { fact, changed: !factsEqual(existing, fact), supersededNow }
1183
+ }
1184
+
1185
+ /**
1186
+ * 合并一批新事实进图(自动去重 / 近似归并 / 上限淘汰)。
1187
+ *
1188
+ * 去重顺序:
1189
+ * 1. 同 `id` → 合并字段;
1190
+ * 2. 同 `(归一化 statement, scopePath)` → 合并字段(不同来源的同一事实);
1191
+ * 3. 同 scopePath 内近似:statement 归一化后 Dice ≥ mergeDiceThreshold,或
1192
+ * 实体 Jaccard ≥ mergeEntityThreshold 且 Dice ≥ mergeEntityDiceFloor → 归并,
1193
+ * 保留 aliases 与全部 source;不同表述的独立事实**不会**被强行合并。
1194
+ *
1195
+ * 合并结果保证:完全重复不计新增(skipped);新事实 added;字段有更新 merged;
1196
+ * 状态转为 superseded/archived 计入 superseded;超 maxFacts 时按重要度淘汰计入
1197
+ * **条件字段** `stats.pruned`(仅在有淘汰时出现,其余情况 stats 严格为
1198
+ * `{added, merged, skipped, superseded}`)。
1199
+ *
1200
+ * @param {object} graph - 现有图(坏输入视为空图)。
1201
+ * @param {unknown} newFacts - 新事实(数组/可迭代/单对象)。
1202
+ * @param {object} [opts] - `{ now?, maxFacts?, ...配置覆盖, linkConflicts? }`。
1203
+ * @returns {{ graph: object, stats: { added: number, merged: number, skipped: number, superseded: number, pruned?: number } }} 新图与统计。
1204
+ */
1205
+ export function mergeFacts(graph, newFacts, opts = {}) {
1206
+ /** 统计(键顺序固定,便于测试/序列化)。 */
1207
+ const stats = { added: 0, merged: 0, skipped: 0, superseded: 0 }
1208
+ try {
1209
+ const cfg = resolveConfig(opts)
1210
+ const base = ensureGraph(graph)
1211
+ const now = readTimestamp(opts.now)
1212
+ const items = toFactInputList(newFacts)
1213
+
1214
+ // 工作副本:既有事实浅拷贝(事实对象保持不可变约定,只在需要时整体替换)。
1215
+ const facts = { ...base.facts }
1216
+ const logicalIndex = new Map() // normalizeStatementKey + \0 + scopeKey → id
1217
+ /** scopeKey → 最近登记的同 scope 事实 entry 数组(近似去重索引)。 */
1218
+ const scopeBuckets = new Map()
1219
+ /** id → bucket entry(用于更新 updatedAt/entitySet)。 */
1220
+ const bucketEntries = new Map()
1221
+
1222
+ /**
1223
+ * 登记一条事实到近似去重索引。
1224
+ * @param {object} fact - 归一化事实。
1225
+ */
1226
+ const register = fact => {
1227
+ const key = scopeKeyOf(fact.scopePath)
1228
+ let bucket = scopeBuckets.get(key)
1229
+ if (bucket === undefined) {
1230
+ bucket = []
1231
+ scopeBuckets.set(key, bucket)
1232
+ }
1233
+ const entry = {
1234
+ id: fact.id,
1235
+ grams: statementBigrams(fact.statement),
1236
+ digits: statementDigitKey(fact.statement),
1237
+ entitySet: new Set(fact.entities.map(entity => entity.toLowerCase())),
1238
+ updatedAt: fact.updatedAt,
1239
+ }
1240
+ // 同一 id 重复登记时替换旧 entry。
1241
+ const previous = bucketEntries.get(fact.id)
1242
+ if (previous !== undefined) {
1243
+ bucket[previous.bucketIndex] = entry
1244
+ } else {
1245
+ entry.bucketIndex = bucket.length
1246
+ bucket.push(entry)
1247
+ }
1248
+ bucketEntries.set(fact.id, entry)
1249
+ // 限制桶内存:只保留最近 approxScanLimit * 2 条(确定性淘汰最旧)。
1250
+ if (bucket.length > cfg.approxScanLimit * 2) {
1251
+ const removeCount = bucket.length - cfg.approxScanLimit * 2
1252
+ for (const removed of bucket.slice(0, removeCount)) {
1253
+ if (removed !== undefined) bucketEntries.delete(removed.id)
1254
+ }
1255
+ bucket.splice(0, removeCount)
1256
+ for (let index = 0; index < bucket.length; index += 1) bucket[index].bucketIndex = index
1257
+ }
1258
+ }
1259
+
1260
+ for (const fact of Object.values(facts)) {
1261
+ const logicalKey = `${normalizeStatementKey(fact.statement)}\u0000${scopeKeyOf(fact.scopePath)}`
1262
+ if (!logicalIndex.has(logicalKey)) logicalIndex.set(logicalKey, fact.id)
1263
+ register(fact)
1264
+ }
1265
+
1266
+ /**
1267
+ * 在同一个 scope 桶内找最相似的既有事实(近似去重)。
1268
+ * @param {object} incoming - 新事实。
1269
+ * @param {Map<string, number>} incomingGrams - 新事实 statement bigram 表。
1270
+ * @param {Set<string>} incomingEntitySet - 新事实实体集合。
1271
+ * @returns {string | null} 最相似事实 id 或 null。
1272
+ */
1273
+ const findApproximate = (incoming, incomingGrams, incomingDigits, incomingEntitySet) => {
1274
+ const bucket = scopeBuckets.get(scopeKeyOf(incoming.scopePath))
1275
+ if (bucket === undefined || bucket.length === 0) return null
1276
+ let bestId = null
1277
+ let bestDice = 0
1278
+ let bestJaccard = 0
1279
+ let bestUpdatedAt = -1
1280
+ const limit = Math.min(bucket.length, cfg.approxScanLimit)
1281
+ // 从最近登记的事实向前扫描(新事实更可能与近期事实重复)。
1282
+ for (let offset = 0; offset < limit; offset += 1) {
1283
+ const entry = bucket[bucket.length - 1 - offset]
1284
+ if (entry === undefined || entry.id === incoming.id) continue
1285
+ // 只差数字的表述视为不同事实(防「端口 8080/9090」类误并)。
1286
+ if (entry.digits !== incomingDigits) continue
1287
+ const dice = diceFromBigrams(incomingGrams, entry.grams)
1288
+ const jaccard = jaccardOfSets(incomingEntitySet, entry.entitySet)
1289
+ const qualified = dice >= cfg.mergeDiceThreshold
1290
+ || (jaccard >= cfg.mergeEntityThreshold && dice >= cfg.mergeEntityDiceFloor)
1291
+ if (!qualified) continue
1292
+ const better = dice > bestDice
1293
+ || (dice === bestDice && jaccard > bestJaccard)
1294
+ || (dice === bestDice && jaccard === bestJaccard && entry.updatedAt > bestUpdatedAt)
1295
+ || (dice === bestDice && jaccard === bestJaccard && entry.updatedAt === bestUpdatedAt
1296
+ && (bestId === null || compareStrings(entry.id, bestId) < 0))
1297
+ if (better) {
1298
+ bestId = entry.id
1299
+ bestDice = dice
1300
+ bestJaccard = jaccard
1301
+ bestUpdatedAt = entry.updatedAt
1302
+ }
1303
+ }
1304
+ return bestId
1305
+ }
1306
+
1307
+ // ── 逐条处理新事实 ──
1308
+ for (const item of items) {
1309
+ const incoming = normalizeFactWithConfig(item, cfg)
1310
+ if (incoming === null) {
1311
+ stats.skipped += 1
1312
+ continue
1313
+ }
1314
+ const incomingKey = normalizeStatementKey(incoming.statement)
1315
+ const logicalKey = `${incomingKey}\u0000${scopeKeyOf(incoming.scopePath)}`
1316
+
1317
+ // 1) 同 id / 同 (statement, scope) / 同 scope 近似 → 合并。
1318
+ let targetId = facts[incoming.id] !== undefined
1319
+ ? incoming.id
1320
+ : logicalIndex.get(logicalKey) ?? null
1321
+ let incomingGrams = null
1322
+ let incomingEntitySet = null
1323
+ if (targetId === null) {
1324
+ incomingGrams = statementBigrams(incoming.statement)
1325
+ incomingEntitySet = new Set(incoming.entities.map(entity => entity.toLowerCase()))
1326
+ targetId = findApproximate(incoming, incomingGrams, statementDigitKey(incoming.statement), incomingEntitySet)
1327
+ }
1328
+
1329
+ if (targetId !== null && facts[targetId] !== undefined) {
1330
+ const { fact, changed, supersededNow } = mergeFactRecords(facts[targetId], incoming, cfg)
1331
+ facts[targetId] = fact
1332
+ if (supersededNow) stats.superseded += 1
1333
+ if (changed) stats.merged += 1
1334
+ else stats.skipped += 1
1335
+ // 近似归并后,新表述也纳入逻辑索引,后续同表述可直接命中。
1336
+ if (changed && !logicalIndex.has(logicalKey)) logicalIndex.set(logicalKey, targetId)
1337
+ const entry = bucketEntries.get(targetId)
1338
+ if (entry !== undefined) {
1339
+ entry.updatedAt = fact.updatedAt
1340
+ entry.entitySet = new Set(fact.entities.map(entity => entity.toLowerCase()))
1341
+ }
1342
+ continue
1343
+ }
1344
+
1345
+ // 2) 新节点。
1346
+ facts[incoming.id] = incoming
1347
+ if (!logicalIndex.has(logicalKey)) logicalIndex.set(logicalKey, incoming.id)
1348
+ register(incoming)
1349
+ stats.added += 1
1350
+ if (incoming.status !== 'active') stats.superseded += 1
1351
+
1352
+ // 可选:把同 scope 内「表述相近但不足以合并」的独立事实标记为冲突关系。
1353
+ if (opts.linkConflicts === true) {
1354
+ const bucket = scopeBuckets.get(scopeKeyOf(incoming.scopePath)) ?? []
1355
+ const grams = statementBigrams(incoming.statement)
1356
+ const candidates = []
1357
+ for (const entry of bucket) {
1358
+ if (entry.id === incoming.id) continue
1359
+ const dice = diceFromBigrams(grams, entry.grams)
1360
+ if (dice < cfg.conflictDiceMin || dice >= cfg.mergeDiceThreshold) continue
1361
+ candidates.push({ id: entry.id, dice })
1362
+ }
1363
+ candidates.sort((a, b) => b.dice - a.dice || compareStrings(a.id, b.id))
1364
+ const conflictIds = candidates.slice(0, cfg.maxConflictRefs).map(candidate => candidate.id)
1365
+ if (conflictIds.length > 0) {
1366
+ facts[incoming.id] = {
1367
+ ...incoming,
1368
+ conflictsWith: normalizeIdList([...incoming.conflictsWith, ...conflictIds], cfg.maxConflictRefs),
1369
+ }
1370
+ for (const conflictId of conflictIds) {
1371
+ const target = facts[conflictId]
1372
+ if (target === undefined) continue
1373
+ facts[conflictId] = {
1374
+ ...target,
1375
+ conflictsWith: normalizeIdList([...target.conflictsWith, incoming.id], cfg.maxConflictRefs),
1376
+ }
1377
+ }
1378
+ }
1379
+ }
1380
+ }
1381
+
1382
+ // ── 容量上限:按重要度淘汰 ──
1383
+ let nextFacts = facts
1384
+ if (Object.keys(nextFacts).length > cfg.maxFacts) {
1385
+ const before = Object.keys(nextFacts).length
1386
+ nextFacts = pruneFacts({ facts: nextFacts, meta: base.meta }, { maxFacts: cfg.maxFacts })
1387
+ stats.pruned = before - Object.keys(nextFacts).length
1388
+ }
1389
+
1390
+ const maxFactAt = maxUpdatedAtOf(nextFacts)
1391
+ const changedAny = stats.added + stats.merged + (stats.pruned ?? 0) > 0
1392
+ const meta = {
1393
+ createdAt: base.meta.createdAt > 0 ? base.meta.createdAt : (now ?? maxFactAt),
1394
+ updatedAt: changedAny ? (now ?? Math.max(base.meta.updatedAt, maxFactAt)) : base.meta.updatedAt,
1395
+ revision: changedAny ? base.meta.revision + 1 : base.meta.revision,
1396
+ }
1397
+ return {
1398
+ graph: { version: GRAPH_VERSION, facts: nextFacts, meta },
1399
+ stats,
1400
+ }
1401
+ } catch {
1402
+ return { graph: emptyGraph(), stats }
1403
+ }
1404
+ }
1405
+
1406
+ /**
1407
+ * 事实表中最大的 updatedAt(缺失视为 0)。
1408
+ * @param {Record<string, object>} facts - 事实表。
1409
+ * @returns {number} 最大 updatedAt。
1410
+ */
1411
+ function maxUpdatedAtOf(facts) {
1412
+ let max = 0
1413
+ for (const fact of Object.values(facts)) {
1414
+ if (typeof fact.updatedAt === 'number' && fact.updatedAt > max) max = fact.updatedAt
1415
+ }
1416
+ return max
1417
+ }
1418
+
1419
+ /* -------------------------------------------------------------------------- */
1420
+ /* 边计算 */
1421
+ /* -------------------------------------------------------------------------- */
1422
+
1423
+ /* -------------------------------------------------------------------------- */
1424
+ /* 检索:倒排索引 + 评分 */
1425
+ /* -------------------------------------------------------------------------- */
1426
+
1427
+ /* -------------------------------------------------------------------------- */
1428
+ /* 图扩展(BFS) */
1429
+ /* -------------------------------------------------------------------------- */
1430
+
1431
+ /* -------------------------------------------------------------------------- */
1432
+ /* scope 查询 */
1433
+ /* -------------------------------------------------------------------------- */
1434
+
1435
+ /* -------------------------------------------------------------------------- */
1436
+ /* 统计 / 裁剪 */
1437
+ /* -------------------------------------------------------------------------- */
1438
+
1439
+ /**
1440
+ * 按重要度裁剪事实数到 maxFacts(确定性)。
1441
+ *
1442
+ * 排序优先级:pinned → confidence 高 → 状态 active → importance 高 → updatedAt 新 → id 小。
1443
+ * @param {{facts?: object, meta?: object}} graph - 事实容器(坏输入视为空)。
1444
+ * @param {{maxFacts?: number}} [opts] - 覆盖上限。
1445
+ * @returns {Record<string, object>} 裁剪后的事实表(不修改输入)。
1446
+ */
1447
+ function pruneFacts(graph, opts = {}) {
1448
+ try {
1449
+ const cfg = resolveConfig(opts)
1450
+ const base = ensureGraph(graph)
1451
+ const maxFacts = clampInt(opts.maxFacts, cfg.maxFacts, 1, 1_000_000)
1452
+ const facts = Object.values(base.facts)
1453
+ if (facts.length <= maxFacts) return { ...base.facts }
1454
+ const statusRankOf = fact => (fact.status === 'active' ? 2 : (fact.status === 'archived' ? 0 : 1))
1455
+ const ranked = facts.slice().sort((a, b) => {
1456
+ const pinnedDiff = (b.pinned === true ? 1 : 0) - (a.pinned === true ? 1 : 0)
1457
+ if (pinnedDiff !== 0) return pinnedDiff
1458
+ const confidenceDiff = (CONFIDENCE_RANK.get(b.confidence) ?? 0) - (CONFIDENCE_RANK.get(a.confidence) ?? 0)
1459
+ if (confidenceDiff !== 0) return confidenceDiff
1460
+ const statusDiff = statusRankOf(b) - statusRankOf(a)
1461
+ if (statusDiff !== 0) return statusDiff
1462
+ const importanceDiff = (normalizeImportance(b.importance) ?? 0) - (normalizeImportance(a.importance) ?? 0)
1463
+ if (importanceDiff !== 0) return importanceDiff
1464
+ if (b.updatedAt !== a.updatedAt) return b.updatedAt - a.updatedAt
1465
+ return compareStrings(a.id, b.id)
1466
+ })
1467
+ const keep = new Set(ranked.slice(0, maxFacts).map(fact => fact.id))
1468
+ const factsNext = {}
1469
+ for (const fact of facts) {
1470
+ if (keep.has(fact.id)) factsNext[fact.id] = fact
1471
+ }
1472
+ return factsNext
1473
+ } catch {
1474
+ return {}
1475
+ }
1476
+ }
1477
+
1478
+ /**
1479
+ * 图统计(facts/active/superseded/rejected/archived/edges/scopes/isolated)。
1480
+ * @param {object} graph - 图(坏输入视为空图)。
1481
+ * @returns {{ facts: number, active: number, superseded: number, rejected: number, archived: number, edges: number, scopes: number, isolated: number }} 统计。
1482
+ */
1483
+ export function graphStats(graph) {
1484
+ try {
1485
+ const base = ensureGraph(graph)
1486
+ const facts = Object.values(base.facts)
1487
+ let active = 0
1488
+ let superseded = 0
1489
+ let rejected = 0
1490
+ let archived = 0
1491
+ for (const fact of facts) {
1492
+ if (fact.status === 'active') active += 1
1493
+ else if (fact.status === 'archived') archived += 1
1494
+ else if (fact.status === 'rejected') rejected += 1
1495
+ else superseded += 1
1496
+ }
1497
+ return { facts: facts.length, active, superseded, rejected, archived }
1498
+ } catch {
1499
+ return { facts: 0, active: 0, superseded: 0, rejected: 0, archived: 0 }
1500
+ }
1501
+ }
1502
+
1503
+ /* -------------------------------------------------------------------------- */
1504
+ /* 序列化 */
1505
+
1506
+ /**
1507
+ * 序列化事实(字段白名单,保证 JSON 安全、无 undefined/函数/循环)。
1508
+ * @param {object} fact - 归一化事实。
1509
+ * @returns {object} 可 JSON 化的事实快照。
1510
+ */
1511
+ function snapshotFact(fact) {
1512
+ const source = fact.source
1513
+ const sourceSnapshot = { cardId: source.cardId, turn: source.turn, at: source.at }
1514
+ if (typeof source.lineageKey === 'string' && source.lineageKey !== '') sourceSnapshot.lineageKey = source.lineageKey
1515
+ if (Array.isArray(source.seqs) && source.seqs.length > 0) sourceSnapshot.seqs = source.seqs.slice()
1516
+ if (typeof source.projectId === 'string' && source.projectId !== '') sourceSnapshot.projectId = source.projectId
1517
+ if (typeof source.sessionId === 'string' && source.sessionId !== '') sourceSnapshot.sessionId = source.sessionId
1518
+ return {
1519
+ id: fact.id,
1520
+ statement: fact.statement,
1521
+ kind: fact.kind,
1522
+ scopePath: fact.scopePath.slice(),
1523
+ entities: fact.entities.slice(),
1524
+ confidence: fact.confidence,
1525
+ source: sourceSnapshot,
1526
+ status: fact.status,
1527
+ projectId: fact.projectId,
1528
+ validFrom: fact.validFrom,
1529
+ validUntil: fact.validUntil,
1530
+ supersededBy: fact.supersededBy.slice(),
1531
+ conflictsWith: fact.conflictsWith.slice(),
1532
+ createdAt: fact.createdAt,
1533
+ updatedAt: fact.updatedAt,
1534
+ lastUsedAt: fact.lastUsedAt,
1535
+ hitCount: fact.hitCount,
1536
+ aliases: fact.aliases.slice(),
1537
+ ...(fact.pinned === true ? { pinned: true } : {}),
1538
+ ...(normalizeImportance(fact.importance) !== null ? { importance: normalizeImportance(fact.importance) } : {}),
1539
+ sources: fact.sources.map(item => {
1540
+ const snapshot = { cardId: item.cardId, turn: item.turn, at: item.at }
1541
+ if (typeof item.lineageKey === 'string' && item.lineageKey !== '') snapshot.lineageKey = item.lineageKey
1542
+ if (Array.isArray(item.seqs) && item.seqs.length > 0) snapshot.seqs = item.seqs.slice()
1543
+ if (typeof item.projectId === 'string' && item.projectId !== '') snapshot.projectId = item.projectId
1544
+ if (typeof item.sessionId === 'string' && item.sessionId !== '') snapshot.sessionId = item.sessionId
1545
+ return snapshot
1546
+ }),
1547
+ }
1548
+ }
1549
+ /* -------------------------------------------------------------------------- */
1550
+
1551
+ /**
1552
+ * 序列化为 JSON 安全的普通对象(字段白名单)。
1553
+ *
1554
+ * 输出形状:`{ version, facts: Fact[], edges: { [from]: Edge[] }, scopes, meta }`。
1555
+ * 与 `deserializeGraph` 互逆;可直接 `JSON.stringify` 落盘(宿主用 kg-store 处理原子写)。
1556
+ *
1557
+ * @param {object} graph - 图(坏输入视为空图)。
1558
+ * @returns {{ version: number, facts: object[], edges: object, scopes: object, meta: object }} 序列化快照。
1559
+ */
1560
+ export function serializeGraph(graph) {
1561
+ try {
1562
+ const base = ensureGraph(graph)
1563
+ const facts = Object.values(base.facts)
1564
+ .sort((a, b) => compareStrings(a.id, b.id))
1565
+ .map(snapshotFact)
1566
+ return {
1567
+ version: GRAPH_VERSION,
1568
+ facts,
1569
+ meta: { createdAt: base.meta.createdAt, updatedAt: base.meta.updatedAt, revision: base.meta.revision },
1570
+ }
1571
+ } catch {
1572
+ return { version: GRAPH_VERSION, facts: [], meta: { createdAt: 0, updatedAt: 0, revision: 0 } }
1573
+ }
1574
+ }
1575
+
1576
+ /**
1577
+ * 从序列化快照/JSON 字符串恢复图。
1578
+ *
1579
+ * 防御式:坏 JSON、非对象、版本不匹配 → 空图;非法事实跳过;悬空边丢弃;
1580
+ * 缺失边时按事实自动重建;事实数受 maxFacts 上限约束(超出只取前 N 条)。
1581
+ *
1582
+ * @param {unknown} raw - serializeGraph 输出、JSON 字符串或任意脏数据。
1583
+ * @param {object} [opts] - `{ maxFacts?, ...配置覆盖 }`。
1584
+ * @returns {object} 合法图(绝不抛出)。
1585
+ */
1586
+ export function deserializeGraph(raw, opts = {}) {
1587
+ try {
1588
+ const cfg = resolveConfig(opts)
1589
+ let data = raw
1590
+ if (typeof raw === 'string') {
1591
+ try {
1592
+ data = JSON.parse(raw)
1593
+ } catch {
1594
+ return emptyGraph()
1595
+ }
1596
+ }
1597
+ if (!isRecord(data)) return emptyGraph()
1598
+ if (Object.prototype.hasOwnProperty.call(data, 'version')) {
1599
+ const version = readNumber(data.version)
1600
+ if (version === null || Math.trunc(version) !== GRAPH_VERSION) return emptyGraph()
1601
+ }
1602
+
1603
+ const factsSource = isRecord(data.facts) ? Object.values(data.facts) : Array.isArray(data.facts) ? data.facts : []
1604
+ const facts = {}
1605
+ let factCount = 0
1606
+ for (const item of factsSource) {
1607
+ if (factCount >= cfg.maxFacts) break
1608
+ const fact = normalizeFactWithConfig(item, cfg)
1609
+ if (fact === null) continue
1610
+ if (facts[fact.id] !== undefined) continue
1611
+ facts[fact.id] = fact
1612
+ factCount += 1
1613
+ }
1614
+
1615
+ const metaSource = isRecord(data.meta) ? data.meta : {}
1616
+ const maxFactAt = maxUpdatedAtOf(facts)
1617
+ const createdAt = readTimestamp(metaSource.createdAt) ?? maxFactAt
1618
+ const updatedAt = readTimestamp(metaSource.updatedAt) ?? Math.max(createdAt, maxFactAt)
1619
+ const revision = readNonNegativeInt(metaSource.revision) ?? 0
1620
+ return {
1621
+ version: GRAPH_VERSION,
1622
+ facts,
1623
+ meta: { createdAt, updatedAt, revision },
1624
+ }
1625
+ } catch {
1626
+ return emptyGraph()
1627
+ }
1628
+ }