@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.
- package/README.md +21 -0
- package/dist/knowledge/build.d.ts.map +1 -1
- package/dist/knowledge/build.js +13 -7
- 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 +25 -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/index.d.ts +5 -3
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +2 -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/pack/crc32.d.ts +7 -0
- package/dist/knowledge/pack/crc32.d.ts.map +1 -0
- package/dist/knowledge/pack/crc32.js +22 -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 +66 -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 +26 -0
- package/dist/knowledge/pack/encode.d.ts.map +1 -0
- package/dist/knowledge/pack/encode.js +86 -0
- package/dist/knowledge/pack/encode.js.map +1 -0
- package/dist/knowledge/pack/extrDiff.d.ts +26 -0
- package/dist/knowledge/pack/extrDiff.d.ts.map +1 -0
- package/dist/knowledge/pack/extrDiff.js +129 -0
- package/dist/knowledge/pack/extrDiff.js.map +1 -0
- package/dist/knowledge/pack/frame.d.ts +45 -0
- package/dist/knowledge/pack/frame.d.ts.map +1 -0
- package/dist/knowledge/pack/frame.js +101 -0
- package/dist/knowledge/pack/frame.js.map +1 -0
- package/dist/knowledge/pack/hex.d.ts +7 -0
- package/dist/knowledge/pack/hex.d.ts.map +1 -0
- package/dist/knowledge/pack/hex.js +17 -0
- package/dist/knowledge/pack/hex.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 +200 -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 +172 -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 +227 -0
- package/dist/knowledge/pack/sections/rows.js.map +1 -0
- package/dist/knowledge/pack/strings.d.ts +43 -0
- package/dist/knowledge/pack/strings.d.ts.map +1 -0
- package/dist/knowledge/pack/strings.js +117 -0
- package/dist/knowledge/pack/strings.js.map +1 -0
- package/dist/knowledge/pack/types.d.ts +118 -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 +57 -0
- package/dist/knowledge/pack/varint.d.ts.map +1 -0
- package/dist/knowledge/pack/varint.js +145 -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 +41 -1
- package/dist/knowledge/reviewModel.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.d.ts +10 -2
- package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.js +60 -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/package.json +8 -3
- package/src/contract/dist.contract.test.ts +44 -0
- package/src/contract/exports.contract.test.ts +90 -0
- package/src/contract/exports.snapshot.json +605 -0
- package/src/contract/pack.contract.test.ts +31 -0
- package/src/contract/regression.review.test.ts +236 -0
- package/src/contract/regression.store.test.ts +84 -0
- package/src/contract/types.contract.test.ts +183 -0
- package/src/knowledge/build.ts +11 -5
- package/src/knowledge/extractFile.ts +28 -6
- package/src/knowledge/extractJob.ts +26 -7
- package/src/knowledge/index.ts +5 -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/pack/crc32.ts +21 -0
- package/src/knowledge/pack/decode.ts +60 -0
- package/src/knowledge/pack/deflate.ts +43 -0
- package/src/knowledge/pack/encode.ts +89 -0
- package/src/knowledge/pack/extrDiff.ts +116 -0
- package/src/knowledge/pack/frame.ts +94 -0
- package/src/knowledge/pack/hex.ts +17 -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 +109 -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 +151 -0
- package/src/knowledge/pack/sections/facts.ts +126 -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 +126 -0
- package/src/knowledge/pack/types.ts +97 -0
- package/src/knowledge/pack/varint.ts +145 -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 +38 -1
- package/src/knowledge/reviewPrefetch.ts +60 -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 +12 -0
- package/src/knowledge/testkit.test-util.ts +13 -2
|
@@ -0,0 +1,94 @@
|
|
|
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 { fromHex64, HEX64, toHex } from './hex.js';
|
|
13
|
+
import { ByteReader, ByteWriter, PackFormatError } from './varint.js';
|
|
14
|
+
|
|
15
|
+
export const MAGIC = [0x42, 0x46, 0x4b, 0x50] as const; // "BFKP"
|
|
16
|
+
export const VERSION = 1;
|
|
17
|
+
export const FLAG_DEFLATED = 1;
|
|
18
|
+
export const KPACK_CONTENT_TYPE = 'application/vnd.builderforce.kpack';
|
|
19
|
+
/** A compressed pack larger than this travels as several parts. */
|
|
20
|
+
export const MAX_PART_BYTES = 8 * 1024 * 1024;
|
|
21
|
+
|
|
22
|
+
export interface FrameHeader { flags: number; rootId: string; baseGeneration: number; targetDigest: string }
|
|
23
|
+
|
|
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
|
+
*/
|
|
28
|
+
export function writeFrame(h: FrameHeader, body: Uint8Array, storedBody: Uint8Array): Uint8Array {
|
|
29
|
+
if (!HEX64.test(h.targetDigest)) throw new PackFormatError('targetDigest is 64 lowercase hex characters');
|
|
30
|
+
const w = new ByteWriter();
|
|
31
|
+
for (const m of MAGIC) w.u8(m);
|
|
32
|
+
w.u8(VERSION);
|
|
33
|
+
w.u8(h.flags);
|
|
34
|
+
w.str(h.rootId);
|
|
35
|
+
w.varint(h.baseGeneration);
|
|
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();
|
|
43
|
+
}
|
|
44
|
+
|
|
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 } {
|
|
50
|
+
if (bytes.length < 4 + 2 + 1 + 1 + 32 + 4) throw new PackFormatError('truncated frame');
|
|
51
|
+
const r = new ByteReader(bytes);
|
|
52
|
+
for (const m of MAGIC) if (r.u8() !== m) throw new PackFormatError('not a BFKP pack (bad magic)');
|
|
53
|
+
const version = r.u8();
|
|
54
|
+
if (version !== VERSION) throw new PackFormatError(`unsupported BFKP version ${version}`);
|
|
55
|
+
const flags = r.u8();
|
|
56
|
+
const rootId = r.str();
|
|
57
|
+
const baseGeneration = r.varint();
|
|
58
|
+
const targetDigest = toHex(r.bytes(32));
|
|
59
|
+
const headerBytes = bytes.subarray(0, r.offset);
|
|
60
|
+
if (r.remaining < 4) throw new PackFormatError('truncated frame');
|
|
61
|
+
const stored = r.bytes(r.remaining - 4);
|
|
62
|
+
return { header: { flags, rootId, baseGeneration, targetDigest }, headerBytes, stored, crc: r.u32le() };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function writeSection(w: ByteWriter, tag: number, bytes: Uint8Array): void {
|
|
66
|
+
w.u8(tag);
|
|
67
|
+
w.varint(bytes.length);
|
|
68
|
+
w.bytes(bytes);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The sections of a decoded body by tag (a repeated tag keeps the last); unknown tags are returned too, for the caller to skip. */
|
|
72
|
+
export function readSections(body: Uint8Array): Map<number, Uint8Array> {
|
|
73
|
+
const r = new ByteReader(body);
|
|
74
|
+
const out = new Map<number, Uint8Array>();
|
|
75
|
+
while (!r.done) { const tag = r.u8(); out.set(tag, r.bytes(r.varint())); }
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Cuts a pack into ordered parts of at most `max` bytes. A pack within `max` is one part. */
|
|
80
|
+
export function splitParts(pack: Uint8Array, max: number = MAX_PART_BYTES): Uint8Array[] {
|
|
81
|
+
if (pack.length <= max) return [pack];
|
|
82
|
+
const parts: Uint8Array[] = [];
|
|
83
|
+
for (let at = 0; at < pack.length; at += max) parts.push(pack.subarray(at, Math.min(at + max, pack.length)));
|
|
84
|
+
return parts;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The inverse of {@link splitParts}. */
|
|
88
|
+
export function joinParts(parts: readonly Uint8Array[]): Uint8Array {
|
|
89
|
+
if (parts.length === 1) return parts[0]!;
|
|
90
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
91
|
+
let at = 0;
|
|
92
|
+
for (const p of parts) { out.set(p, at); at += p.length; }
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -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,109 @@
|
|
|
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, writeSection } from './frame.js';
|
|
8
|
+
import { ByteWriter } from './varint.js';
|
|
9
|
+
import { decodePack, encodePack, joinParts, PackFormatError, PackTooLargeError, peekPack, splitParts, ZERO_DIGEST } from './index.js';
|
|
10
|
+
import { genPack } from './pack.testkit.test-util.js';
|
|
11
|
+
|
|
12
|
+
describe('BFKP guards', () => {
|
|
13
|
+
it('rejects a flipped byte of an uncompressed body with a CRC failure', async () => {
|
|
14
|
+
const bytes = await encodePack(genPack(2, { files: 10 }), { deflate: false });
|
|
15
|
+
const bad = bytes.slice();
|
|
16
|
+
bad[Math.floor(bytes.length / 2)]! ^= 0x01;
|
|
17
|
+
await expect(decodePack(bad)).rejects.toThrow(PackFormatError);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
it('rejects a flipped byte of a deflated body (corrupt stream or CRC)', async () => {
|
|
21
|
+
const bytes = await encodePack(genPack(2, { files: 10 }));
|
|
22
|
+
const bad = bytes.slice();
|
|
23
|
+
bad[Math.floor(bytes.length / 2)]! ^= 0xff;
|
|
24
|
+
await expect(decodePack(bad)).rejects.toThrow(PackFormatError);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it('rejects a bad magic, a truncated frame and an unknown version', async () => {
|
|
28
|
+
const bytes = await encodePack(genPack(2, { files: 3 }));
|
|
29
|
+
await expect(decodePack(new Uint8Array([1, 2, 3]))).rejects.toThrow(PackFormatError);
|
|
30
|
+
const magic = bytes.slice(); magic[0] = 0x00;
|
|
31
|
+
await expect(decodePack(magic)).rejects.toThrow(/magic/);
|
|
32
|
+
const version = bytes.slice(); version[4] = 9;
|
|
33
|
+
await expect(decodePack(version)).rejects.toThrow(/version/);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it('skips a section tag it does not know', async () => {
|
|
37
|
+
const pack = genPack(4, { files: 8 });
|
|
38
|
+
const { header, stored } = readFrame(await encodePack(pack, { deflate: false }));
|
|
39
|
+
const body = new Uint8Array(stored.length + 5);
|
|
40
|
+
body.set(stored);
|
|
41
|
+
body.set([0x7f, 3, 9, 9, 9], stored.length);
|
|
42
|
+
const decoded = await decodePack(writeFrame({ ...header, flags: 0 }, body, body));
|
|
43
|
+
expect(decoded).toEqual(await decodePack(await encodePack(pack)));
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('stops inflating at the cap: a small bomb never holds more than the limit', async () => {
|
|
47
|
+
const body = new Uint8Array(8 * 1024 * 1024);
|
|
48
|
+
const bomb = writeFrame({ flags: FLAG_DEFLATED, rootId: 'r', baseGeneration: 0, targetDigest: ZERO_DIGEST }, body, await deflateRaw(body));
|
|
49
|
+
expect(bomb.length).toBeLessThan(100_000);
|
|
50
|
+
await expect(decodePack(bomb, { maxDecodedBytes: 1024 * 1024 })).rejects.toThrow(PackTooLargeError);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('applies the 64 MB default cap', async () => {
|
|
54
|
+
const body = new Uint8Array(65 * 1024 * 1024);
|
|
55
|
+
const bomb = writeFrame({ flags: FLAG_DEFLATED, rootId: 'r', baseGeneration: 0, targetDigest: ZERO_DIGEST }, body, await deflateRaw(body));
|
|
56
|
+
await expect(decodePack(bomb)).rejects.toThrow(PackTooLargeError);
|
|
57
|
+
}, 60_000);
|
|
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
|
+
|
|
90
|
+
it('bounds counts before allocating for them', async () => {
|
|
91
|
+
const bytes = await encodePack(genPack(5, { files: 20 }));
|
|
92
|
+
await expect(decodePack(bytes, { maxRows: 5 })).rejects.toThrow(PackFormatError);
|
|
93
|
+
await expect(decodePack(bytes, { maxStrings: 5 })).rejects.toThrow(PackFormatError);
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it('reads the generation and digest without inflating the body', async () => {
|
|
97
|
+
const pack = { ...genPack(6, { files: 4 }), baseGeneration: 7 };
|
|
98
|
+
expect(peekPack(await encodePack(pack))).toEqual({ rootId: pack.rootId, baseGeneration: 7, targetDigest: pack.targetDigest });
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('splits into ordered parts and joins them back byte for byte', async () => {
|
|
102
|
+
const bytes = await encodePack(genPack(8, { files: 30 }), { deflate: false });
|
|
103
|
+
const parts = splitParts(bytes, 1000);
|
|
104
|
+
expect(parts.length).toBeGreaterThan(1);
|
|
105
|
+
expect(parts.every((p) => p.length <= 1000)).toBe(true);
|
|
106
|
+
expect(Buffer.from(joinParts(parts)).equals(Buffer.from(bytes))).toBe(true);
|
|
107
|
+
expect(splitParts(bytes, bytes.length + 1)).toHaveLength(1);
|
|
108
|
+
});
|
|
109
|
+
});
|
|
@@ -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
|
+
});
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/pack/pack.roundtrip.test.ts — BFKP v1 is lossless and deterministic (PRD 41 A11 Accept):
|
|
3
|
+
* a property-style round trip over seeded generated graphs, and equal input gives equal bytes.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { decodePack, encodePack, normalizePack, ZERO_DIGEST, type Pack } from './index.js';
|
|
7
|
+
import { genPack } from './pack.testkit.test-util.js';
|
|
8
|
+
|
|
9
|
+
describe('BFKP round trip', () => {
|
|
10
|
+
it('decode(encode(x)) deep-equals the normalized input over 40 generated graphs', async () => {
|
|
11
|
+
for (let seed = 1; seed <= 40; seed++) {
|
|
12
|
+
const pack = genPack(seed, { files: seed % 11 === 0 ? 0 : (seed * 7) % 45, rich: seed % 2 === 0, hashes: seed % 5 === 0 });
|
|
13
|
+
const decoded = await decodePack(await encodePack(pack));
|
|
14
|
+
expect(decoded).toEqual(normalizePack(pack));
|
|
15
|
+
}
|
|
16
|
+
}, 60_000); // 40 generated graphs, each deflated and inflated: about 11 s under a parallel run
|
|
17
|
+
|
|
18
|
+
it('round-trips an uncompressed frame the same as a deflated one', async () => {
|
|
19
|
+
const pack = genPack(3, { files: 20 });
|
|
20
|
+
expect(await decodePack(await encodePack(pack, { deflate: false }))).toEqual(await decodePack(await encodePack(pack)));
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('is deterministic: equal input, in any row order, gives equal bytes', async () => {
|
|
24
|
+
const pack = genPack(7, { files: 30 });
|
|
25
|
+
const shuffled: Pack = { ...pack, files: [...pack.files!].reverse(), facts: [...(pack.facts ?? [])].reverse(), relations: [...(pack.relations ?? [])].reverse() };
|
|
26
|
+
const a = await encodePack(pack), b = await encodePack(pack), c = await encodePack(shuffled);
|
|
27
|
+
expect(Buffer.from(a).equals(Buffer.from(b))).toBe(true);
|
|
28
|
+
expect(Buffer.from(a).equals(Buffer.from(c))).toBe(true);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it('carries an empty pack (frame only)', async () => {
|
|
32
|
+
const empty: Pack = { rootId: 'r', baseGeneration: 0, targetDigest: ZERO_DIGEST };
|
|
33
|
+
expect(await decodePack(await encodePack(empty))).toEqual(empty);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it('keeps explicit hashes (a have request) apart from referenced ones', async () => {
|
|
37
|
+
const have: Pack = { rootId: 'r', baseGeneration: 0, targetDigest: ZERO_DIGEST, hashes: ['a'.repeat(64), '~tag:x', 'b'.repeat(64)] };
|
|
38
|
+
const back = await decodePack(await encodePack(have));
|
|
39
|
+
expect(back.hashes).toEqual(['a'.repeat(64), 'b'.repeat(64), '~tag:x']);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('round-trips awkward numbers exactly', async () => {
|
|
43
|
+
const g = genPack(1, { files: 1 });
|
|
44
|
+
g.facts = [0, 1, 0.5, 1e-9, 0.1234567, 2 ** 40, 1e15 + 0.5, 123456789.123456789].map((importance, i) => ({
|
|
45
|
+
key: `k${i}`, content: 'c', source: 's', importance, origin: 'model' as const, fileAnchors: [],
|
|
46
|
+
}));
|
|
47
|
+
const back = await decodePack(await encodePack(g));
|
|
48
|
+
expect(back.facts!.map((f) => f.importance).sort()).toEqual(g.facts.map((f) => f.importance).sort());
|
|
49
|
+
});
|
|
50
|
+
});
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/pack/pack.size.test.ts — the size promise (PRD 41 A11 Accept): a first sync of a 20,000-file
|
|
3
|
+
* fixture is at most 10% of the same rows as JSON, and a re-review of 10 files is under 50 KB.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { encodePack, jsonBytesOf, MAX_PART_BYTES, splitParts } from './index.js';
|
|
7
|
+
import { genPack } from './pack.testkit.test-util.js';
|
|
8
|
+
|
|
9
|
+
describe('BFKP size', () => {
|
|
10
|
+
it('packs 20,000 files into at most 10% of the same rows as JSON, in 1 + ceil(size / 8 MB) requests at most', async () => {
|
|
11
|
+
const pack = genPack(11, { files: 20_000, symbols: 4, edgesPerFile: 3, facts: 4_000, rich: false });
|
|
12
|
+
const json = jsonBytesOf(pack);
|
|
13
|
+
const bytes = await encodePack(pack);
|
|
14
|
+
expect(bytes.length / json).toBeLessThanOrEqual(0.1);
|
|
15
|
+
expect(splitParts(bytes).length).toBeLessThanOrEqual(1 + Math.ceil(bytes.length / MAX_PART_BYTES));
|
|
16
|
+
}, 120_000);
|
|
17
|
+
|
|
18
|
+
it('a re-review that changes 10 files is one small pack', async () => {
|
|
19
|
+
const full = genPack(12, { files: 10, symbols: 4 });
|
|
20
|
+
expect((await encodePack(full)).length).toBeLessThan(50 * 1024);
|
|
21
|
+
});
|
|
22
|
+
});
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/** knowledge/pack/pack.testkit.test-util.ts — a seeded generator of knowledge packs (no new dependency). */
|
|
2
|
+
|
|
3
|
+
import type { Extracted, KEdge, KNode, NodeRef, StoredFact, StoredRelation } from '../model.js';
|
|
4
|
+
import type { Pack } from './index.js';
|
|
5
|
+
import { ZERO_DIGEST } from './index.js';
|
|
6
|
+
|
|
7
|
+
/** mulberry32: a small seeded PRNG. */
|
|
8
|
+
export function rng(seed: number): () => number {
|
|
9
|
+
let a = seed >>> 0;
|
|
10
|
+
return () => {
|
|
11
|
+
a = (a + 0x6d2b79f5) >>> 0;
|
|
12
|
+
let t = a;
|
|
13
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
14
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
15
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export const ROOT = 'ws:gen';
|
|
20
|
+
const WORDS = ['alpha', 'béta', '日本語', 'delta', 'emoji😀', 'zeta', 'parse', 'render', 'store', 'sync'];
|
|
21
|
+
const KINDS = ['references', 'links', 'contains', 'mentions', 'custom-kind'];
|
|
22
|
+
|
|
23
|
+
export interface Gen { next(): number; int(n: number): number; pick<T>(xs: readonly T[]): T; chance(p: number): boolean; hex64(): string; word(): string }
|
|
24
|
+
|
|
25
|
+
export function gen(seed: number): Gen {
|
|
26
|
+
const next = rng(seed);
|
|
27
|
+
const int = (n: number): number => Math.floor(next() * n);
|
|
28
|
+
return {
|
|
29
|
+
next, int, pick: (xs) => xs[int(xs.length)]!, chance: (p) => next() < p, word: () => WORDS[int(WORDS.length)]! + int(50),
|
|
30
|
+
hex64: () => Array.from({ length: 64 }, () => '0123456789abcdef'[int(16)]).join(''),
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const ref = (path: string, frag = ''): NodeRef => `src:${ROOT}::${path}${frag}` as NodeRef;
|
|
35
|
+
|
|
36
|
+
/** One file's extraction: a file node, `symbols` symbol nodes, edges to other files, keys. */
|
|
37
|
+
export function extractionOf(g: Gen, path: string, hash: string, targets: readonly string[], symbols: number, rich: boolean): Extracted {
|
|
38
|
+
const nodes: KNode[] = [{ ref: ref(path), kind: 'file', label: path, pack: 'code', importance: Math.round(g.next() * 1e4) / 1e4, origin: 'extracted', sourceHash: hash, system: '', app: 'apps/web' }];
|
|
39
|
+
for (let s = 0; s < symbols; s++) {
|
|
40
|
+
const n: KNode = { ref: ref(path, `#sym${s}`), kind: 'symbol', label: `${g.word()}`, pack: 'code', importance: Math.round(g.next() * 1e4) / 1e4, origin: 'extracted', sourceHash: hash, badges: { line: 1 + s * 7 } };
|
|
41
|
+
if (rich && g.chance(0.3)) { n.stale = g.chance(0.5); n.partition = 'ui'; n.badges = { line: s, kind: 'fn', n: g.next() }; }
|
|
42
|
+
nodes.push(n);
|
|
43
|
+
}
|
|
44
|
+
const edges: KEdge[] = targets.map((t) => {
|
|
45
|
+
const e: KEdge = { from: ref(path), to: ref(t), kind: g.pick(KINDS), weight: g.chance(0.5) ? 1 : g.next(), origin: 'extracted' };
|
|
46
|
+
if (rich && g.chance(0.3)) { e.confidence = g.next(); e.verdict = g.pick(['allowed', 'same', 'skips', 'upward'] as const); e.cycle = g.chance(0.5); e.stale = g.chance(0.5); e.byName = g.word(); }
|
|
47
|
+
return e;
|
|
48
|
+
});
|
|
49
|
+
return { sourceRef: ref(path), sourceHash: hash, ...(rich && g.chance(0.5) ? { extractorVersion: g.int(9) } : {}), nodes, edges, keys: [{ ref: ref(path), key: path.toLowerCase() }] };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface GenOptions { files: number; symbols?: number; edgesPerFile?: number; facts?: number; rich?: boolean; hashes?: boolean }
|
|
53
|
+
|
|
54
|
+
/** A generated pack: files, a full extraction per file, facts, relations, stale marks, tombstones, scope. */
|
|
55
|
+
export function genPack(seed: number, o: GenOptions): Pack {
|
|
56
|
+
const g = gen(seed);
|
|
57
|
+
const rich = o.rich ?? true;
|
|
58
|
+
const paths = Array.from({ length: o.files }, (_, i) => `src/d${i % 37}/${g.word()}-${i}.ts`);
|
|
59
|
+
const hashes = paths.map(() => g.hex64());
|
|
60
|
+
const pack: Pack = { rootId: ROOT, baseGeneration: g.int(5), targetDigest: g.hex64() };
|
|
61
|
+
if (o.files > 0) {
|
|
62
|
+
pack.files = paths.map((path, i) => ({ path, hash: hashes[i]!, bytes: g.int(90_000) }));
|
|
63
|
+
pack.extracted = paths.map((path, i) => ({
|
|
64
|
+
kind: 'full' as const, hash: hashes[i]!,
|
|
65
|
+
entries: [extractionOf(g, path, hashes[i]!, Array.from({ length: o.edgesPerFile ?? 3 }, () => paths[g.int(paths.length)]!), o.symbols ?? 4, rich)],
|
|
66
|
+
}));
|
|
67
|
+
pack.stale = paths.slice(0, Math.ceil(o.files / 4)).map((p, i) => ({ sourceRef: ref(p), hash: hashes[i]! }));
|
|
68
|
+
pack.deletes = { files: [`gone/${g.word()}.ts`], facts: [`claim:${g.hex64().slice(0, 12)}`], relations: [{ from: ref('a.ts'), to: ref('b.ts'), kind: 'references' }] };
|
|
69
|
+
}
|
|
70
|
+
const facts: StoredFact[] = Array.from({ length: o.facts ?? Math.floor(o.files / 4) }, (_, i) => {
|
|
71
|
+
const f: StoredFact = { key: `claim:${i}-${g.word()}`, content: `The ${g.word()} module ${g.word()} the ${g.word()}.`, source: 'review', importance: Math.round(g.next() * 1e3) / 1e3, origin: g.pick(['model', 'human', 'agent'] as const), fileAnchors: [] };
|
|
72
|
+
if (paths.length > 0) f.fileAnchors = Array.from({ length: g.int(3) }, () => ({ path: paths[g.int(paths.length)]!, ...(g.chance(0.5) ? { line: g.int(500) } : {}), ...(g.chance(0.5) ? { contentHash: g.hex64() } : {}) }));
|
|
73
|
+
if (rich && g.chance(0.3)) { f.updatedAt = '2026-11-07T10:00:00.000Z'; f.createdBy = g.chance(0.5) ? null : 'user-1'; }
|
|
74
|
+
return f;
|
|
75
|
+
});
|
|
76
|
+
if (facts.length > 0) pack.facts = facts;
|
|
77
|
+
if (paths.length > 1) {
|
|
78
|
+
pack.relations = Array.from({ length: Math.floor(o.files / 3) }, (_, i): StoredRelation => {
|
|
79
|
+
const r: StoredRelation = { from: ref(paths[g.int(paths.length)]!), to: `fact:claim:${i}` as NodeRef, kind: g.pick(KINDS), weight: g.chance(0.5) ? 1 : g.next(), origin: g.pick(['model', 'human', 'agent'] as const) };
|
|
80
|
+
if (rich && g.chance(0.4)) { r.confidence = g.next(); r.sourceHash = hashes[g.int(hashes.length)]!; r.staleAt = g.chance(0.5) ? null : '2026-11-07T00:00:00.000Z'; }
|
|
81
|
+
return r;
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
if (rich && g.chance(0.5)) pack.scope = { rootId: ROOT, title: 'Gen', packs: ['code', 'docs'], lastDigest: g.hex64().slice(0, 32), lastReviewedAt: '2026-11-07T00:00:00.000Z' };
|
|
85
|
+
if (rich && g.chance(0.5)) pack.analysis = { version: 1, nodes: ['a'], edges: [] };
|
|
86
|
+
if (o.hashes) pack.hashes = [g.hex64(), '~tag:odd-id', g.hex64()];
|
|
87
|
+
return pack;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export { ZERO_DIGEST };
|