@seanhogg/builderforce-memory 2026.10.45 → 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 (187) hide show
  1. package/README.md +21 -0
  2. package/dist/knowledge/build.d.ts.map +1 -1
  3. package/dist/knowledge/build.js +13 -7
  4. package/dist/knowledge/build.js.map +1 -1
  5. package/dist/knowledge/extractFile.d.ts +9 -1
  6. package/dist/knowledge/extractFile.d.ts.map +1 -1
  7. package/dist/knowledge/extractFile.js +25 -5
  8. package/dist/knowledge/extractFile.js.map +1 -1
  9. package/dist/knowledge/extractJob.d.ts +30 -5
  10. package/dist/knowledge/extractJob.d.ts.map +1 -1
  11. package/dist/knowledge/extractJob.js +9 -1
  12. package/dist/knowledge/extractJob.js.map +1 -1
  13. package/dist/knowledge/index.d.ts +5 -3
  14. package/dist/knowledge/index.d.ts.map +1 -1
  15. package/dist/knowledge/index.js +2 -1
  16. package/dist/knowledge/index.js.map +1 -1
  17. package/dist/knowledge/jobDeadline.d.ts +17 -0
  18. package/dist/knowledge/jobDeadline.d.ts.map +1 -0
  19. package/dist/knowledge/jobDeadline.js +46 -0
  20. package/dist/knowledge/jobDeadline.js.map +1 -0
  21. package/dist/knowledge/judgeCalls.d.ts +16 -0
  22. package/dist/knowledge/judgeCalls.d.ts.map +1 -1
  23. package/dist/knowledge/judgeCalls.js +20 -1
  24. package/dist/knowledge/judgeCalls.js.map +1 -1
  25. package/dist/knowledge/judgePriority.d.ts +22 -0
  26. package/dist/knowledge/judgePriority.d.ts.map +1 -0
  27. package/dist/knowledge/judgePriority.js +28 -0
  28. package/dist/knowledge/judgePriority.js.map +1 -0
  29. package/dist/knowledge/pack/crc32.d.ts +7 -0
  30. package/dist/knowledge/pack/crc32.d.ts.map +1 -0
  31. package/dist/knowledge/pack/crc32.js +22 -0
  32. package/dist/knowledge/pack/crc32.js.map +1 -0
  33. package/dist/knowledge/pack/decode.d.ts +14 -0
  34. package/dist/knowledge/pack/decode.d.ts.map +1 -0
  35. package/dist/knowledge/pack/decode.js +66 -0
  36. package/dist/knowledge/pack/decode.js.map +1 -0
  37. package/dist/knowledge/pack/deflate.d.ts +9 -0
  38. package/dist/knowledge/pack/deflate.d.ts.map +1 -0
  39. package/dist/knowledge/pack/deflate.js +45 -0
  40. package/dist/knowledge/pack/deflate.js.map +1 -0
  41. package/dist/knowledge/pack/encode.d.ts +26 -0
  42. package/dist/knowledge/pack/encode.d.ts.map +1 -0
  43. package/dist/knowledge/pack/encode.js +86 -0
  44. package/dist/knowledge/pack/encode.js.map +1 -0
  45. package/dist/knowledge/pack/extrDiff.d.ts +26 -0
  46. package/dist/knowledge/pack/extrDiff.d.ts.map +1 -0
  47. package/dist/knowledge/pack/extrDiff.js +129 -0
  48. package/dist/knowledge/pack/extrDiff.js.map +1 -0
  49. package/dist/knowledge/pack/frame.d.ts +45 -0
  50. package/dist/knowledge/pack/frame.d.ts.map +1 -0
  51. package/dist/knowledge/pack/frame.js +101 -0
  52. package/dist/knowledge/pack/frame.js.map +1 -0
  53. package/dist/knowledge/pack/hex.d.ts +7 -0
  54. package/dist/knowledge/pack/hex.d.ts.map +1 -0
  55. package/dist/knowledge/pack/hex.js +17 -0
  56. package/dist/knowledge/pack/hex.js.map +1 -0
  57. package/dist/knowledge/pack/index.d.ts +19 -0
  58. package/dist/knowledge/pack/index.d.ts.map +1 -0
  59. package/dist/knowledge/pack/index.js +17 -0
  60. package/dist/knowledge/pack/index.js.map +1 -0
  61. package/dist/knowledge/pack/jsonSize.d.ts +5 -0
  62. package/dist/knowledge/pack/jsonSize.d.ts.map +1 -0
  63. package/dist/knowledge/pack/jsonSize.js +8 -0
  64. package/dist/knowledge/pack/jsonSize.js.map +1 -0
  65. package/dist/knowledge/pack/manifest.d.ts +66 -0
  66. package/dist/knowledge/pack/manifest.d.ts.map +1 -0
  67. package/dist/knowledge/pack/manifest.js +104 -0
  68. package/dist/knowledge/pack/manifest.js.map +1 -0
  69. package/dist/knowledge/pack/sections/columns.d.ts +32 -0
  70. package/dist/knowledge/pack/sections/columns.d.ts.map +1 -0
  71. package/dist/knowledge/pack/sections/columns.js +53 -0
  72. package/dist/knowledge/pack/sections/columns.js.map +1 -0
  73. package/dist/knowledge/pack/sections/extr.d.ts +8 -0
  74. package/dist/knowledge/pack/sections/extr.d.ts.map +1 -0
  75. package/dist/knowledge/pack/sections/extr.js +99 -0
  76. package/dist/knowledge/pack/sections/extr.js.map +1 -0
  77. package/dist/knowledge/pack/sections/extrLists.d.ts +23 -0
  78. package/dist/knowledge/pack/sections/extrLists.d.ts.map +1 -0
  79. package/dist/knowledge/pack/sections/extrLists.js +200 -0
  80. package/dist/knowledge/pack/sections/extrLists.js.map +1 -0
  81. package/dist/knowledge/pack/sections/facts.d.ts +8 -0
  82. package/dist/knowledge/pack/sections/facts.d.ts.map +1 -0
  83. package/dist/knowledge/pack/sections/facts.js +172 -0
  84. package/dist/knowledge/pack/sections/facts.js.map +1 -0
  85. package/dist/knowledge/pack/sections/index.d.ts +6 -0
  86. package/dist/knowledge/pack/sections/index.d.ts.map +1 -0
  87. package/dist/knowledge/pack/sections/index.js +9 -0
  88. package/dist/knowledge/pack/sections/index.js.map +1 -0
  89. package/dist/knowledge/pack/sections/rows.d.ts +31 -0
  90. package/dist/knowledge/pack/sections/rows.d.ts.map +1 -0
  91. package/dist/knowledge/pack/sections/rows.js +227 -0
  92. package/dist/knowledge/pack/sections/rows.js.map +1 -0
  93. package/dist/knowledge/pack/strings.d.ts +43 -0
  94. package/dist/knowledge/pack/strings.d.ts.map +1 -0
  95. package/dist/knowledge/pack/strings.js +117 -0
  96. package/dist/knowledge/pack/strings.js.map +1 -0
  97. package/dist/knowledge/pack/types.d.ts +118 -0
  98. package/dist/knowledge/pack/types.d.ts.map +1 -0
  99. package/dist/knowledge/pack/types.js +17 -0
  100. package/dist/knowledge/pack/types.js.map +1 -0
  101. package/dist/knowledge/pack/varint.d.ts +57 -0
  102. package/dist/knowledge/pack/varint.d.ts.map +1 -0
  103. package/dist/knowledge/pack/varint.js +145 -0
  104. package/dist/knowledge/pack/varint.js.map +1 -0
  105. package/dist/knowledge/partitions.d.ts +1 -1
  106. package/dist/knowledge/partitions.d.ts.map +1 -1
  107. package/dist/knowledge/partitions.js +6 -1
  108. package/dist/knowledge/partitions.js.map +1 -1
  109. package/dist/knowledge/review.d.ts.map +1 -1
  110. package/dist/knowledge/review.js +58 -16
  111. package/dist/knowledge/review.js.map +1 -1
  112. package/dist/knowledge/reviewJudge.d.ts +8 -1
  113. package/dist/knowledge/reviewJudge.d.ts.map +1 -1
  114. package/dist/knowledge/reviewJudge.js +14 -8
  115. package/dist/knowledge/reviewJudge.js.map +1 -1
  116. package/dist/knowledge/reviewModel.d.ts +41 -1
  117. package/dist/knowledge/reviewModel.d.ts.map +1 -1
  118. package/dist/knowledge/reviewPrefetch.d.ts +10 -2
  119. package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
  120. package/dist/knowledge/reviewPrefetch.js +60 -25
  121. package/dist/knowledge/reviewPrefetch.js.map +1 -1
  122. package/dist/knowledge/reviewRun.d.ts +15 -3
  123. package/dist/knowledge/reviewRun.d.ts.map +1 -1
  124. package/dist/knowledge/reviewRun.js +19 -2
  125. package/dist/knowledge/reviewRun.js.map +1 -1
  126. package/dist/knowledge/reviewRunModel.d.ts +8 -1
  127. package/dist/knowledge/reviewRunModel.d.ts.map +1 -1
  128. package/dist/knowledge/reviewRunModel.js.map +1 -1
  129. package/dist/knowledge/stores/localSnapshotStore.d.ts +72 -6
  130. package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
  131. package/dist/knowledge/stores/localSnapshotStore.js +279 -75
  132. package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
  133. package/package.json +8 -3
  134. package/src/contract/dist.contract.test.ts +44 -0
  135. package/src/contract/exports.contract.test.ts +90 -0
  136. package/src/contract/exports.snapshot.json +605 -0
  137. package/src/contract/pack.contract.test.ts +31 -0
  138. package/src/contract/regression.review.test.ts +236 -0
  139. package/src/contract/regression.store.test.ts +84 -0
  140. package/src/contract/types.contract.test.ts +183 -0
  141. package/src/knowledge/build.ts +11 -5
  142. package/src/knowledge/extractFile.ts +28 -6
  143. package/src/knowledge/extractJob.ts +26 -7
  144. package/src/knowledge/index.ts +5 -3
  145. package/src/knowledge/jobDeadline.ts +43 -0
  146. package/src/knowledge/judgeCalls.ts +19 -2
  147. package/src/knowledge/judgePriority.ts +36 -0
  148. package/src/knowledge/pack/crc32.ts +21 -0
  149. package/src/knowledge/pack/decode.ts +60 -0
  150. package/src/knowledge/pack/deflate.ts +43 -0
  151. package/src/knowledge/pack/encode.ts +89 -0
  152. package/src/knowledge/pack/extrDiff.ts +116 -0
  153. package/src/knowledge/pack/frame.ts +94 -0
  154. package/src/knowledge/pack/hex.ts +17 -0
  155. package/src/knowledge/pack/index.ts +26 -0
  156. package/src/knowledge/pack/jsonSize.ts +11 -0
  157. package/src/knowledge/pack/manifest.ts +128 -0
  158. package/src/knowledge/pack/pack.guards.test.ts +109 -0
  159. package/src/knowledge/pack/pack.reconcile.test.ts +96 -0
  160. package/src/knowledge/pack/pack.roundtrip.test.ts +50 -0
  161. package/src/knowledge/pack/pack.size.test.ts +22 -0
  162. package/src/knowledge/pack/pack.testkit.test-util.ts +90 -0
  163. package/src/knowledge/pack/sections/columns.ts +61 -0
  164. package/src/knowledge/pack/sections/extr.ts +90 -0
  165. package/src/knowledge/pack/sections/extrLists.ts +151 -0
  166. package/src/knowledge/pack/sections/facts.ts +126 -0
  167. package/src/knowledge/pack/sections/index.ts +13 -0
  168. package/src/knowledge/pack/sections/rows.ts +184 -0
  169. package/src/knowledge/pack/strings.ts +126 -0
  170. package/src/knowledge/pack/types.ts +97 -0
  171. package/src/knowledge/pack/varint.ts +145 -0
  172. package/src/knowledge/partitions.test.ts +4 -0
  173. package/src/knowledge/partitions.ts +3 -1
  174. package/src/knowledge/review.throughput.test.ts +122 -0
  175. package/src/knowledge/review.ts +54 -16
  176. package/src/knowledge/review.twoPass.test.ts +224 -0
  177. package/src/knowledge/reviewJudge.ts +19 -8
  178. package/src/knowledge/reviewModel.ts +38 -1
  179. package/src/knowledge/reviewPrefetch.ts +60 -24
  180. package/src/knowledge/reviewRun.test.ts +20 -3
  181. package/src/knowledge/reviewRun.ts +33 -6
  182. package/src/knowledge/reviewRunModel.ts +4 -1
  183. package/src/knowledge/stores/localSnapshotStore.batched.test.ts +25 -3
  184. package/src/knowledge/stores/localSnapshotStore.extractedLog.test.ts +280 -0
  185. package/src/knowledge/stores/localSnapshotStore.ts +283 -76
  186. package/src/knowledge/systems.test.ts +12 -0
  187. package/src/knowledge/testkit.test-util.ts +13 -2
@@ -0,0 +1,126 @@
1
+ /**
2
+ * knowledge/pack/strings.ts — the STR and HASH sections of BFKP v1 (PRD 41 A11).
3
+ *
4
+ * STR every path, key, ref, symbol name and label once, sorted and front-coded: for each
5
+ * string the length of the byte prefix it shares with the one before, then the suffix.
6
+ * HASH every content hash once, sorted. A 64-character lowercase hex hash is stored as its raw
7
+ * 32 bytes (flag 0); any other id (a root-level `~tag:…` output) as UTF-8 (flag 1).
8
+ *
9
+ * Sections refer to both by index. Encoding runs each section encoder twice (see encode.ts): a
10
+ * first pass with {@link collector} gathers what is used, a second with {@link tablesOf} writes real indexes.
11
+ */
12
+
13
+ import { fromHex64, HEX64, toHex } from './hex.js';
14
+ import { PackTooLargeError } from './types.js';
15
+ import { boundedCount, ByteReader, ByteWriter, PackFormatError, utf8 } from './varint.js';
16
+
17
+ /** What a section encoder needs: the index of a string and of a hash. */
18
+ export interface Tables {
19
+ str(s: string): number;
20
+ hash(h: string): number;
21
+ }
22
+
23
+ /** What a section decoder needs: the string and hash at an index. */
24
+ export interface ReadTables {
25
+ str(i: number): string;
26
+ hash(i: number): string;
27
+ }
28
+
29
+
30
+ /** A pass-1 `Tables` that records every string and hash it is asked for. */
31
+ export function collector(): Tables & { strings: Set<string>; hashes: Set<string> } {
32
+ const strings = new Set<string>(), hashes = new Set<string>();
33
+ return { strings, hashes, str: (s) => { strings.add(s); return 0; }, hash: (h) => { hashes.add(h); return 0; } };
34
+ }
35
+
36
+ export interface BuiltTables extends Tables { strings: string[]; hashes: string[] }
37
+
38
+ /** The real tables over what pass 1 collected: sorted, so equal input gives equal bytes. */
39
+ export function tablesOf(strings: Iterable<string>, hashes: Iterable<string>): BuiltTables {
40
+ const s = [...new Set(strings)].sort(), h = [...new Set(hashes)].sort();
41
+ const si = new Map(s.map((v, i) => [v, i])), hi = new Map(h.map((v, i) => [v, i]));
42
+ return { strings: s, hashes: h, str: (v) => si.get(v)!, hash: (v) => hi.get(v)! };
43
+ }
44
+
45
+ function commonPrefix(a: Uint8Array, b: Uint8Array): number {
46
+ const n = Math.min(a.length, b.length);
47
+ let i = 0;
48
+ while (i < n && a[i] === b[i]) i++;
49
+ return i;
50
+ }
51
+
52
+ export function writeStringTable(strings: readonly string[]): Uint8Array {
53
+ const w = new ByteWriter();
54
+ w.varint(strings.length);
55
+ let prev: Uint8Array = new Uint8Array(0);
56
+ for (const s of strings) {
57
+ const b = utf8(s);
58
+ const shared = commonPrefix(prev, b);
59
+ w.varint(shared);
60
+ w.varint(b.length - shared);
61
+ w.bytes(b.subarray(shared));
62
+ prev = b;
63
+ }
64
+ return w.finish();
65
+ }
66
+
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[] {
72
+ const r = new ByteReader(bytes);
73
+ const n = boundedCount(r, { left: maxStrings }, 'string table');
74
+ const dec = new TextDecoder('utf-8', { fatal: true });
75
+ const out: string[] = [];
76
+ let prev: Uint8Array = new Uint8Array(0);
77
+ let total = 0;
78
+ for (let i = 0; i < n; i++) {
79
+ const shared = r.varint(), rest = r.varint();
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);
83
+ const b = new Uint8Array(shared + rest);
84
+ b.set(prev.subarray(0, shared));
85
+ b.set(r.bytes(rest), shared);
86
+ try { out.push(dec.decode(b)); } catch { throw new PackFormatError('string table: invalid UTF-8'); }
87
+ prev = b;
88
+ }
89
+ return out;
90
+ }
91
+
92
+ export function writeHashTable(hashes: readonly string[]): Uint8Array {
93
+ const w = new ByteWriter();
94
+ w.varint(hashes.length);
95
+ for (const h of hashes) {
96
+ if (HEX64.test(h)) {
97
+ w.u8(0);
98
+ w.bytes(fromHex64(h));
99
+ } else {
100
+ w.u8(1);
101
+ w.str(h);
102
+ }
103
+ }
104
+ return w.finish();
105
+ }
106
+
107
+ export function readHashTable(bytes: Uint8Array, maxHashes: number): string[] {
108
+ const r = new ByteReader(bytes);
109
+ const n = boundedCount(r, { left: maxHashes }, 'hash table');
110
+ const out: string[] = [];
111
+ for (let i = 0; i < n; i++) {
112
+ const flag = r.u8();
113
+ if (flag === 0) out.push(toHex(r.bytes(32)));
114
+ else if (flag === 1) out.push(r.str());
115
+ else throw new PackFormatError('hash table: unknown entry flag');
116
+ }
117
+ return out;
118
+ }
119
+
120
+ /** The read-side lookup over decoded tables; an out-of-range index is a malformed pack. */
121
+ export function readTables(strings: readonly string[], hashes: readonly string[]): ReadTables {
122
+ return {
123
+ str: (i) => { const v = strings[i]; if (v === undefined) throw new PackFormatError('string index out of range'); return v; },
124
+ hash: (i) => { const v = hashes[i]; if (v === undefined) throw new PackFormatError('hash index out of range'); return v; },
125
+ };
126
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * knowledge/pack/types.ts — the BFKP v1 data model (PRD 41 A11): what `encodePack` takes and
3
+ * `decodePack` returns. Rows reuse the knowledge model's own types (`StoredFact`, `StoredRelation`,
4
+ * `Extracted`, `ScopeRecord`), so a pack carries exactly what the single writer stores.
5
+ */
6
+
7
+ import type { Extracted, KEdge, KNode, NodeRef, ScopeRecord, StoredFact, StoredOrigin, StoredRelation } from '../model.js';
8
+ import type { Budget } from './varint.js';
9
+
10
+ /** A reviewed file: its root-relative path, the hash its extracted output is keyed under, and its size. */
11
+ export interface PackFileRow { path: string; hash: string; bytes: number }
12
+
13
+ /** A source's current hash (what the old `markStale` call recorded). '' = the file was removed. */
14
+ export interface PackStaleRow { sourceRef: string; hash: string }
15
+
16
+ /** A relation's upsert identity. */
17
+ export interface RelationId { from: string; to: string; kind: string }
18
+
19
+ /** Tombstones: keys the sender no longer has. */
20
+ export interface PackDeletes { files: string[]; facts: string[]; relations: RelationId[] }
21
+
22
+ /** One list of a re-extracted entry, as a diff against the prior extraction: items to drop and items to insert at a position. */
23
+ export interface ListDiff<T> { remove: string[]; add: Array<{ at: number; item: T }> }
24
+
25
+ /** What changed in one source's extraction since the acknowledged prior one (same `sourceRef`). */
26
+ export interface ExtrEntryDiff {
27
+ sourceRef: string;
28
+ sourceHash: string;
29
+ extractorVersion?: number;
30
+ nodes: ListDiff<KNode>;
31
+ edges: ListDiff<KEdge>;
32
+ keys: ListDiff<{ ref: string; key: string }>;
33
+ }
34
+
35
+ /** The Extracted output of one content hash: whole, or as a diff against the prior hash's output. */
36
+ export type PackExtr =
37
+ | { kind: 'full'; hash: string; entries: Extracted[] }
38
+ | { kind: 'diff'; hash: string; prior: string; entries: ExtrEntryDiff[] };
39
+
40
+ /** A leaf of the manifest tree: a stable key and the digest of its content. */
41
+ export interface ManifestLeaf { key: string; digest: string }
42
+
43
+ /** Everything a pack can carry besides its frame fields. Every part is optional (an empty section is not written). */
44
+ export interface PackBody {
45
+ files?: PackFileRow[];
46
+ extracted?: PackExtr[];
47
+ facts?: StoredFact[];
48
+ relations?: StoredRelation[];
49
+ stale?: PackStaleRow[];
50
+ deletes?: PackDeletes;
51
+ scope?: ScopeRecord;
52
+ /** The analysis snapshot (JSON-compatible). */
53
+ analysis?: unknown;
54
+ /** Hashes named for their own sake (a `have` request). Hashes a section already references are not repeated here. */
55
+ hashes?: string[];
56
+ /** Manifest leaves (a reconcile answer). */
57
+ leaves?: ManifestLeaf[];
58
+ /** The 4,096 bucket digests of the manifest tree, hex (a manifest GET answer). */
59
+ buckets?: string[];
60
+ }
61
+
62
+ /** The frame fields plus the body. */
63
+ export interface Pack extends PackBody {
64
+ rootId: string;
65
+ /** The server generation this pack applies to; 0 = a full pack. */
66
+ baseGeneration: number;
67
+ /** The digest the server must reach after applying (64 hex); `ZERO_DIGEST` when the pack asserts none. */
68
+ targetDigest: string;
69
+ }
70
+
71
+ export const ZERO_DIGEST = '0'.repeat(64);
72
+
73
+ /** A pack's decoded counts, for guards before any work. */
74
+ export interface PackLimits {
75
+ /** Bytes the body may inflate to (default 64 MB). */
76
+ maxDecodedBytes: number;
77
+ /** Strings in the table (default 2,000,000). */
78
+ maxStrings: number;
79
+ /** Rows in any one section (default 1,000,000). */
80
+ maxRows: number;
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
+
90
+ export const DEFAULT_PACK_LIMITS: PackLimits = { maxDecodedBytes: 64 * 1024 * 1024, maxStrings: 2_000_000, maxRows: 1_000_000 };
91
+
92
+ /** The decoded body inflated past `maxDecodedBytes`: the server answers 413 `pack_too_large`. */
93
+ export class PackTooLargeError extends Error {
94
+ constructor(readonly limit: number) { super(`pack inflates past ${limit} bytes`); this.name = 'PackTooLargeError'; }
95
+ }
96
+
97
+ export type { Extracted, KEdge, KNode, NodeRef, ScopeRecord, StoredFact, StoredOrigin, StoredRelation };
@@ -0,0 +1,145 @@
1
+ /**
2
+ * knowledge/pack/varint.ts — the byte-level primitives of BFKP v1 (PRD 41 A11): a growable byte
3
+ * writer and a bounds-checked reader over unsigned LEB128 varints, raw bytes, UTF-8 strings, and
4
+ * a compact number codec. Pure TypeScript — no Buffer, no node: imports.
5
+ */
6
+
7
+ /** A malformed pack: the server answers 422 `bad_pack`. */
8
+ export class PackFormatError extends Error {
9
+ constructor(message: string) { super(message); this.name = 'PackFormatError'; }
10
+ }
11
+
12
+ const ENCODER = new TextEncoder();
13
+ const DECODER = new TextDecoder('utf-8', { fatal: true });
14
+
15
+ export const utf8 = (s: string): Uint8Array => ENCODER.encode(s);
16
+
17
+ /** Largest integer a varint carries (2^53 - 1, JS's safe integer). */
18
+ export const MAX_VARINT = Number.MAX_SAFE_INTEGER;
19
+
20
+ export class ByteWriter {
21
+ private buf = new Uint8Array(1024);
22
+ private len = 0;
23
+
24
+ private room(n: number): void {
25
+ if (this.len + n <= this.buf.length) return;
26
+ let cap = this.buf.length;
27
+ while (cap < this.len + n) cap *= 2;
28
+ const next = new Uint8Array(cap);
29
+ next.set(this.buf.subarray(0, this.len));
30
+ this.buf = next;
31
+ }
32
+
33
+ get length(): number { return this.len; }
34
+
35
+ u8(v: number): void { this.room(1); this.buf[this.len++] = v & 0xff; }
36
+
37
+ /** Unsigned LEB128. */
38
+ varint(v: number): void {
39
+ if (!Number.isSafeInteger(v) || v < 0) throw new PackFormatError(`not an unsigned varint: ${v}`);
40
+ this.room(8);
41
+ while (v >= 0x80) { this.buf[this.len++] = (v % 0x80) | 0x80; v = Math.floor(v / 0x80); }
42
+ this.buf[this.len++] = v;
43
+ }
44
+
45
+ bytes(b: Uint8Array): void { this.room(b.length); this.buf.set(b, this.len); this.len += b.length; }
46
+
47
+ /** A varint length, then the UTF-8 bytes. */
48
+ str(s: string): void { const b = utf8(s); this.varint(b.length); this.bytes(b); }
49
+
50
+ u32le(v: number): void { this.room(4); for (let i = 0; i < 4; i++) this.buf[this.len++] = (v >>> (8 * i)) & 0xff; }
51
+
52
+ f64(v: number): void {
53
+ this.room(8);
54
+ new DataView(this.buf.buffer, this.buf.byteOffset + this.len, 8).setFloat64(0, v, true);
55
+ this.len += 8;
56
+ }
57
+
58
+ /**
59
+ * A finite number, as small as it can be and always exactly recoverable: a non-negative integer
60
+ * (tag 0), a non-negative decimal of at most 6 places (tag 1, scaled), or a raw float64 (tag 2).
61
+ */
62
+ num(v: number): void {
63
+ if (Number.isSafeInteger(v) && v >= 0 && v < 2 ** 50) { this.varint(v * 4); return; }
64
+ if (v >= 0 && v < 2 ** 30) {
65
+ const scaled = Math.round(v * 1e6);
66
+ if (scaled / 1e6 === v) { this.varint(scaled * 4 + 1); return; }
67
+ }
68
+ this.varint(2);
69
+ this.f64(v);
70
+ }
71
+
72
+ finish(): Uint8Array { return this.buf.slice(0, this.len); }
73
+ }
74
+
75
+ export class ByteReader {
76
+ private pos = 0;
77
+ constructor(private readonly buf: Uint8Array) {}
78
+
79
+ get offset(): number { return this.pos; }
80
+ get done(): boolean { return this.pos >= this.buf.length; }
81
+ get remaining(): number { return this.buf.length - this.pos; }
82
+
83
+ u8(): number {
84
+ if (this.pos >= this.buf.length) throw new PackFormatError('unexpected end of data');
85
+ return this.buf[this.pos++]!;
86
+ }
87
+
88
+ varint(): number {
89
+ let result = 0, scale = 1;
90
+ for (let i = 0; i < 8; i++) {
91
+ const b = this.u8();
92
+ result += (b & 0x7f) * scale;
93
+ if ((b & 0x80) === 0) return result;
94
+ scale *= 0x80;
95
+ }
96
+ throw new PackFormatError('varint too long');
97
+ }
98
+
99
+ bytes(n: number): Uint8Array {
100
+ if (!Number.isSafeInteger(n) || n < 0 || this.pos + n > this.buf.length) throw new PackFormatError('unexpected end of data');
101
+ const out = this.buf.subarray(this.pos, this.pos + n);
102
+ this.pos += n;
103
+ return out;
104
+ }
105
+
106
+ str(): string {
107
+ try { return DECODER.decode(this.bytes(this.varint())); } catch (e) {
108
+ if (e instanceof PackFormatError) throw e;
109
+ throw new PackFormatError('invalid UTF-8');
110
+ }
111
+ }
112
+
113
+ u32le(): number {
114
+ const b = this.bytes(4);
115
+ return (b[0]! | (b[1]! << 8) | (b[2]! << 16) | (b[3]! << 24)) >>> 0;
116
+ }
117
+
118
+ f64(): number {
119
+ const b = this.bytes(8);
120
+ return new DataView(b.buffer, b.byteOffset, 8).getFloat64(0, true);
121
+ }
122
+
123
+ num(): number {
124
+ const v = this.varint();
125
+ const tag = v % 4;
126
+ if (tag === 0) return v / 4;
127
+ if (tag === 1) return (v - 1) / 4 / 1e6;
128
+ if (v === 2) return this.f64();
129
+ throw new PackFormatError('bad number tag');
130
+ }
131
+ }
132
+
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 {
141
+ const n = r.varint();
142
+ if (n > budget.left) throw new PackFormatError(`${what}: ${n} exceeds the pack's row budget (${budget.left} left)`);
143
+ budget.left -= n;
144
+ return n;
145
+ }
@@ -54,6 +54,10 @@ describe('globs and partitionOf', () => {
54
54
  expect(matchGlob('b.md', '*')).toBe(true);
55
55
  expect(matchGlob('x.ts', '*.{ts,tsx}')).toBe(true);
56
56
  expect(globToRegExp('a.b').test('aXb')).toBe(false);
57
+ // A backslash makes the next character literal.
58
+ expect(matchGlob('copy*/x.ts', 'copy\\*/**')).toBe(true);
59
+ expect(matchGlob('copyabc/x.ts', 'copy\\*/**')).toBe(false);
60
+ expect(matchGlob('a[1]', 'a\\[1\\]')).toBe(true);
57
61
  });
58
62
 
59
63
  it('takes the first matching rule', () => {
@@ -19,7 +19,7 @@ const globCache = new Map<string, RegExp>();
19
19
 
20
20
  /**
21
21
  * A glob as a RegExp over `/`-separated paths: `**` spans folders (`**\/` may match none),
22
- * `*` and `?` stay within one segment, `{a,b}` is alternation.
22
+ * `*` and `?` stay within one segment, `{a,b}` is alternation, `\x` is the literal `x`.
23
23
  */
24
24
  export function globToRegExp(glob: string): RegExp {
25
25
  const cached = globCache.get(glob);
@@ -27,6 +27,8 @@ export function globToRegExp(glob: string): RegExp {
27
27
  let re = '';
28
28
  for (let i = 0; i < glob.length; i++) {
29
29
  const ch = glob[i]!;
30
+ // A backslash makes the next character literal (`copy\*` is the folder named `copy*`), as in `.gitignore`.
31
+ if (ch === '\\' && i + 1 < glob.length) { re += escapeRe(glob[++i]!); continue; }
30
32
  if (ch === '*') {
31
33
  if (glob[i + 1] === '*') {
32
34
  const slashAfter = glob[i + 2] === '/';
@@ -0,0 +1,122 @@
1
+ /**
2
+ * src/knowledge/review.throughput.test.ts — PRD 41 A10 Accept: a 20,000-file folder is MAPPED by pass 1
3
+ * (`mechanical`) without a model call, through a pool of width 4, in time that measures the pipeline's own overhead (60 s is the CI ceiling,
4
+ * not the goal), and neither a slow snapshot checkpoint nor a 30,000-op replica queue with a slow durable write is waited on inside a file's step.
5
+ */
6
+
7
+ import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
8
+ import { extractJob, type ExtractPool } from './extractJob.js';
9
+ import { DOCS_PACK } from './packs/docs.js';
10
+ import type { KnowledgePack, KnowledgeStore, ReviewProgress } from './model.js';
11
+ import { reviewDirectory } from './review.js';
12
+ import { LocalSnapshotStore } from './stores/localSnapshotStore.js';
13
+ import { args, fakeJudge, memPersistence, memSource } from './testkit.test-util.js';
14
+
15
+ const TS_FILES = 19_800;
16
+ const MD_FILES = 200;
17
+ const TOTAL = TS_FILES + MD_FILES;
18
+ const CEILING_MS = 60_000;
19
+
20
+ /** A code-ish pack with no judgement: every `.ts` is one file node. */
21
+ const TS_PACK: KnowledgePack = {
22
+ id: 'ts', parsers: [{ id: 'ts', accepts: (s) => s.id.endsWith('.ts'), parse: () => [] }],
23
+ };
24
+
25
+ function fixture(): Record<string, string> {
26
+ const out: Record<string, string> = {};
27
+ for (let i = 0; i < TS_FILES; i++) out[`src/m${Math.floor(i / 100)}/f${i}.ts`] = `export const v${i} = ${i};\n`;
28
+ for (let i = 0; i < MD_FILES; i++) out[`docs/d${i}.md`] = `# D${i}\nbody ${i}\n`;
29
+ return out;
30
+ }
31
+
32
+ /** A pool of width 4 that extracts in-process, one job per tick, and records how many jobs it held at once. */
33
+ function fakePool(): { pool: ExtractPool; peak: () => number; calls: () => number } {
34
+ let busy = 0, peak = 0, calls = 0;
35
+ const packs = [TS_PACK, DOCS_PACK];
36
+ return {
37
+ peak: () => peak, calls: () => calls,
38
+ pool: async (job) => {
39
+ busy += 1; calls += 1; peak = Math.max(peak, busy);
40
+ await Promise.resolve();
41
+ const out = extractJob(job, packs);
42
+ busy -= 1;
43
+ return out;
44
+ },
45
+ };
46
+ }
47
+
48
+ describe('pass 1 throughput (PRD 41 A10)', () => {
49
+ it('maps 20,000 files with no model call through a pool of width 4 within the CI ceiling', async () => {
50
+ const judge = fakeJudge();
51
+ const { pool, peak, calls } = fakePool();
52
+ const phases: string[] = [];
53
+ const events: ReviewProgress[] = [];
54
+ const t0 = Date.now();
55
+ const report = await reviewDirectory(args(memSource(fixture()), new LocalSnapshotStore(memPersistence()), new InMemoryIngestManifest(), {
56
+ packs: [TS_PACK, DOCS_PACK], judgement: judge, mechanical: true, extractPool: pool, concurrency: 4,
57
+ onProgress: (p) => { events.push(p); if (phases[phases.length - 1] !== p.phase) phases.push(p.phase); },
58
+ }));
59
+ const elapsed = Date.now() - t0;
60
+
61
+ expect(judge.requests).toHaveLength(0);
62
+ expect(report.aborted).toBe(false);
63
+ expect(report.failures).toEqual([]);
64
+ expect(report.extracted).toBe(TOTAL);
65
+ expect(calls()).toBe(TOTAL);
66
+ expect(peak()).toBeLessThanOrEqual(4);
67
+ expect(report.awaitingJudge).toHaveLength(MD_FILES); // the docs are judged later; code never is
68
+ expect(report.awaitingJudgeCount).toBe(MD_FILES);
69
+ // The map is complete: memory's last word is `done` after every file reached extract and write.
70
+ expect(phases[phases.length - 1]).toBe('done');
71
+ expect(events.filter((e) => e.phase === 'write')).toHaveLength(TOTAL);
72
+ expect(elapsed).toBeLessThan(CEILING_MS);
73
+ }, 120_000);
74
+
75
+ it('does not wait for a snapshot checkpoint or a 30,000-op replica queue inside a file\'s step', async () => {
76
+ let release!: () => void;
77
+ const gate = new Promise<void>((r) => { release = r; });
78
+ const durable = memPersistence();
79
+ const write = durable.write;
80
+ let started = 0;
81
+ // Every durable write (the snapshot's checkpoints, the queue's saves) hangs until the run has applied its last file.
82
+ durable.write = async (s) => { started += 1; await gate; await write(s); };
83
+ const local = new LocalSnapshotStore(durable, { checkpointMs: 1 });
84
+
85
+ // The replica queue as the A7 wrapper uses it: 30,000 ops already queued, a durable save that is slow, and an `enqueue` that only appends.
86
+ const queue = { ops: Array.from({ length: 30_000 }, (_, i) => `op${i}`), saves: 0, enqueues: 0 };
87
+ const save = async (): Promise<void> => { queue.saves += 1; await gate; };
88
+ let saving: Promise<void> | undefined;
89
+ const enqueue = (op: string): void => {
90
+ queue.ops.push(op); queue.enqueues += 1;
91
+ saving ??= save().finally(() => { saving = undefined; }); // at most one save in flight; never awaited by a step
92
+ };
93
+ const replicated: KnowledgeStore = {
94
+ scopes: () => local.scopes(), facts: (s) => local.facts(s), relations: (s) => local.relations(s),
95
+ getExtracted: (h) => local.getExtracted(h),
96
+ batched: (work) => local.batched(work),
97
+ async write(batch) { await local.write(batch); enqueue(`w:${batch.facts.length}`); },
98
+ async markStale(scope, ref, hash) { await local.markStale(scope, ref, hash); enqueue(`s:${ref}`); },
99
+ async putExtracted(hash, ex) { await local.putExtracted(hash, ex); enqueue(`x:${hash}`); },
100
+ };
101
+
102
+ const files = fixture();
103
+ const small = Object.fromEntries(Object.entries(files).slice(0, 3_000));
104
+ const { pool } = fakePool();
105
+ let lastWrite = 0;
106
+ const total = Object.keys(small).length;
107
+ const report = await reviewDirectory(args(memSource(small), replicated, new InMemoryIngestManifest(), {
108
+ packs: [TS_PACK, DOCS_PACK], judgement: fakeJudge(), mechanical: true, extractPool: pool, concurrency: 4,
109
+ onProgress: (p) => {
110
+ if (p.phase !== 'write') return;
111
+ lastWrite = p.done + 1;
112
+ if (lastWrite === total) release(); // had a step awaited a pending durable write, this would never be reached
113
+ },
114
+ }));
115
+
116
+ expect(lastWrite).toBe(total);
117
+ expect(report.extracted).toBe(total);
118
+ expect(started).toBeGreaterThan(0); // checkpoints really were pending while files were applied
119
+ expect(queue.enqueues).toBeGreaterThan(total);
120
+ expect(queue.saves).toBeLessThanOrEqual(1 + Math.ceil(queue.enqueues / 500)); // saves are batched, not per op
121
+ }, 120_000);
122
+ });