@seanhogg/builderforce-memory 2026.10.46 → 2026.10.48

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.
Files changed (103) hide show
  1. package/README.md +21 -0
  2. package/dist/knowledge/extractFile.d.ts.map +1 -1
  3. package/dist/knowledge/extractFile.js +3 -0
  4. package/dist/knowledge/extractFile.js.map +1 -1
  5. package/dist/knowledge/pack/crc32.d.ts +6 -2
  6. package/dist/knowledge/pack/crc32.d.ts.map +1 -1
  7. package/dist/knowledge/pack/crc32.js +7 -3
  8. package/dist/knowledge/pack/crc32.js.map +1 -1
  9. package/dist/knowledge/pack/decode.d.ts +7 -3
  10. package/dist/knowledge/pack/decode.d.ts.map +1 -1
  11. package/dist/knowledge/pack/decode.js +21 -13
  12. package/dist/knowledge/pack/decode.js.map +1 -1
  13. package/dist/knowledge/pack/deflate.d.ts +1 -0
  14. package/dist/knowledge/pack/deflate.d.ts.map +1 -1
  15. package/dist/knowledge/pack/deflate.js +17 -0
  16. package/dist/knowledge/pack/deflate.js.map +1 -1
  17. package/dist/knowledge/pack/encode.d.ts +9 -0
  18. package/dist/knowledge/pack/encode.d.ts.map +1 -1
  19. package/dist/knowledge/pack/encode.js +7 -0
  20. package/dist/knowledge/pack/encode.js.map +1 -1
  21. package/dist/knowledge/pack/extrDiff.d.ts +4 -1
  22. package/dist/knowledge/pack/extrDiff.d.ts.map +1 -1
  23. package/dist/knowledge/pack/extrDiff.js +0 -0
  24. package/dist/knowledge/pack/extrDiff.js.map +1 -1
  25. package/dist/knowledge/pack/frame.d.ts +20 -1
  26. package/dist/knowledge/pack/frame.d.ts.map +1 -1
  27. package/dist/knowledge/pack/frame.js +50 -16
  28. package/dist/knowledge/pack/frame.js.map +1 -1
  29. package/dist/knowledge/pack/hex.d.ts +7 -0
  30. package/dist/knowledge/pack/hex.d.ts.map +1 -0
  31. package/dist/knowledge/pack/hex.js +17 -0
  32. package/dist/knowledge/pack/hex.js.map +1 -0
  33. package/dist/knowledge/pack/index.d.ts +1 -1
  34. package/dist/knowledge/pack/index.d.ts.map +1 -1
  35. package/dist/knowledge/pack/index.js +1 -1
  36. package/dist/knowledge/pack/index.js.map +1 -1
  37. package/dist/knowledge/pack/manifest.d.ts +17 -0
  38. package/dist/knowledge/pack/manifest.d.ts.map +1 -1
  39. package/dist/knowledge/pack/manifest.js +37 -8
  40. package/dist/knowledge/pack/manifest.js.map +1 -1
  41. package/dist/knowledge/pack/sections/columns.d.ts +2 -2
  42. package/dist/knowledge/pack/sections/extr.js +8 -8
  43. package/dist/knowledge/pack/sections/extr.js.map +1 -1
  44. package/dist/knowledge/pack/sections/extrLists.d.ts +4 -4
  45. package/dist/knowledge/pack/sections/extrLists.d.ts.map +1 -1
  46. package/dist/knowledge/pack/sections/extrLists.js +14 -8
  47. package/dist/knowledge/pack/sections/extrLists.js.map +1 -1
  48. package/dist/knowledge/pack/sections/facts.d.ts.map +1 -1
  49. package/dist/knowledge/pack/sections/facts.js +11 -6
  50. package/dist/knowledge/pack/sections/facts.js.map +1 -1
  51. package/dist/knowledge/pack/sections/rows.d.ts.map +1 -1
  52. package/dist/knowledge/pack/sections/rows.js +20 -19
  53. package/dist/knowledge/pack/sections/rows.js.map +1 -1
  54. package/dist/knowledge/pack/strings.d.ts +5 -1
  55. package/dist/knowledge/pack/strings.d.ts.map +1 -1
  56. package/dist/knowledge/pack/strings.js +16 -14
  57. package/dist/knowledge/pack/strings.js.map +1 -1
  58. package/dist/knowledge/pack/types.d.ts +13 -3
  59. package/dist/knowledge/pack/types.d.ts.map +1 -1
  60. package/dist/knowledge/pack/types.js +2 -1
  61. package/dist/knowledge/pack/types.js.map +1 -1
  62. package/dist/knowledge/pack/varint.d.ts +9 -2
  63. package/dist/knowledge/pack/varint.d.ts.map +1 -1
  64. package/dist/knowledge/pack/varint.js +8 -4
  65. package/dist/knowledge/pack/varint.js.map +1 -1
  66. package/dist/knowledge/reviewModel.d.ts +6 -0
  67. package/dist/knowledge/reviewModel.d.ts.map +1 -1
  68. package/dist/knowledge/reviewPrefetch.d.ts +2 -0
  69. package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
  70. package/dist/knowledge/reviewPrefetch.js +11 -1
  71. package/dist/knowledge/reviewPrefetch.js.map +1 -1
  72. package/package.json +4 -3
  73. package/src/contract/dist.contract.test.ts +44 -0
  74. package/src/contract/exports.contract.test.ts +90 -0
  75. package/src/contract/exports.snapshot.json +608 -0
  76. package/src/contract/pack.contract.test.ts +31 -0
  77. package/src/contract/regression.pack.test.ts +94 -0
  78. package/src/contract/regression.review.test.ts +236 -0
  79. package/src/contract/regression.store.test.ts +84 -0
  80. package/src/contract/types.contract.test.ts +183 -0
  81. package/src/knowledge/extractFile.ts +2 -0
  82. package/src/knowledge/pack/crc32.ts +7 -3
  83. package/src/knowledge/pack/decode.ts +22 -14
  84. package/src/knowledge/pack/deflate.ts +19 -1
  85. package/src/knowledge/pack/encode.ts +8 -0
  86. package/src/knowledge/pack/extrDiff.ts +0 -0
  87. package/src/knowledge/pack/frame.ts +52 -14
  88. package/src/knowledge/pack/hex.ts +17 -0
  89. package/src/knowledge/pack/index.ts +1 -1
  90. package/src/knowledge/pack/manifest.ts +35 -5
  91. package/src/knowledge/pack/pack.guards.test.ts +35 -3
  92. package/src/knowledge/pack/pack.roundtrip.test.ts +1 -1
  93. package/src/knowledge/pack/sections/columns.ts +2 -2
  94. package/src/knowledge/pack/sections/extr.ts +9 -9
  95. package/src/knowledge/pack/sections/extrLists.ts +13 -9
  96. package/src/knowledge/pack/sections/facts.ts +8 -5
  97. package/src/knowledge/pack/sections/rows.ts +17 -17
  98. package/src/knowledge/pack/strings.ts +15 -12
  99. package/src/knowledge/pack/types.ts +13 -4
  100. package/src/knowledge/pack/varint.ts +10 -3
  101. package/src/knowledge/reviewModel.ts +6 -0
  102. package/src/knowledge/reviewPrefetch.ts +10 -1
  103. package/src/knowledge/testkit.test-util.ts +13 -2
@@ -1,44 +1,52 @@
1
1
  /**
2
2
  * knowledge/pack/decode.ts — `decodePack` (PRD 41 A11). Guards run before any row is built: the
3
- * magic and version, the CRC-32 of the decoded body, the inflate cap (`PackTooLargeError` past
3
+ * magic and version, the CRC-32 of the header and the decoded body, the inflate cap (`PackTooLargeError` past
4
4
  * `maxDecodedBytes`) and the string/row counts. A malformed pack is a `PackFormatError`.
5
5
  */
6
6
 
7
7
  import { crc32 } from './crc32.js';
8
- import { inflateRaw } from './deflate.js';
9
- import { FLAG_DEFLATED, readFrame, readSections } from './frame.js';
8
+ import { inflateRawChunks } from './deflate.js';
9
+ import { FLAG_DEFLATED, joinParts, readFrameParts, readSections } from './frame.js';
10
10
  import { ROW_SECTIONS, TAG } from './sections/index.js';
11
11
  import { readHashTable, readStringTable, readTables } from './strings.js';
12
- import { DEFAULT_PACK_LIMITS, PackTooLargeError, type Pack, type PackLimits } from './types.js';
12
+ import { DEFAULT_PACK_LIMITS, PackTooLargeError, type Pack, type PackLimits, type ReadLimits } from './types.js';
13
13
  import { PackFormatError } from './varint.js';
14
14
 
15
15
  const NONE = new Uint8Array([0]);
16
+ const partsOf = (input: Uint8Array | readonly Uint8Array[]): readonly Uint8Array[] => (input instanceof Uint8Array ? [input] : input);
16
17
 
17
18
  /** The frame's header, without inflating the body (cheap: for routing and the generation check). */
18
- export function peekPack(bytes: Uint8Array): { rootId: string; baseGeneration: number; targetDigest: string } {
19
- const { header } = readFrame(bytes);
19
+ export function peekPack(input: Uint8Array | readonly Uint8Array[]): { rootId: string; baseGeneration: number; targetDigest: string } {
20
+ const { header } = readFrameParts(partsOf(input));
20
21
  return { rootId: header.rootId, baseGeneration: header.baseGeneration, targetDigest: header.targetDigest };
21
22
  }
22
23
 
23
- export async function decodePack(bytes: Uint8Array, limits: Partial<PackLimits> = {}): Promise<Pack> {
24
- const lim: PackLimits = { ...DEFAULT_PACK_LIMITS, ...limits };
25
- const { header, stored, crc } = readFrame(bytes);
24
+ /**
25
+ * Decodes one pack, given whole or as the ordered parts it travelled in. Parts of a deflated pack are inflated as one
26
+ * stream, so the compressed pack is never copied into a second joined buffer.
27
+ */
28
+ export async function decodePack(input: Uint8Array | readonly Uint8Array[], limits: Partial<PackLimits> = {}): Promise<Pack> {
29
+ const base0: PackLimits = { ...DEFAULT_PACK_LIMITS, ...limits };
30
+ // ONE row budget for the whole pack: every list of every section draws from it.
31
+ const lim: ReadLimits = { ...base0, budget: { left: base0.maxRows } };
32
+ const { header, headerBytes, stored, crc } = readFrameParts(partsOf(input));
26
33
  let body: Uint8Array;
27
34
  if (header.flags & FLAG_DEFLATED) {
28
35
  try {
29
- body = await inflateRaw(stored, lim.maxDecodedBytes);
36
+ body = await inflateRawChunks(stored, lim.maxDecodedBytes);
30
37
  } catch (error) {
31
38
  if (error instanceof PackTooLargeError) throw error;
32
39
  throw new PackFormatError('corrupt deflate stream');
33
40
  }
34
41
  } else {
35
- if (stored.length > lim.maxDecodedBytes) throw new PackTooLargeError(lim.maxDecodedBytes);
36
- body = stored;
42
+ const size = stored.reduce((n, c) => n + c.length, 0);
43
+ if (size > lim.maxDecodedBytes) throw new PackTooLargeError(lim.maxDecodedBytes);
44
+ body = stored.length === 1 ? stored[0]! : joinParts(stored);
37
45
  }
38
- if (crc32(body) !== crc) throw new PackFormatError('CRC-32 mismatch');
46
+ if (crc32(body, crc32(headerBytes)) !== crc) throw new PackFormatError('CRC-32 mismatch');
39
47
  try {
40
48
  const sections = readSections(body);
41
- const strings = readStringTable(sections.get(TAG.STR) ?? NONE, lim.maxStrings);
49
+ const strings = readStringTable(sections.get(TAG.STR) ?? NONE, lim.maxStrings, lim.maxDecodedBytes);
42
50
  const hashes = readHashTable(sections.get(TAG.HASH) ?? NONE, lim.maxStrings);
43
51
  const used = new Set<string>();
44
52
  const base = readTables(strings, hashes);
@@ -35,7 +35,25 @@ async function through(data: Uint8Array, transform: { readable: ReadableStream<U
35
35
  }
36
36
  }
37
37
 
38
- export const deflateRaw = (data: Uint8Array): Promise<Uint8Array> =>
38
+ /** Writes `chunks` into one transform in order, draining as it goes: the parts of a split pack are inflated as ONE stream, never joined. */
39
+ async function throughChunks(chunks: readonly Uint8Array[], transform: { readable: ReadableStream<Uint8Array>; writable: WritableStream<BufferSource> }, maxBytes: number): Promise<Uint8Array> {
40
+ const writer = transform.writable.getWriter();
41
+ const wrote = (async () => {
42
+ for (const c of chunks) await writer.write(c as unknown as BufferSource);
43
+ await writer.close();
44
+ })();
45
+ wrote.catch(() => undefined);
46
+ try {
47
+ return await drain(transform.readable, maxBytes);
48
+ } finally {
49
+ await wrote.catch(() => undefined);
50
+ }
51
+ }
52
+
53
+ export const inflateRawChunks = (chunks: readonly Uint8Array[], maxBytes: number): Promise<Uint8Array> =>
54
+ throughChunks(chunks, new DecompressionStream('deflate-raw') as never, maxBytes);
55
+
56
+ export const deflateRaw =(data: Uint8Array): Promise<Uint8Array> =>
39
57
  through(data, new CompressionStream('deflate-raw') as never, Number.MAX_SAFE_INTEGER);
40
58
 
41
59
  /** Throws {@link PackTooLargeError} past `maxBytes` of output, and `Error` on a corrupt stream. */
@@ -5,6 +5,11 @@
5
5
  * is written from the same normalized pack, so equal input (in any row order) gives equal bytes.
6
6
  * Two passes over the section writers: the first collects every string and hash they use, the
7
7
  * second writes real table indexes.
8
+ *
9
+ * NORMALISATION (lossless for every value the model produces, documented where it is not): rows are sorted and
10
+ * empty parts dropped; object keys of badges and of the analysis document are written in sorted order; a
11
+ * negative zero is written as zero; a string holding a lone UTF-16 surrogate is written with U+FFFD in its place
12
+ * (UTF-8 cannot carry it). Equal normalised input gives equal bytes.
8
13
  */
9
14
 
10
15
  import { deflateRaw } from './deflate.js';
@@ -56,6 +61,8 @@ export function normalizePack(pack: Pack): Pack {
56
61
  export interface EncodeOptions {
57
62
  /** Deflate the body (default true). Off, the bytes are the plain columnar form (tests, size comparisons). */
58
63
  deflate?: boolean;
64
+ /** Filled with the size of the DECODED body: a client cuts a pack by it before the server's cap refuses it. */
65
+ stats?: { decodedBytes: number };
59
66
  }
60
67
 
61
68
  export async function encodePack(input: Pack, opts: EncodeOptions = {}): Promise<Uint8Array> {
@@ -72,6 +79,7 @@ export async function encodePack(input: Pack, opts: EncodeOptions = {}): Promise
72
79
  if (bytes) writeSection(body, s.tag, bytes);
73
80
  }
74
81
  const plain = body.finish();
82
+ if (opts.stats) opts.stats.decodedBytes = plain.length;
75
83
  const deflate = opts.deflate ?? true;
76
84
  return writeFrame(
77
85
  { flags: deflate ? FLAG_DEFLATED : 0, rootId: pack.rootId, baseGeneration: pack.baseGeneration, targetDigest: pack.targetDigest },
Binary file
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import { crc32 } from './crc32.js';
12
+ import { fromHex64, HEX64, toHex } from './hex.js';
12
13
  import { ByteReader, ByteWriter, PackFormatError } from './varint.js';
13
14
 
14
15
  export const MAGIC = [0x42, 0x46, 0x4b, 0x50] as const; // "BFKP"
@@ -20,27 +21,31 @@ export const MAX_PART_BYTES = 8 * 1024 * 1024;
20
21
 
21
22
  export interface FrameHeader { flags: number; rootId: string; baseGeneration: number; targetDigest: string }
22
23
 
23
- const hexOf = (b: Uint8Array): string => { let s = ''; for (const x of b) s += (x < 16 ? '0' : '') + x.toString(16); return s; };
24
-
24
+ /**
25
+ * The CRC-32 in the trailer covers the HEADER (magic through digest) and the DECODED body, so a flipped
26
+ * root id, generation or digest fails the same check a flipped row does.
27
+ */
25
28
  export function writeFrame(h: FrameHeader, body: Uint8Array, storedBody: Uint8Array): Uint8Array {
26
- if (!/^[0-9a-f]{64}$/.test(h.targetDigest)) throw new PackFormatError('targetDigest is 64 lowercase hex characters');
29
+ if (!HEX64.test(h.targetDigest)) throw new PackFormatError('targetDigest is 64 lowercase hex characters');
27
30
  const w = new ByteWriter();
28
31
  for (const m of MAGIC) w.u8(m);
29
32
  w.u8(VERSION);
30
33
  w.u8(h.flags);
31
34
  w.str(h.rootId);
32
35
  w.varint(h.baseGeneration);
33
- const raw = new Uint8Array(32);
34
- for (let i = 0; i < 32; i++) raw[i] = parseInt(h.targetDigest.slice(i * 2, i * 2 + 2), 16);
35
- w.bytes(raw);
36
- w.bytes(storedBody);
37
- w.u32le(crc32(body));
38
- return w.finish();
36
+ w.bytes(fromHex64(h.targetDigest));
37
+ const head = w.finish();
38
+ const out = new ByteWriter();
39
+ out.bytes(head);
40
+ out.bytes(storedBody);
41
+ out.u32le(crc32(body, crc32(head)));
42
+ return out.finish();
39
43
  }
40
44
 
41
- /** Splits a frame into header fields, the stored (possibly deflated) body, and the CRC the trailer claims. */
42
- export function readFrame(bytes: Uint8Array): { header: FrameHeader; stored: Uint8Array; crc: number } {
43
- if (bytes.length < 4 + 2 + 1 + 1 + 32 + 4) throw new PackFormatError('truncated frame');
45
+ const MIN_FRAME = 4 + 2 + 1 + 1 + 32 + 4;
46
+
47
+ /** The header alone: magic through digest. `bytes` may be just the first part of a split pack. */
48
+ export function readHeader(bytes: Uint8Array): { header: FrameHeader; headerBytes: Uint8Array } {
44
49
  const r = new ByteReader(bytes);
45
50
  for (const m of MAGIC) if (r.u8() !== m) throw new PackFormatError('not a BFKP pack (bad magic)');
46
51
  const version = r.u8();
@@ -48,10 +53,43 @@ export function readFrame(bytes: Uint8Array): { header: FrameHeader; stored: Uin
48
53
  const flags = r.u8();
49
54
  const rootId = r.str();
50
55
  const baseGeneration = r.varint();
51
- const targetDigest = hexOf(r.bytes(32));
56
+ const targetDigest = toHex(r.bytes(32));
57
+ return { header: { flags, rootId, baseGeneration, targetDigest }, headerBytes: bytes.subarray(0, r.offset) };
58
+ }
59
+
60
+ /**
61
+ * Splits a frame into header fields, the stored (possibly deflated) body, the header's bytes, and the CRC the
62
+ * trailer claims. The caller checks `crc32(decodedBody, crc32(headerBytes)) === crc` once it has inflated.
63
+ */
64
+ export function readFrame(bytes: Uint8Array): { header: FrameHeader; headerBytes: Uint8Array; stored: Uint8Array; crc: number } {
65
+ if (bytes.length < MIN_FRAME) throw new PackFormatError('truncated frame');
66
+ const { header, headerBytes } = readHeader(bytes);
67
+ const r = new ByteReader(bytes);
68
+ r.bytes(headerBytes.length);
52
69
  if (r.remaining < 4) throw new PackFormatError('truncated frame');
53
70
  const stored = r.bytes(r.remaining - 4);
54
- return { header: { flags, rootId, baseGeneration, targetDigest }, stored, crc: r.u32le() };
71
+ return { header, headerBytes, stored, crc: r.u32le() };
72
+ }
73
+
74
+ /** Parts that can be read as a frame without joining: a first part that holds the whole header and a last part that holds the trailer. */
75
+ const HEADER_ROOM = 4096;
76
+ export function readFrameParts(parts: readonly Uint8Array[]): { header: FrameHeader; headerBytes: Uint8Array; stored: Uint8Array[]; crc: number } {
77
+ const first = parts[0], last = parts[parts.length - 1];
78
+ if (parts.length < 2 || !first || !last || first.length < HEADER_ROOM || last.length < 4) return singleFrame(parts);
79
+ const { header, headerBytes } = readHeader(first);
80
+ const trailer = last.subarray(last.length - 4);
81
+ const stored = parts.map((p, i) => {
82
+ const from = i === 0 ? headerBytes.length : 0;
83
+ const to = i === parts.length - 1 ? p.length - 4 : p.length;
84
+ return p.subarray(from, to);
85
+ });
86
+ const crc = (trailer[0]! | (trailer[1]! << 8) | (trailer[2]! << 16) | (trailer[3]! << 24)) >>> 0;
87
+ return { header, headerBytes, stored, crc };
88
+ }
89
+
90
+ function singleFrame(parts: readonly Uint8Array[]): { header: FrameHeader; headerBytes: Uint8Array; stored: Uint8Array[]; crc: number } {
91
+ const f = readFrame(joinParts(parts));
92
+ return { ...f, stored: [f.stored] };
55
93
  }
56
94
 
57
95
  export function writeSection(w: ByteWriter, tag: number, bytes: Uint8Array): void {
@@ -0,0 +1,17 @@
1
+ /** knowledge/pack/hex.ts — the ONE hex helper of the codec (PRD 41 A11): 64-hex digests and hashes as raw 32 bytes and back. */
2
+
3
+ export const HEX64 = /^[0-9a-f]{64}$/;
4
+
5
+ /** Lowercase hex of `bytes`. */
6
+ export function toHex(bytes: Uint8Array): string {
7
+ let s = '';
8
+ for (const b of bytes) s += (b < 16 ? '0' : '') + b.toString(16);
9
+ return s;
10
+ }
11
+
12
+ /** The 32 raw bytes of a 64-character lowercase hex string. */
13
+ export function fromHex64(hex: string): Uint8Array {
14
+ const raw = new Uint8Array(32);
15
+ for (let i = 0; i < 32; i++) raw[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
16
+ return raw;
17
+ }
@@ -20,7 +20,7 @@ export type {
20
20
  export { diffEntries, applyEntryDiffs, diffEntry, applyEntryDiff, deepEqual } from './extrDiff.js';
21
21
  export {
22
22
  MANIFEST_BUCKETS, manifestTree, bucketOf, keyHash, differingBuckets, leafDelta, rootLeaves, rootDigestOf,
23
- fileLeafKey, factLeafKey, relationLeafKey, factDigest, relationDigest,
23
+ fileLeafKey, factLeafKey, relationLeafKey, parseRelationLeafKey, factDigest, relationDigest, bucketDigest, rootDigestOfBuckets,
24
24
  } from './manifest.js';
25
25
  export type { ManifestTree, LeafDelta, RootRows } from './manifest.js';
26
26
  export { jsonBytesOf } from './jsonSize.js';
@@ -37,6 +37,21 @@ export interface ManifestTree {
37
37
 
38
38
  const cmp = (a: ManifestLeaf, b: ManifestLeaf): number => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
39
39
 
40
+ /**
41
+ * The digest of ONE bucket: the hash of its leaves sorted by key (an empty bucket has a fixed digest). The server keeps
42
+ * these per bucket, so a pack recomputes only the buckets it touched.
43
+ */
44
+ export function bucketDigest(leaves: readonly ManifestLeaf[]): string {
45
+ if (leaves.length === 0) return EMPTY_BUCKET;
46
+ return sha256Hex([...leaves].sort(cmp).map((l) => `${l.key}\u0000${l.digest}\n`).join(''));
47
+ }
48
+
49
+ /** The root digest from the `MANIFEST_BUCKETS` bucket digests (hex), in bucket order. */
50
+ export function rootDigestOfBuckets(digests: readonly string[]): string {
51
+ if (digests.length !== MANIFEST_BUCKETS) throw new Error(`a root digest takes ${MANIFEST_BUCKETS} bucket digests, got ${digests.length}`);
52
+ return sha256Hex(digests.join(''));
53
+ }
54
+
40
55
  export function manifestTree(leaves: readonly ManifestLeaf[]): ManifestTree {
41
56
  const grouped = new Map<number, ManifestLeaf[]>();
42
57
  for (const l of leaves) {
@@ -47,11 +62,10 @@ export function manifestTree(leaves: readonly ManifestLeaf[]): ManifestTree {
47
62
  const buckets: string[] = new Array(MANIFEST_BUCKETS);
48
63
  for (let b = 0; b < MANIFEST_BUCKETS; b++) {
49
64
  const list = grouped.get(b);
50
- if (!list) { buckets[b] = EMPTY_BUCKET; continue; }
51
- list.sort(cmp);
52
- buckets[b] = sha256Hex(list.map((l) => `${l.key}\u0000${l.digest}\n`).join(''));
65
+ if (list) list.sort(cmp);
66
+ buckets[b] = bucketDigest(list ?? []);
53
67
  }
54
- return { root: sha256Hex(buckets.join('')), buckets, leaves: grouped };
68
+ return { root: rootDigestOfBuckets(buckets), buckets, leaves: grouped };
55
69
  }
56
70
 
57
71
  /** The bucket ids whose digests differ (or are missing on one side). */
@@ -69,7 +83,23 @@ export function fileLeafKey(path: string, hash: string): string {
69
83
  }
70
84
 
71
85
  export const factLeafKey = (key: string): string => `a:${key}`;
72
- export const relationLeafKey = (r: { from: string; to: string; kind: string }): string => `r:${r.from}\u0000${r.to}\u0000${r.kind}`;
86
+ /**
87
+ * A relation's leaf key: `r:` + the JSON array `[from, to, kind]`. Printable and unambiguous: Postgres `text` and
88
+ * `jsonb` reject NUL, which the earlier `from␀to␀kind` form contained.
89
+ */
90
+ export const relationLeafKey = (r: { from: string; to: string; kind: string }): string => `r:${JSON.stringify([r.from, r.to, r.kind])}`;
91
+
92
+ /** The inverse of {@link relationLeafKey}; null when `key` is not a relation leaf key. The ONE parser. */
93
+ export function parseRelationLeafKey(key: string): { from: string; to: string; kind: string } | null {
94
+ if (!key.startsWith('r:')) return null;
95
+ try {
96
+ const v: unknown = JSON.parse(key.slice(2));
97
+ if (Array.isArray(v) && v.length === 3 && v.every((s) => typeof s === 'string')) {
98
+ return { from: v[0] as string, to: v[1] as string, kind: v[2] as string };
99
+ }
100
+ } catch { /* not JSON: not a relation key */ }
101
+ return null;
102
+ }
73
103
 
74
104
  /** The digest of what a fact says: its key, text and provenance kind. Importance and timestamps are the server's to score. */
75
105
  export const factDigest = (f: Pick<StoredFact, 'key' | 'content' | 'origin'>): string => sha256Hex(JSON.stringify([f.key, f.content, f.origin]));
@@ -4,7 +4,8 @@
4
4
  */
5
5
 
6
6
  import { deflateRaw } from './deflate.js';
7
- import { FLAG_DEFLATED, readFrame, writeFrame } from './frame.js';
7
+ import { FLAG_DEFLATED, readFrame, writeFrame, writeSection } from './frame.js';
8
+ import { ByteWriter } from './varint.js';
8
9
  import { decodePack, encodePack, joinParts, PackFormatError, PackTooLargeError, peekPack, splitParts, ZERO_DIGEST } from './index.js';
9
10
  import { genPack } from './pack.testkit.test-util.js';
10
11
 
@@ -49,12 +50,43 @@ describe('BFKP guards', () => {
49
50
  await expect(decodePack(bomb, { maxDecodedBytes: 1024 * 1024 })).rejects.toThrow(PackTooLargeError);
50
51
  });
51
52
 
52
- it('applies the 64 MB default cap', async () => {
53
- const body = new Uint8Array(65 * 1024 * 1024);
53
+ it('applies the 24 MB default cap (sized for a 128 MB Worker)', async () => {
54
+ const body = new Uint8Array(25 * 1024 * 1024);
54
55
  const bomb = writeFrame({ flags: FLAG_DEFLATED, rootId: 'r', baseGeneration: 0, targetDigest: ZERO_DIGEST }, body, await deflateRaw(body));
55
56
  await expect(decodePack(bomb)).rejects.toThrow(PackTooLargeError);
56
57
  }, 60_000);
57
58
 
59
+ it('the CRC covers the header: a flipped digest or generation byte fails like a flipped row', async () => {
60
+ const bytes = await encodePack(genPack(2, { files: 4 }), { deflate: false });
61
+ const { headerBytes } = readFrame(bytes);
62
+ const bad = bytes.slice();
63
+ bad[headerBytes.length - 1]! ^= 0x01; // the last byte of the target digest
64
+ await expect(decodePack(bad)).rejects.toThrow(/CRC/);
65
+ const gen = bytes.slice();
66
+ gen[headerBytes.length - 33]! ^= 0x01; // the generation varint
67
+ await expect(decodePack(gen)).rejects.toThrow(PackFormatError);
68
+ });
69
+
70
+ it('the row budget is cumulative across sections: many small lists cannot add up to a bomb', async () => {
71
+ const bytes = await encodePack(genPack(9, { files: 15, facts: 15, symbols: 0, edgesPerFile: 0, rich: false }));
72
+ await expect(decodePack(bytes, { maxRows: 100_000 })).resolves.toBeDefined();
73
+ // Each list is under 40, together they are over it.
74
+ await expect(decodePack(bytes, { maxRows: 40 })).rejects.toThrow(PackFormatError);
75
+ });
76
+
77
+ it('a front-coded string table cannot name a huge string many times: the decoded total is capped', async () => {
78
+ const w = new ByteWriter();
79
+ const n = 2000, big = 100_000;
80
+ w.varint(n);
81
+ w.varint(0); w.varint(big); w.bytes(new Uint8Array(big).fill(97));
82
+ for (let i = 1; i < n; i++) { w.varint(big); w.varint(0); } // 2,000 strings of 100 KB each from ~100 KB of input
83
+ const body = new ByteWriter();
84
+ writeSection(body, 1, w.finish());
85
+ const plain = body.finish();
86
+ const frame = writeFrame({ flags: 0, rootId: 'r', baseGeneration: 0, targetDigest: ZERO_DIGEST }, plain, plain);
87
+ await expect(decodePack(frame, { maxDecodedBytes: 8 * 1024 * 1024 })).rejects.toThrow(PackTooLargeError);
88
+ });
89
+
58
90
  it('bounds counts before allocating for them', async () => {
59
91
  const bytes = await encodePack(genPack(5, { files: 20 }));
60
92
  await expect(decodePack(bytes, { maxRows: 5 })).rejects.toThrow(PackFormatError);
@@ -13,7 +13,7 @@ describe('BFKP round trip', () => {
13
13
  const decoded = await decodePack(await encodePack(pack));
14
14
  expect(decoded).toEqual(normalizePack(pack));
15
15
  }
16
- });
16
+ }, 60_000); // 40 generated graphs, each deflated and inflated: about 11 s under a parallel run
17
17
 
18
18
  it('round-trips an uncompressed frame the same as a deflated one', async () => {
19
19
  const pack = genPack(3, { files: 20 });
@@ -4,7 +4,7 @@
4
4
  * descriptor type (PRD 41 A11).
5
5
  */
6
6
 
7
- import type { Pack, PackLimits } from '../types.js';
7
+ import type { Pack, ReadLimits } from '../types.js';
8
8
  import type { ReadTables, Tables } from '../strings.js';
9
9
  import { PackFormatError, type ByteReader, type ByteWriter } from '../varint.js';
10
10
 
@@ -12,7 +12,7 @@ import { PackFormatError, type ByteReader, type ByteWriter } from '../varint.js'
12
12
  export interface SectionCodec {
13
13
  tag: number;
14
14
  write(pack: Pack, t: Tables): Uint8Array | undefined;
15
- read(bytes: Uint8Array, t: ReadTables, limits: PackLimits, into: Pack): void;
15
+ read(bytes: Uint8Array, t: ReadTables, limits: ReadLimits, into: Pack): void;
16
16
  }
17
17
 
18
18
  export const ORIGINS = ['extracted', 'model', 'human', 'agent'] as const;
@@ -6,7 +6,7 @@
6
6
 
7
7
  import type { Extracted, ExtrEntryDiff, ListDiff, PackExtr } from '../types.js';
8
8
  import type { ReadTables, Tables } from '../strings.js';
9
- import { boundedCount, ByteReader, ByteWriter } from '../varint.js';
9
+ import { boundedCount, ByteReader, ByteWriter, type Budget } from '../varint.js';
10
10
  import type { SectionCodec } from './columns.js';
11
11
  import { readEdges, readKeys, readNodes, writeEdges, writeKeys, writeNodes } from './extrLists.js';
12
12
  import { TAG } from './rows.js';
@@ -22,13 +22,13 @@ function writeDiff<T>(w: ByteWriter, t: Tables, d: ListDiff<T>, items: (w: ByteW
22
22
  items(w, t, d.add.map((a) => a.item));
23
23
  }
24
24
 
25
- function readDiff<T>(r: ByteReader, t: ReadTables, max: number, items: (r: ByteReader, t: ReadTables, max: number) => T[]): ListDiff<T> {
26
- const remove = Array.from({ length: boundedCount(r, max, 'diff removals') }, () => t.str(r.varint()));
27
- const n = boundedCount(r, max, 'diff additions');
25
+ function readDiff<T>(r: ByteReader, t: ReadTables, budget: Budget, items: (r: ByteReader, t: ReadTables, budget: Budget) => T[]): ListDiff<T> {
26
+ const remove = Array.from({ length: boundedCount(r, budget, 'diff removals') }, () => t.str(r.varint()));
27
+ const n = boundedCount(r, budget, 'diff additions');
28
28
  const ats: number[] = [];
29
29
  let prev = 0;
30
30
  for (let i = 0; i < n; i++) { prev += r.varint(); ats.push(prev); }
31
- const list = items(r, t, max);
31
+ const list = items(r, t, budget);
32
32
  return { remove, add: ats.map((at, i) => ({ at, item: list[i]! })) };
33
33
  }
34
34
 
@@ -62,24 +62,24 @@ export const extrSection: SectionCodec = {
62
62
  },
63
63
  read(bytes, t, limits, into) {
64
64
  const r = new ByteReader(bytes);
65
- const n = boundedCount(r, limits.maxRows, 'extracted hashes');
65
+ const n = boundedCount(r, limits.budget, 'extracted hashes');
66
66
  const out: PackExtr[] = [];
67
67
  for (let i = 0; i < n; i++) {
68
68
  const diff = r.u8() === 1;
69
69
  const hash = t.hash(r.varint());
70
70
  const prior = diff ? t.hash(r.varint()) : '';
71
- const count = boundedCount(r, limits.maxRows, 'extracted entries');
71
+ const count = boundedCount(r, limits.budget, 'extracted entries');
72
72
  const entries: Array<Extracted | ExtrEntryDiff> = [];
73
73
  for (let k = 0; k < count; k++) {
74
74
  const sourceRef = t.str(r.varint());
75
75
  const sourceHash = t.hash(r.varint());
76
76
  const version = r.u8() & HAS_VERSION ? { extractorVersion: r.varint() } : {};
77
77
  if (!diff) {
78
- entries.push({ sourceRef: sourceRef as Extracted['sourceRef'], sourceHash, ...version, nodes: readNodes(r, t, limits.maxRows), edges: readEdges(r, t, limits.maxRows), keys: readKeys(r, t, limits.maxRows) });
78
+ entries.push({ sourceRef: sourceRef as Extracted['sourceRef'], sourceHash, ...version, nodes: readNodes(r, t, limits.budget), edges: readEdges(r, t, limits.budget), keys: readKeys(r, t, limits.budget) });
79
79
  } else {
80
80
  entries.push({
81
81
  sourceRef, sourceHash, ...version,
82
- nodes: readDiff(r, t, limits.maxRows, readNodes), edges: readDiff(r, t, limits.maxRows, readEdges), keys: readDiff(r, t, limits.maxRows, readKeys),
82
+ nodes: readDiff(r, t, limits.budget, readNodes), edges: readDiff(r, t, limits.budget, readEdges), keys: readDiff(r, t, limits.budget, readKeys),
83
83
  });
84
84
  }
85
85
  }
@@ -6,10 +6,11 @@
6
6
 
7
7
  import type { KEdge, KNode, NodeRef } from '../types.js';
8
8
  import type { ReadTables, Tables } from '../strings.js';
9
- import { boundedCount, ByteReader, ByteWriter, PackFormatError } from '../varint.js';
9
+ import { boundedCount, ByteReader, ByteWriter, PackFormatError, type Budget } from '../varint.js';
10
10
  import { EDGE_KINDS, NODE_KINDS, ORIGINS, VERDICTS, readEnum, readWord, unzigzag, writeEnum, writeWord, zigzag } from './columns.js';
11
11
 
12
12
  const N_PARTITION = 1, N_AREA = 2, N_STALE = 4, N_STALE_V = 8, N_BADGES = 16, N_SYSTEM = 32, N_APP = 64, N_COPY = 128, N_HASH = 256;
13
+ const N_KNOWN = 0x1ff;
13
14
 
14
15
  export function writeNodes(w: ByteWriter, t: Tables, nodes: readonly KNode[]): void {
15
16
  w.varint(nodes.length);
@@ -35,7 +36,7 @@ export function writeNodes(w: ByteWriter, t: Tables, nodes: readonly KNode[]): v
35
36
  if (f & N_COPY) w.varint(t.str(n.copyOf!));
36
37
  if (f & N_HASH) w.varint(t.hash(n.sourceHash!));
37
38
  if (f & N_BADGES) {
38
- const keys = Object.keys(n.badges!);
39
+ const keys = Object.keys(n.badges!).sort(); // canonical order: equal badges, equal bytes
39
40
  w.varint(keys.length);
40
41
  for (const k of keys) {
41
42
  w.varint(t.str(k));
@@ -46,8 +47,8 @@ export function writeNodes(w: ByteWriter, t: Tables, nodes: readonly KNode[]): v
46
47
  });
47
48
  }
48
49
 
49
- export function readNodes(r: ByteReader, t: ReadTables, max: number): KNode[] {
50
- const n = boundedCount(r, max, 'nodes');
50
+ export function readNodes(r: ByteReader, t: ReadTables, budget: Budget): KNode[] {
51
+ const n = boundedCount(r, budget, 'nodes');
51
52
  const refs: string[] = [];
52
53
  let prev = 0;
53
54
  for (let i = 0; i < n; i++) { prev += unzigzag(r.varint()); refs.push(t.str(prev)); }
@@ -57,6 +58,7 @@ export function readNodes(r: ByteReader, t: ReadTables, max: number): KNode[] {
57
58
  const importance = Array.from({ length: n }, () => r.num());
58
59
  const origins = Array.from({ length: n }, () => readEnum(r, ORIGINS));
59
60
  const flags = Array.from({ length: n }, () => r.varint());
61
+ for (const f of flags) assertFlagsKnown(f, N_KNOWN);
60
62
  return refs.map((ref, i): KNode => {
61
63
  const f = flags[i]!;
62
64
  const node: KNode = { ref: ref as NodeRef, kind: kinds[i]!, label: labels[i]!, pack: packs[i]!, importance: importance[i]!, origin: origins[i]! };
@@ -69,7 +71,7 @@ export function readNodes(r: ByteReader, t: ReadTables, max: number): KNode[] {
69
71
  if (f & N_STALE) node.stale = (f & N_STALE_V) !== 0;
70
72
  if (f & N_BADGES) {
71
73
  const badges: Record<string, number | string> = {};
72
- const count = boundedCount(r, max, 'badges');
74
+ const count = boundedCount(r, budget, 'badges');
73
75
  for (let b = 0; b < count; b++) {
74
76
  const key = t.str(r.varint());
75
77
  badges[key] = r.u8() === 0 ? r.num() : t.str(r.varint());
@@ -81,6 +83,7 @@ export function readNodes(r: ByteReader, t: ReadTables, max: number): KNode[] {
81
83
  }
82
84
 
83
85
  const E_CONF = 1, E_VERDICT = 2, E_CYCLE = 4, E_CYCLE_V = 8, E_STALE = 16, E_STALE_V = 32, E_BYNAME = 64;
86
+ const E_KNOWN = 0x7f;
84
87
 
85
88
  export function writeEdges(w: ByteWriter, t: Tables, edges: readonly KEdge[]): void {
86
89
  w.varint(edges.length);
@@ -103,8 +106,8 @@ export function writeEdges(w: ByteWriter, t: Tables, edges: readonly KEdge[]): v
103
106
  });
104
107
  }
105
108
 
106
- export function readEdges(r: ByteReader, t: ReadTables, max: number): KEdge[] {
107
- const n = boundedCount(r, max, 'edges');
109
+ export function readEdges(r: ByteReader, t: ReadTables, budget: Budget): KEdge[] {
110
+ const n = boundedCount(r, budget, 'edges');
108
111
  const from: string[] = [];
109
112
  let prev = 0;
110
113
  for (let i = 0; i < n; i++) { prev += unzigzag(r.varint()); from.push(t.str(prev)); }
@@ -113,6 +116,7 @@ export function readEdges(r: ByteReader, t: ReadTables, max: number): KEdge[] {
113
116
  const weights = Array.from({ length: n }, () => r.num());
114
117
  const origins = Array.from({ length: n }, () => readEnum(r, ORIGINS));
115
118
  const flags = Array.from({ length: n }, () => r.varint());
119
+ for (const f of flags) assertFlagsKnown(f, E_KNOWN);
116
120
  return from.map((f0, i): KEdge => {
117
121
  const f = flags[i]!;
118
122
  const edge: KEdge = { from: f0 as NodeRef, to: to[i]! as NodeRef, kind: kinds[i]!, weight: weights[i]!, origin: origins[i]! };
@@ -134,8 +138,8 @@ export function writeKeys(w: ByteWriter, t: Tables, keys: readonly KeyRow[]): vo
134
138
  for (const k of keys) w.varint(t.str(k.key));
135
139
  }
136
140
 
137
- export function readKeys(r: ByteReader, t: ReadTables, max: number): Array<{ ref: NodeRef; key: string }> {
138
- const n = boundedCount(r, max, 'keys');
141
+ export function readKeys(r: ByteReader, t: ReadTables, budget: Budget): Array<{ ref: NodeRef; key: string }> {
142
+ const n = boundedCount(r, budget, 'keys');
139
143
  const refs: string[] = [];
140
144
  let prev = 0;
141
145
  for (let i = 0; i < n; i++) { prev += unzigzag(r.varint()); refs.push(t.str(prev)); }
@@ -4,8 +4,9 @@
4
4
  */
5
5
 
6
6
  import type { NodeRef, StoredFact, StoredRelation } from '../types.js';
7
- import { boundedCount, ByteReader, ByteWriter, PackFormatError } from '../varint.js';
7
+ import { boundedCount, ByteReader, ByteWriter } from '../varint.js';
8
8
  import { EDGE_KINDS, STORED_ORIGINS, readEnum, readWord, writeEnum, writeWord, type SectionCodec } from './columns.js';
9
+ import { assertFlagsKnown } from './extrLists.js';
9
10
  import { TAG } from './rows.js';
10
11
 
11
12
  const F_UPDATED = 1, F_BY_NULL = 2, F_BY = 4;
@@ -41,7 +42,7 @@ export const factSection: SectionCodec = {
41
42
  },
42
43
  read(bytes, t, limits, into) {
43
44
  const r = new ByteReader(bytes);
44
- const n = boundedCount(r, limits.maxRows, 'facts');
45
+ const n = boundedCount(r, limits.budget, 'facts');
45
46
  const keys: string[] = [];
46
47
  let prev = 0;
47
48
  for (let i = 0; i < n; i++) { prev += r.varint(); keys.push(t.str(prev)); }
@@ -50,17 +51,18 @@ export const factSection: SectionCodec = {
50
51
  const importance = keys.map(() => r.num());
51
52
  const origin = keys.map(() => readEnum(r, STORED_ORIGINS));
52
53
  const flags = keys.map(() => r.u8());
54
+ for (const f of flags) assertFlagsKnown(f, F_UPDATED | F_BY_NULL | F_BY);
53
55
  const facts: StoredFact[] = keys.map((key, i) => ({ key, content: content[i]!, source: source[i]!, importance: importance[i]!, origin: origin[i]!, fileAnchors: [] }));
54
56
  facts.forEach((f, i) => {
55
57
  if (flags[i]! & F_UPDATED) f.updatedAt = t.str(r.varint());
56
58
  if (flags[i]! & F_BY_NULL) f.createdBy = null;
57
59
  if (flags[i]! & F_BY) f.createdBy = t.str(r.varint());
58
60
  });
59
- const counts = facts.map(() => boundedCount(r, limits.maxRows, 'anchors'));
61
+ const counts = facts.map(() => boundedCount(r, limits.budget, 'anchors'));
60
62
  const total = counts.reduce((a, b) => a + b, 0);
61
- if (total > limits.maxRows) throw new PackFormatError('anchors: over the row bound');
62
63
  const paths = Array.from({ length: total }, () => t.str(r.varint()));
63
64
  const aflags = Array.from({ length: total }, () => r.u8());
65
+ for (const f of aflags) assertFlagsKnown(f, A_LINE | A_HASH);
64
66
  let at = 0;
65
67
  facts.forEach((f, i) => {
66
68
  for (let k = 0; k < counts[i]!; k++, at++) {
@@ -101,7 +103,7 @@ export const relationSection: SectionCodec = {
101
103
  },
102
104
  read(bytes, t, limits, into) {
103
105
  const r = new ByteReader(bytes);
104
- const n = boundedCount(r, limits.maxRows, 'relations');
106
+ const n = boundedCount(r, limits.budget, 'relations');
105
107
  const from: string[] = [];
106
108
  let prev = 0;
107
109
  for (let i = 0; i < n; i++) { prev += r.varint(); from.push(t.str(prev)); }
@@ -110,6 +112,7 @@ export const relationSection: SectionCodec = {
110
112
  const weight = from.map(() => r.num());
111
113
  const origin = from.map(() => readEnum(r, STORED_ORIGINS));
112
114
  const flags = from.map(() => r.u8());
115
+ for (const f of flags) assertFlagsKnown(f, R_CONF | R_HASH | R_STALE | R_STALE_NULL);
113
116
  into.relations = from.map((f0, i): StoredRelation => {
114
117
  const x: StoredRelation = { from: f0 as NodeRef, to: to[i]! as NodeRef, kind: kind[i]!, weight: weight[i]!, origin: origin[i]! };
115
118
  const f = flags[i]!;