@seanhogg/builderforce-memory 2026.10.63 → 2026.10.66
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/pack/frame.d.ts +12 -3
- package/dist/knowledge/pack/frame.d.ts.map +1 -1
- package/dist/knowledge/pack/frame.js +18 -4
- package/dist/knowledge/pack/frame.js.map +1 -1
- package/dist/knowledge/pack/manifest.d.ts +11 -3
- package/dist/knowledge/pack/manifest.d.ts.map +1 -1
- package/dist/knowledge/pack/manifest.js +26 -12
- package/dist/knowledge/pack/manifest.js.map +1 -1
- package/dist/knowledge/pack/sections/extr.d.ts.map +1 -1
- package/dist/knowledge/pack/sections/extr.js +16 -4
- package/dist/knowledge/pack/sections/extr.js.map +1 -1
- package/dist/knowledge/pack/sections/extrLists.d.ts +0 -1
- package/dist/knowledge/pack/sections/extrLists.d.ts.map +1 -1
- package/dist/knowledge/pack/sections/extrLists.js +5 -6
- package/dist/knowledge/pack/sections/extrLists.js.map +1 -1
- package/dist/knowledge/pack/sections/facts.d.ts.map +1 -1
- package/dist/knowledge/pack/sections/facts.js +3 -2
- package/dist/knowledge/pack/sections/facts.js.map +1 -1
- package/dist/knowledge/pack/sections/rows.d.ts.map +1 -1
- package/dist/knowledge/pack/sections/rows.js +11 -2
- package/dist/knowledge/pack/sections/rows.js.map +1 -1
- package/dist/knowledge/pack/strings.d.ts.map +1 -1
- package/dist/knowledge/pack/strings.js +6 -1
- package/dist/knowledge/pack/strings.js.map +1 -1
- package/dist/knowledge/pack/varint.d.ts +14 -0
- package/dist/knowledge/pack/varint.d.ts.map +1 -1
- package/dist/knowledge/pack/varint.js +32 -1
- package/dist/knowledge/pack/varint.js.map +1 -1
- package/dist/knowledge/review.d.ts +6 -6
- package/dist/knowledge/review.d.ts.map +1 -1
- package/dist/knowledge/review.js +56 -329
- package/dist/knowledge/review.js.map +1 -1
- package/dist/knowledge/reviewAnalyse.d.ts +17 -0
- package/dist/knowledge/reviewAnalyse.d.ts.map +1 -0
- package/dist/knowledge/reviewAnalyse.js +61 -0
- package/dist/knowledge/reviewAnalyse.js.map +1 -0
- package/dist/knowledge/reviewApply.d.ts +33 -0
- package/dist/knowledge/reviewApply.d.ts.map +1 -0
- package/dist/knowledge/reviewApply.js +121 -0
- package/dist/knowledge/reviewApply.js.map +1 -0
- package/dist/knowledge/reviewContext.d.ts +77 -0
- package/dist/knowledge/reviewContext.d.ts.map +1 -0
- package/dist/knowledge/reviewContext.js +111 -0
- package/dist/knowledge/reviewContext.js.map +1 -0
- package/dist/knowledge/reviewFinish.d.ts +9 -0
- package/dist/knowledge/reviewFinish.d.ts.map +1 -0
- package/dist/knowledge/reviewFinish.js +62 -0
- package/dist/knowledge/reviewFinish.js.map +1 -0
- package/dist/knowledge/reviewRunModel.d.ts +3 -0
- package/dist/knowledge/reviewRunModel.d.ts.map +1 -1
- package/dist/knowledge/reviewRunModel.js.map +1 -1
- package/dist/knowledge/stores/extractLogWriter.d.ts +16 -3
- package/dist/knowledge/stores/extractLogWriter.d.ts.map +1 -1
- package/dist/knowledge/stores/extractLogWriter.js +38 -13
- package/dist/knowledge/stores/extractLogWriter.js.map +1 -1
- package/dist/knowledge/stores/extractRefs.d.ts +68 -0
- package/dist/knowledge/stores/extractRefs.d.ts.map +1 -0
- package/dist/knowledge/stores/extractRefs.js +168 -0
- package/dist/knowledge/stores/extractRefs.js.map +1 -0
- package/dist/knowledge/stores/localSnapshotStore.d.ts +5 -0
- package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.js +25 -5
- package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
- package/dist/knowledge/stores/rowDelta.d.ts +6 -0
- package/dist/knowledge/stores/rowDelta.d.ts.map +1 -1
- package/dist/knowledge/stores/rowDelta.js.map +1 -1
- package/dist/knowledge/stores/rowMemory.d.ts +30 -0
- package/dist/knowledge/stores/rowMemory.d.ts.map +1 -1
- package/dist/knowledge/stores/rowMemory.js +46 -1
- package/dist/knowledge/stores/rowMemory.js.map +1 -1
- package/dist/knowledge/stores/rowSync.d.ts.map +1 -1
- package/dist/knowledge/stores/rowSync.js +2 -1
- package/dist/knowledge/stores/rowSync.js.map +1 -1
- package/dist/knowledge/stores/snapshotFormat.d.ts +13 -2
- package/dist/knowledge/stores/snapshotFormat.d.ts.map +1 -1
- package/dist/knowledge/stores/snapshotFormat.js +22 -9
- package/dist/knowledge/stores/snapshotFormat.js.map +1 -1
- package/dist/working/fold.d.ts +14 -0
- package/dist/working/fold.d.ts.map +1 -1
- package/dist/working/fold.js +14 -4
- package/dist/working/fold.js.map +1 -1
- package/dist/working/index.d.ts +3 -1
- package/dist/working/index.d.ts.map +1 -1
- package/dist/working/index.js +2 -1
- package/dist/working/index.js.map +1 -1
- package/dist/working/textSummary.d.ts +46 -0
- package/dist/working/textSummary.d.ts.map +1 -0
- package/dist/working/textSummary.js +142 -0
- package/dist/working/textSummary.js.map +1 -0
- package/package.json +1 -1
- package/src/contract/exports.snapshot.json +7 -1
- package/src/contract/regression.extractEviction.test.ts +162 -0
- package/src/contract/regression.fixCommits.test.ts +112 -0
- package/src/contract/regression.packWire.test.ts +174 -0
- package/src/contract/types.contract.test.ts +2 -1
- package/src/knowledge/pack/frame.ts +21 -5
- package/src/knowledge/pack/manifest.ts +26 -11
- package/src/knowledge/pack/sections/extr.ts +14 -4
- package/src/knowledge/pack/sections/extrLists.ts +4 -6
- package/src/knowledge/pack/sections/facts.ts +3 -2
- package/src/knowledge/pack/sections/rows.ts +11 -2
- package/src/knowledge/pack/strings.ts +5 -1
- package/src/knowledge/pack/varint.ts +33 -1
- package/src/knowledge/review.ts +58 -311
- package/src/knowledge/reviewAnalyse.ts +59 -0
- package/src/knowledge/reviewApply.ts +128 -0
- package/src/knowledge/reviewContext.ts +158 -0
- package/src/knowledge/reviewFinish.ts +63 -0
- package/src/knowledge/reviewRunModel.ts +3 -0
- package/src/knowledge/stores/extractLogWriter.ts +36 -12
- package/src/knowledge/stores/extractRefs.ts +161 -0
- package/src/knowledge/stores/localSnapshotStore.ts +22 -5
- package/src/knowledge/stores/rowDelta.ts +6 -0
- package/src/knowledge/stores/rowMemory.ts +50 -1
- package/src/knowledge/stores/rowSync.ts +2 -1
- package/src/knowledge/stores/snapshotFormat.ts +27 -10
- package/src/working/fold.ts +15 -4
- package/src/working/index.ts +13 -1
- package/src/working/textSummary.test.ts +113 -0
- package/src/working/textSummary.ts +156 -0
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/contract/regression.extractEviction.test.ts — the extract cache never evicted a body: every edit of a file added a content
|
|
3
|
+
* hash kept forever in memory, the snapshot, the extract log and the host's rows. Each invariant of the fix (extractRefs.ts) is
|
|
4
|
+
* pinned by one test named `regression: <what broke>`. A source keeps its current and its ONE previous body.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { Extracted } from '../knowledge/model.js';
|
|
8
|
+
import { LocalSnapshotStore, type ExtractedLogPersistence, type RowChange, type RowPersistence } from '../knowledge/stores/localSnapshotStore.js';
|
|
9
|
+
import { parseLog } from '../knowledge/stores/snapshotFormat.js';
|
|
10
|
+
import { memLog, memPersistence } from '../knowledge/testkit.test-util.js';
|
|
11
|
+
|
|
12
|
+
const body = (hash: string, ...refs: string[]): Extracted[] =>
|
|
13
|
+
refs.map((sourceRef) => ({ sourceRef, sourceHash: hash, nodes: [], edges: [], keys: [] }) as unknown as Extracted);
|
|
14
|
+
const N = 25;
|
|
15
|
+
const hashOf = (i: number) => `${i}`.padStart(64, '0');
|
|
16
|
+
const linesOf = (text: string | undefined) => (text ?? '').split('\n').filter((l) => l.trim()).length;
|
|
17
|
+
const keys = async (s: LocalSnapshotStore) => Object.keys(await s.extractedEntries()).sort();
|
|
18
|
+
|
|
19
|
+
/** A map-backed row host. */
|
|
20
|
+
function rowHost(): RowPersistence & { applies: RowChange[]; db: Map<string, Extracted[]> } {
|
|
21
|
+
const db = new Map<string, Extracted[]>();
|
|
22
|
+
const applies: RowChange[] = [];
|
|
23
|
+
return {
|
|
24
|
+
db, applies,
|
|
25
|
+
async load() { return undefined; },
|
|
26
|
+
async apply(change) {
|
|
27
|
+
applies.push(change);
|
|
28
|
+
for (const [h, e] of change.upserts.extracted) db.set(h, e);
|
|
29
|
+
for (const h of change.deletes.extracted) db.delete(h);
|
|
30
|
+
return { generation: applies.length };
|
|
31
|
+
},
|
|
32
|
+
async loadExtracted(h) { return db.get(h); },
|
|
33
|
+
async loadAllExtracted() { return Object.fromEntries(db); },
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The three store modes, each opened fresh over the same persistence by `reopen`. */
|
|
38
|
+
function modes(): Array<{ name: string; open(): LocalSnapshotStore }> {
|
|
39
|
+
const snap = memPersistence();
|
|
40
|
+
const logSnap = memPersistence(), log: ExtractedLogPersistence = memLog();
|
|
41
|
+
const rows = rowHost();
|
|
42
|
+
return [
|
|
43
|
+
{ name: 'snapshot', open: () => new LocalSnapshotStore(snap) },
|
|
44
|
+
{ name: 'log', open: () => new LocalSnapshotStore(logSnap, { extractedLog: log }) },
|
|
45
|
+
{ name: 'rows', open: () => new LocalSnapshotStore(undefined, { rows }) },
|
|
46
|
+
];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
describe('regression: extract cache eviction', () => {
|
|
50
|
+
it('regression: editing a file N times keeps O(1) bodies — its current and its previous (snapshot mode: memory and the snapshot)', async () => {
|
|
51
|
+
const snap = memPersistence();
|
|
52
|
+
const store = new LocalSnapshotStore(snap);
|
|
53
|
+
for (let i = 0; i < N; i++) await store.putExtracted(hashOf(i), body(hashOf(i), 'src:r::a.ts'));
|
|
54
|
+
expect(await keys(store)).toEqual([hashOf(N - 2), hashOf(N - 1)]);
|
|
55
|
+
expect(Object.keys((JSON.parse(snap.value!) as { extracted: Record<string, unknown> }).extracted).sort()).toEqual([hashOf(N - 2), hashOf(N - 1)]);
|
|
56
|
+
expect(await store.getExtracted(hashOf(0))).toBeUndefined();
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it('regression: editing a file N times keeps O(1) bodies in the extract log once it is compacted, and the compacted log reloads the same', async () => {
|
|
60
|
+
const log = memLog();
|
|
61
|
+
const first = new LocalSnapshotStore(memPersistence(), { extractedLog: log });
|
|
62
|
+
for (let i = 0; i < N; i++) await first.putExtracted(hashOf(i), body(hashOf(i), 'src:r::a.ts'));
|
|
63
|
+
expect(await keys(first)).toEqual([hashOf(N - 2), hashOf(N - 1)]);
|
|
64
|
+
|
|
65
|
+
const reopened = new LocalSnapshotStore(memPersistence(), { extractedLog: log });
|
|
66
|
+
expect(await keys(reopened)).toEqual([hashOf(N - 2), hashOf(N - 1)]);
|
|
67
|
+
expect(log.replaces).toBe(1);
|
|
68
|
+
expect(linesOf(log.text)).toBe(2);
|
|
69
|
+
// The compacted log restores who is current: the next edit evicts the previous body, not the current one.
|
|
70
|
+
await reopened.putExtracted(hashOf(N), body(hashOf(N), 'src:r::a.ts'));
|
|
71
|
+
expect(await keys(reopened)).toEqual([hashOf(N - 1), hashOf(N)]);
|
|
72
|
+
expect(await keys(new LocalSnapshotStore(memPersistence(), { extractedLog: log }))).toEqual([hashOf(N - 1), hashOf(N)]);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('regression: an evicted body still waiting to be appended is never appended', async () => {
|
|
76
|
+
const log = memLog();
|
|
77
|
+
const store = new LocalSnapshotStore(memPersistence(), { extractedLog: log, checkpointMs: 60_000 });
|
|
78
|
+
await store.batched(async () => {
|
|
79
|
+
for (let i = 0; i < N; i++) await store.putExtracted(hashOf(i), body(hashOf(i), 'src:r::a.ts'));
|
|
80
|
+
});
|
|
81
|
+
expect(linesOf(log.text)).toBe(2);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it('regression: a throwing log replay surfaces; only a line that does not parse counts as torn', async () => {
|
|
85
|
+
const text = `not json\nnull\n${JSON.stringify({ h: 'x', e: [] })}\n`;
|
|
86
|
+
const seen: string[] = [];
|
|
87
|
+
expect(parseLog(text, (h) => { seen.push(h); }).liveLines.size).toBe(1);
|
|
88
|
+
expect(seen).toEqual(['x']);
|
|
89
|
+
expect(() => parseLog(text, () => { throw new Error('replay failed'); })).toThrow('replay failed');
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it('regression: row mode deletes the evicted body through the delta delete path', async () => {
|
|
93
|
+
const rows = rowHost();
|
|
94
|
+
const store = new LocalSnapshotStore(undefined, { rows });
|
|
95
|
+
for (const i of [1, 2, 3]) await store.putExtracted(hashOf(i), body(hashOf(i), 'src:r::a.ts'));
|
|
96
|
+
const last = rows.applies[rows.applies.length - 1]!;
|
|
97
|
+
expect(last.upserts.extracted.map(([h]) => h)).toEqual([hashOf(3)]);
|
|
98
|
+
expect(last.deletes.extracted).toEqual([hashOf(1)]);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('regression: row mode evicts a stored body it never loaded, known only through extractedSources', async () => {
|
|
102
|
+
const rows = rowHost();
|
|
103
|
+
rows.db.set(hashOf(1), body(hashOf(1), 'src:r::a.ts'));
|
|
104
|
+
rows.db.set(hashOf(2), body(hashOf(2), 'src:r::a.ts'));
|
|
105
|
+
const host: RowPersistence = { ...rows, async extractedSources() { return { [hashOf(1)]: ['src:r::a.ts'], [hashOf(2)]: ['src:r::a.ts'] }; } };
|
|
106
|
+
const store = new LocalSnapshotStore(undefined, { rows: host });
|
|
107
|
+
await store.putExtracted(hashOf(3), body(hashOf(3), 'src:r::a.ts'));
|
|
108
|
+
// Both were current (their order unknown): one becomes the previous body, the other is evicted.
|
|
109
|
+
expect(rows.applies[rows.applies.length - 1]!.deletes.extracted).toHaveLength(1);
|
|
110
|
+
expect(rows.db.size).toBe(2);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it('regression: switching a file back to its previous content hits the cache (one previous body per source is kept)', async () => {
|
|
114
|
+
const store = new LocalSnapshotStore(memPersistence());
|
|
115
|
+
await store.putExtracted(hashOf(1), body(hashOf(1), 'src:r::a.ts'));
|
|
116
|
+
await store.putExtracted(hashOf(2), body(hashOf(2), 'src:r::a.ts'));
|
|
117
|
+
expect(await store.getExtracted(hashOf(1))).toEqual(body(hashOf(1), 'src:r::a.ts'));
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it('regression: a body shared by two files is kept until neither file is current or previous at it', async () => {
|
|
121
|
+
const store = new LocalSnapshotStore(memPersistence());
|
|
122
|
+
const shared = hashOf(1);
|
|
123
|
+
await store.putExtracted(shared, body(shared, 'src:r::a.ts', 'src:r::b.ts'));
|
|
124
|
+
await store.putExtracted(hashOf(2), body(hashOf(2), 'src:r::a.ts'));
|
|
125
|
+
await store.putExtracted(hashOf(3), body(hashOf(3), 'src:r::b.ts'));
|
|
126
|
+
await store.putExtracted(hashOf(4), body(hashOf(4), 'src:r::a.ts'));
|
|
127
|
+
expect(await store.getExtracted(shared)).toBeDefined(); // still b's previous body
|
|
128
|
+
await store.putExtracted(hashOf(5), body(hashOf(5), 'src:r::b.ts'));
|
|
129
|
+
expect(await store.getExtracted(shared)).toBeUndefined();
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it('regression: root-level outputs of different analyzers (~tag hashes) for one ref never evict each other', async () => {
|
|
133
|
+
const store = new LocalSnapshotStore(memPersistence());
|
|
134
|
+
for (const h of ['~graph:1', '~systems:1', '~graph:2', '~graph:3']) await store.putExtracted(h, body(h, 'src:r::'));
|
|
135
|
+
expect(await keys(store)).toEqual(['~graph:2', '~graph:3', '~systems:1']);
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it('regression: an empty body (nothing to extract) and a body without a sourceRef are never evicted by another put', async () => {
|
|
139
|
+
const store = new LocalSnapshotStore(memPersistence());
|
|
140
|
+
await store.putExtracted('bin', []);
|
|
141
|
+
await store.putExtracted('odd', [{ name: 'x' }] as unknown as Extracted[]);
|
|
142
|
+
for (const i of [1, 2, 3]) await store.putExtracted(hashOf(i), body(hashOf(i), 'src:r::a.ts'));
|
|
143
|
+
expect(await keys(store)).toEqual([hashOf(2), hashOf(3), 'bin', 'odd'].sort());
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it.each(modes())('regression: re-put of a shared hash does not evict another file\'s current body ($name mode)', async ({ open }) => {
|
|
147
|
+
// a shares H9 with x, then H0 with b, then moves to H5. New files c (in H0) and y (in H9) are merged into those cached bodies,
|
|
148
|
+
// which still carry a's old entry: the re-puts must not make a current there again (that evicted H5, a's real body).
|
|
149
|
+
const [h9, h0, h5] = [hashOf(9), hashOf(0), hashOf(5)];
|
|
150
|
+
const store = open();
|
|
151
|
+
await store.putExtracted(h9, body(h9, 'src:r::a.ts'));
|
|
152
|
+
await store.putExtracted(h9, body(h9, 'src:r::a.ts', 'src:r::x.ts'));
|
|
153
|
+
await store.putExtracted(h0, body(h0, 'src:r::a.ts'));
|
|
154
|
+
await store.putExtracted(h0, body(h0, 'src:r::a.ts', 'src:r::b.ts'));
|
|
155
|
+
await store.putExtracted(h5, body(h5, 'src:r::a.ts'));
|
|
156
|
+
await store.putExtracted(h0, body(h0, 'src:r::a.ts', 'src:r::b.ts', 'src:r::c.ts'));
|
|
157
|
+
await store.putExtracted(h9, body(h9, 'src:r::a.ts', 'src:r::x.ts', 'src:r::y.ts'));
|
|
158
|
+
expect(await store.getExtracted(h5)).toEqual(body(h5, 'src:r::a.ts'));
|
|
159
|
+
// …and after reopening over the same persistence.
|
|
160
|
+
expect(await open().getExtracted(h5)).toEqual(body(h5, 'src:r::a.ts'));
|
|
161
|
+
});
|
|
162
|
+
});
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/contract/regression.fixCommits.test.ts — fixes that shipped without a `regression:` test, each now pinned by one:
|
|
3
|
+
* c1d581c scripts are code, not docs; `[[x]]` in code is not a link
|
|
4
|
+
* 88fe16a a Stop never fails the job already under way: the file in hand finishes (its deleted test pinned the reverted behaviour)
|
|
5
|
+
* cd6d9f9 a pool job's deadline adds only the SOURCE's read override to the extract ceiling, never the default read timeout
|
|
6
|
+
* and the review's analyzers: a failing one is recorded, never silent, and the others still run.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { jest } from '@jest/globals';
|
|
10
|
+
import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
|
|
11
|
+
import { markdownParser } from '../ingest/parsers.js';
|
|
12
|
+
import type { SourceDocument } from '../ingest/types.js';
|
|
13
|
+
import { extractJob, type ExtractJob, type ExtractPool } from '../knowledge/extractJob.js';
|
|
14
|
+
import { createDeadlines } from '../knowledge/jobDeadline.js';
|
|
15
|
+
import type { ExtractContext, Extracted, KnowledgePack } from '../knowledge/model.js';
|
|
16
|
+
import { DOCS_PACK } from '../knowledge/packs/docs.js';
|
|
17
|
+
import { planReview } from '../knowledge/plan.js';
|
|
18
|
+
import { reviewDirectory } from '../knowledge/review.js';
|
|
19
|
+
import { analyzerFailurePath } from '../knowledge/reviewAnalyse.js';
|
|
20
|
+
import { asPathSource, resolveRelativePath } from '../knowledge/sources.js';
|
|
21
|
+
import { args, fakeJudge, FILES, memSource, memStore, quietPack, ROOT } from '../knowledge/testkit.test-util.js';
|
|
22
|
+
|
|
23
|
+
const SHELL = 'if [[ -f x ]]; then :; fi\n';
|
|
24
|
+
|
|
25
|
+
describe('regression: c1d581c scripts and code links', () => {
|
|
26
|
+
it('regression: a shell script is not a docs-pack document, and [[x]] inside markdown code is not a link', async () => {
|
|
27
|
+
const listing = {
|
|
28
|
+
rootId: ROOT, title: 't',
|
|
29
|
+
async *list() { yield { path: 'run.sh', hash: 'h1', size: SHELL.length }; yield { path: 'a.md', hash: 'h2', size: 4 }; },
|
|
30
|
+
async read(path: string): Promise<SourceDocument> { return { id: path, tenantId: 't', content: { kind: 'text', text: path === 'run.sh' ? SHELL : '# A\n' } }; },
|
|
31
|
+
};
|
|
32
|
+
const plan = await planReview(listing, new InMemoryIngestManifest(), [DOCS_PACK]);
|
|
33
|
+
expect(plan.skipped).toContainEqual({ path: 'run.sh', reason: 'no-pack' });
|
|
34
|
+
|
|
35
|
+
const ctx: ExtractContext = { rootId: ROOT, knownKeys: new Map(), resolvePath: resolveRelativePath };
|
|
36
|
+
const text = 'See [[real]].\n\n```sh\nif [[ -f x ]]; then :; fi\n```\n\nInline `[[nope]]` too.\n';
|
|
37
|
+
const src = asPathSource({ id: 'a.md', tenantId: 't', content: { kind: 'text', text } }, 'a.md', 'h');
|
|
38
|
+
const links = markdownParser.extract!(src, markdownParser.parse(src), ctx).edges.filter((e) => e.kind === 'links');
|
|
39
|
+
expect(links).toHaveLength(1);
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
describe('regression: 88fe16a the job in hand finishes on Stop', () => {
|
|
44
|
+
it('regression: a stop that lands mid-job aborts the job signal but the job resolves with its work, it is not rejected', async () => {
|
|
45
|
+
const parent = new AbortController();
|
|
46
|
+
const withDeadline = createDeadlines(parent.signal);
|
|
47
|
+
let seen: AbortSignal | undefined;
|
|
48
|
+
let finish!: () => void;
|
|
49
|
+
const job = withDeadline(60_000, async (signal) => {
|
|
50
|
+
seen = signal;
|
|
51
|
+
await new Promise<void>((r) => { finish = r; });
|
|
52
|
+
return 'read';
|
|
53
|
+
});
|
|
54
|
+
await Promise.resolve();
|
|
55
|
+
parent.abort(new Error('stopped'));
|
|
56
|
+
await new Promise((r) => setImmediate(r));
|
|
57
|
+
expect(seen?.aborted).toBe(true); // a pool may still recycle its worker
|
|
58
|
+
finish();
|
|
59
|
+
await expect(job).resolves.toBe('read');
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
describe('regression: cd6d9f9 pool deadline', () => {
|
|
64
|
+
/** A pool that reads the file itself and takes `ms` to answer. */
|
|
65
|
+
const slowPool = (source: ReturnType<typeof memSource>, ms: number): ExtractPool => async (job) => {
|
|
66
|
+
await new Promise((r) => setTimeout(r, ms));
|
|
67
|
+
const doc = await source.read(job.path);
|
|
68
|
+
const { readByPool: _drop, ...rest } = job;
|
|
69
|
+
return extractJob({ ...rest, doc } as ExtractJob, [DOCS_PACK]);
|
|
70
|
+
};
|
|
71
|
+
/** Runs the review under fake timers, advancing the clock in steps until it settles: no real time decides the outcome. */
|
|
72
|
+
const run = async (source: ReturnType<typeof memSource>) => {
|
|
73
|
+
jest.useFakeTimers();
|
|
74
|
+
try {
|
|
75
|
+
const review = reviewDirectory(args(source, undefined, new InMemoryIngestManifest(), {
|
|
76
|
+
mechanical: true, extractPool: slowPool(source, 150), deferRead: true, timeouts: { extractMs: 30, readMs: 60_000 },
|
|
77
|
+
}));
|
|
78
|
+
let done = false;
|
|
79
|
+
review.then(() => { done = true; }, () => { done = true; });
|
|
80
|
+
for (let i = 0; i < 1_000 && !done; i++) await jest.advanceTimersByTimeAsync(10);
|
|
81
|
+
return await review;
|
|
82
|
+
} finally {
|
|
83
|
+
jest.useRealTimers();
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
it('regression: the default read timeout is NOT added to a pool job deadline (a 60 s readMs once let a stuck job hold its slot)', async () => {
|
|
88
|
+
const report = await run(memSource({ 'a.md': FILES['a.md'] }));
|
|
89
|
+
expect(report.failures).toEqual([{ path: 'a.md', phase: 'extract', reason: 'timeout' }]);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it('regression: the source read override IS added to a pool job deadline', async () => {
|
|
93
|
+
const source = memSource({ 'a.md': FILES['a.md'] });
|
|
94
|
+
source.readTimeoutMs = () => 5_000;
|
|
95
|
+
const report = await run(source);
|
|
96
|
+
expect(report.failures).toEqual([]);
|
|
97
|
+
expect(report.extracted).toBe(1);
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
describe('regression: analyzer failures', () => {
|
|
102
|
+
it('regression: a failing analyzer is recorded in report.failures (it vanished silently) and the other analyzers still store their output', async () => {
|
|
103
|
+
const out = { sourceRef: `src:${ROOT}::`, sourceHash: '~ok:1', nodes: [], edges: [], keys: [] } as unknown as Extracted;
|
|
104
|
+
const bad: KnowledgePack = { ...quietPack, analyzers: { async analyse() { throw new Error('analyzer exploded'); } } };
|
|
105
|
+
const good: KnowledgePack = { ...quietPack, id: 'good', parsers: [], analyzers: { async analyse() { return [out]; } } };
|
|
106
|
+
const store = memStore();
|
|
107
|
+
const report = await reviewDirectory(args(memSource({ ...FILES }), store, new InMemoryIngestManifest(), { judgement: fakeJudge(), packs: [bad, good] }));
|
|
108
|
+
expect(report.failures).toContainEqual({ kind: 'analyzer', path: analyzerFailurePath(quietPack.id), phase: 'analyse', reason: 'analyzer exploded' });
|
|
109
|
+
expect(await store.getExtracted('~ok:1')).toEqual([out]);
|
|
110
|
+
expect(report.aborted).toBe(false);
|
|
111
|
+
});
|
|
112
|
+
});
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/contract/regression.packWire.test.ts — a BFKP pack is untrusted client input. Bugs fixed in how the decoder reads it, each
|
|
3
|
+
* pinned by one test named `regression: <what broke>`. Packs are hand-built from the frame and section primitives and decoded
|
|
4
|
+
* through the PUBLIC `decodePack`.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { readFrame, writeFrame, writeSection } from '../knowledge/pack/frame.js';
|
|
8
|
+
import { TAG } from '../knowledge/pack/sections/index.js';
|
|
9
|
+
import { writeEdges, writeKeys, writeNodes } from '../knowledge/pack/sections/extrLists.js';
|
|
10
|
+
import { collector, tablesOf, writeHashTable, writeStringTable, type Tables } from '../knowledge/pack/strings.js';
|
|
11
|
+
import { ByteReader, ByteWriter, MAX_VARINT } from '../knowledge/pack/varint.js';
|
|
12
|
+
import {
|
|
13
|
+
decodePack, encodePack, factDigest, keyHash, PackFormatError, PackTooLargeError, relationLeafKey, rootDigestOf, ZERO_DIGEST, type Pack,
|
|
14
|
+
} from '../knowledge/pack/index.js';
|
|
15
|
+
import type { KNode, NodeRef } from '../knowledge/model.js';
|
|
16
|
+
|
|
17
|
+
const HEAD = { flags: 0, rootId: 'r', baseGeneration: 0, targetDigest: ZERO_DIGEST };
|
|
18
|
+
const H1 = 'a'.repeat(64), H2 = 'b'.repeat(64);
|
|
19
|
+
const NODE = (ref: string): KNode => ({ ref: ref as NodeRef, kind: 'file', label: 'a', pack: 'docs', importance: 0, origin: 'extracted' });
|
|
20
|
+
|
|
21
|
+
/** A frame whose body is these sections, in order, written as given. */
|
|
22
|
+
function frameOf(sections: ReadonlyArray<readonly [number, Uint8Array]>): Uint8Array {
|
|
23
|
+
const w = new ByteWriter();
|
|
24
|
+
for (const [tag, bytes] of sections) writeSection(w, tag, bytes);
|
|
25
|
+
const body = w.finish();
|
|
26
|
+
return writeFrame(HEAD, body, body);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* One EXTR hash, `kind` byte as given (0 full, 1 diff); for a diff, its node list says `positions` add positions but carries
|
|
31
|
+
* `nodes` items. `vflags` is the entry's version flag byte.
|
|
32
|
+
*/
|
|
33
|
+
function extrPack(o: { kind?: number; positions?: number; nodes?: number; vflags?: number } = {}): Uint8Array {
|
|
34
|
+
const kind = o.kind ?? 1, positions = o.positions ?? 1, nodeCount = o.nodes ?? 1, vflags = o.vflags ?? 0;
|
|
35
|
+
const nodes = Array.from({ length: nodeCount }, (_, i) => NODE(`src:r::n${i}.ts`));
|
|
36
|
+
const write = (t: Tables): Uint8Array => {
|
|
37
|
+
const w = new ByteWriter();
|
|
38
|
+
w.varint(1);
|
|
39
|
+
w.u8(kind);
|
|
40
|
+
w.varint(t.hash(H2));
|
|
41
|
+
if (kind === 1) w.varint(t.hash(H1));
|
|
42
|
+
w.varint(1);
|
|
43
|
+
w.varint(t.str('src:r::a.ts'));
|
|
44
|
+
w.varint(t.hash(H2));
|
|
45
|
+
w.u8(vflags);
|
|
46
|
+
if (vflags & 1) w.varint(2);
|
|
47
|
+
if (kind === 1) {
|
|
48
|
+
w.varint(0); w.varint(positions);
|
|
49
|
+
for (let i = 0; i < positions; i++) w.varint(i === 0 ? 0 : 1);
|
|
50
|
+
writeNodes(w, t, nodes);
|
|
51
|
+
w.varint(0); w.varint(0); writeEdges(w, t, []);
|
|
52
|
+
w.varint(0); w.varint(0); writeKeys(w, t, []);
|
|
53
|
+
} else {
|
|
54
|
+
writeNodes(w, t, nodes); writeEdges(w, t, []); writeKeys(w, t, []);
|
|
55
|
+
}
|
|
56
|
+
return w.finish();
|
|
57
|
+
};
|
|
58
|
+
const col = collector();
|
|
59
|
+
write(col);
|
|
60
|
+
const t = tablesOf(col.strings, col.hashes);
|
|
61
|
+
return frameOf([[TAG.STR, writeStringTable(t.strings)], [TAG.HASH, writeHashTable(t.hashes)], [TAG.EXTR, write(t)]]);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The body sections of a real (uncompressed) pack, so one can be altered. */
|
|
65
|
+
async function sectionsOf(pack: Pack): Promise<Array<[number, Uint8Array]>> {
|
|
66
|
+
const { stored } = readFrame(await encodePack(pack, { deflate: false }));
|
|
67
|
+
const r = new ByteReader(stored);
|
|
68
|
+
const out: Array<[number, Uint8Array]> = [];
|
|
69
|
+
while (!r.done) { const tag = r.u8(); out.push([tag, r.bytes(r.varint())]); }
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const FILES_PACK: Pack = { ...HEAD, files: [{ path: 'a.ts', hash: H1, bytes: 3 }] };
|
|
74
|
+
|
|
75
|
+
describe('regression: EXTR diff counts', () => {
|
|
76
|
+
it('regression: a well-formed diff (positions = items) still decodes', async () => {
|
|
77
|
+
const pack = await decodePack(extrPack());
|
|
78
|
+
const x = pack.extracted![0]!;
|
|
79
|
+
expect(x.kind).toBe('diff');
|
|
80
|
+
if (x.kind === 'diff') expect(x.entries[0]!.nodes.add).toEqual([{ at: 0, item: NODE('src:r::n0.ts') }]);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it('regression: more add positions than added items is malformed (it stored `undefined` items)', async () => {
|
|
84
|
+
await expect(decodePack(extrPack({ positions: 2, nodes: 1 }))).rejects.toThrow(/2 add positions but 1 added items/);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it('regression: more added items than add positions is malformed (the extras were dropped)', async () => {
|
|
88
|
+
await expect(decodePack(extrPack({ positions: 1, nodes: 2 }))).rejects.toThrow(/1 add positions but 2 added items/);
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
describe('regression: unknown flags, kinds and versions are refused', () => {
|
|
93
|
+
it('regression: an unknown frame flag bit is refused, not ignored', async () => {
|
|
94
|
+
const bytes = (await encodePack(FILES_PACK, { deflate: false })).slice();
|
|
95
|
+
bytes[5] = bytes[5]! | 0x02;
|
|
96
|
+
await expect(decodePack(bytes)).rejects.toThrow(/unknown flag bits/);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('regression: an EXTR kind byte other than full (0) or diff (1) is refused (2-255 were read as full)', async () => {
|
|
100
|
+
await expect(decodePack(extrPack({ kind: 0 }))).resolves.toBeDefined();
|
|
101
|
+
await expect(decodePack(extrPack({ kind: 2 }))).rejects.toThrow(/unknown EXTR entry kind 2/);
|
|
102
|
+
await expect(decodePack(extrPack({ kind: 255 }))).rejects.toThrow(PackFormatError);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it('regression: an unknown bit in an EXTR entry version byte is refused', async () => {
|
|
106
|
+
await expect(decodePack(extrPack({ vflags: 1 }))).resolves.toBeDefined();
|
|
107
|
+
await expect(decodePack(extrPack({ vflags: 3 }))).rejects.toThrow(/unknown flag bits/);
|
|
108
|
+
});
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
describe('regression: section framing', () => {
|
|
112
|
+
it('regression: a repeated section tag is refused (the last copy silently won)', async () => {
|
|
113
|
+
const sections = await sectionsOf(FILES_PACK);
|
|
114
|
+
const file = sections.find(([tag]) => tag === TAG.FILE)!;
|
|
115
|
+
await expect(decodePack(frameOf([...sections, file]))).rejects.toThrow(/appears twice/);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
it('regression: a section with trailing bytes is refused (it was read short and the rest ignored)', async () => {
|
|
119
|
+
const sections = await sectionsOf(FILES_PACK);
|
|
120
|
+
const padded = sections.map(([tag, b]): [number, Uint8Array] => (tag === TAG.FILE ? [tag, new Uint8Array([...b, 0])] : [tag, b]));
|
|
121
|
+
await expect(decodePack(frameOf(padded))).rejects.toThrow(/FILE section: 1 trailing bytes/);
|
|
122
|
+
const str = sections.map(([tag, b]): [number, Uint8Array] => (tag === TAG.STR ? [tag, new Uint8Array([...b, 7])] : [tag, b]));
|
|
123
|
+
await expect(decodePack(frameOf(str))).rejects.toThrow(/string table: 1 trailing bytes/);
|
|
124
|
+
await expect(decodePack(frameOf(sections))).resolves.toEqual(await decodePack(await encodePack(FILES_PACK)));
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
describe('regression: lone surrogates on the wire', () => {
|
|
129
|
+
const lone = 'dir/a\uD800.ts';
|
|
130
|
+
const wire = 'dir/a�.ts';
|
|
131
|
+
|
|
132
|
+
it('regression: a path with a lone surrogate gets the same root digest on the client and after decoding on the server', async () => {
|
|
133
|
+
const client = { files: [{ path: lone, hash: H1 }], facts: [], relations: [] };
|
|
134
|
+
const decoded = await decodePack(await encodePack({ ...HEAD, files: [{ path: lone, hash: H1, bytes: 1 }] }));
|
|
135
|
+
expect(decoded.files![0]!.path).toBe(wire);
|
|
136
|
+
const server = { files: decoded.files!.map((f) => ({ path: f.path, hash: f.hash })), facts: [], relations: [] };
|
|
137
|
+
expect(rootDigestOf('r', client)).toBe(rootDigestOf('r', server));
|
|
138
|
+
expect(keyHash(lone)).toBe(keyHash(wire));
|
|
139
|
+
expect(relationLeafKey({ from: `src:r::${lone}`, to: 'fact:x', kind: 'about' })).toBe(relationLeafKey({ from: `src:r::${wire}`, to: 'fact:x', kind: 'about' }));
|
|
140
|
+
expect(factDigest({ key: lone, content: lone, origin: 'model' })).toBe(factDigest({ key: wire, content: wire, origin: 'model' }));
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it('regression: a well-formed key (including a real surrogate pair) hashes exactly as before', () => {
|
|
144
|
+
const fnvUtf16 = (k: string) => { let h = 0x811c9dc5; for (let i = 0; i < k.length; i++) { h ^= k.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; } return h >>> 0; };
|
|
145
|
+
for (const k of ['f:src/a.ts', 'a:claim:日本語', 'f:emoji😀.md', '']) expect(keyHash(k)).toBe(fnvUtf16(k));
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
describe('regression: canonical varints', () => {
|
|
150
|
+
const read = (bytes: number[]) => new ByteReader(new Uint8Array(bytes)).varint();
|
|
151
|
+
|
|
152
|
+
it('regression: an overlong (non-canonical) varint is malformed', () => {
|
|
153
|
+
expect(() => read([0x80, 0x00])).toThrow(/non-canonical/);
|
|
154
|
+
expect(() => read([0x81, 0x80, 0x00])).toThrow(/non-canonical/);
|
|
155
|
+
expect(read([0x00])).toBe(0);
|
|
156
|
+
expect(read([0x80, 0x01])).toBe(128);
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it('regression: a varint past Number.MAX_SAFE_INTEGER is malformed, and MAX_SAFE_INTEGER itself round-trips', () => {
|
|
160
|
+
expect(() => read([0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f])).toThrow(/safe integer/);
|
|
161
|
+
expect(() => read([0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x10])).toThrow(/safe integer/); // exactly 2^53
|
|
162
|
+
const w = new ByteWriter();
|
|
163
|
+
w.varint(MAX_VARINT);
|
|
164
|
+
expect(new ByteReader(w.finish()).varint()).toBe(Number.MAX_SAFE_INTEGER);
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
it('regression: a string table suffix longer than the section is malformed (422), not "too large" (413)', async () => {
|
|
168
|
+
const w = new ByteWriter();
|
|
169
|
+
w.varint(1); w.varint(0); w.varint(10_000_000); w.u8(0x61);
|
|
170
|
+
const err = await decodePack(frameOf([[TAG.STR, w.finish()]]), { maxDecodedBytes: 1024 * 1024 }).catch((e: unknown) => e);
|
|
171
|
+
expect(err).toBeInstanceOf(PackFormatError);
|
|
172
|
+
expect(err).not.toBeInstanceOf(PackTooLargeError);
|
|
173
|
+
});
|
|
174
|
+
});
|
|
@@ -51,7 +51,7 @@ export type ReviewReport_counters = Expect<Equal<
|
|
|
51
51
|
Pick<ReviewReport, 'extracted' | 'judged' | 'unjudged' | 'readErrors' | 'extractErrors' | 'aborted' | 'digest' | 'durationMs'>,
|
|
52
52
|
{ extracted: number; judged: number; unjudged: number; readErrors: number; extractErrors: number; aborted: boolean; digest: string; durationMs: number }
|
|
53
53
|
>>;
|
|
54
|
-
export type ReviewFailure_shape = Expect<Equal<ReviewFailure, { path: string; phase: ReviewPhase; reason: string }>>;
|
|
54
|
+
export type ReviewFailure_shape = Expect<Equal<ReviewFailure, { path: string; phase: ReviewPhase; reason: string; kind?: 'file' | 'analyzer' }>>;
|
|
55
55
|
|
|
56
56
|
/* ── ReviewRun: failures are CHUNKS, read through failuresOf / failureTotal ─────────────────────────────────── */
|
|
57
57
|
export type ReviewRun_failures_are_chunks = Expect<Equal<ReviewRun['failures'], readonly (readonly ReviewFailure[])[]>>;
|
|
@@ -187,6 +187,7 @@ export type RowPersistence_ports = Expect<Equal<RowPersistence, {
|
|
|
187
187
|
apply(change: RowChange): Promise<{ generation: number; reloaded?: KnowledgeSnapshot }>;
|
|
188
188
|
loadAllExtracted?(): Promise<Record<string, Extracted[]>>;
|
|
189
189
|
loadExtracted?(hash: string): Promise<Extracted[] | undefined>;
|
|
190
|
+
extractedSources?(): Promise<Record<string, string[]>>;
|
|
190
191
|
changedElsewhere?(): Promise<boolean>;
|
|
191
192
|
}>>;
|
|
192
193
|
export type SnapshotPersistence_ports = Expect<Equal<
|
|
@@ -1,20 +1,27 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* knowledge/pack/frame.ts — the BFKP v1 frame (PRD 41 A11):
|
|
3
3
|
*
|
|
4
|
-
* magic "BFKP" · version u8 · flags u8 (bit 0 = body deflated) · rootId · baseGeneration varint ·
|
|
4
|
+
* magic "BFKP" · version u8 · flags u8 (bit 0 = body deflated; any other bit is refused) · rootId · baseGeneration varint ·
|
|
5
5
|
* targetDigest (32 raw bytes) · body · trailer: CRC-32 (u32 LE) of the DECODED body
|
|
6
6
|
*
|
|
7
|
-
* The body is sections `{ tag u8, length varint, bytes }`; an unknown tag is skipped
|
|
7
|
+
* The body is sections `{ tag u8, length varint, bytes }`; an unknown tag is skipped, a repeated tag is refused, and a known
|
|
8
|
+
* section must be read to its last byte.
|
|
9
|
+
*
|
|
10
|
+
* EVOLVING THE FORMAT: known sections are CLOSED. A reader refuses trailing bytes in a known section and any flag bit, kind or
|
|
11
|
+
* version byte it does not know, so a writer can never append a field to an existing section or set a new bit in it. A new field
|
|
12
|
+
* goes in a NEW section tag (older readers skip it); a change to how the body itself is read (a new compression) is a new frame
|
|
13
|
+
* VERSION. A new value in an existing closed vocabulary needs every reader upgraded first.
|
|
8
14
|
* Also: the multi-part split a large pack travels in.
|
|
9
15
|
*/
|
|
10
16
|
|
|
11
17
|
import { crc32 } from './crc32.js';
|
|
12
18
|
import { fromHex64, HEX64, toHex } from './hex.js';
|
|
13
|
-
import { ByteReader, ByteWriter, PackFormatError } from './varint.js';
|
|
19
|
+
import { assertFlagsKnown, ByteReader, ByteWriter, PackFormatError } from './varint.js';
|
|
14
20
|
|
|
15
21
|
export const MAGIC = [0x42, 0x46, 0x4b, 0x50] as const; // "BFKP"
|
|
16
22
|
export const VERSION = 1;
|
|
17
23
|
export const FLAG_DEFLATED = 1;
|
|
24
|
+
const KNOWN_FLAGS = FLAG_DEFLATED;
|
|
18
25
|
export const KPACK_CONTENT_TYPE = 'application/vnd.builderforce.kpack';
|
|
19
26
|
/** A compressed pack larger than this travels as several parts. */
|
|
20
27
|
export const MAX_PART_BYTES = 8 * 1024 * 1024;
|
|
@@ -51,6 +58,8 @@ export function readHeader(bytes: Uint8Array): { header: FrameHeader; headerByte
|
|
|
51
58
|
const version = r.u8();
|
|
52
59
|
if (version !== VERSION) throw new PackFormatError(`unsupported BFKP version ${version}`);
|
|
53
60
|
const flags = r.u8();
|
|
61
|
+
// A flag this reader does not know changes how the body must be read (a new compression, say): refuse, never guess.
|
|
62
|
+
assertFlagsKnown(flags, KNOWN_FLAGS);
|
|
54
63
|
const rootId = r.str();
|
|
55
64
|
const baseGeneration = r.varint();
|
|
56
65
|
const targetDigest = toHex(r.bytes(32));
|
|
@@ -98,11 +107,18 @@ export function writeSection(w: ByteWriter, tag: number, bytes: Uint8Array): voi
|
|
|
98
107
|
w.bytes(bytes);
|
|
99
108
|
}
|
|
100
109
|
|
|
101
|
-
/**
|
|
110
|
+
/**
|
|
111
|
+
* The sections of a decoded body by tag; unknown tags are returned too, for the caller to skip. A tag that appears twice is a
|
|
112
|
+
* malformed pack: which copy wins would be a guess, and the writer never repeats one.
|
|
113
|
+
*/
|
|
102
114
|
export function readSections(body: Uint8Array): Map<number, Uint8Array> {
|
|
103
115
|
const r = new ByteReader(body);
|
|
104
116
|
const out = new Map<number, Uint8Array>();
|
|
105
|
-
while (!r.done) {
|
|
117
|
+
while (!r.done) {
|
|
118
|
+
const tag = r.u8();
|
|
119
|
+
if (out.has(tag)) throw new PackFormatError(`section tag ${tag} appears twice`);
|
|
120
|
+
out.set(tag, r.bytes(r.varint()));
|
|
121
|
+
}
|
|
106
122
|
return out;
|
|
107
123
|
}
|
|
108
124
|
|
|
@@ -13,13 +13,19 @@
|
|
|
13
13
|
|
|
14
14
|
import { sha256Hex } from '../../retrieval/knowledge-index/sha256.js';
|
|
15
15
|
import type { ManifestLeaf, StoredFact, StoredRelation } from './types.js';
|
|
16
|
+
import { wireString } from './varint.js';
|
|
16
17
|
|
|
17
18
|
export const MANIFEST_BUCKETS = 4096;
|
|
18
19
|
|
|
19
|
-
/**
|
|
20
|
+
/**
|
|
21
|
+
* FNV-1a (32-bit) over the UTF-16 code units of the key's WIRE form ({@link wireString}): stable across runtimes and
|
|
22
|
+
* releases. A key holding a lone surrogate (a legal Windows path) reaches the other side as U+FFFD, so it is hashed as
|
|
23
|
+
* U+FFFD here too, or the two sides would bucket it differently and never agree. A well-formed key hashes as before.
|
|
24
|
+
*/
|
|
20
25
|
export function keyHash(key: string): number {
|
|
26
|
+
const k = wireString(key);
|
|
21
27
|
let h = 0x811c9dc5;
|
|
22
|
-
for (let i = 0; i <
|
|
28
|
+
for (let i = 0; i < k.length; i++) { h ^= k.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; }
|
|
23
29
|
return h >>> 0;
|
|
24
30
|
}
|
|
25
31
|
|
|
@@ -36,6 +42,8 @@ export interface ManifestTree {
|
|
|
36
42
|
}
|
|
37
43
|
|
|
38
44
|
const cmp = (a: ManifestLeaf, b: ManifestLeaf): number => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
|
|
45
|
+
/** A leaf as the other side decodes it (see {@link wireString}): equal leaves sort, bucket and digest the same on both. */
|
|
46
|
+
const wireLeaf = (l: ManifestLeaf): ManifestLeaf => { const key = wireString(l.key); return key === l.key ? l : { ...l, key }; };
|
|
39
47
|
|
|
40
48
|
/**
|
|
41
49
|
* The digest of ONE bucket: the hash of its leaves sorted by key (an empty bucket has a fixed digest). The server keeps
|
|
@@ -43,7 +51,7 @@ const cmp = (a: ManifestLeaf, b: ManifestLeaf): number => (a.key < b.key ? -1 :
|
|
|
43
51
|
*/
|
|
44
52
|
export function bucketDigest(leaves: readonly ManifestLeaf[]): string {
|
|
45
53
|
if (leaves.length === 0) return EMPTY_BUCKET;
|
|
46
|
-
return sha256Hex(
|
|
54
|
+
return sha256Hex(leaves.map(wireLeaf).sort(cmp).map((l) => `${l.key}\u0000${l.digest}\n`).join(''));
|
|
47
55
|
}
|
|
48
56
|
|
|
49
57
|
/** The root digest from the `MANIFEST_BUCKETS` bucket digests (hex), in bucket order. */
|
|
@@ -54,7 +62,8 @@ export function rootDigestOfBuckets(digests: readonly string[]): string {
|
|
|
54
62
|
|
|
55
63
|
export function manifestTree(leaves: readonly ManifestLeaf[]): ManifestTree {
|
|
56
64
|
const grouped = new Map<number, ManifestLeaf[]>();
|
|
57
|
-
for (const
|
|
65
|
+
for (const l0 of leaves) {
|
|
66
|
+
const l = wireLeaf(l0);
|
|
58
67
|
const b = bucketOf(l.key);
|
|
59
68
|
const list = grouped.get(b);
|
|
60
69
|
if (list) list.push(l); else grouped.set(b, [l]);
|
|
@@ -75,19 +84,25 @@ export function differingBuckets(a: readonly string[], b: readonly string[]): nu
|
|
|
75
84
|
return out;
|
|
76
85
|
}
|
|
77
86
|
|
|
78
|
-
/**
|
|
87
|
+
/**
|
|
88
|
+
* A source's leaf key: its path, or `~tag|path` for a root-level output (the blob store's own source identity). Every leaf
|
|
89
|
+
* key and digest input is taken in its wire form ({@link wireString}), so a lone surrogate means the same on both sides.
|
|
90
|
+
*/
|
|
79
91
|
export function fileLeafKey(path: string, hash: string): string {
|
|
80
|
-
|
|
92
|
+
const p = wireString(path);
|
|
93
|
+
if (!hash.startsWith('~')) return `f:${p}`;
|
|
81
94
|
const colon = hash.indexOf(':');
|
|
82
|
-
return `f:${colon > 0 ? hash.slice(0, colon) : hash}|${
|
|
95
|
+
return `f:${colon > 0 ? hash.slice(0, colon) : hash}|${p}`;
|
|
83
96
|
}
|
|
84
97
|
|
|
85
|
-
export const factLeafKey = (key: string): string => `a:${key}`;
|
|
98
|
+
export const factLeafKey = (key: string): string => `a:${wireString(key)}`;
|
|
86
99
|
/**
|
|
87
100
|
* A relation's leaf key: `r:` + the JSON array `[from, to, kind]`. Printable and unambiguous: Postgres `text` and
|
|
88
|
-
* `jsonb` reject NUL, which the earlier `from␀to␀kind` form contained.
|
|
101
|
+
* `jsonb` reject NUL, which the earlier `from␀to␀kind` form contained. (JSON.stringify would escape a lone surrogate as
|
|
102
|
+
* `\udXXX` text, which the decoded U+FFFD on the other side never equals: the parts are taken in wire form first.)
|
|
89
103
|
*/
|
|
90
|
-
export const relationLeafKey = (r: { from: string; to: string; kind: string }): string =>
|
|
104
|
+
export const relationLeafKey = (r: { from: string; to: string; kind: string }): string =>
|
|
105
|
+
`r:${JSON.stringify([wireString(r.from), wireString(r.to), wireString(r.kind)])}`;
|
|
91
106
|
|
|
92
107
|
/** The inverse of {@link relationLeafKey}; null when `key` is not a relation leaf key. The ONE parser. */
|
|
93
108
|
export function parseRelationLeafKey(key: string): { from: string; to: string; kind: string } | null {
|
|
@@ -102,7 +117,7 @@ export function parseRelationLeafKey(key: string): { from: string; to: string; k
|
|
|
102
117
|
}
|
|
103
118
|
|
|
104
119
|
/** The digest of what a fact says: its key, text and provenance kind. Importance and timestamps are the server's to score. */
|
|
105
|
-
export const factDigest = (f: Pick<StoredFact, 'key' | 'content' | 'origin'>): string => sha256Hex(JSON.stringify([f.key, f.content, f.origin]));
|
|
120
|
+
export const factDigest = (f: Pick<StoredFact, 'key' | 'content' | 'origin'>): string => sha256Hex(JSON.stringify([wireString(f.key), wireString(f.content), f.origin]));
|
|
106
121
|
|
|
107
122
|
export const relationDigest = (r: Pick<StoredRelation, 'weight' | 'origin' | 'confidence' | 'sourceHash'>): string =>
|
|
108
123
|
sha256Hex(`${r.weight.toFixed(3)}|${r.origin}|${r.confidence === undefined ? '' : r.confidence.toFixed(3)}|${r.sourceHash ?? ''}`);
|