@agentproto/adapter-knowledge-files 0.3.4 → 0.4.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 +15 -1
- package/dist/index.d.ts +106 -18
- package/dist/index.mjs +249 -92
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -17,7 +17,7 @@ _are_ the index, with no separate store to keep in sync.
|
|
|
17
17
|
| `FilesKnowledgeAdapter` | The `IKnowledgeProvider` implementation. Consumes an injected `FsPort`; knows nothing about `node:fs` or `process.env`. |
|
|
18
18
|
| `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
19
|
| `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. |
|
|
20
|
+
| BM25 (`tokenize`, `buildIndex`, `buildIndexYielding`, `Bm25IndexBuilder`, `score`, `makeSnippet`) | The dependency-free ranking core. Confined to this package. |
|
|
21
21
|
| provider-kit family (`KNOWLEDGE_FILES_CATALOG`, `makeKnowledgeFilesResolver`, `resolveKnowledgeBackend`) | Registers the `files` backend under the `@agentproto/adapter-knowledge-*` discovery convention. |
|
|
22
22
|
|
|
23
23
|
## Usage
|
|
@@ -69,6 +69,20 @@ names live:
|
|
|
69
69
|
it's rebuilt only when the adapter `invalidate()`s (via `ingest`/`delete`) or
|
|
70
70
|
a fresh instance is created. Hosts wanting second-precision freshness on
|
|
71
71
|
external edits can wire fs-watch into a new instance.
|
|
72
|
+
- **Memory:** the resident index holds no doc text: per doc only its id and
|
|
73
|
+
token count, plus every doc's (term id, term frequency) pairs packed into
|
|
74
|
+
shared typed arrays and one term vocabulary. A query reads the top-K files
|
|
75
|
+
back from disk for their snippet and frontmatter. A build reads files 50 at a
|
|
76
|
+
time, so only one step of text is alive at once.
|
|
77
|
+
- **One build at a time:** index builds are serialized across every adapter in
|
|
78
|
+
the process, so cold queries on several brains never stack their peaks.
|
|
79
|
+
- **Ceiling:** above `maxIndexDocs` indexable files (default 100,000) the
|
|
80
|
+
adapter refuses to build and `query()` / `listSources()` / `getSource()`
|
|
81
|
+
throw `FilesIndexTooLargeError` with the counts.
|
|
82
|
+
- **Logs:** one line per build (`[knowledge-files:<label>] index built: N docs,
|
|
83
|
+
B bytes read, T ms, heapUsed X MB -> Y MB`), per refusal, and per query that
|
|
84
|
+
times out waiting for a cold build (the build keeps going). Inject `log` to
|
|
85
|
+
route them elsewhere.
|
|
72
86
|
|
|
73
87
|
## Provenance and supersession
|
|
74
88
|
|
package/dist/index.d.ts
CHANGED
|
@@ -30,6 +30,31 @@ import { AdapterCatalog, AdapterHandle, AdapterResolver } from '@agentproto/prov
|
|
|
30
30
|
*/
|
|
31
31
|
|
|
32
32
|
declare const FILES_ENGINE_ID: "files";
|
|
33
|
+
/**
|
|
34
|
+
* Default ceiling on the files a brain may index in process. Above it the
|
|
35
|
+
* engine refuses to build and every query fails with
|
|
36
|
+
* {@link FilesIndexTooLargeError}. Measured on 5.8 KB transcript-shaped docs:
|
|
37
|
+
* the lean index costs about 2.4 KB of heap per doc where the old one (text
|
|
38
|
+
* plus a per-doc `tf` Map) cost about 20 KB. Real brains measured 40 KB per doc
|
|
39
|
+
* on the old shape, so budget about 5 KB per doc: 100,000 docs is about
|
|
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.
|
|
43
|
+
*/
|
|
44
|
+
declare const DEFAULT_MAX_INDEX_DOCS = 100000;
|
|
45
|
+
/**
|
|
46
|
+
* Thrown by `query()` / `listSources()` / `getSource()` when the brain holds
|
|
47
|
+
* more indexable files than the configured ceiling. The name is the stable
|
|
48
|
+
* signal (`err.name === "FilesIndexTooLargeError"`) so a second copy of this
|
|
49
|
+
* package in the tree still matches.
|
|
50
|
+
*/
|
|
51
|
+
declare class FilesIndexTooLargeError extends Error {
|
|
52
|
+
readonly docCount: number;
|
|
53
|
+
readonly maxDocs: number;
|
|
54
|
+
constructor(label: string, docCount: number, maxDocs: number);
|
|
55
|
+
}
|
|
56
|
+
/** Index builds running right now, process wide (0 or 1). For tests. */
|
|
57
|
+
declare function filesIndexBuildsRunning(): number;
|
|
33
58
|
declare const FILES_CAPABILITIES: KnowledgeCapabilities;
|
|
34
59
|
interface FilesAdapterConfig {
|
|
35
60
|
/** Workspace-relative root the engine indexes (walks recursively). */
|
|
@@ -38,15 +63,33 @@ interface FilesAdapterConfig {
|
|
|
38
63
|
interface FilesKnowledgeAdapterOptions extends FilesAdapterConfig {
|
|
39
64
|
/** FsPort scoped to the workspace the engine lives in. */
|
|
40
65
|
readonly fs: FsPort;
|
|
66
|
+
/** Name used in log lines and errors (e.g. the brain's workspace slug).
|
|
67
|
+
* Defaults to `workspacePath`. */
|
|
68
|
+
readonly label?: string;
|
|
69
|
+
/** Refuse to build the index above this many indexable files. Defaults to
|
|
70
|
+
* {@link DEFAULT_MAX_INDEX_DOCS}. */
|
|
71
|
+
readonly maxIndexDocs?: number;
|
|
72
|
+
/** How long `query()` waits for a cold build before answering with no
|
|
73
|
+
* hits (the build keeps going). Defaults to 4 s. */
|
|
74
|
+
readonly queryTimeoutMs?: number;
|
|
75
|
+
/** Sink for the one-line build / timeout / refusal logs. Defaults to
|
|
76
|
+
* `console.log`. */
|
|
77
|
+
readonly log?: (line: string) => void;
|
|
41
78
|
}
|
|
42
79
|
declare class FilesKnowledgeAdapter implements IKnowledgeProvider {
|
|
43
80
|
readonly id: "files";
|
|
44
81
|
readonly capabilities: KnowledgeCapabilities;
|
|
45
82
|
private readonly fs;
|
|
46
83
|
private readonly workspacePath;
|
|
84
|
+
private readonly label;
|
|
85
|
+
private readonly maxIndexDocs;
|
|
86
|
+
private readonly queryTimeoutMs;
|
|
87
|
+
private readonly log;
|
|
47
88
|
private cachedIndex;
|
|
48
89
|
private cachedAt;
|
|
49
90
|
private buildInFlight;
|
|
91
|
+
private buildStartedAt;
|
|
92
|
+
private refusal;
|
|
50
93
|
constructor(opts: FilesKnowledgeAdapterOptions);
|
|
51
94
|
ingest(input: KnowledgeIngestInput): Promise<KnowledgeSource>;
|
|
52
95
|
query(q: KnowledgeQuery): Promise<KnowledgeQueryResult>;
|
|
@@ -61,6 +104,8 @@ declare class FilesKnowledgeAdapter implements IKnowledgeProvider {
|
|
|
61
104
|
private invalidate;
|
|
62
105
|
private ensureIndex;
|
|
63
106
|
private _buildIndex;
|
|
107
|
+
/** A doc's current text, or "" when it can no longer be read. */
|
|
108
|
+
private readText;
|
|
64
109
|
}
|
|
65
110
|
|
|
66
111
|
/**
|
|
@@ -167,6 +212,13 @@ declare function loadFilesKnowledgeEnv(): FilesKnowledgeEnv;
|
|
|
167
212
|
* In-process BM25 — a tiny, dependency-free implementation tuned for
|
|
168
213
|
* corpus-sized data (hundreds to low thousands of markdown files).
|
|
169
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
|
+
*
|
|
170
222
|
* Tokenizer: lowercase, split on non-alphanum, length 2-32, drop a small
|
|
171
223
|
* English stopword list. Frontmatter is stripped before tokenization so
|
|
172
224
|
* fence values like `schema: knowledge.entry/v1` don't pollute the
|
|
@@ -177,21 +229,29 @@ declare function loadFilesKnowledgeEnv(): FilesKnowledgeEnv;
|
|
|
177
229
|
* contribute a tiny positive score (avoids the negative-IDF foot-gun
|
|
178
230
|
* for high-frequency terms).
|
|
179
231
|
*/
|
|
232
|
+
/** Strip YAML frontmatter (--- ... ---) from a doc body if present. */
|
|
233
|
+
declare function stripFrontmatter(content: string): string;
|
|
180
234
|
declare function tokenize(text: string): string[];
|
|
181
235
|
interface Bm25Doc {
|
|
182
236
|
/** Stable id — typically the workspace-relative path. */
|
|
183
237
|
readonly id: string;
|
|
184
|
-
/** Original text (kept for snippet extraction at query time). */
|
|
185
|
-
readonly text: string;
|
|
186
238
|
/** Token count — used for length-normalization in BM25. */
|
|
187
239
|
readonly length: number;
|
|
188
|
-
/** Term frequency table for this doc. */
|
|
189
|
-
readonly tf: ReadonlyMap<string, number>;
|
|
190
240
|
}
|
|
191
241
|
interface Bm25Index {
|
|
242
|
+
/** Docs in build order; a doc's position is its index in the arrays below. */
|
|
192
243
|
readonly docs: readonly Bm25Doc[];
|
|
193
|
-
/**
|
|
194
|
-
readonly
|
|
244
|
+
/** Term -> term id. One entry per distinct term across the whole index. */
|
|
245
|
+
readonly vocab: ReadonlyMap<string, number>;
|
|
246
|
+
/** Number of docs containing each term (by term id), used in IDF. */
|
|
247
|
+
readonly df: Uint32Array;
|
|
248
|
+
/** Doc `i`'s postings span `[offsets[i], offsets[i + 1])` in
|
|
249
|
+
* {@link termIds} / {@link tfs}. Length is `docs.length + 1`. */
|
|
250
|
+
readonly offsets: Uint32Array;
|
|
251
|
+
/** Term ids, ascending within each doc's span. */
|
|
252
|
+
readonly termIds: Uint32Array;
|
|
253
|
+
/** Term frequency of the matching {@link termIds} entry. */
|
|
254
|
+
readonly tfs: Uint32Array;
|
|
195
255
|
/** Average document length across the index, in tokens. */
|
|
196
256
|
readonly avgDocLength: number;
|
|
197
257
|
}
|
|
@@ -199,15 +259,34 @@ interface BuildDocInput {
|
|
|
199
259
|
readonly id: string;
|
|
200
260
|
readonly content: string;
|
|
201
261
|
}
|
|
262
|
+
/**
|
|
263
|
+
* Incremental index builder: {@link add} one doc at a time (the caller can
|
|
264
|
+
* drop the doc's text right after), then {@link finish}. Docs keep the order
|
|
265
|
+
* they were added in, which is also the tie-break order of {@link score}.
|
|
266
|
+
*/
|
|
267
|
+
declare class Bm25IndexBuilder {
|
|
268
|
+
private readonly docs;
|
|
269
|
+
private readonly vocab;
|
|
270
|
+
private readonly df;
|
|
271
|
+
private readonly offsets;
|
|
272
|
+
private readonly termIds;
|
|
273
|
+
private readonly tfs;
|
|
274
|
+
private totalLength;
|
|
275
|
+
constructor();
|
|
276
|
+
get docCount(): number;
|
|
277
|
+
add(id: string, content: string): void;
|
|
278
|
+
finish(): Bm25Index;
|
|
279
|
+
}
|
|
202
280
|
declare function buildIndex(inputs: readonly BuildDocInput[]): Bm25Index;
|
|
203
281
|
/**
|
|
204
282
|
* Async, event-loop-friendly variant of {@link buildIndex}. Identical output,
|
|
205
283
|
* but yields to the macrotask queue every `yieldEvery` docs.
|
|
206
284
|
*
|
|
207
|
-
* Why this matters
|
|
208
|
-
* from an in-memory/cached fs
|
|
209
|
-
* never hand control back to the event loop. Without an
|
|
210
|
-
* tokenization of every doc runs as one uninterruptible
|
|
285
|
+
* Why this matters (the adapter's own build loop yields the same way): a caller
|
|
286
|
+
* that reads docs from an in-memory/cached fs sees the awaited reads resolve
|
|
287
|
+
* as MICROTASKS, which never hand control back to the event loop. Without an
|
|
288
|
+
* explicit yield, the tokenization of every doc runs as one uninterruptible
|
|
289
|
+
* synchronous chain —
|
|
211
290
|
* which (a) freezes every concurrent recall on this single-process, multi-tenant
|
|
212
291
|
* instance for the full build and (b) defeats `ensureIndex`'s non-blocking
|
|
213
292
|
* `setTimeout` deadline (the timer can't fire while the loop is blocked). The
|
|
@@ -215,24 +294,33 @@ declare function buildIndex(inputs: readonly BuildDocInput[]): Bm25Index;
|
|
|
215
294
|
* cold build.
|
|
216
295
|
*/
|
|
217
296
|
declare function buildIndexYielding(inputs: readonly BuildDocInput[], yieldEvery?: number): Promise<Bm25Index>;
|
|
297
|
+
/** Docs containing `term` (0 when the term is not in the index). */
|
|
298
|
+
declare function documentFrequency(index: Bm25Index, term: string): number;
|
|
218
299
|
interface ScoredHit {
|
|
219
300
|
readonly doc: Bm25Doc;
|
|
220
301
|
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
302
|
}
|
|
228
303
|
/**
|
|
229
304
|
* Score every doc against the query tokens, return top-k.
|
|
230
|
-
* Docs with score <=
|
|
305
|
+
* Docs with score <= minScore (default 0: no terms matched) are dropped.
|
|
306
|
+
* The index holds no text: cut a snippet with {@link makeSnippet} from the
|
|
307
|
+
* doc's content once the top-k is known.
|
|
231
308
|
*/
|
|
232
309
|
declare function score(index: Bm25Index, queryTokens: readonly string[], opts?: {
|
|
233
310
|
readonly topK?: number;
|
|
234
311
|
readonly minScore?: number;
|
|
235
312
|
}): ScoredHit[];
|
|
313
|
+
/**
|
|
314
|
+
* Pull a ~300-char window around the first matching query token in
|
|
315
|
+
* the doc body. Falls back to the doc's head when no token matches in
|
|
316
|
+
* the surfaced text (e.g. matches were all in the stripped frontmatter).
|
|
317
|
+
* `start` / `end` are char offsets in `text` (the whole file).
|
|
318
|
+
*/
|
|
319
|
+
declare function makeSnippet(text: string, queryTokens: readonly string[]): {
|
|
320
|
+
start: number;
|
|
321
|
+
end: number;
|
|
322
|
+
text: string;
|
|
323
|
+
};
|
|
236
324
|
|
|
237
325
|
/**
|
|
238
326
|
* Family key used for the knowledge backend creds/ledger store path.
|
|
@@ -296,4 +384,4 @@ declare function resolveKnowledgeBackend(slug: string): KnowledgeHandle;
|
|
|
296
384
|
*/
|
|
297
385
|
declare function makeKnowledgeFilesResolver(): AdapterResolver<KnowledgeHandle>;
|
|
298
386
|
|
|
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 };
|
|
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 };
|
package/dist/index.mjs
CHANGED
|
@@ -84,75 +84,138 @@ function tokenize(text) {
|
|
|
84
84
|
}
|
|
85
85
|
return out;
|
|
86
86
|
}
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
87
|
+
var U32Buffer = class {
|
|
88
|
+
buf;
|
|
89
|
+
length = 0;
|
|
90
|
+
constructor(capacity = 1024) {
|
|
91
|
+
this.buf = new Uint32Array(capacity);
|
|
92
|
+
}
|
|
93
|
+
push(value) {
|
|
94
|
+
if (this.length === this.buf.length) {
|
|
95
|
+
const next = new Uint32Array(this.buf.length * 2);
|
|
96
|
+
next.set(this.buf);
|
|
97
|
+
this.buf = next;
|
|
98
|
+
}
|
|
99
|
+
this.buf[this.length++] = value;
|
|
100
|
+
}
|
|
101
|
+
get(i) {
|
|
102
|
+
return this.buf[i];
|
|
103
|
+
}
|
|
104
|
+
set(i, value) {
|
|
105
|
+
this.buf[i] = value;
|
|
106
|
+
}
|
|
107
|
+
take() {
|
|
108
|
+
return this.buf.slice(0, this.length);
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
function ownString(term) {
|
|
112
|
+
return JSON.parse(JSON.stringify(term));
|
|
113
|
+
}
|
|
114
|
+
var Bm25IndexBuilder = class {
|
|
115
|
+
docs = [];
|
|
116
|
+
vocab = /* @__PURE__ */ new Map();
|
|
117
|
+
df = new U32Buffer();
|
|
118
|
+
offsets = new U32Buffer();
|
|
119
|
+
termIds = new U32Buffer(64 * 1024);
|
|
120
|
+
tfs = new U32Buffer(64 * 1024);
|
|
121
|
+
totalLength = 0;
|
|
122
|
+
constructor() {
|
|
123
|
+
this.offsets.push(0);
|
|
124
|
+
}
|
|
125
|
+
get docCount() {
|
|
126
|
+
return this.docs.length;
|
|
127
|
+
}
|
|
128
|
+
add(id, content) {
|
|
129
|
+
const tokens = tokenize(stripFrontmatter(content));
|
|
93
130
|
const tf = /* @__PURE__ */ new Map();
|
|
94
131
|
for (const tok of tokens) {
|
|
95
|
-
|
|
132
|
+
let termId = this.vocab.get(tok);
|
|
133
|
+
if (termId === void 0) {
|
|
134
|
+
termId = this.vocab.size;
|
|
135
|
+
this.vocab.set(ownString(tok), termId);
|
|
136
|
+
this.df.push(0);
|
|
137
|
+
}
|
|
138
|
+
tf.set(termId, (tf.get(termId) ?? 0) + 1);
|
|
96
139
|
}
|
|
97
|
-
|
|
98
|
-
|
|
140
|
+
const ids = [...tf.keys()].sort((a, b) => a - b);
|
|
141
|
+
for (const termId of ids) {
|
|
142
|
+
this.termIds.push(termId);
|
|
143
|
+
this.tfs.push(tf.get(termId));
|
|
144
|
+
this.df.set(termId, this.df.get(termId) + 1);
|
|
99
145
|
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
146
|
+
this.offsets.push(this.termIds.length);
|
|
147
|
+
this.docs.push({ id, length: tokens.length });
|
|
148
|
+
this.totalLength += tokens.length;
|
|
149
|
+
}
|
|
150
|
+
finish() {
|
|
151
|
+
const avgDocLength = this.docs.length === 0 ? 0 : this.totalLength / this.docs.length;
|
|
152
|
+
return {
|
|
153
|
+
docs: this.docs,
|
|
154
|
+
vocab: this.vocab,
|
|
155
|
+
df: this.df.take(),
|
|
156
|
+
offsets: this.offsets.take(),
|
|
157
|
+
termIds: this.termIds.take(),
|
|
158
|
+
tfs: this.tfs.take(),
|
|
159
|
+
avgDocLength
|
|
160
|
+
};
|
|
107
161
|
}
|
|
108
|
-
|
|
109
|
-
|
|
162
|
+
};
|
|
163
|
+
function buildIndex(inputs) {
|
|
164
|
+
const builder = new Bm25IndexBuilder();
|
|
165
|
+
for (const input of inputs) builder.add(input.id, input.content);
|
|
166
|
+
return builder.finish();
|
|
110
167
|
}
|
|
111
168
|
async function buildIndexYielding(inputs, yieldEvery = 50) {
|
|
112
|
-
const
|
|
113
|
-
const df = /* @__PURE__ */ new Map();
|
|
114
|
-
let totalLength = 0;
|
|
169
|
+
const builder = new Bm25IndexBuilder();
|
|
115
170
|
let i = 0;
|
|
116
171
|
for (const input of inputs) {
|
|
117
172
|
if (i++ % yieldEvery === 0)
|
|
118
173
|
await new Promise((resolve) => setImmediate(resolve));
|
|
119
|
-
|
|
120
|
-
const tf = /* @__PURE__ */ new Map();
|
|
121
|
-
for (const tok of tokens) {
|
|
122
|
-
tf.set(tok, (tf.get(tok) ?? 0) + 1);
|
|
123
|
-
}
|
|
124
|
-
for (const term of tf.keys()) {
|
|
125
|
-
df.set(term, (df.get(term) ?? 0) + 1);
|
|
126
|
-
}
|
|
127
|
-
docs.push({
|
|
128
|
-
id: input.id,
|
|
129
|
-
text: input.content,
|
|
130
|
-
length: tokens.length,
|
|
131
|
-
tf
|
|
132
|
-
});
|
|
133
|
-
totalLength += tokens.length;
|
|
174
|
+
builder.add(input.id, input.content);
|
|
134
175
|
}
|
|
135
|
-
|
|
136
|
-
|
|
176
|
+
return builder.finish();
|
|
177
|
+
}
|
|
178
|
+
function documentFrequency(index, term) {
|
|
179
|
+
const termId = index.vocab.get(term);
|
|
180
|
+
return termId === void 0 ? 0 : index.df[termId];
|
|
181
|
+
}
|
|
182
|
+
function termFrequency(index, docIndex, termId) {
|
|
183
|
+
let lo = index.offsets[docIndex];
|
|
184
|
+
let hi = index.offsets[docIndex + 1] - 1;
|
|
185
|
+
while (lo <= hi) {
|
|
186
|
+
const mid = lo + hi >>> 1;
|
|
187
|
+
const at = index.termIds[mid];
|
|
188
|
+
if (at === termId) return index.tfs[mid];
|
|
189
|
+
if (at < termId) lo = mid + 1;
|
|
190
|
+
else hi = mid - 1;
|
|
191
|
+
}
|
|
192
|
+
return 0;
|
|
137
193
|
}
|
|
138
194
|
function score(index, queryTokens, opts = {}) {
|
|
139
195
|
if (queryTokens.length === 0 || index.docs.length === 0) return [];
|
|
140
196
|
const topK = opts.topK ?? 10;
|
|
141
197
|
const minScore = opts.minScore ?? 0;
|
|
142
198
|
const N = index.docs.length;
|
|
199
|
+
const avgDocLength = index.avgDocLength === 0 ? 1 : index.avgDocLength;
|
|
200
|
+
const terms = [];
|
|
201
|
+
for (const tok of queryTokens) {
|
|
202
|
+
const termId = index.vocab.get(tok);
|
|
203
|
+
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) });
|
|
206
|
+
}
|
|
143
207
|
const out = [];
|
|
144
|
-
for (
|
|
208
|
+
for (let i = 0; i < N; i++) {
|
|
209
|
+
const doc = index.docs[i];
|
|
145
210
|
let s = 0;
|
|
146
|
-
for (const
|
|
147
|
-
const f =
|
|
211
|
+
for (const { termId, idf } of terms) {
|
|
212
|
+
const f = termFrequency(index, i, termId);
|
|
148
213
|
if (!f) continue;
|
|
149
|
-
const
|
|
150
|
-
const idf = Math.log((N - n + 0.5) / (n + 0.5) + 1);
|
|
151
|
-
const denom = f + K1 * (1 - B + B * doc.length / (index.avgDocLength === 0 ? 1 : index.avgDocLength));
|
|
214
|
+
const denom = f + K1 * (1 - B + B * doc.length / avgDocLength);
|
|
152
215
|
s += idf * (f * (K1 + 1) / denom);
|
|
153
216
|
}
|
|
154
217
|
if (s <= minScore) continue;
|
|
155
|
-
out.push({ doc, score: s
|
|
218
|
+
out.push({ doc, score: s });
|
|
156
219
|
}
|
|
157
220
|
out.sort((a, b) => b.score - a.score);
|
|
158
221
|
return out.slice(0, topK);
|
|
@@ -189,6 +252,37 @@ var INDEXED_EXTENSIONS = [
|
|
|
189
252
|
var CACHE_TTL_MS = Number.POSITIVE_INFINITY;
|
|
190
253
|
var INDEX_READ_CONCURRENCY = 10;
|
|
191
254
|
var INDEX_QUERY_TIMEOUT_MS = 4e3;
|
|
255
|
+
var INDEX_BUILD_STEP = 50;
|
|
256
|
+
var DEFAULT_MAX_INDEX_DOCS = 1e5;
|
|
257
|
+
var FilesIndexTooLargeError = class extends Error {
|
|
258
|
+
docCount;
|
|
259
|
+
maxDocs;
|
|
260
|
+
constructor(label, docCount, maxDocs) {
|
|
261
|
+
super(
|
|
262
|
+
`files engine (${label}): refusing to build the in-process index: ${docCount} indexable files exceed the ceiling of ${maxDocs}. Raise maxIndexDocs, or back this brain with a real search engine.`
|
|
263
|
+
);
|
|
264
|
+
this.name = "FilesIndexTooLargeError";
|
|
265
|
+
this.docCount = docCount;
|
|
266
|
+
this.maxDocs = maxDocs;
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
var buildGate = Promise.resolve();
|
|
270
|
+
var buildsRunning = 0;
|
|
271
|
+
function runExclusiveBuild(fn) {
|
|
272
|
+
const run = buildGate.then(async () => {
|
|
273
|
+
buildsRunning++;
|
|
274
|
+
try {
|
|
275
|
+
return await fn();
|
|
276
|
+
} finally {
|
|
277
|
+
buildsRunning--;
|
|
278
|
+
}
|
|
279
|
+
});
|
|
280
|
+
buildGate = run.catch(() => void 0);
|
|
281
|
+
return run;
|
|
282
|
+
}
|
|
283
|
+
function filesIndexBuildsRunning() {
|
|
284
|
+
return buildsRunning;
|
|
285
|
+
}
|
|
192
286
|
var FILES_CAPABILITIES = Object.freeze({
|
|
193
287
|
vectorSearch: false,
|
|
194
288
|
graphTraversal: false,
|
|
@@ -207,15 +301,27 @@ var FilesKnowledgeAdapter = class {
|
|
|
207
301
|
capabilities = FILES_CAPABILITIES;
|
|
208
302
|
fs;
|
|
209
303
|
workspacePath;
|
|
304
|
+
label;
|
|
305
|
+
maxIndexDocs;
|
|
306
|
+
queryTimeoutMs;
|
|
307
|
+
log;
|
|
210
308
|
cachedIndex = null;
|
|
211
309
|
cachedAt = 0;
|
|
212
310
|
// In-flight build promise: concurrent turns that arrive while the index is
|
|
213
311
|
// still being built (cachedIndex === null) coalesce onto this promise instead
|
|
214
312
|
// of each kicking off a redundant 40-50s Supabase Storage re-scan.
|
|
215
313
|
buildInFlight = null;
|
|
314
|
+
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;
|
|
216
318
|
constructor(opts) {
|
|
217
319
|
this.fs = opts.fs;
|
|
218
320
|
this.workspacePath = opts.workspacePath;
|
|
321
|
+
this.label = opts.label ?? opts.workspacePath;
|
|
322
|
+
this.maxIndexDocs = typeof opts.maxIndexDocs === "number" && opts.maxIndexDocs > 0 ? opts.maxIndexDocs : DEFAULT_MAX_INDEX_DOCS;
|
|
323
|
+
this.queryTimeoutMs = opts.queryTimeoutMs ?? INDEX_QUERY_TIMEOUT_MS;
|
|
324
|
+
this.log = opts.log ?? ((line) => console.log(line));
|
|
219
325
|
}
|
|
220
326
|
async ingest(input) {
|
|
221
327
|
const corpusBlock = readCorpusMeta(input.metadata);
|
|
@@ -278,7 +384,7 @@ var FilesKnowledgeAdapter = class {
|
|
|
278
384
|
}
|
|
279
385
|
async query(q) {
|
|
280
386
|
const start = Date.now();
|
|
281
|
-
const index = await this.ensureIndex(
|
|
387
|
+
const index = await this.ensureIndex(this.queryTimeoutMs);
|
|
282
388
|
const tokens = tokenize(q.query);
|
|
283
389
|
if (tokens.length === 0) {
|
|
284
390
|
return {
|
|
@@ -292,16 +398,22 @@ var FilesKnowledgeAdapter = class {
|
|
|
292
398
|
topK: q.topK,
|
|
293
399
|
minScore: q.minScore
|
|
294
400
|
});
|
|
295
|
-
const
|
|
296
|
-
|
|
297
|
-
|
|
401
|
+
const texts = await mapWithConcurrency(
|
|
402
|
+
scored,
|
|
403
|
+
INDEX_READ_CONCURRENCY,
|
|
404
|
+
(s) => this.readText(s.doc.id)
|
|
405
|
+
);
|
|
406
|
+
const hits = scored.map((s, i) => {
|
|
407
|
+
const text = texts[i];
|
|
408
|
+
const meta = parseFrontmatterMetadata(text);
|
|
409
|
+
const snippet = makeSnippet(text, tokens);
|
|
298
410
|
return {
|
|
299
411
|
sourceId: s.doc.id,
|
|
300
412
|
chunkId: s.doc.id,
|
|
301
|
-
text:
|
|
413
|
+
text: snippet.text,
|
|
302
414
|
score: s.score,
|
|
303
415
|
// span is in original-file bytes; matches engine "citations" capability.
|
|
304
|
-
span:
|
|
416
|
+
span: { start: snippet.start, end: snippet.end },
|
|
305
417
|
metadata: meta
|
|
306
418
|
};
|
|
307
419
|
});
|
|
@@ -317,21 +429,17 @@ var FilesKnowledgeAdapter = class {
|
|
|
317
429
|
}
|
|
318
430
|
async listSources(filter) {
|
|
319
431
|
const index = await this.ensureIndex();
|
|
432
|
+
if (filter?.kind && filter.kind !== "file") return Object.freeze([]);
|
|
433
|
+
if (filter?.status && filter.status !== "ready") return Object.freeze([]);
|
|
320
434
|
const out = [];
|
|
321
|
-
for (
|
|
322
|
-
const
|
|
323
|
-
const
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
status: "ready",
|
|
330
|
-
metadata: meta
|
|
331
|
-
};
|
|
332
|
-
if (filter?.kind && source.kind !== filter.kind) continue;
|
|
333
|
-
if (filter?.status && source.status !== filter.status) continue;
|
|
334
|
-
out.push(source);
|
|
435
|
+
for (let i = 0; i < index.docs.length; i += INDEX_BUILD_STEP) {
|
|
436
|
+
const step = index.docs.slice(i, i + INDEX_BUILD_STEP);
|
|
437
|
+
const texts = await mapWithConcurrency(
|
|
438
|
+
step,
|
|
439
|
+
INDEX_READ_CONCURRENCY,
|
|
440
|
+
(doc) => this.readText(doc.id)
|
|
441
|
+
);
|
|
442
|
+
step.forEach((doc, j) => out.push(fileSource(doc.id, texts[j])));
|
|
335
443
|
}
|
|
336
444
|
return Object.freeze(out);
|
|
337
445
|
}
|
|
@@ -339,16 +447,7 @@ var FilesKnowledgeAdapter = class {
|
|
|
339
447
|
const index = await this.ensureIndex();
|
|
340
448
|
const doc = index.docs.find((d) => d.id === id);
|
|
341
449
|
if (!doc) return null;
|
|
342
|
-
|
|
343
|
-
return {
|
|
344
|
-
id: doc.id,
|
|
345
|
-
kind: "file",
|
|
346
|
-
uri: doc.id,
|
|
347
|
-
title: typeof meta.title === "string" ? meta.title : void 0,
|
|
348
|
-
bytes: byteLength(doc.text),
|
|
349
|
-
status: "ready",
|
|
350
|
-
metadata: meta
|
|
351
|
-
};
|
|
450
|
+
return fileSource(doc.id, await this.readText(doc.id));
|
|
352
451
|
}
|
|
353
452
|
async deleteSource(id) {
|
|
354
453
|
if (await this.fs.exists(id)) {
|
|
@@ -386,46 +485,104 @@ var FilesKnowledgeAdapter = class {
|
|
|
386
485
|
invalidate() {
|
|
387
486
|
this.cachedIndex = null;
|
|
388
487
|
this.cachedAt = 0;
|
|
488
|
+
this.refusal = null;
|
|
389
489
|
}
|
|
390
490
|
async ensureIndex(timeoutMs) {
|
|
391
491
|
if (this.cachedIndex && Date.now() - this.cachedAt < CACHE_TTL_MS) {
|
|
392
492
|
return this.cachedIndex;
|
|
393
493
|
}
|
|
494
|
+
if (this.refusal) throw this.refusal;
|
|
394
495
|
if (!this.buildInFlight) {
|
|
395
|
-
this.
|
|
496
|
+
this.buildStartedAt = Date.now();
|
|
497
|
+
const build = runExclusiveBuild(() => this._buildIndex()).finally(() => {
|
|
396
498
|
this.buildInFlight = null;
|
|
397
499
|
});
|
|
500
|
+
build.catch(() => void 0);
|
|
501
|
+
this.buildInFlight = build;
|
|
398
502
|
}
|
|
399
503
|
if (timeoutMs !== void 0) {
|
|
400
|
-
const
|
|
401
|
-
|
|
402
|
-
|
|
504
|
+
const build = this.buildInFlight;
|
|
505
|
+
let timer;
|
|
506
|
+
const deadline = new Promise((resolve) => {
|
|
507
|
+
timer = setTimeout(() => resolve(null), timeoutMs);
|
|
508
|
+
});
|
|
509
|
+
const winner = await Promise.race([build, deadline]).finally(
|
|
510
|
+
() => clearTimeout(timer)
|
|
511
|
+
);
|
|
512
|
+
if (winner) return winner;
|
|
513
|
+
this.log(
|
|
514
|
+
`[knowledge-files:${this.label}] query timed out after ${timeoutMs} ms waiting for the index build (running for ${Date.now() - this.buildStartedAt} ms); returning no hits, the build keeps going`
|
|
403
515
|
);
|
|
404
|
-
return
|
|
516
|
+
return EMPTY_INDEX;
|
|
405
517
|
}
|
|
406
518
|
return this.buildInFlight;
|
|
407
519
|
}
|
|
408
520
|
async _buildIndex() {
|
|
521
|
+
const start = Date.now();
|
|
522
|
+
const heapBefore = heapUsedMb();
|
|
409
523
|
const allPaths = await this.fs.walk(this.workspacePath);
|
|
410
524
|
const candidates = allPaths.filter(
|
|
411
525
|
(p) => INDEXED_EXTENSIONS.some((ext) => p.toLowerCase().endsWith(ext))
|
|
412
526
|
);
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
527
|
+
if (candidates.length > this.maxIndexDocs) {
|
|
528
|
+
const refusal = new FilesIndexTooLargeError(
|
|
529
|
+
this.label,
|
|
530
|
+
candidates.length,
|
|
531
|
+
this.maxIndexDocs
|
|
532
|
+
);
|
|
533
|
+
this.refusal = refusal;
|
|
534
|
+
this.log(
|
|
535
|
+
`[knowledge-files:${this.label}] index build refused: ${candidates.length} indexable files exceed the ceiling of ${this.maxIndexDocs}`
|
|
536
|
+
);
|
|
537
|
+
throw refusal;
|
|
538
|
+
}
|
|
539
|
+
const builder = new Bm25IndexBuilder();
|
|
540
|
+
let bytesRead = 0;
|
|
541
|
+
for (let i = 0; i < candidates.length; i += INDEX_BUILD_STEP) {
|
|
542
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
543
|
+
const step = candidates.slice(i, i + INDEX_BUILD_STEP);
|
|
544
|
+
const texts = await mapWithConcurrency(
|
|
545
|
+
step,
|
|
546
|
+
INDEX_READ_CONCURRENCY,
|
|
547
|
+
(path2) => this.fs.readFile(path2).catch(() => "")
|
|
548
|
+
);
|
|
549
|
+
step.forEach((path2, j) => {
|
|
550
|
+
const content = texts[j];
|
|
551
|
+
if (content.length === 0) return;
|
|
552
|
+
bytesRead += byteLength(content);
|
|
553
|
+
builder.add(path2, content);
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
const index = builder.finish();
|
|
424
557
|
this.cachedIndex = index;
|
|
425
558
|
this.cachedAt = Date.now();
|
|
559
|
+
this.log(
|
|
560
|
+
`[knowledge-files:${this.label}] index built: ${index.docs.length} docs, ${bytesRead} bytes read, ${Date.now() - start} ms, heapUsed ${heapBefore} MB -> ${heapUsedMb()} MB`
|
|
561
|
+
);
|
|
426
562
|
return index;
|
|
427
563
|
}
|
|
564
|
+
/** A doc's current text, or "" when it can no longer be read. */
|
|
565
|
+
readText(id) {
|
|
566
|
+
return this.fs.readFile(id).catch(() => "");
|
|
567
|
+
}
|
|
428
568
|
};
|
|
569
|
+
var EMPTY_INDEX = new Bm25IndexBuilder().finish();
|
|
570
|
+
function heapUsedMb() {
|
|
571
|
+
if (typeof process === "undefined" || !process.memoryUsage) return "?";
|
|
572
|
+
return Math.round(process.memoryUsage().heapUsed / (1024 * 1024));
|
|
573
|
+
}
|
|
574
|
+
function fileSource(id, text) {
|
|
575
|
+
const meta = parseFrontmatterMetadata(text);
|
|
576
|
+
return {
|
|
577
|
+
id,
|
|
578
|
+
kind: "file",
|
|
579
|
+
uri: id,
|
|
580
|
+
title: typeof meta.title === "string" ? meta.title : void 0,
|
|
581
|
+
bytes: byteLength(text),
|
|
582
|
+
status: "ready",
|
|
583
|
+
metadata: meta
|
|
584
|
+
};
|
|
585
|
+
}
|
|
429
586
|
async function mapWithConcurrency(items, limit, fn) {
|
|
430
587
|
const results = new Array(items.length);
|
|
431
588
|
let cursor = 0;
|
|
@@ -659,6 +816,6 @@ function makeKnowledgeFilesResolver() {
|
|
|
659
816
|
});
|
|
660
817
|
}
|
|
661
818
|
|
|
662
|
-
export { FILES_BM25_SLUG, FILES_CAPABILITIES, FILES_ENGINE_ID, FilesKnowledgeAdapter, KNOWLEDGE_FAMILY, KNOWLEDGE_FILES_CATALOG, LocalFs, buildIndex, buildIndexYielding, createStandaloneFilesAdapter, loadFilesKnowledgeEnv, makeKnowledgeFilesResolver, resolveKnowledgeBackend, score, tokenize };
|
|
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 };
|
|
663
820
|
//# sourceMappingURL=index.mjs.map
|
|
664
821
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/bm25.ts","../src/adapter.ts","../src/local-fs.ts","../src/env.ts","../src/standalone.ts","../src/catalog.ts","../src/handle.ts"],"names":["path"],"mappings":";;;;;;;;;;;;;;AAeA,IAAM,EAAA,GAAK,GAAA;AACX,IAAM,CAAA,GAAI,IAAA;AACV,IAAM,aAAA,GAAgB,CAAA;AACtB,IAAM,aAAA,GAAgB,EAAA;AAKtB,IAAM,SAAA,uBAAgB,GAAA,CAAI;AAAA,EACxB,GAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,IAAA;AAAA,EACA,IAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,MAAA;AAAA,EACA,KAAA;AAAA,EACA,MAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,GAAA;AAAA,EACA,IAAA;AAAA,EACA,IAAA;AAAA,EACA,IAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,IAAA;AAAA,EACA,IAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,IAAA;AAAA,EACA,IAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,IAAA;AAAA,EACA,MAAA;AAAA,EACA,KAAA;AAAA,EACA,OAAA;AAAA,EACA,MAAA;AAAA,EACA,MAAA;AAAA,EACA,OAAA;AAAA,EACA,MAAA;AAAA,EACA,MAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,IAAA;AAAA,EACA,MAAA;AAAA,EACA,MAAA;AAAA,EACA,MAAA;AAAA,EACA,OAAA;AAAA,EACA,KAAA;AAAA,EACA,MAAA;AAAA,EACA,MAAA;AAAA,EACA,KAAA;AAAA,EACA;AACF,CAAC,CAAA;AAGD,SAAS,iBAAiB,OAAA,EAAyB;AACjD,EAAA,IAAI,CAAC,OAAA,CAAQ,UAAA,CAAW,K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AAA,GAC/B,CAAA;AACH","file":"index.mjs","sourcesContent":["/**\n * In-process BM25 — a tiny, dependency-free implementation tuned for\n * corpus-sized data (hundreds to low thousands of markdown files).\n *\n * Tokenizer: lowercase, split on non-alphanum, length 2-32, drop a small\n * English stopword list. Frontmatter is stripped before tokenization so\n * fence values like `schema: knowledge.entry/v1` don't pollute the\n * vocabulary.\n *\n * Scoring: standard BM25 with k1=1.5, b=0.75 — Lucene defaults. IDF\n * uses the \"BM25+1\" smoothing so terms appearing in every doc still\n * contribute a tiny positive score (avoids the negative-IDF foot-gun\n * for high-frequency terms).\n */\n\nconst K1 = 1.5\nconst B = 0.75\nconst MIN_TOKEN_LEN = 2\nconst MAX_TOKEN_LEN = 32\n\n// Short en stopword list — keeps the index lean without doing real NLP.\n// Domain stopwords (\"the company\", \"agentik\") could be added per-corpus\n// in a follow-up if the noise becomes meaningful.\nconst STOPWORDS = new Set([\n \"a\",\n \"an\",\n \"and\",\n \"are\",\n \"as\",\n \"at\",\n \"be\",\n \"but\",\n \"by\",\n \"for\",\n \"from\",\n \"has\",\n \"have\",\n \"he\",\n \"her\",\n \"his\",\n \"i\",\n \"if\",\n \"in\",\n \"is\",\n \"it\",\n \"its\",\n \"me\",\n \"my\",\n \"no\",\n \"not\",\n \"of\",\n \"on\",\n \"or\",\n \"she\",\n \"so\",\n \"that\",\n \"the\",\n \"their\",\n \"them\",\n \"then\",\n \"there\",\n \"they\",\n \"this\",\n \"to\",\n \"was\",\n \"we\",\n \"were\",\n \"what\",\n \"when\",\n \"which\",\n \"who\",\n \"will\",\n \"with\",\n \"you\",\n \"your\",\n])\n\n/** Strip YAML frontmatter (--- ... ---) from a doc body if present. */\nfunction stripFrontmatter(content: string): string {\n if (!content.startsWith(\"---\")) return content\n const end = content.indexOf(\"\\n---\", 3)\n if (end === -1) return content\n return content.slice(end + 4)\n}\n\nexport function tokenize(text: string): string[] {\n const out: string[] = []\n // Splitting on \\W+ would lose digits in alphanumeric tokens like\n // \"q3\"; use a unicode-aware non-word class instead.\n for (const raw of text.toLowerCase().split(/[^a-z0-9]+/)) {\n if (raw.length < MIN_TOKEN_LEN || raw.length > MAX_TOKEN_LEN) continue\n if (STOPWORDS.has(raw)) continue\n out.push(raw)\n }\n return out\n}\n\nexport interface Bm25Doc {\n /** Stable id — typically the workspace-relative path. */\n readonly id: string\n /** Original text (kept for snippet extraction at query time). */\n readonly text: string\n /** Token count — used for length-normalization in BM25. */\n readonly length: number\n /** Term frequency table for this doc. */\n readonly tf: ReadonlyMap<string, number>\n}\n\nexport interface Bm25Index {\n readonly docs: readonly Bm25Doc[]\n /** Number of docs containing each term — used in IDF. */\n readonly df: ReadonlyMap<string, number>\n /** Average document length across the index, in tokens. */\n readonly avgDocLength: number\n}\n\nexport interface BuildDocInput {\n readonly id: string\n readonly content: string\n}\n\nexport function buildIndex(inputs: readonly BuildDocInput[]): Bm25Index {\n const docs: Bm25Doc[] = []\n const df = new Map<string, number>()\n let totalLength = 0\n for (const input of inputs) {\n const tokens = tokenize(stripFrontmatter(input.content))\n const tf = new Map<string, number>()\n for (const tok of tokens) {\n tf.set(tok, (tf.get(tok) ?? 0) + 1)\n }\n for (const term of tf.keys()) {\n df.set(term, (df.get(term) ?? 0) + 1)\n }\n docs.push({\n id: input.id,\n text: input.content,\n length: tokens.length,\n tf,\n })\n totalLength += tokens.length\n }\n const avgDocLength = docs.length === 0 ? 0 : totalLength / docs.length\n return { docs, df, avgDocLength }\n}\n\n/**\n * Async, event-loop-friendly variant of {@link buildIndex}. Identical output,\n * but yields to the macrotask queue every `yieldEvery` docs.\n *\n * Why this matters: the caller (`FilesKnowledgeAdapter._buildIndex`) reads docs\n * from an in-memory/cached fs, so the awaited reads resolve as MICROTASKS and\n * never hand control back to the event loop. Without an explicit yield, the\n * tokenization of every doc runs as one uninterruptible synchronous chain —\n * which (a) freezes every concurrent recall on this single-process, multi-tenant\n * instance for the full build and (b) defeats `ensureIndex`'s non-blocking\n * `setTimeout` deadline (the timer can't fire while the loop is blocked). The\n * `setImmediate` yield lets sibling turns progress and the deadline fire during a\n * cold build.\n */\nexport async function buildIndexYielding(\n inputs: readonly BuildDocInput[],\n yieldEvery = 50\n): Promise<Bm25Index> {\n const docs: Bm25Doc[] = []\n const df = new Map<string, number>()\n let totalLength = 0\n let i = 0\n for (const input of inputs) {\n if (i++ % yieldEvery === 0)\n await new Promise<void>(resolve => setImmediate(resolve))\n const tokens = tokenize(stripFrontmatter(input.content))\n const tf = new Map<string, number>()\n for (const tok of tokens) {\n tf.set(tok, (tf.get(tok) ?? 0) + 1)\n }\n for (const term of tf.keys()) {\n df.set(term, (df.get(term) ?? 0) + 1)\n }\n docs.push({\n id: input.id,\n text: input.content,\n length: tokens.length,\n tf,\n })\n totalLength += tokens.length\n }\n const avgDocLength = docs.length === 0 ? 0 : totalLength / docs.length\n return { docs, df, avgDocLength }\n}\n\nexport interface ScoredHit {\n readonly doc: Bm25Doc\n readonly score: number\n /** Char range in `doc.text` around the first matching token. */\n readonly snippet?: {\n readonly start: number\n readonly end: number\n readonly text: string\n }\n}\n\n/**\n * Score every doc against the query tokens, return top-k.\n * Docs with score <= 0 are dropped (no terms matched).\n */\nexport function score(\n index: Bm25Index,\n queryTokens: readonly string[],\n opts: { readonly topK?: number; readonly minScore?: number } = {}\n): ScoredHit[] {\n if (queryTokens.length === 0 || index.docs.length === 0) return []\n const topK = opts.topK ?? 10\n const minScore = opts.minScore ?? 0\n const N = index.docs.length\n const out: ScoredHit[] = []\n\n for (const doc of index.docs) {\n let s = 0\n for (const term of queryTokens) {\n const f = doc.tf.get(term)\n if (!f) continue\n const n = index.df.get(term) ?? 0\n // BM25 IDF with +1 smoothing — see \"Improvements to BM25 and\n // language models examined\" (Lv & Zhai, 2011) for the rationale.\n const idf = Math.log((N - n + 0.5) / (n + 0.5) + 1)\n const denom =\n f +\n K1 *\n (1 -\n B +\n (B * doc.length) /\n (index.avgDocLength === 0 ? 1 : index.avgDocLength))\n s += idf * ((f * (K1 + 1)) / denom)\n }\n if (s <= minScore) continue\n out.push({ doc, score: s, snippet: makeSnippet(doc.text, queryTokens) })\n }\n out.sort((a, b) => b.score - a.score)\n return out.slice(0, topK)\n}\n\n/**\n * Pull a ~300-char window around the first matching query token in\n * the doc body. Falls back to the doc's head when no token matches in\n * the surfaced text (e.g. matches were all in the stripped frontmatter).\n */\nfunction makeSnippet(\n text: string,\n queryTokens: readonly string[]\n): { start: number; end: number; text: string } | undefined {\n const body = stripFrontmatter(text)\n const offset = text.length - body.length\n const lower = body.toLowerCase()\n let firstAt = -1\n for (const tok of queryTokens) {\n const idx = lower.indexOf(tok)\n if (idx !== -1 && (firstAt === -1 || idx < firstAt)) firstAt = idx\n }\n const around = 150\n const start = Math.max(0, (firstAt === -1 ? 0 : firstAt) - around)\n const end = Math.min(body.length, start + 300)\n return {\n start: offset + start,\n end: offset + end,\n text: body.slice(start, end),\n }\n}\n","/**\n * FilesKnowledgeAdapter — the no-runtime, no-embedding KB engine.\n *\n * Indexes workspace files in process with BM25. Zero setup: works the\n * instant a guild has a system workspace, no E2B sandbox, no API key,\n * no cold start. Best suited as the DEFAULT corpus backing where the\n * AIP-10 entries already live as markdown files — the entries ARE the\n * index, no separate vector store to keep in sync.\n *\n * Index lifecycle: built lazily on first query, cached for 30s, also\n * invalidated explicitly by `ingest()`. External edits (a user typing\n * in the workspace UI) become visible on the next rebuild — for\n * second-precision freshness, hosts can wire fs-watch into the\n * `invalidate()` method.\n *\n * Lifted VERBATIM from the studio integration package\n * (`packages/integration/knowledge/src/providers/files/adapter.ts`) — the\n * class already carried no `@guilde/@simone/@agstudio` edge (it consumes an\n * injected `FsPort` and the vendor-neutral `IKnowledgeProvider` contract), so\n * it re-homes as-is. The ONLY change is the two import paths: the contract +\n * data types now come from `@agentproto/knowledge-engine` (was\n * `../base-knowledge.provider` / `../../types/knowledge.types`). The guild-side\n * `KnowledgeEngineDescriptor` (studio `descriptor.ts`) is NOT lifted — it\n * belonged to the guild resolution layer; this package registers as a\n * provider-kit family instead (see `handle.ts`).\n */\n\nimport type { FsPort } from \"@agentproto/corpus\"\nimport {\n KnowledgeNotSupportedError,\n type IKnowledgeProvider,\n type KnowledgeCapabilities,\n type KnowledgeHit,\n type KnowledgeIngestInput,\n type KnowledgeQuery,\n type KnowledgeQueryResult,\n type KnowledgeSource,\n type ListSourcesFilter,\n type KnowledgeProvenance,\n} from \"@agentproto/knowledge-engine\"\nimport {\n buildIndexYielding as buildBm25IndexYielding,\n score as scoreBm25,\n tokenize,\n type Bm25Index,\n} from \"./bm25.js\"\n\nexport const FILES_ENGINE_ID = \"files\" as const\n\nconst INDEXED_EXTENSIONS = [\n \".md\",\n \".markdown\",\n \".txt\",\n \".yaml\",\n \".yml\",\n \".json\",\n]\n// Corpus content is immutable between `promote_candidate` / `rebuild_lens`\n// writes. Both code-paths call either `invalidate()` (via ingest/delete) or\n// drop the whole provider instance (via `invalidateKnowledgeProvider`), so\n// time-based expiry is never needed for correctness — it only forces a full\n// Supabase Storage re-scan on every turn after 30 s, causing 37-52s latency.\n// Use a permanent cache: the index is rebuilt only when the adapter explicitly\n// calls `invalidate()`, or when a new instance is created after a provider\n// cache eviction.\nconst CACHE_TTL_MS = Number.POSITIVE_INFINITY\n\n/**\n * Max concurrent file reads while (re)building the index. Backings like\n * Supabase Storage serve each `readFile` as its own REST round-trip with\n * an internal `AbortSignal.timeout(4000)`; firing all ~N reads at once\n * saturates the event loop and connection pool so the timers expire\n * before the responses land (observed: 426 TimeoutErrors on a ~264-file\n * corpus). A small ceiling keeps each read inside its own budget.\n */\nconst INDEX_READ_CONCURRENCY = 10\n\n/**\n * Max ms a query waits for an in-progress BM25 build before giving up and\n * returning empty results. The build continues in background — the next query\n * on the same instance will find the index ready (or still building if the\n * corpus is very large). Without this cap, cold-start builds on Supabase\n * Storage (50-150 s for large corpora) block every turn on every new Cloud\n * Run instance, which has no cross-instance shared cache.\n */\nconst INDEX_QUERY_TIMEOUT_MS = 4_000\n\nexport const FILES_CAPABILITIES: KnowledgeCapabilities = Object.freeze({\n vectorSearch: false,\n graphTraversal: false,\n hybridSearch: false,\n multiModal: false,\n streaming: false,\n // BM25 returns ranked hits with file path + byte span — usable as\n // citations even though there's no vector concept.\n citations: true,\n // Chunk size matters for backings that split — files engine indexes\n // whole files so this is an informational ceiling.\n maxChunkBytes: 64 * 1024,\n})\n\nexport interface FilesAdapterConfig {\n /** Workspace-relative root the engine indexes (walks recursively). */\n readonly workspacePath: string\n}\n\nexport interface FilesKnowledgeAdapterOptions extends FilesAdapterConfig {\n /** FsPort scoped to the workspace the engine lives in. */\n readonly fs: FsPort\n}\n\nexport class FilesKnowledgeAdapter implements IKnowledgeProvider {\n readonly id = FILES_ENGINE_ID\n readonly capabilities = FILES_CAPABILITIES\n\n private readonly fs: FsPort\n private readonly workspacePath: string\n private cachedIndex: Bm25Index | null = null\n private cachedAt = 0\n // In-flight build promise: concurrent turns that arrive while the index is\n // still being built (cachedIndex === null) coalesce onto this promise instead\n // of each kicking off a redundant 40-50s Supabase Storage re-scan.\n private buildInFlight: Promise<Bm25Index> | null = null\n\n constructor(opts: FilesKnowledgeAdapterOptions) {\n this.fs = opts.fs\n this.workspacePath = opts.workspacePath\n }\n\n async ingest(input: KnowledgeIngestInput): Promise<KnowledgeSource> {\n // The corpus indexer pushes pre-chunked entries here; the entry .md\n // file is already written by CorpusPromoter, so all we need to do\n // is invalidate the index and return a synthetic source. Skipping\n // the write avoids ghost `sources/chunk-*.md` files duplicating\n // every entry's body.\n const corpusBlock = readCorpusMeta(input.metadata)\n if (corpusBlock?.entrySlug) {\n this.invalidate()\n return {\n id: `${corpusBlock.entrySlug}#${corpusBlock.chunkIndex ?? 0}`,\n kind: \"text\",\n uri: corpusBlock.entryPath ?? input.uri,\n title: input.title,\n metadata: input.metadata ?? {},\n bytes: byteLength(input.content),\n status: \"ready\",\n indexedAt: new Date(),\n }\n }\n\n if (input.kind === \"text\") {\n const sourceId = stableSlug(input.uri)\n const dest = `${this.workspacePath}/sources/${sourceId}.md`\n const content = decodeContent(input.content) ?? \"\"\n await this.fs.writeFile(dest, content)\n this.invalidate()\n return {\n id: sourceId,\n kind: \"text\",\n uri: input.uri,\n title: input.title,\n metadata: input.metadata ?? {},\n bytes: byteLength(content),\n status: \"ready\",\n indexedAt: new Date(),\n }\n }\n\n if (input.kind === \"url\") {\n const res = await fetch(input.uri)\n if (!res.ok) {\n throw new Error(\n `files engine: failed to fetch ${input.uri}: ${res.status} ${res.statusText}`\n )\n }\n const text = await res.text()\n const sourceId = stableSlug(input.uri)\n const dest = `${this.workspacePath}/sources/${sourceId}.txt`\n await this.fs.writeFile(dest, text)\n this.invalidate()\n return {\n id: sourceId,\n kind: \"url\",\n uri: input.uri,\n title: input.title,\n metadata: input.metadata ?? {},\n bytes: byteLength(text),\n status: \"ready\",\n indexedAt: new Date(),\n }\n }\n\n throw new Error(\n `files engine: ingest kind=\"${input.kind}\" not supported. ` +\n `Pass kind=\"text\" with inline content, or kind=\"url\" for the engine to fetch.`\n )\n }\n\n async query(q: KnowledgeQuery): Promise<KnowledgeQueryResult> {\n const start = Date.now()\n // Non-blocking: if the BM25 index isn't ready within INDEX_QUERY_TIMEOUT_MS,\n // return empty results and let the build continue in background. The next\n // query on the same instance will find the index warm. This prevents a cold\n // Supabase Storage rebuild (50-150 s on large corpora) from blocking every\n // turn on fresh Cloud Run instances.\n const index = await this.ensureIndex(INDEX_QUERY_TIMEOUT_MS)\n const tokens = tokenize(q.query)\n if (tokens.length === 0) {\n return {\n hits: Object.freeze([]),\n tookMs: Date.now() - start,\n engine: this.id,\n modeUsed: \"vector\",\n }\n }\n const scored = scoreBm25(index, tokens, {\n topK: q.topK,\n minScore: q.minScore,\n })\n const hits: KnowledgeHit[] = scored.map(s => {\n const meta = parseFrontmatterMetadata(s.doc.text)\n const snippetText = s.snippet?.text ?? s.doc.text.slice(0, 300)\n return {\n sourceId: s.doc.id,\n chunkId: s.doc.id,\n text: snippetText,\n score: s.score,\n // span is in original-file bytes; matches engine \"citations\" capability.\n span: s.snippet\n ? { start: s.snippet.start, end: s.snippet.end }\n : undefined,\n metadata: meta,\n }\n })\n return {\n hits: Object.freeze(hits),\n tookMs: Date.now() - start,\n engine: this.id,\n // BM25 isn't really \"vector\" — the union doesn't have a \"keyword\"\n // option. Report \"vector\" as the closest existing label until the\n // mode union widens.\n modeUsed: \"vector\",\n }\n }\n\n async listSources(\n filter?: ListSourcesFilter\n ): Promise<readonly KnowledgeSource[]> {\n const index = await this.ensureIndex()\n const out: KnowledgeSource[] = []\n for (const doc of index.docs) {\n const meta = parseFrontmatterMetadata(doc.text)\n const source: KnowledgeSource = {\n id: doc.id,\n kind: \"file\",\n uri: doc.id,\n title: typeof meta.title === \"string\" ? meta.title : undefined,\n bytes: byteLength(doc.text),\n status: \"ready\",\n metadata: meta,\n }\n if (filter?.kind && source.kind !== filter.kind) continue\n if (filter?.status && source.status !== filter.status) continue\n out.push(source)\n }\n return Object.freeze(out)\n }\n\n async getSource(id: string): Promise<KnowledgeSource | null> {\n const index = await this.ensureIndex()\n const doc = index.docs.find(d => d.id === id)\n if (!doc) return null\n const meta = parseFrontmatterMetadata(doc.text)\n return {\n id: doc.id,\n kind: \"file\",\n uri: doc.id,\n title: typeof meta.title === \"string\" ? meta.title : undefined,\n bytes: byteLength(doc.text),\n status: \"ready\",\n metadata: meta,\n }\n }\n\n async deleteSource(id: string): Promise<void> {\n // The path IS the source — deletion means removing the file. The\n // adapter intentionally writes through the same FsPort it reads\n // from, so external editors and the engine stay in sync.\n if (await this.fs.exists(id)) {\n // FsPort doesn't expose `unlink`; write empty to drop content\n // without breaking the contract. Hosts that need true unlink\n // wire it via their own admin path.\n await this.fs.writeFile(id, \"\")\n }\n this.invalidate()\n }\n\n async supersede(_id: string, _by?: string): Promise<void> {\n throw new KnowledgeNotSupportedError(\n this.id,\n \"supersede\",\n \"plain files carry no lifecycle status; use the corpus adapter over an AIP-10 workspace\",\n )\n }\n\n async explain(id: string): Promise<KnowledgeProvenance | null> {\n const source = await this.getSource(id)\n if (!source) return null\n // A file's provenance is its path and own frontmatter; there is no\n // upstream-derivation or audit chain at this layer.\n return {\n sourceId: source.id,\n derivedFrom: [],\n metadata: { uri: source.uri, ...source.metadata },\n }\n }\n\n async healthCheck(): Promise<boolean> {\n try {\n // Health = the root path is reachable. An empty workspace is\n // healthy (zero hits is a valid query result).\n return await this.fs.exists(this.workspacePath)\n } catch {\n return false\n }\n }\n\n async dispose(): Promise<void> {\n this.cachedIndex = null\n }\n\n /** Drop the cached BM25 index — next query rebuilds. */\n private invalidate(): void {\n this.cachedIndex = null\n this.cachedAt = 0\n // Do NOT clear buildInFlight: an in-flight build that started before the\n // invalidate will still store its result, which is immediately stale. The\n // next ensureIndex() call after it resolves will see cachedIndex !== null\n // but cachedAt = 0, which with POSITIVE_INFINITY TTL still passes. This is\n // acceptable: the stale index is at most one build's worth of lag and is\n // replaced on the next explicit write that calls invalidate() + triggers a\n // new query. Clearing buildInFlight would just cause more redundant builds.\n }\n\n private async ensureIndex(timeoutMs?: number): Promise<Bm25Index> {\n if (this.cachedIndex && Date.now() - this.cachedAt < CACHE_TTL_MS) {\n return this.cachedIndex\n }\n // Coalesce concurrent callers onto one in-flight build. Without this,\n // two turns arriving before the first build completes both see\n // cachedIndex===null and each kick off a full 40-50s Supabase Storage\n // re-scan — wasting resources and keeping both turns slow.\n if (!this.buildInFlight) {\n this.buildInFlight = this._buildIndex().finally(() => {\n this.buildInFlight = null\n })\n }\n if (timeoutMs !== undefined) {\n // Non-blocking mode: race the build against a deadline. If the build\n // wins, great — the index is ready. If the deadline fires first, return\n // an empty index so the turn can proceed without knowledge context. The\n // build continues in background; the next call to ensureIndex() will\n // either find the cache populated (build done) or coalesce onto the\n // still-in-flight promise again.\n const EMPTY: Bm25Index = { docs: [], avgDocLength: 0, df: new Map() }\n const deadline = new Promise<Bm25Index>(resolve =>\n setTimeout(() => resolve(EMPTY), timeoutMs)\n )\n return Promise.race([this.buildInFlight, deadline])\n }\n return this.buildInFlight\n }\n\n private async _buildIndex(): Promise<Bm25Index> {\n const allPaths = await this.fs.walk(this.workspacePath)\n const candidates = allPaths.filter(p =>\n INDEXED_EXTENSIONS.some(ext => p.toLowerCase().endsWith(ext))\n )\n const inputs = await mapWithConcurrency(\n candidates,\n INDEX_READ_CONCURRENCY,\n async path => ({\n id: path,\n content: await this.fs.readFile(path).catch(() => \"\"),\n })\n )\n const index = await buildBm25IndexYielding(\n inputs.filter(i => i.content.length > 0)\n )\n this.cachedIndex = index\n this.cachedAt = Date.now()\n return index\n }\n}\n\n// ── helpers ──────────────────────────────────────────────────────────\n\n/**\n * Map `items` through `fn` with at most `limit` calls in flight at once,\n * preserving input order in the result. A fixed pool of workers drains a\n * shared cursor — no batch barriers, so a slow read never stalls the\n * whole pool. Dependency-free stand-in for p-limit.\n */\nasync function mapWithConcurrency<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T, index: number) => Promise<R>\n): Promise<R[]> {\n const results = new Array<R>(items.length)\n let cursor = 0\n const workers = Array.from(\n { length: Math.max(1, Math.min(limit, items.length)) },\n async () => {\n while (cursor < items.length) {\n const i = cursor++\n results[i] = await fn(items[i]!, i)\n }\n }\n )\n await Promise.all(workers)\n return results\n}\n\nfunction decodeContent(content: unknown): string | undefined {\n if (typeof content === \"string\") return content\n if (content instanceof Uint8Array) return new TextDecoder().decode(content)\n return undefined\n}\n\nfunction byteLength(content: unknown): number {\n if (typeof content === \"string\")\n return new TextEncoder().encode(content).byteLength\n if (content instanceof Uint8Array) return content.byteLength\n return 0\n}\n\n/** Stable kebab-case id derived from a uri-ish input. */\nfunction stableSlug(uri: string): string {\n const base = uri.replace(/^[a-z]+:\\/+/, \"\").replace(/[/\\\\]+/g, \"-\")\n const slug = base\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 96)\n return slug || `source-${Date.now().toString(36)}`\n}\n\n/**\n * Surface frontmatter as the hit's metadata so corpus-side hydration\n * (which keys on `metadata.entrySlug`) round-trips correctly when this\n * engine backs a corpus. Frontmatter is also surfaced for standalone\n * use so callers can read entry-level fields like `title`, `tags`.\n *\n * Returns `{}` when no frontmatter is present — never throws.\n */\nfunction parseFrontmatterMetadata(\n content: string\n): Readonly<Record<string, unknown>> {\n if (!content.startsWith(\"---\")) return Object.freeze({})\n const end = content.indexOf(\"\\n---\", 3)\n if (end === -1) return Object.freeze({})\n const block = content.slice(4, end).trim()\n const out: Record<string, unknown> = {}\n // Minimal YAML — handle `key: value` and `key: \"value\"` at top level.\n // Nested objects are rare in entry frontmatter that drives retrieval;\n // hosts that need full parsing can wire gray-matter outside the\n // adapter and re-parse.\n for (const line of block.split(\"\\n\")) {\n const m = line.match(/^([a-zA-Z0-9_.-]+)\\s*:\\s*(.*)$/)\n if (!m) continue\n const key = m[1]!\n let value: unknown = m[2]!.trim()\n if (typeof value === \"string\") {\n if (value.startsWith('\"') && value.endsWith('\"'))\n value = value.slice(1, -1)\n else if (value.startsWith(\"'\") && value.endsWith(\"'\"))\n value = value.slice(1, -1)\n }\n out[key] = value\n }\n // Mirror the slug key into `entrySlug` so corpus-hydration finds it\n // without a per-engine adapter — corpus's `hydrateHit` keys on\n // `metadata.entrySlug` (see corpus/hydrate.ts).\n if (typeof out.slug === \"string\" && !(\"entrySlug\" in out)) {\n out.entrySlug = out.slug\n }\n return Object.freeze(out)\n}\n\nfunction readCorpusMeta(\n metadata: Readonly<Record<string, unknown>> | undefined\n): { entrySlug?: string; entryPath?: string; chunkIndex?: number } | undefined {\n if (!metadata) return undefined\n const corpus = (metadata as { corpus?: unknown }).corpus\n if (!corpus || typeof corpus !== \"object\") return undefined\n const block = corpus as Record<string, unknown>\n return {\n entrySlug:\n typeof block.entrySlug === \"string\" ? block.entrySlug : undefined,\n entryPath:\n typeof block.entryPath === \"string\" ? block.entryPath : undefined,\n chunkIndex:\n typeof block.chunkIndex === \"number\" ? block.chunkIndex : undefined,\n }\n}\n","/**\n * LocalFs — a `FsPort` (from `@agentproto/corpus`) backed by node:fs.\n *\n * The studio files provider never shipped its own `FsPort`: the guild host\n * resolved one (`resolveWorkspaceFs`) and injected it. agentproto-side that\n * host is gone (the guild registry stays studio-side per the Ph4 plan), so\n * this package ships the minimal local backing that lets the adapter run\n * standalone — the same role the code-brain adapter's own gbrain client plays.\n *\n * Mirrors `@agentproto/corpus-cli`'s `NodeFsAdapter` (that class lives in a\n * `-cli` package; a library adapter must not take a `-cli` edge, so the small\n * node:fs surface the files engine needs is re-implemented here). Paths are\n * workspace-relative and resolved under `root`; `resolve()` refuses to climb\n * out of it. `walk()` returns workspace-relative paths (readable back through\n * `readFile`) and skips hidden segments, exactly as `FsPort` specifies. `lock`\n * is a single-process no-op — this backing is local CLI, which the port\n * contract explicitly permits.\n */\n\nimport { randomBytes } from \"node:crypto\"\nimport {\n appendFile,\n mkdir,\n readFile,\n readdir,\n rename,\n stat,\n writeFile,\n} from \"node:fs/promises\"\nimport path from \"node:path\"\nimport type { FsLockHandle, FsPort, FsStat } from \"@agentproto/corpus\"\n\nexport interface LocalFsOptions {\n /**\n * Absolute path to the workspace root. Every `FsPort` path is resolved\n * relative to this — the adapter never sees a host filesystem path.\n */\n readonly root: string\n}\n\nexport class LocalFs implements FsPort {\n private readonly root: string\n\n constructor(opts: LocalFsOptions) {\n this.root = opts.root\n }\n\n async exists(p: string): Promise<boolean> {\n try {\n await stat(this.resolve(p))\n return true\n } catch {\n return false\n }\n }\n\n async readFile(p: string): Promise<string> {\n return await readFile(this.resolve(p), \"utf8\")\n }\n\n /**\n * Atomic write: write to `${target}.tmp-{nonce}`, then rename. Rename is\n * atomic on the same filesystem. Creates parent dirs as needed.\n */\n async writeFile(p: string, content: string): Promise<void> {\n const target = this.resolve(p)\n await mkdir(path.dirname(target), { recursive: true })\n const tmp = `${target}.tmp-${randomBytes(8).toString(\"hex\")}`\n await writeFile(tmp, content, \"utf8\")\n await rename(tmp, target)\n }\n\n async appendFile(p: string, content: string): Promise<void> {\n const target = this.resolve(p)\n await mkdir(path.dirname(target), { recursive: true })\n await appendFile(target, content, \"utf8\")\n }\n\n async readdir(p: string): Promise<readonly string[]> {\n return await readdir(this.resolve(p))\n }\n\n async walk(p: string): Promise<readonly string[]> {\n const out: string[] = []\n const start = this.resolve(p)\n const visit = async (dir: string): Promise<void> => {\n let entries: string[] = []\n try {\n entries = await readdir(dir)\n } catch {\n return\n }\n for (const ent of entries) {\n // Skip hidden segments — matches the FsPort contract.\n if (ent.startsWith(\".\")) continue\n const full = path.join(dir, ent)\n const s = await stat(full)\n if (s.isDirectory()) {\n await visit(full)\n } else if (s.isFile()) {\n out.push(path.relative(this.root, full).split(path.sep).join(\"/\"))\n }\n }\n }\n await visit(start)\n return out\n }\n\n async stat(p: string): Promise<FsStat | null> {\n try {\n const s = await stat(this.resolve(p))\n return {\n kind: s.isDirectory() ? \"directory\" : \"file\",\n bytes: s.isFile() ? s.size : undefined,\n modifiedAt: s.mtime,\n }\n } catch {\n return null\n }\n }\n\n /**\n * Advisory lock — a single-process no-op. The files engine never calls\n * `lock()` (it only reads/writes whole source files), and this backing is\n * local CLI, for which the `FsPort` contract permits a no-op lock.\n */\n async lock(_p: string): Promise<FsLockHandle> {\n return { release: async () => {} }\n }\n\n /**\n * Resolve a workspace-relative path to an absolute host path, refusing to\n * climb out of the workspace root (defense against `../../etc/passwd`-style\n * abuse). The files engine's paths must stay inside the workspace.\n */\n private resolve(p: string): string {\n const normalized = path.posix.normalize(\"/\" + p.replace(/^\\/+/, \"\"))\n const rel = normalized.slice(1)\n if (rel.startsWith(\"..\")) {\n throw new Error(\n `LocalFs: path \"${p}\" escapes the workspace root \"${this.root}\"`,\n )\n }\n return path.join(this.root, rel)\n }\n}\n","/**\n * Typed environment module for the files knowledge adapter.\n *\n * Every `process.env` read in this package flows through here — no raw\n * `process.env.X` at a call site (mirrors the code-brain adapter's `env.ts`).\n * Each loader parses the ambient env into a typed, defaulted config once, so\n * the rest of the adapter is a pure function of its inputs. This is the ONE\n * place the files-engine env names (`KNOWLEDGE_FILES_*`) live.\n */\n\n/** Config for the standalone files backend — a local root + a folder to index. */\nexport interface FilesKnowledgeEnv {\n /**\n * Absolute host path to the workspace root the {@link LocalFs} is rooted at.\n * Default: the process cwd.\n */\n readonly root: string\n /**\n * Workspace-relative folder the engine walks and indexes (recursively).\n * Default `\"knowledge\"`.\n */\n readonly workspacePath: string\n}\n\n/** Load {@link FilesKnowledgeEnv} from `process.env` with defaults. */\nexport function loadFilesKnowledgeEnv(): FilesKnowledgeEnv {\n const root = process.env.KNOWLEDGE_FILES_ROOT\n const workspacePath = process.env.KNOWLEDGE_FILES_PATH\n return {\n root: root !== undefined && root !== \"\" ? root : process.cwd(),\n workspacePath:\n workspacePath !== undefined && workspacePath !== \"\"\n ? workspacePath.trim()\n : \"knowledge\",\n }\n}\n","/**\n * Standalone wiring for {@link FilesKnowledgeAdapter}.\n *\n * The adapter class itself is backing-agnostic: it consumes an injected\n * `FsPort` and knows nothing about `node:fs` or `process.env`. This module\n * is the ONE place that binds it to the local filesystem — it reads the\n * typed `KNOWLEDGE_FILES_*` env (via {@link loadFilesKnowledgeEnv}) and roots\n * a {@link LocalFs} at it, exactly the role the code-brain adapter's\n * `gbrainLocalProvider` factory plays for its backend. Hosts that already\n * hold an `FsPort` (e.g. a studio guild host) should construct\n * `FilesKnowledgeAdapter` directly and skip this factory.\n */\n\nimport { FilesKnowledgeAdapter } from \"./adapter.js\"\nimport { loadFilesKnowledgeEnv } from \"./env.js\"\nimport { LocalFs } from \"./local-fs.js\"\n\n/**\n * Build a {@link FilesKnowledgeAdapter} backed by the local filesystem,\n * rooted and scoped from the ambient `KNOWLEDGE_FILES_*` env. Each call\n * returns a fresh adapter (and thus a fresh, empty BM25 cache) — callers\n * that want a shared warm index should hold onto the instance.\n */\nexport function createStandaloneFilesAdapter(): FilesKnowledgeAdapter {\n const env = loadFilesKnowledgeEnv()\n return new FilesKnowledgeAdapter({\n fs: new LocalFs({ root: env.root }),\n workspacePath: env.workspacePath,\n })\n}\n","import type { AdapterCatalog } from \"@agentproto/provider-kit\"\n\n/**\n * Family key used for the knowledge backend creds/ledger store path.\n *\n * The retrieval sibling of the `code-brain` family: the provider-kit\n * discovery convention (`@agentproto/adapter-knowledge-*`) points every\n * knowledge backend at its providing package.\n */\nexport const KNOWLEDGE_FAMILY = \"knowledge\" as const\n\n/** The single backend slug this adapter provides. */\nexport const FILES_BM25_SLUG = \"files\" as const\n\n/**\n * Static catalog of knowledge backends shipped by this adapter. The `files`\n * slug resolves from THIS package (`@agentproto/adapter-knowledge-files`) —\n * an in-process BM25 index over local workspace files, no embeddings, no\n * network, no credential.\n */\nexport const KNOWLEDGE_FILES_CATALOG: AdapterCatalog = [\n {\n slug: FILES_BM25_SLUG,\n name: \"files (BM25)\",\n description:\n \"Knowledge retrieval from local workspace files via an in-process \" +\n \"BM25 index. No embeddings, no network, no API key — works the \" +\n \"instant a workspace has files to index.\",\n packageName: \"@agentproto/adapter-knowledge-files\",\n hint: \"files · bm25\",\n },\n]\n","/**\n * provider-kit family wiring for the files knowledge backend.\n *\n * The studio home-grown `createEngineRegistry`-based knowledge registry is\n * NOT ported (it was the guild resolution layer, which stays studio-side per\n * the Ph4 plan). Instead the files backend registers as a provider-kit family\n * (`TInfo = KnowledgeFilesInfo`, `THandle = KnowledgeHandle extends\n * AdapterHandle`), reusing the exact consumer shape the code-brain adapter\n * established — catalog + resolver + a safe `info()` descriptor. Discovery\n * flows through the kit's `@agentproto/adapter-knowledge-*` naming convention.\n */\n\nimport type { IKnowledgeProvider } from \"@agentproto/knowledge-engine\"\nimport {\n makeAdapterResolver,\n type AdapterHandle,\n type AdapterResolver,\n} from \"@agentproto/provider-kit\"\nimport { FILES_BM25_SLUG, KNOWLEDGE_FILES_CATALOG } from \"./catalog.js\"\nimport { createStandaloneFilesAdapter } from \"./standalone.js\"\n\n/** Safe descriptor for a knowledge backend — NEVER carries a secret. */\nexport interface KnowledgeFilesInfo {\n readonly slug: string\n /** The retrieval engine this backend uses. */\n readonly engine: \"bm25\"\n readonly capabilities: {\n /** True when the backend performs dense/vector retrieval. */\n readonly vectorSearch: boolean\n /** True when the backend needs a credential to authenticate. */\n readonly needsCreds: boolean\n }\n}\n\n/** A resolved knowledge backend handle. */\nexport interface KnowledgeHandle extends AdapterHandle {\n /** Safe descriptor — NEVER a secret. */\n info(): KnowledgeFilesInfo\n /** Build the live {@link IKnowledgeProvider}. */\n provider(): IKnowledgeProvider\n}\n\n/**\n * Resolve a catalog slug to a concrete knowledge handle. Throws for unknown\n * slugs so the kit's resolver wrapper folds the miss to `null`. `provider()`\n * is lazy and caches a single standalone adapter — repeated calls share one\n * warm BM25 index rather than each cold-building their own.\n */\nexport function resolveKnowledgeBackend(slug: string): KnowledgeHandle {\n const catalogEntry = KNOWLEDGE_FILES_CATALOG.find(\n entry => entry.slug === slug\n )\n if (catalogEntry === undefined) {\n throw new Error(`unknown knowledge backend slug: ${slug}`)\n }\n\n switch (slug) {\n case FILES_BM25_SLUG: {\n // Lazily built + cached so every provider() call shares one warm index.\n let cached: IKnowledgeProvider | null = null\n const provider = (): IKnowledgeProvider =>\n (cached ??= createStandaloneFilesAdapter())\n return {\n slug,\n name: catalogEntry.name,\n description: catalogEntry.description,\n version: \"0.1.0\",\n // No creds, no external service — indexing the local workspace works\n // out of the box, so there is nothing to set up.\n requiresSetup: false,\n check: () => provider().healthCheck(),\n info() {\n return {\n slug,\n engine: \"bm25\",\n capabilities: { vectorSearch: false, needsCreds: false },\n }\n },\n provider,\n }\n }\n }\n\n throw new Error(`unhandled knowledge backend slug: ${slug}`)\n}\n\n/**\n * Build the knowledge resolver: resolves a catalog slug to a handle,\n * returning `null` when the slug is unknown (via the kit's wrapper).\n */\nexport function makeKnowledgeFilesResolver(): AdapterResolver<KnowledgeHandle> {\n return makeAdapterResolver<KnowledgeHandle>({\n load: async (slug: string): Promise<KnowledgeHandle> =>\n resolveKnowledgeBackend(slug),\n })\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/bm25.ts","../src/adapter.ts","../src/local-fs.ts","../src/env.ts","../src/standalone.ts","../src/catalog.ts","../src/handle.ts"],"names":["path"],"mappings":";;;;;;;;;;;;;;AAsBA,IAAM,EAAA,GAAK,GAAA;AACX,IAAM,CAAA,GAAI,IAAA;AACV,IAAM,aAAA,GAAgB,CAAA;AACtB,IAAM,aAAA,GAAgB,EAAA;AAKtB,IAAM,SAAA,uBAAgB,GAAA,CAAI;AAAA,EACxB,GAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,IAAA;AAAA,EACA,IAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,MAAA;AAAA,EACA,KAAA;AAAA,EACA,MAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,KAAA;AAAA,EACA,GAAA;AAAA,EACA,IAAA;AAAA,EACA,IAAA;AAAA,EACA,IAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,IAAA;AAAA,EACA,IAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,IAAA;AAAA,EACA,IAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,IAAA;AAAA,EACA,MAAA;AAAA,EACA,KAAA;AAAA,EACA,OAAA;AAAA,EACA,MAAA;AAAA,EACA,MAAA;AAAA,EACA,OAAA;AAAA,EACA,MAAA;AAAA,EACA,MAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,IAAA;AAAA,EACA,MAAA;AAAA,EACA,MAAA;AAAA,EACA,MAAA;AAAA,EACA,OAAA;AAAA,EACA,KAAA;AAAA,EACA,MAAA;AAAA,EACA,MAAA;AAAA,EACA,KAAA;AAAA,EACA;AACF,CAAC,CAAA;AAGM,SAAS,iBAAiB,OAAA,EAAyB;AACxD,EAAA,IAAI,CAAC,OAAA,CAAQ,UAAA,CAAW,KAAK,GAAG,OAAO,OAAA;AACvC,E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A,GAAoC,IAAA;AACxC,MAAA,MAAM,QAAA,GAAW,MACd,MAAA,KAAW,4BAAA,EAA6B;AAC3C,MAAA,OAAO;AAAA,QACL,IAAA;AAAA,QACA,MAAM,YAAA,CAAa,IAAA;AAAA,QACnB,aAAa,YAAA,CAAa,WAAA;AAAA,QAC1B,OAAA,EAAS,OAAA;AAAA;AAAA;AAAA,QAGT,aAAA,EAAe,KAAA;AAAA,QACf,KAAA,EAAO,MAAM,QAAA,EAAS,CAAE,WAAA,EAAY;AAAA,QACpC,IAAA,GAAO;AACL,UAAA,OAAO;AAAA,YACL,IAAA;AAAA,YACA,MAAA,EAAQ,MAAA;AAAA,YACR,YAAA,EAAc,EAAE,YAAA,EAAc,KAAA,EAAO,YAAY,KAAA;AAAM,WACzD;AAAA,QACF,CAAA;AAAA,QACA;AAAA,OACF;AAAA,IACF;AAAA;AAGF,EAAA,MAAM,IAAI,KAAA,CAAM,CAAA,kCAAA,EAAqC,IAAI,CAAA,CAAE,CAAA;AAC7D;AAMO,SAAS,0BAAA,GAA+D;AAC7E,EAAA,OAAO,mBAAA,CAAqC;AAAA,IAC1C,IAAA,EAAM,OAAO,IAAA,KACX,uBAAA,CAAwB,IAAI;AAAA,GAC/B,CAAA;AACH","file":"index.mjs","sourcesContent":["/**\n * In-process BM25 — a tiny, dependency-free implementation tuned for\n * corpus-sized data (hundreds to low thousands of markdown files).\n *\n * Memory shape: the index keeps only what scoring needs. Doc text is NOT\n * retained (a snippet is cut from the file at query time, top-K hits only),\n * and there is no per-doc `Map`: every doc's (term id, term frequency) pairs\n * live in two shared packed typed arrays, sliced per doc by an offset table,\n * with one vocabulary map (term -> id) for the whole index. Keeping the full\n * text plus a per-doc `tf` Map cost about 6.5x the corpus bytes on disk.\n *\n * Tokenizer: lowercase, split on non-alphanum, length 2-32, drop a small\n * English stopword list. Frontmatter is stripped before tokenization so\n * fence values like `schema: knowledge.entry/v1` don't pollute the\n * vocabulary.\n *\n * Scoring: standard BM25 with k1=1.5, b=0.75 — Lucene defaults. IDF\n * uses the \"BM25+1\" smoothing so terms appearing in every doc still\n * contribute a tiny positive score (avoids the negative-IDF foot-gun\n * for high-frequency terms).\n */\n\nconst K1 = 1.5\nconst B = 0.75\nconst MIN_TOKEN_LEN = 2\nconst MAX_TOKEN_LEN = 32\n\n// Short en stopword list — keeps the index lean without doing real NLP.\n// Domain stopwords (\"the company\", \"agentik\") could be added per-corpus\n// in a follow-up if the noise becomes meaningful.\nconst STOPWORDS = new Set([\n \"a\",\n \"an\",\n \"and\",\n \"are\",\n \"as\",\n \"at\",\n \"be\",\n \"but\",\n \"by\",\n \"for\",\n \"from\",\n \"has\",\n \"have\",\n \"he\",\n \"her\",\n \"his\",\n \"i\",\n \"if\",\n \"in\",\n \"is\",\n \"it\",\n \"its\",\n \"me\",\n \"my\",\n \"no\",\n \"not\",\n \"of\",\n \"on\",\n \"or\",\n \"she\",\n \"so\",\n \"that\",\n \"the\",\n \"their\",\n \"them\",\n \"then\",\n \"there\",\n \"they\",\n \"this\",\n \"to\",\n \"was\",\n \"we\",\n \"were\",\n \"what\",\n \"when\",\n \"which\",\n \"who\",\n \"will\",\n \"with\",\n \"you\",\n \"your\",\n])\n\n/** Strip YAML frontmatter (--- ... ---) from a doc body if present. */\nexport function stripFrontmatter(content: string): string {\n if (!content.startsWith(\"---\")) return content\n const end = content.indexOf(\"\\n---\", 3)\n if (end === -1) return content\n return content.slice(end + 4)\n}\n\nexport function tokenize(text: string): string[] {\n const out: string[] = []\n // Splitting on \\W+ would lose digits in alphanumeric tokens like\n // \"q3\"; use a unicode-aware non-word class instead.\n for (const raw of text.toLowerCase().split(/[^a-z0-9]+/)) {\n if (raw.length < MIN_TOKEN_LEN || raw.length > MAX_TOKEN_LEN) continue\n if (STOPWORDS.has(raw)) continue\n out.push(raw)\n }\n return out\n}\n\nexport interface Bm25Doc {\n /** Stable id — typically the workspace-relative path. */\n readonly id: string\n /** Token count — used for length-normalization in BM25. */\n readonly length: number\n}\n\nexport interface Bm25Index {\n /** Docs in build order; a doc's position is its index in the arrays below. */\n readonly docs: readonly Bm25Doc[]\n /** Term -> term id. One entry per distinct term across the whole index. */\n readonly vocab: ReadonlyMap<string, number>\n /** Number of docs containing each term (by term id), used in IDF. */\n readonly df: Uint32Array\n /** Doc `i`'s postings span `[offsets[i], offsets[i + 1])` in\n * {@link termIds} / {@link tfs}. Length is `docs.length + 1`. */\n readonly offsets: Uint32Array\n /** Term ids, ascending within each doc's span. */\n readonly termIds: Uint32Array\n /** Term frequency of the matching {@link termIds} entry. */\n readonly tfs: Uint32Array\n /** Average document length across the index, in tokens. */\n readonly avgDocLength: number\n}\n\nexport interface BuildDocInput {\n readonly id: string\n readonly content: string\n}\n\n/** Growable `Uint32Array` (capacity doubling), trimmed on {@link take}. */\nclass U32Buffer {\n private buf: Uint32Array\n length = 0\n\n constructor(capacity = 1024) {\n this.buf = new Uint32Array(capacity)\n }\n\n push(value: number): void {\n if (this.length === this.buf.length) {\n const next = new Uint32Array(this.buf.length * 2)\n next.set(this.buf)\n this.buf = next\n }\n this.buf[this.length++] = value\n }\n\n get(i: number): number {\n return this.buf[i]!\n }\n\n set(i: number, value: number): void {\n this.buf[i] = value\n }\n\n take(): Uint32Array {\n return this.buf.slice(0, this.length)\n }\n}\n\n/**\n * A copy of `term` that shares no storage with the text it was cut from.\n * `split()` may hand back a slice that points into the lowercased doc, and a\n * vocabulary key that is such a slice keeps that whole doc alive.\n */\nfunction ownString(term: string): string {\n return JSON.parse(JSON.stringify(term)) as string\n}\n\n/**\n * Incremental index builder: {@link add} one doc at a time (the caller can\n * drop the doc's text right after), then {@link finish}. Docs keep the order\n * they were added in, which is also the tie-break order of {@link score}.\n */\nexport class Bm25IndexBuilder {\n private readonly docs: Bm25Doc[] = []\n private readonly vocab = new Map<string, number>()\n private readonly df = new U32Buffer()\n private readonly offsets = new U32Buffer()\n private readonly termIds = new U32Buffer(64 * 1024)\n private readonly tfs = new U32Buffer(64 * 1024)\n private totalLength = 0\n\n constructor() {\n this.offsets.push(0)\n }\n\n get docCount(): number {\n return this.docs.length\n }\n\n add(id: string, content: string): void {\n const tokens = tokenize(stripFrontmatter(content))\n const tf = new Map<number, number>()\n for (const tok of tokens) {\n let termId = this.vocab.get(tok)\n if (termId === undefined) {\n termId = this.vocab.size\n this.vocab.set(ownString(tok), termId)\n this.df.push(0)\n }\n tf.set(termId, (tf.get(termId) ?? 0) + 1)\n }\n const ids = [...tf.keys()].sort((a, b) => a - b)\n for (const termId of ids) {\n this.termIds.push(termId)\n this.tfs.push(tf.get(termId)!)\n this.df.set(termId, this.df.get(termId) + 1)\n }\n this.offsets.push(this.termIds.length)\n this.docs.push({ id, length: tokens.length })\n this.totalLength += tokens.length\n }\n\n finish(): Bm25Index {\n const avgDocLength =\n this.docs.length === 0 ? 0 : this.totalLength / this.docs.length\n return {\n docs: this.docs,\n vocab: this.vocab,\n df: this.df.take(),\n offsets: this.offsets.take(),\n termIds: this.termIds.take(),\n tfs: this.tfs.take(),\n avgDocLength,\n }\n }\n}\n\nexport function buildIndex(inputs: readonly BuildDocInput[]): Bm25Index {\n const builder = new Bm25IndexBuilder()\n for (const input of inputs) builder.add(input.id, input.content)\n return builder.finish()\n}\n\n/**\n * Async, event-loop-friendly variant of {@link buildIndex}. Identical output,\n * but yields to the macrotask queue every `yieldEvery` docs.\n *\n * Why this matters (the adapter's own build loop yields the same way): a caller\n * that reads docs from an in-memory/cached fs sees the awaited reads resolve\n * as MICROTASKS, which never hand control back to the event loop. Without an\n * explicit yield, the tokenization of every doc runs as one uninterruptible\n * synchronous chain —\n * which (a) freezes every concurrent recall on this single-process, multi-tenant\n * instance for the full build and (b) defeats `ensureIndex`'s non-blocking\n * `setTimeout` deadline (the timer can't fire while the loop is blocked). The\n * `setImmediate` yield lets sibling turns progress and the deadline fire during a\n * cold build.\n */\nexport async function buildIndexYielding(\n inputs: readonly BuildDocInput[],\n yieldEvery = 50\n): Promise<Bm25Index> {\n const builder = new Bm25IndexBuilder()\n let i = 0\n for (const input of inputs) {\n if (i++ % yieldEvery === 0)\n await new Promise<void>(resolve => setImmediate(resolve))\n builder.add(input.id, input.content)\n }\n return builder.finish()\n}\n\n/** Docs containing `term` (0 when the term is not in the index). */\nexport function documentFrequency(index: Bm25Index, term: string): number {\n const termId = index.vocab.get(term)\n return termId === undefined ? 0 : index.df[termId]!\n}\n\n/** Frequency of `termId` in doc `docIndex` (binary search of its span). */\nfunction termFrequency(\n index: Bm25Index,\n docIndex: number,\n termId: number\n): number {\n let lo = index.offsets[docIndex]!\n let hi = index.offsets[docIndex + 1]! - 1\n while (lo <= hi) {\n const mid = (lo + hi) >>> 1\n const at = index.termIds[mid]!\n if (at === termId) return index.tfs[mid]!\n if (at < termId) lo = mid + 1\n else hi = mid - 1\n }\n return 0\n}\n\nexport interface ScoredHit {\n readonly doc: Bm25Doc\n readonly score: number\n}\n\n/**\n * Score every doc against the query tokens, return top-k.\n * Docs with score <= minScore (default 0: no terms matched) are dropped.\n * The index holds no text: cut a snippet with {@link makeSnippet} from the\n * doc's content once the top-k is known.\n */\nexport function score(\n index: Bm25Index,\n queryTokens: readonly string[],\n opts: { readonly topK?: number; readonly minScore?: number } = {}\n): ScoredHit[] {\n if (queryTokens.length === 0 || index.docs.length === 0) return []\n const topK = opts.topK ?? 10\n const minScore = opts.minScore ?? 0\n const N = index.docs.length\n const avgDocLength = index.avgDocLength === 0 ? 1 : index.avgDocLength\n // Resolve each query token once. Unknown terms match no doc and add\n // nothing; duplicates stay, so a repeated token counts again.\n const terms: Array<{ termId: number; idf: number }> = []\n for (const tok of queryTokens) {\n const termId = index.vocab.get(tok)\n if (termId === undefined) continue\n const n = index.df[termId]!\n // BM25 IDF with +1 smoothing — see \"Improvements to BM25 and\n // language models examined\" (Lv & Zhai, 2011) for the rationale.\n terms.push({ termId, idf: Math.log((N - n + 0.5) / (n + 0.5) + 1) })\n }\n const out: ScoredHit[] = []\n\n for (let i = 0; i < N; i++) {\n const doc = index.docs[i]!\n let s = 0\n for (const { termId, idf } of terms) {\n const f = termFrequency(index, i, termId)\n if (!f) continue\n const denom = f + K1 * (1 - B + (B * doc.length) / avgDocLength)\n s += idf * ((f * (K1 + 1)) / denom)\n }\n if (s <= minScore) continue\n out.push({ doc, score: s })\n }\n out.sort((a, b) => b.score - a.score)\n return out.slice(0, topK)\n}\n\n/**\n * Pull a ~300-char window around the first matching query token in\n * the doc body. Falls back to the doc's head when no token matches in\n * the surfaced text (e.g. matches were all in the stripped frontmatter).\n * `start` / `end` are char offsets in `text` (the whole file).\n */\nexport function makeSnippet(\n text: string,\n queryTokens: readonly string[]\n): { start: number; end: number; text: string } {\n const body = stripFrontmatter(text)\n const offset = text.length - body.length\n const lower = body.toLowerCase()\n let firstAt = -1\n for (const tok of queryTokens) {\n const idx = lower.indexOf(tok)\n if (idx !== -1 && (firstAt === -1 || idx < firstAt)) firstAt = idx\n }\n const around = 150\n const start = Math.max(0, (firstAt === -1 ? 0 : firstAt) - around)\n const end = Math.min(body.length, start + 300)\n return {\n start: offset + start,\n end: offset + end,\n text: body.slice(start, end),\n }\n}\n","/**\n * FilesKnowledgeAdapter — the no-runtime, no-embedding KB engine.\n *\n * Indexes workspace files in process with BM25. Zero setup: works the\n * instant a guild has a system workspace, no E2B sandbox, no API key,\n * no cold start. Best suited as the DEFAULT corpus backing where the\n * AIP-10 entries already live as markdown files — the entries ARE the\n * index, no separate vector store to keep in sync.\n *\n * Index lifecycle: built lazily on first query, cached for 30s, also\n * invalidated explicitly by `ingest()`. External edits (a user typing\n * in the workspace UI) become visible on the next rebuild — for\n * second-precision freshness, hosts can wire fs-watch into the\n * `invalidate()` method.\n *\n * Lifted VERBATIM from the studio integration package\n * (`packages/integration/knowledge/src/providers/files/adapter.ts`) — the\n * class already carried no `@guilde/@simone/@agstudio` edge (it consumes an\n * injected `FsPort` and the vendor-neutral `IKnowledgeProvider` contract), so\n * it re-homes as-is. The ONLY change is the two import paths: the contract +\n * data types now come from `@agentproto/knowledge-engine` (was\n * `../base-knowledge.provider` / `../../types/knowledge.types`). The guild-side\n * `KnowledgeEngineDescriptor` (studio `descriptor.ts`) is NOT lifted — it\n * belonged to the guild resolution layer; this package registers as a\n * provider-kit family instead (see `handle.ts`).\n */\n\nimport type { FsPort } from \"@agentproto/corpus\"\nimport {\n KnowledgeNotSupportedError,\n type IKnowledgeProvider,\n type KnowledgeCapabilities,\n type KnowledgeHit,\n type KnowledgeIngestInput,\n type KnowledgeQuery,\n type KnowledgeQueryResult,\n type KnowledgeSource,\n type ListSourcesFilter,\n type KnowledgeProvenance,\n} from \"@agentproto/knowledge-engine\"\nimport {\n Bm25IndexBuilder,\n makeSnippet,\n score as scoreBm25,\n tokenize,\n type Bm25Index,\n} from \"./bm25.js\"\n\nexport const FILES_ENGINE_ID = \"files\" as const\n\nconst INDEXED_EXTENSIONS = [\n \".md\",\n \".markdown\",\n \".txt\",\n \".yaml\",\n \".yml\",\n \".json\",\n]\n// Corpus content is immutable between `promote_candidate` / `rebuild_lens`\n// writes. Both code-paths call either `invalidate()` (via ingest/delete) or\n// drop the whole provider instance (via `invalidateKnowledgeProvider`), so\n// time-based expiry is never needed for correctness — it only forces a full\n// Supabase Storage re-scan on every turn after 30 s, causing 37-52s latency.\n// Use a permanent cache: the index is rebuilt only when the adapter explicitly\n// calls `invalidate()`, or when a new instance is created after a provider\n// cache eviction.\nconst CACHE_TTL_MS = Number.POSITIVE_INFINITY\n\n/**\n * Max concurrent file reads while (re)building the index. Backings like\n * Supabase Storage serve each `readFile` as its own REST round-trip with\n * an internal `AbortSignal.timeout(4000)`; firing all ~N reads at once\n * saturates the event loop and connection pool so the timers expire\n * before the responses land (observed: 426 TimeoutErrors on a ~264-file\n * corpus). A small ceiling keeps each read inside its own budget.\n */\nconst INDEX_READ_CONCURRENCY = 10\n\n/**\n * Max ms a query waits for an in-progress BM25 build before giving up and\n * returning empty results. The build continues in background — the next query\n * on the same instance will find the index ready (or still building if the\n * corpus is very large). Without this cap, cold-start builds on Supabase\n * Storage (50-150 s for large corpora) block every turn on every new Cloud\n * Run instance, which has no cross-instance shared cache.\n */\nconst INDEX_QUERY_TIMEOUT_MS = 4_000\n\n/** Docs read, tokenized, and folded into the index per step of a build, and\n * the interval at which the build yields to the event loop (see\n * `buildIndexYielding` in bm25.ts for why the yield matters). Only one\n * step's text is alive at a time. */\nconst INDEX_BUILD_STEP = 50\n\n/**\n * Default ceiling on the files a brain may index in process. Above it the\n * engine refuses to build and every query fails with\n * {@link FilesIndexTooLargeError}. Measured on 5.8 KB transcript-shaped docs:\n * the lean index costs about 2.4 KB of heap per doc where the old one (text\n * plus a per-doc `tf` Map) cost about 20 KB. Real brains measured 40 KB per doc\n * on the old shape, so budget about 5 KB per doc: 100,000 docs is about\n * 500 MB resident at worst. That covers the 47k and 91k doc brains seen in the\n * field and refuses the 223k one, which wants a real engine (qdrant,\n * gbrain-doc) rather than a whole-corpus scan per query.\n */\nexport const DEFAULT_MAX_INDEX_DOCS = 100_000\n\n/**\n * Thrown by `query()` / `listSources()` / `getSource()` when the brain holds\n * more indexable files than the configured ceiling. The name is the stable\n * signal (`err.name === \"FilesIndexTooLargeError\"`) so a second copy of this\n * package in the tree still matches.\n */\nexport class FilesIndexTooLargeError extends Error {\n readonly docCount: number\n readonly maxDocs: number\n\n constructor(label: string, docCount: number, maxDocs: number) {\n super(\n `files engine (${label}): refusing to build the in-process index: ` +\n `${docCount} indexable files exceed the ceiling of ${maxDocs}. ` +\n `Raise maxIndexDocs, or back this brain with a real search engine.`\n )\n this.name = \"FilesIndexTooLargeError\"\n this.docCount = docCount\n this.maxDocs = maxDocs\n }\n}\n\n/**\n * One index build at a time across every adapter in the process. A build\n * peaks at its index plus one step of file text, so serializing builds keeps\n * the peak to the largest single brain instead of the sum of all of them\n * (a federated query used to build every brain at once).\n */\nlet buildGate: Promise<unknown> = Promise.resolve()\nlet buildsRunning = 0\nfunction runExclusiveBuild<T>(fn: () => Promise<T>): Promise<T> {\n const run = buildGate.then(async () => {\n buildsRunning++\n try {\n return await fn()\n } finally {\n buildsRunning--\n }\n })\n buildGate = run.catch(() => undefined)\n return run\n}\n\n/** Index builds running right now, process wide (0 or 1). For tests. */\nexport function filesIndexBuildsRunning(): number {\n return buildsRunning\n}\n\nexport const FILES_CAPABILITIES: KnowledgeCapabilities = Object.freeze({\n vectorSearch: false,\n graphTraversal: false,\n hybridSearch: false,\n multiModal: false,\n streaming: false,\n // BM25 returns ranked hits with file path + byte span — usable as\n // citations even though there's no vector concept.\n citations: true,\n // Chunk size matters for backings that split — files engine indexes\n // whole files so this is an informational ceiling.\n maxChunkBytes: 64 * 1024,\n})\n\nexport interface FilesAdapterConfig {\n /** Workspace-relative root the engine indexes (walks recursively). */\n readonly workspacePath: string\n}\n\nexport interface FilesKnowledgeAdapterOptions extends FilesAdapterConfig {\n /** FsPort scoped to the workspace the engine lives in. */\n readonly fs: FsPort\n /** Name used in log lines and errors (e.g. the brain's workspace slug).\n * Defaults to `workspacePath`. */\n readonly label?: string\n /** Refuse to build the index above this many indexable files. Defaults to\n * {@link DEFAULT_MAX_INDEX_DOCS}. */\n readonly maxIndexDocs?: number\n /** How long `query()` waits for a cold build before answering with no\n * hits (the build keeps going). Defaults to 4 s. */\n readonly queryTimeoutMs?: number\n /** Sink for the one-line build / timeout / refusal logs. Defaults to\n * `console.log`. */\n readonly log?: (line: string) => void\n}\n\nexport class FilesKnowledgeAdapter implements IKnowledgeProvider {\n readonly id = FILES_ENGINE_ID\n readonly capabilities = FILES_CAPABILITIES\n\n private readonly fs: FsPort\n private readonly workspacePath: string\n private readonly label: string\n private readonly maxIndexDocs: number\n private readonly queryTimeoutMs: number\n private readonly log: (line: string) => void\n private cachedIndex: Bm25Index | null = null\n private cachedAt = 0\n // In-flight build promise: concurrent turns that arrive while the index is\n // still being built (cachedIndex === null) coalesce onto this promise instead\n // of each kicking off a redundant 40-50s Supabase Storage re-scan.\n private buildInFlight: Promise<Bm25Index> | null = null\n private buildStartedAt = 0\n // A refused build (over the ceiling) is remembered until the next\n // invalidate(), so repeated queries do not re-walk a huge brain.\n private refusal: FilesIndexTooLargeError | null = null\n\n constructor(opts: FilesKnowledgeAdapterOptions) {\n this.fs = opts.fs\n this.workspacePath = opts.workspacePath\n this.label = opts.label ?? opts.workspacePath\n this.maxIndexDocs =\n typeof opts.maxIndexDocs === \"number\" && opts.maxIndexDocs > 0\n ? opts.maxIndexDocs\n : DEFAULT_MAX_INDEX_DOCS\n this.queryTimeoutMs = opts.queryTimeoutMs ?? INDEX_QUERY_TIMEOUT_MS\n this.log = opts.log ?? (line => console.log(line))\n }\n\n async ingest(input: KnowledgeIngestInput): Promise<KnowledgeSource> {\n // The corpus indexer pushes pre-chunked entries here; the entry .md\n // file is already written by CorpusPromoter, so all we need to do\n // is invalidate the index and return a synthetic source. Skipping\n // the write avoids ghost `sources/chunk-*.md` files duplicating\n // every entry's body.\n const corpusBlock = readCorpusMeta(input.metadata)\n if (corpusBlock?.entrySlug) {\n this.invalidate()\n return {\n id: `${corpusBlock.entrySlug}#${corpusBlock.chunkIndex ?? 0}`,\n kind: \"text\",\n uri: corpusBlock.entryPath ?? input.uri,\n title: input.title,\n metadata: input.metadata ?? {},\n bytes: byteLength(input.content),\n status: \"ready\",\n indexedAt: new Date(),\n }\n }\n\n if (input.kind === \"text\") {\n const sourceId = stableSlug(input.uri)\n const dest = `${this.workspacePath}/sources/${sourceId}.md`\n const content = decodeContent(input.content) ?? \"\"\n await this.fs.writeFile(dest, content)\n this.invalidate()\n return {\n id: sourceId,\n kind: \"text\",\n uri: input.uri,\n title: input.title,\n metadata: input.metadata ?? {},\n bytes: byteLength(content),\n status: \"ready\",\n indexedAt: new Date(),\n }\n }\n\n if (input.kind === \"url\") {\n const res = await fetch(input.uri)\n if (!res.ok) {\n throw new Error(\n `files engine: failed to fetch ${input.uri}: ${res.status} ${res.statusText}`\n )\n }\n const text = await res.text()\n const sourceId = stableSlug(input.uri)\n const dest = `${this.workspacePath}/sources/${sourceId}.txt`\n await this.fs.writeFile(dest, text)\n this.invalidate()\n return {\n id: sourceId,\n kind: \"url\",\n uri: input.uri,\n title: input.title,\n metadata: input.metadata ?? {},\n bytes: byteLength(text),\n status: \"ready\",\n indexedAt: new Date(),\n }\n }\n\n throw new Error(\n `files engine: ingest kind=\"${input.kind}\" not supported. ` +\n `Pass kind=\"text\" with inline content, or kind=\"url\" for the engine to fetch.`\n )\n }\n\n async query(q: KnowledgeQuery): Promise<KnowledgeQueryResult> {\n const start = Date.now()\n // Non-blocking: if the BM25 index isn't ready within INDEX_QUERY_TIMEOUT_MS,\n // return empty results and let the build continue in background. The next\n // query on the same instance will find the index warm. This prevents a cold\n // Supabase Storage rebuild (50-150 s on large corpora) from blocking every\n // turn on fresh Cloud Run instances.\n const index = await this.ensureIndex(this.queryTimeoutMs)\n const tokens = tokenize(q.query)\n if (tokens.length === 0) {\n return {\n hits: Object.freeze([]),\n tookMs: Date.now() - start,\n engine: this.id,\n modeUsed: \"vector\",\n }\n }\n const scored = scoreBm25(index, tokens, {\n topK: q.topK,\n minScore: q.minScore,\n })\n // The index holds no text: read the top-K files back for their snippet\n // and frontmatter. A file that vanished since the build yields an empty\n // snippet rather than failing the whole query.\n const texts = await mapWithConcurrency(\n scored,\n INDEX_READ_CONCURRENCY,\n s => this.readText(s.doc.id)\n )\n const hits: KnowledgeHit[] = scored.map((s, i) => {\n const text = texts[i]!\n const meta = parseFrontmatterMetadata(text)\n const snippet = makeSnippet(text, tokens)\n return {\n sourceId: s.doc.id,\n chunkId: s.doc.id,\n text: snippet.text,\n score: s.score,\n // span is in original-file bytes; matches engine \"citations\" capability.\n span: { start: snippet.start, end: snippet.end },\n metadata: meta,\n }\n })\n return {\n hits: Object.freeze(hits),\n tookMs: Date.now() - start,\n engine: this.id,\n // BM25 isn't really \"vector\" — the union doesn't have a \"keyword\"\n // option. Report \"vector\" as the closest existing label until the\n // mode union widens.\n modeUsed: \"vector\",\n }\n }\n\n async listSources(\n filter?: ListSourcesFilter\n ): Promise<readonly KnowledgeSource[]> {\n const index = await this.ensureIndex()\n // Every source is kind \"file\" + status \"ready\": filter before reading.\n if (filter?.kind && filter.kind !== \"file\") return Object.freeze([])\n if (filter?.status && filter.status !== \"ready\") return Object.freeze([])\n const out: KnowledgeSource[] = []\n for (let i = 0; i < index.docs.length; i += INDEX_BUILD_STEP) {\n const step = index.docs.slice(i, i + INDEX_BUILD_STEP)\n const texts = await mapWithConcurrency(\n step,\n INDEX_READ_CONCURRENCY,\n doc => this.readText(doc.id)\n )\n step.forEach((doc, j) => out.push(fileSource(doc.id, texts[j]!)))\n }\n return Object.freeze(out)\n }\n\n async getSource(id: string): Promise<KnowledgeSource | null> {\n const index = await this.ensureIndex()\n const doc = index.docs.find(d => d.id === id)\n if (!doc) return null\n return fileSource(doc.id, await this.readText(doc.id))\n }\n\n async deleteSource(id: string): Promise<void> {\n // The path IS the source — deletion means removing the file. The\n // adapter intentionally writes through the same FsPort it reads\n // from, so external editors and the engine stay in sync.\n if (await this.fs.exists(id)) {\n // FsPort doesn't expose `unlink`; write empty to drop content\n // without breaking the contract. Hosts that need true unlink\n // wire it via their own admin path.\n await this.fs.writeFile(id, \"\")\n }\n this.invalidate()\n }\n\n async supersede(_id: string, _by?: string): Promise<void> {\n throw new KnowledgeNotSupportedError(\n this.id,\n \"supersede\",\n \"plain files carry no lifecycle status; use the corpus adapter over an AIP-10 workspace\",\n )\n }\n\n async explain(id: string): Promise<KnowledgeProvenance | null> {\n const source = await this.getSource(id)\n if (!source) return null\n // A file's provenance is its path and own frontmatter; there is no\n // upstream-derivation or audit chain at this layer.\n return {\n sourceId: source.id,\n derivedFrom: [],\n metadata: { uri: source.uri, ...source.metadata },\n }\n }\n\n async healthCheck(): Promise<boolean> {\n try {\n // Health = the root path is reachable. An empty workspace is\n // healthy (zero hits is a valid query result).\n return await this.fs.exists(this.workspacePath)\n } catch {\n return false\n }\n }\n\n async dispose(): Promise<void> {\n this.cachedIndex = null\n }\n\n /** Drop the cached BM25 index — next query rebuilds. */\n private invalidate(): void {\n this.cachedIndex = null\n this.cachedAt = 0\n this.refusal = null\n // Do NOT clear buildInFlight: an in-flight build that started before the\n // invalidate will still store its result, which is immediately stale. The\n // next ensureIndex() call after it resolves will see cachedIndex !== null\n // but cachedAt = 0, which with POSITIVE_INFINITY TTL still passes. This is\n // acceptable: the stale index is at most one build's worth of lag and is\n // replaced on the next explicit write that calls invalidate() + triggers a\n // new query. Clearing buildInFlight would just cause more redundant builds.\n }\n\n private async ensureIndex(timeoutMs?: number): Promise<Bm25Index> {\n if (this.cachedIndex && Date.now() - this.cachedAt < CACHE_TTL_MS) {\n return this.cachedIndex\n }\n if (this.refusal) throw this.refusal\n // Coalesce concurrent callers onto one in-flight build. Without this,\n // two turns arriving before the first build completes both see\n // cachedIndex===null and each kick off a full 40-50s Supabase Storage\n // re-scan — wasting resources and keeping both turns slow.\n if (!this.buildInFlight) {\n this.buildStartedAt = Date.now()\n const build = runExclusiveBuild(() => this._buildIndex()).finally(() => {\n this.buildInFlight = null\n })\n // A caller that gave up at its deadline no longer awaits the build;\n // keep a failure from surfacing as an unhandled rejection.\n build.catch(() => undefined)\n this.buildInFlight = build\n }\n if (timeoutMs !== undefined) {\n // Non-blocking mode: race the build against a deadline. If the build\n // wins, great — the index is ready. If the deadline fires first, return\n // an empty index so the turn can proceed without knowledge context. The\n // build continues in background; the next call to ensureIndex() will\n // either find the cache populated (build done) or coalesce onto the\n // still-in-flight promise again.\n const build = this.buildInFlight\n let timer: ReturnType<typeof setTimeout> | undefined\n const deadline = new Promise<null>(resolve => {\n timer = setTimeout(() => resolve(null), timeoutMs)\n })\n const winner = await Promise.race([build, deadline]).finally(() =>\n clearTimeout(timer)\n )\n if (winner) return winner\n this.log(\n `[knowledge-files:${this.label}] query timed out after ${timeoutMs} ms ` +\n `waiting for the index build (running for ${Date.now() - this.buildStartedAt} ms); ` +\n `returning no hits, the build keeps going`\n )\n return EMPTY_INDEX\n }\n return this.buildInFlight\n }\n\n private async _buildIndex(): Promise<Bm25Index> {\n const start = Date.now()\n const heapBefore = heapUsedMb()\n const allPaths = await this.fs.walk(this.workspacePath)\n const candidates = allPaths.filter(p =>\n INDEXED_EXTENSIONS.some(ext => p.toLowerCase().endsWith(ext))\n )\n if (candidates.length > this.maxIndexDocs) {\n const refusal = new FilesIndexTooLargeError(\n this.label,\n candidates.length,\n this.maxIndexDocs\n )\n this.refusal = refusal\n this.log(\n `[knowledge-files:${this.label}] index build refused: ` +\n `${candidates.length} indexable files exceed the ceiling of ${this.maxIndexDocs}`\n )\n throw refusal\n }\n // Read, tokenize, and fold in one step at a time, in walk order, so only\n // one step's text is ever alive (the old build held every file's text,\n // then kept it in the index).\n const builder = new Bm25IndexBuilder()\n let bytesRead = 0\n for (let i = 0; i < candidates.length; i += INDEX_BUILD_STEP) {\n await new Promise<void>(resolve => setImmediate(resolve))\n const step = candidates.slice(i, i + INDEX_BUILD_STEP)\n const texts = await mapWithConcurrency(\n step,\n INDEX_READ_CONCURRENCY,\n path => this.fs.readFile(path).catch(() => \"\")\n )\n step.forEach((path, j) => {\n const content = texts[j]!\n if (content.length === 0) return\n bytesRead += byteLength(content)\n builder.add(path, content)\n })\n }\n const index = builder.finish()\n this.cachedIndex = index\n this.cachedAt = Date.now()\n this.log(\n `[knowledge-files:${this.label}] index built: ${index.docs.length} docs, ` +\n `${bytesRead} bytes read, ${Date.now() - start} ms, ` +\n `heapUsed ${heapBefore} MB -> ${heapUsedMb()} MB`\n )\n return index\n }\n\n /** A doc's current text, or \"\" when it can no longer be read. */\n private readText(id: string): Promise<string> {\n return this.fs.readFile(id).catch(() => \"\")\n }\n}\n\n// ── helpers ──────────────────────────────────────────────────────────\n\nconst EMPTY_INDEX = new Bm25IndexBuilder().finish()\n\n/** `process.memoryUsage().heapUsed` in MB, or \"?\" off Node. */\nfunction heapUsedMb(): number | \"?\" {\n if (typeof process === \"undefined\" || !process.memoryUsage) return \"?\"\n return Math.round(process.memoryUsage().heapUsed / (1024 * 1024))\n}\n\n/** The {@link KnowledgeSource} for an indexed file and its current text. */\nfunction fileSource(id: string, text: string): KnowledgeSource {\n const meta = parseFrontmatterMetadata(text)\n return {\n id,\n kind: \"file\",\n uri: id,\n title: typeof meta.title === \"string\" ? meta.title : undefined,\n bytes: byteLength(text),\n status: \"ready\",\n metadata: meta,\n }\n}\n\n/**\n * Map `items` through `fn` with at most `limit` calls in flight at once,\n * preserving input order in the result. A fixed pool of workers drains a\n * shared cursor — no batch barriers, so a slow read never stalls the\n * whole pool. Dependency-free stand-in for p-limit.\n */\nasync function mapWithConcurrency<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T, index: number) => Promise<R>\n): Promise<R[]> {\n const results = new Array<R>(items.length)\n let cursor = 0\n const workers = Array.from(\n { length: Math.max(1, Math.min(limit, items.length)) },\n async () => {\n while (cursor < items.length) {\n const i = cursor++\n results[i] = await fn(items[i]!, i)\n }\n }\n )\n await Promise.all(workers)\n return results\n}\n\nfunction decodeContent(content: unknown): string | undefined {\n if (typeof content === \"string\") return content\n if (content instanceof Uint8Array) return new TextDecoder().decode(content)\n return undefined\n}\n\nfunction byteLength(content: unknown): number {\n if (typeof content === \"string\")\n return new TextEncoder().encode(content).byteLength\n if (content instanceof Uint8Array) return content.byteLength\n return 0\n}\n\n/** Stable kebab-case id derived from a uri-ish input. */\nfunction stableSlug(uri: string): string {\n const base = uri.replace(/^[a-z]+:\\/+/, \"\").replace(/[/\\\\]+/g, \"-\")\n const slug = base\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 96)\n return slug || `source-${Date.now().toString(36)}`\n}\n\n/**\n * Surface frontmatter as the hit's metadata so corpus-side hydration\n * (which keys on `metadata.entrySlug`) round-trips correctly when this\n * engine backs a corpus. Frontmatter is also surfaced for standalone\n * use so callers can read entry-level fields like `title`, `tags`.\n *\n * Returns `{}` when no frontmatter is present — never throws.\n */\nfunction parseFrontmatterMetadata(\n content: string\n): Readonly<Record<string, unknown>> {\n if (!content.startsWith(\"---\")) return Object.freeze({})\n const end = content.indexOf(\"\\n---\", 3)\n if (end === -1) return Object.freeze({})\n const block = content.slice(4, end).trim()\n const out: Record<string, unknown> = {}\n // Minimal YAML — handle `key: value` and `key: \"value\"` at top level.\n // Nested objects are rare in entry frontmatter that drives retrieval;\n // hosts that need full parsing can wire gray-matter outside the\n // adapter and re-parse.\n for (const line of block.split(\"\\n\")) {\n const m = line.match(/^([a-zA-Z0-9_.-]+)\\s*:\\s*(.*)$/)\n if (!m) continue\n const key = m[1]!\n let value: unknown = m[2]!.trim()\n if (typeof value === \"string\") {\n if (value.startsWith('\"') && value.endsWith('\"'))\n value = value.slice(1, -1)\n else if (value.startsWith(\"'\") && value.endsWith(\"'\"))\n value = value.slice(1, -1)\n }\n out[key] = value\n }\n // Mirror the slug key into `entrySlug` so corpus-hydration finds it\n // without a per-engine adapter — corpus's `hydrateHit` keys on\n // `metadata.entrySlug` (see corpus/hydrate.ts).\n if (typeof out.slug === \"string\" && !(\"entrySlug\" in out)) {\n out.entrySlug = out.slug\n }\n return Object.freeze(out)\n}\n\nfunction readCorpusMeta(\n metadata: Readonly<Record<string, unknown>> | undefined\n): { entrySlug?: string; entryPath?: string; chunkIndex?: number } | undefined {\n if (!metadata) return undefined\n const corpus = (metadata as { corpus?: unknown }).corpus\n if (!corpus || typeof corpus !== \"object\") return undefined\n const block = corpus as Record<string, unknown>\n return {\n entrySlug:\n typeof block.entrySlug === \"string\" ? block.entrySlug : undefined,\n entryPath:\n typeof block.entryPath === \"string\" ? block.entryPath : undefined,\n chunkIndex:\n typeof block.chunkIndex === \"number\" ? block.chunkIndex : undefined,\n }\n}\n","/**\n * LocalFs — a `FsPort` (from `@agentproto/corpus`) backed by node:fs.\n *\n * The studio files provider never shipped its own `FsPort`: the guild host\n * resolved one (`resolveWorkspaceFs`) and injected it. agentproto-side that\n * host is gone (the guild registry stays studio-side per the Ph4 plan), so\n * this package ships the minimal local backing that lets the adapter run\n * standalone — the same role the code-brain adapter's own gbrain client plays.\n *\n * Mirrors `@agentproto/corpus-cli`'s `NodeFsAdapter` (that class lives in a\n * `-cli` package; a library adapter must not take a `-cli` edge, so the small\n * node:fs surface the files engine needs is re-implemented here). Paths are\n * workspace-relative and resolved under `root`; `resolve()` refuses to climb\n * out of it. `walk()` returns workspace-relative paths (readable back through\n * `readFile`) and skips hidden segments, exactly as `FsPort` specifies. `lock`\n * is a single-process no-op — this backing is local CLI, which the port\n * contract explicitly permits.\n */\n\nimport { randomBytes } from \"node:crypto\"\nimport {\n appendFile,\n mkdir,\n readFile,\n readdir,\n rename,\n stat,\n writeFile,\n} from \"node:fs/promises\"\nimport path from \"node:path\"\nimport type { FsLockHandle, FsPort, FsStat } from \"@agentproto/corpus\"\n\nexport interface LocalFsOptions {\n /**\n * Absolute path to the workspace root. Every `FsPort` path is resolved\n * relative to this — the adapter never sees a host filesystem path.\n */\n readonly root: string\n}\n\nexport class LocalFs implements FsPort {\n private readonly root: string\n\n constructor(opts: LocalFsOptions) {\n this.root = opts.root\n }\n\n async exists(p: string): Promise<boolean> {\n try {\n await stat(this.resolve(p))\n return true\n } catch {\n return false\n }\n }\n\n async readFile(p: string): Promise<string> {\n return await readFile(this.resolve(p), \"utf8\")\n }\n\n /**\n * Atomic write: write to `${target}.tmp-{nonce}`, then rename. Rename is\n * atomic on the same filesystem. Creates parent dirs as needed.\n */\n async writeFile(p: string, content: string): Promise<void> {\n const target = this.resolve(p)\n await mkdir(path.dirname(target), { recursive: true })\n const tmp = `${target}.tmp-${randomBytes(8).toString(\"hex\")}`\n await writeFile(tmp, content, \"utf8\")\n await rename(tmp, target)\n }\n\n async appendFile(p: string, content: string): Promise<void> {\n const target = this.resolve(p)\n await mkdir(path.dirname(target), { recursive: true })\n await appendFile(target, content, \"utf8\")\n }\n\n async readdir(p: string): Promise<readonly string[]> {\n return await readdir(this.resolve(p))\n }\n\n async walk(p: string): Promise<readonly string[]> {\n const out: string[] = []\n const start = this.resolve(p)\n const visit = async (dir: string): Promise<void> => {\n let entries: string[] = []\n try {\n entries = await readdir(dir)\n } catch {\n return\n }\n for (const ent of entries) {\n // Skip hidden segments — matches the FsPort contract.\n if (ent.startsWith(\".\")) continue\n const full = path.join(dir, ent)\n const s = await stat(full)\n if (s.isDirectory()) {\n await visit(full)\n } else if (s.isFile()) {\n out.push(path.relative(this.root, full).split(path.sep).join(\"/\"))\n }\n }\n }\n await visit(start)\n return out\n }\n\n async stat(p: string): Promise<FsStat | null> {\n try {\n const s = await stat(this.resolve(p))\n return {\n kind: s.isDirectory() ? \"directory\" : \"file\",\n bytes: s.isFile() ? s.size : undefined,\n modifiedAt: s.mtime,\n }\n } catch {\n return null\n }\n }\n\n /**\n * Advisory lock — a single-process no-op. The files engine never calls\n * `lock()` (it only reads/writes whole source files), and this backing is\n * local CLI, for which the `FsPort` contract permits a no-op lock.\n */\n async lock(_p: string): Promise<FsLockHandle> {\n return { release: async () => {} }\n }\n\n /**\n * Resolve a workspace-relative path to an absolute host path, refusing to\n * climb out of the workspace root (defense against `../../etc/passwd`-style\n * abuse). The files engine's paths must stay inside the workspace.\n */\n private resolve(p: string): string {\n const normalized = path.posix.normalize(\"/\" + p.replace(/^\\/+/, \"\"))\n const rel = normalized.slice(1)\n if (rel.startsWith(\"..\")) {\n throw new Error(\n `LocalFs: path \"${p}\" escapes the workspace root \"${this.root}\"`,\n )\n }\n return path.join(this.root, rel)\n }\n}\n","/**\n * Typed environment module for the files knowledge adapter.\n *\n * Every `process.env` read in this package flows through here — no raw\n * `process.env.X` at a call site (mirrors the code-brain adapter's `env.ts`).\n * Each loader parses the ambient env into a typed, defaulted config once, so\n * the rest of the adapter is a pure function of its inputs. This is the ONE\n * place the files-engine env names (`KNOWLEDGE_FILES_*`) live.\n */\n\n/** Config for the standalone files backend — a local root + a folder to index. */\nexport interface FilesKnowledgeEnv {\n /**\n * Absolute host path to the workspace root the {@link LocalFs} is rooted at.\n * Default: the process cwd.\n */\n readonly root: string\n /**\n * Workspace-relative folder the engine walks and indexes (recursively).\n * Default `\"knowledge\"`.\n */\n readonly workspacePath: string\n}\n\n/** Load {@link FilesKnowledgeEnv} from `process.env` with defaults. */\nexport function loadFilesKnowledgeEnv(): FilesKnowledgeEnv {\n const root = process.env.KNOWLEDGE_FILES_ROOT\n const workspacePath = process.env.KNOWLEDGE_FILES_PATH\n return {\n root: root !== undefined && root !== \"\" ? root : process.cwd(),\n workspacePath:\n workspacePath !== undefined && workspacePath !== \"\"\n ? workspacePath.trim()\n : \"knowledge\",\n }\n}\n","/**\n * Standalone wiring for {@link FilesKnowledgeAdapter}.\n *\n * The adapter class itself is backing-agnostic: it consumes an injected\n * `FsPort` and knows nothing about `node:fs` or `process.env`. This module\n * is the ONE place that binds it to the local filesystem — it reads the\n * typed `KNOWLEDGE_FILES_*` env (via {@link loadFilesKnowledgeEnv}) and roots\n * a {@link LocalFs} at it, exactly the role the code-brain adapter's\n * `gbrainLocalProvider` factory plays for its backend. Hosts that already\n * hold an `FsPort` (e.g. a studio guild host) should construct\n * `FilesKnowledgeAdapter` directly and skip this factory.\n */\n\nimport { FilesKnowledgeAdapter } from \"./adapter.js\"\nimport { loadFilesKnowledgeEnv } from \"./env.js\"\nimport { LocalFs } from \"./local-fs.js\"\n\n/**\n * Build a {@link FilesKnowledgeAdapter} backed by the local filesystem,\n * rooted and scoped from the ambient `KNOWLEDGE_FILES_*` env. Each call\n * returns a fresh adapter (and thus a fresh, empty BM25 cache) — callers\n * that want a shared warm index should hold onto the instance.\n */\nexport function createStandaloneFilesAdapter(): FilesKnowledgeAdapter {\n const env = loadFilesKnowledgeEnv()\n return new FilesKnowledgeAdapter({\n fs: new LocalFs({ root: env.root }),\n workspacePath: env.workspacePath,\n })\n}\n","import type { AdapterCatalog } from \"@agentproto/provider-kit\"\n\n/**\n * Family key used for the knowledge backend creds/ledger store path.\n *\n * The retrieval sibling of the `code-brain` family: the provider-kit\n * discovery convention (`@agentproto/adapter-knowledge-*`) points every\n * knowledge backend at its providing package.\n */\nexport const KNOWLEDGE_FAMILY = \"knowledge\" as const\n\n/** The single backend slug this adapter provides. */\nexport const FILES_BM25_SLUG = \"files\" as const\n\n/**\n * Static catalog of knowledge backends shipped by this adapter. The `files`\n * slug resolves from THIS package (`@agentproto/adapter-knowledge-files`) —\n * an in-process BM25 index over local workspace files, no embeddings, no\n * network, no credential.\n */\nexport const KNOWLEDGE_FILES_CATALOG: AdapterCatalog = [\n {\n slug: FILES_BM25_SLUG,\n name: \"files (BM25)\",\n description:\n \"Knowledge retrieval from local workspace files via an in-process \" +\n \"BM25 index. No embeddings, no network, no API key — works the \" +\n \"instant a workspace has files to index.\",\n packageName: \"@agentproto/adapter-knowledge-files\",\n hint: \"files · bm25\",\n },\n]\n","/**\n * provider-kit family wiring for the files knowledge backend.\n *\n * The studio home-grown `createEngineRegistry`-based knowledge registry is\n * NOT ported (it was the guild resolution layer, which stays studio-side per\n * the Ph4 plan). Instead the files backend registers as a provider-kit family\n * (`TInfo = KnowledgeFilesInfo`, `THandle = KnowledgeHandle extends\n * AdapterHandle`), reusing the exact consumer shape the code-brain adapter\n * established — catalog + resolver + a safe `info()` descriptor. Discovery\n * flows through the kit's `@agentproto/adapter-knowledge-*` naming convention.\n */\n\nimport type { IKnowledgeProvider } from \"@agentproto/knowledge-engine\"\nimport {\n makeAdapterResolver,\n type AdapterHandle,\n type AdapterResolver,\n} from \"@agentproto/provider-kit\"\nimport { FILES_BM25_SLUG, KNOWLEDGE_FILES_CATALOG } from \"./catalog.js\"\nimport { createStandaloneFilesAdapter } from \"./standalone.js\"\n\n/** Safe descriptor for a knowledge backend — NEVER carries a secret. */\nexport interface KnowledgeFilesInfo {\n readonly slug: string\n /** The retrieval engine this backend uses. */\n readonly engine: \"bm25\"\n readonly capabilities: {\n /** True when the backend performs dense/vector retrieval. */\n readonly vectorSearch: boolean\n /** True when the backend needs a credential to authenticate. */\n readonly needsCreds: boolean\n }\n}\n\n/** A resolved knowledge backend handle. */\nexport interface KnowledgeHandle extends AdapterHandle {\n /** Safe descriptor — NEVER a secret. */\n info(): KnowledgeFilesInfo\n /** Build the live {@link IKnowledgeProvider}. */\n provider(): IKnowledgeProvider\n}\n\n/**\n * Resolve a catalog slug to a concrete knowledge handle. Throws for unknown\n * slugs so the kit's resolver wrapper folds the miss to `null`. `provider()`\n * is lazy and caches a single standalone adapter — repeated calls share one\n * warm BM25 index rather than each cold-building their own.\n */\nexport function resolveKnowledgeBackend(slug: string): KnowledgeHandle {\n const catalogEntry = KNOWLEDGE_FILES_CATALOG.find(\n entry => entry.slug === slug\n )\n if (catalogEntry === undefined) {\n throw new Error(`unknown knowledge backend slug: ${slug}`)\n }\n\n switch (slug) {\n case FILES_BM25_SLUG: {\n // Lazily built + cached so every provider() call shares one warm index.\n let cached: IKnowledgeProvider | null = null\n const provider = (): IKnowledgeProvider =>\n (cached ??= createStandaloneFilesAdapter())\n return {\n slug,\n name: catalogEntry.name,\n description: catalogEntry.description,\n version: \"0.1.0\",\n // No creds, no external service — indexing the local workspace works\n // out of the box, so there is nothing to set up.\n requiresSetup: false,\n check: () => provider().healthCheck(),\n info() {\n return {\n slug,\n engine: \"bm25\",\n capabilities: { vectorSearch: false, needsCreds: false },\n }\n },\n provider,\n }\n }\n }\n\n throw new Error(`unhandled knowledge backend slug: ${slug}`)\n}\n\n/**\n * Build the knowledge resolver: resolves a catalog slug to a handle,\n * returning `null` when the slug is unknown (via the kit's wrapper).\n */\nexport function makeKnowledgeFilesResolver(): AdapterResolver<KnowledgeHandle> {\n return makeAdapterResolver<KnowledgeHandle>({\n load: async (slug: string): Promise<KnowledgeHandle> =>\n resolveKnowledgeBackend(slug),\n })\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentproto/adapter-knowledge-files",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Pure, zero-runtime knowledge adapter: implements @agentproto/knowledge-engine's IKnowledgeProvider over local files with an in-process BM25 index (no embeddings, no network, no API key). Registers as a provider-kit family and ships a node:fs FsPort so it runs standalone. All BM25 index/query logic is confined to this package.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agentproto",
|
|
@@ -46,16 +46,16 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@agentproto/corpus": "0.
|
|
50
|
-
"@agentproto/knowledge-engine": "0.3.
|
|
51
|
-
"@agentproto/provider-kit": "0.
|
|
49
|
+
"@agentproto/corpus": "1.0.0",
|
|
50
|
+
"@agentproto/knowledge-engine": "0.3.5",
|
|
51
|
+
"@agentproto/provider-kit": "0.6.0"
|
|
52
52
|
},
|
|
53
53
|
"devDependencies": {
|
|
54
54
|
"@types/node": "^25.9.9",
|
|
55
55
|
"tsup": "^8.5.1",
|
|
56
56
|
"typescript": "^5.9.3",
|
|
57
57
|
"vitest": "^3.2.7",
|
|
58
|
-
"@agentproto/tool": "0.
|
|
58
|
+
"@agentproto/tool": "0.6.1",
|
|
59
59
|
"@agentproto/tooling": "0.1.0"
|
|
60
60
|
},
|
|
61
61
|
"engines": {
|