@jjh32456/longlive 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,662 @@
1
+ /**
2
+ * 链路直连快路径(2.1.0 / PLAN-v0.1 §6.14、PLAN-v0.4)。
3
+ *
4
+ * 职责边界(只读,不学习、不写文件、不碰会话):
5
+ * 1. 把 `.longlive/recall/links.jsonl` 读成内存边表 `term → [{cardPath, weight, source}]`;
6
+ * 每次 match 只 stat 文件,按 mtime+size 判缓存、按 sha256 判是否需要重建,
7
+ * 未变化不重读、不重建(mtime+sha 增量)。
8
+ * 2. 用户文本直接在边表上匹配:中文 term 走子串(大小写不敏感),
9
+ * 拉丁/ASCII term 走词边界(避免 `ace` 命中 `space`);命中按边权合并、
10
+ * 同卡只留最高权、单词 ≤5 张、全局 ≤5 张。
11
+ * 3. `readHits()` 用注入的 MemoryReader `getCard(path)` 直读正文(不回落索引扫描);
12
+ * 单卡读失败记 `error`,不抛。
13
+ * 4. links 缺失 / 空 / 坏行 >50% → `unavailable:true`(fail-visible),调用方回落全索引;
14
+ * bad 行按行计数跳过,不影响其余可用边。
15
+ *
16
+ * 与全索引链路口径的关系:行格式、卡路径归一化、weight 语义直接复用
17
+ * `links.mjs` 的 `parseLinksText` / `normalizeCardPath` / `LINKS_DEFAULTS`;
18
+ * 分数归一复用 `link-recall.mjs` 的 `linkScore`(0.5+0.5*score 由调用方做)。
19
+ *
20
+ * 隐私钩子:`privacyHook(item)` 在**合并前**调用(item={cardPath,term,weight,source});
21
+ * 显式返回 false / 'blocked' / 'local_only' / {blocked:true} / {allowed:false} 视为阻断,
22
+ * 抛错也按阻断处理(fail-closed);默认不注入 = 全部放行。
23
+ *
24
+ * @module recall/link-fastpath
25
+ */
26
+
27
+ import { createHash } from 'node:crypto';
28
+ import { readFileSync, statSync } from 'node:fs';
29
+ import { linkScore } from './link-recall.mjs';
30
+ import { LINKS_DEFAULTS, linksPaths, parseLinksText } from './links.mjs';
31
+
32
+ /** @typedef {{cardPath:string, term:string, weight:number, source:string}} LinkEdge */
33
+
34
+ export const LINK_FASTPATH_VERSION = 'link-fastpath/0.1.0';
35
+ export const LINK_FASTPATH_SCHEMA = 'link-fastpath/v1';
36
+
37
+ /** 与 links.mjs 同源默认值;匹配侧上限是硬顶 5(只能调小,不能调大)。 */
38
+ export const FASTPATH_DEFAULTS = Object.freeze({
39
+ minWeight: LINKS_DEFAULTS.minWeight,
40
+ maxCardsPerTerm: LINKS_DEFAULTS.maxCardsPerTerm,
41
+ maxCardsPerTurn: LINKS_DEFAULTS.maxCardsPerTurn,
42
+ corruptBadRatio: 0.5,
43
+ });
44
+
45
+ /** `unavailable` 的原因码(调用方据此决定回落方式)。 */
46
+ export const FASTPATH_REASONS = Object.freeze({
47
+ MISSING: 'links-missing',
48
+ EMPTY: 'links-empty',
49
+ CORRUPT: 'links-corrupt',
50
+ READ_ERROR: 'links-read-error',
51
+ });
52
+
53
+ const HARD_CAP_PER_TERM = 5;
54
+ const HARD_CAP_PER_TURN = 5;
55
+ // CJK(含假名/谚文/扩展 A/兼容区)→ 子串;其余 → 词边界。
56
+ const CJK_RE = /[\u3040-\u30FF\u3400-\u4DBF\u4E00-\u9FFF\uF900-\uFAFF]/u;
57
+
58
+ function hrtimeMs() {
59
+ return Number(process.hrtime.bigint()) / 1e6;
60
+ }
61
+
62
+ function round3(n) {
63
+ return Math.round(Number(n) * 1000) / 1000;
64
+ }
65
+
66
+ function sha256hex(text) {
67
+ return createHash('sha256').update(String(text ?? ''), 'utf8').digest('hex');
68
+ }
69
+
70
+ /** 码点计数(与 MemoryReader 的 chars 口径一致,代理对算 1)。 */
71
+ function codePointLength(text) {
72
+ const s = String(text ?? '');
73
+ let count = 0;
74
+ for (let i = 0; i < s.length; i += 1) {
75
+ const code = s.charCodeAt(i);
76
+ if (code >= 0xd800 && code <= 0xdbff && i + 1 < s.length) i += 1;
77
+ count += 1;
78
+ }
79
+ return count;
80
+ }
81
+
82
+ function fastpathError(code, message, extra = {}) {
83
+ const error = new Error(message);
84
+ error.code = code;
85
+ if (extra && typeof extra === 'object') Object.assign(error, extra);
86
+ return error;
87
+ }
88
+
89
+ function clampInt(value, min, max, fallback) {
90
+ const n = Number(value);
91
+ if (!Number.isFinite(n)) return fallback;
92
+ return Math.min(max, Math.max(min, Math.trunc(n)));
93
+ }
94
+
95
+ function escapeRegExp(text) {
96
+ return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
97
+ }
98
+
99
+ /** links.jsonl 的绝对路径(与 links.mjs 的 linksPaths 同源)。 */
100
+ export function linksFastPathFile(memoryRoot) {
101
+ if (typeof memoryRoot !== 'string' || memoryRoot.trim() === '') {
102
+ throw fastpathError('E_LINK_FASTPATH_ARG', 'linksFastPathFile 需要非空 memoryRoot');
103
+ }
104
+ return linksPaths(memoryRoot).file;
105
+ }
106
+
107
+ function resolveConfig(options = {}) {
108
+ const opts = options && typeof options === 'object' ? options : {};
109
+ const minWeightRaw = Number(opts.minWeight);
110
+ const minWeight = Number.isFinite(minWeightRaw) ? minWeightRaw : FASTPATH_DEFAULTS.minWeight;
111
+ const badRatioRaw = Number(opts.corruptBadRatio);
112
+ const corruptBadRatio = Number.isFinite(badRatioRaw)
113
+ ? Math.min(1, Math.max(0, badRatioRaw))
114
+ : FASTPATH_DEFAULTS.corruptBadRatio;
115
+ return {
116
+ minWeight,
117
+ // 硬顶 5:任务书要求单词 ≤5、全局 ≤5,调用方只能收紧。
118
+ maxCardsPerTerm: clampInt(opts.maxCardsPerTerm, 1, HARD_CAP_PER_TERM, FASTPATH_DEFAULTS.maxCardsPerTerm),
119
+ maxCardsPerTurn: clampInt(opts.maxCardsPerTurn, 1, HARD_CAP_PER_TURN, FASTPATH_DEFAULTS.maxCardsPerTurn),
120
+ corruptBadRatio,
121
+ privacyHook: typeof opts.privacyHook === 'function' ? opts.privacyHook : null,
122
+ };
123
+ }
124
+
125
+ /**
126
+ * term → 命中器。中文子串;其余词边界(含空格/符号的 term 按整串边界,
127
+ * 大小写不敏感)。与 links.mjs#termInText 对纯 ASCII term 完全同口径。
128
+ * @param {string} term
129
+ */
130
+ function buildMatcher(term) {
131
+ const needle = String(term ?? '');
132
+ if (CJK_RE.test(needle)) {
133
+ return { kind: 'cjk', needleLower: needle.toLowerCase(), regex: null };
134
+ }
135
+ return {
136
+ kind: 'latin',
137
+ needleLower: null,
138
+ regex: new RegExp(`(^|[^A-Za-z0-9_])${escapeRegExp(needle)}([^A-Za-z0-9_]|$)`, 'i'),
139
+ };
140
+ }
141
+
142
+ /**
143
+ * 由边数组建内存表。重复 (term,cardPath) 保留最高权;低于 minWeight 的边丢弃。
144
+ * @param {LinkEdge[]} edges
145
+ * @param {{minWeight?:number}} [options]
146
+ * @returns {{terms:object[], byTerm:Map<string,object>, termCount:number, edgeCount:number, skipped:number, minWeight:number}}
147
+ */
148
+ export function buildTermTable(edges, options = {}) {
149
+ const minWeight = Number.isFinite(Number(options?.minWeight))
150
+ ? Number(options.minWeight)
151
+ : FASTPATH_DEFAULTS.minWeight;
152
+ const byTerm = new Map();
153
+ let edgeCount = 0;
154
+ let skipped = 0;
155
+ const list = Array.isArray(edges) ? edges : [];
156
+ for (const edge of list) {
157
+ const term = typeof edge?.term === 'string' ? edge.term.trim() : '';
158
+ const cardPath = typeof edge?.cardPath === 'string' ? edge.cardPath.trim() : '';
159
+ const weight = Number(edge?.weight);
160
+ if (term === '' || cardPath === '' || !Number.isFinite(weight) || weight < minWeight) {
161
+ skipped += 1;
162
+ continue;
163
+ }
164
+ edgeCount += 1;
165
+ let bucket = byTerm.get(term);
166
+ if (!bucket) {
167
+ bucket = {
168
+ term,
169
+ ...buildMatcher(term),
170
+ entries: [],
171
+ byPath: new Map(),
172
+ bestWeight: 0,
173
+ };
174
+ byTerm.set(term, bucket);
175
+ }
176
+ const previous = bucket.byPath.get(cardPath);
177
+ if (previous) {
178
+ if (weight > previous.weight) {
179
+ previous.weight = weight;
180
+ previous.source = typeof edge.source === 'string' ? edge.source : previous.source;
181
+ }
182
+ continue;
183
+ }
184
+ const item = {
185
+ cardPath,
186
+ weight,
187
+ source: typeof edge.source === 'string' ? edge.source : 'seed',
188
+ };
189
+ bucket.byPath.set(cardPath, item);
190
+ bucket.entries.push(item);
191
+ if (weight > bucket.bestWeight) bucket.bestWeight = weight;
192
+ }
193
+ for (const bucket of byTerm.values()) {
194
+ bucket.entries.sort((a, b) => (b.weight - a.weight)
195
+ || (a.cardPath < b.cardPath ? -1 : a.cardPath > b.cardPath ? 1 : 0));
196
+ bucket.bestWeight = bucket.entries.length > 0 ? bucket.entries[0].weight : 0;
197
+ delete bucket.byPath; // 不再需要,释放内存
198
+ }
199
+ const terms = [...byTerm.values()].sort((a, b) => (b.term.length - a.term.length)
200
+ || (a.term < b.term ? -1 : a.term > b.term ? 1 : 0));
201
+ return {
202
+ terms,
203
+ byTerm,
204
+ termCount: terms.length,
205
+ edgeCount,
206
+ skipped,
207
+ minWeight,
208
+ };
209
+ }
210
+
211
+ function emptyStats() {
212
+ return {
213
+ textChars: 0,
214
+ termsHit: 0,
215
+ termsWithCards: 0,
216
+ candidates: 0,
217
+ cardsMerged: 0,
218
+ cardsReturned: 0,
219
+ droppedByCap: 0,
220
+ blockedByPrivacy: 0,
221
+ privacyErrors: 0,
222
+ matchMs: 0,
223
+ };
224
+ }
225
+
226
+ function isBlockedVerdict(verdict) {
227
+ if (verdict === false || verdict === 'blocked' || verdict === 'local_only') return true;
228
+ if (verdict && typeof verdict === 'object') {
229
+ if (verdict.blocked === true) return true;
230
+ if (verdict.allowed === false) return true;
231
+ }
232
+ return false;
233
+ }
234
+
235
+ /**
236
+ * 在内存表上匹配文本。纯函数:不改表、不做 IO。
237
+ * @param {string} text
238
+ * @param {ReturnType<typeof buildTermTable>|null} table
239
+ * @param {{maxCardsPerTerm?:number,maxCardsPerTurn?:number,privacyHook?:Function}} [options]
240
+ * @returns {{items:Array<{cardPath:string,term:string,weight:number,score:number}>, matchedTerms:string[], loaded:boolean, catalogScan:boolean, unavailable:boolean, reason:string|null, stats:object}}
241
+ */
242
+ export function matchText(text, table, options = {}) {
243
+ const started = hrtimeMs();
244
+ const config = resolveConfig(options);
245
+ const stats = emptyStats();
246
+ const source = typeof text === 'string' ? text : '';
247
+ stats.textChars = source.length;
248
+ const finish = (payload) => {
249
+ stats.matchMs = round3(hrtimeMs() - started);
250
+ return { ...payload, stats };
251
+ };
252
+ if (!table || !Array.isArray(table.terms)) {
253
+ return finish({
254
+ items: [],
255
+ matchedTerms: [],
256
+ loaded: false,
257
+ catalogScan: false,
258
+ unavailable: true,
259
+ reason: 'table-missing',
260
+ });
261
+ }
262
+ if (source === '') {
263
+ return finish({ items: [], matchedTerms: [], loaded: true, catalogScan: false, unavailable: false, reason: null });
264
+ }
265
+ const lower = source.toLowerCase();
266
+ const matched = [];
267
+ for (const bucket of table.terms) {
268
+ let hit = false;
269
+ if (bucket.kind === 'cjk') hit = lower.includes(bucket.needleLower);
270
+ else hit = bucket.regex.test(source);
271
+ if (!hit) continue;
272
+ const top = bucket.entries.slice(0, config.maxCardsPerTerm);
273
+ matched.push({ bucket, top, bestWeight: top.length > 0 ? top[0].weight : 0 });
274
+ stats.termsHit += 1;
275
+ if (top.length > 0) stats.termsWithCards += 1;
276
+ }
277
+ if (matched.length === 0) {
278
+ return finish({ items: [], matchedTerms: [], loaded: true, catalogScan: false, unavailable: false, reason: null });
279
+ }
280
+ // 输出顺序:长 term 先、同长按 bestWeight 降序(与 links.mjs#matchTerms 同向)。
281
+ matched.sort((a, b) => (b.bucket.term.length - a.bucket.term.length)
282
+ || (b.bestWeight - a.bestWeight)
283
+ || (a.bucket.term < b.bucket.term ? -1 : a.bucket.term > b.bucket.term ? 1 : 0));
284
+ const merged = new Map();
285
+ for (const bucket of matched) {
286
+ for (const candidate of bucket.top) {
287
+ stats.candidates += 1;
288
+ if (config.privacyHook) {
289
+ let blocked = false;
290
+ try {
291
+ blocked = isBlockedVerdict(config.privacyHook({
292
+ cardPath: candidate.cardPath,
293
+ term: bucket.bucket.term,
294
+ weight: candidate.weight,
295
+ source: candidate.source,
296
+ }));
297
+ } catch {
298
+ blocked = true;
299
+ stats.privacyErrors += 1;
300
+ }
301
+ if (blocked) {
302
+ stats.blockedByPrivacy += 1;
303
+ continue;
304
+ }
305
+ }
306
+ // 同卡只留最高权;等权时保留先到的(长 term 先到)。
307
+ const previous = merged.get(candidate.cardPath);
308
+ if (!previous || candidate.weight > previous.weight) {
309
+ merged.set(candidate.cardPath, {
310
+ cardPath: candidate.cardPath,
311
+ term: bucket.bucket.term,
312
+ weight: candidate.weight,
313
+ score: linkScore(candidate.weight),
314
+ });
315
+ }
316
+ }
317
+ }
318
+ stats.cardsMerged = merged.size;
319
+ const items = [...merged.values()].sort((a, b) => (b.weight - a.weight)
320
+ || (a.cardPath < b.cardPath ? -1 : a.cardPath > b.cardPath ? 1 : 0));
321
+ const capped = items.slice(0, config.maxCardsPerTurn);
322
+ stats.cardsReturned = capped.length;
323
+ stats.droppedByCap = items.length - capped.length;
324
+ const matchedTerms = matched
325
+ .map((entry) => entry.bucket.term)
326
+ .filter((term, index, arr) => arr.indexOf(term) === index);
327
+ return finish({
328
+ items: capped,
329
+ matchedTerms,
330
+ loaded: true,
331
+ catalogScan: false,
332
+ unavailable: false,
333
+ reason: null,
334
+ });
335
+ }
336
+
337
+ /**
338
+ * 用 MemoryReader 直读命中卡正文。单卡失败记 error,不抛;隐私/local_only 阻断由
339
+ * MemoryReader 返回(blocked:true → body:null),这里原样透传。
340
+ * @param {Array<{cardPath:string}|string>} items
341
+ * @param {{reader:{getCard:Function}}} context
342
+ * @returns {Array<{path:string,title:string|null,bodyChars:number,body:string|null,sha:string|null,ms:number,error?:object,blocked?:boolean,blockReason?:string|null}>}
343
+ */
344
+ export function readHits(items, context = {}) {
345
+ const list = Array.isArray(items) ? items : (items && typeof items === 'object' ? [items] : []);
346
+ const reader = context && typeof context === 'object' ? context.reader : null;
347
+ const rows = [];
348
+ for (const item of list) {
349
+ const cardPath = typeof item === 'string' ? item : String(item?.cardPath ?? '');
350
+ const started = hrtimeMs();
351
+ const base = {
352
+ path: cardPath,
353
+ title: null,
354
+ bodyChars: 0,
355
+ body: null,
356
+ sha: null,
357
+ ms: 0,
358
+ };
359
+ if (!reader || typeof reader.getCard !== 'function') {
360
+ rows.push({
361
+ ...base,
362
+ ms: round3(hrtimeMs() - started),
363
+ error: {
364
+ code: 'E_LINK_FASTPATH_READER_REQUIRED',
365
+ message: 'readHits 需要 { reader } 且 reader.getCard(path) 可用',
366
+ },
367
+ });
368
+ continue;
369
+ }
370
+ if (cardPath === '') {
371
+ rows.push({
372
+ ...base,
373
+ ms: round3(hrtimeMs() - started),
374
+ error: { code: 'E_LINK_FASTPATH_BAD_ITEM', message: 'item.cardPath 为空' },
375
+ });
376
+ continue;
377
+ }
378
+ try {
379
+ const card = reader.getCard(cardPath);
380
+ if (!card || typeof card !== 'object') {
381
+ throw fastpathError('E_LINK_FASTPATH_BAD_CARD', `getCard 返回非对象:${cardPath}`);
382
+ }
383
+ const blocked = card.blocked === true;
384
+ const body = typeof card.body === 'string' ? card.body : null;
385
+ const row = {
386
+ path: cardPath,
387
+ title: typeof card.title === 'string' ? card.title : null,
388
+ bodyChars: blocked || body === null ? 0 : codePointLength(body),
389
+ body: blocked ? null : body,
390
+ sha: typeof card.sha256 === 'string' ? card.sha256 : null,
391
+ ms: round3(hrtimeMs() - started),
392
+ };
393
+ if (blocked) {
394
+ row.blocked = true;
395
+ row.blockReason = typeof card.blockReason === 'string' ? card.blockReason : 'blocked';
396
+ }
397
+ rows.push(row);
398
+ } catch (error) {
399
+ rows.push({
400
+ ...base,
401
+ ms: round3(hrtimeMs() - started),
402
+ error: {
403
+ code: String(error?.code ?? 'E_LINK_FASTPATH_READ_FAILED'),
404
+ message: String(error?.message ?? error),
405
+ },
406
+ });
407
+ }
408
+ }
409
+ return rows;
410
+ }
411
+
412
+ /**
413
+ * 链路直连快路径:内存边表 + mtime/sha 增量刷新 + 隐私钩子。
414
+ * 每轮 `match()` 只 stat links.jsonl;内容未变不重读、不重建。
415
+ */
416
+ export class LinkFastPath {
417
+ /**
418
+ * @param {string} memoryRoot 记忆根绝对路径
419
+ * @param {{linksPath?:string,minWeight?:number,maxCardsPerTerm?:number,maxCardsPerTurn?:number,corruptBadRatio?:number,privacyHook?:Function}} [options]
420
+ */
421
+ constructor(memoryRoot, options = {}) {
422
+ if (typeof memoryRoot !== 'string' || memoryRoot.trim() === '') {
423
+ throw fastpathError('E_LINK_FASTPATH_ARG', 'LinkFastPath 需要非空 memoryRoot');
424
+ }
425
+ const config = resolveConfig(options);
426
+ this.memoryRoot = memoryRoot;
427
+ this.linksPath = typeof options.linksPath === 'string' && options.linksPath.trim() !== ''
428
+ ? options.linksPath
429
+ : linksFastPathFile(memoryRoot);
430
+ this.config = config;
431
+ this._cache = null; // { key, sha256, mtimeMs, size, table, status, loadedAtMs }
432
+ this._everLoaded = false;
433
+ this._stats = {
434
+ loads: 0,
435
+ reloads: 0,
436
+ reads: 0,
437
+ touched: 0,
438
+ unchanged: 0,
439
+ missing: 0,
440
+ matches: 0,
441
+ loadMsTotal: 0,
442
+ lastLoadMs: 0,
443
+ lastMode: null,
444
+ lastReason: null,
445
+ lastMatchMs: 0,
446
+ };
447
+ }
448
+
449
+ /** 当前边表快照(不触发 IO)。 */
450
+ status() {
451
+ const cache = this._cache;
452
+ return {
453
+ version: LINK_FASTPATH_VERSION,
454
+ schema: LINK_FASTPATH_SCHEMA,
455
+ path: this.linksPath,
456
+ loadedOnce: this._everLoaded,
457
+ loaded: Boolean(cache && cache.status.loaded),
458
+ unavailable: cache ? Boolean(cache.status.unavailable) : null,
459
+ reason: cache ? cache.status.reason : null,
460
+ mode: cache ? cache.status.mode : null,
461
+ sha256: cache ? cache.sha256 : null,
462
+ bytes: cache ? cache.size : 0,
463
+ mtimeMs: cache ? cache.mtimeMs : 0,
464
+ lines: cache ? cache.status.lines : 0,
465
+ bad: cache ? cache.status.bad : 0,
466
+ badRatio: cache ? cache.status.badRatio : 0,
467
+ duplicates: cache ? cache.status.duplicates : 0,
468
+ edges: cache ? cache.status.edges : 0,
469
+ parsedEdges: cache ? cache.status.parsedEdges : 0,
470
+ terms: cache ? cache.status.terms : 0,
471
+ };
472
+ }
473
+
474
+ /** 计数器快照(reads/unchanged/reloads 用于证明「不每轮读文件」)。 */
475
+ stats() {
476
+ return {
477
+ ...this._stats,
478
+ config: { ...this.config },
479
+ status: this.status(),
480
+ };
481
+ }
482
+
483
+ /**
484
+ * 确保边表就绪:stat → mtime+size 命中直接复用;内容变化才重读,
485
+ * sha 未变只更新 mtime(touched),不重建表。
486
+ * @returns {object} 加载状态(loaded/unavailable/reason/mode/...)
487
+ */
488
+ ensureLoaded() {
489
+ const started = hrtimeMs();
490
+ let stat = null;
491
+ try {
492
+ stat = statSync(this.linksPath);
493
+ } catch {
494
+ stat = null;
495
+ }
496
+ const finish = (status) => {
497
+ const loadMs = round3(hrtimeMs() - started);
498
+ this._stats.lastLoadMs = loadMs;
499
+ this._stats.loadMsTotal = round3(this._stats.loadMsTotal + loadMs);
500
+ this._stats.lastMode = status.mode;
501
+ this._stats.lastReason = status.reason;
502
+ return { ...status, loadMs };
503
+ };
504
+ if (!stat || !stat.isFile()) {
505
+ this._cache = null;
506
+ this._stats.missing += 1;
507
+ return finish({
508
+ loaded: false,
509
+ unavailable: true,
510
+ reason: FASTPATH_REASONS.MISSING,
511
+ mode: 'missing',
512
+ path: this.linksPath,
513
+ sha256: null,
514
+ bytes: 0,
515
+ mtimeMs: 0,
516
+ size: 0,
517
+ lines: 0,
518
+ bad: 0,
519
+ badRatio: 0,
520
+ duplicates: 0,
521
+ edges: 0,
522
+ parsedEdges: 0,
523
+ terms: 0,
524
+ error: null,
525
+ });
526
+ }
527
+ const key = `${stat.mtimeMs}:${stat.size}`;
528
+ if (this._cache && this._cache.key === key) {
529
+ this._stats.unchanged += 1;
530
+ return finish({ ...this._cache.status, mode: 'unchanged' });
531
+ }
532
+ let text = null;
533
+ try {
534
+ text = readFileSync(this.linksPath, 'utf8');
535
+ } catch (error) {
536
+ this._cache = null;
537
+ return finish({
538
+ loaded: false,
539
+ unavailable: true,
540
+ reason: FASTPATH_REASONS.READ_ERROR,
541
+ mode: 'read-error',
542
+ path: this.linksPath,
543
+ sha256: null,
544
+ bytes: 0,
545
+ mtimeMs: stat.mtimeMs,
546
+ size: stat.size,
547
+ lines: 0,
548
+ bad: 0,
549
+ badRatio: 0,
550
+ duplicates: 0,
551
+ edges: 0,
552
+ parsedEdges: 0,
553
+ terms: 0,
554
+ error: { code: String(error?.code ?? 'E_LINK_FASTPATH_READ'), message: String(error?.message ?? error) },
555
+ });
556
+ }
557
+ this._stats.reads += 1;
558
+ const sha256 = sha256hex(text);
559
+ if (this._cache && this._cache.sha256 === sha256) {
560
+ // mtime/size 变了但内容没变:只刷新 stat 缓存,不重建表。
561
+ this._cache.key = key;
562
+ this._cache.mtimeMs = stat.mtimeMs;
563
+ this._cache.size = stat.size;
564
+ this._stats.touched += 1;
565
+ return finish({ ...this._cache.status, mode: 'touched' });
566
+ }
567
+ const parsed = parseLinksText(text, { memoryRoot: this.memoryRoot });
568
+ const lines = parsed.lines;
569
+ const bad = parsed.bad;
570
+ const badRatio = lines > 0 ? bad / lines : 0;
571
+ const bytes = Buffer.byteLength(text, 'utf8');
572
+ let table = null;
573
+ let loaded = false;
574
+ let unavailable = false;
575
+ let reason = null;
576
+ let mode = 'loaded';
577
+ if (lines === 0) {
578
+ unavailable = true;
579
+ reason = FASTPATH_REASONS.EMPTY;
580
+ mode = 'empty';
581
+ } else if (badRatio > this.config.corruptBadRatio) {
582
+ unavailable = true;
583
+ reason = FASTPATH_REASONS.CORRUPT;
584
+ mode = 'corrupt';
585
+ } else {
586
+ table = buildTermTable(parsed.edges, { minWeight: this.config.minWeight });
587
+ loaded = true;
588
+ }
589
+ const status = {
590
+ loaded,
591
+ unavailable,
592
+ reason,
593
+ mode,
594
+ path: this.linksPath,
595
+ sha256,
596
+ bytes,
597
+ mtimeMs: stat.mtimeMs,
598
+ size: stat.size,
599
+ lines,
600
+ bad,
601
+ badRatio: round3(badRatio),
602
+ duplicates: parsed.duplicates,
603
+ edges: table ? table.edgeCount : parsed.edges.length,
604
+ parsedEdges: parsed.edges.length,
605
+ terms: table ? table.termCount : 0,
606
+ error: null,
607
+ };
608
+ this._cache = {
609
+ key,
610
+ sha256,
611
+ mtimeMs: stat.mtimeMs,
612
+ size: stat.size,
613
+ table,
614
+ status,
615
+ loadedAtMs: Date.now(),
616
+ };
617
+ this._stats.loads += 1;
618
+ if (this._everLoaded) this._stats.reloads += 1;
619
+ this._everLoaded = true;
620
+ return finish(status);
621
+ }
622
+
623
+ /**
624
+ * 匹配用户文本并返回命中卡。links 不可用时返回 `unavailable:true`,
625
+ * 由调用方回落全索引/关键词/向量链路。
626
+ * @param {string} text
627
+ * @param {{maxCardsPerTerm?:number,maxCardsPerTurn?:number,privacyHook?:Function}} [options]
628
+ */
629
+ match(text, options = {}) {
630
+ this._stats.matches += 1;
631
+ const status = this.ensureLoaded();
632
+ const merged = {
633
+ maxCardsPerTerm: options.maxCardsPerTerm ?? this.config.maxCardsPerTerm,
634
+ maxCardsPerTurn: options.maxCardsPerTurn ?? this.config.maxCardsPerTurn,
635
+ privacyHook: options.privacyHook ?? this.config.privacyHook,
636
+ };
637
+ if (!status.loaded || status.unavailable || !this._cache || !this._cache.table) {
638
+ this._stats.lastMatchMs = 0;
639
+ return {
640
+ items: [],
641
+ matchedTerms: [],
642
+ loaded: false,
643
+ catalogScan: false,
644
+ unavailable: true,
645
+ reason: status.reason,
646
+ stats: {
647
+ ...emptyStats(),
648
+ textChars: typeof text === 'string' ? text.length : 0,
649
+ loadMode: status.mode,
650
+ loadMs: status.loadMs,
651
+ },
652
+ };
653
+ }
654
+ const result = matchText(text, this._cache.table, merged);
655
+ result.stats.loadMode = status.mode;
656
+ result.stats.loadMs = status.loadMs;
657
+ this._stats.lastMatchMs = result.stats.matchMs;
658
+ return result;
659
+ }
660
+ }
661
+
662
+ export default { LinkFastPath, readHits, matchText, buildTermTable, linksFastPathFile, FASTPATH_DEFAULTS, FASTPATH_REASONS, LINK_FASTPATH_VERSION };
@@ -416,6 +416,33 @@ export function maxCosine(queryVector, vectorList) {
416
416
  return best === -1 ? 0 : best;
417
417
  }
418
418
 
419
+ /**
420
+ * chooseRecall 的「零候选」返回形状(hits 统计键与 chooseRecall 首段完全一致)。
421
+ * 2.1.0 链路直连:fastpath 命中时跳过 chooseRecall,但仍要产出同样的 result 形状给
422
+ * 下游审计/预算记账使用(eligible=0、无候选),保证行为与统计口径不出现 undefined。
423
+ * @param {{contextBoosted?:boolean}} [options] queryTimeRefs/实体别名存在时补 contextBoosted=0
424
+ * @returns {{items:[],tokens:0,hits:object,rejections:[]}}
425
+ */
426
+ export function emptyRecallResult({ contextBoosted = false } = {}) {
427
+ const stats = {
428
+ eligible: 0,
429
+ injected: 0,
430
+ phrases: [],
431
+ best: null,
432
+ droppedByBudget: 0,
433
+ droppedByDedupe: 0,
434
+ droppedBySeen: 0,
435
+ droppedLocalOnly: 0,
436
+ droppedByPrivacy: 0,
437
+ redactedByPrivacy: 0,
438
+ semanticCandidates: 0,
439
+ semanticAdmitted: 0,
440
+ droppedByLowTrust: 0,
441
+ };
442
+ if (contextBoosted) stats.contextBoosted = 0;
443
+ return { items: [], tokens: 0, hits: stats, rejections: [] };
444
+ }
445
+
419
446
  /* ------------------------------------------------------------------ *
420
447
  * 4. 主函数(纯)
421
448
  * ------------------------------------------------------------------ */