@seanhogg/builderforce-memory 2026.10.46 → 2026.10.47

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 (86) 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 +1 -1
  10. package/dist/knowledge/pack/decode.d.ts.map +1 -1
  11. package/dist/knowledge/pack/decode.js +7 -5
  12. package/dist/knowledge/pack/decode.js.map +1 -1
  13. package/dist/knowledge/pack/encode.d.ts +9 -0
  14. package/dist/knowledge/pack/encode.d.ts.map +1 -1
  15. package/dist/knowledge/pack/encode.js +7 -0
  16. package/dist/knowledge/pack/encode.js.map +1 -1
  17. package/dist/knowledge/pack/extrDiff.d.ts +4 -1
  18. package/dist/knowledge/pack/extrDiff.d.ts.map +1 -1
  19. package/dist/knowledge/pack/extrDiff.js +0 -0
  20. package/dist/knowledge/pack/extrDiff.js.map +1 -1
  21. package/dist/knowledge/pack/frame.d.ts +9 -1
  22. package/dist/knowledge/pack/frame.d.ts.map +1 -1
  23. package/dist/knowledge/pack/frame.js +20 -13
  24. package/dist/knowledge/pack/frame.js.map +1 -1
  25. package/dist/knowledge/pack/hex.d.ts +7 -0
  26. package/dist/knowledge/pack/hex.d.ts.map +1 -0
  27. package/dist/knowledge/pack/hex.js +17 -0
  28. package/dist/knowledge/pack/hex.js.map +1 -0
  29. package/dist/knowledge/pack/sections/columns.d.ts +2 -2
  30. package/dist/knowledge/pack/sections/extr.js +8 -8
  31. package/dist/knowledge/pack/sections/extr.js.map +1 -1
  32. package/dist/knowledge/pack/sections/extrLists.d.ts +4 -4
  33. package/dist/knowledge/pack/sections/extrLists.d.ts.map +1 -1
  34. package/dist/knowledge/pack/sections/extrLists.js +14 -8
  35. package/dist/knowledge/pack/sections/extrLists.js.map +1 -1
  36. package/dist/knowledge/pack/sections/facts.d.ts.map +1 -1
  37. package/dist/knowledge/pack/sections/facts.js +11 -6
  38. package/dist/knowledge/pack/sections/facts.js.map +1 -1
  39. package/dist/knowledge/pack/sections/rows.d.ts.map +1 -1
  40. package/dist/knowledge/pack/sections/rows.js +20 -19
  41. package/dist/knowledge/pack/sections/rows.js.map +1 -1
  42. package/dist/knowledge/pack/strings.d.ts +5 -1
  43. package/dist/knowledge/pack/strings.d.ts.map +1 -1
  44. package/dist/knowledge/pack/strings.js +16 -14
  45. package/dist/knowledge/pack/strings.js.map +1 -1
  46. package/dist/knowledge/pack/types.d.ts +9 -0
  47. package/dist/knowledge/pack/types.d.ts.map +1 -1
  48. package/dist/knowledge/pack/types.js.map +1 -1
  49. package/dist/knowledge/pack/varint.d.ts +9 -2
  50. package/dist/knowledge/pack/varint.d.ts.map +1 -1
  51. package/dist/knowledge/pack/varint.js +8 -4
  52. package/dist/knowledge/pack/varint.js.map +1 -1
  53. package/dist/knowledge/reviewModel.d.ts +6 -0
  54. package/dist/knowledge/reviewModel.d.ts.map +1 -1
  55. package/dist/knowledge/reviewPrefetch.d.ts +2 -0
  56. package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
  57. package/dist/knowledge/reviewPrefetch.js +11 -1
  58. package/dist/knowledge/reviewPrefetch.js.map +1 -1
  59. package/package.json +4 -3
  60. package/src/contract/dist.contract.test.ts +44 -0
  61. package/src/contract/exports.contract.test.ts +90 -0
  62. package/src/contract/exports.snapshot.json +605 -0
  63. package/src/contract/pack.contract.test.ts +31 -0
  64. package/src/contract/regression.review.test.ts +236 -0
  65. package/src/contract/regression.store.test.ts +84 -0
  66. package/src/contract/types.contract.test.ts +183 -0
  67. package/src/knowledge/extractFile.ts +2 -0
  68. package/src/knowledge/pack/crc32.ts +7 -3
  69. package/src/knowledge/pack/decode.ts +8 -6
  70. package/src/knowledge/pack/encode.ts +8 -0
  71. package/src/knowledge/pack/extrDiff.ts +0 -0
  72. package/src/knowledge/pack/frame.ts +21 -13
  73. package/src/knowledge/pack/hex.ts +17 -0
  74. package/src/knowledge/pack/pack.guards.test.ts +33 -1
  75. package/src/knowledge/pack/pack.roundtrip.test.ts +1 -1
  76. package/src/knowledge/pack/sections/columns.ts +2 -2
  77. package/src/knowledge/pack/sections/extr.ts +9 -9
  78. package/src/knowledge/pack/sections/extrLists.ts +13 -9
  79. package/src/knowledge/pack/sections/facts.ts +7 -4
  80. package/src/knowledge/pack/sections/rows.ts +17 -17
  81. package/src/knowledge/pack/strings.ts +15 -12
  82. package/src/knowledge/pack/types.ts +8 -0
  83. package/src/knowledge/pack/varint.ts +10 -3
  84. package/src/knowledge/reviewModel.ts +6 -0
  85. package/src/knowledge/reviewPrefetch.ts +10 -1
  86. package/src/knowledge/testkit.test-util.ts +13 -2
@@ -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,26 +21,32 @@ 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 } {
45
+ /**
46
+ * Splits a frame into header fields, the stored (possibly deflated) body, the header's bytes, and the CRC the
47
+ * trailer claims. The caller checks `crc32(decodedBody, crc32(headerBytes)) === crc` once it has inflated.
48
+ */
49
+ export function readFrame(bytes: Uint8Array): { header: FrameHeader; headerBytes: Uint8Array; stored: Uint8Array; crc: number } {
43
50
  if (bytes.length < 4 + 2 + 1 + 1 + 32 + 4) throw new PackFormatError('truncated frame');
44
51
  const r = new ByteReader(bytes);
45
52
  for (const m of MAGIC) if (r.u8() !== m) throw new PackFormatError('not a BFKP pack (bad magic)');
@@ -48,10 +55,11 @@ export function readFrame(bytes: Uint8Array): { header: FrameHeader; stored: Uin
48
55
  const flags = r.u8();
49
56
  const rootId = r.str();
50
57
  const baseGeneration = r.varint();
51
- const targetDigest = hexOf(r.bytes(32));
58
+ const targetDigest = toHex(r.bytes(32));
59
+ const headerBytes = bytes.subarray(0, r.offset);
52
60
  if (r.remaining < 4) throw new PackFormatError('truncated frame');
53
61
  const stored = r.bytes(r.remaining - 4);
54
- return { header: { flags, rootId, baseGeneration, targetDigest }, stored, crc: r.u32le() };
62
+ return { header: { flags, rootId, baseGeneration, targetDigest }, headerBytes, stored, crc: r.u32le() };
55
63
  }
56
64
 
57
65
  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
+ }
@@ -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
 
@@ -55,6 +56,37 @@ describe('BFKP guards', () => {
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)); }
@@ -6,6 +6,7 @@
6
6
  import type { NodeRef, StoredFact, StoredRelation } from '../types.js';
7
7
  import { boundedCount, ByteReader, ByteWriter, PackFormatError } 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]!;
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  import { boundedCount, ByteReader, ByteWriter, PackFormatError } from '../varint.js';
9
+ import { fromHex64, toHex } from '../hex.js';
9
10
  import type { Pack } from '../types.js';
10
11
  import type { SectionCodec } from './columns.js';
11
12
  import { MANIFEST_BUCKETS } from '../manifest.js';
@@ -27,7 +28,7 @@ export const fileSection: SectionCodec = {
27
28
  },
28
29
  read(bytes, t, limits, into) {
29
30
  const r = new ByteReader(bytes);
30
- const n = boundedCount(r, limits.maxRows, 'files');
31
+ const n = boundedCount(r, limits.budget, 'files');
31
32
  const paths: string[] = [];
32
33
  let prev = 0;
33
34
  for (let i = 0; i < n; i++) { prev += r.varint(); paths.push(t.str(prev)); }
@@ -50,7 +51,7 @@ export const staleSection: SectionCodec = {
50
51
  },
51
52
  read(bytes, t, limits, into) {
52
53
  const r = new ByteReader(bytes);
53
- const n = boundedCount(r, limits.maxRows, 'stale');
54
+ const n = boundedCount(r, limits.budget, 'stale');
54
55
  const refs: string[] = [];
55
56
  let prev = 0;
56
57
  for (let i = 0; i < n; i++) { prev += r.varint(); refs.push(t.str(prev)); }
@@ -79,13 +80,13 @@ export const deleteSection: SectionCodec = {
79
80
  const r = new ByteReader(bytes);
80
81
  const lists: string[][] = [];
81
82
  for (let k = 0; k < 2; k++) {
82
- const n = boundedCount(r, limits.maxRows, 'tombstones');
83
+ const n = boundedCount(r, limits.budget, 'tombstones');
83
84
  const out: string[] = [];
84
85
  let prev = 0;
85
86
  for (let i = 0; i < n; i++) { prev += r.varint(); out.push(t.str(prev)); }
86
87
  lists.push(out);
87
88
  }
88
- const n = boundedCount(r, limits.maxRows, 'relation tombstones');
89
+ const n = boundedCount(r, limits.budget, 'relation tombstones');
89
90
  const from = Array.from({ length: n }, () => t.str(r.varint()));
90
91
  const to = Array.from({ length: n }, () => t.str(r.varint()));
91
92
  const kind = Array.from({ length: n }, () => t.str(r.varint()));
@@ -111,7 +112,7 @@ export const scopeSection: SectionCodec = {
111
112
  read(bytes, t, limits, into) {
112
113
  const r = new ByteReader(bytes);
113
114
  const scope: NonNullable<Pack['scope']> = { rootId: t.str(r.varint()), title: t.str(r.varint()), packs: [] };
114
- const n = boundedCount(r, limits.maxRows, 'packs');
115
+ const n = boundedCount(r, limits.budget, 'packs');
115
116
  for (let i = 0; i < n; i++) scope.packs.push(t.str(r.varint()));
116
117
  const flags = r.u8();
117
118
  if (flags & 1) scope.lastDigest = t.str(r.varint());
@@ -120,13 +121,20 @@ export const scopeSection: SectionCodec = {
120
121
  },
121
122
  };
122
123
 
124
+ /** Object keys in sorted order, recursively: equal documents become equal bytes however their keys were built. */
125
+ const canonical = (v: unknown): unknown => {
126
+ if (Array.isArray(v)) return v.map(canonical);
127
+ if (v && typeof v === 'object') return Object.fromEntries(Object.keys(v).sort().map((k) => [k, canonical((v as Record<string, unknown>)[k])]));
128
+ return v;
129
+ };
130
+
123
131
  /** The analysis snapshot is one JSON-compatible document with no row structure; it travels as one string (deflate does the rest). */
124
132
  export const analysisSection: SectionCodec = {
125
133
  tag: TAG.ANALYSIS,
126
134
  write(pack, t) {
127
135
  if (pack.analysis === undefined) return undefined;
128
136
  const w = new ByteWriter();
129
- w.varint(t.str(JSON.stringify(pack.analysis)));
137
+ w.varint(t.str(JSON.stringify(canonical(pack.analysis))));
130
138
  return w.finish();
131
139
  },
132
140
  read(bytes, t, _limits, into) {
@@ -148,7 +156,7 @@ export const leafSection: SectionCodec = {
148
156
  },
149
157
  read(bytes, t, limits, into) {
150
158
  const r = new ByteReader(bytes);
151
- const n = boundedCount(r, limits.maxRows, 'leaves');
159
+ const n = boundedCount(r, limits.budget, 'leaves');
152
160
  const keys: string[] = [];
153
161
  let prev = 0;
154
162
  for (let i = 0; i < n; i++) { prev += r.varint(); keys.push(t.str(prev)); }
@@ -164,21 +172,13 @@ export const bucketSection: SectionCodec = {
164
172
  if (!b) return undefined;
165
173
  if (b.length !== MANIFEST_BUCKETS) throw new PackFormatError(`a bucket list holds ${MANIFEST_BUCKETS} digests`);
166
174
  const w = new ByteWriter();
167
- for (const hex of b) {
168
- const raw = new Uint8Array(32);
169
- for (let i = 0; i < 32; i++) raw[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
170
- w.bytes(raw);
171
- }
175
+ for (const hex of b) w.bytes(fromHex64(hex));
172
176
  return w.finish();
173
177
  },
174
178
  read(bytes, _t, _limits, into) {
175
179
  if (bytes.length !== MANIFEST_BUCKETS * 32) throw new PackFormatError('bucket section has the wrong size');
176
180
  const out: string[] = [];
177
- for (let i = 0; i < MANIFEST_BUCKETS; i++) {
178
- let hex = '';
179
- for (const b of bytes.subarray(i * 32, i * 32 + 32)) hex += (b < 16 ? '0' : '') + b.toString(16);
180
- out.push(hex);
181
- }
181
+ for (let i = 0; i < MANIFEST_BUCKETS; i++) out.push(toHex(bytes.subarray(i * 32, i * 32 + 32)));
182
182
  into.buckets = out;
183
183
  },
184
184
  };
@@ -10,6 +10,8 @@
10
10
  * first pass with {@link collector} gathers what is used, a second with {@link tablesOf} writes real indexes.
11
11
  */
12
12
 
13
+ import { fromHex64, HEX64, toHex } from './hex.js';
14
+ import { PackTooLargeError } from './types.js';
13
15
  import { boundedCount, ByteReader, ByteWriter, PackFormatError, utf8 } from './varint.js';
14
16
 
15
17
  /** What a section encoder needs: the index of a string and of a hash. */
@@ -24,7 +26,6 @@ export interface ReadTables {
24
26
  hash(i: number): string;
25
27
  }
26
28
 
27
- const HEX64 = /^[0-9a-f]{64}$/;
28
29
 
29
30
  /** A pass-1 `Tables` that records every string and hash it is asked for. */
30
31
  export function collector(): Tables & { strings: Set<string>; hashes: Set<string> } {
@@ -63,15 +64,22 @@ export function writeStringTable(strings: readonly string[]): Uint8Array {
63
64
  return w.finish();
64
65
  }
65
66
 
66
- export function readStringTable(bytes: Uint8Array, maxStrings: number): string[] {
67
+ /**
68
+ * Reads the front-coded string table. `maxBytes` bounds the table's TOTAL decoded bytes: front coding lets a few
69
+ * input bytes name a very long string many times over, so the cap is on what is built, not on what was sent.
70
+ */
71
+ export function readStringTable(bytes: Uint8Array, maxStrings: number, maxBytes: number): string[] {
67
72
  const r = new ByteReader(bytes);
68
- const n = boundedCount(r, maxStrings, 'string table');
73
+ const n = boundedCount(r, { left: maxStrings }, 'string table');
69
74
  const dec = new TextDecoder('utf-8', { fatal: true });
70
75
  const out: string[] = [];
71
76
  let prev: Uint8Array = new Uint8Array(0);
77
+ let total = 0;
72
78
  for (let i = 0; i < n; i++) {
73
79
  const shared = r.varint(), rest = r.varint();
74
80
  if (shared > prev.length) throw new PackFormatError('string table: prefix longer than the previous string');
81
+ total += shared + rest;
82
+ if (total > maxBytes) throw new PackTooLargeError(maxBytes);
75
83
  const b = new Uint8Array(shared + rest);
76
84
  b.set(prev.subarray(0, shared));
77
85
  b.set(r.bytes(rest), shared);
@@ -87,9 +95,7 @@ export function writeHashTable(hashes: readonly string[]): Uint8Array {
87
95
  for (const h of hashes) {
88
96
  if (HEX64.test(h)) {
89
97
  w.u8(0);
90
- const raw = new Uint8Array(32);
91
- for (let i = 0; i < 32; i++) raw[i] = parseInt(h.slice(i * 2, i * 2 + 2), 16);
92
- w.bytes(raw);
98
+ w.bytes(fromHex64(h));
93
99
  } else {
94
100
  w.u8(1);
95
101
  w.str(h);
@@ -100,15 +106,12 @@ export function writeHashTable(hashes: readonly string[]): Uint8Array {
100
106
 
101
107
  export function readHashTable(bytes: Uint8Array, maxHashes: number): string[] {
102
108
  const r = new ByteReader(bytes);
103
- const n = boundedCount(r, maxHashes, 'hash table');
109
+ const n = boundedCount(r, { left: maxHashes }, 'hash table');
104
110
  const out: string[] = [];
105
111
  for (let i = 0; i < n; i++) {
106
112
  const flag = r.u8();
107
- if (flag === 0) {
108
- let hex = '';
109
- for (const b of r.bytes(32)) hex += (b < 16 ? '0' : '') + b.toString(16);
110
- out.push(hex);
111
- } else if (flag === 1) out.push(r.str());
113
+ if (flag === 0) out.push(toHex(r.bytes(32)));
114
+ else if (flag === 1) out.push(r.str());
112
115
  else throw new PackFormatError('hash table: unknown entry flag');
113
116
  }
114
117
  return out;
@@ -5,6 +5,7 @@
5
5
  */
6
6
 
7
7
  import type { Extracted, KEdge, KNode, NodeRef, ScopeRecord, StoredFact, StoredOrigin, StoredRelation } from '../model.js';
8
+ import type { Budget } from './varint.js';
8
9
 
9
10
  /** A reviewed file: its root-relative path, the hash its extracted output is keyed under, and its size. */
10
11
  export interface PackFileRow { path: string; hash: string; bytes: number }
@@ -79,6 +80,13 @@ export interface PackLimits {
79
80
  maxRows: number;
80
81
  }
81
82
 
83
+ /**
84
+ * The limits a decode reads under. `maxRows` is CUMULATIVE: one `budget` is drawn down by every list of every
85
+ * section, so a pack of many small lists is bounded as a whole. `maxDecodedBytes` bounds the inflated body AND the
86
+ * total bytes of the string table.
87
+ */
88
+ export interface ReadLimits extends PackLimits { budget: Budget }
89
+
82
90
  export const DEFAULT_PACK_LIMITS: PackLimits = { maxDecodedBytes: 64 * 1024 * 1024, maxStrings: 2_000_000, maxRows: 1_000_000 };
83
91
 
84
92
  /** The decoded body inflated past `maxDecodedBytes`: the server answers 413 `pack_too_large`. */
@@ -130,9 +130,16 @@ export class ByteReader {
130
130
  }
131
131
  }
132
132
 
133
- /** A count that is bounded before anything is allocated for it. */
134
- export function boundedCount(r: ByteReader, max: number, what: string): number {
133
+ /** What a whole pack may still hold: every list a decode reads draws its count from ONE budget. */
134
+ export interface Budget { left: number }
135
+
136
+ /**
137
+ * A count that is bounded before anything is allocated for it, and drawn from the pack's cumulative budget, so
138
+ * many lists that are each small cannot add up to a memory bomb.
139
+ */
140
+ export function boundedCount(r: ByteReader, budget: Budget, what: string): number {
135
141
  const n = r.varint();
136
- if (n > max) throw new PackFormatError(`${what}: ${n} exceeds the bound ${max}`);
142
+ if (n > budget.left) throw new PackFormatError(`${what}: ${n} exceeds the pack's row budget (${budget.left} left)`);
143
+ budget.left -= n;
137
144
  return n;
138
145
  }
@@ -18,6 +18,12 @@ export interface DirectorySource {
18
18
  /** `signal` aborts the read when the review gives up on it (a per-job timeout, a stop); a source that cannot cancel may ignore it. */
19
19
  read(path: string, signal?: AbortSignal): Promise<SourceDocument>;
20
20
  watch?(cb: (paths: string[]) => void): () => void;
21
+ /**
22
+ * The function that produced the `hash` of `list()` entries, over a text file's content. When given, the review hashes the
23
+ * text it read (once) and a file whose bytes no longer match the planned hash fails with "changed since plan" and stays owed.
24
+ * Optional: a source whose hash is not a pure function of the text (or that cannot say) is not checked in-thread.
25
+ */
26
+ hashOf?(text: string): string;
21
27
  }
22
28
 
23
29
  export interface ReviewPlan {
@@ -58,6 +58,9 @@ export function extractStepOf(path: string, job: Prefetch): ReviewStep {
58
58
  }
59
59
  }
60
60
 
61
+ /** The failure reason of a file whose bytes no longer match the planned hash. */
62
+ export const CHANGED_SINCE_PLAN = 'changed since plan';
63
+
61
64
  /** Per-job ceilings of the extract path (PRD 41 A10 rule 2). */
62
65
  export const DEFAULT_READ_TIMEOUT_MS = 5_000;
63
66
  export const DEFAULT_EXTRACT_TIMEOUT_MS = 10_000;
@@ -94,7 +97,13 @@ export function createPrefetch(c: PrefetchContext): (f: { path: string; hash: st
94
97
  ...(c.args.extractPool ? { pool: c.args.extractPool, signal, wantsSections, ...(byPool ? { readByPool: true } : {}) } : {}),
95
98
  })); } finally { lanes.free(held.lane); }
96
99
  });
97
- return extraction ? { kind: 'extracted', ...(doc ? { doc } : {}), extraction } : { kind: 'none' };
100
+ if (!extraction) return { kind: 'none' };
101
+ // Binary and no-pack files are decided above and never hash-checked (as in the host worker). For a file that WILL be
102
+ // stored, the bytes read must be the bytes planned: hashed once, from the text already in hand. The review writes the
103
+ // extract cache only for an 'extracted' job, so nothing is stored under the stale hash.
104
+ const hashOf = c.args.source.hashOf;
105
+ if (hashOf && doc && doc.content.kind === 'text' && hashOf(doc.content.text) !== f.hash) return { kind: 'failed', reason: CHANGED_SINCE_PLAN };
106
+ return { kind: 'extracted', ...(doc ? { doc } : {}), extraction };
98
107
  } catch (error) {
99
108
  if (error instanceof BinaryContent) return { kind: 'binary' };
100
109
  return { kind: 'failed', reason: reasonOf(error) };