@agentproto/adapter-knowledge-files 0.4.0 → 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);
@@ -191,6 +193,13 @@ function termFrequency(index, docIndex, termId) {
191
193
  }
192
194
  return 0;
193
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);
202
+ }
194
203
  function score(index, queryTokens, opts = {}) {
195
204
  if (queryTokens.length === 0 || index.docs.length === 0) return [];
196
205
  const topK = opts.topK ?? 10;
@@ -201,8 +210,7 @@ function score(index, queryTokens, opts = {}) {
201
210
  for (const tok of queryTokens) {
202
211
  const termId = index.vocab.get(tok);
203
212
  if (termId === void 0) continue;
204
- const n = index.df[termId];
205
- terms.push({ termId, idf: Math.log((N - n + 0.5) / (n + 0.5) + 1) });
213
+ terms.push({ termId, idf: bm25Idf(N, index.df[termId]) });
206
214
  }
207
215
  const out = [];
208
216
  for (let i = 0; i < N; i++) {
@@ -211,8 +219,7 @@ function score(index, queryTokens, opts = {}) {
211
219
  for (const { termId, idf } of terms) {
212
220
  const f = termFrequency(index, i, termId);
213
221
  if (!f) continue;
214
- const denom = f + K1 * (1 - B + B * doc.length / avgDocLength);
215
- s += idf * (f * (K1 + 1) / denom);
222
+ s += bm25TermScore(idf, f, doc.length, avgDocLength);
216
223
  }
217
224
  if (s <= minScore) continue;
218
225
  out.push({ doc, score: s });
@@ -239,6 +246,444 @@ function makeSnippet(text, queryTokens) {
239
246
  };
240
247
  }
241
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
+
242
687
  // src/adapter.ts
243
688
  var FILES_ENGINE_ID = "files";
244
689
  var INDEXED_EXTENSIONS = [
@@ -251,8 +696,14 @@ var INDEXED_EXTENSIONS = [
251
696
  ];
252
697
  var CACHE_TTL_MS = Number.POSITIVE_INFINITY;
253
698
  var INDEX_READ_CONCURRENCY = 10;
699
+ var SCAN_STAT_CONCURRENCY = 32;
254
700
  var INDEX_QUERY_TIMEOUT_MS = 4e3;
255
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;
256
707
  var DEFAULT_MAX_INDEX_DOCS = 1e5;
257
708
  var FilesIndexTooLargeError = class extends Error {
258
709
  docCount;
@@ -305,16 +756,34 @@ var FilesKnowledgeAdapter = class {
305
756
  maxIndexDocs;
306
757
  queryTimeoutMs;
307
758
  log;
759
+ indexPath;
760
+ indexWorker;
761
+ reconcileIntervalMs;
762
+ // ── in-memory engine ──
308
763
  cachedIndex = null;
309
764
  cachedAt = 0;
765
+ // True when the cached index holds only the most recent maxIndexDocs files.
766
+ cachedPartial = false;
310
767
  // In-flight build promise: concurrent turns that arrive while the index is
311
768
  // still being built (cachedIndex === null) coalesce onto this promise instead
312
769
  // of each kicking off a redundant 40-50s Supabase Storage re-scan.
313
770
  buildInFlight = null;
314
771
  buildStartedAt = 0;
315
- // A refused build (over the ceiling) is remembered until the next
316
- // invalidate(), so repeated queries do not re-walk a huge brain.
317
- refusal = null;
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;
318
787
  constructor(opts) {
319
788
  this.fs = opts.fs;
320
789
  this.workspacePath = opts.workspacePath;
@@ -322,6 +791,9 @@ var FilesKnowledgeAdapter = class {
322
791
  this.maxIndexDocs = typeof opts.maxIndexDocs === "number" && opts.maxIndexDocs > 0 ? opts.maxIndexDocs : DEFAULT_MAX_INDEX_DOCS;
323
792
  this.queryTimeoutMs = opts.queryTimeoutMs ?? INDEX_QUERY_TIMEOUT_MS;
324
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;
325
797
  }
326
798
  async ingest(input) {
327
799
  const corpusBlock = readCorpusMeta(input.metadata);
@@ -343,7 +815,7 @@ var FilesKnowledgeAdapter = class {
343
815
  const dest = `${this.workspacePath}/sources/${sourceId}.md`;
344
816
  const content = decodeContent(input.content) ?? "";
345
817
  await this.fs.writeFile(dest, content);
346
- this.invalidate();
818
+ await this.indexWritten(dest, content);
347
819
  return {
348
820
  id: sourceId,
349
821
  kind: "text",
@@ -366,7 +838,7 @@ var FilesKnowledgeAdapter = class {
366
838
  const sourceId = stableSlug(input.uri);
367
839
  const dest = `${this.workspacePath}/sources/${sourceId}.txt`;
368
840
  await this.fs.writeFile(dest, text);
369
- this.invalidate();
841
+ await this.indexWritten(dest, text);
370
842
  return {
371
843
  id: sourceId,
372
844
  kind: "url",
@@ -384,15 +856,19 @@ var FilesKnowledgeAdapter = class {
384
856
  }
385
857
  async query(q) {
386
858
  const start = Date.now();
387
- const index = await this.ensureIndex(this.queryTimeoutMs);
388
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;
389
870
  if (tokens.length === 0) {
390
- return {
391
- hits: Object.freeze([]),
392
- tookMs: Date.now() - start,
393
- engine: this.id,
394
- modeUsed: "vector"
395
- };
871
+ return result([], start, partial);
396
872
  }
397
873
  const scored = score(index, tokens, {
398
874
  topK: q.topK,
@@ -403,47 +879,38 @@ var FilesKnowledgeAdapter = class {
403
879
  INDEX_READ_CONCURRENCY,
404
880
  (s) => this.readText(s.doc.id)
405
881
  );
406
- const hits = scored.map((s, i) => {
407
- const text = texts[i];
408
- const meta = parseFrontmatterMetadata(text);
409
- const snippet = makeSnippet(text, tokens);
410
- return {
411
- sourceId: s.doc.id,
412
- chunkId: s.doc.id,
413
- text: snippet.text,
414
- score: s.score,
415
- // span is in original-file bytes; matches engine "citations" capability.
416
- span: { start: snippet.start, end: snippet.end },
417
- metadata: meta
418
- };
419
- });
420
- return {
421
- hits: Object.freeze(hits),
422
- tookMs: Date.now() - start,
423
- engine: this.id,
424
- // BM25 isn't really "vector" — the union doesn't have a "keyword"
425
- // option. Report "vector" as the closest existing label until the
426
- // mode union widens.
427
- modeUsed: "vector"
428
- };
882
+ return result(
883
+ scored.map((s, i) => toHit(s.doc.id, s.score, texts[i], tokens)),
884
+ start,
885
+ partial
886
+ );
429
887
  }
430
888
  async listSources(filter) {
431
- const index = await this.ensureIndex();
889
+ const ids = await this.indexedIds();
432
890
  if (filter?.kind && filter.kind !== "file") return Object.freeze([]);
433
891
  if (filter?.status && filter.status !== "ready") return Object.freeze([]);
434
892
  const out = [];
435
- for (let i = 0; i < index.docs.length; i += INDEX_BUILD_STEP) {
436
- const step = index.docs.slice(i, i + INDEX_BUILD_STEP);
893
+ for (let i = 0; i < ids.length; i += INDEX_BUILD_STEP) {
894
+ const step = ids.slice(i, i + INDEX_BUILD_STEP);
437
895
  const texts = await mapWithConcurrency(
438
896
  step,
439
897
  INDEX_READ_CONCURRENCY,
440
- (doc) => this.readText(doc.id)
898
+ (id) => this.readText(id)
441
899
  );
442
- step.forEach((doc, j) => out.push(fileSource(doc.id, texts[j])));
900
+ step.forEach((id, j) => out.push(fileSource(id, texts[j])));
443
901
  }
444
902
  return Object.freeze(out);
445
903
  }
446
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
+ }
447
914
  const index = await this.ensureIndex();
448
915
  const doc = index.docs.find((d) => d.id === id);
449
916
  if (!doc) return null;
@@ -452,6 +919,18 @@ var FilesKnowledgeAdapter = class {
452
919
  async deleteSource(id) {
453
920
  if (await this.fs.exists(id)) {
454
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
+ }
455
934
  }
456
935
  this.invalidate();
457
936
  }
@@ -480,18 +959,267 @@ var FilesKnowledgeAdapter = class {
480
959
  }
481
960
  async dispose() {
482
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();
967
+ }
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);
483
976
  }
484
- /** Drop the cached BM25 index — next query rebuilds. */
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
+ */
485
981
  invalidate() {
486
982
  this.cachedIndex = null;
487
983
  this.cachedAt = 0;
488
- this.refusal = null;
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;
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
+ };
489
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 ──────────────────────────────────────────────
490
1219
  async ensureIndex(timeoutMs) {
491
1220
  if (this.cachedIndex && Date.now() - this.cachedAt < CACHE_TTL_MS) {
492
1221
  return this.cachedIndex;
493
1222
  }
494
- if (this.refusal) throw this.refusal;
495
1223
  if (!this.buildInFlight) {
496
1224
  this.buildStartedAt = Date.now();
497
1225
  const build = runExclusiveBuild(() => this._buildIndex()).finally(() => {
@@ -521,20 +1249,15 @@ var FilesKnowledgeAdapter = class {
521
1249
  const start = Date.now();
522
1250
  const heapBefore = heapUsedMb();
523
1251
  const allPaths = await this.fs.walk(this.workspacePath);
524
- const candidates = allPaths.filter(
525
- (p) => INDEXED_EXTENSIONS.some((ext) => p.toLowerCase().endsWith(ext))
526
- );
1252
+ let candidates = allPaths.filter(isIndexable);
1253
+ let partial = false;
527
1254
  if (candidates.length > this.maxIndexDocs) {
528
- const refusal = new FilesIndexTooLargeError(
529
- this.label,
530
- candidates.length,
531
- this.maxIndexDocs
532
- );
533
- this.refusal = refusal;
1255
+ const total = candidates.length;
1256
+ candidates = await this.mostRecent(candidates, this.maxIndexDocs);
1257
+ partial = true;
534
1258
  this.log(
535
- `[knowledge-files:${this.label}] index build refused: ${candidates.length} indexable files exceed the ceiling of ${this.maxIndexDocs}`
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`
536
1260
  );
537
- throw refusal;
538
1261
  }
539
1262
  const builder = new Bm25IndexBuilder();
540
1263
  let bytesRead = 0;
@@ -544,29 +1267,73 @@ var FilesKnowledgeAdapter = class {
544
1267
  const texts = await mapWithConcurrency(
545
1268
  step,
546
1269
  INDEX_READ_CONCURRENCY,
547
- (path2) => this.fs.readFile(path2).catch(() => "")
1270
+ (path3) => this.fs.readFile(path3).catch(() => "")
548
1271
  );
549
- step.forEach((path2, j) => {
1272
+ step.forEach((path3, j) => {
550
1273
  const content = texts[j];
551
1274
  if (content.length === 0) return;
552
1275
  bytesRead += byteLength(content);
553
- builder.add(path2, content);
1276
+ builder.add(path3, content);
554
1277
  });
555
1278
  }
556
1279
  const index = builder.finish();
557
1280
  this.cachedIndex = index;
558
1281
  this.cachedAt = Date.now();
1282
+ this.cachedPartial = partial;
559
1283
  this.log(
560
1284
  `[knowledge-files:${this.label}] index built: ${index.docs.length} docs, ${bytesRead} bytes read, ${Date.now() - start} ms, heapUsed ${heapBefore} MB -> ${heapUsedMb()} MB`
561
1285
  );
562
1286
  return index;
563
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
+ }
564
1300
  /** A doc's current text, or "" when it can no longer be read. */
565
1301
  readText(id) {
566
1302
  return this.fs.readFile(id).catch(() => "");
567
1303
  }
568
1304
  };
569
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
+ }
570
1337
  function heapUsedMb() {
571
1338
  if (typeof process === "undefined" || !process.memoryUsage) return "?";
572
1339
  return Math.round(process.memoryUsage().heapUsed / (1024 * 1024));
@@ -649,6 +1416,8 @@ function readCorpusMeta(metadata) {
649
1416
  chunkIndex: typeof block.chunkIndex === "number" ? block.chunkIndex : void 0
650
1417
  };
651
1418
  }
1419
+ var WALK_STAT_CONCURRENCY = 32;
1420
+ var WALK_STAT_YIELD_EVERY = 2e3;
652
1421
  var LocalFs = class {
653
1422
  root;
654
1423
  constructor(opts) {
@@ -671,14 +1440,14 @@ var LocalFs = class {
671
1440
  */
672
1441
  async writeFile(p, content) {
673
1442
  const target = this.resolve(p);
674
- await mkdir(path.dirname(target), { recursive: true });
1443
+ await mkdir(path2.dirname(target), { recursive: true });
675
1444
  const tmp = `${target}.tmp-${randomBytes(8).toString("hex")}`;
676
1445
  await writeFile(tmp, content, "utf8");
677
1446
  await rename(tmp, target);
678
1447
  }
679
1448
  async appendFile(p, content) {
680
1449
  const target = this.resolve(p);
681
- await mkdir(path.dirname(target), { recursive: true });
1450
+ await mkdir(path2.dirname(target), { recursive: true });
682
1451
  await appendFile(target, content, "utf8");
683
1452
  }
684
1453
  async readdir(p) {
@@ -696,18 +1465,74 @@ var LocalFs = class {
696
1465
  }
697
1466
  for (const ent of entries) {
698
1467
  if (ent.startsWith(".")) continue;
699
- const full = path.join(dir, ent);
1468
+ const full = path2.join(dir, ent);
700
1469
  const s = await stat(full);
701
1470
  if (s.isDirectory()) {
702
1471
  await visit(full);
703
1472
  } else if (s.isFile()) {
704
- out.push(path.relative(this.root, full).split(path.sep).join("/"));
1473
+ out.push(path2.relative(this.root, full).split(path2.sep).join("/"));
705
1474
  }
706
1475
  }
707
1476
  };
708
1477
  await visit(start);
709
1478
  return out;
710
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
+ }
711
1536
  async stat(p) {
712
1537
  try {
713
1538
  const s = await stat(this.resolve(p));
@@ -735,14 +1560,14 @@ var LocalFs = class {
735
1560
  * abuse). The files engine's paths must stay inside the workspace.
736
1561
  */
737
1562
  resolve(p) {
738
- const normalized = path.posix.normalize("/" + p.replace(/^\/+/, ""));
1563
+ const normalized = path2.posix.normalize("/" + p.replace(/^\/+/, ""));
739
1564
  const rel = normalized.slice(1);
740
1565
  if (rel.startsWith("..")) {
741
1566
  throw new Error(
742
1567
  `LocalFs: path "${p}" escapes the workspace root "${this.root}"`
743
1568
  );
744
1569
  }
745
- return path.join(this.root, rel);
1570
+ return path2.join(this.root, rel);
746
1571
  }
747
1572
  };
748
1573
 
@@ -750,9 +1575,11 @@ var LocalFs = class {
750
1575
  function loadFilesKnowledgeEnv() {
751
1576
  const root = process.env.KNOWLEDGE_FILES_ROOT;
752
1577
  const workspacePath = process.env.KNOWLEDGE_FILES_PATH;
1578
+ const indexPath = process.env.KNOWLEDGE_FILES_INDEX_PATH?.trim();
753
1579
  return {
754
1580
  root: root !== void 0 && root !== "" ? root : process.cwd(),
755
- workspacePath: workspacePath !== void 0 && workspacePath !== "" ? workspacePath.trim() : "knowledge"
1581
+ workspacePath: workspacePath !== void 0 && workspacePath !== "" ? workspacePath.trim() : "knowledge",
1582
+ ...indexPath ? { indexPath } : {}
756
1583
  };
757
1584
  }
758
1585
 
@@ -761,7 +1588,8 @@ function createStandaloneFilesAdapter() {
761
1588
  const env = loadFilesKnowledgeEnv();
762
1589
  return new FilesKnowledgeAdapter({
763
1590
  fs: new LocalFs({ root: env.root }),
764
- workspacePath: env.workspacePath
1591
+ workspacePath: env.workspacePath,
1592
+ ...env.indexPath ? { indexPath: env.indexPath } : {}
765
1593
  });
766
1594
  }
767
1595
 
@@ -772,7 +1600,7 @@ var KNOWLEDGE_FILES_CATALOG = [
772
1600
  {
773
1601
  slug: FILES_BM25_SLUG,
774
1602
  name: "files (BM25)",
775
- 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.",
776
1604
  packageName: "@agentproto/adapter-knowledge-files",
777
1605
  hint: "files \xB7 bm25"
778
1606
  }
@@ -816,6 +1644,6 @@ function makeKnowledgeFilesResolver() {
816
1644
  });
817
1645
  }
818
1646
 
819
- export { Bm25IndexBuilder, DEFAULT_MAX_INDEX_DOCS, FILES_BM25_SLUG, FILES_CAPABILITIES, FILES_ENGINE_ID, FilesIndexTooLargeError, FilesKnowledgeAdapter, KNOWLEDGE_FAMILY, KNOWLEDGE_FILES_CATALOG, LocalFs, buildIndex, buildIndexYielding, createStandaloneFilesAdapter, documentFrequency, filesIndexBuildsRunning, loadFilesKnowledgeEnv, makeKnowledgeFilesResolver, makeSnippet, resolveKnowledgeBackend, score, stripFrontmatter, 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 };
820
1648
  //# sourceMappingURL=index.mjs.map
821
1649
  //# sourceMappingURL=index.mjs.map