@seanhogg/builderforce-memory 2026.10.44 → 2026.10.46
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/knowledge/build.d.ts.map +1 -1
- package/dist/knowledge/build.js +34 -2
- package/dist/knowledge/build.js.map +1 -1
- package/dist/knowledge/extractFile.d.ts +9 -1
- package/dist/knowledge/extractFile.d.ts.map +1 -1
- package/dist/knowledge/extractFile.js +22 -5
- package/dist/knowledge/extractFile.js.map +1 -1
- package/dist/knowledge/extractJob.d.ts +30 -5
- package/dist/knowledge/extractJob.d.ts.map +1 -1
- package/dist/knowledge/extractJob.js +9 -1
- package/dist/knowledge/extractJob.js.map +1 -1
- package/dist/knowledge/findings.d.ts.map +1 -1
- package/dist/knowledge/findings.js +9 -1
- package/dist/knowledge/findings.js.map +1 -1
- package/dist/knowledge/index.d.ts +7 -4
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +3 -1
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge/jobDeadline.d.ts +17 -0
- package/dist/knowledge/jobDeadline.d.ts.map +1 -0
- package/dist/knowledge/jobDeadline.js +46 -0
- package/dist/knowledge/jobDeadline.js.map +1 -0
- package/dist/knowledge/judgeCalls.d.ts +16 -0
- package/dist/knowledge/judgeCalls.d.ts.map +1 -1
- package/dist/knowledge/judgeCalls.js +20 -1
- package/dist/knowledge/judgeCalls.js.map +1 -1
- package/dist/knowledge/judgePriority.d.ts +22 -0
- package/dist/knowledge/judgePriority.d.ts.map +1 -0
- package/dist/knowledge/judgePriority.js +28 -0
- package/dist/knowledge/judgePriority.js.map +1 -0
- package/dist/knowledge/model.d.ts +57 -0
- package/dist/knowledge/model.d.ts.map +1 -1
- package/dist/knowledge/outline.d.ts.map +1 -1
- package/dist/knowledge/outline.js +14 -1
- package/dist/knowledge/outline.js.map +1 -1
- package/dist/knowledge/pack/crc32.d.ts +3 -0
- package/dist/knowledge/pack/crc32.d.ts.map +1 -0
- package/dist/knowledge/pack/crc32.js +18 -0
- package/dist/knowledge/pack/crc32.js.map +1 -0
- package/dist/knowledge/pack/decode.d.ts +14 -0
- package/dist/knowledge/pack/decode.d.ts.map +1 -0
- package/dist/knowledge/pack/decode.js +64 -0
- package/dist/knowledge/pack/decode.js.map +1 -0
- package/dist/knowledge/pack/deflate.d.ts +9 -0
- package/dist/knowledge/pack/deflate.d.ts.map +1 -0
- package/dist/knowledge/pack/deflate.js +45 -0
- package/dist/knowledge/pack/deflate.js.map +1 -0
- package/dist/knowledge/pack/encode.d.ts +17 -0
- package/dist/knowledge/pack/encode.d.ts.map +1 -0
- package/dist/knowledge/pack/encode.js +79 -0
- package/dist/knowledge/pack/encode.js.map +1 -0
- package/dist/knowledge/pack/extrDiff.d.ts +23 -0
- package/dist/knowledge/pack/extrDiff.d.ts.map +1 -0
- package/dist/knowledge/pack/extrDiff.js +0 -0
- package/dist/knowledge/pack/extrDiff.js.map +1 -0
- package/dist/knowledge/pack/frame.d.ts +37 -0
- package/dist/knowledge/pack/frame.d.ts.map +1 -0
- package/dist/knowledge/pack/frame.js +94 -0
- package/dist/knowledge/pack/frame.js.map +1 -0
- package/dist/knowledge/pack/index.d.ts +19 -0
- package/dist/knowledge/pack/index.d.ts.map +1 -0
- package/dist/knowledge/pack/index.js +17 -0
- package/dist/knowledge/pack/index.js.map +1 -0
- package/dist/knowledge/pack/jsonSize.d.ts +5 -0
- package/dist/knowledge/pack/jsonSize.d.ts.map +1 -0
- package/dist/knowledge/pack/jsonSize.js +8 -0
- package/dist/knowledge/pack/jsonSize.js.map +1 -0
- package/dist/knowledge/pack/manifest.d.ts +66 -0
- package/dist/knowledge/pack/manifest.d.ts.map +1 -0
- package/dist/knowledge/pack/manifest.js +104 -0
- package/dist/knowledge/pack/manifest.js.map +1 -0
- package/dist/knowledge/pack/sections/columns.d.ts +32 -0
- package/dist/knowledge/pack/sections/columns.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/columns.js +53 -0
- package/dist/knowledge/pack/sections/columns.js.map +1 -0
- package/dist/knowledge/pack/sections/extr.d.ts +8 -0
- package/dist/knowledge/pack/sections/extr.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/extr.js +99 -0
- package/dist/knowledge/pack/sections/extr.js.map +1 -0
- package/dist/knowledge/pack/sections/extrLists.d.ts +23 -0
- package/dist/knowledge/pack/sections/extrLists.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/extrLists.js +194 -0
- package/dist/knowledge/pack/sections/extrLists.js.map +1 -0
- package/dist/knowledge/pack/sections/facts.d.ts +8 -0
- package/dist/knowledge/pack/sections/facts.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/facts.js +167 -0
- package/dist/knowledge/pack/sections/facts.js.map +1 -0
- package/dist/knowledge/pack/sections/index.d.ts +6 -0
- package/dist/knowledge/pack/sections/index.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/index.js +9 -0
- package/dist/knowledge/pack/sections/index.js.map +1 -0
- package/dist/knowledge/pack/sections/rows.d.ts +31 -0
- package/dist/knowledge/pack/sections/rows.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/rows.js +226 -0
- package/dist/knowledge/pack/sections/rows.js.map +1 -0
- package/dist/knowledge/pack/strings.d.ts +39 -0
- package/dist/knowledge/pack/strings.d.ts.map +1 -0
- package/dist/knowledge/pack/strings.js +115 -0
- package/dist/knowledge/pack/strings.js.map +1 -0
- package/dist/knowledge/pack/types.d.ts +109 -0
- package/dist/knowledge/pack/types.d.ts.map +1 -0
- package/dist/knowledge/pack/types.js +17 -0
- package/dist/knowledge/pack/types.js.map +1 -0
- package/dist/knowledge/pack/varint.d.ts +50 -0
- package/dist/knowledge/pack/varint.d.ts.map +1 -0
- package/dist/knowledge/pack/varint.js +141 -0
- package/dist/knowledge/pack/varint.js.map +1 -0
- package/dist/knowledge/partitions.d.ts +1 -1
- package/dist/knowledge/partitions.d.ts.map +1 -1
- package/dist/knowledge/partitions.js +6 -1
- package/dist/knowledge/partitions.js.map +1 -1
- package/dist/knowledge/review.d.ts.map +1 -1
- package/dist/knowledge/review.js +58 -16
- package/dist/knowledge/review.js.map +1 -1
- package/dist/knowledge/reviewJudge.d.ts +8 -1
- package/dist/knowledge/reviewJudge.d.ts.map +1 -1
- package/dist/knowledge/reviewJudge.js +14 -8
- package/dist/knowledge/reviewJudge.js.map +1 -1
- package/dist/knowledge/reviewModel.d.ts +35 -1
- package/dist/knowledge/reviewModel.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.d.ts +8 -2
- package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.js +50 -25
- package/dist/knowledge/reviewPrefetch.js.map +1 -1
- package/dist/knowledge/reviewRun.d.ts +15 -3
- package/dist/knowledge/reviewRun.d.ts.map +1 -1
- package/dist/knowledge/reviewRun.js +19 -2
- package/dist/knowledge/reviewRun.js.map +1 -1
- package/dist/knowledge/reviewRunModel.d.ts +8 -1
- package/dist/knowledge/reviewRunModel.d.ts.map +1 -1
- package/dist/knowledge/reviewRunModel.js.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.d.ts +72 -6
- package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.js +279 -75
- package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
- package/dist/knowledge/systems.d.ts +18 -0
- package/dist/knowledge/systems.d.ts.map +1 -0
- package/dist/knowledge/systems.js +29 -0
- package/dist/knowledge/systems.js.map +1 -0
- package/package.json +7 -3
- package/src/knowledge/build.ts +31 -3
- package/src/knowledge/extractFile.ts +26 -6
- package/src/knowledge/extractJob.ts +26 -7
- package/src/knowledge/findings.ts +9 -1
- package/src/knowledge/index.ts +7 -3
- package/src/knowledge/jobDeadline.ts +43 -0
- package/src/knowledge/judgeCalls.ts +19 -2
- package/src/knowledge/judgePriority.ts +36 -0
- package/src/knowledge/model.ts +49 -0
- package/src/knowledge/outline.test.ts +50 -0
- package/src/knowledge/outline.ts +15 -1
- package/src/knowledge/pack/crc32.ts +17 -0
- package/src/knowledge/pack/decode.ts +58 -0
- package/src/knowledge/pack/deflate.ts +43 -0
- package/src/knowledge/pack/encode.ts +81 -0
- package/src/knowledge/pack/extrDiff.ts +0 -0
- package/src/knowledge/pack/frame.ts +86 -0
- package/src/knowledge/pack/index.ts +26 -0
- package/src/knowledge/pack/jsonSize.ts +11 -0
- package/src/knowledge/pack/manifest.ts +128 -0
- package/src/knowledge/pack/pack.guards.test.ts +77 -0
- package/src/knowledge/pack/pack.reconcile.test.ts +96 -0
- package/src/knowledge/pack/pack.roundtrip.test.ts +50 -0
- package/src/knowledge/pack/pack.size.test.ts +22 -0
- package/src/knowledge/pack/pack.testkit.test-util.ts +90 -0
- package/src/knowledge/pack/sections/columns.ts +61 -0
- package/src/knowledge/pack/sections/extr.ts +90 -0
- package/src/knowledge/pack/sections/extrLists.ts +147 -0
- package/src/knowledge/pack/sections/facts.ts +123 -0
- package/src/knowledge/pack/sections/index.ts +13 -0
- package/src/knowledge/pack/sections/rows.ts +184 -0
- package/src/knowledge/pack/strings.ts +123 -0
- package/src/knowledge/pack/types.ts +89 -0
- package/src/knowledge/pack/varint.ts +138 -0
- package/src/knowledge/partitions.test.ts +4 -0
- package/src/knowledge/partitions.ts +3 -1
- package/src/knowledge/review.throughput.test.ts +122 -0
- package/src/knowledge/review.ts +54 -16
- package/src/knowledge/review.twoPass.test.ts +224 -0
- package/src/knowledge/reviewJudge.ts +19 -8
- package/src/knowledge/reviewModel.ts +32 -1
- package/src/knowledge/reviewPrefetch.ts +51 -24
- package/src/knowledge/reviewRun.test.ts +20 -3
- package/src/knowledge/reviewRun.ts +33 -6
- package/src/knowledge/reviewRunModel.ts +4 -1
- package/src/knowledge/stores/localSnapshotStore.batched.test.ts +25 -3
- package/src/knowledge/stores/localSnapshotStore.extractedLog.test.ts +280 -0
- package/src/knowledge/stores/localSnapshotStore.ts +283 -76
- package/src/knowledge/systems.test.ts +119 -0
- package/src/knowledge/systems.ts +32 -0
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
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
|
|
4
|
+
* `maxDecodedBytes`) and the string/row counts. A malformed pack is a `PackFormatError`.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { crc32 } from './crc32.js';
|
|
8
|
+
import { inflateRaw } from './deflate.js';
|
|
9
|
+
import { FLAG_DEFLATED, readFrame, readSections } from './frame.js';
|
|
10
|
+
import { ROW_SECTIONS, TAG } from './sections/index.js';
|
|
11
|
+
import { readHashTable, readStringTable, readTables } from './strings.js';
|
|
12
|
+
import { DEFAULT_PACK_LIMITS, PackTooLargeError, type Pack, type PackLimits } from './types.js';
|
|
13
|
+
import { PackFormatError } from './varint.js';
|
|
14
|
+
|
|
15
|
+
const NONE = new Uint8Array([0]);
|
|
16
|
+
|
|
17
|
+
/** 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);
|
|
20
|
+
return { rootId: header.rootId, baseGeneration: header.baseGeneration, targetDigest: header.targetDigest };
|
|
21
|
+
}
|
|
22
|
+
|
|
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);
|
|
26
|
+
let body: Uint8Array;
|
|
27
|
+
if (header.flags & FLAG_DEFLATED) {
|
|
28
|
+
try {
|
|
29
|
+
body = await inflateRaw(stored, lim.maxDecodedBytes);
|
|
30
|
+
} catch (error) {
|
|
31
|
+
if (error instanceof PackTooLargeError) throw error;
|
|
32
|
+
throw new PackFormatError('corrupt deflate stream');
|
|
33
|
+
}
|
|
34
|
+
} else {
|
|
35
|
+
if (stored.length > lim.maxDecodedBytes) throw new PackTooLargeError(lim.maxDecodedBytes);
|
|
36
|
+
body = stored;
|
|
37
|
+
}
|
|
38
|
+
if (crc32(body) !== crc) throw new PackFormatError('CRC-32 mismatch');
|
|
39
|
+
try {
|
|
40
|
+
const sections = readSections(body);
|
|
41
|
+
const strings = readStringTable(sections.get(TAG.STR) ?? NONE, lim.maxStrings);
|
|
42
|
+
const hashes = readHashTable(sections.get(TAG.HASH) ?? NONE, lim.maxStrings);
|
|
43
|
+
const used = new Set<string>();
|
|
44
|
+
const base = readTables(strings, hashes);
|
|
45
|
+
const tables = { str: base.str, hash: (i: number) => { const h = base.hash(i); used.add(h); return h; } };
|
|
46
|
+
const pack: Pack = { rootId: header.rootId, baseGeneration: header.baseGeneration, targetDigest: header.targetDigest };
|
|
47
|
+
for (const s of ROW_SECTIONS) {
|
|
48
|
+
const bytes = sections.get(s.tag);
|
|
49
|
+
if (bytes) s.read(bytes, tables, lim, pack);
|
|
50
|
+
}
|
|
51
|
+
const extra = hashes.filter((h) => !used.has(h));
|
|
52
|
+
if (extra.length > 0) pack.hashes = extra;
|
|
53
|
+
return pack;
|
|
54
|
+
} catch (error) {
|
|
55
|
+
if (error instanceof PackFormatError || error instanceof PackTooLargeError) throw error;
|
|
56
|
+
throw new PackFormatError(error instanceof Error ? error.message : 'malformed pack');
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/pack/deflate.ts — `deflate-raw` through `CompressionStream` / `DecompressionStream`, which
|
|
3
|
+
* Node 18+, Cloudflare Workers and browsers all have (PRD 41 A11). Inflation is CAPPED: a stream that
|
|
4
|
+
* produces more than `maxBytes` is cancelled at once, so a bomb never holds more than the cap.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { PackTooLargeError } from './types.js';
|
|
8
|
+
|
|
9
|
+
async function drain(stream: ReadableStream<Uint8Array>, maxBytes: number): Promise<Uint8Array> {
|
|
10
|
+
const reader = stream.getReader();
|
|
11
|
+
const chunks: Uint8Array[] = [];
|
|
12
|
+
let total = 0;
|
|
13
|
+
for (;;) {
|
|
14
|
+
const { done, value } = await reader.read();
|
|
15
|
+
if (done) break;
|
|
16
|
+
total += value.length;
|
|
17
|
+
if (total > maxBytes) { await reader.cancel().catch(() => undefined); throw new PackTooLargeError(maxBytes); }
|
|
18
|
+
chunks.push(value);
|
|
19
|
+
}
|
|
20
|
+
const out = new Uint8Array(total);
|
|
21
|
+
let at = 0;
|
|
22
|
+
for (const c of chunks) { out.set(c, at); at += c.length; }
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function through(data: Uint8Array, transform: { readable: ReadableStream<Uint8Array>; writable: WritableStream<BufferSource> }, maxBytes: number): Promise<Uint8Array> {
|
|
27
|
+
const writer = transform.writable.getWriter();
|
|
28
|
+
// Written without waiting: the reader below must drain it, or a large input would stall on backpressure.
|
|
29
|
+
const wrote = writer.write(data as unknown as BufferSource).then(() => writer.close());
|
|
30
|
+
wrote.catch(() => undefined);
|
|
31
|
+
try {
|
|
32
|
+
return await drain(transform.readable, maxBytes);
|
|
33
|
+
} finally {
|
|
34
|
+
await wrote.catch(() => undefined);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const deflateRaw = (data: Uint8Array): Promise<Uint8Array> =>
|
|
39
|
+
through(data, new CompressionStream('deflate-raw') as never, Number.MAX_SAFE_INTEGER);
|
|
40
|
+
|
|
41
|
+
/** Throws {@link PackTooLargeError} past `maxBytes` of output, and `Error` on a corrupt stream. */
|
|
42
|
+
export const inflateRaw = (data: Uint8Array, maxBytes: number): Promise<Uint8Array> =>
|
|
43
|
+
through(data, new DecompressionStream('deflate-raw') as never, maxBytes);
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/pack/encode.ts — `encodePack` and `normalizePack` (PRD 41 A11).
|
|
3
|
+
*
|
|
4
|
+
* Deterministic: rows are put in canonical order first, the tables are sorted, and every section
|
|
5
|
+
* is written from the same normalized pack, so equal input (in any row order) gives equal bytes.
|
|
6
|
+
* Two passes over the section writers: the first collects every string and hash they use, the
|
|
7
|
+
* second writes real table indexes.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { deflateRaw } from './deflate.js';
|
|
11
|
+
import { FLAG_DEFLATED, writeFrame, writeSection } from './frame.js';
|
|
12
|
+
import { ROW_SECTIONS, TAG } from './sections/index.js';
|
|
13
|
+
import { compare } from './sections/columns.js';
|
|
14
|
+
import { collector, tablesOf, writeHashTable, writeStringTable } from './strings.js';
|
|
15
|
+
import type { Pack, RelationId } from './types.js';
|
|
16
|
+
import { ByteWriter } from './varint.js';
|
|
17
|
+
|
|
18
|
+
const nonEmpty = <T>(xs: readonly T[] | undefined): T[] | undefined => (xs && xs.length > 0 ? [...xs] : undefined);
|
|
19
|
+
const byRelation = (a: RelationId, b: RelationId): number => compare(a.from, b.from) || compare(a.to, b.to) || compare(a.kind, b.kind);
|
|
20
|
+
|
|
21
|
+
/** The hashes the row sections reference (a `have` request's explicit hashes are not among them). */
|
|
22
|
+
function referencedHashes(pack: Pack): Set<string> {
|
|
23
|
+
const col = collector();
|
|
24
|
+
for (const s of ROW_SECTIONS) s.write(pack, col);
|
|
25
|
+
return col.hashes;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The pack in canonical form: rows sorted, empty parts dropped, `hashes` reduced to those no section references. */
|
|
29
|
+
export function normalizePack(pack: Pack): Pack {
|
|
30
|
+
const out: Pack = { rootId: pack.rootId, baseGeneration: pack.baseGeneration, targetDigest: pack.targetDigest };
|
|
31
|
+
const files = nonEmpty(pack.files)?.sort((a, b) => compare(a.path, b.path));
|
|
32
|
+
if (files) out.files = files;
|
|
33
|
+
const extracted = nonEmpty(pack.extracted)?.sort((a, b) => compare(a.hash, b.hash));
|
|
34
|
+
if (extracted) out.extracted = extracted;
|
|
35
|
+
const facts = nonEmpty(pack.facts)?.sort((a, b) => compare(a.key, b.key));
|
|
36
|
+
if (facts) out.facts = facts;
|
|
37
|
+
const relations = nonEmpty(pack.relations)?.sort((a, b) => byRelation(a, b));
|
|
38
|
+
if (relations) out.relations = relations;
|
|
39
|
+
const stale = nonEmpty(pack.stale)?.sort((a, b) => compare(a.sourceRef, b.sourceRef));
|
|
40
|
+
if (stale) out.stale = stale;
|
|
41
|
+
const d = pack.deletes;
|
|
42
|
+
if (d && d.files.length + d.facts.length + d.relations.length > 0) {
|
|
43
|
+
out.deletes = { files: [...d.files].sort(compare), facts: [...d.facts].sort(compare), relations: [...d.relations].sort(byRelation) };
|
|
44
|
+
}
|
|
45
|
+
if (pack.scope) out.scope = pack.scope;
|
|
46
|
+
if (pack.analysis !== undefined) out.analysis = pack.analysis;
|
|
47
|
+
const leaves = nonEmpty(pack.leaves)?.sort((a, b) => compare(a.key, b.key));
|
|
48
|
+
if (leaves) out.leaves = leaves;
|
|
49
|
+
if (pack.buckets) out.buckets = pack.buckets;
|
|
50
|
+
const used = referencedHashes(out);
|
|
51
|
+
const extra = [...new Set(pack.hashes ?? [])].filter((h) => !used.has(h)).sort(compare);
|
|
52
|
+
if (extra.length > 0) out.hashes = extra;
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface EncodeOptions {
|
|
57
|
+
/** Deflate the body (default true). Off, the bytes are the plain columnar form (tests, size comparisons). */
|
|
58
|
+
deflate?: boolean;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function encodePack(input: Pack, opts: EncodeOptions = {}): Promise<Uint8Array> {
|
|
62
|
+
const pack = normalizePack(input);
|
|
63
|
+
const col = collector();
|
|
64
|
+
for (const s of ROW_SECTIONS) s.write(pack, col);
|
|
65
|
+
const tables = tablesOf(col.strings, [...col.hashes, ...(pack.hashes ?? [])]);
|
|
66
|
+
|
|
67
|
+
const body = new ByteWriter();
|
|
68
|
+
writeSection(body, TAG.STR, writeStringTable(tables.strings));
|
|
69
|
+
writeSection(body, TAG.HASH, writeHashTable(tables.hashes));
|
|
70
|
+
for (const s of ROW_SECTIONS) {
|
|
71
|
+
const bytes = s.write(pack, tables);
|
|
72
|
+
if (bytes) writeSection(body, s.tag, bytes);
|
|
73
|
+
}
|
|
74
|
+
const plain = body.finish();
|
|
75
|
+
const deflate = opts.deflate ?? true;
|
|
76
|
+
return writeFrame(
|
|
77
|
+
{ flags: deflate ? FLAG_DEFLATED : 0, rootId: pack.rootId, baseGeneration: pack.baseGeneration, targetDigest: pack.targetDigest },
|
|
78
|
+
plain,
|
|
79
|
+
deflate ? await deflateRaw(plain) : plain,
|
|
80
|
+
);
|
|
81
|
+
}
|
|
Binary file
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/pack/frame.ts — the BFKP v1 frame (PRD 41 A11):
|
|
3
|
+
*
|
|
4
|
+
* magic "BFKP" · version u8 · flags u8 (bit 0 = body deflated) · rootId · baseGeneration varint ·
|
|
5
|
+
* targetDigest (32 raw bytes) · body · trailer: CRC-32 (u32 LE) of the DECODED body
|
|
6
|
+
*
|
|
7
|
+
* The body is sections `{ tag u8, length varint, bytes }`; an unknown tag is skipped.
|
|
8
|
+
* Also: the multi-part split a large pack travels in.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { crc32 } from './crc32.js';
|
|
12
|
+
import { ByteReader, ByteWriter, PackFormatError } from './varint.js';
|
|
13
|
+
|
|
14
|
+
export const MAGIC = [0x42, 0x46, 0x4b, 0x50] as const; // "BFKP"
|
|
15
|
+
export const VERSION = 1;
|
|
16
|
+
export const FLAG_DEFLATED = 1;
|
|
17
|
+
export const KPACK_CONTENT_TYPE = 'application/vnd.builderforce.kpack';
|
|
18
|
+
/** A compressed pack larger than this travels as several parts. */
|
|
19
|
+
export const MAX_PART_BYTES = 8 * 1024 * 1024;
|
|
20
|
+
|
|
21
|
+
export interface FrameHeader { flags: number; rootId: string; baseGeneration: number; targetDigest: string }
|
|
22
|
+
|
|
23
|
+
const hexOf = (b: Uint8Array): string => { let s = ''; for (const x of b) s += (x < 16 ? '0' : '') + x.toString(16); return s; };
|
|
24
|
+
|
|
25
|
+
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');
|
|
27
|
+
const w = new ByteWriter();
|
|
28
|
+
for (const m of MAGIC) w.u8(m);
|
|
29
|
+
w.u8(VERSION);
|
|
30
|
+
w.u8(h.flags);
|
|
31
|
+
w.str(h.rootId);
|
|
32
|
+
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();
|
|
39
|
+
}
|
|
40
|
+
|
|
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');
|
|
44
|
+
const r = new ByteReader(bytes);
|
|
45
|
+
for (const m of MAGIC) if (r.u8() !== m) throw new PackFormatError('not a BFKP pack (bad magic)');
|
|
46
|
+
const version = r.u8();
|
|
47
|
+
if (version !== VERSION) throw new PackFormatError(`unsupported BFKP version ${version}`);
|
|
48
|
+
const flags = r.u8();
|
|
49
|
+
const rootId = r.str();
|
|
50
|
+
const baseGeneration = r.varint();
|
|
51
|
+
const targetDigest = hexOf(r.bytes(32));
|
|
52
|
+
if (r.remaining < 4) throw new PackFormatError('truncated frame');
|
|
53
|
+
const stored = r.bytes(r.remaining - 4);
|
|
54
|
+
return { header: { flags, rootId, baseGeneration, targetDigest }, stored, crc: r.u32le() };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function writeSection(w: ByteWriter, tag: number, bytes: Uint8Array): void {
|
|
58
|
+
w.u8(tag);
|
|
59
|
+
w.varint(bytes.length);
|
|
60
|
+
w.bytes(bytes);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The sections of a decoded body by tag (a repeated tag keeps the last); unknown tags are returned too, for the caller to skip. */
|
|
64
|
+
export function readSections(body: Uint8Array): Map<number, Uint8Array> {
|
|
65
|
+
const r = new ByteReader(body);
|
|
66
|
+
const out = new Map<number, Uint8Array>();
|
|
67
|
+
while (!r.done) { const tag = r.u8(); out.set(tag, r.bytes(r.varint())); }
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Cuts a pack into ordered parts of at most `max` bytes. A pack within `max` is one part. */
|
|
72
|
+
export function splitParts(pack: Uint8Array, max: number = MAX_PART_BYTES): Uint8Array[] {
|
|
73
|
+
if (pack.length <= max) return [pack];
|
|
74
|
+
const parts: Uint8Array[] = [];
|
|
75
|
+
for (let at = 0; at < pack.length; at += max) parts.push(pack.subarray(at, Math.min(at + max, pack.length)));
|
|
76
|
+
return parts;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The inverse of {@link splitParts}. */
|
|
80
|
+
export function joinParts(parts: readonly Uint8Array[]): Uint8Array {
|
|
81
|
+
if (parts.length === 1) return parts[0]!;
|
|
82
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
83
|
+
let at = 0;
|
|
84
|
+
for (const p of parts) { out.set(p, at); at += p.length; }
|
|
85
|
+
return out;
|
|
86
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@seanhogg/builderforce-memory/knowledge/pack` — BFKP v1, "Builderforce Knowledge Pack" (PRD 41 A11):
|
|
3
|
+
* the one compact, lossless wire format a client syncs to the server in, and the server expands.
|
|
4
|
+
*
|
|
5
|
+
* Pure TypeScript with no Node APIs (`CompressionStream` is the only runtime dependency): the VS Code
|
|
6
|
+
* host and the API Worker run this same module. There is no second copy of the codec.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export { encodePack, normalizePack, type EncodeOptions } from './encode.js';
|
|
10
|
+
export { decodePack, peekPack } from './decode.js';
|
|
11
|
+
export { KPACK_CONTENT_TYPE, MAX_PART_BYTES, splitParts, joinParts } from './frame.js';
|
|
12
|
+
export { PackFormatError } from './varint.js';
|
|
13
|
+
export { crc32 } from './crc32.js';
|
|
14
|
+
export {
|
|
15
|
+
ZERO_DIGEST, DEFAULT_PACK_LIMITS, PackTooLargeError,
|
|
16
|
+
} from './types.js';
|
|
17
|
+
export type {
|
|
18
|
+
Pack, PackBody, PackFileRow, PackStaleRow, PackDeletes, RelationId, PackExtr, ExtrEntryDiff, ListDiff, ManifestLeaf, PackLimits,
|
|
19
|
+
} from './types.js';
|
|
20
|
+
export { diffEntries, applyEntryDiffs, diffEntry, applyEntryDiff, deepEqual } from './extrDiff.js';
|
|
21
|
+
export {
|
|
22
|
+
MANIFEST_BUCKETS, manifestTree, bucketOf, keyHash, differingBuckets, leafDelta, rootLeaves, rootDigestOf,
|
|
23
|
+
fileLeafKey, factLeafKey, relationLeafKey, factDigest, relationDigest,
|
|
24
|
+
} from './manifest.js';
|
|
25
|
+
export type { ManifestTree, LeafDelta, RootRows } from './manifest.js';
|
|
26
|
+
export { jsonBytesOf } from './jsonSize.js';
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** knowledge/pack/jsonSize.ts — the bytes the same rows would take as JSON: the baseline a pack's size is shown against (PRD 41 A11 rule 6). */
|
|
2
|
+
|
|
3
|
+
import type { Pack } from './types.js';
|
|
4
|
+
|
|
5
|
+
const ENCODER = new TextEncoder();
|
|
6
|
+
|
|
7
|
+
/** UTF-8 bytes of the pack's rows as JSON (frame fields and manifest sections excluded). */
|
|
8
|
+
export function jsonBytesOf(pack: Pack): number {
|
|
9
|
+
const { files, extracted, facts, relations, stale, deletes, scope, analysis } = pack;
|
|
10
|
+
return ENCODER.encode(JSON.stringify({ files, extracted, facts, relations, stale, deletes, scope, analysis })).length;
|
|
11
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/pack/manifest.ts — `manifestTree`, the ONE function both sides use to find a delta
|
|
3
|
+
* (PRD 41 A11 rule 2, the reconcile path).
|
|
4
|
+
*
|
|
5
|
+
* Leaves are `(key, contentDigest)` for every file, fact and relation of a root, grouped into 4,096
|
|
6
|
+
* buckets by a stable hash of the key. A bucket's digest is the hash of its sorted leaves; the root
|
|
7
|
+
* digest is the hash of the bucket digests. Two sides with equal root digests hold equal state; with
|
|
8
|
+
* unequal ones, only the buckets whose digests differ need their leaves compared.
|
|
9
|
+
*
|
|
10
|
+
* What counts as "a leaf of the root" is decided HERE ({@link rootLeaves}), so the client's local rows
|
|
11
|
+
* and the server's stored rows are cut the same way and a digest means the same on both.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { sha256Hex } from '../../retrieval/knowledge-index/sha256.js';
|
|
15
|
+
import type { ManifestLeaf, StoredFact, StoredRelation } from './types.js';
|
|
16
|
+
|
|
17
|
+
export const MANIFEST_BUCKETS = 4096;
|
|
18
|
+
|
|
19
|
+
/** FNV-1a (32-bit) over the key's UTF-16 code units: stable across runtimes and releases. */
|
|
20
|
+
export function keyHash(key: string): number {
|
|
21
|
+
let h = 0x811c9dc5;
|
|
22
|
+
for (let i = 0; i < key.length; i++) { h ^= key.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; }
|
|
23
|
+
return h >>> 0;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const bucketOf = (key: string): number => keyHash(key) % MANIFEST_BUCKETS;
|
|
27
|
+
|
|
28
|
+
const EMPTY_BUCKET = sha256Hex('');
|
|
29
|
+
|
|
30
|
+
export interface ManifestTree {
|
|
31
|
+
root: string;
|
|
32
|
+
/** `MANIFEST_BUCKETS` bucket digests, hex. */
|
|
33
|
+
buckets: string[];
|
|
34
|
+
/** The leaves of each non-empty bucket, sorted by key. */
|
|
35
|
+
leaves: Map<number, ManifestLeaf[]>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const cmp = (a: ManifestLeaf, b: ManifestLeaf): number => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
|
|
39
|
+
|
|
40
|
+
export function manifestTree(leaves: readonly ManifestLeaf[]): ManifestTree {
|
|
41
|
+
const grouped = new Map<number, ManifestLeaf[]>();
|
|
42
|
+
for (const l of leaves) {
|
|
43
|
+
const b = bucketOf(l.key);
|
|
44
|
+
const list = grouped.get(b);
|
|
45
|
+
if (list) list.push(l); else grouped.set(b, [l]);
|
|
46
|
+
}
|
|
47
|
+
const buckets: string[] = new Array(MANIFEST_BUCKETS);
|
|
48
|
+
for (let b = 0; b < MANIFEST_BUCKETS; b++) {
|
|
49
|
+
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(''));
|
|
53
|
+
}
|
|
54
|
+
return { root: sha256Hex(buckets.join('')), buckets, leaves: grouped };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The bucket ids whose digests differ (or are missing on one side). */
|
|
58
|
+
export function differingBuckets(a: readonly string[], b: readonly string[]): number[] {
|
|
59
|
+
const out: number[] = [];
|
|
60
|
+
for (let i = 0; i < MANIFEST_BUCKETS; i++) if (a[i] !== b[i]) out.push(i);
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** A source's leaf key: its path, or `~tag|path` for a root-level output (the blob store's own source identity). */
|
|
65
|
+
export function fileLeafKey(path: string, hash: string): string {
|
|
66
|
+
if (!hash.startsWith('~')) return `f:${path}`;
|
|
67
|
+
const colon = hash.indexOf(':');
|
|
68
|
+
return `f:${colon > 0 ? hash.slice(0, colon) : hash}|${path}`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
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}`;
|
|
73
|
+
|
|
74
|
+
/** The digest of what a fact says: its key, text and provenance kind. Importance and timestamps are the server's to score. */
|
|
75
|
+
export const factDigest = (f: Pick<StoredFact, 'key' | 'content' | 'origin'>): string => sha256Hex(JSON.stringify([f.key, f.content, f.origin]));
|
|
76
|
+
|
|
77
|
+
export const relationDigest = (r: Pick<StoredRelation, 'weight' | 'origin' | 'confidence' | 'sourceHash'>): string =>
|
|
78
|
+
sha256Hex(`${r.weight.toFixed(3)}|${r.origin}|${r.confidence === undefined ? '' : r.confidence.toFixed(3)}|${r.sourceHash ?? ''}`);
|
|
79
|
+
|
|
80
|
+
export interface RootRows {
|
|
81
|
+
files: ReadonlyArray<{ path: string; hash: string }>;
|
|
82
|
+
facts: readonly StoredFact[];
|
|
83
|
+
relations: readonly StoredRelation[];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The leaves of a root. A fact belongs to the root when it is anchored to one of its files; a relation
|
|
88
|
+
* when either end is one of its sources (`src:<root>::…`) or one of those facts.
|
|
89
|
+
*
|
|
90
|
+
* Only the review's own judgements count (`origin: 'model'`): a person's note or an agent's fact can be
|
|
91
|
+
* written on the server by someone else, so it never makes two sides "differ"; those rows travel by the
|
|
92
|
+
* dirty set when their writer changes them.
|
|
93
|
+
*/
|
|
94
|
+
export function rootLeaves(rootId: string, rows: RootRows): ManifestLeaf[] {
|
|
95
|
+
const paths = new Set(rows.files.map((f) => f.path));
|
|
96
|
+
const facts = rows.facts.filter((f) => f.origin === 'model' && f.fileAnchors.some((a) => paths.has(a.path)));
|
|
97
|
+
const factRefs = new Set(facts.map((f) => `fact:${f.key}`));
|
|
98
|
+
const prefix = `src:${rootId}::`;
|
|
99
|
+
const touches = (ref: string): boolean => ref.startsWith(prefix) || factRefs.has(ref);
|
|
100
|
+
return [
|
|
101
|
+
...rows.files.map((f) => ({ key: fileLeafKey(f.path, f.hash), digest: f.hash })),
|
|
102
|
+
...facts.map((f) => ({ key: factLeafKey(f.key), digest: factDigest(f) })),
|
|
103
|
+
...rows.relations.filter((r) => r.origin === 'model' && (touches(r.from) || touches(r.to))).map((r) => ({ key: relationLeafKey(r), digest: relationDigest(r) })),
|
|
104
|
+
];
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The root digest of a root's rows: what a pack asserts as its `targetDigest`. */
|
|
108
|
+
export const rootDigestOf = (rootId: string, rows: RootRows): string => manifestTree(rootLeaves(rootId, rows)).root;
|
|
109
|
+
|
|
110
|
+
export interface LeafDelta {
|
|
111
|
+
/** Keys the remote lacks or holds with another digest. */
|
|
112
|
+
upsert: string[];
|
|
113
|
+
/** Keys the remote holds that the local side does not. */
|
|
114
|
+
remove: string[];
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Compares local leaves with the remote's leaves of the differing buckets; only those buckets are considered. */
|
|
118
|
+
export function leafDelta(local: ManifestTree, remote: readonly ManifestLeaf[], buckets: readonly number[]): LeafDelta {
|
|
119
|
+
const remoteByKey = new Map(remote.map((l) => [l.key, l.digest] as const));
|
|
120
|
+
const upsert: string[] = [], seen = new Set<string>();
|
|
121
|
+
for (const b of buckets) {
|
|
122
|
+
for (const l of local.leaves.get(b) ?? []) {
|
|
123
|
+
seen.add(l.key);
|
|
124
|
+
if (remoteByKey.get(l.key) !== l.digest) upsert.push(l.key);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return { upsert, remove: remote.map((l) => l.key).filter((k) => !seen.has(k)) };
|
|
128
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/pack/pack.guards.test.ts — what the server's guards rely on (PRD 41 A11 Accept): a flipped
|
|
3
|
+
* byte fails the CRC, an unknown section is skipped, a bomb stops at the cap, parts re-join.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { deflateRaw } from './deflate.js';
|
|
7
|
+
import { FLAG_DEFLATED, readFrame, writeFrame } from './frame.js';
|
|
8
|
+
import { decodePack, encodePack, joinParts, PackFormatError, PackTooLargeError, peekPack, splitParts, ZERO_DIGEST } from './index.js';
|
|
9
|
+
import { genPack } from './pack.testkit.test-util.js';
|
|
10
|
+
|
|
11
|
+
describe('BFKP guards', () => {
|
|
12
|
+
it('rejects a flipped byte of an uncompressed body with a CRC failure', async () => {
|
|
13
|
+
const bytes = await encodePack(genPack(2, { files: 10 }), { deflate: false });
|
|
14
|
+
const bad = bytes.slice();
|
|
15
|
+
bad[Math.floor(bytes.length / 2)]! ^= 0x01;
|
|
16
|
+
await expect(decodePack(bad)).rejects.toThrow(PackFormatError);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it('rejects a flipped byte of a deflated body (corrupt stream or CRC)', async () => {
|
|
20
|
+
const bytes = await encodePack(genPack(2, { files: 10 }));
|
|
21
|
+
const bad = bytes.slice();
|
|
22
|
+
bad[Math.floor(bytes.length / 2)]! ^= 0xff;
|
|
23
|
+
await expect(decodePack(bad)).rejects.toThrow(PackFormatError);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it('rejects a bad magic, a truncated frame and an unknown version', async () => {
|
|
27
|
+
const bytes = await encodePack(genPack(2, { files: 3 }));
|
|
28
|
+
await expect(decodePack(new Uint8Array([1, 2, 3]))).rejects.toThrow(PackFormatError);
|
|
29
|
+
const magic = bytes.slice(); magic[0] = 0x00;
|
|
30
|
+
await expect(decodePack(magic)).rejects.toThrow(/magic/);
|
|
31
|
+
const version = bytes.slice(); version[4] = 9;
|
|
32
|
+
await expect(decodePack(version)).rejects.toThrow(/version/);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it('skips a section tag it does not know', async () => {
|
|
36
|
+
const pack = genPack(4, { files: 8 });
|
|
37
|
+
const { header, stored } = readFrame(await encodePack(pack, { deflate: false }));
|
|
38
|
+
const body = new Uint8Array(stored.length + 5);
|
|
39
|
+
body.set(stored);
|
|
40
|
+
body.set([0x7f, 3, 9, 9, 9], stored.length);
|
|
41
|
+
const decoded = await decodePack(writeFrame({ ...header, flags: 0 }, body, body));
|
|
42
|
+
expect(decoded).toEqual(await decodePack(await encodePack(pack)));
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('stops inflating at the cap: a small bomb never holds more than the limit', async () => {
|
|
46
|
+
const body = new Uint8Array(8 * 1024 * 1024);
|
|
47
|
+
const bomb = writeFrame({ flags: FLAG_DEFLATED, rootId: 'r', baseGeneration: 0, targetDigest: ZERO_DIGEST }, body, await deflateRaw(body));
|
|
48
|
+
expect(bomb.length).toBeLessThan(100_000);
|
|
49
|
+
await expect(decodePack(bomb, { maxDecodedBytes: 1024 * 1024 })).rejects.toThrow(PackTooLargeError);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it('applies the 64 MB default cap', async () => {
|
|
53
|
+
const body = new Uint8Array(65 * 1024 * 1024);
|
|
54
|
+
const bomb = writeFrame({ flags: FLAG_DEFLATED, rootId: 'r', baseGeneration: 0, targetDigest: ZERO_DIGEST }, body, await deflateRaw(body));
|
|
55
|
+
await expect(decodePack(bomb)).rejects.toThrow(PackTooLargeError);
|
|
56
|
+
}, 60_000);
|
|
57
|
+
|
|
58
|
+
it('bounds counts before allocating for them', async () => {
|
|
59
|
+
const bytes = await encodePack(genPack(5, { files: 20 }));
|
|
60
|
+
await expect(decodePack(bytes, { maxRows: 5 })).rejects.toThrow(PackFormatError);
|
|
61
|
+
await expect(decodePack(bytes, { maxStrings: 5 })).rejects.toThrow(PackFormatError);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it('reads the generation and digest without inflating the body', async () => {
|
|
65
|
+
const pack = { ...genPack(6, { files: 4 }), baseGeneration: 7 };
|
|
66
|
+
expect(peekPack(await encodePack(pack))).toEqual({ rootId: pack.rootId, baseGeneration: 7, targetDigest: pack.targetDigest });
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('splits into ordered parts and joins them back byte for byte', async () => {
|
|
70
|
+
const bytes = await encodePack(genPack(8, { files: 30 }), { deflate: false });
|
|
71
|
+
const parts = splitParts(bytes, 1000);
|
|
72
|
+
expect(parts.length).toBeGreaterThan(1);
|
|
73
|
+
expect(parts.every((p) => p.length <= 1000)).toBe(true);
|
|
74
|
+
expect(Buffer.from(joinParts(parts)).equals(Buffer.from(bytes))).toBe(true);
|
|
75
|
+
expect(splitParts(bytes, bytes.length + 1)).toHaveLength(1);
|
|
76
|
+
});
|
|
77
|
+
});
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/pack/pack.reconcile.test.ts — the delta-finding halves of PRD 41 A11 rule 2: the manifest
|
|
3
|
+
* tree (reconcile path) and the within-file diff (EXTR `prior`).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { applyEntryDiffs, decodePack, diffEntries, encodePack, differingBuckets, leafDelta, manifestTree, MANIFEST_BUCKETS, rootLeaves, ZERO_DIGEST, type ManifestLeaf } from './index.js';
|
|
7
|
+
import { extractionOf, gen, genPack, ROOT } from './pack.testkit.test-util.js';
|
|
8
|
+
|
|
9
|
+
const rowsOf = (seed: number, files: number, facts = files) => {
|
|
10
|
+
const p = genPack(seed, { files, facts, rich: false });
|
|
11
|
+
return { files: p.files!, facts: p.facts ?? [], relations: p.relations ?? [] };
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
describe('manifestTree', () => {
|
|
15
|
+
it('is the same on two sides with equal state, whatever the order of the rows', () => {
|
|
16
|
+
const rows = rowsOf(1, 200);
|
|
17
|
+
const a = manifestTree(rootLeaves(ROOT, rows));
|
|
18
|
+
const b = manifestTree(rootLeaves(ROOT, { files: [...rows.files].reverse(), facts: [...rows.facts].reverse(), relations: [...rows.relations].reverse() }));
|
|
19
|
+
expect(a.root).toBe(b.root);
|
|
20
|
+
expect(a.buckets).toHaveLength(MANIFEST_BUCKETS);
|
|
21
|
+
expect(differingBuckets(a.buckets, b.buckets)).toEqual([]);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
it('finds exactly the buckets of the changed, added and removed keys, and the leaf delta inside them', () => {
|
|
25
|
+
const rows = rowsOf(2, 600, 0);
|
|
26
|
+
const server = manifestTree(rootLeaves(ROOT, rows));
|
|
27
|
+
const changed = rows.files.map((f, i) => (i < 6 ? { ...f, hash: 'c'.repeat(64) } : f));
|
|
28
|
+
const local = manifestTree(rootLeaves(ROOT, { ...rows, files: [...changed.slice(0, -3), { path: 'brand/new.ts', hash: 'd'.repeat(64), bytes: 1 }] }));
|
|
29
|
+
expect(local.root).not.toBe(server.root);
|
|
30
|
+
const differing = differingBuckets(local.buckets, server.buckets);
|
|
31
|
+
expect(differing.length).toBeGreaterThan(0);
|
|
32
|
+
expect(differing.length).toBeLessThanOrEqual(6 + 3 + 1 + 5);
|
|
33
|
+
const remote: ManifestLeaf[] = differing.flatMap((b) => server.leaves.get(b) ?? []);
|
|
34
|
+
const delta = leafDelta(local, remote, differing);
|
|
35
|
+
expect(delta.upsert.sort()).toEqual([...rows.files.slice(0, 6).map((f) => `f:${f.path}`), 'f:brand/new.ts'].sort());
|
|
36
|
+
expect(delta.remove.sort()).toEqual(rows.files.slice(-3).map((f) => `f:${f.path}`).sort());
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('sends nothing for equal roots', () => {
|
|
40
|
+
const rows = rowsOf(3, 50);
|
|
41
|
+
const a = manifestTree(rootLeaves(ROOT, rows)), b = manifestTree(rootLeaves(ROOT, rows));
|
|
42
|
+
expect(differingBuckets(a.buckets, b.buckets)).toEqual([]);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('answers a manifest GET in at most 128 KB and a leaf request losslessly', async () => {
|
|
46
|
+
const tree = manifestTree(rootLeaves(ROOT, rowsOf(4, 300)));
|
|
47
|
+
const bytes = await encodePack({ rootId: ROOT, baseGeneration: 3, targetDigest: tree.root, buckets: tree.buckets });
|
|
48
|
+
expect(bytes.length).toBeLessThanOrEqual(128 * 1024 + 256);
|
|
49
|
+
expect((await decodePack(bytes)).buckets).toEqual(tree.buckets);
|
|
50
|
+
const leaves = [...tree.leaves.values()].flat().slice(0, 50);
|
|
51
|
+
const back = await decodePack(await encodePack({ rootId: ROOT, baseGeneration: 0, targetDigest: ZERO_DIGEST, leaves }));
|
|
52
|
+
expect(back.leaves).toEqual([...leaves].sort((a, b) => (a.key < b.key ? -1 : 1)));
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
describe('within-file diff', () => {
|
|
57
|
+
it('adding one function sends that node and its edges, not the file extraction, and reapplies exactly', async () => {
|
|
58
|
+
const g = gen(5);
|
|
59
|
+
const targets = Array.from({ length: 12 }, (_, i) => `src/t${i}.ts`);
|
|
60
|
+
const prior = extractionOf(g, 'src/big.ts', 'a'.repeat(64), targets, 400, false);
|
|
61
|
+
const hash = 'b'.repeat(64);
|
|
62
|
+
const restamped = prior.nodes.map((n) => ({ ...n, sourceHash: hash }));
|
|
63
|
+
const next = { ...prior, sourceHash: hash, nodes: [...restamped, { ...restamped[1]!, ref: 'src:ws:gen::src/big.ts#added' as typeof prior.nodes[0]['ref'], label: 'added' }],
|
|
64
|
+
edges: [...prior.edges, { ...prior.edges[0]!, to: 'src:ws:gen::src/added-target.ts' as typeof prior.edges[0]['to'] }] };
|
|
65
|
+
const diffs = diffEntries([prior], [next])!;
|
|
66
|
+
expect(diffs).toBeDefined();
|
|
67
|
+
expect(diffs[0]!.nodes.add).toHaveLength(1);
|
|
68
|
+
expect(diffs[0]!.nodes.remove).toEqual([]);
|
|
69
|
+
expect(diffs[0]!.edges.add).toHaveLength(1);
|
|
70
|
+
expect(applyEntryDiffs([prior], diffs)).toEqual([next]);
|
|
71
|
+
|
|
72
|
+
const base = { rootId: ROOT, baseGeneration: 1, targetDigest: ZERO_DIGEST };
|
|
73
|
+
const small = await encodePack({ ...base, extracted: [{ kind: 'diff', hash: next.sourceHash, prior: prior.sourceHash, entries: diffs }] });
|
|
74
|
+
const whole = await encodePack({ ...base, extracted: [{ kind: 'full', hash: next.sourceHash, entries: [next] }] });
|
|
75
|
+
expect(small.length * 5).toBeLessThan(whole.length);
|
|
76
|
+
const back = await decodePack(small);
|
|
77
|
+
expect(applyEntryDiffs([prior], (back.extracted![0] as { entries: typeof diffs }).entries)).toEqual([next]);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it('handles removed, changed and inserted items at any position', () => {
|
|
81
|
+
const g = gen(6);
|
|
82
|
+
const prior = extractionOf(g, 'src/a.ts', 'a'.repeat(64), ['src/x.ts', 'src/y.ts'], 6, true);
|
|
83
|
+
const nodes = prior.nodes.filter((_, i) => i !== 2).map((n, i) => (i === 3 ? { ...n, label: 'renamed' } : n));
|
|
84
|
+
nodes.splice(1, 0, { ...prior.nodes[2]!, ref: 'src:ws:gen::src/a.ts#mid' as typeof prior.nodes[0]['ref'] });
|
|
85
|
+
const next = { ...prior, sourceHash: 'e'.repeat(64), nodes };
|
|
86
|
+
expect(applyEntryDiffs([prior], diffEntries([prior], [next])!)).toEqual([next]);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it('falls back to a whole entry when the surviving items change order or an identity repeats', () => {
|
|
90
|
+
const g = gen(7);
|
|
91
|
+
const prior = extractionOf(g, 'src/a.ts', 'a'.repeat(64), ['src/x.ts'], 4, false);
|
|
92
|
+
expect(diffEntries([prior], [{ ...prior, nodes: [...prior.nodes].reverse() }])).toBeUndefined();
|
|
93
|
+
expect(diffEntries([prior], [{ ...prior, nodes: [...prior.nodes, prior.nodes[0]!] }])).toBeUndefined();
|
|
94
|
+
expect(diffEntries([], [prior])).toBeUndefined();
|
|
95
|
+
});
|
|
96
|
+
});
|