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.
@@ -25,9 +25,10 @@ import { loadStudentModel, embedTextWithStudent } from './student-embedder.mjs';
25
25
  import { computeMatchQuality, computePreSearchAbstention } from './student-abstention.mjs';
26
26
  import { createAbstentionScorer } from './retrieval-abstention.mjs';
27
27
  import { openLexicalIndex, openLexicalIndexLazy } from './lexical.mjs';
28
+ import { groundQuery, GROUNDING_PASSAGES } from './grounding.mjs';
28
29
  import { parseRowMapSegment } from './rowmap.mjs';
29
30
  import { PikeletSketchArtifact } from '../src/artifact/pikelet-artifact.js';
30
- import { blobCacheGet, blobCachePut } from '../src/artifact/pikelet-artifact-common.js';
31
+ import { blobCacheGet, blobCachePut, verifySegmentSha256 } from '../src/artifact/pikelet-artifact-common.js';
31
32
  import { MAGIC, HEADER_BYTES, TABLE_ENTRY_BYTES, KINDS, KIND_NAMES } from './format.mjs';
32
33
 
33
34
  import {
@@ -43,8 +44,8 @@ export { httpRangeSource } from './sources.mjs';
43
44
  // in-memory lexical searcher over the segment bytes already assembled by
44
45
  // buildLexicalSegment, before the artifact is written to disk.
45
46
  export { openLexicalIndex } from './lexical.mjs';
46
- export { fuseCandidates, FUSION_DEFAULTS } from './fusion.mjs';
47
- import { fuseCandidates } from './fusion.mjs';
47
+ export { fuseCandidates, FUSION_DEFAULTS, ENCODER_FUSION_DEFAULTS, fusionDefaultsFor } from './fusion.mjs';
48
+ import { fuseCandidates, fusionDefaultsFor } from './fusion.mjs';
48
49
  export {
49
50
  KERNEL_LAYOUT, KERNEL_MAX_LAYERS, expectedBlobBytes, parseInlineTransformerEncoder,
50
51
  createInlineTransformerEmbedder, INLINE_TEST_VECTOR_TEXTS,
@@ -54,11 +55,9 @@ export {
54
55
 
55
56
  // Supported container formats: header formatVersion -> manifest profile.
56
57
  export const SUPPORTED_PROFILES = Object.freeze({ 1: 'pikelet-complete-v1', 2: 'pikelet-complete-v2' });
57
- // Pre-rename profile strings (2026-09): every .pikelet published before this
58
- // date — including live GitHub release assets — carries "pancake-complete-
59
- // vN" in its manifest. Readers accept both spellings indefinitely so an
60
- // already-published pack does not go dark on a reader upgrade; only
61
- // SUPPORTED_PROFILES (above) is what a fresh build ever writes.
58
+ // Pre-rename profile strings: every pack published before 2026-09-12
59
+ // (including live release assets) says "pancake-complete-vN". Readers accept
60
+ // both spellings indefinitely; builds only write SUPPORTED_PROFILES.
62
61
  const LEGACY_PROFILES = Object.freeze({ 1: 'pancake-complete-v1', 2: 'pancake-complete-v2' });
63
62
  export const CORPUS_LAYOUT_V2 = 'records-v2';
64
63
 
@@ -82,24 +81,14 @@ const SKETCH_HEADER_BYTES = 256;
82
81
  // query; the fusion rule and its constants live in fusion.mjs, shared with
83
82
  // the calibrator so fit-time rankings match what is served.
84
83
  export const LEXICAL_CANDIDATES = 24;
85
- // scoreQuality's coverage term hydrates the fused top passagesNeeded
86
- // records (asset.coverage.topK, 5 by default — see calibrate.mjs's
87
- // COVERAGE_TOP_PASSAGES) once retrieval returns. The scorer that knows
88
- // the real number is created inside retrievalScorer()'s own closure, not
89
- // reachable from here, so this is a fixed approximation used to decide
90
- // how many of fusedFull's records to include in the batched hydration
91
- // below, alongside phrase-pinning's own candidates — hydrating a couple
92
- // more than coverage strictly needs just costs a little extra bandwidth
93
- // on a cache entry that goes unread; hydrating fewer only narrows how
94
- // much of coverage's later hydration hits warm cache. Either way is
95
- // harmless: it's a batch-sizing choice, not a correctness one.
84
+ // How many fused top records to hydrate in the shared batch so the coverage
85
+ // term hits warm cache (asset.coverage.topK, 5 by default). A batch-sizing
86
+ // choice only: too many costs a little bandwidth, too few a later fetch.
96
87
  const COVERAGE_BATCH_COUNT = 5;
97
- // Only BM25 hits within this fraction of the top lexical score join fusion.
98
- // Common query terms give every matching document a near-tied score (idf
99
- // collapses them flat); a wide cutoff let that tied mass ride into fusion on
100
- // a technicality. Calibration (pikelet/src/calibrate.mjs) gathers its
101
- // evidence through this reader's own retrieval, so it is fit against the
102
- // same cutoff and fusion the reader serves.
88
+ // Only BM25 hits scoring at least top / LEXICAL_CUTOFF join fusion:
89
+ // common terms give every matching document a near-tied score that carries
90
+ // no ranking information. Calibration retrieves through this reader, so it
91
+ // is fit against the same cutoff.
103
92
  export const LEXICAL_CUTOFF = 1.5;
104
93
  // Query-interpretation segments above this size open lazily (kind 3's
105
94
  // inline encoder is ~25 MiB); smaller ones keep the one-read eager path.
@@ -108,15 +97,18 @@ const LAZY_QI_BYTES = 4 * 1024 * 1024;
108
97
  // index runs to tens of MiB): only the header and doclen array become
109
98
  // resident, term lookups interpolate into the remote table. Lazy reads are
110
99
  // committed via the manifest digest but not individually verified — the
111
- // transitional stance format-1 sketch rows carry.
100
+ // transitional stance format-1 sketch rows carry — until verifyLexical()
101
+ // streams the whole segment. options.lazyLexicalBytes overrides the size.
112
102
  const LAZY_LEXICAL_BYTES = 8 * 1024 * 1024;
113
- // The resident sketch scan is O(count * sketchDims) per query in pure JS —
114
- // ~500 ms at wiki scale (456k rows x 192 dims). At or above this many
115
- // cells the reader loads the engine's SIMD scan kernel in the background
116
- // (Node only; browser bundles inject one via options.sketchScanner) and
117
- // serves queries from it once staged. Below it, docs-scale corpora scan in
118
- // single-digit milliseconds and the engine load costs more than it saves.
119
- 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;
120
112
  // The scanner's candidate output buffers are sized once at creation; the
121
113
  // sketch reader falls back to the JS scan for any query whose C exceeds
122
114
  // this, so an oversized rerank degrades speed, never recall.
@@ -140,14 +132,10 @@ function toHex(bytes) {
140
132
 
141
133
  const isSha256Hex = (value) => typeof value === 'string' && /^[0-9a-f]{64}$/.test(value);
142
134
 
143
- // SHA-256 via WebCrypto (browser, workerd, Node 18+); node:crypto fallback
144
- // for older Node, gated on an actual Node runtime check rather than just
145
- // "WebCrypto is missing" — a browser can lack crypto.subtle too (privacy
146
- // settings, a hardened build), and a bare dynamic import('node:crypto')
147
- // there isn't a Node module resolution failure, it's a cross-origin module
148
- // fetch a browser refuses outright, surfacing as an opaque module-loading
149
- // error instead of the clear message below. Fails closed either way:
150
- // verification is not optional in this reader.
135
+ // SHA-256 via WebCrypto, with a node:crypto fallback gated on an actual Node
136
+ // runtime check: a browser can lack crypto.subtle too, and importing
137
+ // node:crypto there fails with an opaque module error instead of the clear
138
+ // one below. Fails closed either way.
151
139
  async function sha256hex(bytes) {
152
140
  if (globalThis.crypto?.subtle) {
153
141
  return toHex(new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', bytes)));
@@ -354,10 +342,18 @@ export async function verifyHostEncoder(declaration, encodeQuery, dim) {
354
342
  * base, and paying for a full open per hop only to discard it is wasteful when
355
343
  * the walk may then reject the location.
356
344
  *
357
- * Returns { identity, manifest, isLayer, parent }. The identity check is the
358
- * same one openPikeletFile makes, so a tampered manifest fails here too.
345
+ * Returns { identity, manifest, isLayer, parent }. The header is held to the
346
+ * same plausibility checks, and the manifest to the same identity check, as
347
+ * openPikeletFile makes, so a tampered manifest fails here too. With
348
+ * options.expectedIdentity, a header naming another identity is refused
349
+ * before the manifest is read; the error carries code 'IDENTITY_MISMATCH'
350
+ * and the header's `identity`.
359
351
  */
360
352
  export async function readMemberManifest(input, options = {}) {
353
+ const expected = options.expectedIdentity;
354
+ if (expected !== undefined && (typeof expected !== 'string' || !/^[0-9a-f]{64}$/i.test(expected))) {
355
+ throw new Error('options.expectedIdentity must be a sha256 hex string');
356
+ }
361
357
  const source = typeof input === 'string' ? await fileSource(input) : input;
362
358
  const owned = typeof input === 'string';
363
359
  const maxReadBytes = resolveBudget(options.maxReadBytes, 'maxReadBytes', DEFAULT_OPEN_READ_BYTES);
@@ -366,14 +362,34 @@ export async function readMemberManifest(input, options = {}) {
366
362
  const hv = viewOf(header);
367
363
  if (hv.getUint32(0, true) !== MAGIC) throw new Error('not a .pikelet file (bad magic)');
368
364
  const manifestBytes = hv.getUint32(8, true);
369
- const identity = [...new Uint8Array(header.buffer, header.byteOffset + 24, 32)]
370
- .map((b) => b.toString(16).padStart(2, '0')).join('');
365
+ const segmentCount = hv.getUint32(12, true);
366
+ const identity = toHex(header.subarray(24, 56));
371
367
  const fileBytes = u64(hv, 16, 'header fileBytes');
368
+ if (manifestBytes < 2 || manifestBytes > MAX_MANIFEST_BYTES || segmentCount < 1 || segmentCount > MAX_SEGMENTS
369
+ || HEADER_BYTES + manifestBytes + segmentCount * TABLE_ENTRY_BYTES > fileBytes) {
370
+ throw new Error('.pikelet header is implausible');
371
+ }
372
+ if (Number.isSafeInteger(source.size) && source.size !== fileBytes) {
373
+ throw new Error(`.pikelet is truncated or padded: header says ${fileBytes} bytes, source has ${source.size}`);
374
+ }
375
+ // A pinned identity is refused one header read in: the wrong
376
+ // artifact's manifest is never fetched or hashed.
377
+ if (expected !== undefined && identity !== expected.toLowerCase()) {
378
+ throw Object.assign(
379
+ new Error(`.pikelet identity mismatch: expected ${expected.toLowerCase()}, found ${identity}`),
380
+ { code: 'IDENTITY_MISMATCH', identity });
381
+ }
372
382
  const manifestBuf = await readChecked(source, HEADER_BYTES, manifestBytes, 'manifest', maxReadBytes, fileBytes);
373
383
  if (await sha256hex(manifestBuf) !== identity) {
374
384
  throw new Error('.pikelet manifest failed identity verification');
375
385
  }
376
- const manifest = JSON.parse(decoder.decode(manifestBuf));
386
+ let manifest;
387
+ try { manifest = JSON.parse(decoder.decode(manifestBuf)); } catch (err) {
388
+ throw new Error('.pikelet manifest is not valid JSON', { cause: err });
389
+ }
390
+ if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) {
391
+ throw new Error('.pikelet manifest is not a JSON object');
392
+ }
377
393
  const isLayer = manifest.profile === 'pikelet-layer-v1';
378
394
  return {
379
395
  identity,
@@ -449,7 +465,13 @@ export async function readChainMemberShell(input, options = {}) {
449
465
  if (await sha256hex(manifestBuf) !== identity) {
450
466
  throw new Error('.pikelet manifest failed identity verification');
451
467
  }
452
- const manifest = JSON.parse(decoder.decode(manifestBuf));
468
+ let manifest;
469
+ try { manifest = JSON.parse(decoder.decode(manifestBuf)); } catch (err) {
470
+ throw new Error('.pikelet manifest is not valid JSON', { cause: err });
471
+ }
472
+ if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) {
473
+ throw new Error('.pikelet manifest is not a JSON object');
474
+ }
453
475
  if (manifest.profile !== 'pikelet-layer-v1' || formatVersion !== 2) {
454
476
  return { tombstoneOnly: false, tier: null, close };
455
477
  }
@@ -459,10 +481,8 @@ export async function readChainMemberShell(input, options = {}) {
459
481
  if (!Array.isArray(manifest.segments) || manifest.segments.length !== segmentCount) {
460
482
  throw new Error('.pikelet manifest segment list disagrees with the header segment count');
461
483
  }
462
- // The same table checks as the full open. This path used to keep only
463
- // length and digest shape: it never compared the table's kind with the
464
- // manifest's and let a later duplicate overwrite an earlier one, so
465
- // whoever controls the table bytes (a mirror) could relabel another
484
+ // The same table checks as the full open (kind, order, no duplicates):
485
+ // otherwise whoever controls the table bytes could relabel another
466
486
  // committed segment as the tombstone mask without changing identity.
467
487
  const table = await readChecked(source, HEADER_BYTES + manifestBytes, segmentCount * TABLE_ENTRY_BYTES, 'segment table', maxReadBytes, fileBytes);
468
488
  const segments = parseSegmentTable(table, manifest, segmentCount, manifestBytes, fileBytes);
@@ -504,6 +524,7 @@ export async function openPikeletFile(input, options = {}) {
504
524
  }
505
525
  const maxReadBytes = resolveBudget(options.maxReadBytes, 'maxReadBytes', DEFAULT_OPEN_READ_BYTES);
506
526
  const maxRecordBytes = resolveBudget(options.maxRecordBytes, 'maxRecordBytes', DEFAULT_RECORD_BYTES);
527
+ const lazyLexicalBytes = resolveBudget(options.lazyLexicalBytes, 'lazyLexicalBytes', LAZY_LEXICAL_BYTES);
507
528
  const verifyRecords = options.verifyRecords !== false;
508
529
  // Opt-in full authentication of the lazy rerank rows at open: one
509
530
  // streamed pass over the vectors segment against the (identity-anchored)
@@ -606,11 +627,8 @@ export async function openPikeletFile(input, options = {}) {
606
627
 
607
628
  const table = await readChecked(source, HEADER_BYTES + manifestBytes, tableBytes, 'segment table', maxReadBytes, fileBytes);
608
629
  const segments = parseSegmentTable(table, manifest, segmentCount, manifestBytes, fileBytes);
609
- // The evaluation segment, read and hash-verified. Named so both the
610
- // reader's own evaluation() and the __chainTier seam can reach it: a
611
- // chain has no evaluation segment of its own, and `verify_pack` called
612
- // `search.evaluation()` on a chain reader that had no such method,
613
- // which threw a TypeError instead of reporting the base's goldens.
630
+ // The evaluation segment, read and hash-verified. Shared by evaluation()
631
+ // and the __chainTier seam, since a chain surfaces its base's (6.2).
614
632
  const readEvaluationSegment = async () => {
615
633
  const ev = segments.get('evaluation');
616
634
  if (!ev) return null;
@@ -627,16 +645,10 @@ export async function openPikeletFile(input, options = {}) {
627
645
  }
628
646
  return parsed;
629
647
  };
630
- // The lineage segment (kind 7, LAYERED_PROFILE.md 6.3), parsed and
631
- // validated on first use. Present only on a base compacted from a
632
- // chain. buildLineageSegment wrote it and parseLineageSegment validated
633
- // it, but nothing on the read side ever reached either: a real
634
- // compacted pack could not translate a citation, which is the whole
635
- // point of the segment ("what lets a consumer treat a translated
636
- // citation as evidence rather than as a hint").
637
- //
638
- // Cached because the validation is not free and the segment is
639
- // immutable; the cache holds the parse, never a translation.
648
+ // The lineage segment (kind 7, LAYERED_PROFILE.md 6.3), present only on a
649
+ // base compacted from a chain; it is what lets citation() translate old ids.
650
+ // Parsed and validated on first use and cached (the parse, never a
651
+ // translation).
640
652
  let lineageCache;
641
653
  const readLineageSegment = async () => {
642
654
  if (lineageCache !== undefined) return lineageCache;
@@ -654,11 +666,9 @@ export async function openPikeletFile(input, options = {}) {
654
666
  return lineageCache;
655
667
  };
656
668
 
657
- // oldId -> new dense id, by 6.3's rule: a surviving id loses one
658
- // position per tombstone below it. The per-byte prefix table is built
659
- // once and reused, because the naive form rescans the bitset from zero
660
- // on every call -- O(id) per citation, quadratic over a run of them on
661
- // a large pack.
669
+ // oldId -> new dense id (6.3): a surviving id loses one position per
670
+ // tombstone below it. A per-byte prefix table keeps this O(1) per citation
671
+ // instead of rescanning the bitset.
662
672
  let compactPrefix;
663
673
  const compactMapFor = (lineage) => {
664
674
  if (compactPrefix === undefined) {
@@ -683,12 +693,9 @@ export async function openPikeletFile(input, options = {}) {
683
693
  };
684
694
 
685
695
  // Required segments are per-profile (layered profile 4.3). A layer with
686
- // records carries a tombstones segment on top of the complete set; a
687
- // TOMBSTONE-ONLY layer has neither an index nor a corpus segment and is
688
- // therefore not opened through this function at all — the chain reader
689
- // reads its two segments directly (see openPikeletChain), because
690
- // threading "no index, no corpus" through the whole of this open would
691
- // put a branch on every step of the single-file path.
696
+ // records adds a tombstones segment; a tombstone-only layer has no index or
697
+ // corpus and is read directly by the chain reader (see openPikeletChain),
698
+ // never through this open.
692
699
  if (acceptLayer && manifest.layer?.records === 0) {
693
700
  throw new Error('a tombstone-only layer is read by the chain reader, not opened as a member');
694
701
  }
@@ -755,21 +762,15 @@ export async function openPikeletFile(input, options = {}) {
755
762
  throw new Error('.pikelet manifest carries no index header commitment (index.headerSha256)');
756
763
  }
757
764
 
758
- // After the segment table, every remaining open-path extent is known,
759
- // so the query-interp segment, the embedded sketch (two dependent
760
- // reads of its own), and the corpus tables fetch as one concurrent
761
- // wave instead of dependent rounds — at 100 ms/request that is most
762
- // of the open time.
763
- // A large query-interpretation segment (kind 3's inline encoder is
764
- // ~25 MiB) is not read at open: only its 16-byte header joins the
765
- // wave, the calibration region follows as one small dependent read,
766
- // and the encoder bytes arrive lazily — prefetched in the background
767
- // by default, awaited by the first query. The whole-segment digest
768
- // is verified when those bytes arrive, and the header/calibration
769
- // slices used at open are byte-compared against the verified
770
- // segment before any query can complete, so nothing unverified ever
771
- // influences a returned result. Small segments (kinds 1/2) keep the
772
- // one-read eager path unchanged.
765
+ // After the segment table every open-path extent is known, so the
766
+ // query-interp segment, the embedded sketch and the corpus tables fetch as
767
+ // one concurrent wave instead of dependent rounds.
768
+ // A large query-interp segment (kind 3's ~25 MiB encoder) is not read at
769
+ // open: its header joins the wave, the calibration region follows, and the
770
+ // encoder bytes arrive lazily (prefetched in the background, awaited by the
771
+ // first query). The header and calibration slices are byte-compared against
772
+ // the digest-verified segment before any query can complete, so nothing
773
+ // unverified influences a result.
773
774
  const qiDeferrable = qi.length > LAZY_QI_BYTES;
774
775
  const [qiFirst, sketch, tables, lexicalBytes, rowMapBytes] = await Promise.all([
775
776
  (async () => {
@@ -798,7 +799,7 @@ export async function openPikeletFile(input, options = {}) {
798
799
  // predate the kind skip it (spec 3.3).
799
800
  segments.has('lexical') ? (async () => {
800
801
  const seg = segments.get('lexical');
801
- if (seg.length > LAZY_LEXICAL_BYTES) {
802
+ if (seg.length > lazyLexicalBytes) {
802
803
  // Confined to the segment's own window: lazy reads are
803
804
  // not individually verified, so no field they carry may
804
805
  // steer a read into another segment.
@@ -835,6 +836,9 @@ export async function openPikeletFile(input, options = {}) {
835
836
  if (lexicalIndex && lexicalIndex.docCount !== declaredRecords) {
836
837
  throw new Error(`.pikelet lexical segment covers ${lexicalIndex.docCount} records, corpus declares ${declaredRecords}`);
837
838
  }
839
+ // An eager segment was hashed whole above; a lazy one only once
840
+ // verifyLexical() has streamed it.
841
+ let lexicalVerified = Boolean(lexicalIndex && !lexicalIndex.lazy);
838
842
 
839
843
  // Query interpretation: version word, kind, two length-prefixed
840
844
  // regions that must tile the segment exactly.
@@ -883,7 +887,7 @@ export async function openPikeletFile(input, options = {}) {
883
887
  // (inline-transformer-v1): the pinned teacher as data, executed by
884
888
  // reader-owned kernels, verified against its own test vectors.
885
889
  let embed;
886
- let preScore = () => null;
890
+ let preScore = (_context) => null;
887
891
  let scoreQuality;
888
892
  let encoderInfo;
889
893
  let encoderVerified = null;
@@ -892,30 +896,16 @@ export async function openPikeletFile(input, options = {}) {
892
896
  const VERDICTS = { answer: 'strong', weak: 'weak', abstain: 'none' };
893
897
  return async (hits, context, fusedHits, scoreOptions) => {
894
898
  if (!scorer) return { match_quality: 'unscored' };
895
- // The coverage term grounds the verdict in the top passages'
896
- // text, so those records hydrate before scoring. Hydrated
897
- // from the fused (RRF) order when hybrid retrieval produced
898
- // one — calibrate.mjs fits coverage against the same fused
899
- // ranking, and a chunk BM25 ranks first but the embedding
900
- // ranks far down is exactly the case coverage exists to
901
- // catch; scoring it against vector-only order would miss it
902
- // again. Falls back to vector order (hits) when there is no
903
- // lexical segment or fusion did not change anything. When
904
- // the query is answered the pages are already hot for
905
- // result hydration; an abstained query costs these extra
906
- // reads. Hydration failures propagate — on format 2 a
907
- // record that fails its digest must fail the query, not
908
- // skew its verdict.
899
+ // The coverage term grounds the verdict in the top passages' text, so they
900
+ // hydrate before scoring, from the fused order when there is one (as
901
+ // calibrate.mjs fits it) and from vector order otherwise. Hydration failures
902
+ // propagate: on format 2 a record that fails its digest must fail the query,
903
+ // not skew its verdict.
909
904
  const passageSource = fusedHits?.length ? fusedHits : hits;
910
- // A record's text starts with its own heading echoed as the
911
- // first line (ingest.mjs's section-to-chunk join). A
912
- // heading match still grounds the query but at reduced
913
- // credit — see retrieval-abstention.mjs's coverageFrac and
914
- // calibrate.mjs's HEADING_COVERAGE_WEIGHT, which this split
915
- // must match exactly (build-time and serve-time coverage
916
- // must agree, or the fitted thresholds are scoring a
917
- // different signal than the one they were calibrated
918
- // against).
905
+ // A record's text starts with its heading (ingest.mjs). Coverage gives a
906
+ // heading match reduced credit, and this split must match
907
+ // retrieval-abstention.mjs's coverageFrac and calibrate.mjs exactly, or the
908
+ // thresholds score a different signal than the one they were fit on.
919
909
  const splitHeadingBody = (text) => {
920
910
  const nl = String(text || '').indexOf('\n');
921
911
  return nl === -1 ? { heading: text, body: '' } : { heading: text.slice(0, nl), body: text.slice(nl + 1) };
@@ -1108,19 +1098,14 @@ export async function openPikeletFile(input, options = {}) {
1108
1098
  }
1109
1099
 
1110
1100
  // Resident-scan acceleration. options.sketchScanner:
1111
- // false — pure JS scan always (the pre-0.7 behavior);
1112
- // an object — a ready scanner (createSketchScanner's shape),
1113
- // caller-owned, used as-is;
1114
- // a function — async factory (sketchArtifact) => scanner, invoked
1115
- // in the background once the sketch is fully resident
1116
- // (the injection point for browser bundles, which
1117
- // cannot load the Node engine entrypoint);
1118
- // undefined — auto: in Node, when the corpus is large enough
1119
- // that the JS scan dominates query time, stage the
1120
- // engine's SIMD scan kernel in the background.
1121
- // Staging failures are silent by design: every query the scanner
1122
- // would have served is answered identically (and identically
1123
- // correctly) by the JS scan, just slower.
1101
+ // false - pure JS scan always;
1102
+ // an object - a ready scanner (createSketchScanner's shape), caller-owned;
1103
+ // a function - async factory (sketchArtifact) => scanner, run in the
1104
+ // background once the sketch is resident (the injection point
1105
+ // for browser bundles, which cannot load the Node engine);
1106
+ // undefined - auto: in Node, stage the engine's SIMD scan kernel when the
1107
+ // corpus is large enough for the JS scan to dominate.
1108
+ // Staging failures are silent: the JS scan answers identically, only slower.
1124
1109
  const scannerOption = options.sketchScanner;
1125
1110
  if (scannerOption !== undefined && scannerOption !== false
1126
1111
  && typeof scannerOption !== 'object' && typeof scannerOption !== 'function') {
@@ -1294,61 +1279,44 @@ export async function openPikeletFile(input, options = {}) {
1294
1279
  if (closed) throw new Error('.pikelet reader is closed');
1295
1280
  };
1296
1281
 
1297
- // The rerank's default coalescing gap. The identity-verified manifest
1298
- // may carry a fetch hint: cluster-ordered layouts only coalesce at a
1299
- // gap at least matched to their cluster geometry (the wiki pack's
1300
- // k-means layout needs ~16 KiB; a 2 KiB gap squanders it — measured
1301
- // 440 vs 200 requests/query at C=600). The hint is a floor: a wider
1302
- // gap merges a superset of the same runs, so a source that prefers
1303
- // more (HTTP's 256 KiB) keeps its own. undefined leaves the sketch
1304
- // reader on the source's preference. A chain reads it per tier
1305
- // through __chainTier.
1282
+ // The rerank's default coalescing gap. A manifest fetch hint sets a floor
1283
+ // matched to cluster-ordered layouts (the wiki pack's k-means layout needs
1284
+ // ~16 KiB: 440 vs 200 requests/query at C=600 with a 2 KiB gap); a source
1285
+ // that prefers a wider gap (HTTP's 256 KiB) keeps its own. A chain reads it
1286
+ // per tier through __chainTier.
1306
1287
  const rerankGapHint = Number.isFinite(manifest.recommendedGap)
1307
1288
  ? Math.max(manifest.recommendedGap, Number(source.preferredGapBytes) || 0)
1308
1289
  : undefined;
1309
1290
 
1310
- // The one retrieval path behind query(): resident sketch scan plus
1311
- // BM25 candidates, exact rerank, rank fusion and phrase pinning.
1312
- // Compile-time calibration fits on exactly this (through
1313
- // __calibrationEvidence below), so the evidence a verdict was fit on
1314
- // is the evidence query() scores. excludeIds removes records from
1315
- // both candidate sources before either is cut to size — calibration
1316
- // ablations use it; query() never does.
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
+
1295
+ // The one retrieval path behind query(): resident sketch scan plus BM25
1296
+ // candidates, exact rerank, rank fusion and phrase pinning. Calibration fits
1297
+ // on exactly this through __calibrationEvidence. excludeIds removes records
1298
+ // from both candidate sources before either is cut to size (calibration
1299
+ // ablations only).
1317
1300
  const retrieveCandidates = async (trimmed, context, k, queryOptions, excludeIds = null) => {
1318
1301
  let fusedFull = null;
1319
- // Hybrid retrieval when the artifact carries a lexical
1320
- // segment: the BM25 top matches join the sketch's exact
1321
- // rerank as extra candidates (scored by true vector
1322
- // distance like any candidate — this is what recovers
1323
- // known-item lookups the sketch scan's top-C missed),
1324
- // and the final ordering fuses the distance ranking
1325
- // with the BM25 ranking by reciprocal rank (RRF, k=60,
1326
- // untuned). Abstention still scores the distance-sorted
1327
- // top-k exactly as calibrated; fusion affects result
1328
- // order only. fullRerankOutput returns every reranked
1329
- // candidate (all already fetched and exactly scored) so
1330
- // fusion sees the true distance of every lexical match.
1331
- // Common query terms give every matching document a
1332
- // small, near-tied BM25 score (idf collapses them);
1333
- // that flat mass carries no ranking information and
1334
- // dilutes rank fusion. Keep only hits within a factor
1335
- // of the best lexical score — for a known-item lookup
1336
- // that is typically the one document holding the rare
1337
- // terms.
1338
- // retrieval: 'hybrid' (default when the artifact
1339
- // carries a lexical segment) | 'vector' | 'lexical' —
1340
- // the last two exist for measurement and debugging
1341
- // (retrieval-quality bakeoffs run all three on one
1342
- // artifact). Abstention scores the distance-sorted
1343
- // top-k identically in every mode.
1344
- // 'augmented' unions the lexical candidates into the
1345
- // exact rerank but keeps pure distance order — the mode
1346
- // for workloads scored against exact nearest neighbors,
1347
- // where RRF's reordering reads as loss by definition.
1302
+ // retrieval: 'hybrid' (default with a lexical segment) - BM25 top matches
1303
+ // join the exact rerank as extra candidates (recovering known items the
1304
+ // sketch's top-C missed), and the final order fuses distance and BM25 ranks
1305
+ // (fuseCandidates, fusion.mjs); near-tied low BM25 scores are cut first
1306
+ // (LEXICAL_CUTOFF).
1307
+ // 'augmented' - lexical candidates join the rerank but order stays by pure
1308
+ // distance, for workloads scored against exact nearest neighbors.
1309
+ // 'vector' | 'lexical' - for measurement and debugging.
1310
+ // Abstention scores the distance-sorted window identically in every mode;
1311
+ // fusion changes result order only.
1348
1312
  const retrieval = queryOptions.retrieval ?? 'hybrid';
1349
1313
  if (!['hybrid', 'vector', 'lexical', 'augmented'].includes(retrieval)) {
1350
1314
  throw new Error(`query() retrieval must be hybrid, vector, lexical, or augmented, got ${retrieval}`);
1351
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;
1352
1320
  // An excluded record must not take a candidate slot on either
1353
1321
  // side, so both sources skip it before cutting to size — BM25
1354
1322
  // before its top-n sort (scored with the full corpus's term
@@ -1387,12 +1355,8 @@ export async function openPikeletFile(input, options = {}) {
1387
1355
  ...(scanner ? { scanner } : {}),
1388
1356
  ...(extraRows.length ? { extraCandidates: extraRows } : {}),
1389
1357
  ...(excludeBits ? { exclude: excludeBits } : {}),
1390
- // Always return the full reranked candidate list
1391
- // (already fetched and exactly scored) rather than
1392
- // truncating to k: abstention is fit at a fixed
1393
- // top-10 window (calibrate.mjs) independent of the
1394
- // caller's k, and needs that full window to score
1395
- // consistently — see retrieval-abstention.mjs.
1358
+ // Return the full reranked list, not k: abstention is fit at a fixed
1359
+ // top-10 window independent of the caller's k (retrieval-abstention.mjs).
1396
1360
  fullRerankOutput: true,
1397
1361
  })).results;
1398
1362
  // The rerank output is distance-ordered, so a record's first row
@@ -1408,38 +1372,19 @@ export async function openPikeletFile(input, options = {}) {
1408
1372
  }
1409
1373
  }
1410
1374
  const hits = searched.slice(0, k);
1411
- // Full-window fused order (not k-truncated) for scoring:
1412
- // coverage grounds its verdict in the passage fusion
1413
- // actually ranks first, and calibrate.mjs fits it the
1414
- // same way — a k-truncated fused list would silently
1415
- // drop the fused top hit for callers requesting a small k.
1375
+ // Full-window fused order for scoring: a k-truncated list would drop the
1376
+ // fused top hit that coverage grades for callers asking for a small k.
1416
1377
  if (retrieval === 'lexical') {
1417
1378
  const byId = new Map(searched.map((hit) => [hit.id, hit]));
1418
1379
  fusedFull = lexicalHits.map((h) => byId.get(h.id)).filter(Boolean);
1419
1380
  } else if (retrieval !== 'augmented' && lexicalHits.length) {
1420
1381
  const lexRank = new Map(lexicalHits.map((h, i) => [h.id, i]));
1421
- fusedFull = fuseCandidates(searched, lexicalHits.map((h) => h.id));
1422
- // One batched hydration for everything this block and
1423
- // scoreQuality's coverage term (below) will need, in
1424
- // place of two separate staged fetches (phrase-pin's
1425
- // own, then a later cold start for coverage): over a
1426
- // remote range-read source each hydrate() a caller
1427
- // hasn't already paid for is its own network round
1428
- // trip, and sequential/staged awaits pay that cost
1429
- // once per stage instead of once per query. The
1430
- // union of phrase-pin's candidates (top lexical
1431
- // hits) and coverage's (fusedFull's top few — phrase
1432
- // pinning only ever reorders that window, never
1433
- // changes its membership) is known right here, so
1434
- // both stages can share one round trip. A record
1435
- // that fails to hydrate here does not fail the
1436
- // query: the id is just missing from the map, and
1437
- // each site below falls through exactly as it would
1438
- // on a cold cache miss (recs[i] undefined; coverage
1439
- // sees fewer usable passages) — hydrate() raising
1440
- // for a bad id is still a real failure, but only
1441
- // once a site actually needs that specific record,
1442
- // not speculatively for every candidate touched here.
1382
+ fusedFull = fuseCandidates(searched, lexicalHits.map((h) => h.id), fusion);
1383
+ // One batched hydration for phrase pinning's candidates (top lexical hits)
1384
+ // and coverage's (fusedFull's top few): over a range-read source each
1385
+ // uncached hydrate() is a round trip, so the two stages share one. A record
1386
+ // that fails here does not fail the query; it is just missing from the map,
1387
+ // and a site that actually needs it hydrates (and fails) itself.
1443
1388
  const phraseCandidates = lexicalHits.slice(0, 3);
1444
1389
  const coverageCandidates = fusedFull.slice(0, COVERAGE_BATCH_COUNT);
1445
1390
  const batchIds = [...new Set([...phraseCandidates, ...coverageCandidates].map((h) => h.id))];
@@ -1474,11 +1419,8 @@ export async function openPikeletFile(input, options = {}) {
1474
1419
  identity,
1475
1420
  formatVersion,
1476
1421
  profile,
1477
- // 6.3: present when this base was compacted from a chain,
1478
- // and the key to whether citation() can say anything. It
1479
- // was in the manifest all along and reported nowhere, so a
1480
- // compacted pack looked indistinguishable from a freshly
1481
- // compiled one.
1422
+ // 6.3: present when this base was compacted from a chain, and the key to
1423
+ // whether citation() can say anything.
1482
1424
  compactedFrom: manifest.compactedFrom
1483
1425
  && typeof manifest.compactedFrom === 'object'
1484
1426
  && !Array.isArray(manifest.compactedFrom)
@@ -1504,6 +1446,8 @@ export async function openPikeletFile(input, options = {}) {
1504
1446
  metric: manifest.metric,
1505
1447
  encoder: encoderInfo,
1506
1448
  encoderVerified,
1449
+ // The fusion defaults query() applies (per encoder model).
1450
+ fusion: { ...packFusion },
1507
1451
  corpusIntegrity,
1508
1452
  fileBytes,
1509
1453
  residentBytes: sketch.residentBytes + 8 * (recordCount + 1) + (pageTable ? pageTable.length : 0),
@@ -1529,6 +1473,10 @@ export async function openPikeletFile(input, options = {}) {
1529
1473
  // Lazy reads are bounded to the segment but not
1530
1474
  // individually verified (LAZY_LEXICAL_BYTES).
1531
1475
  integrity: lexicalIndex.lazy ? 'unverified-lazy-reads' : 'segment-sha256',
1476
+ // True once the whole segment matched its digest:
1477
+ // at open for an eager segment, after
1478
+ // verifyLexical() for a lazy one.
1479
+ verified: lexicalVerified,
1532
1480
  ...(lexicalIndex.lazy ? { lazy: true } : {}),
1533
1481
  }
1534
1482
  : null,
@@ -1569,17 +1517,11 @@ export async function openPikeletFile(input, options = {}) {
1569
1517
  let searched = null;
1570
1518
  let fusedFull = null;
1571
1519
  if (!pre) ({ hits, fused, searched, fusedFull } = await retrieveCandidates(trimmed, context, k, queryOptions));
1572
- // Abstention scores the full reranked candidate window
1573
- // (searched), not the k-truncated hits: calibrate.mjs fits
1574
- // its signals at a fixed top-10 (top-5 for coverage)
1575
- // regardless of how many results a caller ultimately
1576
- // requests, so scoring must use the same window to match.
1577
- // preScore (kind 1) runs before search and has no window to
1578
- // fix, so it is unaffected. fusedFull (RRF over the same
1579
- // full window, not k-truncated) is threaded through
1580
- // separately so coverage grades the passage fusion actually
1581
- // ranks first, while d0/margin/mean10 still read vector
1582
- // order (searched) exactly as calibrated.
1520
+ // Abstention scores the full reranked window (searched), not the
1521
+ // k-truncated hits, because calibration fits at a fixed top-10 (top-5 for
1522
+ // coverage). fusedFull lets coverage grade the passage fusion ranks first,
1523
+ // while d0/margin/mean10 read vector order as calibrated. preScore (kind 1)
1524
+ // runs before search and is unaffected.
1583
1525
  const quality = pre || await scoreQuality(searched ?? hits, context, fusedFull);
1584
1526
  // A 'none' verdict withholds results by default — the
1585
1527
  // calibrated abstention signal is doing its job, and most
@@ -1596,11 +1538,15 @@ export async function openPikeletFile(input, options = {}) {
1596
1538
  const record = await hydrate(hit.id);
1597
1539
  return { ...record, id: hit.id, distance: hit.distance, ...(hit.fusedRank ? { fusedRank: hit.fusedRank, lexicalRank: hit.lexicalRank, vectorRank: hit.vectorRank } : {}) };
1598
1540
  }));
1599
- // Grounding transparency: which record's text grounded the verdict
1600
- // and which query words it covered, so a consumer can tell a
1601
- // topical match ("much money darcy make year") from an answer.
1602
- const passageOrder = fusedFull?.length ? fusedFull : (searched ?? hits);
1603
- const grounding = quality.grounding ? { ...quality.grounding, recordId: passageOrder[quality.grounding.passageIndex]?.id ?? null } : null;
1541
+ // Grounding: which query words the best of the top passages
1542
+ // contains and which none does, so a consumer can tell a topical
1543
+ // match ("much money darcy make year") from an answer. Computed
1544
+ // for every pack (grounding.mjs), calibrated or not, from the
1545
+ // passages fusion ranks first; recordId names the graded passage.
1546
+ const passageOrder = (fusedFull?.length ? fusedFull : (searched ?? hits)).slice(0, GROUNDING_PASSAGES);
1547
+ const passageTexts = await Promise.all(passageOrder.map(async (hit) => (await hydrate(hit.id))?.text ?? ''));
1548
+ const graded = groundQuery(trimmed, passageTexts);
1549
+ const grounding = graded ? { ...graded, recordId: passageOrder[graded.passageIndex]?.id ?? null } : null;
1604
1550
  return { matchQuality: quality.match_quality, confidence: quality.confidence, results, ...(grounding ? { grounding } : {}) };
1605
1551
  },
1606
1552
 
@@ -1651,6 +1597,27 @@ export async function openPikeletFile(input, options = {}) {
1651
1597
  return sketch.verifyVectors(verifyOptions);
1652
1598
  },
1653
1599
 
1600
+ /**
1601
+ * Full pass over a lazily opened lexical segment against its
1602
+ * identity-anchored digest, streamed in bounded chunks where the
1603
+ * runtime has an incremental hash. An eager segment was already
1604
+ * verified whole at open. Resolves false when the pack carries no
1605
+ * lexical segment.
1606
+ */
1607
+ async verifyLexical(verifyOptions = {}) {
1608
+ assertOpen();
1609
+ if (!lexicalIndex) return false;
1610
+ if (!lexicalVerified) {
1611
+ const seg = segments.get('lexical');
1612
+ const expected = new Uint8Array(32);
1613
+ for (let b = 0; b < 32; b++) expected[b] = Number.parseInt(seg.sha256.slice(2 * b, 2 * b + 2), 16);
1614
+ await verifySegmentSha256(source, seg.offset, seg.length, expected, 'lexical segment',
1615
+ { chunkBytes: verifyOptions.chunkBytes, oneShotLimit: maxReadBytes });
1616
+ lexicalVerified = true;
1617
+ }
1618
+ return true;
1619
+ },
1620
+
1654
1621
  async evaluation() {
1655
1622
  assertOpen();
1656
1623
  return readEvaluationSegment();
@@ -1733,29 +1700,20 @@ export async function openPikeletFile(input, options = {}) {
1733
1700
  // This member's own evaluation segment, hash-verified.
1734
1701
  // A chain surfaces the base's through it (6.2).
1735
1702
  evaluation: readEvaluationSegment,
1736
- // The tier's staged WASM scan kernel, or null before
1737
- // background staging resolves. A chain queries
1738
- // sketch.search directly, so without passing this through
1739
- // every tier fell back to the JS scan: on the 456k-record
1740
- // wiki base that is ~450 ms a query against ~50 ms with
1741
- // the kernel. A getter, not a captured value, because
1703
+ // The tier's staged WASM scan kernel, or null until staging resolves. A
1704
+ // chain calls sketch.search directly, so it needs this to avoid the JS scan
1705
+ // (~450 vs ~50 ms a query on the 456k-record wiki base). A getter because
1742
1706
  // staging completes after open() returns.
1743
1707
  get scanner() { return scanner; },
1744
1708
  // The rerank's default coalescing gap for this member
1745
1709
  // (manifest hint as a floor under the source's own), so
1746
1710
  // a chain fetches each tier's rows as this member would.
1747
1711
  rerankGap: rerankGapHint,
1748
- // The base's OWN encoder, for `append` (6.1): "a kind-3
1749
- // base carries the teacher, and append loads it from the
1750
- // base's own query-interp segment — no model download, no
1751
- // external dependency: a pack is sufficient to compile its
1752
- // own successors." Resolving it here rather than letting a
1753
- // producer construct one is what makes substituting a
1754
- // different encoder impossible.
1755
- //
1756
- // Returns null for kinds that cannot embed passages: kind 1
1757
- // carries a query encoder only (6.1 refuses it), and kind 4
1758
- // is a layer, which inherits.
1712
+ // The base's own encoder, for `append` (6.1): a kind-3 base carries the
1713
+ // teacher, so a pack can compile its own successors with no download.
1714
+ // Resolving it here, not in the producer, makes substituting a different
1715
+ // encoder impossible. Null for kinds that cannot embed passages: kind 1
1716
+ // (query encoder only) and kind 4 (a layer, which inherits).
1759
1717
  async passageEmbedder() {
1760
1718
  assertOpen();
1761
1719
  if (qiKind !== 3 || !resolveEmbedder) return null;
@@ -1806,6 +1764,16 @@ export async function openPikeletFile(input, options = {}) {
1806
1764
  // `asset.driftLimit` is the producer's declared validity
1807
1765
  // envelope when it declared one.
1808
1766
  calibrationJson,
1767
+ // A deferred kind-3 base read its calibration region at
1768
+ // open without a digest check; the region is verified
1769
+ // only when the full query-interp segment arrives (the
1770
+ // encoder load). A chain query takes a caller's vector
1771
+ // and never embeds, so it awaits this before trusting
1772
+ // calibrationJson. Rejects if the bytes did not verify.
1773
+ async calibrationVerified() {
1774
+ assertOpen();
1775
+ if (qiDeferred && resolveEmbedder) await resolveEmbedder();
1776
+ },
1809
1777
  // Raw segment bytes for the chain's structural parsing
1810
1778
  // (tombstones, kind-4). Bounded and digest-checked exactly
1811
1779
  // as any other segment read: the digest comes from the