@agentproto/adapter-knowledge-files 0.4.0 → 0.5.1
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 +80 -16
- package/dist/index.d.ts +146 -63
- package/dist/index.mjs +902 -74
- package/dist/index.mjs.map +1 -1
- package/package.json +6 -6
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
|
|
8
|
-
|
|
9
|
-
|
|
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
|
|
|
@@ -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,25 +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
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
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.
|
|
72
125
|
- **Memory:** the resident index holds no doc text: per doc only its id and
|
|
73
126
|
token count, plus every doc's (term id, term frequency) pairs packed into
|
|
74
127
|
shared typed arrays and one term vocabulary. A query reads the top-K files
|
|
75
128
|
back from disk for their snippet and frontmatter. A build reads files 50 at a
|
|
76
129
|
time, so only one step of text is alive at once.
|
|
77
|
-
- **
|
|
78
|
-
the
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
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.
|
|
82
142
|
- **Logs:** one line per build (`[knowledge-files:<label>] index built: N docs,
|
|
83
|
-
B bytes read, T ms, heapUsed X MB -> Y MB`
|
|
84
|
-
|
|
85
|
-
|
|
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.
|
|
86
150
|
|
|
87
151
|
## Provenance and supersession
|
|
88
152
|
|
package/dist/index.d.ts
CHANGED
|
@@ -5,48 +5,60 @@ 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
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
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
|
-
*
|
|
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
|
-
*
|
|
21
|
-
* (
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
* it
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
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;
|
|
33
48
|
/**
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
* the lean index costs about 2.4 KB of heap per
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
* 500 MB resident at worst. That covers the 47k and 91k doc brains seen in the
|
|
41
|
-
* field and refuses the 223k one, which wants a real engine (qdrant,
|
|
42
|
-
* gbrain-doc) rather than a whole-corpus scan per query.
|
|
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.
|
|
43
55
|
*/
|
|
44
56
|
declare const DEFAULT_MAX_INDEX_DOCS = 100000;
|
|
45
57
|
/**
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
*
|
|
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.
|
|
50
62
|
*/
|
|
51
63
|
declare class FilesIndexTooLargeError extends Error {
|
|
52
64
|
readonly docCount: number;
|
|
@@ -66,13 +78,26 @@ interface FilesKnowledgeAdapterOptions extends FilesAdapterConfig {
|
|
|
66
78
|
/** Name used in log lines and errors (e.g. the brain's workspace slug).
|
|
67
79
|
* Defaults to `workspacePath`. */
|
|
68
80
|
readonly label?: string;
|
|
69
|
-
/**
|
|
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
|
|
70
94
|
* {@link DEFAULT_MAX_INDEX_DOCS}. */
|
|
71
95
|
readonly maxIndexDocs?: number;
|
|
72
|
-
/** How long `query()` waits for a cold build before answering
|
|
73
|
-
* hits (the build keeps going). Defaults to
|
|
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. */
|
|
74
99
|
readonly queryTimeoutMs?: number;
|
|
75
|
-
/** Sink for the one-line build /
|
|
100
|
+
/** Sink for the one-line build / reconcile / timeout logs. Defaults to
|
|
76
101
|
* `console.log`. */
|
|
77
102
|
readonly log?: (line: string) => void;
|
|
78
103
|
}
|
|
@@ -85,11 +110,25 @@ declare class FilesKnowledgeAdapter implements IKnowledgeProvider {
|
|
|
85
110
|
private readonly maxIndexDocs;
|
|
86
111
|
private readonly queryTimeoutMs;
|
|
87
112
|
private readonly log;
|
|
113
|
+
private readonly indexPath;
|
|
114
|
+
private readonly indexWorker;
|
|
115
|
+
private readonly reconcileIntervalMs;
|
|
88
116
|
private cachedIndex;
|
|
89
117
|
private cachedAt;
|
|
118
|
+
private cachedPartial;
|
|
90
119
|
private buildInFlight;
|
|
91
120
|
private buildStartedAt;
|
|
92
|
-
private
|
|
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;
|
|
93
132
|
constructor(opts: FilesKnowledgeAdapterOptions);
|
|
94
133
|
ingest(input: KnowledgeIngestInput): Promise<KnowledgeSource>;
|
|
95
134
|
query(q: KnowledgeQuery): Promise<KnowledgeQueryResult>;
|
|
@@ -100,10 +139,44 @@ declare class FilesKnowledgeAdapter implements IKnowledgeProvider {
|
|
|
100
139
|
explain(id: string): Promise<KnowledgeProvenance | null>;
|
|
101
140
|
healthCheck(): Promise<boolean>;
|
|
102
141
|
dispose(): Promise<void>;
|
|
103
|
-
/**
|
|
104
|
-
|
|
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;
|
|
105
176
|
private ensureIndex;
|
|
106
177
|
private _buildIndex;
|
|
178
|
+
/** The `limit` most recently modified of `paths`, kept in walk order. */
|
|
179
|
+
private mostRecent;
|
|
107
180
|
/** A doc's current text, or "" when it can no longer be read. */
|
|
108
181
|
private readText;
|
|
109
182
|
}
|
|
@@ -134,6 +207,13 @@ interface LocalFsOptions {
|
|
|
134
207
|
*/
|
|
135
208
|
readonly root: string;
|
|
136
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
|
+
}
|
|
137
217
|
declare class LocalFs implements FsPort {
|
|
138
218
|
private readonly root;
|
|
139
219
|
constructor(opts: LocalFsOptions);
|
|
@@ -147,6 +227,15 @@ declare class LocalFs implements FsPort {
|
|
|
147
227
|
appendFile(p: string, content: string): Promise<void>;
|
|
148
228
|
readdir(p: string): Promise<readonly string[]>;
|
|
149
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[]>;
|
|
150
239
|
stat(p: string): Promise<FsStat | null>;
|
|
151
240
|
/**
|
|
152
241
|
* Advisory lock — a single-process no-op. The files engine never calls
|
|
@@ -179,7 +268,8 @@ declare class LocalFs implements FsPort {
|
|
|
179
268
|
* Build a {@link FilesKnowledgeAdapter} backed by the local filesystem,
|
|
180
269
|
* rooted and scoped from the ambient `KNOWLEDGE_FILES_*` env. Each call
|
|
181
270
|
* returns a fresh adapter (and thus a fresh, empty BM25 cache) — callers
|
|
182
|
-
* 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.
|
|
183
273
|
*/
|
|
184
274
|
declare function createStandaloneFilesAdapter(): FilesKnowledgeAdapter;
|
|
185
275
|
|
|
@@ -204,31 +294,15 @@ interface FilesKnowledgeEnv {
|
|
|
204
294
|
* Default `"knowledge"`.
|
|
205
295
|
*/
|
|
206
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;
|
|
207
302
|
}
|
|
208
303
|
/** Load {@link FilesKnowledgeEnv} from `process.env` with defaults. */
|
|
209
304
|
declare function loadFilesKnowledgeEnv(): FilesKnowledgeEnv;
|
|
210
305
|
|
|
211
|
-
/**
|
|
212
|
-
* In-process BM25 — a tiny, dependency-free implementation tuned for
|
|
213
|
-
* corpus-sized data (hundreds to low thousands of markdown files).
|
|
214
|
-
*
|
|
215
|
-
* Memory shape: the index keeps only what scoring needs. Doc text is NOT
|
|
216
|
-
* retained (a snippet is cut from the file at query time, top-K hits only),
|
|
217
|
-
* and there is no per-doc `Map`: every doc's (term id, term frequency) pairs
|
|
218
|
-
* live in two shared packed typed arrays, sliced per doc by an offset table,
|
|
219
|
-
* with one vocabulary map (term -> id) for the whole index. Keeping the full
|
|
220
|
-
* text plus a per-doc `tf` Map cost about 6.5x the corpus bytes on disk.
|
|
221
|
-
*
|
|
222
|
-
* Tokenizer: lowercase, split on non-alphanum, length 2-32, drop a small
|
|
223
|
-
* English stopword list. Frontmatter is stripped before tokenization so
|
|
224
|
-
* fence values like `schema: knowledge.entry/v1` don't pollute the
|
|
225
|
-
* vocabulary.
|
|
226
|
-
*
|
|
227
|
-
* Scoring: standard BM25 with k1=1.5, b=0.75 — Lucene defaults. IDF
|
|
228
|
-
* uses the "BM25+1" smoothing so terms appearing in every doc still
|
|
229
|
-
* contribute a tiny positive score (avoids the negative-IDF foot-gun
|
|
230
|
-
* for high-frequency terms).
|
|
231
|
-
*/
|
|
232
306
|
/** Strip YAML frontmatter (--- ... ---) from a doc body if present. */
|
|
233
307
|
declare function stripFrontmatter(content: string): string;
|
|
234
308
|
declare function tokenize(text: string): string[];
|
|
@@ -296,6 +370,15 @@ declare function buildIndex(inputs: readonly BuildDocInput[]): Bm25Index;
|
|
|
296
370
|
declare function buildIndexYielding(inputs: readonly BuildDocInput[], yieldEvery?: number): Promise<Bm25Index>;
|
|
297
371
|
/** Docs containing `term` (0 when the term is not in the index). */
|
|
298
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;
|
|
299
382
|
interface ScoredHit {
|
|
300
383
|
readonly doc: Bm25Doc;
|
|
301
384
|
readonly score: number;
|
|
@@ -384,4 +467,4 @@ declare function resolveKnowledgeBackend(slug: string): KnowledgeHandle;
|
|
|
384
467
|
*/
|
|
385
468
|
declare function makeKnowledgeFilesResolver(): AdapterResolver<KnowledgeHandle>;
|
|
386
469
|
|
|
387
|
-
export { type Bm25Doc, type Bm25Index, Bm25IndexBuilder, type BuildDocInput, DEFAULT_MAX_INDEX_DOCS, 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, buildIndex, buildIndexYielding, createStandaloneFilesAdapter, documentFrequency, filesIndexBuildsRunning, loadFilesKnowledgeEnv, makeKnowledgeFilesResolver, makeSnippet, resolveKnowledgeBackend, score, stripFrontmatter, 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 };
|