@agentproto/adapter-knowledge-files 0.3.5 → 0.5.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/dist/index.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  import { KnowledgeNotSupportedError } from '@agentproto/knowledge-engine';
2
+ import { stat, readFile, mkdir, writeFile, rename, appendFile, readdir, rm } from 'fs/promises';
3
+ import path2 from 'path';
4
+ import { Worker } from 'worker_threads';
2
5
  import { randomBytes } from 'crypto';
3
- import { stat, readFile, mkdir, writeFile, rename, appendFile, readdir } from 'fs/promises';
4
- import path from 'path';
5
6
  import { makeAdapterResolver } from '@agentproto/provider-kit';
6
7
 
7
8
  /**
@@ -16,7 +17,7 @@ var K1 = 1.5;
16
17
  var B = 0.75;
17
18
  var MIN_TOKEN_LEN = 2;
18
19
  var MAX_TOKEN_LEN = 32;
19
- var STOPWORDS = /* @__PURE__ */ new Set([
20
+ var STOPWORD_LIST = Object.freeze([
20
21
  "a",
21
22
  "an",
22
23
  "and",
@@ -69,6 +70,7 @@ var STOPWORDS = /* @__PURE__ */ new Set([
69
70
  "you",
70
71
  "your"
71
72
  ]);
73
+ var STOPWORDS = new Set(STOPWORD_LIST);
72
74
  function stripFrontmatter(content) {
73
75
  if (!content.startsWith("---")) return content;
74
76
  const end = content.indexOf("\n---", 3);
@@ -84,75 +86,143 @@ function tokenize(text) {
84
86
  }
85
87
  return out;
86
88
  }
87
- function buildIndex(inputs) {
88
- const docs = [];
89
- const df = /* @__PURE__ */ new Map();
90
- let totalLength = 0;
91
- for (const input of inputs) {
92
- const tokens = tokenize(stripFrontmatter(input.content));
89
+ var U32Buffer = class {
90
+ buf;
91
+ length = 0;
92
+ constructor(capacity = 1024) {
93
+ this.buf = new Uint32Array(capacity);
94
+ }
95
+ push(value) {
96
+ if (this.length === this.buf.length) {
97
+ const next = new Uint32Array(this.buf.length * 2);
98
+ next.set(this.buf);
99
+ this.buf = next;
100
+ }
101
+ this.buf[this.length++] = value;
102
+ }
103
+ get(i) {
104
+ return this.buf[i];
105
+ }
106
+ set(i, value) {
107
+ this.buf[i] = value;
108
+ }
109
+ take() {
110
+ return this.buf.slice(0, this.length);
111
+ }
112
+ };
113
+ function ownString(term) {
114
+ return JSON.parse(JSON.stringify(term));
115
+ }
116
+ var Bm25IndexBuilder = class {
117
+ docs = [];
118
+ vocab = /* @__PURE__ */ new Map();
119
+ df = new U32Buffer();
120
+ offsets = new U32Buffer();
121
+ termIds = new U32Buffer(64 * 1024);
122
+ tfs = new U32Buffer(64 * 1024);
123
+ totalLength = 0;
124
+ constructor() {
125
+ this.offsets.push(0);
126
+ }
127
+ get docCount() {
128
+ return this.docs.length;
129
+ }
130
+ add(id, content) {
131
+ const tokens = tokenize(stripFrontmatter(content));
93
132
  const tf = /* @__PURE__ */ new Map();
94
133
  for (const tok of tokens) {
95
- tf.set(tok, (tf.get(tok) ?? 0) + 1);
134
+ let termId = this.vocab.get(tok);
135
+ if (termId === void 0) {
136
+ termId = this.vocab.size;
137
+ this.vocab.set(ownString(tok), termId);
138
+ this.df.push(0);
139
+ }
140
+ tf.set(termId, (tf.get(termId) ?? 0) + 1);
96
141
  }
97
- for (const term of tf.keys()) {
98
- df.set(term, (df.get(term) ?? 0) + 1);
142
+ const ids = [...tf.keys()].sort((a, b) => a - b);
143
+ for (const termId of ids) {
144
+ this.termIds.push(termId);
145
+ this.tfs.push(tf.get(termId));
146
+ this.df.set(termId, this.df.get(termId) + 1);
99
147
  }
100
- docs.push({
101
- id: input.id,
102
- text: input.content,
103
- length: tokens.length,
104
- tf
105
- });
106
- totalLength += tokens.length;
148
+ this.offsets.push(this.termIds.length);
149
+ this.docs.push({ id, length: tokens.length });
150
+ this.totalLength += tokens.length;
151
+ }
152
+ finish() {
153
+ const avgDocLength = this.docs.length === 0 ? 0 : this.totalLength / this.docs.length;
154
+ return {
155
+ docs: this.docs,
156
+ vocab: this.vocab,
157
+ df: this.df.take(),
158
+ offsets: this.offsets.take(),
159
+ termIds: this.termIds.take(),
160
+ tfs: this.tfs.take(),
161
+ avgDocLength
162
+ };
107
163
  }
108
- const avgDocLength = docs.length === 0 ? 0 : totalLength / docs.length;
109
- return { docs, df, avgDocLength };
164
+ };
165
+ function buildIndex(inputs) {
166
+ const builder = new Bm25IndexBuilder();
167
+ for (const input of inputs) builder.add(input.id, input.content);
168
+ return builder.finish();
110
169
  }
111
170
  async function buildIndexYielding(inputs, yieldEvery = 50) {
112
- const docs = [];
113
- const df = /* @__PURE__ */ new Map();
114
- let totalLength = 0;
171
+ const builder = new Bm25IndexBuilder();
115
172
  let i = 0;
116
173
  for (const input of inputs) {
117
174
  if (i++ % yieldEvery === 0)
118
175
  await new Promise((resolve) => setImmediate(resolve));
119
- const tokens = tokenize(stripFrontmatter(input.content));
120
- const tf = /* @__PURE__ */ new Map();
121
- for (const tok of tokens) {
122
- tf.set(tok, (tf.get(tok) ?? 0) + 1);
123
- }
124
- for (const term of tf.keys()) {
125
- df.set(term, (df.get(term) ?? 0) + 1);
126
- }
127
- docs.push({
128
- id: input.id,
129
- text: input.content,
130
- length: tokens.length,
131
- tf
132
- });
133
- totalLength += tokens.length;
176
+ builder.add(input.id, input.content);
177
+ }
178
+ return builder.finish();
179
+ }
180
+ function documentFrequency(index, term) {
181
+ const termId = index.vocab.get(term);
182
+ return termId === void 0 ? 0 : index.df[termId];
183
+ }
184
+ function termFrequency(index, docIndex, termId) {
185
+ let lo = index.offsets[docIndex];
186
+ let hi = index.offsets[docIndex + 1] - 1;
187
+ while (lo <= hi) {
188
+ const mid = lo + hi >>> 1;
189
+ const at = index.termIds[mid];
190
+ if (at === termId) return index.tfs[mid];
191
+ if (at < termId) lo = mid + 1;
192
+ else hi = mid - 1;
134
193
  }
135
- const avgDocLength = docs.length === 0 ? 0 : totalLength / docs.length;
136
- return { docs, df, avgDocLength };
194
+ return 0;
195
+ }
196
+ function bm25Idf(N, n) {
197
+ return Math.log((N - n + 0.5) / (n + 0.5) + 1);
198
+ }
199
+ function bm25TermScore(idf, f, docLength, avgDocLength) {
200
+ const denom = f + K1 * (1 - B + B * docLength / avgDocLength);
201
+ return idf * (f * (K1 + 1) / denom);
137
202
  }
138
203
  function score(index, queryTokens, opts = {}) {
139
204
  if (queryTokens.length === 0 || index.docs.length === 0) return [];
140
205
  const topK = opts.topK ?? 10;
141
206
  const minScore = opts.minScore ?? 0;
142
207
  const N = index.docs.length;
208
+ const avgDocLength = index.avgDocLength === 0 ? 1 : index.avgDocLength;
209
+ const terms = [];
210
+ for (const tok of queryTokens) {
211
+ const termId = index.vocab.get(tok);
212
+ if (termId === void 0) continue;
213
+ terms.push({ termId, idf: bm25Idf(N, index.df[termId]) });
214
+ }
143
215
  const out = [];
144
- for (const doc of index.docs) {
216
+ for (let i = 0; i < N; i++) {
217
+ const doc = index.docs[i];
145
218
  let s = 0;
146
- for (const term of queryTokens) {
147
- const f = doc.tf.get(term);
219
+ for (const { termId, idf } of terms) {
220
+ const f = termFrequency(index, i, termId);
148
221
  if (!f) continue;
149
- const n = index.df.get(term) ?? 0;
150
- const idf = Math.log((N - n + 0.5) / (n + 0.5) + 1);
151
- const denom = f + K1 * (1 - B + B * doc.length / (index.avgDocLength === 0 ? 1 : index.avgDocLength));
152
- s += idf * (f * (K1 + 1) / denom);
222
+ s += bm25TermScore(idf, f, doc.length, avgDocLength);
153
223
  }
154
224
  if (s <= minScore) continue;
155
- out.push({ doc, score: s, snippet: makeSnippet(doc.text, queryTokens) });
225
+ out.push({ doc, score: s });
156
226
  }
157
227
  out.sort((a, b) => b.score - a.score);
158
228
  return out.slice(0, topK);
@@ -176,6 +246,444 @@ function makeSnippet(text, queryTokens) {
176
246
  };
177
247
  }
178
248
 
249
+ // src/fts-store.ts
250
+ var FTS_SCHEMA_VERSION = 1;
251
+ var FTS_MANIFEST_SEP = "\0";
252
+ function ftsStoreMain(sqlite, config) {
253
+ const stop = new Set(config.stopwords);
254
+ const minLen = config.minTokenLength;
255
+ const maxLen = config.maxTokenLength;
256
+ const version = `${config.schemaVersion}|${minLen}|${maxLen}|${config.stopwords.join(",")}`;
257
+ function tokenize2(text) {
258
+ let body = text;
259
+ if (body.startsWith("---")) {
260
+ const end = body.indexOf("\n---", 3);
261
+ if (end !== -1) body = body.slice(end + 4);
262
+ }
263
+ const out = [];
264
+ for (const raw of body.toLowerCase().split(/[^a-z0-9]+/)) {
265
+ if (raw.length < minLen || raw.length > maxLen) continue;
266
+ if (stop.has(raw)) continue;
267
+ out.push(raw);
268
+ }
269
+ return out;
270
+ }
271
+ const db = new sqlite.DatabaseSync(config.path);
272
+ db.exec("PRAGMA journal_mode = WAL");
273
+ db.exec("PRAGMA synchronous = NORMAL");
274
+ db.exec("PRAGMA busy_timeout = 5000");
275
+ db.exec("CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)");
276
+ const metaGet = db.prepare("SELECT value FROM meta WHERE key = ?");
277
+ const metaSet = db.prepare(
278
+ "INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
279
+ );
280
+ const stored = metaGet.get("version")?.value;
281
+ let created = null;
282
+ if (stored !== version) {
283
+ created = stored === void 0 ? "new" : "version";
284
+ db.exec("DROP TABLE IF EXISTS fts_row");
285
+ db.exec("DROP TABLE IF EXISTS fts");
286
+ db.exec("DROP TABLE IF EXISTS docs");
287
+ db.exec(
288
+ "CREATE TABLE docs (rowid INTEGER PRIMARY KEY, path TEXT NOT NULL UNIQUE, size INTEGER NOT NULL, mtime INTEGER NOT NULL, len INTEGER NOT NULL, has_text INTEGER NOT NULL, written INTEGER NOT NULL)"
289
+ );
290
+ db.exec(
291
+ "CREATE VIRTUAL TABLE fts USING fts5(body, content='', contentless_delete=1, tokenize='ascii', detail=full)"
292
+ );
293
+ db.exec("CREATE VIRTUAL TABLE fts_row USING fts5vocab(fts, 'row')");
294
+ metaSet.run("version", version);
295
+ metaSet.run("complete", "0");
296
+ }
297
+ const selectDoc = db.prepare("SELECT rowid, has_text FROM docs WHERE path = ?");
298
+ const insertDoc = db.prepare(
299
+ "INSERT INTO docs (path, size, mtime, len, has_text, written) VALUES (?, ?, ?, ?, ?, ?)"
300
+ );
301
+ const updateDoc = db.prepare(
302
+ "UPDATE docs SET size = ?, mtime = ?, len = ?, has_text = ?, written = ? WHERE rowid = ?"
303
+ );
304
+ const deleteDoc = db.prepare("DELETE FROM docs WHERE rowid = ?");
305
+ const insertFts = db.prepare("INSERT INTO fts (rowid, body) VALUES (?, ?)");
306
+ const deleteFts = db.prepare("DELETE FROM fts WHERE rowid = ?");
307
+ const allDocs = db.prepare("SELECT rowid, path, size, mtime, has_text, written FROM docs");
308
+ const statsStmt = db.prepare(
309
+ "SELECT count(*) AS n, coalesce(sum(len), 0) AS total FROM docs WHERE has_text = 1"
310
+ );
311
+ const dfStmt = db.prepare("SELECT doc FROM fts_row WHERE term = ?");
312
+ const searchStmt = db.prepare(
313
+ "SELECT rowid, bm25(fts) AS s FROM fts WHERE fts MATCH ? ORDER BY s, rowid LIMIT ?"
314
+ );
315
+ const pathOf = db.prepare("SELECT path FROM docs WHERE rowid = ?");
316
+ const listStmt = db.prepare("SELECT path FROM docs WHERE has_text = 1 ORDER BY rowid");
317
+ const sqliteVersion = String(db.prepare("SELECT sqlite_version() AS v").get()?.v ?? "?");
318
+ let stats = null;
319
+ let seq = Number(db.prepare("SELECT coalesce(max(written), 0) AS m FROM docs").get()?.m ?? 0);
320
+ function inTransaction(fn) {
321
+ db.exec("BEGIN IMMEDIATE");
322
+ try {
323
+ const out = fn();
324
+ db.exec("COMMIT");
325
+ return out;
326
+ } catch (err) {
327
+ db.exec("ROLLBACK");
328
+ throw err;
329
+ }
330
+ }
331
+ function dropRow(rowid, hasText) {
332
+ if (hasText) deleteFts.run(rowid);
333
+ deleteDoc.run(rowid);
334
+ }
335
+ function currentStats() {
336
+ if (!stats) {
337
+ const row = statsStmt.get();
338
+ stats = { n: Number(row?.n ?? 0), total: Number(row?.total ?? 0) };
339
+ }
340
+ return stats;
341
+ }
342
+ const ops = {
343
+ info() {
344
+ return {
345
+ docs: currentStats().n,
346
+ complete: metaGet.get("complete")?.value === "1",
347
+ created,
348
+ sqliteVersion
349
+ };
350
+ },
351
+ mark() {
352
+ return seq;
353
+ },
354
+ diff(args) {
355
+ const known = /* @__PURE__ */ new Map();
356
+ for (const row of allDocs.all()) {
357
+ known.set(String(row.path), {
358
+ rowid: Number(row.rowid),
359
+ size: Number(row.size),
360
+ mtime: Number(row.mtime),
361
+ hasText: Number(row.has_text) === 1,
362
+ written: Number(row.written)
363
+ });
364
+ }
365
+ const { sizes, mtimes } = args.manifest;
366
+ const paths = args.manifest.paths === "" ? [] : args.manifest.paths.split("\0");
367
+ const changed = [];
368
+ let unchanged = 0;
369
+ paths.forEach((path3, i) => {
370
+ const row = known.get(path3);
371
+ if (row) known.delete(path3);
372
+ if (row && row.size === sizes[i] && row.mtime === mtimes[i]) unchanged++;
373
+ else changed.push(i);
374
+ });
375
+ let removed = 0;
376
+ inTransaction(() => {
377
+ for (const row of known.values()) {
378
+ if (row.written > args.mark) continue;
379
+ dropRow(row.rowid, row.hasText);
380
+ removed++;
381
+ }
382
+ });
383
+ if (removed > 0) stats = null;
384
+ return { changed: Uint32Array.from(changed), removed, unchanged };
385
+ },
386
+ upsert(args) {
387
+ let added = 0;
388
+ let updated = 0;
389
+ inTransaction(() => {
390
+ for (const doc of args.docs) {
391
+ const hasText = doc.text.length > 0;
392
+ const tokens = hasText ? tokenize2(doc.text) : [];
393
+ const row = selectDoc.get(doc.path);
394
+ let rowid;
395
+ if (row) {
396
+ rowid = Number(row.rowid);
397
+ if (Number(row.has_text) === 1) deleteFts.run(rowid);
398
+ updateDoc.run(doc.size, doc.mtimeMs, tokens.length, hasText ? 1 : 0, ++seq, rowid);
399
+ updated++;
400
+ } else {
401
+ const res = insertDoc.run(
402
+ doc.path,
403
+ doc.size,
404
+ doc.mtimeMs,
405
+ tokens.length,
406
+ hasText ? 1 : 0,
407
+ ++seq
408
+ );
409
+ rowid = Number(res.lastInsertRowid);
410
+ added++;
411
+ }
412
+ if (hasText) insertFts.run(rowid, tokens.join(" "));
413
+ }
414
+ });
415
+ stats = null;
416
+ return { added, updated };
417
+ },
418
+ remove(args) {
419
+ let removed = 0;
420
+ inTransaction(() => {
421
+ for (const path3 of args.paths) {
422
+ const row = selectDoc.get(path3);
423
+ if (!row) continue;
424
+ dropRow(Number(row.rowid), Number(row.has_text) === 1);
425
+ removed++;
426
+ }
427
+ });
428
+ stats = null;
429
+ return { removed };
430
+ },
431
+ setComplete(args) {
432
+ metaSet.run("complete", args.complete ? "1" : "0");
433
+ return null;
434
+ },
435
+ search(args) {
436
+ const { n, total } = currentStats();
437
+ const distinct = [...new Set(args.tokens)];
438
+ const df = {};
439
+ for (const term of distinct) df[term] = Number(dfStmt.get(term)?.doc ?? 0);
440
+ const present = args.tokens.filter((t) => df[t] > 0);
441
+ const candidates = [];
442
+ if (present.length > 0) {
443
+ const match = present.map((t) => `"${t}"`).join(" OR ");
444
+ for (const row of searchStmt.all(match, args.limit)) {
445
+ const path3 = pathOf.get(Number(row.rowid))?.path;
446
+ if (typeof path3 === "string") candidates.push({ path: path3, ftsScore: -Number(row.s) });
447
+ }
448
+ }
449
+ return { candidates, docs: n, avgDocLength: n === 0 ? 0 : total / n, df };
450
+ },
451
+ list() {
452
+ return listStmt.all().map((row) => String(row.path));
453
+ },
454
+ has(args) {
455
+ return Number(selectDoc.get(args.path)?.has_text ?? 0) === 1;
456
+ },
457
+ tokenize(args) {
458
+ return tokenize2(args.text);
459
+ },
460
+ close() {
461
+ db.close();
462
+ return null;
463
+ }
464
+ };
465
+ return {
466
+ handle(op, args) {
467
+ const fn = ops[op];
468
+ if (!fn) throw new Error(`fts store: unknown op "${String(op)}"`);
469
+ return fn(args);
470
+ }
471
+ };
472
+ }
473
+
474
+ // src/fts-index.ts
475
+ var FtsUnavailableError = class extends Error {
476
+ constructor(message) {
477
+ super(message);
478
+ this.name = "FtsUnavailableError";
479
+ }
480
+ };
481
+ var NODE_SQLITE = "node:sqlite";
482
+ var shared = /* @__PURE__ */ new Map();
483
+ async function openFtsIndex(opts) {
484
+ const key = path2.resolve(opts.path);
485
+ let entry = shared.get(key);
486
+ if (!entry) {
487
+ const handle = openTransport(key, opts.worker ?? true, opts.onReset);
488
+ entry = { refs: 0, handle };
489
+ shared.set(key, entry);
490
+ handle.catch(() => {
491
+ if (shared.get(key) === entry) shared.delete(key);
492
+ });
493
+ }
494
+ entry.refs++;
495
+ let transport;
496
+ try {
497
+ transport = await entry.handle;
498
+ } catch (err) {
499
+ entry.refs--;
500
+ throw err;
501
+ }
502
+ const owner = entry;
503
+ let released = false;
504
+ return {
505
+ path: key,
506
+ inWorker: transport.inWorker,
507
+ request: (op, args) => transport.call(op, args),
508
+ async release() {
509
+ if (released) return;
510
+ released = true;
511
+ owner.refs--;
512
+ if (owner.refs > 0) return;
513
+ if (shared.get(key) === owner) shared.delete(key);
514
+ await transport.close();
515
+ }
516
+ };
517
+ }
518
+ async function openTransport(file, worker, onReset) {
519
+ await mkdir(path2.dirname(file), { recursive: true });
520
+ const config = {
521
+ path: file,
522
+ schemaVersion: FTS_SCHEMA_VERSION,
523
+ stopwords: STOPWORD_LIST,
524
+ minTokenLength: MIN_TOKEN_LEN,
525
+ maxTokenLength: MAX_TOKEN_LEN
526
+ };
527
+ const open = worker ? openWorker : openInline;
528
+ try {
529
+ return await open(config);
530
+ } catch (err) {
531
+ if (err instanceof FtsUnavailableError) throw err;
532
+ const message = err instanceof Error ? err.message : String(err);
533
+ if (!CORRUPT_RE.test(message) || !await exists(file)) throw err;
534
+ onReset?.(message);
535
+ await removeIndexFiles(file);
536
+ return await open(config);
537
+ }
538
+ }
539
+ var CORRUPT_RE = /not a database|malformed|corrupt|encrypted/i;
540
+ async function removeIndexFiles(file) {
541
+ for (const suffix of ["", "-wal", "-shm"]) {
542
+ await rm(file + suffix, { force: true });
543
+ }
544
+ }
545
+ async function exists(file) {
546
+ try {
547
+ await stat(file);
548
+ return true;
549
+ } catch {
550
+ return false;
551
+ }
552
+ }
553
+ function unavailableReason(message) {
554
+ if (/node:sqlite|No such built-in module|ERR_UNKNOWN_BUILTIN_MODULE/i.test(message)) {
555
+ return `node:sqlite is not available in Node ${process.versions.node}`;
556
+ }
557
+ if (/no such module: fts5|contentless_delete|no such module: fts5vocab/i.test(message)) {
558
+ return `the SQLite linked into Node ${process.versions.node} lacks FTS5 (contentless_delete)`;
559
+ }
560
+ return null;
561
+ }
562
+ async function openInline(config) {
563
+ let sqlite;
564
+ try {
565
+ sqlite = await import(
566
+ /* @vite-ignore */
567
+ NODE_SQLITE
568
+ );
569
+ } catch (err) {
570
+ const message = err instanceof Error ? err.message : String(err);
571
+ throw new FtsUnavailableError(unavailableReason(message) ?? message);
572
+ }
573
+ let store;
574
+ try {
575
+ store = ftsStoreMain(sqlite, config);
576
+ } catch (err) {
577
+ const message = err instanceof Error ? err.message : String(err);
578
+ const reason = unavailableReason(message);
579
+ if (reason) throw new FtsUnavailableError(reason);
580
+ throw err;
581
+ }
582
+ return {
583
+ inWorker: false,
584
+ async call(op, args) {
585
+ return store.handle(op, args);
586
+ },
587
+ async close() {
588
+ store.handle("close", void 0);
589
+ }
590
+ };
591
+ }
592
+ var WORKER_SOURCE = `
593
+ // A bundler running with keepNames wraps inner functions in __name(): make
594
+ // that a no-op so the stringified store still runs.
595
+ const __name = fn => fn
596
+ const { parentPort, workerData } = require("node:worker_threads")
597
+ let store = null
598
+ try {
599
+ const sqlite = require("node:sqlite")
600
+ store = (${ftsStoreMain.toString()})(sqlite, workerData)
601
+ parentPort.postMessage({ ready: true })
602
+ } catch (err) {
603
+ parentPort.postMessage({ ready: false, error: String((err && err.message) || err) })
604
+ }
605
+ parentPort.on("message", msg => {
606
+ try {
607
+ const value = store.handle(msg.op, msg.args)
608
+ parentPort.postMessage({ id: msg.id, ok: true, value })
609
+ } catch (err) {
610
+ parentPort.postMessage({ id: msg.id, ok: false, error: String((err && err.message) || err) })
611
+ }
612
+ })
613
+ `;
614
+ async function openWorker(config) {
615
+ let worker;
616
+ try {
617
+ worker = new Worker(WORKER_SOURCE, { eval: true, workerData: config });
618
+ } catch (err) {
619
+ throw new FtsUnavailableError(
620
+ `cannot start the index worker: ${err instanceof Error ? err.message : String(err)}`
621
+ );
622
+ }
623
+ const pending = /* @__PURE__ */ new Map();
624
+ let nextId = 1;
625
+ let dead = null;
626
+ const settle = () => {
627
+ if (pending.size === 0) worker.unref();
628
+ };
629
+ await new Promise((resolve, reject) => {
630
+ const onFirst = (msg) => {
631
+ worker.off("error", onError);
632
+ if (msg.ready) return resolve();
633
+ void worker.terminate();
634
+ const message = msg.error ?? "index worker failed to start";
635
+ const reason = unavailableReason(message);
636
+ reject(reason ? new FtsUnavailableError(reason) : new Error(message));
637
+ };
638
+ const onError = (err) => {
639
+ worker.off("message", onFirst);
640
+ reject(new FtsUnavailableError(`index worker crashed on start: ${err.message}`));
641
+ };
642
+ worker.once("message", onFirst);
643
+ worker.once("error", onError);
644
+ });
645
+ worker.unref();
646
+ const failAll = (err) => {
647
+ dead = err;
648
+ for (const p of pending.values()) p.reject(err);
649
+ pending.clear();
650
+ };
651
+ worker.on("message", (msg) => {
652
+ const p = pending.get(msg.id);
653
+ if (!p) return;
654
+ pending.delete(msg.id);
655
+ settle();
656
+ if (msg.ok) p.resolve(msg.value);
657
+ else p.reject(new Error(msg.error));
658
+ });
659
+ worker.on("error", (err) => failAll(new Error(`index worker crashed: ${err.message}`)));
660
+ worker.on("exit", (code) => {
661
+ if (!dead) failAll(new Error(`index worker exited (code ${code})`));
662
+ });
663
+ const call = (op, args) => {
664
+ if (dead) return Promise.reject(dead);
665
+ const id = nextId++;
666
+ return new Promise((resolve, reject) => {
667
+ pending.set(id, { resolve, reject });
668
+ worker.ref();
669
+ worker.postMessage({ id, op, args });
670
+ });
671
+ };
672
+ return {
673
+ inWorker: true,
674
+ call,
675
+ async close() {
676
+ if (dead) return;
677
+ try {
678
+ await call("close", void 0);
679
+ } catch {
680
+ }
681
+ dead = new Error("index closed");
682
+ await worker.terminate();
683
+ }
684
+ };
685
+ }
686
+
179
687
  // src/adapter.ts
180
688
  var FILES_ENGINE_ID = "files";
181
689
  var INDEXED_EXTENSIONS = [
@@ -188,7 +696,44 @@ var INDEXED_EXTENSIONS = [
188
696
  ];
189
697
  var CACHE_TTL_MS = Number.POSITIVE_INFINITY;
190
698
  var INDEX_READ_CONCURRENCY = 10;
699
+ var SCAN_STAT_CONCURRENCY = 32;
191
700
  var INDEX_QUERY_TIMEOUT_MS = 4e3;
701
+ var INDEX_BUILD_STEP = 50;
702
+ var FTS_BUILD_STEP = 100;
703
+ var FTS_CANDIDATE_FACTOR = 8;
704
+ var FTS_MIN_CANDIDATES = 80;
705
+ var FTS_MAX_CANDIDATES = 300;
706
+ var DEFAULT_RECONCILE_INTERVAL_MS = 5 * 6e4;
707
+ var DEFAULT_MAX_INDEX_DOCS = 1e5;
708
+ var FilesIndexTooLargeError = class extends Error {
709
+ docCount;
710
+ maxDocs;
711
+ constructor(label, docCount, maxDocs) {
712
+ super(
713
+ `files engine (${label}): refusing to build the in-process index: ${docCount} indexable files exceed the ceiling of ${maxDocs}. Raise maxIndexDocs, or back this brain with a real search engine.`
714
+ );
715
+ this.name = "FilesIndexTooLargeError";
716
+ this.docCount = docCount;
717
+ this.maxDocs = maxDocs;
718
+ }
719
+ };
720
+ var buildGate = Promise.resolve();
721
+ var buildsRunning = 0;
722
+ function runExclusiveBuild(fn) {
723
+ const run = buildGate.then(async () => {
724
+ buildsRunning++;
725
+ try {
726
+ return await fn();
727
+ } finally {
728
+ buildsRunning--;
729
+ }
730
+ });
731
+ buildGate = run.catch(() => void 0);
732
+ return run;
733
+ }
734
+ function filesIndexBuildsRunning() {
735
+ return buildsRunning;
736
+ }
192
737
  var FILES_CAPABILITIES = Object.freeze({
193
738
  vectorSearch: false,
194
739
  graphTraversal: false,
@@ -207,15 +752,48 @@ var FilesKnowledgeAdapter = class {
207
752
  capabilities = FILES_CAPABILITIES;
208
753
  fs;
209
754
  workspacePath;
755
+ label;
756
+ maxIndexDocs;
757
+ queryTimeoutMs;
758
+ log;
759
+ indexPath;
760
+ indexWorker;
761
+ reconcileIntervalMs;
762
+ // ── in-memory engine ──
210
763
  cachedIndex = null;
211
764
  cachedAt = 0;
765
+ // True when the cached index holds only the most recent maxIndexDocs files.
766
+ cachedPartial = false;
212
767
  // In-flight build promise: concurrent turns that arrive while the index is
213
768
  // still being built (cachedIndex === null) coalesce onto this promise instead
214
769
  // of each kicking off a redundant 40-50s Supabase Storage re-scan.
215
770
  buildInFlight = null;
771
+ buildStartedAt = 0;
772
+ // ── on-disk engine ──
773
+ ftsOpening = null;
774
+ ftsHandle = null;
775
+ ftsDisabled = false;
776
+ // The index holds every file (a full build finished at least once).
777
+ ftsComplete = false;
778
+ sync = null;
779
+ syncStartedAt = 0;
780
+ lastSyncAt = 0;
781
+ // A reconcile is due on the next query (an external writer was signalled).
782
+ syncDue = false;
783
+ disposed = false;
784
+ // Per-document updates since the last reconcile, for its log line.
785
+ incrementalUpserts = 0;
786
+ incrementalDeletes = 0;
216
787
  constructor(opts) {
217
788
  this.fs = opts.fs;
218
789
  this.workspacePath = opts.workspacePath;
790
+ this.label = opts.label ?? opts.workspacePath;
791
+ this.maxIndexDocs = typeof opts.maxIndexDocs === "number" && opts.maxIndexDocs > 0 ? opts.maxIndexDocs : DEFAULT_MAX_INDEX_DOCS;
792
+ this.queryTimeoutMs = opts.queryTimeoutMs ?? INDEX_QUERY_TIMEOUT_MS;
793
+ this.log = opts.log ?? ((line) => console.log(line));
794
+ this.indexPath = opts.indexPath;
795
+ this.indexWorker = opts.indexWorker ?? true;
796
+ this.reconcileIntervalMs = typeof opts.reconcileIntervalMs === "number" && opts.reconcileIntervalMs >= 0 ? opts.reconcileIntervalMs : DEFAULT_RECONCILE_INTERVAL_MS;
219
797
  }
220
798
  async ingest(input) {
221
799
  const corpusBlock = readCorpusMeta(input.metadata);
@@ -237,7 +815,7 @@ var FilesKnowledgeAdapter = class {
237
815
  const dest = `${this.workspacePath}/sources/${sourceId}.md`;
238
816
  const content = decodeContent(input.content) ?? "";
239
817
  await this.fs.writeFile(dest, content);
240
- this.invalidate();
818
+ await this.indexWritten(dest, content);
241
819
  return {
242
820
  id: sourceId,
243
821
  kind: "text",
@@ -260,7 +838,7 @@ var FilesKnowledgeAdapter = class {
260
838
  const sourceId = stableSlug(input.uri);
261
839
  const dest = `${this.workspacePath}/sources/${sourceId}.txt`;
262
840
  await this.fs.writeFile(dest, text);
263
- this.invalidate();
841
+ await this.indexWritten(dest, text);
264
842
  return {
265
843
  id: sourceId,
266
844
  kind: "url",
@@ -278,81 +856,81 @@ var FilesKnowledgeAdapter = class {
278
856
  }
279
857
  async query(q) {
280
858
  const start = Date.now();
281
- const index = await this.ensureIndex(INDEX_QUERY_TIMEOUT_MS);
282
859
  const tokens = tokenize(q.query);
860
+ const fts = await this.openFts();
861
+ if (fts) {
862
+ try {
863
+ return await this.queryFts(fts, q, tokens, start);
864
+ } catch (err) {
865
+ this.disableFts(err);
866
+ }
867
+ }
868
+ const index = await this.ensureIndex(this.queryTimeoutMs);
869
+ const partial = index === EMPTY_INDEX || this.cachedPartial;
283
870
  if (tokens.length === 0) {
284
- return {
285
- hits: Object.freeze([]),
286
- tookMs: Date.now() - start,
287
- engine: this.id,
288
- modeUsed: "vector"
289
- };
871
+ return result([], start, partial);
290
872
  }
291
873
  const scored = score(index, tokens, {
292
874
  topK: q.topK,
293
875
  minScore: q.minScore
294
876
  });
295
- const hits = scored.map((s) => {
296
- const meta = parseFrontmatterMetadata(s.doc.text);
297
- const snippetText = s.snippet?.text ?? s.doc.text.slice(0, 300);
298
- return {
299
- sourceId: s.doc.id,
300
- chunkId: s.doc.id,
301
- text: snippetText,
302
- score: s.score,
303
- // span is in original-file bytes; matches engine "citations" capability.
304
- span: s.snippet ? { start: s.snippet.start, end: s.snippet.end } : void 0,
305
- metadata: meta
306
- };
307
- });
308
- return {
309
- hits: Object.freeze(hits),
310
- tookMs: Date.now() - start,
311
- engine: this.id,
312
- // BM25 isn't really "vector" — the union doesn't have a "keyword"
313
- // option. Report "vector" as the closest existing label until the
314
- // mode union widens.
315
- modeUsed: "vector"
316
- };
877
+ const texts = await mapWithConcurrency(
878
+ scored,
879
+ INDEX_READ_CONCURRENCY,
880
+ (s) => this.readText(s.doc.id)
881
+ );
882
+ return result(
883
+ scored.map((s, i) => toHit(s.doc.id, s.score, texts[i], tokens)),
884
+ start,
885
+ partial
886
+ );
317
887
  }
318
888
  async listSources(filter) {
319
- const index = await this.ensureIndex();
889
+ const ids = await this.indexedIds();
890
+ if (filter?.kind && filter.kind !== "file") return Object.freeze([]);
891
+ if (filter?.status && filter.status !== "ready") return Object.freeze([]);
320
892
  const out = [];
321
- for (const doc of index.docs) {
322
- const meta = parseFrontmatterMetadata(doc.text);
323
- const source = {
324
- id: doc.id,
325
- kind: "file",
326
- uri: doc.id,
327
- title: typeof meta.title === "string" ? meta.title : void 0,
328
- bytes: byteLength(doc.text),
329
- status: "ready",
330
- metadata: meta
331
- };
332
- if (filter?.kind && source.kind !== filter.kind) continue;
333
- if (filter?.status && source.status !== filter.status) continue;
334
- out.push(source);
893
+ for (let i = 0; i < ids.length; i += INDEX_BUILD_STEP) {
894
+ const step = ids.slice(i, i + INDEX_BUILD_STEP);
895
+ const texts = await mapWithConcurrency(
896
+ step,
897
+ INDEX_READ_CONCURRENCY,
898
+ (id) => this.readText(id)
899
+ );
900
+ step.forEach((id, j) => out.push(fileSource(id, texts[j])));
335
901
  }
336
902
  return Object.freeze(out);
337
903
  }
338
904
  async getSource(id) {
905
+ const fts = await this.openFts();
906
+ if (fts) {
907
+ try {
908
+ if (!await fts.request("has", { path: id })) return null;
909
+ return fileSource(id, await this.readText(id));
910
+ } catch (err) {
911
+ this.disableFts(err);
912
+ }
913
+ }
339
914
  const index = await this.ensureIndex();
340
915
  const doc = index.docs.find((d) => d.id === id);
341
916
  if (!doc) return null;
342
- const meta = parseFrontmatterMetadata(doc.text);
343
- return {
344
- id: doc.id,
345
- kind: "file",
346
- uri: doc.id,
347
- title: typeof meta.title === "string" ? meta.title : void 0,
348
- bytes: byteLength(doc.text),
349
- status: "ready",
350
- metadata: meta
351
- };
917
+ return fileSource(doc.id, await this.readText(doc.id));
352
918
  }
353
919
  async deleteSource(id) {
354
920
  if (await this.fs.exists(id)) {
355
921
  await this.fs.writeFile(id, "");
922
+ await this.indexWritten(id, "");
923
+ return;
924
+ }
925
+ const fts = await this.openFts();
926
+ if (fts) {
927
+ try {
928
+ const { removed } = await fts.request("remove", { paths: [id] });
929
+ this.incrementalDeletes += removed;
930
+ return;
931
+ } catch (err) {
932
+ this.disableFts(err);
933
+ }
356
934
  }
357
935
  this.invalidate();
358
936
  }
@@ -381,51 +959,397 @@ var FilesKnowledgeAdapter = class {
381
959
  }
382
960
  async dispose() {
383
961
  this.cachedIndex = null;
962
+ this.disposed = true;
963
+ const handle = await this.ftsOpening?.catch(() => null);
964
+ this.ftsOpening = null;
965
+ this.ftsHandle = null;
966
+ await handle?.release();
384
967
  }
385
- /** Drop the cached BM25 index — next query rebuilds. */
968
+ /**
969
+ * Resolves once the on-disk index has no build or reconcile running (at
970
+ * once on the in-memory engine). For hosts and tests that need a settled
971
+ * index; queries never need it.
972
+ */
973
+ async whenIndexSynced() {
974
+ await this.openFts();
975
+ while (this.sync) await this.sync.catch(() => void 0);
976
+ }
977
+ /**
978
+ * Signal that files changed outside the adapter. In memory: drop the index
979
+ * (next query rebuilds). On disk: the next query starts a reconcile scan.
980
+ */
386
981
  invalidate() {
387
982
  this.cachedIndex = null;
388
983
  this.cachedAt = 0;
984
+ this.cachedPartial = false;
985
+ this.syncDue = true;
986
+ }
987
+ // ── on-disk engine ────────────────────────────────────────────────
988
+ /** The on-disk index, opened on first use (which also starts its first
989
+ * reconcile), or null when this adapter runs in memory. */
990
+ openFts() {
991
+ if (!this.indexPath || this.ftsDisabled || this.disposed) return Promise.resolve(null);
992
+ this.ftsOpening ??= this.doOpenFts(this.indexPath);
993
+ return this.ftsOpening;
389
994
  }
995
+ async doOpenFts(indexPath) {
996
+ try {
997
+ const handle = await openFtsIndex({
998
+ path: indexPath,
999
+ worker: this.indexWorker,
1000
+ onReset: (reason) => this.log(
1001
+ `[knowledge-files:${this.label}] on-disk index unreadable (${reason}); deleted, rebuilding`
1002
+ )
1003
+ });
1004
+ const info = await handle.request("info", void 0);
1005
+ this.ftsHandle = handle;
1006
+ this.ftsComplete = info.complete;
1007
+ this.log(
1008
+ `[knowledge-files:${this.label}] on-disk index opened: ${info.docs} docs, ${info.complete ? "complete" : "incomplete"}` + (info.created === "new" ? ", new file" : "") + (info.created === "version" ? ", format changed: rebuilding" : "") + `, sqlite ${info.sqliteVersion}, ${handle.inWorker ? "worker thread" : "inline"}`
1009
+ );
1010
+ this.kickSync();
1011
+ return handle;
1012
+ } catch (err) {
1013
+ this.disableFts(err);
1014
+ return null;
1015
+ }
1016
+ }
1017
+ /** Give up on the on-disk index for this adapter: log once, fall back to
1018
+ * the in-memory engine. */
1019
+ disableFts(err) {
1020
+ if (this.ftsDisabled) return;
1021
+ this.ftsDisabled = true;
1022
+ this.log(
1023
+ `[knowledge-files:${this.label}] on-disk index unavailable (${err instanceof Error ? err.message : String(err)}); using the in-memory index (up to ${this.maxIndexDocs} docs)`
1024
+ );
1025
+ const handle = this.ftsHandle;
1026
+ this.ftsHandle = null;
1027
+ this.ftsOpening = null;
1028
+ void handle?.release().catch(() => void 0);
1029
+ }
1030
+ /** Start a build / reconcile when one is due, without waiting for it. */
1031
+ kickSync() {
1032
+ if (this.sync || this.disposed || !this.ftsHandle) return;
1033
+ const due = this.lastSyncAt === 0 || this.syncDue || this.reconcileIntervalMs > 0 && Date.now() - this.lastSyncAt >= this.reconcileIntervalMs;
1034
+ if (!due) return;
1035
+ const handle = this.ftsHandle;
1036
+ this.syncDue = false;
1037
+ this.syncStartedAt = Date.now();
1038
+ const run = runExclusiveBuild(() => this.runSync(handle)).catch((err) => {
1039
+ if (this.disposed) return;
1040
+ this.log(
1041
+ `[knowledge-files:${this.label}] on-disk index ${this.ftsComplete ? "reconcile" : "build"} failed: ${err instanceof Error ? err.message : String(err)}`
1042
+ );
1043
+ }).finally(() => {
1044
+ this.lastSyncAt = Date.now();
1045
+ this.sync = null;
1046
+ });
1047
+ this.sync = run;
1048
+ }
1049
+ /**
1050
+ * Bring the on-disk index in line with the files: a stat-only scan, then
1051
+ * read and upsert only what is new or changed, batch by batch, and drop
1052
+ * rows whose file is gone. The first run over an empty index is the build.
1053
+ */
1054
+ async runSync(handle) {
1055
+ const start = Date.now();
1056
+ const heapBefore = heapUsedMb();
1057
+ const initial = !this.ftsComplete;
1058
+ const upsertsBefore = this.incrementalUpserts;
1059
+ const deletesBefore = this.incrementalDeletes;
1060
+ const mark = await handle.request("mark", void 0);
1061
+ const { paths, manifest } = await this.scanManifest();
1062
+ const scanMs = Date.now() - start;
1063
+ const diff = await handle.request("diff", { manifest, mark });
1064
+ let bytesRead = 0;
1065
+ for (let i = 0; i < diff.changed.length; i += FTS_BUILD_STEP) {
1066
+ if (this.disposed) return;
1067
+ await new Promise((resolve) => setImmediate(resolve));
1068
+ const step = Array.from(diff.changed.subarray(i, i + FTS_BUILD_STEP));
1069
+ const texts = await mapWithConcurrency(
1070
+ step,
1071
+ INDEX_READ_CONCURRENCY,
1072
+ (k) => this.readText(paths[k])
1073
+ );
1074
+ const docs = step.map((k, j) => {
1075
+ bytesRead += byteLength(texts[j]);
1076
+ return {
1077
+ path: paths[k],
1078
+ size: manifest.sizes[k],
1079
+ mtimeMs: manifest.mtimes[k],
1080
+ text: texts[j]
1081
+ };
1082
+ });
1083
+ await handle.request("upsert", { docs });
1084
+ }
1085
+ if (initial) {
1086
+ await handle.request("setComplete", { complete: true });
1087
+ this.ftsComplete = true;
1088
+ }
1089
+ const info = await handle.request("info", void 0);
1090
+ const ms = Date.now() - start;
1091
+ if (initial) {
1092
+ this.log(
1093
+ `[knowledge-files:${this.label}] index built: ${info.docs} docs, ${bytesRead} bytes read, ${ms} ms, heapUsed ${heapBefore} MB -> ${heapUsedMb()} MB (on disk, ${paths.length} files scanned in ${scanMs} ms)`
1094
+ );
1095
+ } else {
1096
+ this.log(
1097
+ `[knowledge-files:${this.label}] index reconciled: ${paths.length} files scanned in ${scanMs} ms, ${diff.changed.length} re-indexed, ${diff.removed} removed, ${bytesRead} bytes read, ${ms} ms; ${upsertsBefore} upserts and ${deletesBefore} deletes applied incrementally since the last reconcile`
1098
+ );
1099
+ this.incrementalUpserts -= upsertsBefore;
1100
+ this.incrementalDeletes -= deletesBefore;
1101
+ }
1102
+ }
1103
+ /** Every indexable file with its size and mtime, without reading any. */
1104
+ async scanManifest() {
1105
+ const walker = this.fs;
1106
+ let found;
1107
+ if (typeof walker.walkStat === "function") {
1108
+ found = [...await walker.walkStat(this.workspacePath)];
1109
+ } else {
1110
+ const listed = await this.fs.walk(this.workspacePath);
1111
+ const stats = await mapWithConcurrency(
1112
+ listed,
1113
+ SCAN_STAT_CONCURRENCY,
1114
+ (p) => this.fs.stat(p).catch(() => null)
1115
+ );
1116
+ found = [];
1117
+ listed.forEach((p, i) => {
1118
+ const s = stats[i];
1119
+ if (s && s.kind === "file") {
1120
+ found.push({ path: p, size: s.bytes ?? 0, mtimeMs: mtimeOf(s.modifiedAt) });
1121
+ }
1122
+ });
1123
+ }
1124
+ found = found.filter((e) => isIndexable(e.path) && !e.path.includes(FTS_MANIFEST_SEP));
1125
+ const paths = found.map((e) => e.path);
1126
+ return {
1127
+ paths,
1128
+ manifest: {
1129
+ paths: paths.join(FTS_MANIFEST_SEP),
1130
+ sizes: Float64Array.from(found, (e) => e.size),
1131
+ mtimes: Float64Array.from(found, (e) => e.mtimeMs)
1132
+ }
1133
+ };
1134
+ }
1135
+ /** Update the on-disk row of a file this adapter just wrote; falls back to
1136
+ * invalidating the in-memory index. */
1137
+ async indexWritten(path3, text) {
1138
+ const fts = isIndexable(path3) ? await this.openFts() : null;
1139
+ if (fts) {
1140
+ try {
1141
+ const st = await this.fs.stat(path3);
1142
+ await fts.request("upsert", {
1143
+ docs: [
1144
+ {
1145
+ path: path3,
1146
+ size: st?.bytes ?? byteLength(text),
1147
+ mtimeMs: mtimeOf(st?.modifiedAt),
1148
+ text
1149
+ }
1150
+ ]
1151
+ });
1152
+ if (text.length > 0) this.incrementalUpserts++;
1153
+ else this.incrementalDeletes++;
1154
+ return;
1155
+ } catch (err) {
1156
+ this.disableFts(err);
1157
+ }
1158
+ }
1159
+ this.invalidate();
1160
+ }
1161
+ async queryFts(fts, q, tokens, start) {
1162
+ this.kickSync();
1163
+ const partial = !this.ftsComplete;
1164
+ if (tokens.length === 0) return result([], start, partial);
1165
+ const topK = q.topK ?? 10;
1166
+ const minScore = q.minScore ?? 0;
1167
+ const limit = Math.min(
1168
+ FTS_MAX_CANDIDATES,
1169
+ Math.max(topK * FTS_CANDIDATE_FACTOR, FTS_MIN_CANDIDATES)
1170
+ );
1171
+ const found = await fts.request("search", { tokens, limit });
1172
+ if (partial) {
1173
+ this.log(
1174
+ `[knowledge-files:${this.label}] query answered from a partial index: ${found.docs} docs indexed so far, first build running for ${Date.now() - this.syncStartedAt} ms`
1175
+ );
1176
+ }
1177
+ const texts = await mapWithConcurrency(
1178
+ found.candidates,
1179
+ INDEX_READ_CONCURRENCY,
1180
+ (c) => this.readText(c.path)
1181
+ );
1182
+ const avgDocLength = found.avgDocLength === 0 ? 1 : found.avgDocLength;
1183
+ const idf = /* @__PURE__ */ new Map();
1184
+ for (const t of tokens) {
1185
+ const n = found.df[t] ?? 0;
1186
+ if (n > 0) idf.set(t, bm25Idf(found.docs, n));
1187
+ }
1188
+ const scored = [];
1189
+ found.candidates.forEach((_, i) => {
1190
+ const docTokens = tokenize(stripFrontmatter(texts[i]));
1191
+ const tf = /* @__PURE__ */ new Map();
1192
+ for (const t of docTokens) if (idf.has(t)) tf.set(t, (tf.get(t) ?? 0) + 1);
1193
+ let s = 0;
1194
+ for (const t of tokens) {
1195
+ const f = tf.get(t);
1196
+ if (!f) continue;
1197
+ s += bm25TermScore(idf.get(t), f, docTokens.length, avgDocLength);
1198
+ }
1199
+ if (s > minScore) scored.push({ i, score: s });
1200
+ });
1201
+ scored.sort((a, b) => b.score - a.score || a.i - b.i);
1202
+ const hits = scored.slice(0, topK).map((s) => toHit(found.candidates[s.i].path, s.score, texts[s.i], tokens));
1203
+ return result(hits, start, partial);
1204
+ }
1205
+ /** Ids of every indexed doc, from whichever engine serves this adapter. */
1206
+ async indexedIds() {
1207
+ const fts = await this.openFts();
1208
+ if (fts) {
1209
+ try {
1210
+ return await fts.request("list", void 0);
1211
+ } catch (err) {
1212
+ this.disableFts(err);
1213
+ }
1214
+ }
1215
+ const index = await this.ensureIndex();
1216
+ return index.docs.map((d) => d.id);
1217
+ }
1218
+ // ── in-memory engine ──────────────────────────────────────────────
390
1219
  async ensureIndex(timeoutMs) {
391
1220
  if (this.cachedIndex && Date.now() - this.cachedAt < CACHE_TTL_MS) {
392
1221
  return this.cachedIndex;
393
1222
  }
394
1223
  if (!this.buildInFlight) {
395
- this.buildInFlight = this._buildIndex().finally(() => {
1224
+ this.buildStartedAt = Date.now();
1225
+ const build = runExclusiveBuild(() => this._buildIndex()).finally(() => {
396
1226
  this.buildInFlight = null;
397
1227
  });
1228
+ build.catch(() => void 0);
1229
+ this.buildInFlight = build;
398
1230
  }
399
1231
  if (timeoutMs !== void 0) {
400
- const EMPTY = { docs: [], avgDocLength: 0, df: /* @__PURE__ */ new Map() };
401
- const deadline = new Promise(
402
- (resolve) => setTimeout(() => resolve(EMPTY), timeoutMs)
1232
+ const build = this.buildInFlight;
1233
+ let timer;
1234
+ const deadline = new Promise((resolve) => {
1235
+ timer = setTimeout(() => resolve(null), timeoutMs);
1236
+ });
1237
+ const winner = await Promise.race([build, deadline]).finally(
1238
+ () => clearTimeout(timer)
403
1239
  );
404
- return Promise.race([this.buildInFlight, deadline]);
1240
+ if (winner) return winner;
1241
+ this.log(
1242
+ `[knowledge-files:${this.label}] query timed out after ${timeoutMs} ms waiting for the index build (running for ${Date.now() - this.buildStartedAt} ms); returning no hits, the build keeps going`
1243
+ );
1244
+ return EMPTY_INDEX;
405
1245
  }
406
1246
  return this.buildInFlight;
407
1247
  }
408
1248
  async _buildIndex() {
1249
+ const start = Date.now();
1250
+ const heapBefore = heapUsedMb();
409
1251
  const allPaths = await this.fs.walk(this.workspacePath);
410
- const candidates = allPaths.filter(
411
- (p) => INDEXED_EXTENSIONS.some((ext) => p.toLowerCase().endsWith(ext))
412
- );
413
- const inputs = await mapWithConcurrency(
414
- candidates,
415
- INDEX_READ_CONCURRENCY,
416
- async (path2) => ({
417
- id: path2,
418
- content: await this.fs.readFile(path2).catch(() => "")
419
- })
420
- );
421
- const index = await buildIndexYielding(
422
- inputs.filter((i) => i.content.length > 0)
423
- );
1252
+ let candidates = allPaths.filter(isIndexable);
1253
+ let partial = false;
1254
+ if (candidates.length > this.maxIndexDocs) {
1255
+ const total = candidates.length;
1256
+ candidates = await this.mostRecent(candidates, this.maxIndexDocs);
1257
+ partial = true;
1258
+ this.log(
1259
+ `[knowledge-files:${this.label}] index capped: ${total} indexable files exceed the in-memory ceiling of ${this.maxIndexDocs}; indexing the ${candidates.length} most recent, results flagged partial`
1260
+ );
1261
+ }
1262
+ const builder = new Bm25IndexBuilder();
1263
+ let bytesRead = 0;
1264
+ for (let i = 0; i < candidates.length; i += INDEX_BUILD_STEP) {
1265
+ await new Promise((resolve) => setImmediate(resolve));
1266
+ const step = candidates.slice(i, i + INDEX_BUILD_STEP);
1267
+ const texts = await mapWithConcurrency(
1268
+ step,
1269
+ INDEX_READ_CONCURRENCY,
1270
+ (path3) => this.fs.readFile(path3).catch(() => "")
1271
+ );
1272
+ step.forEach((path3, j) => {
1273
+ const content = texts[j];
1274
+ if (content.length === 0) return;
1275
+ bytesRead += byteLength(content);
1276
+ builder.add(path3, content);
1277
+ });
1278
+ }
1279
+ const index = builder.finish();
424
1280
  this.cachedIndex = index;
425
1281
  this.cachedAt = Date.now();
1282
+ this.cachedPartial = partial;
1283
+ this.log(
1284
+ `[knowledge-files:${this.label}] index built: ${index.docs.length} docs, ${bytesRead} bytes read, ${Date.now() - start} ms, heapUsed ${heapBefore} MB -> ${heapUsedMb()} MB`
1285
+ );
426
1286
  return index;
427
1287
  }
1288
+ /** The `limit` most recently modified of `paths`, kept in walk order. */
1289
+ async mostRecent(paths, limit) {
1290
+ const stats = await mapWithConcurrency(
1291
+ paths,
1292
+ SCAN_STAT_CONCURRENCY,
1293
+ (p) => this.fs.stat(p).catch(() => null)
1294
+ );
1295
+ const order = paths.map((_, i) => i);
1296
+ order.sort((a, b) => mtimeOf(stats[b]?.modifiedAt) - mtimeOf(stats[a]?.modifiedAt) || a - b);
1297
+ const keep = new Set(order.slice(0, limit));
1298
+ return paths.filter((_, i) => keep.has(i));
1299
+ }
1300
+ /** A doc's current text, or "" when it can no longer be read. */
1301
+ readText(id) {
1302
+ return this.fs.readFile(id).catch(() => "");
1303
+ }
428
1304
  };
1305
+ var EMPTY_INDEX = new Bm25IndexBuilder().finish();
1306
+ function isIndexable(path3) {
1307
+ const lower = path3.toLowerCase();
1308
+ return INDEXED_EXTENSIONS.some((ext) => lower.endsWith(ext));
1309
+ }
1310
+ function mtimeOf(date) {
1311
+ return date ? Math.trunc(date.getTime()) : 0;
1312
+ }
1313
+ function result(hits, start, partial) {
1314
+ return {
1315
+ hits: Object.freeze(hits),
1316
+ tookMs: Date.now() - start,
1317
+ engine: FILES_ENGINE_ID,
1318
+ // BM25 isn't really "vector": the union doesn't have a "keyword"
1319
+ // option. Report "vector" as the closest existing label until the
1320
+ // mode union widens.
1321
+ modeUsed: "vector",
1322
+ ...partial ? { partial: true } : {}
1323
+ };
1324
+ }
1325
+ function toHit(id, score2, text, tokens) {
1326
+ const snippet = makeSnippet(text, tokens);
1327
+ return {
1328
+ sourceId: id,
1329
+ chunkId: id,
1330
+ text: snippet.text,
1331
+ score: score2,
1332
+ // span is in original-file bytes; matches engine "citations" capability.
1333
+ span: { start: snippet.start, end: snippet.end },
1334
+ metadata: parseFrontmatterMetadata(text)
1335
+ };
1336
+ }
1337
+ function heapUsedMb() {
1338
+ if (typeof process === "undefined" || !process.memoryUsage) return "?";
1339
+ return Math.round(process.memoryUsage().heapUsed / (1024 * 1024));
1340
+ }
1341
+ function fileSource(id, text) {
1342
+ const meta = parseFrontmatterMetadata(text);
1343
+ return {
1344
+ id,
1345
+ kind: "file",
1346
+ uri: id,
1347
+ title: typeof meta.title === "string" ? meta.title : void 0,
1348
+ bytes: byteLength(text),
1349
+ status: "ready",
1350
+ metadata: meta
1351
+ };
1352
+ }
429
1353
  async function mapWithConcurrency(items, limit, fn) {
430
1354
  const results = new Array(items.length);
431
1355
  let cursor = 0;
@@ -492,6 +1416,8 @@ function readCorpusMeta(metadata) {
492
1416
  chunkIndex: typeof block.chunkIndex === "number" ? block.chunkIndex : void 0
493
1417
  };
494
1418
  }
1419
+ var WALK_STAT_CONCURRENCY = 32;
1420
+ var WALK_STAT_YIELD_EVERY = 2e3;
495
1421
  var LocalFs = class {
496
1422
  root;
497
1423
  constructor(opts) {
@@ -514,14 +1440,14 @@ var LocalFs = class {
514
1440
  */
515
1441
  async writeFile(p, content) {
516
1442
  const target = this.resolve(p);
517
- await mkdir(path.dirname(target), { recursive: true });
1443
+ await mkdir(path2.dirname(target), { recursive: true });
518
1444
  const tmp = `${target}.tmp-${randomBytes(8).toString("hex")}`;
519
1445
  await writeFile(tmp, content, "utf8");
520
1446
  await rename(tmp, target);
521
1447
  }
522
1448
  async appendFile(p, content) {
523
1449
  const target = this.resolve(p);
524
- await mkdir(path.dirname(target), { recursive: true });
1450
+ await mkdir(path2.dirname(target), { recursive: true });
525
1451
  await appendFile(target, content, "utf8");
526
1452
  }
527
1453
  async readdir(p) {
@@ -539,18 +1465,74 @@ var LocalFs = class {
539
1465
  }
540
1466
  for (const ent of entries) {
541
1467
  if (ent.startsWith(".")) continue;
542
- const full = path.join(dir, ent);
1468
+ const full = path2.join(dir, ent);
543
1469
  const s = await stat(full);
544
1470
  if (s.isDirectory()) {
545
1471
  await visit(full);
546
1472
  } else if (s.isFile()) {
547
- out.push(path.relative(this.root, full).split(path.sep).join("/"));
1473
+ out.push(path2.relative(this.root, full).split(path2.sep).join("/"));
548
1474
  }
549
1475
  }
550
1476
  };
551
1477
  await visit(start);
552
1478
  return out;
553
1479
  }
1480
+ /**
1481
+ * {@link walk} plus each file's size and mtime, in one pass: the stat-only
1482
+ * scan the files engine reconciles its on-disk index with. Same paths and
1483
+ * hidden-segment rule as `walk`, but directory entries are typed by
1484
+ * `readdir`, so only files (and symlinks) cost a `stat`, and the stats of a
1485
+ * directory run concurrently. Not part of `FsPort`: the adapter uses it when
1486
+ * the backing has it and falls back to `walk` + `stat` otherwise.
1487
+ */
1488
+ async walkStat(p) {
1489
+ const out = [];
1490
+ const visit = async (dir) => {
1491
+ let entries = [];
1492
+ try {
1493
+ entries = await readdir(dir, { withFileTypes: true });
1494
+ } catch {
1495
+ return;
1496
+ }
1497
+ const visible = entries.filter((ent) => !ent.name.startsWith("."));
1498
+ const toStat = visible.filter((ent) => !ent.isDirectory());
1499
+ const stats = /* @__PURE__ */ new Map();
1500
+ for (let i = 0; i < toStat.length; i += WALK_STAT_CONCURRENCY) {
1501
+ const step = toStat.slice(i, i + WALK_STAT_CONCURRENCY);
1502
+ const got = await Promise.all(
1503
+ step.map((ent) => stat(path2.join(dir, ent.name)).catch(() => null))
1504
+ );
1505
+ step.forEach((ent, j) => stats.set(ent.name, got[j]));
1506
+ }
1507
+ const relDir = path2.relative(this.root, dir).split(path2.sep).join("/");
1508
+ const prefix = relDir === "" ? "" : `${relDir}/`;
1509
+ let emitted = 0;
1510
+ for (const ent of visible) {
1511
+ if (++emitted % WALK_STAT_YIELD_EVERY === 0) {
1512
+ await new Promise((resolve) => setImmediate(resolve));
1513
+ }
1514
+ if (ent.isDirectory()) {
1515
+ await visit(path2.join(dir, ent.name));
1516
+ continue;
1517
+ }
1518
+ const s = stats.get(ent.name);
1519
+ if (s?.isDirectory()) await visit(path2.join(dir, ent.name));
1520
+ else if (s?.isFile()) {
1521
+ out.push({
1522
+ path: prefix + ent.name,
1523
+ size: s.size,
1524
+ // `Stats.mtime` (Node rounds `mtimeMs` to whole ms), exactly what
1525
+ // `stat()` reports: the reconcile compares rows written from one
1526
+ // against scans from the other, and truncating `mtimeMs` would
1527
+ // differ by 1 ms on sub-ms filesystems and re-index every time.
1528
+ mtimeMs: s.mtime.getTime()
1529
+ });
1530
+ }
1531
+ }
1532
+ };
1533
+ await visit(this.resolve(p));
1534
+ return out;
1535
+ }
554
1536
  async stat(p) {
555
1537
  try {
556
1538
  const s = await stat(this.resolve(p));
@@ -578,14 +1560,14 @@ var LocalFs = class {
578
1560
  * abuse). The files engine's paths must stay inside the workspace.
579
1561
  */
580
1562
  resolve(p) {
581
- const normalized = path.posix.normalize("/" + p.replace(/^\/+/, ""));
1563
+ const normalized = path2.posix.normalize("/" + p.replace(/^\/+/, ""));
582
1564
  const rel = normalized.slice(1);
583
1565
  if (rel.startsWith("..")) {
584
1566
  throw new Error(
585
1567
  `LocalFs: path "${p}" escapes the workspace root "${this.root}"`
586
1568
  );
587
1569
  }
588
- return path.join(this.root, rel);
1570
+ return path2.join(this.root, rel);
589
1571
  }
590
1572
  };
591
1573
 
@@ -593,9 +1575,11 @@ var LocalFs = class {
593
1575
  function loadFilesKnowledgeEnv() {
594
1576
  const root = process.env.KNOWLEDGE_FILES_ROOT;
595
1577
  const workspacePath = process.env.KNOWLEDGE_FILES_PATH;
1578
+ const indexPath = process.env.KNOWLEDGE_FILES_INDEX_PATH?.trim();
596
1579
  return {
597
1580
  root: root !== void 0 && root !== "" ? root : process.cwd(),
598
- workspacePath: workspacePath !== void 0 && workspacePath !== "" ? workspacePath.trim() : "knowledge"
1581
+ workspacePath: workspacePath !== void 0 && workspacePath !== "" ? workspacePath.trim() : "knowledge",
1582
+ ...indexPath ? { indexPath } : {}
599
1583
  };
600
1584
  }
601
1585
 
@@ -604,7 +1588,8 @@ function createStandaloneFilesAdapter() {
604
1588
  const env = loadFilesKnowledgeEnv();
605
1589
  return new FilesKnowledgeAdapter({
606
1590
  fs: new LocalFs({ root: env.root }),
607
- workspacePath: env.workspacePath
1591
+ workspacePath: env.workspacePath,
1592
+ ...env.indexPath ? { indexPath: env.indexPath } : {}
608
1593
  });
609
1594
  }
610
1595
 
@@ -615,7 +1600,7 @@ var KNOWLEDGE_FILES_CATALOG = [
615
1600
  {
616
1601
  slug: FILES_BM25_SLUG,
617
1602
  name: "files (BM25)",
618
- description: "Knowledge retrieval from local workspace files via an in-process BM25 index. No embeddings, no network, no API key \u2014 works the instant a workspace has files to index.",
1603
+ description: "Knowledge retrieval from local workspace files via a BM25 index (on disk in SQLite FTS5 when available, in process otherwise). No embeddings, no network, no API key; works the instant a workspace has files to index.",
619
1604
  packageName: "@agentproto/adapter-knowledge-files",
620
1605
  hint: "files \xB7 bm25"
621
1606
  }
@@ -659,6 +1644,6 @@ function makeKnowledgeFilesResolver() {
659
1644
  });
660
1645
  }
661
1646
 
662
- export { FILES_BM25_SLUG, FILES_CAPABILITIES, FILES_ENGINE_ID, FilesKnowledgeAdapter, KNOWLEDGE_FAMILY, KNOWLEDGE_FILES_CATALOG, LocalFs, buildIndex, buildIndexYielding, createStandaloneFilesAdapter, loadFilesKnowledgeEnv, makeKnowledgeFilesResolver, resolveKnowledgeBackend, score, tokenize };
1647
+ export { Bm25IndexBuilder, DEFAULT_MAX_INDEX_DOCS, DEFAULT_RECONCILE_INTERVAL_MS, FILES_BM25_SLUG, FILES_CAPABILITIES, FILES_ENGINE_ID, FilesIndexTooLargeError, FilesKnowledgeAdapter, KNOWLEDGE_FAMILY, KNOWLEDGE_FILES_CATALOG, LocalFs, bm25Idf, bm25TermScore, buildIndex, buildIndexYielding, createStandaloneFilesAdapter, documentFrequency, filesIndexBuildsRunning, loadFilesKnowledgeEnv, makeKnowledgeFilesResolver, makeSnippet, resolveKnowledgeBackend, score, stripFrontmatter, tokenize };
663
1648
  //# sourceMappingURL=index.mjs.map
664
1649
  //# sourceMappingURL=index.mjs.map