@seanhogg/builderforce-memory 2026.10.28 → 2026.10.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ingest/IngestionPipeline.d.ts +1 -8
- package/dist/ingest/IngestionPipeline.d.ts.map +1 -1
- package/dist/ingest/IngestionPipeline.js +3 -15
- package/dist/ingest/IngestionPipeline.js.map +1 -1
- package/dist/ingest/docsExtract.d.ts +30 -0
- package/dist/ingest/docsExtract.d.ts.map +1 -0
- package/dist/ingest/docsExtract.js +221 -0
- package/dist/ingest/docsExtract.js.map +1 -0
- package/dist/ingest/hash.d.ts +15 -0
- package/dist/ingest/hash.d.ts.map +1 -0
- package/dist/ingest/hash.js +22 -0
- package/dist/ingest/hash.js.map +1 -0
- package/dist/ingest/parsers.d.ts.map +1 -1
- package/dist/ingest/parsers.js +4 -0
- package/dist/ingest/parsers.js.map +1 -1
- package/dist/ingest/types.d.ts +7 -0
- package/dist/ingest/types.d.ts.map +1 -1
- package/dist/ingest/types.js.map +1 -1
- package/dist/knowledge/build.d.ts +24 -0
- package/dist/knowledge/build.d.ts.map +1 -0
- package/dist/knowledge/build.js +263 -0
- package/dist/knowledge/build.js.map +1 -0
- package/dist/knowledge/cards.d.ts +17 -0
- package/dist/knowledge/cards.d.ts.map +1 -0
- package/dist/knowledge/cards.js +118 -0
- package/dist/knowledge/cards.js.map +1 -0
- package/dist/knowledge/findings.d.ts +24 -0
- package/dist/knowledge/findings.d.ts.map +1 -0
- package/dist/knowledge/findings.js +152 -0
- package/dist/knowledge/findings.js.map +1 -0
- package/dist/knowledge/importance.d.ts +21 -0
- package/dist/knowledge/importance.d.ts.map +1 -0
- package/dist/knowledge/importance.js +70 -0
- package/dist/knowledge/importance.js.map +1 -0
- package/dist/knowledge/index.d.ts +31 -0
- package/dist/knowledge/index.d.ts.map +1 -0
- package/dist/knowledge/index.js +26 -0
- package/dist/knowledge/index.js.map +1 -0
- package/dist/knowledge/judge.d.ts +86 -0
- package/dist/knowledge/judge.d.ts.map +1 -0
- package/dist/knowledge/judge.js +213 -0
- package/dist/knowledge/judge.js.map +1 -0
- package/dist/knowledge/model.d.ts +333 -0
- package/dist/knowledge/model.d.ts.map +1 -0
- package/dist/knowledge/model.js +13 -0
- package/dist/knowledge/model.js.map +1 -0
- package/dist/knowledge/packs/docs.d.ts +17 -0
- package/dist/knowledge/packs/docs.d.ts.map +1 -0
- package/dist/knowledge/packs/docs.js +89 -0
- package/dist/knowledge/packs/docs.js.map +1 -0
- package/dist/knowledge/partitions.d.ts +31 -0
- package/dist/knowledge/partitions.d.ts.map +1 -0
- package/dist/knowledge/partitions.js +135 -0
- package/dist/knowledge/partitions.js.map +1 -0
- package/dist/knowledge/plan.d.ts +33 -0
- package/dist/knowledge/plan.d.ts.map +1 -0
- package/dist/knowledge/plan.js +89 -0
- package/dist/knowledge/plan.js.map +1 -0
- package/dist/knowledge/refs.d.ts +40 -0
- package/dist/knowledge/refs.d.ts.map +1 -0
- package/dist/knowledge/refs.js +102 -0
- package/dist/knowledge/refs.js.map +1 -0
- package/dist/knowledge/resolve.d.ts +35 -0
- package/dist/knowledge/resolve.d.ts.map +1 -0
- package/dist/knowledge/resolve.js +67 -0
- package/dist/knowledge/resolve.js.map +1 -0
- package/dist/knowledge/review.d.ts +23 -0
- package/dist/knowledge/review.d.ts.map +1 -0
- package/dist/knowledge/review.js +233 -0
- package/dist/knowledge/review.js.map +1 -0
- package/dist/knowledge/sources.d.ts +47 -0
- package/dist/knowledge/sources.d.ts.map +1 -0
- package/dist/knowledge/sources.js +136 -0
- package/dist/knowledge/sources.js.map +1 -0
- package/dist/knowledge/stores/localSnapshotStore.d.ts +50 -0
- package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -0
- package/dist/knowledge/stores/localSnapshotStore.js +125 -0
- package/dist/knowledge/stores/localSnapshotStore.js.map +1 -0
- package/dist/knowledge/trace.d.ts +32 -0
- package/dist/knowledge/trace.d.ts.map +1 -0
- package/dist/knowledge/trace.js +102 -0
- package/dist/knowledge/trace.js.map +1 -0
- package/dist/knowledge/truncate.d.ts +24 -0
- package/dist/knowledge/truncate.d.ts.map +1 -0
- package/dist/knowledge/truncate.js +128 -0
- package/dist/knowledge/truncate.js.map +1 -0
- package/dist/memory/SemanticRecall.d.ts.map +1 -1
- package/dist/memory/SemanticRecall.js +3 -1
- package/dist/memory/SemanticRecall.js.map +1 -1
- package/dist/retrieval/HybridRetriever.d.ts.map +1 -1
- package/dist/retrieval/HybridRetriever.js +3 -1
- package/dist/retrieval/HybridRetriever.js.map +1 -1
- package/dist/retrieval/bm25.d.ts +3 -2
- package/dist/retrieval/bm25.d.ts.map +1 -1
- package/dist/retrieval/bm25.js +5 -3
- package/dist/retrieval/bm25.js.map +1 -1
- package/dist/retrieval/fusion.d.ts +2 -1
- package/dist/retrieval/fusion.d.ts.map +1 -1
- package/dist/retrieval/fusion.js +4 -2
- package/dist/retrieval/fusion.js.map +1 -1
- package/dist/retrieval/hnsw.d.ts +49 -11
- package/dist/retrieval/hnsw.d.ts.map +1 -1
- package/dist/retrieval/hnsw.js +57 -29
- package/dist/retrieval/hnsw.js.map +1 -1
- package/dist/retrieval/index.d.ts +7 -3
- package/dist/retrieval/index.d.ts.map +1 -1
- package/dist/retrieval/index.js +5 -2
- package/dist/retrieval/index.js.map +1 -1
- package/dist/retrieval/knowledge-index/bytes.d.ts +43 -0
- package/dist/retrieval/knowledge-index/bytes.d.ts.map +1 -0
- package/dist/retrieval/knowledge-index/bytes.js +151 -0
- package/dist/retrieval/knowledge-index/bytes.js.map +1 -0
- package/dist/retrieval/knowledge-index/cascade.d.ts +39 -0
- package/dist/retrieval/knowledge-index/cascade.d.ts.map +1 -0
- package/dist/retrieval/knowledge-index/cascade.js +125 -0
- package/dist/retrieval/knowledge-index/cascade.js.map +1 -0
- package/dist/retrieval/knowledge-index/compact.d.ts +22 -0
- package/dist/retrieval/knowledge-index/compact.d.ts.map +1 -0
- package/dist/retrieval/knowledge-index/compact.js +72 -0
- package/dist/retrieval/knowledge-index/compact.js.map +1 -0
- package/dist/retrieval/knowledge-index/csr.d.ts +41 -0
- package/dist/retrieval/knowledge-index/csr.d.ts.map +1 -0
- package/dist/retrieval/knowledge-index/csr.js +76 -0
- package/dist/retrieval/knowledge-index/csr.js.map +1 -0
- package/dist/retrieval/knowledge-index/digest.d.ts +22 -0
- package/dist/retrieval/knowledge-index/digest.d.ts.map +1 -0
- package/dist/retrieval/knowledge-index/digest.js +52 -0
- package/dist/retrieval/knowledge-index/digest.js.map +1 -0
- package/dist/retrieval/knowledge-index/embeddings.d.ts +32 -0
- package/dist/retrieval/knowledge-index/embeddings.d.ts.map +1 -0
- package/dist/retrieval/knowledge-index/embeddings.js +78 -0
- package/dist/retrieval/knowledge-index/embeddings.js.map +1 -0
- package/dist/retrieval/knowledge-index/expand.d.ts +19 -0
- package/dist/retrieval/knowledge-index/expand.d.ts.map +1 -0
- package/dist/retrieval/knowledge-index/expand.js +49 -0
- package/dist/retrieval/knowledge-index/expand.js.map +1 -0
- package/dist/retrieval/knowledge-index/index.d.ts +44 -0
- package/dist/retrieval/knowledge-index/index.d.ts.map +1 -0
- package/dist/retrieval/knowledge-index/index.js +136 -0
- package/dist/retrieval/knowledge-index/index.js.map +1 -0
- package/dist/retrieval/knowledge-index/lexical.d.ts +26 -0
- package/dist/retrieval/knowledge-index/lexical.d.ts.map +1 -0
- package/dist/retrieval/knowledge-index/lexical.js +76 -0
- package/dist/retrieval/knowledge-index/lexical.js.map +1 -0
- package/dist/retrieval/knowledge-index/pairs.d.ts +24 -0
- package/dist/retrieval/knowledge-index/pairs.d.ts.map +1 -0
- package/dist/retrieval/knowledge-index/pairs.js +65 -0
- package/dist/retrieval/knowledge-index/pairs.js.map +1 -0
- package/dist/retrieval/knowledge-index/prune.d.ts +21 -0
- package/dist/retrieval/knowledge-index/prune.d.ts.map +1 -0
- package/dist/retrieval/knowledge-index/prune.js +43 -0
- package/dist/retrieval/knowledge-index/prune.js.map +1 -0
- package/dist/retrieval/knowledge-index/quantize.d.ts +37 -0
- package/dist/retrieval/knowledge-index/quantize.d.ts.map +1 -0
- package/dist/retrieval/knowledge-index/quantize.js +77 -0
- package/dist/retrieval/knowledge-index/quantize.js.map +1 -0
- package/dist/retrieval/knowledge-index/scan.d.ts +39 -0
- package/dist/retrieval/knowledge-index/scan.d.ts.map +1 -0
- package/dist/retrieval/knowledge-index/scan.js +104 -0
- package/dist/retrieval/knowledge-index/scan.js.map +1 -0
- package/dist/retrieval/knowledge-index/serialize.d.ts +23 -0
- package/dist/retrieval/knowledge-index/serialize.d.ts.map +1 -0
- package/dist/retrieval/knowledge-index/serialize.js +135 -0
- package/dist/retrieval/knowledge-index/serialize.js.map +1 -0
- package/dist/retrieval/knowledge-index/sha256.d.ts +30 -0
- package/dist/retrieval/knowledge-index/sha256.d.ts.map +1 -0
- package/dist/retrieval/knowledge-index/sha256.js +130 -0
- package/dist/retrieval/knowledge-index/sha256.js.map +1 -0
- package/dist/retrieval/knowledge-index/state.d.ts +59 -0
- package/dist/retrieval/knowledge-index/state.d.ts.map +1 -0
- package/dist/retrieval/knowledge-index/state.js +72 -0
- package/dist/retrieval/knowledge-index/state.js.map +1 -0
- package/dist/retrieval/knowledge-index/tokenize.d.ts +20 -0
- package/dist/retrieval/knowledge-index/tokenize.d.ts.map +1 -0
- package/dist/retrieval/knowledge-index/tokenize.js +42 -0
- package/dist/retrieval/knowledge-index/tokenize.js.map +1 -0
- package/dist/retrieval/knowledge-index/traverse.d.ts +30 -0
- package/dist/retrieval/knowledge-index/traverse.d.ts.map +1 -0
- package/dist/retrieval/knowledge-index/traverse.js +90 -0
- package/dist/retrieval/knowledge-index/traverse.js.map +1 -0
- package/dist/retrieval/knowledge-index/types.d.ts +94 -0
- package/dist/retrieval/knowledge-index/types.d.ts.map +1 -0
- package/dist/retrieval/knowledge-index/types.js +9 -0
- package/dist/retrieval/knowledge-index/types.js.map +1 -0
- package/dist/retrieval/mmr.d.ts +11 -4
- package/dist/retrieval/mmr.d.ts.map +1 -1
- package/dist/retrieval/mmr.js +28 -8
- package/dist/retrieval/mmr.js.map +1 -1
- package/dist/retrieval/order.d.ts +41 -0
- package/dist/retrieval/order.d.ts.map +1 -0
- package/dist/retrieval/order.js +54 -0
- package/dist/retrieval/order.js.map +1 -0
- package/dist/retrieval/weightedFusion.d.ts +2 -1
- package/dist/retrieval/weightedFusion.d.ts.map +1 -1
- package/dist/retrieval/weightedFusion.js +7 -5
- package/dist/retrieval/weightedFusion.js.map +1 -1
- package/dist/vectorstore/MemoryVectorStore.d.ts.map +1 -1
- package/dist/vectorstore/MemoryVectorStore.js +2 -1
- package/dist/vectorstore/MemoryVectorStore.js.map +1 -1
- package/package.json +8 -3
- package/src/ingest/IngestionPipeline.ts +3 -15
- package/src/ingest/docsExtract.ts +219 -0
- package/src/ingest/hash.ts +22 -0
- package/src/ingest/parsers.ts +4 -0
- package/src/ingest/types.ts +7 -0
- package/src/knowledge/build.test.ts +150 -0
- package/src/knowledge/build.ts +266 -0
- package/src/knowledge/cards.ts +130 -0
- package/src/knowledge/docs.test.ts +118 -0
- package/src/knowledge/findings.ts +159 -0
- package/src/knowledge/importance.ts +72 -0
- package/src/knowledge/index.ts +53 -0
- package/src/knowledge/judge.ts +231 -0
- package/src/knowledge/model.ts +312 -0
- package/src/knowledge/packs/docs.ts +91 -0
- package/src/knowledge/partitions.test.ts +98 -0
- package/src/knowledge/partitions.ts +119 -0
- package/src/knowledge/plan.ts +115 -0
- package/src/knowledge/refs.ts +108 -0
- package/src/knowledge/resolve.ts +78 -0
- package/src/knowledge/review.test.ts +180 -0
- package/src/knowledge/review.ts +235 -0
- package/src/knowledge/sources.ts +146 -0
- package/src/knowledge/stores/localSnapshotStore.test.ts +82 -0
- package/src/knowledge/stores/localSnapshotStore.ts +159 -0
- package/src/knowledge/testkit.test-util.ts +92 -0
- package/src/knowledge/trace.test.ts +91 -0
- package/src/knowledge/trace.ts +111 -0
- package/src/knowledge/truncate.ts +118 -0
- package/src/memory/SemanticRecall.ts +3 -1
- package/src/retrieval/HybridRetriever.ts +3 -1
- package/src/retrieval/bm25.ts +5 -3
- package/src/retrieval/fusion.ts +5 -2
- package/src/retrieval/hnsw.ts +82 -35
- package/src/retrieval/index.ts +17 -3
- package/src/retrieval/knowledge-index/bytes.ts +166 -0
- package/src/retrieval/knowledge-index/cascade.ts +139 -0
- package/src/retrieval/knowledge-index/compact.ts +76 -0
- package/src/retrieval/knowledge-index/csr.ts +102 -0
- package/src/retrieval/knowledge-index/digest.ts +56 -0
- package/src/retrieval/knowledge-index/embeddings.ts +85 -0
- package/src/retrieval/knowledge-index/expand.ts +55 -0
- package/src/retrieval/knowledge-index/index.ts +166 -0
- package/src/retrieval/knowledge-index/lexical.ts +78 -0
- package/src/retrieval/knowledge-index/pairs.ts +72 -0
- package/src/retrieval/knowledge-index/prune.ts +48 -0
- package/src/retrieval/knowledge-index/quantize.ts +78 -0
- package/src/retrieval/knowledge-index/scan.ts +101 -0
- package/src/retrieval/knowledge-index/serialize.ts +136 -0
- package/src/retrieval/knowledge-index/sha256.ts +122 -0
- package/src/retrieval/knowledge-index/state.ts +116 -0
- package/src/retrieval/knowledge-index/tokenize.ts +41 -0
- package/src/retrieval/knowledge-index/traverse.ts +95 -0
- package/src/retrieval/knowledge-index/types.ts +88 -0
- package/src/retrieval/mmr.ts +35 -10
- package/src/retrieval/order.ts +68 -0
- package/src/retrieval/weightedFusion.ts +8 -5
- package/src/vectorstore/MemoryVectorStore.ts +2 -1
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* quantize.ts — int8 codes with one symmetric per-index scale.
|
|
3
|
+
*
|
|
4
|
+
* Graph traversal compares int8 codes with integer dot products. A sum of
|
|
5
|
+
* int8×int8 products stays far inside 2^53, so it is exact in a JS number and
|
|
6
|
+
* bit-identical on every platform — the float noise between a CPU and a WebGPU
|
|
7
|
+
* embedding only matters where a component sits on a rounding boundary.
|
|
8
|
+
*
|
|
9
|
+
* The scale is fitted once (at the index's first compaction) and then fixed, so a
|
|
10
|
+
* code never changes meaning while the index lives.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Largest code magnitude; symmetric, so -128 is never produced. */
|
|
14
|
+
export const CODE_MAX = 127;
|
|
15
|
+
|
|
16
|
+
/** How far from unit norm a vector may be and still be taken as already normalised. */
|
|
17
|
+
const UNIT_TOLERANCE = 1e-3;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* A unit-norm Float32 copy of `v`. Every embedder behind the port already emits
|
|
21
|
+
* L2-normalised vectors; those (|‖v‖² − 1| ≤ 1e-3) are copied as-is, so a
|
|
22
|
+
* last-bit difference between two hosts' embeddings is not amplified by a
|
|
23
|
+
* renormalisation. Anything else is normalised; a zero vector stays zero.
|
|
24
|
+
*/
|
|
25
|
+
export function toUnit(v: ArrayLike<number>): Float32Array {
|
|
26
|
+
let sum = 0;
|
|
27
|
+
for (let i = 0; i < v.length; i++) sum += v[i]! * v[i]!;
|
|
28
|
+
const out = Float32Array.from(v);
|
|
29
|
+
if (sum === 0 || Math.abs(sum - 1) <= UNIT_TOLERANCE) return out;
|
|
30
|
+
const norm = Math.sqrt(sum);
|
|
31
|
+
for (let i = 0; i < out.length; i++) out[i] = out[i]! / norm;
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The symmetric scale for a set of (normalised) vectors: CODE_MAX over the largest
|
|
37
|
+
* component magnitude, rounded UP to 1/64 first so a little float noise in the
|
|
38
|
+
* maximum does not move the scale.
|
|
39
|
+
*/
|
|
40
|
+
export function fitScale(vectors: Iterable<ArrayLike<number>>): number {
|
|
41
|
+
let maxAbs = 0;
|
|
42
|
+
for (const v of vectors) {
|
|
43
|
+
for (let i = 0; i < v.length; i++) {
|
|
44
|
+
const a = Math.abs(v[i]!);
|
|
45
|
+
if (a > maxAbs) maxAbs = a;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const bound = Math.max(1, Math.ceil(maxAbs * 64)) / 64;
|
|
49
|
+
return CODE_MAX / bound;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** int8 codes of `v` at `scale`, clamped to ±CODE_MAX. */
|
|
53
|
+
export function quantize(v: ArrayLike<number>, scale: number): Int8Array {
|
|
54
|
+
const out = new Int8Array(v.length);
|
|
55
|
+
for (let i = 0; i < v.length; i++) {
|
|
56
|
+
const q = Math.round(v[i]! * scale);
|
|
57
|
+
out[i] = q > CODE_MAX ? CODE_MAX : q < -CODE_MAX ? -CODE_MAX : q;
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Exact integer dot product of two code vectors. */
|
|
63
|
+
export function dotInt8(a: Int8Array, b: Int8Array): number {
|
|
64
|
+
const n = Math.min(a.length, b.length);
|
|
65
|
+
let dot = 0;
|
|
66
|
+
for (let i = 0; i < n; i++) dot += a[i]! * b[i]!;
|
|
67
|
+
return dot;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Cosine of two code vectors: an exact integer dot over exact integer norms, then
|
|
72
|
+
* IEEE `sqrt` and division — both correctly rounded, so the result is the same
|
|
73
|
+
* everywhere. 0 when either is a zero vector.
|
|
74
|
+
*/
|
|
75
|
+
export function cosineInt8(a: Int8Array, b: Int8Array): number {
|
|
76
|
+
const denom = Math.sqrt(dotInt8(a, a)) * Math.sqrt(dotInt8(b, b));
|
|
77
|
+
return denom === 0 ? 0 : dotInt8(a, b) / denom;
|
|
78
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* scan.ts — exact mode: the dense tier and `similarPairs` with no graph.
|
|
3
|
+
*
|
|
4
|
+
* Below `exactBelow` cards an HNSW graph costs more to build than it saves, so
|
|
5
|
+
* `compact()` builds none and these replace the walk:
|
|
6
|
+
*
|
|
7
|
+
* - {@link scanCodes}: an exact integer dot product against every live int8 code,
|
|
8
|
+
* the best `n` kept with ties on node index (= id order). Same order as the
|
|
9
|
+
* graph walk's candidates, so the float rerank after it is unchanged.
|
|
10
|
+
* - {@link exactPairCandidates}: the node pairs `similarPairs` scores. All pairs
|
|
11
|
+
* while there are at most {@link EXACT_PAIR_BUDGET}; above that, deterministic
|
|
12
|
+
* sign-bit blocking (see the function), capped at the same budget.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { graphNode, type Compacted, type IndexState } from './state.js';
|
|
16
|
+
import { dotInt8 } from './quantize.js';
|
|
17
|
+
import { before, insertOrdered, type GraphCandidate } from './traverse.js';
|
|
18
|
+
|
|
19
|
+
/** The most node pairs `similarPairs` scores in exact mode. */
|
|
20
|
+
export const EXACT_PAIR_BUDGET = 250_000;
|
|
21
|
+
/** Blocking tables: a pair is a candidate when it shares a bucket in any one of them. */
|
|
22
|
+
export const PAIR_BLOCK_TABLES = 8;
|
|
23
|
+
/** Sign bits per table (2^bits buckets each). */
|
|
24
|
+
export const PAIR_BLOCK_BITS = 10;
|
|
25
|
+
/** Within a bucket, each node is paired with at most this many following members (id order). */
|
|
26
|
+
export const PAIR_BLOCK_WINDOW = 32;
|
|
27
|
+
|
|
28
|
+
/** The best `n` live coded nodes by integer dot product with `qc`, in {@link before} order. */
|
|
29
|
+
export function scanCodes(state: IndexState, c: Compacted, qc: Int8Array, n: number): GraphCandidate[] {
|
|
30
|
+
const top: GraphCandidate[] = [];
|
|
31
|
+
if (n <= 0) return top;
|
|
32
|
+
for (let node = 0; node < c.ids.length; node++) {
|
|
33
|
+
const code = c.codes[node];
|
|
34
|
+
if (!code || graphNode(state, c.ids[node]!) !== node) continue;
|
|
35
|
+
const cand = { node, score: dotInt8(qc, code) };
|
|
36
|
+
if (top.length < n || before(cand, top[top.length - 1]!)) {
|
|
37
|
+
insertOrdered(top, cand);
|
|
38
|
+
if (top.length > n) top.pop();
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return top;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The dimensions table `t` reads its sign bits from, spread evenly across `dims`. */
|
|
45
|
+
function blockDims(t: number, dims: number): number[] {
|
|
46
|
+
const stride = Math.max(1, Math.floor(dims / (PAIR_BLOCK_TABLES * PAIR_BLOCK_BITS)));
|
|
47
|
+
return Array.from({ length: PAIR_BLOCK_BITS }, (_, j) => ((t * PAIR_BLOCK_BITS + j) * stride) % dims);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Candidate `[lo, hi]` node pairs (lo < hi) among `nodes` (ascending, all coded).
|
|
52
|
+
*
|
|
53
|
+
* When every pair fits in {@link EXACT_PAIR_BUDGET} (about 700 nodes), every pair is
|
|
54
|
+
* a candidate. Above that, each of {@link PAIR_BLOCK_TABLES} tables buckets the nodes
|
|
55
|
+
* by the signs of {@link PAIR_BLOCK_BITS} fixed code dimensions; a near-duplicate
|
|
56
|
+
* agrees on almost every sign, so it lands with its twin in at least one table.
|
|
57
|
+
* Inside a bucket a node is paired with its next {@link PAIR_BLOCK_WINDOW} members.
|
|
58
|
+
* Tables run in order, buckets in key order, members in node order, and generation
|
|
59
|
+
* stops at the budget — so the candidates are a pure function of the codes, and the
|
|
60
|
+
* cost is at most `EXACT_PAIR_BUDGET` cosine evaluations whatever the size.
|
|
61
|
+
*/
|
|
62
|
+
export function exactPairCandidates(
|
|
63
|
+
codes: ReadonlyArray<Int8Array | undefined>,
|
|
64
|
+
nodes: readonly number[],
|
|
65
|
+
dims: number,
|
|
66
|
+
): Array<[number, number]> {
|
|
67
|
+
const out: Array<[number, number]> = [];
|
|
68
|
+
const n = nodes.length;
|
|
69
|
+
if ((n * (n - 1)) / 2 <= EXACT_PAIR_BUDGET) {
|
|
70
|
+
for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) out.push([nodes[i]!, nodes[j]!]);
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
if (dims <= 0) return out;
|
|
74
|
+
const seen = new Set<number>();
|
|
75
|
+
for (let t = 0; t < PAIR_BLOCK_TABLES; t++) {
|
|
76
|
+
const bits = blockDims(t, dims);
|
|
77
|
+
const buckets = new Map<number, number[]>();
|
|
78
|
+
for (const node of nodes) {
|
|
79
|
+
const code = codes[node]!;
|
|
80
|
+
let key = 0;
|
|
81
|
+
for (const d of bits) key = key * 2 + ((code[d] ?? 0) > 0 ? 1 : 0);
|
|
82
|
+
const members = buckets.get(key);
|
|
83
|
+
if (members) members.push(node);
|
|
84
|
+
else buckets.set(key, [node]);
|
|
85
|
+
}
|
|
86
|
+
for (const key of [...buckets.keys()].sort((a, b) => a - b)) {
|
|
87
|
+
const members = buckets.get(key)!;
|
|
88
|
+
for (let i = 0; i < members.length; i++) {
|
|
89
|
+
const end = Math.min(members.length, i + 1 + PAIR_BLOCK_WINDOW);
|
|
90
|
+
for (let j = i + 1; j < end; j++) {
|
|
91
|
+
const pairKey = members[i]! * codes.length + members[j]!;
|
|
92
|
+
if (seen.has(pairKey)) continue;
|
|
93
|
+
seen.add(pairKey);
|
|
94
|
+
out.push([members[i]!, members[j]!]);
|
|
95
|
+
if (out.length >= EXACT_PAIR_BUDGET) return out;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* serialize.ts — the versioned binary form of an index state.
|
|
3
|
+
*
|
|
4
|
+
* Layout (little-endian, via `bytes.ts`), version 2:
|
|
5
|
+
* magic "BFKI" · u32 version
|
|
6
|
+
* fingerprint · dims · scale · params (`writeParams`, ending in `exactBelow`)
|
|
7
|
+
* docs (id order): id · text · hash · keys · optional pending float vector
|
|
8
|
+
* u8 compacted? → u8 mode (1 exact, 0 graph) · node ids · node hashes · hubs ·
|
|
9
|
+
* code-present flags · codes · graph (empty in exact mode)
|
|
10
|
+
*
|
|
11
|
+
* Version 1 (2026.10.29) had no `exactBelow` and no mode byte; every v1 index was a
|
|
12
|
+
* graph. It still loads: as graph mode, with `exactBelow` 0 so a later `compact()`
|
|
13
|
+
* keeps building the graph it was made with. Writing is always the current version.
|
|
14
|
+
*
|
|
15
|
+
* Texts travel with the index because the lexical tier, the recompute path and a
|
|
16
|
+
* re-embed under a new fingerprint all need them. Loading rebuilds the derived
|
|
17
|
+
* structures (key map, BM25 postings) and gives back the same digest.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { compareIds } from '../order.js';
|
|
21
|
+
import type { IndexParams } from './types.js';
|
|
22
|
+
import { createState, indexKeys, type Compacted, type DocEntry, type IndexState } from './state.js';
|
|
23
|
+
import type { CsrLayer } from './csr.js';
|
|
24
|
+
import { ByteReader, ByteWriter } from './bytes.js';
|
|
25
|
+
import { writeGraph, writeParams } from './digest.js';
|
|
26
|
+
|
|
27
|
+
const MAGIC = [0x42, 0x46, 0x4b, 0x49]; // "BFKI"
|
|
28
|
+
export const SERIALIZE_VERSION = 2;
|
|
29
|
+
/** The oldest version `deserializeState` still reads. */
|
|
30
|
+
const MIN_READ_VERSION = 1;
|
|
31
|
+
|
|
32
|
+
export function serializeState(state: IndexState): Uint8Array {
|
|
33
|
+
const w = new ByteWriter();
|
|
34
|
+
w.raw(Uint8Array.from(MAGIC)).u32(SERIALIZE_VERSION);
|
|
35
|
+
w.str(state.fingerprint).u32(state.dims).f64(state.scale);
|
|
36
|
+
writeParams(w, state.params);
|
|
37
|
+
|
|
38
|
+
const ids = [...state.docs.keys()].sort(compareIds);
|
|
39
|
+
w.u32(ids.length);
|
|
40
|
+
for (const id of ids) {
|
|
41
|
+
const doc = state.docs.get(id)!;
|
|
42
|
+
w.str(doc.id).str(doc.text).str(doc.hash).u32(doc.keys.length);
|
|
43
|
+
for (const key of doc.keys) w.str(key);
|
|
44
|
+
w.u8(doc.vec ? 1 : 0);
|
|
45
|
+
if (doc.vec) w.f32s(doc.vec);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const c = state.compacted;
|
|
49
|
+
w.u8(c ? 1 : 0);
|
|
50
|
+
if (c) {
|
|
51
|
+
w.u8(c.mode === 'exact' ? 1 : 0);
|
|
52
|
+
w.u32(c.ids.length);
|
|
53
|
+
for (let i = 0; i < c.ids.length; i++) w.str(c.ids[i]!).str(c.hashes[i]!);
|
|
54
|
+
w.bytes(c.hubs);
|
|
55
|
+
w.bytes(Uint8Array.from(c.codes, (code) => (code ? 1 : 0)));
|
|
56
|
+
for (const code of c.codes) if (code) w.bytes(code);
|
|
57
|
+
writeGraph(w, c.graph);
|
|
58
|
+
}
|
|
59
|
+
return w.finish();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function readParams(r: ByteReader, version: number): IndexParams {
|
|
63
|
+
return {
|
|
64
|
+
m: r.u32(),
|
|
65
|
+
efConstruction: r.u32(),
|
|
66
|
+
efSearch: r.u32(),
|
|
67
|
+
hubShare: r.f64(),
|
|
68
|
+
rerankFactor: r.u32(),
|
|
69
|
+
lean: r.u8() === 1,
|
|
70
|
+
rrfK: r.u32(),
|
|
71
|
+
// v1 indexes were always graphs: keep building one.
|
|
72
|
+
exactBelow: version >= 2 ? r.u32() : 0,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function deserializeState(bytes: Uint8Array): IndexState {
|
|
77
|
+
const r = new ByteReader(bytes);
|
|
78
|
+
const magic = r.raw(4);
|
|
79
|
+
if (MAGIC.some((b, i) => magic[i] !== b)) throw new Error('knowledge-index: not a serialized index');
|
|
80
|
+
const version = r.u32();
|
|
81
|
+
if (version < MIN_READ_VERSION || version > SERIALIZE_VERSION) throw new Error(`knowledge-index: unsupported version ${version}`);
|
|
82
|
+
|
|
83
|
+
const fingerprint = r.str();
|
|
84
|
+
const dims = r.u32();
|
|
85
|
+
const scale = r.f64();
|
|
86
|
+
const state = createState(readParams(r, version));
|
|
87
|
+
Object.assign(state, { fingerprint, dims, scale });
|
|
88
|
+
|
|
89
|
+
const docCount = r.u32();
|
|
90
|
+
for (let i = 0; i < docCount; i++) {
|
|
91
|
+
const doc: DocEntry = { id: r.str(), text: r.str(), hash: r.str(), keys: [] };
|
|
92
|
+
const keyCount = r.u32();
|
|
93
|
+
for (let k = 0; k < keyCount; k++) doc.keys.push(r.str());
|
|
94
|
+
if (r.u8() === 1) doc.vec = r.f32s();
|
|
95
|
+
state.docs.set(doc.id, doc);
|
|
96
|
+
indexKeys(state, doc, true);
|
|
97
|
+
state.lexical.set(doc.id, doc.text);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
if (r.u8() === 1) {
|
|
101
|
+
const mode: Compacted['mode'] = version >= 2 && r.u8() === 1 ? 'exact' : 'graph';
|
|
102
|
+
const n = r.u32();
|
|
103
|
+
const ids: string[] = [];
|
|
104
|
+
const hashes: string[] = [];
|
|
105
|
+
for (let i = 0; i < n; i++) {
|
|
106
|
+
ids.push(r.str());
|
|
107
|
+
hashes.push(r.str());
|
|
108
|
+
}
|
|
109
|
+
const hubs = r.bytes();
|
|
110
|
+
const present = r.bytes();
|
|
111
|
+
const codes: Compacted['codes'] = Array.from(present, (p) => {
|
|
112
|
+
if (p !== 1) return undefined;
|
|
113
|
+
const raw = r.bytes();
|
|
114
|
+
return new Int8Array(raw.buffer, raw.byteOffset, raw.byteLength);
|
|
115
|
+
});
|
|
116
|
+
const entry = r.i32();
|
|
117
|
+
const layerCount = r.u32();
|
|
118
|
+
const layers: CsrLayer[] = [];
|
|
119
|
+
for (let l = 0; l < layerCount; l++) {
|
|
120
|
+
const nodes = r.u32s();
|
|
121
|
+
const offsets = r.u32s();
|
|
122
|
+
const neighbours = r.u32s();
|
|
123
|
+
layers.push(l === 0 ? { offsets, neighbours } : { nodes, offsets, neighbours });
|
|
124
|
+
}
|
|
125
|
+
state.compacted = {
|
|
126
|
+
mode,
|
|
127
|
+
ids,
|
|
128
|
+
hashes,
|
|
129
|
+
codes,
|
|
130
|
+
hubs,
|
|
131
|
+
graph: { entry, layers },
|
|
132
|
+
nodeOf: new Map(ids.map((id, i) => [id, i])),
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
return state;
|
|
136
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* sha256.ts — a synchronous, pure-TypeScript SHA-256 (FIPS 180-4).
|
|
3
|
+
*
|
|
4
|
+
* The knowledge index names its state with a digest that must be identical on
|
|
5
|
+
* every host. WebCrypto is async and `node:crypto` is Node-only, so this is the
|
|
6
|
+
* one portable, synchronous hasher in the package: it runs in a Worker, a browser
|
|
7
|
+
* and Node, and it is incremental so a large state is hashed without first
|
|
8
|
+
* concatenating it.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const K = new Uint32Array([
|
|
12
|
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
|
13
|
+
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
|
14
|
+
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
|
15
|
+
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
|
16
|
+
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
|
17
|
+
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
|
18
|
+
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
|
19
|
+
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
|
20
|
+
]);
|
|
21
|
+
|
|
22
|
+
const encoder = new TextEncoder();
|
|
23
|
+
|
|
24
|
+
/** Incremental SHA-256: `update(...)` any number of times, then `digest()` once. */
|
|
25
|
+
export class Sha256 {
|
|
26
|
+
private readonly _h = new Uint32Array([
|
|
27
|
+
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
|
|
28
|
+
]);
|
|
29
|
+
private readonly _block = new Uint8Array(64);
|
|
30
|
+
private readonly _w = new Uint32Array(64);
|
|
31
|
+
private _blockLen = 0;
|
|
32
|
+
private _bytes = 0;
|
|
33
|
+
private _done = false;
|
|
34
|
+
|
|
35
|
+
/** Feeds bytes, or a string as UTF-8. */
|
|
36
|
+
update(data: Uint8Array | string): this {
|
|
37
|
+
if (this._done) throw new Error('Sha256: update after digest');
|
|
38
|
+
const bytes = typeof data === 'string' ? encoder.encode(data) : data;
|
|
39
|
+
this._bytes += bytes.length;
|
|
40
|
+
let i = 0;
|
|
41
|
+
while (i < bytes.length) {
|
|
42
|
+
const take = Math.min(64 - this._blockLen, bytes.length - i);
|
|
43
|
+
this._block.set(bytes.subarray(i, i + take), this._blockLen);
|
|
44
|
+
this._blockLen += take;
|
|
45
|
+
i += take;
|
|
46
|
+
if (this._blockLen === 64) {
|
|
47
|
+
this._compress();
|
|
48
|
+
this._blockLen = 0;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return this;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The 32-byte digest. The hasher is finished afterwards. */
|
|
55
|
+
digest(): Uint8Array {
|
|
56
|
+
if (this._done) throw new Error('Sha256: digest called twice');
|
|
57
|
+
const bitsHi = Math.floor(this._bytes / 0x20000000);
|
|
58
|
+
const bitsLo = (this._bytes * 8) >>> 0;
|
|
59
|
+
this.update(new Uint8Array([0x80]));
|
|
60
|
+
while (this._blockLen !== 56) this.update(new Uint8Array(1));
|
|
61
|
+
const len = new Uint8Array(8);
|
|
62
|
+
const view = new DataView(len.buffer);
|
|
63
|
+
view.setUint32(0, bitsHi);
|
|
64
|
+
view.setUint32(4, bitsLo);
|
|
65
|
+
this.update(len);
|
|
66
|
+
this._done = true;
|
|
67
|
+
const out = new Uint8Array(32);
|
|
68
|
+
const outView = new DataView(out.buffer);
|
|
69
|
+
for (let j = 0; j < 8; j++) outView.setUint32(j * 4, this._h[j]!);
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The digest as lowercase hex. */
|
|
74
|
+
hex(): string {
|
|
75
|
+
return toHex(this.digest());
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
private _compress(): void {
|
|
79
|
+
const w = this._w;
|
|
80
|
+
const b = this._block;
|
|
81
|
+
for (let t = 0; t < 16; t++) {
|
|
82
|
+
w[t] = ((b[t * 4]! << 24) | (b[t * 4 + 1]! << 16) | (b[t * 4 + 2]! << 8) | b[t * 4 + 3]!) >>> 0;
|
|
83
|
+
}
|
|
84
|
+
for (let t = 16; t < 64; t++) {
|
|
85
|
+
const x = w[t - 15]!;
|
|
86
|
+
const y = w[t - 2]!;
|
|
87
|
+
const s0 = ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3);
|
|
88
|
+
const s1 = ((y >>> 17) | (y << 15)) ^ ((y >>> 19) | (y << 13)) ^ (y >>> 10);
|
|
89
|
+
w[t] = (w[t - 16]! + s0 + w[t - 7]! + s1) >>> 0;
|
|
90
|
+
}
|
|
91
|
+
const h = this._h;
|
|
92
|
+
let a = h[0]!, bb = h[1]!, c = h[2]!, d = h[3]!, e = h[4]!, f = h[5]!, g = h[6]!, hh = h[7]!;
|
|
93
|
+
for (let t = 0; t < 64; t++) {
|
|
94
|
+
const S1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
|
|
95
|
+
const ch = (e & f) ^ (~e & g);
|
|
96
|
+
const t1 = (hh + S1 + ch + K[t]! + w[t]!) >>> 0;
|
|
97
|
+
const S0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
|
|
98
|
+
const maj = (a & bb) ^ (a & c) ^ (bb & c);
|
|
99
|
+
const t2 = (S0 + maj) >>> 0;
|
|
100
|
+
hh = g; g = f; f = e; e = (d + t1) >>> 0;
|
|
101
|
+
d = c; c = bb; bb = a; a = (t1 + t2) >>> 0;
|
|
102
|
+
}
|
|
103
|
+
h[0] = (h[0]! + a) >>> 0; h[1] = (h[1]! + bb) >>> 0; h[2] = (h[2]! + c) >>> 0; h[3] = (h[3]! + d) >>> 0;
|
|
104
|
+
h[4] = (h[4]! + e) >>> 0; h[5] = (h[5]! + f) >>> 0; h[6] = (h[6]! + g) >>> 0; h[7] = (h[7]! + hh) >>> 0;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function toHex(bytes: Uint8Array): string {
|
|
109
|
+
let s = '';
|
|
110
|
+
for (let i = 0; i < bytes.length; i++) s += bytes[i]!.toString(16).padStart(2, '0');
|
|
111
|
+
return s;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** SHA-256 of a string (UTF-8) or bytes. */
|
|
115
|
+
export function sha256(data: Uint8Array | string): Uint8Array {
|
|
116
|
+
return new Sha256().update(data).digest();
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** SHA-256 hex of a string (UTF-8) or bytes. */
|
|
120
|
+
export function sha256Hex(data: Uint8Array | string): string {
|
|
121
|
+
return new Sha256().update(data).hex();
|
|
122
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* state.ts — the knowledge index's in-memory state, shared by the cascade,
|
|
3
|
+
* compaction, digest and serializer. Everything a result depends on lives here,
|
|
4
|
+
* so `digest()` can name it and `serialize()` can carry it.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { EmbedderPort, IndexMode, IndexParams, IndexTier } from './types.js';
|
|
8
|
+
import type { CsrGraph } from './csr.js';
|
|
9
|
+
import { LexicalIndex } from './lexical.js';
|
|
10
|
+
import { foldKey } from './tokenize.js';
|
|
11
|
+
|
|
12
|
+
export const DEFAULT_INDEX_PARAMS: Readonly<IndexParams> = Object.freeze({
|
|
13
|
+
m: 16,
|
|
14
|
+
efConstruction: 200,
|
|
15
|
+
efSearch: 64,
|
|
16
|
+
hubShare: 0.02,
|
|
17
|
+
rerankFactor: 4,
|
|
18
|
+
lean: false,
|
|
19
|
+
rrfK: 60,
|
|
20
|
+
exactBelow: 20000,
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
/** One live card. `vec` is its unit float embedding while it is not yet in the graph. */
|
|
24
|
+
export interface DocEntry {
|
|
25
|
+
id: string;
|
|
26
|
+
text: string;
|
|
27
|
+
/** Case-folded, de-duplicated, sorted. */
|
|
28
|
+
keys: string[];
|
|
29
|
+
hash: string;
|
|
30
|
+
vec?: Float32Array;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The canonical, id-ordered snapshot written by `compact()`. Node index = rank of its id. */
|
|
34
|
+
export interface Compacted {
|
|
35
|
+
/** `exact`: no graph (empty `graph`, zero `hubs`, every code kept); `graph`: HNSW over the codes. */
|
|
36
|
+
mode: IndexMode;
|
|
37
|
+
ids: string[];
|
|
38
|
+
/** The doc hash each node was coded from; a node whose doc changed is stale. */
|
|
39
|
+
hashes: string[];
|
|
40
|
+
/** int8 codes by node; `undefined` where lean mode dropped a non-hub's code. */
|
|
41
|
+
codes: Array<Int8Array | undefined>;
|
|
42
|
+
/** 1 for a hub (top `hubShare` by in-degree). */
|
|
43
|
+
hubs: Uint8Array;
|
|
44
|
+
graph: CsrGraph;
|
|
45
|
+
nodeOf: Map<string, number>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface IndexState {
|
|
49
|
+
params: IndexParams;
|
|
50
|
+
/** Fingerprint of every stored vector and code; '' when none was ever embedded. */
|
|
51
|
+
fingerprint: string;
|
|
52
|
+
dims: number;
|
|
53
|
+
/** The int8 scale, fixed at the first compaction; 0 until then. */
|
|
54
|
+
scale: number;
|
|
55
|
+
docs: Map<string, DocEntry>;
|
|
56
|
+
/** Folded key → ids. */
|
|
57
|
+
keys: Map<string, Set<string>>;
|
|
58
|
+
lexical: LexicalIndex;
|
|
59
|
+
compacted: Compacted | null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function createState(params: Partial<IndexParams> | undefined, embedder?: EmbedderPort): IndexState {
|
|
63
|
+
return {
|
|
64
|
+
params: { ...DEFAULT_INDEX_PARAMS, ...params },
|
|
65
|
+
fingerprint: embedder?.fingerprint ?? '',
|
|
66
|
+
dims: embedder?.dims ?? 0,
|
|
67
|
+
scale: 0,
|
|
68
|
+
docs: new Map(),
|
|
69
|
+
keys: new Map(),
|
|
70
|
+
lexical: new LexicalIndex(),
|
|
71
|
+
compacted: null,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Folded, unique, sorted keys. */
|
|
76
|
+
export function canonicalKeys(keys: readonly string[] | undefined): string[] {
|
|
77
|
+
return [...new Set((keys ?? []).map(foldKey).filter(Boolean))].sort();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Adds (`on`) or removes a doc's keys from the exact-match map. */
|
|
81
|
+
export function indexKeys(state: IndexState, doc: DocEntry, on: boolean): void {
|
|
82
|
+
for (const key of doc.keys) {
|
|
83
|
+
let ids = state.keys.get(key);
|
|
84
|
+
if (on) {
|
|
85
|
+
if (!ids) state.keys.set(key, (ids = new Set()));
|
|
86
|
+
ids.add(doc.id);
|
|
87
|
+
} else if (ids) {
|
|
88
|
+
ids.delete(doc.id);
|
|
89
|
+
if (ids.size === 0) state.keys.delete(key);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The node index of `id` when its doc is live in the graph at the coded hash, else -1. */
|
|
95
|
+
export function graphNode(state: IndexState, id: string): number {
|
|
96
|
+
const c = state.compacted;
|
|
97
|
+
if (!c) return -1;
|
|
98
|
+
const node = c.nodeOf.get(id);
|
|
99
|
+
if (node === undefined) return -1;
|
|
100
|
+
return state.docs.get(id)?.hash === c.hashes[node] ? node : -1;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The search mode a compaction of `size` cards uses under `params`. */
|
|
104
|
+
export function modeFor(params: IndexParams, size: number): IndexMode {
|
|
105
|
+
return size < params.exactBelow ? 'exact' : 'graph';
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Whether `embedder` may produce vectors comparable with the stored ones. */
|
|
109
|
+
export function denseReady(state: IndexState, embedder: EmbedderPort | undefined): embedder is EmbedderPort {
|
|
110
|
+
return !!embedder && embedder.fingerprint === state.fingerprint && embedder.dims === state.dims;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** The tiers a search can run right now. */
|
|
114
|
+
export function availableTiers(state: IndexState, embedder: EmbedderPort | undefined): IndexTier[] {
|
|
115
|
+
return denseReady(state, embedder) ? ['exact', 'lexical', 'dense'] : ['exact', 'lexical'];
|
|
116
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* tokenize.ts — the code-aware tokenizer the knowledge index's lexical tier uses.
|
|
3
|
+
*
|
|
4
|
+
* Cards name things the way code does: `retryPolicy.ts`, `stripe_webhook`,
|
|
5
|
+
* `api/src/billing/invoice.ts`. The package's plain `tokenize` keeps
|
|
6
|
+
* `retrypolicy` whole, so "retry policy" never matches it. This splits paths on
|
|
7
|
+
* separators, then each word on snake_case and camelCase boundaries, and emits
|
|
8
|
+
* the parts AND the whole compound — an exact identifier still scores higher.
|
|
9
|
+
*
|
|
10
|
+
* Lowercasing is `toLowerCase` (locale-free), so the tokens are the same on every
|
|
11
|
+
* host. Pure and zero-dependency.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** camelCase / PascalCase / acronym boundaries: `parseHTTPResponse` → parse, HTTP, Response. */
|
|
15
|
+
function splitCamel(word: string): string[] {
|
|
16
|
+
return word
|
|
17
|
+
.replace(/([\p{Ll}\p{N}])(\p{Lu})/gu, '$1 $2')
|
|
18
|
+
.replace(/(\p{Lu}+)(\p{Lu}\p{Ll})/gu, '$1 $2')
|
|
19
|
+
.split(' ');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Splits `text` into lowercase terms: every word (a run of letters, digits and `_`)
|
|
24
|
+
* yields its snake/camel parts, plus the whole word when it has more than one part.
|
|
25
|
+
*/
|
|
26
|
+
export function codeTokenize(text: string): string[] {
|
|
27
|
+
const out: string[] = [];
|
|
28
|
+
for (const word of text.split(/[^\p{L}\p{N}_]+/u)) {
|
|
29
|
+
if (!word) continue;
|
|
30
|
+
const parts = word.split('_').flatMap(splitCamel).filter(Boolean).map((p) => p.toLowerCase());
|
|
31
|
+
if (parts.length === 0) continue;
|
|
32
|
+
out.push(...parts);
|
|
33
|
+
if (parts.length > 1) out.push(word.toLowerCase());
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Case-folds an exact-match key or query the same way on insert and on lookup. */
|
|
39
|
+
export function foldKey(key: string): string {
|
|
40
|
+
return key.trim().toLowerCase();
|
|
41
|
+
}
|