@seanhogg/builderforce-memory 2026.10.45 → 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 +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 +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/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 +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/package.json +7 -3
- package/src/knowledge/build.ts +11 -5
- package/src/knowledge/extractFile.ts +26 -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 +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 +12 -0
|
@@ -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
|
+
});
|
|
@@ -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
|
+
});
|
|
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 };
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/pack/sections/columns.ts — helpers the BFKP sections share: enums that turn the model's
|
|
3
|
+
* small closed vocabularies into one byte, zigzag deltas for index runs, and the section
|
|
4
|
+
* descriptor type (PRD 41 A11).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { Pack, PackLimits } from '../types.js';
|
|
8
|
+
import type { ReadTables, Tables } from '../strings.js';
|
|
9
|
+
import { PackFormatError, type ByteReader, type ByteWriter } from '../varint.js';
|
|
10
|
+
|
|
11
|
+
/** One section: its tag, how it is written from a pack (undefined = nothing to write) and read back into one. */
|
|
12
|
+
export interface SectionCodec {
|
|
13
|
+
tag: number;
|
|
14
|
+
write(pack: Pack, t: Tables): Uint8Array | undefined;
|
|
15
|
+
read(bytes: Uint8Array, t: ReadTables, limits: PackLimits, into: Pack): void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const ORIGINS = ['extracted', 'model', 'human', 'agent'] as const;
|
|
19
|
+
export const STORED_ORIGINS = ['model', 'human', 'agent'] as const;
|
|
20
|
+
export const VERDICTS = ['allowed', 'same', 'skips', 'upward'] as const;
|
|
21
|
+
/** The relation/edge kinds the model names; anything else is stored as 0 + a string. */
|
|
22
|
+
export const EDGE_KINDS = [
|
|
23
|
+
'references', 'links', 'contains', 'mentions', 'duplicate', 'near-duplicate', 'contradicts', 'agrees',
|
|
24
|
+
'supersedes', 'about', 'co-changed',
|
|
25
|
+
] as const;
|
|
26
|
+
/** The node kinds the packs name. */
|
|
27
|
+
export const NODE_KINDS = ['file', 'section', 'symbol', 'area', 'entity', 'claim', 'fact'] as const;
|
|
28
|
+
|
|
29
|
+
export const zigzag = (n: number): number => (n >= 0 ? n * 2 : -n * 2 - 1);
|
|
30
|
+
export const unzigzag = (z: number): number => (z % 2 === 0 ? z / 2 : -(z + 1) / 2);
|
|
31
|
+
|
|
32
|
+
/** A closed vocabulary: the index + 1 of a known word, else 0 followed by the word's string index. */
|
|
33
|
+
export function writeWord(w: ByteWriter, t: Tables, vocab: readonly string[], word: string): void {
|
|
34
|
+
const at = vocab.indexOf(word);
|
|
35
|
+
if (at >= 0) w.varint(at + 1);
|
|
36
|
+
else { w.varint(0); w.varint(t.str(word)); }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function readWord(r: ByteReader, t: ReadTables, vocab: readonly string[]): string {
|
|
40
|
+
const code = r.varint();
|
|
41
|
+
if (code === 0) return t.str(r.varint());
|
|
42
|
+
const word = vocab[code - 1];
|
|
43
|
+
if (word === undefined) throw new PackFormatError('unknown vocabulary code');
|
|
44
|
+
return word;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** A closed enum that must be one of `vocab`. */
|
|
48
|
+
export function writeEnum(w: ByteWriter, vocab: readonly string[], value: string): void {
|
|
49
|
+
const at = vocab.indexOf(value);
|
|
50
|
+
if (at < 0) throw new PackFormatError(`value '${value}' is not one of ${vocab.join('|')}`);
|
|
51
|
+
w.u8(at);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function readEnum<T extends string>(r: ByteReader, vocab: readonly T[]): T {
|
|
55
|
+
const v = vocab[r.u8()];
|
|
56
|
+
if (v === undefined) throw new PackFormatError('unknown enum code');
|
|
57
|
+
return v;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Strings sort the way the string table does, so a sorted run of rows has non-decreasing indexes. */
|
|
61
|
+
export const compare = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/pack/sections/extr.ts — the EXTR section of BFKP v1 (PRD 41 A11): the Extracted output per
|
|
3
|
+
* content hash. A hash is either whole (`full`: nodes, edges and keys columnar) or a `diff` against the
|
|
4
|
+
* prior hash's extraction of the same source (`prior hash#` plus the added and removed items).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { Extracted, ExtrEntryDiff, ListDiff, PackExtr } from '../types.js';
|
|
8
|
+
import type { ReadTables, Tables } from '../strings.js';
|
|
9
|
+
import { boundedCount, ByteReader, ByteWriter } from '../varint.js';
|
|
10
|
+
import type { SectionCodec } from './columns.js';
|
|
11
|
+
import { readEdges, readKeys, readNodes, writeEdges, writeKeys, writeNodes } from './extrLists.js';
|
|
12
|
+
import { TAG } from './rows.js';
|
|
13
|
+
|
|
14
|
+
const HAS_VERSION = 1;
|
|
15
|
+
|
|
16
|
+
function writeDiff<T>(w: ByteWriter, t: Tables, d: ListDiff<T>, items: (w: ByteWriter, t: Tables, xs: T[]) => void): void {
|
|
17
|
+
w.varint(d.remove.length);
|
|
18
|
+
for (const id of d.remove) w.varint(t.str(id));
|
|
19
|
+
let prev = 0;
|
|
20
|
+
w.varint(d.add.length);
|
|
21
|
+
for (const a of d.add) { w.varint(a.at - prev); prev = a.at; }
|
|
22
|
+
items(w, t, d.add.map((a) => a.item));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function readDiff<T>(r: ByteReader, t: ReadTables, max: number, items: (r: ByteReader, t: ReadTables, max: number) => T[]): ListDiff<T> {
|
|
26
|
+
const remove = Array.from({ length: boundedCount(r, max, 'diff removals') }, () => t.str(r.varint()));
|
|
27
|
+
const n = boundedCount(r, max, 'diff additions');
|
|
28
|
+
const ats: number[] = [];
|
|
29
|
+
let prev = 0;
|
|
30
|
+
for (let i = 0; i < n; i++) { prev += r.varint(); ats.push(prev); }
|
|
31
|
+
const list = items(r, t, max);
|
|
32
|
+
return { remove, add: ats.map((at, i) => ({ at, item: list[i]! })) };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export const extrSection: SectionCodec = {
|
|
36
|
+
tag: TAG.EXTR,
|
|
37
|
+
write(pack, t) {
|
|
38
|
+
const rows = pack.extracted;
|
|
39
|
+
if (!rows?.length) return undefined;
|
|
40
|
+
const w = new ByteWriter();
|
|
41
|
+
w.varint(rows.length);
|
|
42
|
+
for (const x of rows) {
|
|
43
|
+
w.u8(x.kind === 'full' ? 0 : 1);
|
|
44
|
+
w.varint(t.hash(x.hash));
|
|
45
|
+
if (x.kind === 'diff') w.varint(t.hash(x.prior));
|
|
46
|
+
w.varint(x.entries.length);
|
|
47
|
+
for (const e of x.entries) {
|
|
48
|
+
w.varint(t.str(e.sourceRef));
|
|
49
|
+
w.varint(t.hash(e.sourceHash));
|
|
50
|
+
w.u8(e.extractorVersion !== undefined ? HAS_VERSION : 0);
|
|
51
|
+
if (e.extractorVersion !== undefined) w.varint(e.extractorVersion);
|
|
52
|
+
if (x.kind === 'full') {
|
|
53
|
+
const f = e as Extracted;
|
|
54
|
+
writeNodes(w, t, f.nodes); writeEdges(w, t, f.edges); writeKeys(w, t, f.keys);
|
|
55
|
+
} else {
|
|
56
|
+
const d = e as ExtrEntryDiff;
|
|
57
|
+
writeDiff(w, t, d.nodes, writeNodes); writeDiff(w, t, d.edges, writeEdges); writeDiff(w, t, d.keys, writeKeys);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return w.finish();
|
|
62
|
+
},
|
|
63
|
+
read(bytes, t, limits, into) {
|
|
64
|
+
const r = new ByteReader(bytes);
|
|
65
|
+
const n = boundedCount(r, limits.maxRows, 'extracted hashes');
|
|
66
|
+
const out: PackExtr[] = [];
|
|
67
|
+
for (let i = 0; i < n; i++) {
|
|
68
|
+
const diff = r.u8() === 1;
|
|
69
|
+
const hash = t.hash(r.varint());
|
|
70
|
+
const prior = diff ? t.hash(r.varint()) : '';
|
|
71
|
+
const count = boundedCount(r, limits.maxRows, 'extracted entries');
|
|
72
|
+
const entries: Array<Extracted | ExtrEntryDiff> = [];
|
|
73
|
+
for (let k = 0; k < count; k++) {
|
|
74
|
+
const sourceRef = t.str(r.varint());
|
|
75
|
+
const sourceHash = t.hash(r.varint());
|
|
76
|
+
const version = r.u8() & HAS_VERSION ? { extractorVersion: r.varint() } : {};
|
|
77
|
+
if (!diff) {
|
|
78
|
+
entries.push({ sourceRef: sourceRef as Extracted['sourceRef'], sourceHash, ...version, nodes: readNodes(r, t, limits.maxRows), edges: readEdges(r, t, limits.maxRows), keys: readKeys(r, t, limits.maxRows) });
|
|
79
|
+
} else {
|
|
80
|
+
entries.push({
|
|
81
|
+
sourceRef, sourceHash, ...version,
|
|
82
|
+
nodes: readDiff(r, t, limits.maxRows, readNodes), edges: readDiff(r, t, limits.maxRows, readEdges), keys: readDiff(r, t, limits.maxRows, readKeys),
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
out.push(diff ? { kind: 'diff', hash, prior, entries: entries as ExtrEntryDiff[] } : { kind: 'full', hash, entries: entries as Extracted[] });
|
|
87
|
+
}
|
|
88
|
+
into.extracted = out;
|
|
89
|
+
},
|
|
90
|
+
};
|