pikelet-wasm 0.15.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 CHANGED
@@ -8,6 +8,190 @@ Through 0.6.0 these were published as `pancake-wasm` and
8
8
  packages are pre-1.0: a minor bump may carry breaking changes, and each entry lists them
9
9
  first.
10
10
 
11
+ ## pikelet-wasm 0.16.0 / pikelet 0.16.0 — 2026-11-30
12
+
13
+ Pikelet narrows to the `.pikelet` toolchain. The Cloudflare Worker
14
+ scaffold (`pikelet create`, `rebuild`, Workers AI and student builds),
15
+ the Docusaurus plugin and the retired `.pikelet-range` format leave both
16
+ packages; packs built by earlier releases still open and serve. BGE-small
17
+ becomes a built-in encoder (`compile --encoder-model
18
+ BAAI/bge-small-en-v1.5`), and the reader fuses keyword and vector results
19
+ with a weight chosen for the pack's encoder, which raises BGE packs'
20
+ scores on the larger BEIR sets and leaves MiniLM packs' rankings
21
+ unchanged. Queries on large packs get faster: rerank rows are verified in
22
+ one batch, and mid-sized packs use the WASM SIMD scan (FiQA's median
23
+ hybrid query from 88.9 to 14.1 ms). The journal gains standing notes,
24
+ crawls check robots.txt on every redirect, and ingestion no longer stalls
25
+ on long runs of spaces or brackets. MiniLM packs compile to the same
26
+ bytes as under 0.15.0. Both packages move to 0.16.0 together, and
27
+ `pikelet` requires `pikelet-wasm` ^0.16.0.
28
+
29
+ ### Compatibility
30
+
31
+ 0.16 narrows Pikelet to the `.pikelet` toolchain: `compile`, `query` and `mcp`, the
32
+ layered-pack commands (`append`, `compact`, `rebase`), `journal` and
33
+ `doctor`, plus the `pikelet-wasm` reader, builder and engine. The older
34
+ workflows below are removed. Packs built by earlier releases, including
35
+ Workers AI and student-encoder packs from the scaffold, still open,
36
+ verify and serve.
37
+
38
+ - **`pikelet create` and `pikelet rebuild` are removed**, with the
39
+ Cloudflare Worker scaffold they generated: the Worker, UI and
40
+ reindex-workflow templates, the `pikelet.config.json` format and its
41
+ schema, the Workers AI and student-encoder build modes, and the
42
+ student trainer (`tools/train_student.py`). Their flags (`--yes`,
43
+ `--no-deploy`, `--skip-abstention`, `--runtime`, `--mode`, `--artifact`,
44
+ `--model`, `--epochs`, `--student-model`, `--student-vectors`,
45
+ `--student-abstention`) are now unknown flags. A project scaffolded
46
+ by an earlier release keeps building with the `pikelet` 0.15 it pins. `pikelet` with
47
+ flags but no command used to start the scaffold; it now fails with
48
+ "No command given" and the command overview. To serve a corpus, compile
49
+ it (`pikelet compile`) and mount the file: over MCP, with `pikelet
50
+ query`, or from any static host through `pikelet-wasm/complete`.
51
+ - **The Docusaurus plugin is removed** (`pikelet/docusaurus`, the
52
+ package's only export besides `package.json`). A Docusaurus site can
53
+ compile its docs folder with `pikelet compile` and serve the pack with
54
+ the `pikelet-wasm/complete` reader. Docusaurus folders remain a
55
+ supported compile source (route mapping, `{#custom-id}` anchors).
56
+ - **The `.pikelet-range` format is retired from `pikelet-wasm`.** It was
57
+ deprecated in favour of the sketch index every `.pikelet` carries. Gone:
58
+ the `pikelet-wasm/artifact` export subpath, `Pikelet.RangeArtifact` on
59
+ every entry point, and on Node `Pikelet.buildRangeArtifact`,
60
+ `buildRangeArtifactFile` and `openRangeArtifactFile`, with their types
61
+ (`PikeletRangeArtifact`, `RangeArtifact*`). The engine API (`create`,
62
+ `add`, `search`, `export`, `restore`, ...) and the sketch artifact API
63
+ (`Pikelet.SketchArtifact`, `buildSketchArtifact*`,
64
+ `openSketchArtifactFile`, `createSketchScanner`) are unchanged.
65
+ Builders that imported the sketch helpers from the subpath get
66
+ `buildSketchArtifactBytes`, `exportSketchArtifact` and
67
+ `MAX_RECOMMENDED_RERANK` from `pikelet-wasm/complete/builder`, whose
68
+ `measureRecommendedRerank` no longer needs an `artifactModule`.
69
+ - **Hybrid results from BGE-small packs are ordered differently.** Packs
70
+ whose encoder is `BAAI/bge-small-en-v1.5` now fuse with lexical weight
71
+ 0.25 instead of 0.5 (see Added). MiniLM packs, including every pack
72
+ `compile` builds by default, rank exactly as before. Pass
73
+ `query(text, { fusion: { lexicalWeight: 0.5 } })` for the old order.
74
+
75
+ ### Added
76
+
77
+ - **`compile --encoder-model BAAI/bge-small-en-v1.5` builds a BGE-small
78
+ pack with no other flags.** The pinned u8 weights (36 MiB, MIT) download
79
+ into the model cache on first use and are checked against their digest
80
+ on every compile (`PIKELET_BGE_WEIGHTS_URL` names a mirror); the pack
81
+ declares BGE's 12-layer kernel layout and licence; queries get BGE's
82
+ retrieval prefix unless `--encoder-query-prefix` is given, and `""`
83
+ turns it off. Before, `--encoder-model` required `--encoder-weights`,
84
+ and even with them the declaration described MiniLM's 6-layer shape, so
85
+ the kernel refused the pack. BGE-small scores higher than MiniLM on the
86
+ larger BEIR sets: hybrid nDCG@10 0.744 against 0.546 on TREC-COVID,
87
+ 0.400 against 0.374 on FiQA (at the fusion defaults below). Any other model still needs
88
+ `--encoder-weights`, and the error lists the built-in encoders.
89
+ - **Fusion defaults follow the pack's encoder.** BM25 compensates less
90
+ for a stronger encoder: with BGE-small, lexical weight 0.25 beat 0.5 on
91
+ FiQA (nDCG@10 +0.010) and on TREC-COVID's judged documents (+0.023), and
92
+ was never worse on SciFact, NFCorpus or ArguAna, while MiniLM lost 0.039
93
+ on TREC-COVID at 0.25. The reader picks the defaults from the encoder
94
+ model the pack declares (a chain from its base), before a deferred
95
+ encoder loads, so existing BGE packs need no rebuild.
96
+ `pikelet-wasm/complete` exports `ENCODER_FUSION_DEFAULTS` and
97
+ `fusionDefaultsFor(model)`; `query()` takes an optional `fusion` object
98
+ (`rrfK`, `lexicalWeight`, `guardMargin`) merged over the defaults, and
99
+ `info().fusion` reports the defaults in force.
100
+
101
+ - **Standing notes in the agent journal.** `write_note` takes
102
+ `standing: true` for a note that binds all later work until it is
103
+ changed (a ground rule, constraint or convention), and
104
+ `supersedes: [ids]` (at most 20) for the earlier notes a note replaces.
105
+ A standing note stays in force until a later note lists it in
106
+ `supersedes`. An unfiltered `latest` now leads with a `standing` list:
107
+ every standing note in force, newest first, as its id, title, date and
108
+ the first 120 characters of its text (at most 200, with a
109
+ `standingWarning` when more are in force). The newest notes follow
110
+ under `notes` as before, minus any already listed as standing, so
111
+ `notes` can hold fewer than `limit` entries. `latest` with
112
+ `standing: true` lists only the standing notes, in full; a call
113
+ filtered by `kind` or `tag` leaves the section out. Before this, rules
114
+ written at a project's start dropped out of `latest` once a page of
115
+ newer notes came after them. Each note's `preview` is now cut at a
116
+ word boundary with an ellipsis instead of mid-word at 300 characters.
117
+
118
+ ### Changed
119
+
120
+ - **`pikelet query` no longer prints distances unless asked.** Results
121
+ are in hybrid order, which weighs keyword matches as well as vector
122
+ distance, so the printed distances were not always ascending and read
123
+ as a ranking error. The numbered order is the ranking; `--verbose`
124
+ adds each result's distance. `--json` and the MCP `search` response
125
+ are unchanged and still carry `distance` on every result.
126
+ - **Verified rerank rows are hashed in one batch per query.** A format-2
127
+ sketch checks every row it fetches for reranking against its SHA-256
128
+ digest page. Each row was hashed with its own awaited
129
+ `crypto.subtle.digest`, one after another, about 0.1 ms each, so a
130
+ query's first read of a few hundred rows spent tens of milliseconds
131
+ hashing. The pages and rows a query fetches are now hashed together:
132
+ with `node:crypto` in Node, or with concurrent `crypto.subtle` calls in
133
+ browsers. Every page and row is still checked before any is returned or
134
+ cached, and a mismatch fails the query as before. On the Simple English
135
+ Wikipedia pack (456k rows), vector retrieval on first-read rows went
136
+ from p50 37.7 / p99 64.1 ms to 19.4 / 27.1 ms. Results are unchanged.
137
+ - **Mid-sized packs use the WASM SIMD sketch scan.** In Node the
138
+ complete reader stages the engine's scan kernel in the background once
139
+ a sketch holds at least 1 Mi cells (rows × sketch dims), down from 16
140
+ Mi: about 5,500 rows for 384-dim embeddings (192-dim sketches), where
141
+ it was about 87,000. The JS scan costs about 6 ms per million cells
142
+ against about 0.6 ms for the kernel. Staging loads the engine once per
143
+ process (about 0.2 s and 12 MiB) while the JS scan keeps serving, so
144
+ the switch pays for itself after a few dozen queries. Hybrid queries
145
+ on BEIR FiQA (57,638 documents) went from a median of 88.9 ms to 14.1
146
+ ms, and on ArguAna (8,674) from 16.7 ms to 8.3 ms, with identical
147
+ rankings. `pikelet query`, which runs one query and exits, does not
148
+ stage it: the reader waits for staging at close, so a single query
149
+ would pay the engine load and never earn it back. Browser bundles are
150
+ unaffected: they inject a scanner through `options.sketchScanner`, and
151
+ `sketchScanner: false` still forces the JS scan.
152
+ - **The MCP server describes the ranking accurately.** The `search` tool
153
+ description and the server instructions said results were "ranked by
154
+ closeness of meaning"; they now say results come best first, ranked by
155
+ meaning and keyword match together, and that `distance` is vector
156
+ similarity only.
157
+
158
+ ### Fixed
159
+
160
+ - **The range-proof server stays inside its folder and survives bad
161
+ requests** (`benchmarks/range-proof/dumb-server.mjs`, a benchmark tool,
162
+ not part of either package). Its containment check compared paths
163
+ without a trailing separator, so an encoded slash
164
+ (`/..%2Froot-secret/file`) could read a sibling folder whose name began
165
+ with the served folder's name; it now requires the path to be the
166
+ folder or under `folder/`, and answers 403 otherwise. A malformed
167
+ percent-escape (`/%E0%A4%A`) made `decodeURIComponent` throw and the
168
+ server exit; it now answers 400. A request for a directory, the root
169
+ included, crashed it with EISDIR; it now answers 404.
170
+ - **A seed URL's redirects are checked against robots.txt before they are
171
+ fetched.** `compile --source <url>` (and `append --source <url>`)
172
+ follows the seed through up to five redirects, HTTP or meta refresh,
173
+ before crawling. Each hop was requested without a robots.txt check:
174
+ only the typed URL was checked first, and the final URL afterwards.
175
+ So a seed that redirected to another host had its page fetched before
176
+ that host's robots.txt was read, and a redirect onto a path the site's
177
+ own robots.txt disallows was fetched before the crawl refused it.
178
+ Every hop is now checked against its own origin's robots.txt, and that
179
+ origin's Crawl-delay applies, before it is requested. A seed that
180
+ redirects to a URL that is not HTTP(S) is refused with an error saying
181
+ so, where it failed with "Could not read null/robots.txt".
182
+ - **Ingestion no longer stalls on long runs of spaces, brackets or `<`.**
183
+ Several of the regular expressions that strip Markdown, read headings
184
+ and titles, flatten HTML and parse robots.txt restarted at every
185
+ character of a long run that was not followed by what they needed, so
186
+ their time grew with the square of the run: 40 KB of spaces in a
187
+ heading line took 14 s, and a crawled page or a document with a few
188
+ hundred KB of such text could hold `compile` for many minutes. They are
189
+ now linear scans (`packages/pikelet/src/text-scan.mjs`) that return
190
+ exactly what the expressions returned, so records, titles, anchors and
191
+ pack identities are unchanged. The same change covers route and
192
+ repository path trimming, the scaffold's project name, the Docusaurus
193
+ client's result links, and `clean_title` in the student trainer.
194
+
11
195
  ## pikelet-wasm 0.15.0 / pikelet 0.15.0 — 2026-11-19
12
196
 
13
197
  `pikelet mcp` and `pikelet query` stop reporting a relevance verdict, and
package/FORMAT.md CHANGED
@@ -263,8 +263,8 @@ small and full-quality:
263
263
  | Kind | Name | Encoder bytes | Trade-off |
264
264
  | ---: | --- | --- | --- |
265
265
  | 3 | `inline-transformer-v1` | the quantized transformer itself, ~24 MiB | the default; self-contained and full quality, but large |
266
- | 1 | `student-inline-v1` | a distilled student model, small | self-contained and small, lower quality; not appendable |
267
- | 2 | `external-transformers-v1` | a JSON declaration naming the model, plus test vectors | small and full quality, but the host must supply the encoder |
266
+ | 1 | `student-inline-v1` | a distilled student model, small | self-contained and small, lower quality; not appendable. Built only by releases before 0.16, which still reads it |
267
+ | 2 | `external-transformers-v1` | a JSON declaration naming the model, plus test vectors | small and full quality, but the host must supply the encoder. Built only by releases before 0.16, which still reads it; `pikelet mcp` refuses it |
268
268
 
269
269
  **Kind 3**, which `pikelet compile` writes, holds three length-prefixed
270
270
  regions:
package/README.md CHANGED
@@ -2,9 +2,9 @@
2
2
 
3
3
  **Knowledge that ships as a file.**
4
4
 
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 it is queried: the model that encodes a question, the indexes that find candidates, and the order they rank passages in. **The format makes retrieval semantics part of the versioned knowledge artifact.**
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 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, 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.
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
8
 
9
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.
10
10
 
@@ -32,7 +32,7 @@ Next:
32
32
  pikelet mcp install --pack docs.pikelet give it to Claude Code
33
33
  ```
34
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.
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
36
 
37
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
38
 
@@ -46,7 +46,7 @@ npx pikelet query docs.pikelet "why is a pack one file"
46
46
  docs: 5 results
47
47
 
48
48
  1. Why make knowledge a file
49
- why-a-file.md#why-make-knowledge-a-file · distance 0.617
49
+ why-a-file.md#why-make-knowledge-a-file
50
50
  The reasoning behind the single-artifact design. ...
51
51
  ```
52
52
 
@@ -116,7 +116,7 @@ On a 20-record test pack with a 24.6 MiB base, deleting a record took a 1.2 KiB
116
116
 
117
117
  ## Does the pack answer the question?
118
118
 
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 `distance`, 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.
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.
120
120
 
121
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.
122
122
 
@@ -128,7 +128,7 @@ Pikelet targets `build → publish → query many times → replace on release`,
128
128
 
129
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)).
130
130
 
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. 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.**
132
132
 
133
133
  ## Deeper dives
134
134
 
@@ -143,7 +143,7 @@ It is also not new retrieval research. HNSW is HNSW, BM25 is BM25, HTTP Range is
143
143
  ```text
144
144
  packages/pikelet-wasm/ The pikelet-wasm library: C++ HNSW engine compiled to WASM
145
145
  (used at compile time), readers and builders for .pikelet
146
- packages/pikelet/ The pikelet CLI: compiler, MCP server, Docusaurus plugin
146
+ packages/pikelet/ The pikelet CLI: compile, query, MCP server, layers, journal
147
147
  docs/ Deeper dives, design notes, measurement reports
148
148
  spec/ Byte-level artifact contracts
149
149
  LAYERED_PROFILE.md The layered profile: append, compact, rebase
@@ -160,7 +160,7 @@ The **range proof** uses a server that does not understand Pikelet and reports m
160
160
 
161
161
  ## Status
162
162
 
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, 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.
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.
164
164
 
165
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.
166
166
 
@@ -168,4 +168,4 @@ Previously known as **Pancake** (renamed September 2026); files from before the
168
168
 
169
169
  Apache-2.0. See [LICENSE](LICENSE).
170
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.
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.
@@ -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
- artifactModule: unknown;
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;
@@ -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
@@ -28,7 +34,8 @@ export function canonicalJson(value) {
28
34
  }
29
35
  if (value && typeof value === 'object') {
30
36
  const parts = [];
31
- for (const k of Object.keys(value).sort()) {
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))) {
32
39
  const serialized = canonicalJson(value[k]);
33
40
  if (serialized !== undefined) parts.push(`${JSON.stringify(k)}:${serialized}`);
34
41
  }
@@ -333,7 +340,8 @@ export function buildInlineTransformerEncoderSegment({ declaration, vocabBytes,
333
340
  // (MAX_RECOMMENDED_RERANK), so a pack never records a recall it would not be
334
341
  // served at; targetReached says whether the target was met below it.
335
342
  export async function measureRecommendedRerank({
336
- artifactModule,
343
+ // The sketch artifact module; defaults to this package's own.
344
+ artifactModule = artifactContract,
337
345
  sketchBytes,
338
346
  queryVectors = null,
339
347
  snapshotBytes = null,
@@ -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
@@ -212,6 +212,11 @@ export interface CompleteSearch {
212
212
  * Kind 1: null (inline student encoder, nothing external to verify).
213
213
  */
214
214
  encoderVerified: boolean | null;
215
+ /**
216
+ * The rank-fusion parameters query() applies by default: FUSION_DEFAULTS
217
+ * overridden for the pack's encoder model (ENCODER_FUSION_DEFAULTS).
218
+ */
219
+ fusion: Readonly<Required<FusionOptions>>;
215
220
  /**
216
221
  * 'per-record-sha256' on format 2 (each hydrated record verified on its
217
222
  * own range read); 'segment-sha256' on format 1 (whole-segment digests
@@ -284,6 +289,11 @@ export interface CompleteSearch {
284
289
  * metric). Abstention scores identically in every mode.
285
290
  */
286
291
  retrieval?: 'hybrid' | 'vector' | 'lexical' | 'augmented';
292
+ /**
293
+ * Rank-fusion parameters for this call, merged over the pack's defaults
294
+ * (info().fusion). Hybrid retrieval only.
295
+ */
296
+ fusion?: FusionOptions;
287
297
  rerank?: number;
288
298
  parallelism?: number;
289
299
  gap?: number;
@@ -414,6 +424,13 @@ export interface FusionOptions {
414
424
  guardMargin?: number;
415
425
  }
416
426
  export declare const FUSION_DEFAULTS: Readonly<Required<FusionOptions>>;
427
+ /**
428
+ * Per-encoder overrides of FUSION_DEFAULTS, keyed by the declared encoder
429
+ * model (BAAI/bge-small-en-v1.5: lexicalWeight 0.25).
430
+ */
431
+ export declare const ENCODER_FUSION_DEFAULTS: Readonly<Record<string, Readonly<FusionOptions>>>;
432
+ /** The fusion defaults for a pack whose encoder declares this model. */
433
+ export declare function fusionDefaultsFor(model: string | null | undefined): Readonly<Required<FusionOptions>>;
417
434
  /**
418
435
  * Fuse the exact-reranked vector order (every lexical candidate included) with the BM25 order.
419
436
  * Returns the same hit objects, reordered.
@@ -44,8 +44,8 @@ export { httpRangeSource } from './sources.mjs';
44
44
  // in-memory lexical searcher over the segment bytes already assembled by
45
45
  // buildLexicalSegment, before the artifact is written to disk.
46
46
  export { openLexicalIndex } from './lexical.mjs';
47
- export { fuseCandidates, FUSION_DEFAULTS } from './fusion.mjs';
48
- import { fuseCandidates } from './fusion.mjs';
47
+ export { fuseCandidates, FUSION_DEFAULTS, ENCODER_FUSION_DEFAULTS, fusionDefaultsFor } from './fusion.mjs';
48
+ import { fuseCandidates, fusionDefaultsFor } from './fusion.mjs';
49
49
  export {
50
50
  KERNEL_LAYOUT, KERNEL_MAX_LAYERS, expectedBlobBytes, parseInlineTransformerEncoder,
51
51
  createInlineTransformerEmbedder, INLINE_TEST_VECTOR_TEXTS,
@@ -100,13 +100,15 @@ const LAZY_QI_BYTES = 4 * 1024 * 1024;
100
100
  // transitional stance format-1 sketch rows carry — until verifyLexical()
101
101
  // streams the whole segment. options.lazyLexicalBytes overrides the size.
102
102
  const LAZY_LEXICAL_BYTES = 8 * 1024 * 1024;
103
- // The resident sketch scan is O(count * sketchDims) per query in pure JS —
104
- // ~500 ms at wiki scale (456k rows x 192 dims). At or above this many
105
- // cells the reader loads the engine's SIMD scan kernel in the background
106
- // (Node only; browser bundles inject one via options.sketchScanner) and
107
- // serves queries from it once staged. Below it, docs-scale corpora scan in
108
- // single-digit milliseconds and the engine load costs more than it saves.
109
- const SCANNER_AUTO_CELLS = 16 * 1024 * 1024;
103
+ // The resident sketch scan is O(count * sketchDims) per query in pure JS,
104
+ // about 6 ms per million cells against about 0.6 ms for the engine's SIMD
105
+ // kernel. At or above this many cells the reader stages that kernel in the
106
+ // background (Node only; browser bundles inject one via
107
+ // options.sketchScanner) and serves queries from it once staged; the JS scan
108
+ // serves until then. Staging loads the engine once per process (~0.2 s,
109
+ // ~12 MiB) and copies one byte per cell, so at this size it pays for itself
110
+ // after a few dozen queries, and below it the per-query saving is too small.
111
+ const SCANNER_AUTO_CELLS = 1024 * 1024;
110
112
  // The scanner's candidate output buffers are sized once at creation; the
111
113
  // sketch reader falls back to the JS scan for any query whose C exceeds
112
114
  // this, so an oversized rerank degrades speed, never recall.
@@ -885,7 +887,7 @@ export async function openPikeletFile(input, options = {}) {
885
887
  // (inline-transformer-v1): the pinned teacher as data, executed by
886
888
  // reader-owned kernels, verified against its own test vectors.
887
889
  let embed;
888
- let preScore = () => null;
890
+ let preScore = (_context) => null;
889
891
  let scoreQuality;
890
892
  let encoderInfo;
891
893
  let encoderVerified = null;
@@ -1286,6 +1288,10 @@ export async function openPikeletFile(input, options = {}) {
1286
1288
  ? Math.max(manifest.recommendedGap, Number(source.preferredGapBytes) || 0)
1287
1289
  : undefined;
1288
1290
 
1291
+ // Fusion defaults for this pack's declared encoder (fusion.mjs
1292
+ // ENCODER_FUSION_DEFAULTS); query({ fusion }) overrides them per call.
1293
+ const packFusion = fusionDefaultsFor(encoderInfo?.model);
1294
+
1289
1295
  // The one retrieval path behind query(): resident sketch scan plus BM25
1290
1296
  // candidates, exact rerank, rank fusion and phrase pinning. Calibration fits
1291
1297
  // on exactly this through __calibrationEvidence. excludeIds removes records
@@ -1307,6 +1313,10 @@ export async function openPikeletFile(input, options = {}) {
1307
1313
  if (!['hybrid', 'vector', 'lexical', 'augmented'].includes(retrieval)) {
1308
1314
  throw new Error(`query() retrieval must be hybrid, vector, lexical, or augmented, got ${retrieval}`);
1309
1315
  }
1316
+ if (queryOptions.fusion !== undefined && (queryOptions.fusion === null || typeof queryOptions.fusion !== 'object')) {
1317
+ throw new Error('query() fusion must be an object of rrfK, lexicalWeight and guardMargin');
1318
+ }
1319
+ const fusion = queryOptions.fusion ? { ...packFusion, ...queryOptions.fusion } : packFusion;
1310
1320
  // An excluded record must not take a candidate slot on either
1311
1321
  // side, so both sources skip it before cutting to size — BM25
1312
1322
  // before its top-n sort (scored with the full corpus's term
@@ -1369,7 +1379,7 @@ export async function openPikeletFile(input, options = {}) {
1369
1379
  fusedFull = lexicalHits.map((h) => byId.get(h.id)).filter(Boolean);
1370
1380
  } else if (retrieval !== 'augmented' && lexicalHits.length) {
1371
1381
  const lexRank = new Map(lexicalHits.map((h, i) => [h.id, i]));
1372
- fusedFull = fuseCandidates(searched, lexicalHits.map((h) => h.id));
1382
+ fusedFull = fuseCandidates(searched, lexicalHits.map((h) => h.id), fusion);
1373
1383
  // One batched hydration for phrase pinning's candidates (top lexical hits)
1374
1384
  // and coverage's (fusedFull's top few): over a range-read source each
1375
1385
  // uncached hydrate() is a round trip, so the two stages share one. A record
@@ -1436,6 +1446,8 @@ export async function openPikeletFile(input, options = {}) {
1436
1446
  metric: manifest.metric,
1437
1447
  encoder: encoderInfo,
1438
1448
  encoderVerified,
1449
+ // The fusion defaults query() applies (per encoder model).
1450
+ fusion: { ...packFusion },
1439
1451
  corpusIntegrity,
1440
1452
  fileBytes,
1441
1453
  residentBytes: sketch.residentBytes + 8 * (recordCount + 1) + (pageTable ? pageTable.length : 0),
@@ -1598,7 +1610,7 @@ export async function openPikeletFile(input, options = {}) {
1598
1610
  if (!lexicalVerified) {
1599
1611
  const seg = segments.get('lexical');
1600
1612
  const expected = new Uint8Array(32);
1601
- for (let b = 0; b < 32; b++) expected[b] = parseInt(seg.sha256.slice(2 * b, 2 * b + 2), 16);
1613
+ for (let b = 0; b < 32; b++) expected[b] = Number.parseInt(seg.sha256.slice(2 * b, 2 * b + 2), 16);
1602
1614
  await verifySegmentSha256(source, seg.offset, seg.length, expected, 'lexical segment',
1603
1615
  { chunkBytes: verifyOptions.chunkBytes, oneShotLimit: maxReadBytes });
1604
1616
  lexicalVerified = true;
@@ -52,7 +52,7 @@ export function planAppendability({ qiKind, corpusIngest = null, assertIngest =
52
52
  else if (qiKind === 2) encoderSource = 'host'; // the host supplies the named encoder
53
53
  else throw new Error(`unsupported query-interpretation kind ${qiKind} for append`);
54
54
 
55
- if (corpusIngest !== null && corpusIngest !== undefined) {
55
+ if (corpusIngest !== null) {
56
56
  if (assertIngest) {
57
57
  throw new Error('the base declares corpus.ingest; --assert-ingest would override an artifact\'s own declaration (6.1)');
58
58
  }
@@ -31,7 +31,7 @@ export const MAX_HEADS = 17;
31
31
  const isHex64 = (v) => typeof v === 'string' && /^[0-9a-f]{64}$/.test(v);
32
32
  const hexToBytes = (hex) => {
33
33
  const out = new Uint8Array(32);
34
- for (let i = 0; i < 32; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
34
+ for (let i = 0; i < 32; i++) out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
35
35
  return out;
36
36
  };
37
37
  const bytesToHex = (bytes) => [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');
@@ -32,7 +32,8 @@ const isCount = (v, max = MAX_RECORDS) => Number.isSafeInteger(v) && v >= 0 && v
32
32
  export function canonicalJson(value) {
33
33
  if (value === null || typeof value !== 'object') return JSON.stringify(value);
34
34
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
35
- const keys = Object.keys(value).filter((k) => value[k] !== undefined).sort();
35
+ // Code-unit order, not localeCompare: key order is part of the pack identity.
36
+ const keys = Object.keys(value).filter((k) => value[k] !== undefined).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
36
37
  return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(',')}}`;
37
38
  }
38
39
 
@@ -24,7 +24,7 @@
24
24
  import { openPikeletFile, readChainMemberShell, readMemberManifest, base64Bytes, LEXICAL_CANDIDATES, LEXICAL_CUTOFF } from './index.mjs';
25
25
  import { resolveParentLocation, assertConfined } from './layer-locator.mjs';
26
26
  import { httpRangeSource } from './sources.mjs';
27
- import { fuseCandidates, FUSION_DEFAULTS } from './fusion.mjs';
27
+ import { fuseCandidates, FUSION_DEFAULTS, fusionDefaultsFor } from './fusion.mjs';
28
28
  import { parseTombstoneSegment, firstSupersetViolation } from './tombstones.mjs';
29
29
  import { groundQuery, GROUNDING_PASSAGES } from './grounding.mjs';
30
30
  import { validateAgainstParent, chainIngestDeclaration, validateIngestAgainstChain, LAYER_PROFILE, MAX_DEPTH } from './layer-manifest.mjs';
@@ -212,6 +212,9 @@ export async function openPikeletChain(members, options = {}) {
212
212
  tiersRaw.push(reader.__chainTier);
213
213
  }
214
214
  const base = tiersRaw[0];
215
+ // A chain encodes with its base's encoder (4.5), so its fusion
216
+ // defaults are that encoder's (fusion.mjs ENCODER_FUSION_DEFAULTS).
217
+ const chainFusion = fusionDefaultsFor(base.encoderInfo?.model ?? base.manifest?.encoder?.model);
215
218
  if (base.manifest.profile === LAYER_PROFILE) {
216
219
  throw new Error('the first chain member is a layer, not a base: a layer opened alone would serve a fraction of a corpus (4.1)');
217
220
  }
@@ -387,6 +390,8 @@ export async function openPikeletChain(members, options = {}) {
387
390
  // 4.5: a chain's encoder IS the base's — a layer carries no
388
391
  // encoder bytes and inherits by commitment.
389
392
  encoder: base.encoderInfo ?? null,
393
+ // The fusion defaults query() applies (the base encoder's).
394
+ fusion: { ...chainFusion },
390
395
  calibrationDrift: calibration.drift,
391
396
  calibrationStatus: calibration.status,
392
397
  driftLimit: calibration.effectiveLimit,
@@ -521,7 +526,8 @@ export async function openPikeletChain(members, options = {}) {
521
526
  fusedFull = lexicalHits.map((h) => byId.get(h.id)).filter(Boolean);
522
527
  } else if (retrieval === 'hybrid' && lexicalHits.length) {
523
528
  const lexRank = new Map(lexicalHits.map((h, i) => [h.id, i]));
524
- fusedFull = fuseCandidates(searched, lexicalHits.map((h) => h.id), queryOptions.fusion);
529
+ fusedFull = fuseCandidates(searched, lexicalHits.map((h) => h.id),
530
+ queryOptions.fusion ? { ...chainFusion, ...queryOptions.fusion } : chainFusion);
525
531
  const vecRank = new Map(searched.map((h, i) => [h.id, i]));
526
532
  fusedFull = fusedFull.map((hit, i) => ({
527
533
  ...hit,
@@ -15,7 +15,7 @@ export function httpRangeSource(url, options = {}) {
15
15
  // and a Retry-After of up to a minute; honoring it (capped) beats
16
16
  // guessing. Without one, exponential backoff capped at 15 s.
17
17
  const raw = response.headers.get('retry-after');
18
- const after = raw?.trim() ? Number(raw) : NaN;
18
+ const after = raw?.trim() ? Number(raw) : Number.NaN;
19
19
  if (Number.isFinite(after) && after >= 0 && after <= 90) return after * 1000;
20
20
  return Math.min(15000, 250 * 2 ** attempt);
21
21
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pikelet-wasm",
3
- "version": "0.15.0",
3
+ "version": "0.16.0",
4
4
  "description": "Vector search engine and .pikelet artifact readers/builders, in WebAssembly. Compile a corpus into one self-contained, hash-verified search file, or use the underlying HNSW engine directly. Runs in Node.js, browsers, and Cloudflare Workers with no native dependencies.",
5
5
  "main": "src/pikelet.js",
6
6
  "types": "src/pikelet.d.ts",
@@ -59,10 +59,6 @@
59
59
  "default": "./src/pikelet.js"
60
60
  }
61
61
  },
62
- "./artifact": {
63
- "types": "./src/artifact/pikelet-artifact.d.ts",
64
- "default": "./src/artifact/pikelet-artifact.js"
65
- },
66
62
  "./complete": {
67
63
  "types": "./complete/index.d.ts",
68
64
  "workerd": "./complete/index.mjs",