pikelet-wasm 0.14.0 → 0.16.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/CHANGELOG.md +528 -0
- package/FORMAT.md +500 -0
- package/NOTICE +25 -0
- package/README.md +50 -22
- package/complete/builder.d.ts +19 -1
- package/complete/builder.mjs +57 -64
- package/complete/fusion.mjs +17 -0
- package/complete/grounding.mjs +92 -0
- package/complete/index.d.ts +56 -7
- package/complete/index.mjs +214 -246
- package/complete/layer-append.mjs +5 -9
- package/complete/layer-chain.mjs +1 -2
- package/complete/layer-compact.mjs +5 -7
- package/complete/layer-manifest.mjs +2 -1
- package/complete/layer-reader.mjs +97 -82
- package/complete/layer-rebase.mjs +1 -1
- package/complete/node-fetch.mjs +22 -3
- package/complete/retrieval-abstention.mjs +68 -91
- package/complete/sources.mjs +171 -68
- package/package.json +2 -5
- package/src/artifact/pikelet-artifact-common.js +27 -0
- package/src/artifact/pikelet-artifact-sketch.js +38 -26
- package/src/artifact/pikelet-artifact.d.ts +4 -29
- package/src/artifact/pikelet-artifact.js +5 -8
- package/src/core/pikelet-core.js +9 -0
- package/src/pikelet.d.ts +2 -186
- package/src/pikelet.js +1 -9
- package/src/pikelet.node.mjs +1 -9
- package/src/pikelet.web.d.ts +0 -8
- package/src/pikelet.web.mjs +1 -2
- package/src/pikelet.workerd.mjs +1 -2
- package/src/artifact/pikelet-artifact-range.js +0 -806
package/README.md
CHANGED
|
@@ -2,9 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
**Knowledge that ships as a file.**
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
A `.pikelet` file is a searchable corpus in a single file. It holds the source text, a vector index and a keyword (BM25) index, the neural encoder that turns a question into a vector, and the tests the pack was built to pass. Its identity is a SHA-256 digest that commits to all of it, so the file fixes not just what the corpus says but how a question reaches it: the model that encodes the question and the indexes that find candidates. **The corpus, its encoder and its indexes are one versioned artifact.** How the vector and keyword candidates are combined into one ranking (the fusion rule and BM25 parameters) belongs to the reader version, not the file, so a newer reader can order the same pack's results differently; see [FORMAT.md](FORMAT.md#operational-limitations).
|
|
6
6
|
|
|
7
|
-
The
|
|
7
|
+
The layout is built for byte-range reads. A reader opens the file from a small prefix and then fetches only the index rows and records a query needs, verifying each against the identity (a keyword index over 8 MiB is the exception: it is checked whole only by `verify_pack` with `full: true`, not on each read), so a pack can sit on disk, S3, R2, a CDN or any static HTTP host, with no vector database, embedding API or retrieval server behind it. [FORMAT.md](FORMAT.md) describes the binary structure, the embedded encoder, the indexes, the integrity commitments, versioning, compatibility and the format's limits.
|
|
8
|
+
|
|
9
|
+
**Pikelet** is the open-source toolchain for the format: a compiler (`pikelet compile`) that builds packs from folders, websites, git history or exported chats; a reader library (`pikelet-wasm`) for browsers, Node and edge workers; and an MCP server (`pikelet mcp`) that mounts packs for LLM agents.
|
|
8
10
|
|
|
9
11
|
It is built for corpora that are static or change on a release cycle: documentation, API references, manuals, standards, legal and policy texts, research corpora, and reference packs for agents.
|
|
10
12
|
|
|
@@ -13,18 +15,40 @@ It is built for corpora that are static or change on a release cycle: documentat
|
|
|
13
15
|
The `pikelet` CLI requires Node 22.23.4+, 24.22.1+ or 26.12.1+ (earlier releases' fetch decompresses whatever a server labels as encoded; 18.x and 20.x are end-of-life and cannot be fixed); the `pikelet-wasm` library runs on Node 18+, browsers, and Cloudflare Workers.
|
|
14
16
|
|
|
15
17
|
```bash
|
|
16
|
-
npx pikelet compile
|
|
18
|
+
npx pikelet compile ./docs --out docs.pikelet
|
|
17
19
|
```
|
|
18
20
|
|
|
19
21
|
```text
|
|
20
|
-
Ingested 3 docs ->
|
|
21
|
-
Embedded
|
|
22
|
-
|
|
22
|
+
Ingested 3 docs -> 16 chunks
|
|
23
|
+
Embedded 16/16 chunks with inline transformer
|
|
24
|
+
2/16 chunks exceeded the 512-token encoder window and were mean-pooled across windows
|
|
25
|
+
Validated self-recall@1 on 16 sampled chunks
|
|
26
|
+
Embedded 24 golden queries, each verified to retrieve its source
|
|
27
|
+
Built complete .pikelet artifact with 24.59 MiB
|
|
23
28
|
Compiled docs.pikelet
|
|
24
|
-
24.
|
|
29
|
+
24.59 MiB, 16 records, identity 5fcdaeac75d4...
|
|
30
|
+
Next:
|
|
31
|
+
pikelet query docs.pikelet "a question" search it here
|
|
32
|
+
pikelet mcp install --pack docs.pikelet give it to Claude Code
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Every `.pikelet` is at least ~25 MiB, because the query encoder ships inside it: a 5-file folder and a 500-file folder both start around that size. The first run downloads the encoder from a GitHub release and caches it. `--encoder-model BAAI/bge-small-en-v1.5` builds with BGE-small instead: packs about 11.5 MiB larger that retrieve better on larger corpora (see [Encoders](packages/pikelet/README.md#encoders)).
|
|
36
|
+
|
|
37
|
+
Compiling is mostly embedding, at about one chunk a second per CPU core: 828 chunks took 110 seconds on 8 cores, so a few thousand chunks take several minutes, and longer on a 2-core machine.
|
|
38
|
+
|
|
39
|
+
Search it from the terminal:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
npx pikelet query docs.pikelet "why is a pack one file"
|
|
25
43
|
```
|
|
26
44
|
|
|
27
|
-
|
|
45
|
+
```text
|
|
46
|
+
docs: 5 results
|
|
47
|
+
|
|
48
|
+
1. Why make knowledge a file
|
|
49
|
+
why-a-file.md#why-make-knowledge-a-file
|
|
50
|
+
The reasoning behind the single-artifact design. ...
|
|
51
|
+
```
|
|
28
52
|
|
|
29
53
|
Give it to an LLM — Claude Code, Claude Desktop, or any MCP client:
|
|
30
54
|
|
|
@@ -39,9 +63,9 @@ Or query it from code:
|
|
|
39
63
|
```js
|
|
40
64
|
import { openPikeletFile } from 'pikelet-wasm/complete';
|
|
41
65
|
const pack = await openPikeletFile('docs.pikelet');
|
|
42
|
-
const out = await pack.query('how
|
|
43
|
-
console.log(out.
|
|
44
|
-
// '
|
|
66
|
+
const out = await pack.query('how is a remote pack verified', { k: 5 });
|
|
67
|
+
console.log(out.results[0]?.title, out.grounding?.uncovered);
|
|
68
|
+
// 'How a .pikelet query runs' []
|
|
45
69
|
```
|
|
46
70
|
|
|
47
71
|
`compile` also takes a live URL (`--source https://docs.example.com`), a repository's commit history (`--git ./repo`), or exported chats (`--conversations <file|folder>`). To install instead of using `npx`, run `npm install -g pikelet`. `create` builds a deployed search app (a Worker and UI) rather than a file. [QUICKSTART.md](QUICKSTART.md) walks the whole lifecycle; [`packages/pikelet/README.md`](packages/pikelet/README.md) is the full CLI reference.
|
|
@@ -63,11 +87,11 @@ The complete artifact is never downloaded. The transcript and per-query table ar
|
|
|
63
87
|
|
|
64
88
|
## Packs for agents
|
|
65
89
|
|
|
66
|
-
`pikelet mcp` serves one or more packs over the Model Context Protocol, with four tools: `search`, `get_record`, `list_packs`, and `verify_pack`, which replays the tests stored inside the pack. If one pack fails to mount (an unreachable host, a refused pin), the others still serve and `list_packs` names the missing one and why.
|
|
90
|
+
`pikelet mcp` serves one or more packs over the Model Context Protocol, with four tools: `search`, `get_record`, `list_packs`, and `verify_pack`, which replays the tests stored inside the pack. If one pack fails to mount (an unreachable host, a refused pin), the others still serve and `list_packs` names the missing one and why; one on a slow host does not hold the others up past a 2 s grace.
|
|
67
91
|
|
|
68
92
|
A pack mounted with a content hash — `https://example.com/docs.pikelet#<sha256>` — has a stable identity, so "what body of knowledge did this agent query?" has a reproducible answer. A citation is `(pack identity, record id)`, and it survives updates: a chain of layers resolves citations made against its earlier versions, and a compacted pack translates them forward or reports that the record was deleted. Citation translation is a library call today (`citation(identity, id)`); the MCP tools do not expose it yet.
|
|
69
93
|
|
|
70
|
-
**A mounted pack's content reaches the model as tool output.** `verify_pack`
|
|
94
|
+
**A mounted pack's content reaches the model as tool output.** `verify_pack` reports which of the pack's bytes have been checked against its identity (with `full: true` it also checks a large pack's lexical index whole) and replays the pack's own tests; it does not prove the corpus is trustworthy. Mounting a pack from a source you don't control is the same trust decision as giving an agent any other untrusted-content tool — treat pack text like search results or fetched web pages, not as instructions.
|
|
71
95
|
|
|
72
96
|
**A journal the agent can write (experimental).** Packs are read-only to the model, with one opt-in exception: `--journal <name>` mounts a private pack the agent appends notes to — handoffs, decisions, dead ends, measurements — through `write_note` and `latest`, so a later session, from any vendor, can pick up where the work stands. Notes come back labelled agent-written and unverified. See [the CLI README](packages/pikelet/README.md#a-journal-the-agent-can-write-experimental) and [`docs/agent-journal.md`](docs/agent-journal.md).
|
|
73
97
|
|
|
@@ -88,25 +112,27 @@ npx pikelet append --parent docs.0001.pikelet --remove 412 --out docs.0002.pikel
|
|
|
88
112
|
npx pikelet mcp --pack docs.0002.pikelet
|
|
89
113
|
```
|
|
90
114
|
|
|
91
|
-
On a 20-record test pack with a 24.6 MiB base, deleting a record took a 1.2 KiB layer and replacing one took
|
|
115
|
+
On a 20-record test pack with a 24.6 MiB base, deleting a record took a 1.2 KiB layer and replacing one took 4.3 KiB. Deleting hides a record from search but does not erase it: the older files still hold its bytes, and `get_record` still serves it by id, marked `tombstoned`, so old citations resolve. `compact` writes a new base without it. Mounting the newest layer finds and verifies the rest of the chain, locally or over HTTP, and `#<sha256>` on it pins the whole history. Each layer adds a file to fetch and an index to search, so fold a long chain into a fresh base with `compact`. The format is specified in [`LAYERED_PROFILE.md`](LAYERED_PROFILE.md).
|
|
116
|
+
|
|
117
|
+
## Does the pack answer the question?
|
|
92
118
|
|
|
93
|
-
|
|
119
|
+
A nearest neighbour is not evidence that a corpus answers a question: every query returns *something*. Pikelet does not try to decide for you. Each result carries its vector `distance` (results come in hybrid order, which also weighs keyword matches, so distances are not always ascending), and each response lists the question's words missing from whichever of the top five passages contains the most of them (`grounding.uncovered`). "How do I keep snapshots forever" against a pack whose snapshot page never mentions keeping them forever comes back with `keep` and `forever` uncovered; the MCP server tells the model to cite only a passage that states the answer.
|
|
94
120
|
|
|
95
|
-
|
|
121
|
+
Earlier releases also shipped a relevance verdict (`matchQuality: strong | weak | none`) fitted at build time. On a 1,377-article Wikipedia pack it called 278 of 512 questions whose answer article was not in the pack `strong`, and agents given the verdict declined unanswerable questions no more often than agents without it: they read the passages either way. So `compile` no longer fits one; packs calibrated by earlier releases keep theirs in the library. [docs/calibration.md](docs/calibration.md#why-the-verdict-was-dropped-2026-11) has the measurements.
|
|
96
122
|
|
|
97
|
-
|
|
123
|
+
None of this is a guarantee that an LLM will never hallucinate.
|
|
98
124
|
|
|
99
125
|
## When it fits, and when it doesn't
|
|
100
126
|
|
|
101
127
|
Pikelet targets `build → publish → query many times → replace on release`, with small layered updates in between. Use it when you want search without operating search infrastructure, search inside a browser, edge worker, or offline tool, a corpus you can hand to someone else, or an agent working against a frozen, versioned body of knowledge.
|
|
102
128
|
|
|
103
|
-
Use a database instead if your corpus has heavy online writes, needs transactional mutation, serves many tenants, or already lives comfortably in one. The remote scan is linear in row count, so the design targets corpora through the low millions of records, not web scale.
|
|
129
|
+
Use a database instead if your corpus has heavy online writes, needs transactional mutation, serves many tenants, or already lives comfortably in one. The remote scan is linear in row count, so the design targets corpora through the low millions of records, not web scale. Text handling is English-first: keyword search keeps only ASCII letters and digits, so accented words are split into fragments and non-Latin words are dropped (see [Limitations](packages/pikelet/README.md#limitations)).
|
|
104
130
|
|
|
105
|
-
It is also not new retrieval research. HNSW is HNSW, BM25 is BM25, HTTP Range is HTTP Range, and the bundled MiniLM-L6 encoder was chosen for being small enough to live inside the file — ArguAna shows a real quality cost from that. The project is about arranging those pieces around one constraint: **the knowledge base itself must be distributable as a file and stay useful without retrieval infrastructure.**
|
|
131
|
+
It is also not new retrieval research. HNSW is HNSW, BM25 is BM25, HTTP Range is HTTP Range, and the bundled MiniLM-L6 encoder was chosen for being small enough to live inside the file — ArguAna shows a real quality cost from that, and BGE-small is the built-in alternative when quality matters more than size. The project is about arranging those pieces around one constraint: **the knowledge base itself must be distributable as a file and stay useful without retrieval infrastructure.**
|
|
106
132
|
|
|
107
133
|
## Deeper dives
|
|
108
134
|
|
|
109
|
-
- [How a `.pikelet` query runs](docs/how-a-query-runs.md) — what is inside the file, what a query costs on the wire, integrity checks on the read path, and
|
|
135
|
+
- [How a `.pikelet` query runs](docs/how-a-query-runs.md) — what is inside the file, what a query costs on the wire, integrity checks on the read path, and grounding.
|
|
110
136
|
- [The Wikipedia demonstration](docs/wikipedia-demonstration.md) — the agent transcript, the network table, and what cold processes cost.
|
|
111
137
|
- [The Veyra ablation](docs/veyra-ablation.md) — what happens to answers when the supporting record is edited or removed.
|
|
112
138
|
- [Why make knowledge a file](docs/why-a-file.md) — the reasoning behind the single-artifact design.
|
|
@@ -117,7 +143,7 @@ It is also not new retrieval research. HNSW is HNSW, BM25 is BM25, HTTP Range is
|
|
|
117
143
|
```text
|
|
118
144
|
packages/pikelet-wasm/ The pikelet-wasm library: C++ HNSW engine compiled to WASM
|
|
119
145
|
(used at compile time), readers and builders for .pikelet
|
|
120
|
-
packages/pikelet/ The pikelet CLI:
|
|
146
|
+
packages/pikelet/ The pikelet CLI: compile, query, MCP server, layers, journal
|
|
121
147
|
docs/ Deeper dives, design notes, measurement reports
|
|
122
148
|
spec/ Byte-level artifact contracts
|
|
123
149
|
LAYERED_PROFILE.md The layered profile: append, compact, rebase
|
|
@@ -134,10 +160,12 @@ The **range proof** uses a server that does not understand Pikelet and reports m
|
|
|
134
160
|
|
|
135
161
|
## Status
|
|
136
162
|
|
|
137
|
-
Pikelet is early: the implementation is real, the format is not frozen
|
|
163
|
+
Pikelet is early: the implementation is real, the format is not frozen, and there is one primary author. Prebuilt WASM, local and HTTP readers, the embedded encoder, BM25 hybrid retrieval, content identity with lazy-read verification (except large keyword indexes, as above), query-word grounding, MCP mounting, layered updates, and the experimental journal all ship today. `npm test` runs the engine, artifact-profile, MCP, ingestion, and format-hardening conformance suites.
|
|
138
164
|
|
|
139
165
|
Previously known as **Pancake** (renamed September 2026); files from before the rename remain readable — see [`docs/history.md`](docs/history.md). Pikelet is unrelated to the Pikelet programming language.
|
|
140
166
|
|
|
141
167
|
## License
|
|
142
168
|
|
|
143
169
|
Apache-2.0. See [LICENSE](LICENSE).
|
|
170
|
+
|
|
171
|
+
Every `.pikelet` carries its query encoder, so a pack redistributes the all-MiniLM-L6-v2 weights (quantized) and the BERT WordPiece vocabulary, both Apache-2.0. [NOTICE](NOTICE) credits them; keep it with packs you publish. A BGE-small pack redistributes the BAAI/bge-small-en-v1.5 weights (quantized, MIT) instead; its encoder declaration records the license.
|
package/complete/builder.d.ts
CHANGED
|
@@ -4,6 +4,23 @@
|
|
|
4
4
|
* the same objects the reader uses (complete/format.mjs).
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
+
import type { SketchArtifactBuildManifest, SketchArtifactBuildOptions } from '../src/pikelet.js';
|
|
8
|
+
import type { SketchRowSource } from '../src/artifact/pikelet-artifact.js';
|
|
9
|
+
|
|
10
|
+
/** Build a sketch index (spec/SKETCH_PROFILE.md) from uint8 engine snapshot bytes. */
|
|
11
|
+
export declare function buildSketchArtifactBytes(
|
|
12
|
+
snapshot: Uint8Array | ArrayBufferLike,
|
|
13
|
+
options?: SketchArtifactBuildOptions
|
|
14
|
+
): { bytes: Uint8Array; manifest: SketchArtifactBuildManifest };
|
|
15
|
+
/** Build a sketch index from quantized rows; with outPath null, returns its bytes. */
|
|
16
|
+
export declare function exportSketchArtifact(
|
|
17
|
+
index: SketchRowSource,
|
|
18
|
+
outPath: string | null,
|
|
19
|
+
options?: SketchArtifactBuildOptions
|
|
20
|
+
): SketchArtifactBuildManifest | { bytes: Uint8Array; manifest: SketchArtifactBuildManifest };
|
|
21
|
+
/** Ceiling on a sketch header's recommendedRerank (readers' default rerank depth). */
|
|
22
|
+
export declare const MAX_RECOMMENDED_RERANK: number;
|
|
23
|
+
|
|
7
24
|
export declare const MAGIC: number;
|
|
8
25
|
export declare const HEADER_BYTES: number;
|
|
9
26
|
export declare const TABLE_ENTRY_BYTES: number;
|
|
@@ -60,7 +77,8 @@ export declare function assemblePikeletFile(
|
|
|
60
77
|
|
|
61
78
|
/** Measured recall-vs-rerank operating point (SKETCH_PROFILE.md section 5). */
|
|
62
79
|
export declare function measureRecommendedRerank(input: {
|
|
63
|
-
|
|
80
|
+
/** The sketch artifact module (default: this package's own). */
|
|
81
|
+
artifactModule?: unknown;
|
|
64
82
|
sketchBytes: Uint8Array | ArrayBufferLike;
|
|
65
83
|
queryVectors?: Float32Array[] | null;
|
|
66
84
|
snapshotBytes?: Uint8Array | ArrayBufferLike | null;
|
package/complete/builder.mjs
CHANGED
|
@@ -6,6 +6,12 @@ export { buildRowMapSegment } from './rowmap.mjs';
|
|
|
6
6
|
|
|
7
7
|
export { MAGIC, HEADER_BYTES, TABLE_ENTRY_BYTES, KINDS, KIND_NAMES };
|
|
8
8
|
|
|
9
|
+
// The sketch index every pack carries (spec/SKETCH_PROFILE.md), built from an
|
|
10
|
+
// engine snapshot or from quantized rows. The artifact module has no export
|
|
11
|
+
// subpath of its own; builders reach it here.
|
|
12
|
+
import artifactContract from '../src/artifact/pikelet-artifact.js';
|
|
13
|
+
export const { buildSketchArtifactBytes, exportSketchArtifact, MAX_RECOMMENDED_RERANK } = artifactContract;
|
|
14
|
+
|
|
9
15
|
// The inline-transformer kernel via the web glue with an explicitly read
|
|
10
16
|
// wasm binary — the form that works under both native ESM and jiti's CJS
|
|
11
17
|
// transform (the node glue's createRequire bootstrap breaks there). Node
|
|
@@ -20,17 +26,16 @@ export const sha256 = (bytes) => crypto.createHash('sha256').update(bytes).diges
|
|
|
20
26
|
export const align16 = (n) => Math.ceil(n / 16) * 16;
|
|
21
27
|
|
|
22
28
|
// Canonical form = JSON.stringify semantics with sorted object keys:
|
|
23
|
-
// undefined / functions / symbols are omitted as
|
|
24
|
-
//
|
|
25
|
-
// previously they leaked through as the literal text `undefined`, producing
|
|
26
|
-
// output JSON.parse rejects.
|
|
29
|
+
// undefined / functions / symbols are omitted as properties and become null
|
|
30
|
+
// as array elements.
|
|
27
31
|
export function canonicalJson(value) {
|
|
28
32
|
if (Array.isArray(value)) {
|
|
29
33
|
return `[${value.map((v) => canonicalJson(v) ?? 'null').join(',')}]`;
|
|
30
34
|
}
|
|
31
35
|
if (value && typeof value === 'object') {
|
|
32
36
|
const parts = [];
|
|
33
|
-
|
|
37
|
+
// Code-unit order, not localeCompare: key order is part of the pack identity.
|
|
38
|
+
for (const k of Object.keys(value).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))) {
|
|
34
39
|
const serialized = canonicalJson(value[k]);
|
|
35
40
|
if (serialized !== undefined) parts.push(`${JSON.stringify(k)}:${serialized}`);
|
|
36
41
|
}
|
|
@@ -51,16 +56,11 @@ export function buildQueryInterpSegment(kind, encoderBytes, calibrationBytes) {
|
|
|
51
56
|
}
|
|
52
57
|
|
|
53
58
|
// Lexical index segment (kind 5, OPTIONAL), layout bm25-v1: a static
|
|
54
|
-
// inverted index
|
|
55
|
-
//
|
|
56
|
-
//
|
|
57
|
-
//
|
|
58
|
-
//
|
|
59
|
-
// Postings are (docIdDelta, tf) varint pairs. Document length (indexed
|
|
60
|
-
// tokens per record) and the corpus token total ship for BM25
|
|
61
|
-
// normalization. Hash collisions merge two terms' postings; at 64 bits over
|
|
62
|
-
// realistic vocabularies the probability is negligible and the failure mode
|
|
63
|
-
// is one slightly-wrong lexical score, not corruption.
|
|
59
|
+
// inverted index for hybrid retrieval. Terms are addressed by a 64-bit hash
|
|
60
|
+
// (two fnv1a-32 passes, seeds 0 and 0x9e3779b9) in a table sorted by
|
|
61
|
+
// (hashHi, hashLo), so a reader can binary search, or read lazily, without
|
|
62
|
+
// term strings. A hash collision merges two terms' postings: at 64 bits the
|
|
63
|
+
// odds are negligible and the cost is one slightly wrong score.
|
|
64
64
|
//
|
|
65
65
|
// [0,4) u32 version = 1
|
|
66
66
|
// [4,8) u32 docCount
|
|
@@ -79,25 +79,14 @@ export function buildQueryInterpSegment(kind, encoderBytes, calibrationBytes) {
|
|
|
79
79
|
// varint tf, repeated df times
|
|
80
80
|
//
|
|
81
81
|
// Indexing tokenizes on [a-z0-9']+ lowercased, keeps tokens of 2..32 chars,
|
|
82
|
-
// and skips a small
|
|
83
|
-
//
|
|
84
|
-
// no postings.
|
|
82
|
+
// and skips a small stopword list; readers need no copy of it, since an
|
|
83
|
+
// unindexed query token just finds no postings.
|
|
85
84
|
//
|
|
86
|
-
//
|
|
87
|
-
//
|
|
88
|
-
//
|
|
89
|
-
//
|
|
90
|
-
//
|
|
91
|
-
// does Elizabeth initially react to Mr. Darcy?" purely from "how does" and
|
|
92
|
-
// "darcy" co-occurring, with zero topical relevance. Confirmed live: this
|
|
93
|
-
// pushed a genuinely correct chunk (ranked #2 by the vector search alone)
|
|
94
|
-
// completely out of the fused top-10, replaced by RRF-boosted noise. Not
|
|
95
|
-
// borrowed wholesale from calibrate.mjs's COVERAGE_STOPWORDS, which also
|
|
96
|
-
// excludes domain words ("tell", "explain", "overview", "history",
|
|
97
|
-
// "definition") that are legitimate lexical CONTENT on many real corpora
|
|
98
|
-
// (a docs site literally titled "History") — this list only adds the
|
|
99
|
-
// unambiguous interrogative set, since the lexical index (unlike coverage)
|
|
100
|
-
// also indexes passage text, not just the query.
|
|
85
|
+
// Interrogatives (how/does/what/...) are stopped here too: otherwise a
|
|
86
|
+
// question's scaffolding scores BM25 matches against literal dialogue ("How
|
|
87
|
+
// does Georgiana get on, Darcy?") and pushes correct chunks out of the fused
|
|
88
|
+
// top-10. calibrate.mjs's COVERAGE_STOPWORDS is not reused: it also stops
|
|
89
|
+
// words ("history", "overview") that are real content in passage text.
|
|
101
90
|
const LEXICAL_LAYOUT = 'bm25-v1';
|
|
102
91
|
const LEXICAL_STOPWORDS = new Set(['the', 'a', 'an', 'and', 'or', 'but', 'of', 'to', 'in', 'on', 'at', 'by', 'for', 'with', 'from', 'into', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'it', 'its', 'this', 'that', 'these', 'those', 'as', 'their', 'they', 'them', 'his', 'her', 'has', 'have', 'had', 'not', 'can', 'will', 'if', 'we', 'you', 'your', 'i',
|
|
103
92
|
'how', 'does', 'did', 'do', 'what', 'who', 'why', 'where', 'when', 'which']);
|
|
@@ -125,14 +114,11 @@ function varintBytes(n) {
|
|
|
125
114
|
return out;
|
|
126
115
|
}
|
|
127
116
|
|
|
128
|
-
// Counting-sort construction over typed arrays:
|
|
129
|
-
//
|
|
130
|
-
//
|
|
131
|
-
//
|
|
132
|
-
//
|
|
133
|
-
// (docId, tf) pairs into per-term slots. Entries land doc-ascending per
|
|
134
|
-
// term by construction, which is what the delta varints need. Output
|
|
135
|
-
// bytes are identical to the original builder's.
|
|
117
|
+
// Counting-sort construction over typed arrays: a Map-of-Maps build dies
|
|
118
|
+
// around tens of millions of postings (the 456k-chunk wiki corpus has ~30M).
|
|
119
|
+
// Terms are interned and df counted on a first pass, entry arrays are
|
|
120
|
+
// preallocated, and a second pass scatters (docId, tf) pairs into per-term
|
|
121
|
+
// slots, doc-ascending as the delta varints need.
|
|
136
122
|
export function buildLexicalSegment(texts) {
|
|
137
123
|
const docCount = texts.length;
|
|
138
124
|
const doclens = new Uint32Array(docCount);
|
|
@@ -345,21 +331,17 @@ export function buildInlineTransformerEncoderSegment({ declaration, vocabBytes,
|
|
|
345
331
|
return out;
|
|
346
332
|
}
|
|
347
333
|
|
|
348
|
-
// The
|
|
349
|
-
//
|
|
350
|
-
//
|
|
351
|
-
// exact full-rerank top-k,
|
|
352
|
-
//
|
|
353
|
-
//
|
|
354
|
-
//
|
|
355
|
-
//
|
|
356
|
-
// The sweep stops at the reader's default ceiling (MAX_RECOMMENDED_RERANK):
|
|
357
|
-
// it used to fall back to the full row count, a depth readers no longer
|
|
358
|
-
// honor by default, so a pack could record a recall it would not be served
|
|
359
|
-
// at. The last rung is the ceiling, measured like any other, and
|
|
360
|
-
// targetReached says whether the target was met below it.
|
|
334
|
+
// The measured operating point (SKETCH_PROFILE.md section 5, mandatory in
|
|
335
|
+
// the evaluation segment): replay a query set against the just-built sketch
|
|
336
|
+
// at increasing rerank C and return the smallest C whose recall against the
|
|
337
|
+
// exact full-rerank top-k reaches targetRecall, plus the curve. Queries are
|
|
338
|
+
// the corpus's float embeddings when given, else rows dequantized from the
|
|
339
|
+
// snapshot. The sweep stops at the reader's default ceiling
|
|
340
|
+
// (MAX_RECOMMENDED_RERANK), so a pack never records a recall it would not be
|
|
341
|
+
// served at; targetReached says whether the target was met below it.
|
|
361
342
|
export async function measureRecommendedRerank({
|
|
362
|
-
|
|
343
|
+
// The sketch artifact module; defaults to this package's own.
|
|
344
|
+
artifactModule = artifactContract,
|
|
363
345
|
sketchBytes,
|
|
364
346
|
queryVectors = null,
|
|
365
347
|
snapshotBytes = null,
|
|
@@ -552,17 +534,28 @@ export function assemblePikeletFile(manifestFields, segments, outPath) {
|
|
|
552
534
|
header.writeBigUInt64LE(BigInt(fileBytes), 16);
|
|
553
535
|
identity.copy(header, 24);
|
|
554
536
|
|
|
555
|
-
|
|
537
|
+
// Write beside the target and rename over it: a crash mid-write, or an
|
|
538
|
+
// output that is also an input still being read, never leaves a truncated
|
|
539
|
+
// pack where a valid one was.
|
|
540
|
+
const tmpPath = `${outPath}.${process.pid}.${crypto.randomBytes(6).toString('hex')}.tmp`;
|
|
541
|
+
const fd = fs.openSync(tmpPath, 'wx');
|
|
556
542
|
try {
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
543
|
+
try {
|
|
544
|
+
fs.writeSync(fd, header, 0, header.length, 0);
|
|
545
|
+
fs.writeSync(fd, manifestBytes, 0, manifestBytes.length, HEADER_BYTES);
|
|
546
|
+
fs.writeSync(fd, table, 0, table.length, tableOffset);
|
|
547
|
+
for (const { offset, bytes } of placed) {
|
|
548
|
+
fs.writeSync(fd, bytes, 0, bytes.length, offset);
|
|
549
|
+
}
|
|
550
|
+
fs.ftruncateSync(fd, fileBytes);
|
|
551
|
+
fs.fsyncSync(fd);
|
|
552
|
+
} finally {
|
|
553
|
+
fs.closeSync(fd);
|
|
562
554
|
}
|
|
563
|
-
fs.
|
|
564
|
-
}
|
|
565
|
-
fs.
|
|
555
|
+
fs.renameSync(tmpPath, outPath);
|
|
556
|
+
} catch (error) {
|
|
557
|
+
fs.rmSync(tmpPath, { force: true });
|
|
558
|
+
throw error;
|
|
566
559
|
}
|
|
567
560
|
return { outPath, fileBytes, formatVersion, identity: identity.toString('hex'), manifest };
|
|
568
561
|
}
|
package/complete/fusion.mjs
CHANGED
|
@@ -24,6 +24,23 @@ export const FUSION_DEFAULTS = Object.freeze({
|
|
|
24
24
|
guardMargin: 0.05,
|
|
25
25
|
});
|
|
26
26
|
|
|
27
|
+
// Per-encoder overrides of FUSION_DEFAULTS, keyed by the encoder model a
|
|
28
|
+
// pack declares. A stronger encoder needs BM25 to compensate less: with
|
|
29
|
+
// BGE-small, lexicalWeight 0.25 beat 0.5 on FiQA (nDCG@10 +0.010) and
|
|
30
|
+
// TREC-COVID judged-only (+0.023) and was never worse on SciFact, NFCorpus
|
|
31
|
+
// or ArguAna, while MiniLM lost 0.039 on TREC-COVID at 0.25, so MiniLM
|
|
32
|
+
// keeps 0.5. The guard margin measured the same for both (0.02-0.1 equal;
|
|
33
|
+
// only 0 hurts), so it is not overridden.
|
|
34
|
+
export const ENCODER_FUSION_DEFAULTS = Object.freeze({
|
|
35
|
+
'BAAI/bge-small-en-v1.5': Object.freeze({ lexicalWeight: 0.25 }),
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
// The fusion defaults for a pack whose encoder declares this model.
|
|
39
|
+
export function fusionDefaultsFor(model) {
|
|
40
|
+
const override = typeof model === 'string' ? ENCODER_FUSION_DEFAULTS[model] : undefined;
|
|
41
|
+
return override ? Object.freeze({ ...FUSION_DEFAULTS, ...override }) : FUSION_DEFAULTS;
|
|
42
|
+
}
|
|
43
|
+
|
|
27
44
|
/**
|
|
28
45
|
* @param {Array<{id: number, distance: number}>} vectorOrder hits sorted by
|
|
29
46
|
* exact distance ascending (the rerank output), including every lexical
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// Grounding: which of the query's content words the best of the top
|
|
2
|
+
// passages contains (covered) and which none of them does (uncovered). It
|
|
3
|
+
// needs nothing from the pack but the passages' text, so every pack gets
|
|
4
|
+
// it, calibrated or not; an agent reads `uncovered` to tell "the passage is
|
|
5
|
+
// about this" from "the passage states this".
|
|
6
|
+
//
|
|
7
|
+
// The word rules follow the calibrated coverage term
|
|
8
|
+
// (retrieval-abstention.mjs) — possessives stripped, light suffix stemming,
|
|
9
|
+
// plural forms, heading-only matches at half credit — with two
|
|
10
|
+
// differences: a token holding a digit counts whatever its length ("v8",
|
|
11
|
+
// "3d", "4"), and every word weighs the same (the calibrated term discounts
|
|
12
|
+
// corpus-common words through a bloom only a calibration asset carries).
|
|
13
|
+
// The calibrated verdict keeps its own coverage term unchanged.
|
|
14
|
+
|
|
15
|
+
// How many passages grounding reads, in fused order.
|
|
16
|
+
export const GROUNDING_PASSAGES = 5;
|
|
17
|
+
|
|
18
|
+
const MIN_WORD_LEN = 3;
|
|
19
|
+
const STOPWORDS = new Set([
|
|
20
|
+
'the', 'a', 'an', 'and', 'or', 'but', 'of', 'to', 'in', 'on', 'at', 'by', 'for', 'with', 'from', 'into',
|
|
21
|
+
'through', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'it', 'its', 'this', 'that', 'these', 'those',
|
|
22
|
+
'as', 'their', 'they', 'them', 'also', 'can', 'will', 'which', 'when', 'where', 'while', 'his', 'her', 'has',
|
|
23
|
+
'have', 'had', 'not', 'often', 'usually', 'without',
|
|
24
|
+
// Question scaffolding, so "how does X work" is grounded by X.
|
|
25
|
+
'what', 'how', 'who', 'why', 'do', 'does', 'did', 'me', 'tell', 'about', 'explain', 'explained', 'facts',
|
|
26
|
+
'information', 'overview', 'history', 'definition', 'important', 'work', 'works', 'known', 'anything', 'said',
|
|
27
|
+
'much', 'many', 'each', 'would', 'could', 'some', 'such', 'very', 'more', 'after', 'before',
|
|
28
|
+
]);
|
|
29
|
+
const HEADING_WEIGHT = 0.5;
|
|
30
|
+
const STEM_MIN_LEN = 4;
|
|
31
|
+
const STEM_SUFFIXES = ['ization', 'isation', 'ication', 'ation', 'ition', 'tion', 'ing', 'ed', 'ate', 'ize', 'ise'];
|
|
32
|
+
|
|
33
|
+
const tokenize = (text) => String(text || '').toLowerCase().match(/[a-z0-9']+/g) || [];
|
|
34
|
+
function stem(w) {
|
|
35
|
+
for (const suf of STEM_SUFFIXES) {
|
|
36
|
+
if (w.length - suf.length >= STEM_MIN_LEN && w.endsWith(suf)) return w.slice(0, -suf.length);
|
|
37
|
+
}
|
|
38
|
+
if (w.length - 1 >= STEM_MIN_LEN && w.endsWith('e')) return w.slice(0, -1);
|
|
39
|
+
return w;
|
|
40
|
+
}
|
|
41
|
+
function stripPossessive(w) {
|
|
42
|
+
if (w.endsWith("'s")) return w.slice(0, -2);
|
|
43
|
+
if (w.endsWith("s'")) return w.slice(0, -1);
|
|
44
|
+
if (w.endsWith("'")) return w.slice(0, -1);
|
|
45
|
+
return w;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// The query words grounding grades, in query order, without repeats.
|
|
49
|
+
export function groundingWords(query) {
|
|
50
|
+
const words = tokenize(query).map(stripPossessive)
|
|
51
|
+
.filter((w) => w && (w.length >= MIN_WORD_LEN || /\d/.test(w)) && !STOPWORDS.has(w));
|
|
52
|
+
return [...new Set(words)];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Grade the query's content words against passage texts (a record's first
|
|
57
|
+
* line is its heading, as ingest writes it). Returns the best passage's
|
|
58
|
+
* { passageIndex, coverage, covered, uncovered }, or null when the query has
|
|
59
|
+
* no gradable word or there are no passages.
|
|
60
|
+
*/
|
|
61
|
+
export function groundQuery(query, passageTexts) {
|
|
62
|
+
const content = groundingWords(query);
|
|
63
|
+
if (!content.length || !passageTexts?.length) return null;
|
|
64
|
+
let best = null;
|
|
65
|
+
let bestRaw = -1;
|
|
66
|
+
passageTexts.forEach((text, passageIndex) => {
|
|
67
|
+
const s = String(text || '');
|
|
68
|
+
const nl = s.indexOf('\n');
|
|
69
|
+
const heading = nl === -1 ? s : s.slice(0, nl);
|
|
70
|
+
const body = nl === -1 ? '' : s.slice(nl + 1);
|
|
71
|
+
const bodyWords = tokenize(body).map(stripPossessive);
|
|
72
|
+
const bodySet = new Set(bodyWords);
|
|
73
|
+
const bodyStems = new Set(bodyWords.map(stem));
|
|
74
|
+
const headingSet = new Set(tokenize(heading).map(stripPossessive));
|
|
75
|
+
const presentIn = (set, stems, w) => set.has(w) || set.has(`${w}s`) || set.has(`${w}es`)
|
|
76
|
+
|| (w.endsWith('s') && set.has(w.slice(0, -1)))
|
|
77
|
+
|| (stems !== null && stems.has(stem(w)));
|
|
78
|
+
const credit = (w) => (presentIn(bodySet, bodyStems, w) ? 1 : presentIn(headingSet, null, w) ? HEADING_WEIGHT : 0);
|
|
79
|
+
const credits = content.map(credit);
|
|
80
|
+
const coverage = credits.reduce((a, c) => a + c, 0) / content.length;
|
|
81
|
+
if (coverage > bestRaw) {
|
|
82
|
+
bestRaw = coverage;
|
|
83
|
+
best = {
|
|
84
|
+
passageIndex,
|
|
85
|
+
coverage: +coverage.toFixed(3),
|
|
86
|
+
covered: content.filter((_, i) => credits[i] > 0),
|
|
87
|
+
uncovered: content.filter((_, i) => credits[i] === 0),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
return best;
|
|
92
|
+
}
|