@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,1003 @@
1
+ /* eslint-disable no-console */
2
+ /**
3
+ * 长活记忆 2.1.0 · MemoryReader(读取层)
4
+ *
5
+ * 目标(PLAN-v0.2 §3.3 / §6.13,验收 #8):
6
+ * - 一份卡索引 `<memoryRoot>/.longlive/index/cards.idx.json`(schema `cards.idx/v1`),
7
+ * 覆盖 `topics/ journal/ procedures/ handover/` 四类 Markdown;
8
+ * - 启动全量建索引,之后按 mtime + sha256 增量更新;索引缺失/损坏自动全量重建且计数可见;
9
+ * - `getCard(path)` 读正文(剥离 frontmatter)、校验 sha、只读不写回、隐私扫描可阻断;
10
+ * - `search(query,{lanes,limit})` 关键词车道复用 recall-core 的 `phraseWeight` 与
11
+ * coverage 公式;正文车道为 opt-in;
12
+ * - `listLanes()/stats()` 暴露四类卡计数、建索引耗时、重建次数。
13
+ *
14
+ * 本文件属于读取层,不改 recall 注入接线;`src/recall/index.js` 的接线在后续 lane 完成。
15
+ *
16
+ * 边界(写进 REPORT 的「已知边界」):
17
+ * 1. 索引只记录 mtime;外部改写文件但保留 mtime 的极端情况探测不到(下一次全量重建可纠正)。
18
+ * 2. `getCard` 只报 `shaMatch:false`,不自动修补索引——修补统一走 `ensureIndex()`,读路径不写盘。
19
+ * 3. `body` 车道要读全部卡正文,成本高,默认不开;关键词车道只读索引。
20
+ * 4. `links` / `vector` 车道未实现,显式抛 `E_READER_LANE_UNAVAILABLE`,不静默退化。
21
+ * 5. 索引写入是原子替换(tmp + rename),并发读者可能各写一次相同内容(last write wins,内容一致)。
22
+ */
23
+
24
+ import fs from 'node:fs';
25
+ import path from 'node:path';
26
+ import { createHash } from 'node:crypto';
27
+
28
+ import { parseFrontmatter } from './frontmatter.js';
29
+ import { memoryError, PATH_CODES, resolveInside } from './paths.js';
30
+ import { phraseWeight } from '../recall/recall-core.mjs';
31
+ import { privacyScan as defaultPrivacyScan } from '../recall/privacy.mjs';
32
+
33
+ /* ---------------- 常量 ---------------- */
34
+
35
+ export const READER_VERSION = 'memory-reader/0.1.0';
36
+ export const INDEX_SCHEMA = 'cards.idx/v1';
37
+ export const INDEX_REL_PATH = '.longlive/index/cards.idx.json';
38
+
39
+ /** 目录名 → 卡 kind。索引/搜索只认这四个目录(其他目录不扫)。 */
40
+ export const READER_DIRS = Object.freeze({
41
+ topics: 'topic',
42
+ journal: 'journal',
43
+ procedures: 'procedure',
44
+ handover: 'handover',
45
+ });
46
+
47
+ export const READER_KINDS = Object.freeze(['topic', 'journal', 'procedure', 'handover']);
48
+
49
+ const CARD_EXT = '.md';
50
+ const MAX_INDEX_ERRORS = 200;
51
+ const MAX_INDEX_FILE_BYTES = 64 * 1024 * 1024;
52
+ const DEFAULT_MAX_FILE_BYTES = 8 * 1024 * 1024;
53
+ const MAX_WALK_DEPTH = 8;
54
+
55
+ /** 读取层错误码(全部 fail-closed,不返回空成功)。 */
56
+ const READER_CODES = Object.freeze({
57
+ BAD_ARGUMENT: 'E_READER_BAD_ARGUMENT',
58
+ INDEX_CORRUPT: 'E_READER_INDEX_CORRUPT',
59
+ INDEX_WRITE: 'E_READER_INDEX_WRITE',
60
+ NOT_CARD_DIR: 'E_READER_NOT_CARD_DIR',
61
+ CARD_NOT_FOUND: 'E_READER_CARD_NOT_FOUND',
62
+ READ_FAILED: 'E_READER_READ_FAILED',
63
+ FILE_TOO_LARGE: 'E_READER_FILE_TOO_LARGE',
64
+ EMPTY_QUERY: 'E_READER_EMPTY_QUERY',
65
+ QUERY_TOO_LONG: 'E_READER_QUERY_TOO_LONG',
66
+ LANE_UNAVAILABLE: 'E_READER_LANE_UNAVAILABLE',
67
+ SCAN_FAILED: 'E_READER_SCAN_FAILED',
68
+ });
69
+
70
+ const LANES = Object.freeze({
71
+ keyword: { id: 'keyword', status: 'ready', fields: ['path', 'kind', 'title', 'score', 'chars'], readsBodies: false, source: 'cards.idx.json(title/tags/aliases/scope)' },
72
+ body: { id: 'body', status: 'ready', fields: ['path', 'kind', 'title', 'score', 'chars'], readsBodies: true, source: '卡片正文(逐卡读取,跳过 local_only)' },
73
+ links: { id: 'links', status: 'not_implemented', fields: ['path', 'kind', 'title', 'score', 'chars'], readsBodies: false, source: 'links.jsonl 边表(由后续 lane 落地)' },
74
+ vector: { id: 'vector', status: 'not_implemented', fields: ['path', 'kind', 'title', 'score', 'chars'], readsBodies: false, source: '向量车道(未实现)' },
75
+ });
76
+
77
+ const DEFAULT_LANES = Object.freeze(['keyword']);
78
+
79
+ /* ---------------- 小工具 ---------------- */
80
+
81
+ function sha256(buf) {
82
+ return createHash('sha256').update(buf).digest('hex');
83
+ }
84
+
85
+ /** 按 Unicode 码点数计数(与 Buffer.byteLength 不同,中文/emoji 一视同仁)。 */
86
+ function charCount(text) {
87
+ let count = 0;
88
+ for (const _ of text) count += 1;
89
+ return count;
90
+ }
91
+
92
+ function isPlainObject(value) {
93
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
94
+ }
95
+
96
+ function normalizeStats(raw) {
97
+ const base = isPlainObject(raw) ? raw : {};
98
+ const num = (value) => (Number.isFinite(value) && value >= 0 ? value : 0);
99
+ return {
100
+ fullBuilds: num(base.fullBuilds),
101
+ rebuilds: num(base.rebuilds),
102
+ updates: num(base.updates),
103
+ writes: num(base.writes),
104
+ buildMs: num(base.buildMs),
105
+ };
106
+ }
107
+
108
+ function normalizeErrors(raw) {
109
+ if (!Array.isArray(raw)) return [];
110
+ const out = [];
111
+ for (const item of raw) {
112
+ if (!isPlainObject(item)) continue;
113
+ const filePath = typeof item.path === 'string' ? item.path : '';
114
+ if (!filePath) continue;
115
+ out.push({
116
+ path: filePath,
117
+ code: typeof item.code === 'string' ? item.code : 'E_READER_UNKNOWN',
118
+ message: typeof item.message === 'string' ? item.message : '',
119
+ });
120
+ }
121
+ out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
122
+ return out.slice(0, MAX_INDEX_ERRORS);
123
+ }
124
+
125
+ function normalizeEntries(raw) {
126
+ if (!Array.isArray(raw)) return [];
127
+ const seen = new Set();
128
+ const out = [];
129
+ for (const item of raw) {
130
+ if (!isPlainObject(item)) continue;
131
+ const relPath = typeof item.path === 'string' ? item.path.replace(/\\/g, '/') : '';
132
+ if (!relPath || relPath.startsWith('.') || relPath.split('/').some((seg) => seg === '..' || seg === '')) continue;
133
+ const head = relPath.split('/')[0];
134
+ const kind = READER_DIRS[head];
135
+ if (!kind) continue;
136
+ const digest = typeof item.sha256 === 'string' ? item.sha256.toLowerCase() : '';
137
+ if (!/^[0-9a-f]{64}$/.test(digest)) continue;
138
+ const key = `${kind}:${relPath}`;
139
+ if (seen.has(key)) continue;
140
+ seen.add(key);
141
+ out.push({
142
+ path: relPath,
143
+ kind,
144
+ sha256: digest,
145
+ mtime: Number.isFinite(item.mtime) ? item.mtime : 0,
146
+ title: typeof item.title === 'string' ? item.title : null,
147
+ tags: Array.isArray(item.tags) ? item.tags.filter((tag) => typeof tag === 'string') : [],
148
+ aliases: Array.isArray(item.aliases) ? item.aliases.filter((alias) => typeof alias === 'string') : [],
149
+ scope: typeof item.scope === 'string' ? item.scope : null,
150
+ chars: Number.isFinite(item.chars) && item.chars >= 0 ? item.chars : 0,
151
+ });
152
+ }
153
+ return out;
154
+ }
155
+
156
+ function normalizeIndex(raw) {
157
+ return {
158
+ schema: INDEX_SCHEMA,
159
+ generatedBy: typeof raw.generatedBy === 'string' ? raw.generatedBy : READER_VERSION,
160
+ builtAt: typeof raw.builtAt === 'string' ? raw.builtAt : new Date().toISOString(),
161
+ stats: normalizeStats(raw.stats),
162
+ entries: normalizeEntries(raw.entries),
163
+ errors: normalizeErrors(raw.errors),
164
+ };
165
+ }
166
+
167
+ function parseListValue(raw) {
168
+ if (raw == null) return [];
169
+ const value = String(raw).trim();
170
+ if (!value) return [];
171
+ let items;
172
+ if (value.startsWith('[') && value.endsWith(']')) {
173
+ items = value.slice(1, -1).split(',');
174
+ } else {
175
+ items = value.split(',');
176
+ }
177
+ const out = [];
178
+ for (const item of items) {
179
+ let text = item.trim();
180
+ if (
181
+ (text.startsWith('"') && text.endsWith('"') && text.length >= 2) ||
182
+ (text.startsWith("'") && text.endsWith("'") && text.length >= 2)
183
+ ) {
184
+ text = text.slice(1, -1).trim();
185
+ }
186
+ if (text) out.push(text);
187
+ }
188
+ return out;
189
+ }
190
+
191
+ /**
192
+ * frontmatter 里的 local_only / localOnly / local 只要像 true 就阻断。
193
+ * 解析失败(parsed === null)时退到原文行匹配:坏卡也不能因为「解析不了」
194
+ * 就把 local_only 漏成明文。
195
+ */
196
+ function isLocalOnly(parsed, rawText = '') {
197
+ if (!parsed) {
198
+ return /^[ \t]*local_?only[ \t]*:[ \t]*(true|1|yes|on)[ \t]*$/im.test(String(rawText ?? ''));
199
+ }
200
+ const extras = parsed.extras ?? {};
201
+ const raw = extras.local_only ?? extras.localOnly ?? extras.local;
202
+ if (raw == null) return false;
203
+ const text = String(raw).trim().toLowerCase();
204
+ return text === 'true' || text === '1' || text === 'yes' || text === 'on';
205
+ }
206
+
207
+ function entryFromDisk(absPath, relPath, kind, mtime, buffer, maxFileBytes) {
208
+ if (buffer.length > maxFileBytes) {
209
+ return {
210
+ entry: null,
211
+ error: { path: relPath, code: READER_CODES.FILE_TOO_LARGE, message: `卡片 ${buffer.length}B 超过上限 ${maxFileBytes}B` },
212
+ };
213
+ }
214
+ const text = buffer.toString('utf8');
215
+ let parsed = null;
216
+ let parseError = null;
217
+ try {
218
+ parsed = parseFrontmatter(text);
219
+ } catch (error) {
220
+ parseError = {
221
+ path: relPath,
222
+ code: error?.code ?? 'E_FRONTMATTER_PARSE',
223
+ message: error?.message ?? String(error),
224
+ };
225
+ }
226
+ const fields = parsed?.fields ?? {};
227
+ const body = parseError ? text : (parsed.body ?? '');
228
+ const title = (typeof fields.title === 'string' && fields.title.trim()) || path.basename(relPath, CARD_EXT);
229
+ const extras = parsed?.extras ?? {};
230
+ return {
231
+ entry: {
232
+ path: relPath,
233
+ kind,
234
+ sha256: sha256(buffer),
235
+ mtime,
236
+ title,
237
+ tags: Array.isArray(fields.tags) ? fields.tags : [],
238
+ aliases: parseListValue(extras.scope_aliases ?? extras.aliases),
239
+ scope: typeof fields.scope === 'string' ? fields.scope : null,
240
+ chars: charCount(body),
241
+ },
242
+ error: parseError,
243
+ };
244
+ }
245
+
246
+ function makeStats(overrides = {}) {
247
+ return {
248
+ fullBuilds: 0,
249
+ rebuilds: 0,
250
+ updates: 0,
251
+ writes: 0,
252
+ buildMs: 0,
253
+ ...overrides,
254
+ };
255
+ }
256
+
257
+ /* ---------------- MemoryReader ---------------- */
258
+
259
+ export class MemoryReader {
260
+ /**
261
+ * @param {string} memoryRoot 记忆根(绝对或相对路径)
262
+ * @param {object} [options]
263
+ * @param {true|false|Function} [options.privacyScan=true] 读卡时默认隐私扫描:true 用内置
264
+ * `privacy.mjs`;false 关闭(只在明确要求时);函数则自定义 `(text)=>verdict`。
265
+ * @param {string} [options.indexPath] 覆盖索引路径(测试/迁移用),默认 memoryRoot 内。
266
+ * @param {number} [options.maxFileBytes] 单卡上限,默认 8 MiB,超限记错误不索引。
267
+ * @param {() => Date|number|string} [options.now] 注入时钟(测试用)。
268
+ */
269
+ constructor(memoryRoot, options = {}) {
270
+ if (typeof memoryRoot !== 'string' || memoryRoot.trim() === '') {
271
+ throw memoryError(READER_CODES.BAD_ARGUMENT, 'MemoryReader 需要非空 memoryRoot');
272
+ }
273
+ if (!isPlainObject(options)) {
274
+ throw memoryError(READER_CODES.BAD_ARGUMENT, 'MemoryReader options 必须是对象');
275
+ }
276
+ const maxFileBytes = options.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES;
277
+ if (!Number.isFinite(maxFileBytes) || maxFileBytes <= 0) {
278
+ throw memoryError(READER_CODES.BAD_ARGUMENT, 'maxFileBytes 必须是正数');
279
+ }
280
+ this.root = path.resolve(memoryRoot);
281
+ this.maxFileBytes = maxFileBytes;
282
+ this._privacyOption = options.privacyScan === undefined ? true : options.privacyScan;
283
+ if (
284
+ this._privacyOption !== true &&
285
+ this._privacyOption !== false &&
286
+ typeof this._privacyOption !== 'function'
287
+ ) {
288
+ throw memoryError(READER_CODES.BAD_ARGUMENT, 'privacyScan 只能是 true / false / 函数');
289
+ }
290
+ this.indexPath = options.indexPath
291
+ ? path.resolve(String(options.indexPath))
292
+ : path.join(this.root, ...INDEX_REL_PATH.split('/'));
293
+ this._now = typeof options.now === 'function' ? options.now : () => new Date();
294
+ this._index = null;
295
+ this._stats = {
296
+ ensureCalls: 0,
297
+ lastEnsureMs: 0,
298
+ lastMode: null,
299
+ lastReason: null,
300
+ reads: 0,
301
+ readMsTotal: 0,
302
+ readMsMax: 0,
303
+ readMsLast: 0,
304
+ searches: 0,
305
+ searchMsLast: 0,
306
+ };
307
+ }
308
+
309
+ /* -------- 公共 API -------- */
310
+
311
+ /**
312
+ * 保证索引可用:每次调用先重读索引文件,再按 mtime+sha 做增量;
313
+ * 索引缺失 → 全量建(不计 rebuild);索引损坏/不合法 → 自动全量重建并计 rebuild。
314
+ * @returns {ReturnType<MemoryReader['_resultPayload']>}
315
+ */
316
+ ensureIndex() {
317
+ const startedAt = process.hrtime.bigint();
318
+ this._stats.ensureCalls += 1;
319
+ this._assertRoot();
320
+
321
+ const loaded = this._loadIndexFile();
322
+ let index;
323
+ let mode;
324
+ let reason;
325
+ let rebuild = false;
326
+ let delta = { added: 0, updated: 0, touched: 0, removed: 0 };
327
+
328
+ if (loaded.ok) {
329
+ const result = this._updateFromDisk(loaded.index);
330
+ index = result.index;
331
+ delta = result.delta;
332
+ mode = result.changed ? 'incremental' : 'unchanged';
333
+ reason = loaded.reason ?? null;
334
+ } else {
335
+ rebuild = !loaded.missing;
336
+ reason = loaded.reason;
337
+ mode = 'full';
338
+ const built = this._fullBuild(reason, { rebuild, priorStats: loaded.raw?.stats });
339
+ index = built.index;
340
+ delta = built.delta;
341
+ }
342
+
343
+ const elapsedMs = Number(process.hrtime.bigint() - startedAt) / 1e6;
344
+ this._index = index;
345
+ this._stats.lastEnsureMs = Math.round(elapsedMs * 1000) / 1000;
346
+ this._stats.lastMode = mode;
347
+ this._stats.lastReason = reason ?? null;
348
+ return this._resultPayload(index, { mode, reason, rebuild, delta });
349
+ }
350
+
351
+ /** 显式全量重建(维护/修复入口)。 */
352
+ rebuild(reason = 'manual') {
353
+ this._assertRoot();
354
+ const loaded = this._loadIndexFile();
355
+ const built = this._fullBuild(reason, {
356
+ rebuild: false,
357
+ priorStats: loaded.raw?.stats ?? this._index?.stats,
358
+ });
359
+ this._index = built.index;
360
+ return this._resultPayload(built.index, {
361
+ mode: 'full',
362
+ reason,
363
+ rebuild: false,
364
+ delta: built.delta,
365
+ });
366
+ }
367
+
368
+ /** 启动预热:等价 `ensureIndex()`,名字留给接线方表达意图。 */
369
+ warmup() {
370
+ return this.ensureIndex();
371
+ }
372
+
373
+ /**
374
+ * 读取一张卡:剥离 frontmatter 的正文 + sha256 校验 + 隐私/local_only 阻断。只读,不写回。
375
+ * @param {string} cardPath 记忆根内相对路径(也接受根内绝对路径)
376
+ * @param {object} [options] `{privacyScan}` 覆盖本实例默认值
377
+ */
378
+ getCard(cardPath, options = {}) {
379
+ this._assertRoot();
380
+ const resolved = this._resolveCardPath(cardPath);
381
+ const relPath = path.relative(this.root, resolved).replace(/\\/g, '/');
382
+ const kind = this._kindOf(relPath);
383
+ if (!kind) {
384
+ throw memoryError(
385
+ READER_CODES.NOT_CARD_DIR,
386
+ `getCard 只接受 topics/journal/procedures/handover 下的卡:${relPath}`,
387
+ );
388
+ }
389
+ this._ensureLoaded();
390
+
391
+ const startedAt = process.hrtime.bigint();
392
+ let buffer;
393
+ try {
394
+ buffer = fs.readFileSync(resolved);
395
+ } catch (error) {
396
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') {
397
+ throw memoryError(READER_CODES.CARD_NOT_FOUND, `卡片不存在:${relPath}`, error);
398
+ }
399
+ throw memoryError(READER_CODES.READ_FAILED, `读卡失败:${relPath}: ${error?.message ?? error}`, error);
400
+ }
401
+ if (buffer.length > this.maxFileBytes) {
402
+ throw memoryError(
403
+ READER_CODES.FILE_TOO_LARGE,
404
+ `卡片 ${relPath} 为 ${buffer.length}B,超过上限 ${this.maxFileBytes}B`,
405
+ );
406
+ }
407
+
408
+ const text = buffer.toString('utf8');
409
+ const digest = sha256(buffer);
410
+ let parsed = null;
411
+ let parseError = null;
412
+ try {
413
+ parsed = parseFrontmatter(text);
414
+ } catch (error) {
415
+ parseError = { code: error?.code ?? 'E_FRONTMATTER_PARSE', message: error?.message ?? String(error) };
416
+ }
417
+
418
+ const fields = parsed?.fields ?? {};
419
+ const title = (typeof fields.title === 'string' && fields.title.trim()) || path.basename(relPath, CARD_EXT);
420
+ const body = parsed ? parsed.body ?? '' : text;
421
+ const localOnly = isLocalOnly(parsed, text);
422
+ const scan = this._resolvePrivacyScan(options);
423
+ const privacy = scan ? scan(`${title}\n${body}`) : null;
424
+ const privacyBlocked = privacy?.verdict === 'local_only';
425
+ const blocked = localOnly || privacyBlocked;
426
+
427
+ const entry = this._index?.entries.find((item) => item.path === relPath) ?? null;
428
+ const elapsedMs = Number(process.hrtime.bigint() - startedAt) / 1e6;
429
+ this._stats.reads += 1;
430
+ this._stats.readMsTotal += elapsedMs;
431
+ this._stats.readMsLast = Math.round(elapsedMs * 1000) / 1000;
432
+ this._stats.readMsMax = Math.max(this._stats.readMsMax, this._stats.readMsLast);
433
+
434
+ return {
435
+ path: relPath,
436
+ kind,
437
+ title,
438
+ tags: Array.isArray(fields.tags) ? fields.tags : [],
439
+ aliases: parseListValue(parsed?.extras?.scope_aliases ?? parsed?.extras?.aliases),
440
+ scope: typeof fields.scope === 'string' ? fields.scope : null,
441
+ chars: charCount(body),
442
+ sha256: digest,
443
+ indexedSha256: entry?.sha256 ?? null,
444
+ shaMatch: entry ? entry.sha256 === digest : false,
445
+ stale: entry ? entry.sha256 !== digest : true,
446
+ body: blocked ? null : body,
447
+ blocked,
448
+ blockReason: blocked ? (localOnly ? 'local_only' : 'privacy_local_only') : null,
449
+ localOnly,
450
+ privacy,
451
+ frontmatter: { hasFrontmatter: Boolean(parsed?.hasFrontmatter), legacy: Boolean(parsed?.legacy), fields },
452
+ parseError,
453
+ readMs: this._stats.readMsLast,
454
+ };
455
+ }
456
+
457
+ /**
458
+ * 搜索卡。默认只开关键词车道(零正文读取);`body` 车道 opt-in。
459
+ * 未知/未实现车道抛 `E_READER_LANE_UNAVAILABLE`,不静默降级(PLAN-v0.2 §6.11)。
460
+ * @param {string} query
461
+ * @param {{lanes?: string[], limit?: number, minScore?: number}} [options]
462
+ * @returns {{path:string,kind:string,title:string|null,score:number,chars:number}[]}
463
+ */
464
+ search(query, options = {}) {
465
+ this._assertRoot();
466
+ if (typeof query !== 'string') {
467
+ throw memoryError(READER_CODES.BAD_ARGUMENT, 'search 需要字符串 query');
468
+ }
469
+ const text = query.trim();
470
+ if (!text) throw memoryError(READER_CODES.EMPTY_QUERY, 'search 需要非空 query(E_READER_EMPTY_QUERY)');
471
+ if (text.length > 4000) {
472
+ throw memoryError(READER_CODES.QUERY_TOO_LONG, 'query 超过 4000 字符(E_READER_QUERY_TOO_LONG)');
473
+ }
474
+ const lanes = this._normalizeLanes(options.lanes);
475
+ const limit = options.limit === undefined ? 10 : options.limit;
476
+ if (!Number.isInteger(limit) || limit < 1) {
477
+ throw memoryError(READER_CODES.BAD_ARGUMENT, 'limit 必须是 >=1 的整数');
478
+ }
479
+ const minScore = options.minScore ?? 0;
480
+ if (!Number.isFinite(minScore) || minScore < 0) {
481
+ throw memoryError(READER_CODES.BAD_ARGUMENT, 'minScore 必须是 >=0 的数字');
482
+ }
483
+
484
+ const startedAt = process.hrtime.bigint();
485
+ this._ensureLoaded();
486
+ const terms = this._splitQuery(text);
487
+ const byPath = new Map();
488
+ for (const entry of this._index.entries) {
489
+ let score = 0;
490
+ const hits = [];
491
+ if (lanes.includes('keyword')) {
492
+ const lane = this._keywordScore(entry, terms);
493
+ score += lane.score;
494
+ hits.push(...lane.hits);
495
+ }
496
+ if (lanes.includes('body')) {
497
+ const lane = this._bodyScore(entry, terms);
498
+ score += lane.score;
499
+ hits.push(...lane.hits);
500
+ }
501
+ if (score <= 0) continue;
502
+ byPath.set(entry.path, {
503
+ path: entry.path,
504
+ kind: entry.kind,
505
+ title: entry.title,
506
+ score: Math.round(score * 1000) / 1000,
507
+ chars: entry.chars,
508
+ });
509
+ }
510
+ const results = [...byPath.values()]
511
+ .filter((item) => item.score >= minScore)
512
+ .sort((a, b) => b.score - a.score || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
513
+ .slice(0, limit);
514
+
515
+ this._stats.searches += 1;
516
+ this._stats.searchMsLast = Math.round((Number(process.hrtime.bigint() - startedAt) / 1e6) * 1000) / 1000;
517
+ return results;
518
+ }
519
+
520
+ /** 车道清单(接线/配置自检用;未实现车道如实标 not_implemented)。 */
521
+ listLanes() {
522
+ return Object.values(LANES).map((lane) => ({ ...lane }));
523
+ }
524
+
525
+ /** 计数 / 耗时 / 重建次数。 */
526
+ stats() {
527
+ const ensure = this.ensureIndex();
528
+ const byKind = ensure.byKind;
529
+ const entries = this._index?.entries ?? [];
530
+ let chars = 0;
531
+ for (const entry of entries) chars += entry.chars;
532
+ const read = {
533
+ count: this._stats.reads,
534
+ totalMs: Math.round(this._stats.readMsTotal * 1000) / 1000,
535
+ avgMs: this._stats.reads > 0 ? Math.round((this._stats.readMsTotal / this._stats.reads) * 1000) / 1000 : 0,
536
+ maxMs: this._stats.readMsMax,
537
+ lastMs: this._stats.readMsLast,
538
+ };
539
+ return {
540
+ memoryRoot: this.root,
541
+ indexPath: this.indexPath,
542
+ schema: INDEX_SCHEMA,
543
+ version: READER_VERSION,
544
+ builtAt: this._index?.builtAt ?? null,
545
+ counts: { total: entries.length, byKind, chars },
546
+ index: {
547
+ fullBuilds: this._index?.stats.fullBuilds ?? 0,
548
+ rebuilds: this._index?.stats.rebuilds ?? 0,
549
+ updates: this._index?.stats.updates ?? 0,
550
+ writes: this._index?.stats.writes ?? 0,
551
+ buildMs: this._index?.stats.buildMs ?? 0,
552
+ lastEnsureMs: this._stats.lastEnsureMs,
553
+ lastMode: this._stats.lastMode,
554
+ lastReason: this._stats.lastReason,
555
+ errors: this._index?.errors ?? [],
556
+ },
557
+ read,
558
+ search: { count: this._stats.searches, lastMs: this._stats.searchMsLast },
559
+ };
560
+ }
561
+
562
+ /* -------- 内部:初始化 / 索引 -------- */
563
+
564
+ _assertRoot() {
565
+ if (!fs.existsSync(this.root)) {
566
+ throw memoryError(PATH_CODES.ROOT_MISSING, `记忆根不存在:${this.root}`, { code: 'ENOENT' });
567
+ }
568
+ let stat;
569
+ try {
570
+ stat = fs.statSync(this.root);
571
+ } catch (error) {
572
+ throw memoryError(PATH_CODES.ROOT_UNSET, `记忆根不可读:${this.root}`, error);
573
+ }
574
+ if (!stat.isDirectory()) {
575
+ throw memoryError(PATH_CODES.ROOT_NOT_DIR, `记忆根不是目录:${this.root}`);
576
+ }
577
+ }
578
+
579
+ _ensureLoaded() {
580
+ if (!this._index) this.ensureIndex();
581
+ }
582
+
583
+ _loadIndexFile() {
584
+ const indexPath = this.indexPath;
585
+ let buffer;
586
+ try {
587
+ buffer = fs.readFileSync(indexPath);
588
+ } catch (error) {
589
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') {
590
+ return { ok: false, missing: true, reason: 'index-missing', raw: null, reasons: ['index-missing'] };
591
+ }
592
+ return {
593
+ ok: false,
594
+ missing: false,
595
+ reason: `index-unreadable:${error?.code ?? 'UNKNOWN'}`,
596
+ raw: null,
597
+ reasons: [`index-unreadable:${error?.code ?? 'UNKNOWN'}`],
598
+ };
599
+ }
600
+ if (buffer.length > MAX_INDEX_FILE_BYTES) {
601
+ return { ok: false, missing: false, reason: 'index-too-large', raw: null, reasons: ['index-too-large'] };
602
+ }
603
+ let raw;
604
+ try {
605
+ raw = JSON.parse(buffer.toString('utf8'));
606
+ } catch {
607
+ return { ok: false, missing: false, reason: 'index-corrupt-json', raw: null, reasons: ['index-corrupt-json'] };
608
+ }
609
+ if (!isPlainObject(raw)) {
610
+ return { ok: false, missing: false, reason: 'index-not-object', raw: null, reasons: ['index-not-object'] };
611
+ }
612
+ if (raw.schema !== INDEX_SCHEMA) {
613
+ return {
614
+ ok: false,
615
+ missing: false,
616
+ reason: 'index-schema-mismatch',
617
+ raw,
618
+ reasons: ['index-schema-mismatch'],
619
+ };
620
+ }
621
+ if (!Array.isArray(raw.entries)) {
622
+ return {
623
+ ok: false,
624
+ missing: false,
625
+ reason: 'index-entries-invalid',
626
+ raw,
627
+ reasons: ['index-entries-invalid'],
628
+ };
629
+ }
630
+ const entries = normalizeEntries(raw.entries);
631
+ // 有效条目数必须等于原始条目数:任何一条坏记录都视为索引损坏,整份重建而不是悄悄丢卡。
632
+ if (entries.length !== raw.entries.length) {
633
+ return {
634
+ ok: false,
635
+ missing: false,
636
+ reason: 'index-entries-invalid',
637
+ raw,
638
+ reasons: ['index-entries-invalid'],
639
+ };
640
+ }
641
+ const index = normalizeIndex({ ...raw, entries });
642
+ return { ok: true, missing: false, reason: null, index, raw };
643
+ }
644
+
645
+ _updateFromDisk(prev) {
646
+ const diskFiles = this._scanDisk();
647
+ const prevByPath = new Map(prev.entries.map((entry) => [entry.path, entry]));
648
+ const nextEntries = [];
649
+ const errors = [];
650
+ const delta = { added: 0, updated: 0, touched: 0, removed: 0 };
651
+
652
+ for (const file of diskFiles) {
653
+ const old = prevByPath.get(file.path);
654
+ if (old && old.mtime === file.mtime) {
655
+ nextEntries.push(old);
656
+ continue;
657
+ }
658
+ let buffer;
659
+ try {
660
+ buffer = fs.readFileSync(file.absPath);
661
+ } catch (error) {
662
+ errors.push({
663
+ path: file.path,
664
+ code: READER_CODES.READ_FAILED,
665
+ message: error?.message ?? String(error),
666
+ });
667
+ // 读失败:保留上一条索引(若存在),不把卡从索引里悄悄丢掉。
668
+ if (old) nextEntries.push(old);
669
+ continue;
670
+ }
671
+ const result = entryFromDisk(file.absPath, file.path, file.kind, file.mtime, buffer, this.maxFileBytes);
672
+ if (result.entry) nextEntries.push(result.entry);
673
+ if (result.error) errors.push(result.error);
674
+ if (old && result.entry) {
675
+ if (old.sha256 === result.entry.sha256) delta.touched += 1;
676
+ else delta.updated += 1;
677
+ } else if (result.entry) {
678
+ delta.added += 1;
679
+ }
680
+ }
681
+
682
+ const diskPaths = new Set(diskFiles.map((file) => file.path));
683
+ for (const old of prev.entries) {
684
+ if (!diskPaths.has(old.path)) delta.removed += 1;
685
+ }
686
+
687
+ const errorChanged =
688
+ errors.length !== prev.errors.length ||
689
+ errors.some((error, index) => {
690
+ const before = prev.errors[index];
691
+ return !before || before.path !== error.path || before.code !== error.code || before.message !== error.message;
692
+ });
693
+
694
+ const changed = delta.added + delta.updated + delta.touched + delta.removed > 0 || errorChanged;
695
+ const stats = { ...prev.stats };
696
+ const index = {
697
+ schema: INDEX_SCHEMA,
698
+ generatedBy: prev.generatedBy,
699
+ builtAt: prev.builtAt,
700
+ stats,
701
+ entries: nextEntries,
702
+ errors: normalizeErrors(errors),
703
+ };
704
+ if (changed) {
705
+ stats.updates += 1;
706
+ this._commitIndex(index, { buildMs: stats.buildMs, fullBuilds: stats.fullBuilds, rebuilds: stats.rebuilds });
707
+ }
708
+ return { index, delta, changed };
709
+ }
710
+
711
+ _fullBuild(reason, { rebuild = false, priorStats } = {}) {
712
+ const startedAt = process.hrtime.bigint();
713
+ const diskFiles = this._scanDisk();
714
+ const entries = [];
715
+ const errors = [];
716
+ for (const file of diskFiles) {
717
+ let buffer;
718
+ try {
719
+ buffer = fs.readFileSync(file.absPath);
720
+ } catch (error) {
721
+ errors.push({
722
+ path: file.path,
723
+ code: READER_CODES.READ_FAILED,
724
+ message: error?.message ?? String(error),
725
+ });
726
+ continue;
727
+ }
728
+ const result = entryFromDisk(file.absPath, file.path, file.kind, file.mtime, buffer, this.maxFileBytes);
729
+ if (result.error) errors.push(result.error);
730
+ if (result.entry) entries.push(result.entry);
731
+ }
732
+ const elapsed = Number(process.hrtime.bigint() - startedAt) / 1e6;
733
+ const base = normalizeStats(priorStats);
734
+ const stats = {
735
+ fullBuilds: base.fullBuilds + 1,
736
+ rebuilds: base.rebuilds + (rebuild ? 1 : 0),
737
+ updates: base.updates,
738
+ writes: base.writes,
739
+ buildMs: Math.round(elapsed * 1000) / 1000,
740
+ };
741
+ const index = {
742
+ schema: INDEX_SCHEMA,
743
+ generatedBy: READER_VERSION,
744
+ builtAt: this._isoNow(),
745
+ stats,
746
+ entries,
747
+ errors: normalizeErrors(errors),
748
+ };
749
+ this._commitIndex(index, { buildMs: stats.buildMs, fullBuilds: stats.fullBuilds, rebuilds: stats.rebuilds });
750
+ return {
751
+ index,
752
+ delta: { added: entries.length, updated: 0, touched: 0, removed: 0 },
753
+ };
754
+ }
755
+
756
+ _commitIndex(index, { buildMs, fullBuilds, rebuilds } = {}) {
757
+ const payload = {
758
+ schema: INDEX_SCHEMA,
759
+ generatedBy: index.generatedBy ?? READER_VERSION,
760
+ builtAt: index.builtAt ?? this._isoNow(),
761
+ stats: {
762
+ fullBuilds: fullBuilds ?? index.stats?.fullBuilds ?? 0,
763
+ rebuilds: rebuilds ?? index.stats?.rebuilds ?? 0,
764
+ updates: index.stats?.updates ?? 0,
765
+ writes: (index.stats?.writes ?? 0) + 1,
766
+ buildMs: buildMs ?? index.stats?.buildMs ?? 0,
767
+ },
768
+ entries: index.entries,
769
+ errors: normalizeErrors(index.errors),
770
+ };
771
+ index.stats = payload.stats;
772
+ const tmp = `${this.indexPath}.tmp-${process.pid}-${Date.now().toString(36)}`;
773
+ try {
774
+ fs.mkdirSync(path.dirname(this.indexPath), { recursive: true });
775
+ fs.writeFileSync(tmp, `${JSON.stringify(payload, null, 1)}\n`, 'utf8');
776
+ fs.renameSync(tmp, this.indexPath);
777
+ } catch (error) {
778
+ try {
779
+ fs.rmSync(tmp, { force: true });
780
+ } catch {
781
+ /* 清理失败不掩盖原始错误 */
782
+ }
783
+ throw memoryError(READER_CODES.INDEX_WRITE, `写索引失败:${this.indexPath}: ${error?.message ?? error}`, error);
784
+ }
785
+ this._stats.writes = payload.stats.writes;
786
+ }
787
+
788
+ _scanDisk() {
789
+ const files = [];
790
+ for (const [dirName, kind] of Object.entries(READER_DIRS)) {
791
+ const dirPath = path.join(this.root, dirName);
792
+ let stat;
793
+ try {
794
+ stat = fs.statSync(dirPath);
795
+ } catch (error) {
796
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') continue;
797
+ throw memoryError(READER_CODES.SCAN_FAILED, `扫描目录失败:${dirName}: ${error?.message ?? error}`, error);
798
+ }
799
+ if (!stat.isDirectory()) continue;
800
+ this._walkDir(dirPath, dirName, kind, files, 0);
801
+ }
802
+ files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
803
+ return files;
804
+ }
805
+
806
+ _walkDir(absDir, relDir, kind, files, depth) {
807
+ if (depth > MAX_WALK_DEPTH) return;
808
+ let names;
809
+ try {
810
+ names = fs.readdirSync(absDir, { withFileTypes: true });
811
+ } catch (error) {
812
+ throw memoryError(READER_CODES.SCAN_FAILED, `扫描目录失败:${relDir}: ${error?.message ?? error}`, error);
813
+ }
814
+ names.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
815
+ for (const dirent of names) {
816
+ if (dirent.name.startsWith('.')) continue;
817
+ if (dirent.name === 'archive') continue;
818
+ const absPath = path.join(absDir, dirent.name);
819
+ const relPath = `${relDir}/${dirent.name}`;
820
+ if (dirent.isSymbolicLink()) continue;
821
+ if (dirent.isDirectory()) {
822
+ this._walkDir(absPath, relPath, kind, files, depth + 1);
823
+ continue;
824
+ }
825
+ if (!dirent.isFile() || !dirent.name.endsWith(CARD_EXT)) continue;
826
+ let stat;
827
+ try {
828
+ stat = fs.statSync(absPath);
829
+ } catch {
830
+ continue;
831
+ }
832
+ files.push({ path: relPath, kind, absPath, mtime: stat.mtimeMs });
833
+ }
834
+ }
835
+
836
+ /* -------- 内部:搜索评分 -------- */
837
+
838
+ _normalizeLanes(rawLanes) {
839
+ const source = rawLanes === undefined ? DEFAULT_LANES : rawLanes;
840
+ if (!Array.isArray(source) || source.length === 0) {
841
+ throw memoryError(READER_CODES.BAD_ARGUMENT, 'lanes 必须是非空数组');
842
+ }
843
+ const out = [];
844
+ for (const name of source) {
845
+ if (typeof name !== 'string') {
846
+ throw memoryError(READER_CODES.BAD_ARGUMENT, 'lanes 元素必须是字符串');
847
+ }
848
+ const displayName = name;
849
+ const lane = LANES[name];
850
+ if (!lane) {
851
+ throw memoryError(READER_CODES.LANE_UNAVAILABLE, `未知搜索车道:${displayName}`, { lane: name });
852
+ }
853
+ if (lane.status !== 'ready') {
854
+ throw memoryError(READER_CODES.LANE_UNAVAILABLE, `搜索车道未实现:${name}`, { lane: name, status: lane.status });
855
+ }
856
+ if (!out.includes(name)) out.push(name);
857
+ }
858
+ return out;
859
+ }
860
+
861
+ _splitQuery(text) {
862
+ return text
863
+ .toLowerCase()
864
+ .split(/[\s,,、;;::/|\\]+/)
865
+ .map((term) => term.trim())
866
+ .filter(Boolean);
867
+ }
868
+
869
+ _keywordScore(entry, terms) {
870
+ const phrases = [
871
+ entry.title ?? '',
872
+ ...(entry.tags ?? []),
873
+ ...(entry.aliases ?? []),
874
+ ...String(entry.scope ?? '').split(','),
875
+ ]
876
+ .map((phrase) => phrase.trim().toLowerCase())
877
+ .filter(Boolean);
878
+ let score = 0;
879
+ let hits = 0;
880
+ const matched = [];
881
+ for (const term of terms) {
882
+ let hit = false;
883
+ for (const phrase of phrases) {
884
+ if (phrase.includes(term) || term.includes(phrase)) {
885
+ hit = true;
886
+ matched.push(phrase);
887
+ break;
888
+ }
889
+ }
890
+ if (hit) {
891
+ hits += 1;
892
+ score += phraseWeight(term);
893
+ }
894
+ }
895
+ if (hits === 0) return { score: 0, hits: [] };
896
+ return { score: this._combineScore(score, hits, terms.length), hits: matched };
897
+ }
898
+
899
+ _bodyScore(entry, terms) {
900
+ let text;
901
+ try {
902
+ text = fs.readFileSync(path.join(this.root, ...entry.path.split('/')), 'utf8');
903
+ } catch {
904
+ return { score: 0, hits: [] };
905
+ }
906
+ let parsed = null;
907
+ let body = text;
908
+ if (text.length <= this.maxFileBytes) {
909
+ try {
910
+ parsed = parseFrontmatter(text);
911
+ body = parsed.body ?? '';
912
+ } catch {
913
+ body = text;
914
+ }
915
+ }
916
+ if (isLocalOnly(parsed, text)) return { score: 0, hits: [] };
917
+ const haystack = body.toLowerCase();
918
+ let score = 0;
919
+ let hits = 0;
920
+ const matched = [];
921
+ for (const term of terms) {
922
+ if (haystack.includes(term)) {
923
+ hits += 1;
924
+ score += phraseWeight(term);
925
+ matched.push(term);
926
+ }
927
+ }
928
+ if (hits === 0) return { score: 0, hits: [] };
929
+ return { score: this._combineScore(score, hits, terms.length), hits: matched };
930
+ }
931
+
932
+ /** 与 `recall-core.scoreCard` 同形:sumW * (coverageWeight + (1-coverageWeight)*coverage)。 */
933
+ _combineScore(sumW, hits, termCount) {
934
+ if (termCount <= 0) return 0;
935
+ const coverage = hits / termCount;
936
+ return sumW * (0.75 + 0.25 * coverage);
937
+ }
938
+
939
+ /* -------- 内部:杂项 -------- */
940
+
941
+ _resolveCardPath(cardPath) {
942
+ if (typeof cardPath !== 'string' || cardPath.trim() === '') {
943
+ throw memoryError(READER_CODES.BAD_ARGUMENT, 'getCard 需要非空卡片路径');
944
+ }
945
+ return resolveInside(this.root, cardPath.trim());
946
+ }
947
+
948
+ _kindOf(relPath) {
949
+ const head = relPath.split('/')[0];
950
+ return READER_DIRS[head] ?? null;
951
+ }
952
+
953
+ _countByKind(entries) {
954
+ const byKind = { topic: 0, journal: 0, procedure: 0, handover: 0 };
955
+ for (const entry of entries) byKind[entry.kind] += 1;
956
+ return byKind;
957
+ }
958
+
959
+ _resultPayload(index, { mode, reason, rebuild, delta }) {
960
+ return {
961
+ ok: true,
962
+ indexPath: this.indexPath,
963
+ schema: INDEX_SCHEMA,
964
+ entries: index.entries.length,
965
+ byKind: this._countByKind(index.entries),
966
+ changed: Boolean(rebuild) || mode !== 'unchanged',
967
+ mode,
968
+ reason: reason ?? null,
969
+ rebuild: Boolean(rebuild),
970
+ delta,
971
+ buildMs: index.stats.buildMs,
972
+ fullBuilds: index.stats.fullBuilds,
973
+ rebuilds: index.stats.rebuilds,
974
+ errors: index.errors,
975
+ };
976
+ }
977
+
978
+ _resolvePrivacyScan(options) {
979
+ const option = options?.privacyScan === undefined ? this._privacyOption : options.privacyScan;
980
+ if (option === false) return null;
981
+ if (typeof option === 'function') return option;
982
+ if (option === true) return defaultPrivacyScan;
983
+ throw memoryError(READER_CODES.BAD_ARGUMENT, 'privacyScan 只能是 true / false / 函数');
984
+ }
985
+
986
+ _isoNow() {
987
+ let value;
988
+ try {
989
+ value = this._now();
990
+ } catch {
991
+ value = new Date();
992
+ }
993
+ const date = value instanceof Date ? value : new Date(value);
994
+ return Number.isFinite(date.getTime()) ? date.toISOString() : new Date().toISOString();
995
+ }
996
+ }
997
+
998
+ /** 索引路径帮助函数(接线方可直接用)。 */
999
+ export function memoryReaderIndexPath(memoryRoot) {
1000
+ return path.join(path.resolve(String(memoryRoot)), ...INDEX_REL_PATH.split('/'));
1001
+ }
1002
+
1003
+ export default MemoryReader;