@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/README.md CHANGED
@@ -4,9 +4,10 @@ The pure, zero-runtime **files** backing for the
4
4
  [`@agentproto/knowledge-engine`](../../packages/knowledge-engine)
5
5
  `IKnowledgeProvider` contract.
6
6
 
7
- Knowledge retrieval from local workspace files via an **in-process BM25
8
- index** — no embeddings, no vector store, no network, no API key. It works the
9
- instant a workspace has files to index, which makes it the natural default
7
+ Knowledge retrieval from local workspace files via a **BM25 index**, kept on
8
+ disk in SQLite FTS5 when the runtime has it and in process otherwise: no
9
+ embeddings, no vector store, no network, no API key. It works the instant a
10
+ workspace has files to index, which makes it the natural default
10
11
  corpus backing where AIP-10 entries already live as markdown: the entries
11
12
  _are_ the index, with no separate store to keep in sync.
12
13
 
@@ -17,7 +18,7 @@ _are_ the index, with no separate store to keep in sync.
17
18
  | `FilesKnowledgeAdapter` | The `IKnowledgeProvider` implementation. Consumes an injected `FsPort`; knows nothing about `node:fs` or `process.env`. |
18
19
  | `LocalFs` | A `node:fs`-backed `FsPort` (from `@agentproto/corpus`) so the adapter runs standalone. Paths are workspace-relative and can't escape the root. |
19
20
  | `createStandaloneFilesAdapter()` | Wires `LocalFs` + the typed env into a ready-to-use adapter. |
20
- | BM25 (`tokenize`, `buildIndex`, `buildIndexYielding`, `score`) | The dependency-free ranking core. Confined to this package. |
21
+ | BM25 (`tokenize`, `buildIndex`, `buildIndexYielding`, `Bm25IndexBuilder`, `score`, `makeSnippet`) | The dependency-free ranking core. Confined to this package. |
21
22
  | provider-kit family (`KNOWLEDGE_FILES_CATALOG`, `makeKnowledgeFilesResolver`, `resolveKnowledgeBackend`) | Registers the `files` backend under the `@agentproto/adapter-knowledge-*` discovery convention. |
22
23
 
23
24
  ## Usage
@@ -39,6 +40,16 @@ import { FilesKnowledgeAdapter } from "@agentproto/adapter-knowledge-files"
39
40
  const kb = new FilesKnowledgeAdapter({ fs, workspacePath: "knowledge" })
40
41
  ```
41
42
 
43
+ With an on-disk index (recommended for anything large):
44
+
45
+ ```ts
46
+ const kb = new FilesKnowledgeAdapter({
47
+ fs,
48
+ workspacePath: "knowledge",
49
+ indexPath: "/abs/path/to/brain/.index/fts.sqlite",
50
+ })
51
+ ```
52
+
42
53
  Through the provider-kit resolver (discovery / catalogs):
43
54
 
44
55
  ```ts
@@ -57,6 +68,7 @@ names live:
57
68
  | --- | --- | --- |
58
69
  | `KNOWLEDGE_FILES_ROOT` | `process.cwd()` | Absolute host path the `LocalFs` is rooted at. |
59
70
  | `KNOWLEDGE_FILES_PATH` | `knowledge` | Workspace-relative folder walked and indexed (recursively). |
71
+ | `KNOWLEDGE_FILES_INDEX_PATH` | unset | Absolute path of the on-disk index file. Unset: in-memory index. |
60
72
 
61
73
  ## Indexing model
62
74
 
@@ -64,11 +76,77 @@ names live:
64
76
  YAML frontmatter is stripped before tokenizing so schema fences don't pollute
65
77
  the vocabulary; frontmatter is still surfaced as each hit's `metadata` (and a
66
78
  `slug` mirrors to `entrySlug` for corpus hydration).
67
- - **Ranking:** standard BM25 (k1=1.5, b=0.75) with `+1`-smoothed IDF.
68
- - **Cache:** the index is built lazily on first query and cached permanently —
69
- it's rebuilt only when the adapter `invalidate()`s (via `ingest`/`delete`) or
70
- a fresh instance is created. Hosts wanting second-precision freshness on
71
- external edits can wire fs-watch into a new instance.
79
+ - **Ranking:** standard BM25 (k1=1.5, b=0.75) with `+1`-smoothed IDF, on both
80
+ engines (see the on-disk section for how).
81
+ - **Two engines.** With `indexPath` set and a runtime whose `node:sqlite` has
82
+ FTS5, the index lives on disk; otherwise (no `indexPath`, Node 20, Node
83
+ 22.5-22.12 without `--experimental-sqlite`, or the on-disk index failing to
84
+ open) it lives in process. `node:sqlite` is loaded dynamically, so the
85
+ package still runs on `node >= 20.9`.
86
+
87
+ ### On-disk index (SQLite FTS5)
88
+
89
+ - **Where:** the file at `indexPath`, e.g. `<brain>/.index/fts.sqlite` (a
90
+ hidden directory, so never walked as content). WAL mode, one connection per
91
+ file per process. It is derived data: delete it and the next open rebuilds
92
+ it; an unreadable file is deleted and rebuilt; a schema or tokenizer change
93
+ (`meta.version`) drops the tables and rebuilds.
94
+ - **Off the main thread:** SQLite runs in a `worker_threads` worker
95
+ (`indexWorker: false` runs it inline). The build reads files on the caller's
96
+ thread, 100 per batch, and hands them to the worker, which tokenizes and
97
+ writes them in one transaction per batch.
98
+ - **Incremental:** `ingest()` upserts the written doc's row, `deleteSource()`
99
+ empties it. Nothing invalidates the whole brain.
100
+ - **External edits:** on open, and then at most every `reconcileIntervalMs`
101
+ (default 5 min, checked when a query arrives, run in the background), a
102
+ stat-only scan (path, size, mtime) re-indexes only the files that changed
103
+ and drops rows whose file is gone. `invalidate()` makes the next query
104
+ start one.
105
+ - **First build:** batched and yielding. A query during it answers from what
106
+ is already indexed and sets `partial: true` on the result; it never waits,
107
+ fails, or refuses.
108
+ - **Ranking parity:** the FTS column stores the doc's tokens from the same
109
+ tokenizer (lowercase, split on non `[a-z0-9]`, length 2-32, stopwords,
110
+ frontmatter stripped) under FTS5's `ascii` tokenizer, so doc lengths and
111
+ frequencies match the in-memory engine. FTS5's `bm25()` (k1 1.2, and a zero
112
+ IDF for terms in more than half the docs) picks `max(topK * 8, 80)`
113
+ candidates (at most 300); those are re-scored with this package's BM25 from
114
+ their text, read back from disk anyway for the snippet. On a generated
115
+ corpus the top-10 overlap with the in-memory engine is 99.7%; the captured
116
+ parity fixture matches exactly. Only docs matching at least one query term
117
+ are returned, so a negative `minScore` does not pad the result.
118
+ - **No ceiling:** `maxIndexDocs` does not apply.
119
+
120
+ ### In-memory index (fallback)
121
+
122
+ - **Cache:** built lazily on first query and cached permanently, rebuilt only
123
+ when the adapter `invalidate()`s (via `ingest`/`delete`) or a fresh instance
124
+ is created.
125
+ - **Memory:** the resident index holds no doc text: per doc only its id and
126
+ token count, plus every doc's (term id, term frequency) pairs packed into
127
+ shared typed arrays and one term vocabulary. A query reads the top-K files
128
+ back from disk for their snippet and frontmatter. A build reads files 50 at a
129
+ time, so only one step of text is alive at once.
130
+ - **Ceiling:** above `maxIndexDocs` indexable files (default 100,000) it
131
+ indexes the most recently modified `maxIndexDocs` files and flags every
132
+ result `partial: true`. Search is never refused (`FilesIndexTooLargeError` is
133
+ kept for compatibility but no longer thrown).
134
+ - **Cold build:** a query waits at most `queryTimeoutMs` (4 s) for it, then
135
+ answers with no hits and `partial: true` while the build keeps going.
136
+
137
+ ### Both engines
138
+
139
+ - **One build at a time:** index builds (and on-disk reconciles) are
140
+ serialized across every adapter in the process, so cold queries on several
141
+ brains never stack their peaks.
142
+ - **Logs:** one line per build (`[knowledge-files:<label>] index built: N docs,
143
+ B bytes read, T ms, heapUsed X MB -> Y MB`, plus `(on disk, F files scanned
144
+ in S ms)` for the on-disk engine), per on-disk open, per reconcile
145
+ (`index reconciled: F files scanned in S ms, C re-indexed, R removed, B bytes
146
+ read, T ms; U upserts and D deletes applied incrementally since the last
147
+ reconcile`), per query answered from a partial on-disk index, per in-memory
148
+ cap, per fallback to the in-memory engine, and per query that times out
149
+ waiting for a cold in-memory build. Inject `log` to route them elsewhere.
72
150
 
73
151
  ## Provenance and supersession
74
152
 
package/dist/index.d.ts CHANGED
@@ -5,31 +5,68 @@ import { AdapterCatalog, AdapterHandle, AdapterResolver } from '@agentproto/prov
5
5
  /**
6
6
  * FilesKnowledgeAdapter — the no-runtime, no-embedding KB engine.
7
7
  *
8
- * Indexes workspace files in process with BM25. Zero setup: works the
9
- * instant a guild has a system workspace, no E2B sandbox, no API key,
10
- * no cold start. Best suited as the DEFAULT corpus backing where the
11
- * AIP-10 entries already live as markdown files — the entries ARE the
12
- * index, no separate vector store to keep in sync.
8
+ * Indexes workspace files with BM25. Zero setup: works the instant a guild
9
+ * has a system workspace, no E2B sandbox, no API key, no cold start. Best
10
+ * suited as the DEFAULT corpus backing where the AIP-10 entries already live
11
+ * as markdown files: the entries ARE the index, no separate vector store to
12
+ * keep in sync.
13
13
  *
14
- * Index lifecycle: built lazily on first query, cached for 30s, also
15
- * invalidated explicitly by `ingest()`. External edits (a user typing
16
- * in the workspace UI) become visible on the next rebuild — for
17
- * second-precision freshness, hosts can wire fs-watch into the
18
- * `invalidate()` method.
14
+ * Two index engines, picked per adapter:
19
15
  *
20
- * Lifted VERBATIM from the studio integration package
21
- * (`packages/integration/knowledge/src/providers/files/adapter.ts`) — the
22
- * class already carried no `@guilde/@simone/@agstudio` edge (it consumes an
23
- * injected `FsPort` and the vendor-neutral `IKnowledgeProvider` contract), so
24
- * it re-homes as-is. The ONLY change is the two import paths: the contract +
25
- * data types now come from `@agentproto/knowledge-engine` (was
26
- * `../base-knowledge.provider` / `../../types/knowledge.types`). The guild-side
27
- * `KnowledgeEngineDescriptor` (studio `descriptor.ts`) is NOT lifted — it
28
- * belonged to the guild resolution layer; this package registers as a
29
- * provider-kit family instead (see `handle.ts`).
16
+ * - **On disk (FTS5)** when `indexPath` is set and the runtime has
17
+ * `node:sqlite` with FTS5 (Node 22.13+ / 23.4+ / 24+; 22.5-22.12 only with
18
+ * `--experimental-sqlite`). The index is a SQLite file next to the corpus,
19
+ * updated per document: `ingest()` upserts that doc's row, `deleteSource()`
20
+ * empties it, nothing invalidates the whole brain. On open, and then at
21
+ * most every `reconcileIntervalMs` (checked when a query arrives), a
22
+ * stat-only scan of the files re-indexes what changed outside the adapter
23
+ * and drops rows whose file is gone. The first build of a large brain runs
24
+ * in batches; a query during it answers from what is already indexed with
25
+ * `partial: true`. Candidates come from FTS5's own `bm25()`, then the top
26
+ * ones are re-scored with this package's BM25 (k1 1.5, +1 IDF) from their
27
+ * text, read back from disk anyway for the snippet. No size ceiling.
28
+ * - **In memory** otherwise (no `indexPath`, Node 20, no FTS5, or the on-disk
29
+ * index failing): the lean BM25 index of bm25.ts, built lazily on first
30
+ * query, kept until `ingest()` invalidates it. Above `maxIndexDocs` files it
31
+ * indexes the most recently modified `maxIndexDocs` and flags every result
32
+ * `partial` instead of refusing.
33
+ *
34
+ * Lifted from the studio integration package
35
+ * (`packages/integration/knowledge/src/providers/files/adapter.ts`), which
36
+ * consumed an injected `FsPort` and the vendor-neutral `IKnowledgeProvider`
37
+ * contract. The guild-side `KnowledgeEngineDescriptor` (studio
38
+ * `descriptor.ts`) is NOT lifted: it belonged to the guild resolution layer;
39
+ * this package registers as a provider-kit family instead (see `handle.ts`).
30
40
  */
31
41
 
32
42
  declare const FILES_ENGINE_ID: "files";
43
+ /** Default gap between two reconcile scans of the on-disk index. A scan is
44
+ * stat-only (no reads unless a file changed) and runs in the background:
45
+ * a query that finds the last scan older than this starts one and answers
46
+ * right away. */
47
+ declare const DEFAULT_RECONCILE_INTERVAL_MS: number;
48
+ /**
49
+ * Ceiling on the files the IN-MEMORY engine indexes (the on-disk index has
50
+ * none). Above it, the in-memory engine indexes only the most recently
51
+ * modified `maxIndexDocs` files and flags results `partial`. Measured on
52
+ * 5.8 KB transcript-shaped docs, the lean index costs about 2.4 KB of heap per
53
+ * doc; real brains measured up to 5 KB, so 100,000 docs is about 500 MB
54
+ * resident at worst.
55
+ */
56
+ declare const DEFAULT_MAX_INDEX_DOCS = 100000;
57
+ /**
58
+ * @deprecated No longer thrown: over the ceiling the in-memory engine now
59
+ * indexes the most recent `maxIndexDocs` files and flags results `partial`,
60
+ * and the on-disk engine has no ceiling. Kept so existing imports and
61
+ * `err.name` checks keep compiling.
62
+ */
63
+ declare class FilesIndexTooLargeError extends Error {
64
+ readonly docCount: number;
65
+ readonly maxDocs: number;
66
+ constructor(label: string, docCount: number, maxDocs: number);
67
+ }
68
+ /** Index builds running right now, process wide (0 or 1). For tests. */
69
+ declare function filesIndexBuildsRunning(): number;
33
70
  declare const FILES_CAPABILITIES: KnowledgeCapabilities;
34
71
  interface FilesAdapterConfig {
35
72
  /** Workspace-relative root the engine indexes (walks recursively). */
@@ -38,15 +75,60 @@ interface FilesAdapterConfig {
38
75
  interface FilesKnowledgeAdapterOptions extends FilesAdapterConfig {
39
76
  /** FsPort scoped to the workspace the engine lives in. */
40
77
  readonly fs: FsPort;
78
+ /** Name used in log lines and errors (e.g. the brain's workspace slug).
79
+ * Defaults to `workspacePath`. */
80
+ readonly label?: string;
81
+ /** Absolute host path of the on-disk index file (SQLite FTS5), e.g.
82
+ * `<brain>/.index/fts.sqlite`. Keep it out of the walked tree (a hidden
83
+ * directory is skipped). Absent: in-memory index only. The file is
84
+ * derived data: deleting it only costs a rebuild. */
85
+ readonly indexPath?: string;
86
+ /** Run the on-disk index in a worker thread so SQLite never blocks the
87
+ * caller's thread. Default true. */
88
+ readonly indexWorker?: boolean;
89
+ /** Gap between two reconcile scans of the on-disk index; 0 scans only
90
+ * when the index is opened. Default {@link DEFAULT_RECONCILE_INTERVAL_MS}. */
91
+ readonly reconcileIntervalMs?: number;
92
+ /** In-memory engine only: index at most this many files (the most recently
93
+ * modified) and flag results `partial` above it. Defaults to
94
+ * {@link DEFAULT_MAX_INDEX_DOCS}. */
95
+ readonly maxIndexDocs?: number;
96
+ /** How long `query()` waits for a cold in-memory build before answering
97
+ * with no hits, flagged `partial` (the build keeps going). Defaults to
98
+ * 4 s. */
99
+ readonly queryTimeoutMs?: number;
100
+ /** Sink for the one-line build / reconcile / timeout logs. Defaults to
101
+ * `console.log`. */
102
+ readonly log?: (line: string) => void;
41
103
  }
42
104
  declare class FilesKnowledgeAdapter implements IKnowledgeProvider {
43
105
  readonly id: "files";
44
106
  readonly capabilities: KnowledgeCapabilities;
45
107
  private readonly fs;
46
108
  private readonly workspacePath;
109
+ private readonly label;
110
+ private readonly maxIndexDocs;
111
+ private readonly queryTimeoutMs;
112
+ private readonly log;
113
+ private readonly indexPath;
114
+ private readonly indexWorker;
115
+ private readonly reconcileIntervalMs;
47
116
  private cachedIndex;
48
117
  private cachedAt;
118
+ private cachedPartial;
49
119
  private buildInFlight;
120
+ private buildStartedAt;
121
+ private ftsOpening;
122
+ private ftsHandle;
123
+ private ftsDisabled;
124
+ private ftsComplete;
125
+ private sync;
126
+ private syncStartedAt;
127
+ private lastSyncAt;
128
+ private syncDue;
129
+ private disposed;
130
+ private incrementalUpserts;
131
+ private incrementalDeletes;
50
132
  constructor(opts: FilesKnowledgeAdapterOptions);
51
133
  ingest(input: KnowledgeIngestInput): Promise<KnowledgeSource>;
52
134
  query(q: KnowledgeQuery): Promise<KnowledgeQueryResult>;
@@ -57,10 +139,46 @@ declare class FilesKnowledgeAdapter implements IKnowledgeProvider {
57
139
  explain(id: string): Promise<KnowledgeProvenance | null>;
58
140
  healthCheck(): Promise<boolean>;
59
141
  dispose(): Promise<void>;
60
- /** Drop the cached BM25 index — next query rebuilds. */
61
- private invalidate;
142
+ /**
143
+ * Resolves once the on-disk index has no build or reconcile running (at
144
+ * once on the in-memory engine). For hosts and tests that need a settled
145
+ * index; queries never need it.
146
+ */
147
+ whenIndexSynced(): Promise<void>;
148
+ /**
149
+ * Signal that files changed outside the adapter. In memory: drop the index
150
+ * (next query rebuilds). On disk: the next query starts a reconcile scan.
151
+ */
152
+ invalidate(): void;
153
+ /** The on-disk index, opened on first use (which also starts its first
154
+ * reconcile), or null when this adapter runs in memory. */
155
+ private openFts;
156
+ private doOpenFts;
157
+ /** Give up on the on-disk index for this adapter: log once, fall back to
158
+ * the in-memory engine. */
159
+ private disableFts;
160
+ /** Start a build / reconcile when one is due, without waiting for it. */
161
+ private kickSync;
162
+ /**
163
+ * Bring the on-disk index in line with the files: a stat-only scan, then
164
+ * read and upsert only what is new or changed, batch by batch, and drop
165
+ * rows whose file is gone. The first run over an empty index is the build.
166
+ */
167
+ private runSync;
168
+ /** Every indexable file with its size and mtime, without reading any. */
169
+ private scanManifest;
170
+ /** Update the on-disk row of a file this adapter just wrote; falls back to
171
+ * invalidating the in-memory index. */
172
+ private indexWritten;
173
+ private queryFts;
174
+ /** Ids of every indexed doc, from whichever engine serves this adapter. */
175
+ private indexedIds;
62
176
  private ensureIndex;
63
177
  private _buildIndex;
178
+ /** The `limit` most recently modified of `paths`, kept in walk order. */
179
+ private mostRecent;
180
+ /** A doc's current text, or "" when it can no longer be read. */
181
+ private readText;
64
182
  }
65
183
 
66
184
  /**
@@ -89,6 +207,13 @@ interface LocalFsOptions {
89
207
  */
90
208
  readonly root: string;
91
209
  }
210
+ /** A file found by {@link LocalFs.walkStat}: workspace-relative path, size in
211
+ * bytes, and mtime in whole milliseconds (as `stat().modifiedAt`). */
212
+ interface WalkStatEntry {
213
+ readonly path: string;
214
+ readonly size: number;
215
+ readonly mtimeMs: number;
216
+ }
92
217
  declare class LocalFs implements FsPort {
93
218
  private readonly root;
94
219
  constructor(opts: LocalFsOptions);
@@ -102,6 +227,15 @@ declare class LocalFs implements FsPort {
102
227
  appendFile(p: string, content: string): Promise<void>;
103
228
  readdir(p: string): Promise<readonly string[]>;
104
229
  walk(p: string): Promise<readonly string[]>;
230
+ /**
231
+ * {@link walk} plus each file's size and mtime, in one pass: the stat-only
232
+ * scan the files engine reconciles its on-disk index with. Same paths and
233
+ * hidden-segment rule as `walk`, but directory entries are typed by
234
+ * `readdir`, so only files (and symlinks) cost a `stat`, and the stats of a
235
+ * directory run concurrently. Not part of `FsPort`: the adapter uses it when
236
+ * the backing has it and falls back to `walk` + `stat` otherwise.
237
+ */
238
+ walkStat(p: string): Promise<WalkStatEntry[]>;
105
239
  stat(p: string): Promise<FsStat | null>;
106
240
  /**
107
241
  * Advisory lock — a single-process no-op. The files engine never calls
@@ -134,7 +268,8 @@ declare class LocalFs implements FsPort {
134
268
  * Build a {@link FilesKnowledgeAdapter} backed by the local filesystem,
135
269
  * rooted and scoped from the ambient `KNOWLEDGE_FILES_*` env. Each call
136
270
  * returns a fresh adapter (and thus a fresh, empty BM25 cache) — callers
137
- * that want a shared warm index should hold onto the instance.
271
+ * that want a shared warm index should hold onto the instance, or set
272
+ * `KNOWLEDGE_FILES_INDEX_PATH` for an on-disk index that outlives it.
138
273
  */
139
274
  declare function createStandaloneFilesAdapter(): FilesKnowledgeAdapter;
140
275
 
@@ -159,39 +294,38 @@ interface FilesKnowledgeEnv {
159
294
  * Default `"knowledge"`.
160
295
  */
161
296
  readonly workspacePath: string;
297
+ /**
298
+ * Absolute host path of the on-disk search index (SQLite FTS5), from
299
+ * `KNOWLEDGE_FILES_INDEX_PATH`. Unset: in-memory index only.
300
+ */
301
+ readonly indexPath?: string;
162
302
  }
163
303
  /** Load {@link FilesKnowledgeEnv} from `process.env` with defaults. */
164
304
  declare function loadFilesKnowledgeEnv(): FilesKnowledgeEnv;
165
305
 
166
- /**
167
- * In-process BM25 — a tiny, dependency-free implementation tuned for
168
- * corpus-sized data (hundreds to low thousands of markdown files).
169
- *
170
- * Tokenizer: lowercase, split on non-alphanum, length 2-32, drop a small
171
- * English stopword list. Frontmatter is stripped before tokenization so
172
- * fence values like `schema: knowledge.entry/v1` don't pollute the
173
- * vocabulary.
174
- *
175
- * Scoring: standard BM25 with k1=1.5, b=0.75 — Lucene defaults. IDF
176
- * uses the "BM25+1" smoothing so terms appearing in every doc still
177
- * contribute a tiny positive score (avoids the negative-IDF foot-gun
178
- * for high-frequency terms).
179
- */
306
+ /** Strip YAML frontmatter (--- ... ---) from a doc body if present. */
307
+ declare function stripFrontmatter(content: string): string;
180
308
  declare function tokenize(text: string): string[];
181
309
  interface Bm25Doc {
182
310
  /** Stable id — typically the workspace-relative path. */
183
311
  readonly id: string;
184
- /** Original text (kept for snippet extraction at query time). */
185
- readonly text: string;
186
312
  /** Token count — used for length-normalization in BM25. */
187
313
  readonly length: number;
188
- /** Term frequency table for this doc. */
189
- readonly tf: ReadonlyMap<string, number>;
190
314
  }
191
315
  interface Bm25Index {
316
+ /** Docs in build order; a doc's position is its index in the arrays below. */
192
317
  readonly docs: readonly Bm25Doc[];
193
- /** Number of docs containing each term — used in IDF. */
194
- readonly df: ReadonlyMap<string, number>;
318
+ /** Term -> term id. One entry per distinct term across the whole index. */
319
+ readonly vocab: ReadonlyMap<string, number>;
320
+ /** Number of docs containing each term (by term id), used in IDF. */
321
+ readonly df: Uint32Array;
322
+ /** Doc `i`'s postings span `[offsets[i], offsets[i + 1])` in
323
+ * {@link termIds} / {@link tfs}. Length is `docs.length + 1`. */
324
+ readonly offsets: Uint32Array;
325
+ /** Term ids, ascending within each doc's span. */
326
+ readonly termIds: Uint32Array;
327
+ /** Term frequency of the matching {@link termIds} entry. */
328
+ readonly tfs: Uint32Array;
195
329
  /** Average document length across the index, in tokens. */
196
330
  readonly avgDocLength: number;
197
331
  }
@@ -199,15 +333,34 @@ interface BuildDocInput {
199
333
  readonly id: string;
200
334
  readonly content: string;
201
335
  }
336
+ /**
337
+ * Incremental index builder: {@link add} one doc at a time (the caller can
338
+ * drop the doc's text right after), then {@link finish}. Docs keep the order
339
+ * they were added in, which is also the tie-break order of {@link score}.
340
+ */
341
+ declare class Bm25IndexBuilder {
342
+ private readonly docs;
343
+ private readonly vocab;
344
+ private readonly df;
345
+ private readonly offsets;
346
+ private readonly termIds;
347
+ private readonly tfs;
348
+ private totalLength;
349
+ constructor();
350
+ get docCount(): number;
351
+ add(id: string, content: string): void;
352
+ finish(): Bm25Index;
353
+ }
202
354
  declare function buildIndex(inputs: readonly BuildDocInput[]): Bm25Index;
203
355
  /**
204
356
  * Async, event-loop-friendly variant of {@link buildIndex}. Identical output,
205
357
  * but yields to the macrotask queue every `yieldEvery` docs.
206
358
  *
207
- * Why this matters: the caller (`FilesKnowledgeAdapter._buildIndex`) reads docs
208
- * from an in-memory/cached fs, so the awaited reads resolve as MICROTASKS and
209
- * never hand control back to the event loop. Without an explicit yield, the
210
- * tokenization of every doc runs as one uninterruptible synchronous chain —
359
+ * Why this matters (the adapter's own build loop yields the same way): a caller
360
+ * that reads docs from an in-memory/cached fs sees the awaited reads resolve
361
+ * as MICROTASKS, which never hand control back to the event loop. Without an
362
+ * explicit yield, the tokenization of every doc runs as one uninterruptible
363
+ * synchronous chain —
211
364
  * which (a) freezes every concurrent recall on this single-process, multi-tenant
212
365
  * instance for the full build and (b) defeats `ensureIndex`'s non-blocking
213
366
  * `setTimeout` deadline (the timer can't fire while the loop is blocked). The
@@ -215,24 +368,42 @@ declare function buildIndex(inputs: readonly BuildDocInput[]): Bm25Index;
215
368
  * cold build.
216
369
  */
217
370
  declare function buildIndexYielding(inputs: readonly BuildDocInput[], yieldEvery?: number): Promise<Bm25Index>;
371
+ /** Docs containing `term` (0 when the term is not in the index). */
372
+ declare function documentFrequency(index: Bm25Index, term: string): number;
373
+ /**
374
+ * IDF of a term found in `n` of `N` docs. BM25 IDF with +1 smoothing, see
375
+ * "Improvements to BM25 and language models examined" (Lv & Zhai, 2011) for
376
+ * the rationale.
377
+ */
378
+ declare function bm25Idf(N: number, n: number): number;
379
+ /** One term's BM25 contribution: frequency `f` in a doc of `docLength`
380
+ * tokens, against an index whose mean length is `avgDocLength`. */
381
+ declare function bm25TermScore(idf: number, f: number, docLength: number, avgDocLength: number): number;
218
382
  interface ScoredHit {
219
383
  readonly doc: Bm25Doc;
220
384
  readonly score: number;
221
- /** Char range in `doc.text` around the first matching token. */
222
- readonly snippet?: {
223
- readonly start: number;
224
- readonly end: number;
225
- readonly text: string;
226
- };
227
385
  }
228
386
  /**
229
387
  * Score every doc against the query tokens, return top-k.
230
- * Docs with score <= 0 are dropped (no terms matched).
388
+ * Docs with score <= minScore (default 0: no terms matched) are dropped.
389
+ * The index holds no text: cut a snippet with {@link makeSnippet} from the
390
+ * doc's content once the top-k is known.
231
391
  */
232
392
  declare function score(index: Bm25Index, queryTokens: readonly string[], opts?: {
233
393
  readonly topK?: number;
234
394
  readonly minScore?: number;
235
395
  }): ScoredHit[];
396
+ /**
397
+ * Pull a ~300-char window around the first matching query token in
398
+ * the doc body. Falls back to the doc's head when no token matches in
399
+ * the surfaced text (e.g. matches were all in the stripped frontmatter).
400
+ * `start` / `end` are char offsets in `text` (the whole file).
401
+ */
402
+ declare function makeSnippet(text: string, queryTokens: readonly string[]): {
403
+ start: number;
404
+ end: number;
405
+ text: string;
406
+ };
236
407
 
237
408
  /**
238
409
  * Family key used for the knowledge backend creds/ledger store path.
@@ -296,4 +467,4 @@ declare function resolveKnowledgeBackend(slug: string): KnowledgeHandle;
296
467
  */
297
468
  declare function makeKnowledgeFilesResolver(): AdapterResolver<KnowledgeHandle>;
298
469
 
299
- export { type Bm25Doc, type Bm25Index, type BuildDocInput, FILES_BM25_SLUG, FILES_CAPABILITIES, FILES_ENGINE_ID, type FilesAdapterConfig, FilesKnowledgeAdapter, type FilesKnowledgeAdapterOptions, type FilesKnowledgeEnv, KNOWLEDGE_FAMILY, KNOWLEDGE_FILES_CATALOG, type KnowledgeFilesInfo, type KnowledgeHandle, LocalFs, type LocalFsOptions, type ScoredHit, buildIndex, buildIndexYielding, createStandaloneFilesAdapter, loadFilesKnowledgeEnv, makeKnowledgeFilesResolver, resolveKnowledgeBackend, score, tokenize };
470
+ export { type Bm25Doc, type Bm25Index, Bm25IndexBuilder, type BuildDocInput, DEFAULT_MAX_INDEX_DOCS, DEFAULT_RECONCILE_INTERVAL_MS, FILES_BM25_SLUG, FILES_CAPABILITIES, FILES_ENGINE_ID, type FilesAdapterConfig, FilesIndexTooLargeError, FilesKnowledgeAdapter, type FilesKnowledgeAdapterOptions, type FilesKnowledgeEnv, KNOWLEDGE_FAMILY, KNOWLEDGE_FILES_CATALOG, type KnowledgeFilesInfo, type KnowledgeHandle, LocalFs, type LocalFsOptions, type ScoredHit, type WalkStatEntry, bm25Idf, bm25TermScore, buildIndex, buildIndexYielding, createStandaloneFilesAdapter, documentFrequency, filesIndexBuildsRunning, loadFilesKnowledgeEnv, makeKnowledgeFilesResolver, makeSnippet, resolveKnowledgeBackend, score, stripFrontmatter, tokenize };