@seanhogg/builderforce-memory 2026.10.45 → 2026.10.47
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -0
- package/dist/knowledge/build.d.ts.map +1 -1
- package/dist/knowledge/build.js +13 -7
- package/dist/knowledge/build.js.map +1 -1
- package/dist/knowledge/extractFile.d.ts +9 -1
- package/dist/knowledge/extractFile.d.ts.map +1 -1
- package/dist/knowledge/extractFile.js +25 -5
- package/dist/knowledge/extractFile.js.map +1 -1
- package/dist/knowledge/extractJob.d.ts +30 -5
- package/dist/knowledge/extractJob.d.ts.map +1 -1
- package/dist/knowledge/extractJob.js +9 -1
- package/dist/knowledge/extractJob.js.map +1 -1
- package/dist/knowledge/index.d.ts +5 -3
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +2 -1
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge/jobDeadline.d.ts +17 -0
- package/dist/knowledge/jobDeadline.d.ts.map +1 -0
- package/dist/knowledge/jobDeadline.js +46 -0
- package/dist/knowledge/jobDeadline.js.map +1 -0
- package/dist/knowledge/judgeCalls.d.ts +16 -0
- package/dist/knowledge/judgeCalls.d.ts.map +1 -1
- package/dist/knowledge/judgeCalls.js +20 -1
- package/dist/knowledge/judgeCalls.js.map +1 -1
- package/dist/knowledge/judgePriority.d.ts +22 -0
- package/dist/knowledge/judgePriority.d.ts.map +1 -0
- package/dist/knowledge/judgePriority.js +28 -0
- package/dist/knowledge/judgePriority.js.map +1 -0
- package/dist/knowledge/pack/crc32.d.ts +7 -0
- package/dist/knowledge/pack/crc32.d.ts.map +1 -0
- package/dist/knowledge/pack/crc32.js +22 -0
- package/dist/knowledge/pack/crc32.js.map +1 -0
- package/dist/knowledge/pack/decode.d.ts +14 -0
- package/dist/knowledge/pack/decode.d.ts.map +1 -0
- package/dist/knowledge/pack/decode.js +66 -0
- package/dist/knowledge/pack/decode.js.map +1 -0
- package/dist/knowledge/pack/deflate.d.ts +9 -0
- package/dist/knowledge/pack/deflate.d.ts.map +1 -0
- package/dist/knowledge/pack/deflate.js +45 -0
- package/dist/knowledge/pack/deflate.js.map +1 -0
- package/dist/knowledge/pack/encode.d.ts +26 -0
- package/dist/knowledge/pack/encode.d.ts.map +1 -0
- package/dist/knowledge/pack/encode.js +86 -0
- package/dist/knowledge/pack/encode.js.map +1 -0
- package/dist/knowledge/pack/extrDiff.d.ts +26 -0
- package/dist/knowledge/pack/extrDiff.d.ts.map +1 -0
- package/dist/knowledge/pack/extrDiff.js +129 -0
- package/dist/knowledge/pack/extrDiff.js.map +1 -0
- package/dist/knowledge/pack/frame.d.ts +45 -0
- package/dist/knowledge/pack/frame.d.ts.map +1 -0
- package/dist/knowledge/pack/frame.js +101 -0
- package/dist/knowledge/pack/frame.js.map +1 -0
- package/dist/knowledge/pack/hex.d.ts +7 -0
- package/dist/knowledge/pack/hex.d.ts.map +1 -0
- package/dist/knowledge/pack/hex.js +17 -0
- package/dist/knowledge/pack/hex.js.map +1 -0
- package/dist/knowledge/pack/index.d.ts +19 -0
- package/dist/knowledge/pack/index.d.ts.map +1 -0
- package/dist/knowledge/pack/index.js +17 -0
- package/dist/knowledge/pack/index.js.map +1 -0
- package/dist/knowledge/pack/jsonSize.d.ts +5 -0
- package/dist/knowledge/pack/jsonSize.d.ts.map +1 -0
- package/dist/knowledge/pack/jsonSize.js +8 -0
- package/dist/knowledge/pack/jsonSize.js.map +1 -0
- package/dist/knowledge/pack/manifest.d.ts +66 -0
- package/dist/knowledge/pack/manifest.d.ts.map +1 -0
- package/dist/knowledge/pack/manifest.js +104 -0
- package/dist/knowledge/pack/manifest.js.map +1 -0
- package/dist/knowledge/pack/sections/columns.d.ts +32 -0
- package/dist/knowledge/pack/sections/columns.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/columns.js +53 -0
- package/dist/knowledge/pack/sections/columns.js.map +1 -0
- package/dist/knowledge/pack/sections/extr.d.ts +8 -0
- package/dist/knowledge/pack/sections/extr.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/extr.js +99 -0
- package/dist/knowledge/pack/sections/extr.js.map +1 -0
- package/dist/knowledge/pack/sections/extrLists.d.ts +23 -0
- package/dist/knowledge/pack/sections/extrLists.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/extrLists.js +200 -0
- package/dist/knowledge/pack/sections/extrLists.js.map +1 -0
- package/dist/knowledge/pack/sections/facts.d.ts +8 -0
- package/dist/knowledge/pack/sections/facts.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/facts.js +172 -0
- package/dist/knowledge/pack/sections/facts.js.map +1 -0
- package/dist/knowledge/pack/sections/index.d.ts +6 -0
- package/dist/knowledge/pack/sections/index.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/index.js +9 -0
- package/dist/knowledge/pack/sections/index.js.map +1 -0
- package/dist/knowledge/pack/sections/rows.d.ts +31 -0
- package/dist/knowledge/pack/sections/rows.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/rows.js +227 -0
- package/dist/knowledge/pack/sections/rows.js.map +1 -0
- package/dist/knowledge/pack/strings.d.ts +43 -0
- package/dist/knowledge/pack/strings.d.ts.map +1 -0
- package/dist/knowledge/pack/strings.js +117 -0
- package/dist/knowledge/pack/strings.js.map +1 -0
- package/dist/knowledge/pack/types.d.ts +118 -0
- package/dist/knowledge/pack/types.d.ts.map +1 -0
- package/dist/knowledge/pack/types.js +17 -0
- package/dist/knowledge/pack/types.js.map +1 -0
- package/dist/knowledge/pack/varint.d.ts +57 -0
- package/dist/knowledge/pack/varint.d.ts.map +1 -0
- package/dist/knowledge/pack/varint.js +145 -0
- package/dist/knowledge/pack/varint.js.map +1 -0
- package/dist/knowledge/partitions.d.ts +1 -1
- package/dist/knowledge/partitions.d.ts.map +1 -1
- package/dist/knowledge/partitions.js +6 -1
- package/dist/knowledge/partitions.js.map +1 -1
- package/dist/knowledge/review.d.ts.map +1 -1
- package/dist/knowledge/review.js +58 -16
- package/dist/knowledge/review.js.map +1 -1
- package/dist/knowledge/reviewJudge.d.ts +8 -1
- package/dist/knowledge/reviewJudge.d.ts.map +1 -1
- package/dist/knowledge/reviewJudge.js +14 -8
- package/dist/knowledge/reviewJudge.js.map +1 -1
- package/dist/knowledge/reviewModel.d.ts +41 -1
- package/dist/knowledge/reviewModel.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.d.ts +10 -2
- package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.js +60 -25
- package/dist/knowledge/reviewPrefetch.js.map +1 -1
- package/dist/knowledge/reviewRun.d.ts +15 -3
- package/dist/knowledge/reviewRun.d.ts.map +1 -1
- package/dist/knowledge/reviewRun.js +19 -2
- package/dist/knowledge/reviewRun.js.map +1 -1
- package/dist/knowledge/reviewRunModel.d.ts +8 -1
- package/dist/knowledge/reviewRunModel.d.ts.map +1 -1
- package/dist/knowledge/reviewRunModel.js.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.d.ts +72 -6
- package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.js +279 -75
- package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
- package/package.json +8 -3
- package/src/contract/dist.contract.test.ts +44 -0
- package/src/contract/exports.contract.test.ts +90 -0
- package/src/contract/exports.snapshot.json +605 -0
- package/src/contract/pack.contract.test.ts +31 -0
- package/src/contract/regression.review.test.ts +236 -0
- package/src/contract/regression.store.test.ts +84 -0
- package/src/contract/types.contract.test.ts +183 -0
- package/src/knowledge/build.ts +11 -5
- package/src/knowledge/extractFile.ts +28 -6
- package/src/knowledge/extractJob.ts +26 -7
- package/src/knowledge/index.ts +5 -3
- package/src/knowledge/jobDeadline.ts +43 -0
- package/src/knowledge/judgeCalls.ts +19 -2
- package/src/knowledge/judgePriority.ts +36 -0
- package/src/knowledge/pack/crc32.ts +21 -0
- package/src/knowledge/pack/decode.ts +60 -0
- package/src/knowledge/pack/deflate.ts +43 -0
- package/src/knowledge/pack/encode.ts +89 -0
- package/src/knowledge/pack/extrDiff.ts +116 -0
- package/src/knowledge/pack/frame.ts +94 -0
- package/src/knowledge/pack/hex.ts +17 -0
- package/src/knowledge/pack/index.ts +26 -0
- package/src/knowledge/pack/jsonSize.ts +11 -0
- package/src/knowledge/pack/manifest.ts +128 -0
- package/src/knowledge/pack/pack.guards.test.ts +109 -0
- package/src/knowledge/pack/pack.reconcile.test.ts +96 -0
- package/src/knowledge/pack/pack.roundtrip.test.ts +50 -0
- package/src/knowledge/pack/pack.size.test.ts +22 -0
- package/src/knowledge/pack/pack.testkit.test-util.ts +90 -0
- package/src/knowledge/pack/sections/columns.ts +61 -0
- package/src/knowledge/pack/sections/extr.ts +90 -0
- package/src/knowledge/pack/sections/extrLists.ts +151 -0
- package/src/knowledge/pack/sections/facts.ts +126 -0
- package/src/knowledge/pack/sections/index.ts +13 -0
- package/src/knowledge/pack/sections/rows.ts +184 -0
- package/src/knowledge/pack/strings.ts +126 -0
- package/src/knowledge/pack/types.ts +97 -0
- package/src/knowledge/pack/varint.ts +145 -0
- package/src/knowledge/partitions.test.ts +4 -0
- package/src/knowledge/partitions.ts +3 -1
- package/src/knowledge/review.throughput.test.ts +122 -0
- package/src/knowledge/review.ts +54 -16
- package/src/knowledge/review.twoPass.test.ts +224 -0
- package/src/knowledge/reviewJudge.ts +19 -8
- package/src/knowledge/reviewModel.ts +38 -1
- package/src/knowledge/reviewPrefetch.ts +60 -24
- package/src/knowledge/reviewRun.test.ts +20 -3
- package/src/knowledge/reviewRun.ts +33 -6
- package/src/knowledge/reviewRunModel.ts +4 -1
- package/src/knowledge/stores/localSnapshotStore.batched.test.ts +25 -3
- package/src/knowledge/stores/localSnapshotStore.extractedLog.test.ts +280 -0
- package/src/knowledge/stores/localSnapshotStore.ts +283 -76
- package/src/knowledge/systems.test.ts +12 -0
- package/src/knowledge/testkit.test-util.ts +13 -2
|
@@ -8,10 +8,10 @@
|
|
|
8
8
|
|
|
9
9
|
import type { ParsedSection, SourceDocument } from '../ingest/types.js';
|
|
10
10
|
import type { Extracted, KnowledgePack, KnowledgeParser, KnowledgeStore, NodeRef } from './model.js';
|
|
11
|
-
import { jobOf, runExtractor, type ExtractPool } from './extractJob.js';
|
|
11
|
+
import { BinaryContent, jobOf, runExtractor, type ExtractPool } from './extractJob.js';
|
|
12
12
|
import { srcRef } from './refs.js';
|
|
13
13
|
import { entityName, knownKeysOf, resolveEntities } from './resolve.js';
|
|
14
|
-
import { asPathSource, composePacks, EXTRACTOR_VERSION, resolveRelativePath, type ComposedPacks } from './sources.js';
|
|
14
|
+
import { asPathSource, composePacks, EXTRACTOR_VERSION, resolveRelativePath, stubSource, type ComposedPacks } from './sources.js';
|
|
15
15
|
|
|
16
16
|
/** The normalized entity keys of `ent:` fact keys, for `mentions`. */
|
|
17
17
|
export function knownKeysOfEntities(keys: Iterable<string>): ReadonlyMap<string, NodeRef> {
|
|
@@ -24,7 +24,8 @@ export interface ExtractFileArgs {
|
|
|
24
24
|
path: string;
|
|
25
25
|
/** Content hash of the file (the extracted cache's key). */
|
|
26
26
|
hash: string;
|
|
27
|
-
|
|
27
|
+
/** The document as read; absent with `readByPool` (the pool reads the file itself). */
|
|
28
|
+
doc?: SourceDocument;
|
|
28
29
|
packs: readonly KnowledgePack[];
|
|
29
30
|
store: KnowledgeStore;
|
|
30
31
|
/** Already composed from `packs` (a review composes once). */
|
|
@@ -39,6 +40,10 @@ export interface ExtractFileArgs {
|
|
|
39
40
|
signal?: AbortSignal;
|
|
40
41
|
/** With a `pool`: whether the file's pack judges it, i.e. the worker must return its sections (default: never). */
|
|
41
42
|
wantsSections?: (pack: KnowledgePack) => boolean;
|
|
43
|
+
/** The pool reads the file itself: no `doc` (see `ExtractJob.readByPool`). */
|
|
44
|
+
readByPool?: boolean;
|
|
45
|
+
/** Told where the time went: the cache lookup and the pool job (PRD 41 A10, so a stall names itself). */
|
|
46
|
+
onTiming?: (t: { lookupMs: number; poolMs: number }) => void;
|
|
42
47
|
/** Leave the extract cache write to the caller (the review writes it in plan order); default: write it. */
|
|
43
48
|
writeCache?: boolean;
|
|
44
49
|
}
|
|
@@ -53,6 +58,11 @@ export interface FileExtraction {
|
|
|
53
58
|
cached: boolean;
|
|
54
59
|
}
|
|
55
60
|
|
|
61
|
+
/** How the file reaches the pool: its document, or `readByPool` when the pool reads it. */
|
|
62
|
+
function jobSource(a: ExtractFileArgs): { doc: SourceDocument; readByPool?: false } | { doc?: undefined; readByPool: true } {
|
|
63
|
+
return a.readByPool || !a.doc ? { readByPool: true } : { doc: a.doc };
|
|
64
|
+
}
|
|
65
|
+
|
|
56
66
|
/** Adds `extracted` to the content-hash cache, keeping the entries of the other files that share the hash. */
|
|
57
67
|
export async function putExtract(store: KnowledgeStore, hash: string, extracted: Extracted, prior?: readonly Extracted[]): Promise<void> {
|
|
58
68
|
const cached = prior ?? (await store.getExtracted?.(hash)) ?? [];
|
|
@@ -61,32 +71,44 @@ export async function putExtract(store: KnowledgeStore, hash: string, extracted:
|
|
|
61
71
|
|
|
62
72
|
/** Extraction plus what produced it; undefined when no pack's parser accepts the file. */
|
|
63
73
|
export async function extractFileDetailed(a: ExtractFileArgs): Promise<FileExtraction | undefined> {
|
|
64
|
-
|
|
74
|
+
// Pack resolution needs only the path and media type, so a file the pool reads is resolved from a content-free key.
|
|
75
|
+
const src = asPathSource(a.doc ?? stubSource(a.path), a.path, a.hash);
|
|
65
76
|
const hit = (a.composed ?? composePacks(a.packs)).resolve(src);
|
|
66
77
|
if (!hit) return undefined;
|
|
78
|
+
if (!a.doc && !a.pool) throw new Error(`extractFile: ${a.path} has no document and no pool to read it`);
|
|
67
79
|
const ref = srcRef(a.rootId, a.path);
|
|
68
80
|
// With a pool the main thread never parses: the worker returns the sections when the file will be judged.
|
|
69
81
|
const wants = !!a.pool && !!a.wantsSections?.(hit.pack);
|
|
70
82
|
let sections: ParsedSection[] = a.pool ? [] : hit.parser.parse(src);
|
|
83
|
+
const tLookup = Date.now();
|
|
71
84
|
const cached = await a.store.getExtracted?.(a.hash);
|
|
85
|
+
const lookupMs = Date.now() - tLookup;
|
|
72
86
|
// A cached entry of another extractor version is ignored: its output may differ from today's.
|
|
73
87
|
const found = cached?.find((e) => e.sourceRef === ref && e.extractorVersion === EXTRACTOR_VERSION);
|
|
74
88
|
if (found) {
|
|
89
|
+
const tSections = Date.now();
|
|
75
90
|
if (a.pool && wants) {
|
|
76
|
-
const out = await a.pool(jobOf({ rootId: a.rootId, path: a.path, hash: a.hash,
|
|
91
|
+
const out = await a.pool(jobOf({ rootId: a.rootId, path: a.path, hash: a.hash, knownKeys: new Map(), sectionsOnly: true, ...jobSource(a) }), a.signal);
|
|
92
|
+
if (out.binary) throw new BinaryContent();
|
|
77
93
|
if (!out.sections) throw new Error(`extract pool returned no sections for ${a.path}`);
|
|
78
94
|
sections = out.sections;
|
|
79
95
|
}
|
|
96
|
+
a.onTiming?.({ lookupMs, poolMs: Date.now() - tSections });
|
|
80
97
|
return { extracted: found, parser: hit.parser, pack: hit.pack, sections, cached: true };
|
|
81
98
|
}
|
|
82
99
|
|
|
83
100
|
const knownKeys = a.knownKeys ?? knownKeysOfEntities((await a.store.facts({ rootId: a.rootId })).map((f) => f.key));
|
|
84
101
|
let extracted: Extracted;
|
|
85
102
|
if (a.pool) {
|
|
86
|
-
const
|
|
103
|
+
const tPool = Date.now();
|
|
104
|
+
const out = await a.pool(jobOf({ rootId: a.rootId, path: a.path, hash: a.hash, knownKeys, needSections: wants, ...jobSource(a) }), a.signal);
|
|
105
|
+
a.onTiming?.({ lookupMs, poolMs: Date.now() - tPool });
|
|
106
|
+
if (out.binary) throw new BinaryContent();
|
|
87
107
|
// Exact match only: a result for another file, or none although the packs accept this one, is a failure.
|
|
88
108
|
const mine = out.extracted.find((e) => e.sourceRef === ref);
|
|
89
109
|
if (!mine) throw new Error(`extract pool returned no extract for ${a.path}`);
|
|
110
|
+
// The pool read other bytes than the plan hashed: nothing is stored under the planned hash.
|
|
111
|
+
if (mine.sourceHash !== a.hash) throw new Error('changed since plan');
|
|
90
112
|
if (wants) {
|
|
91
113
|
if (!out.sections) throw new Error(`extract pool returned no sections for ${a.path}`);
|
|
92
114
|
sections = out.sections;
|
|
@@ -15,14 +15,13 @@ import { basenameOf, srcRef } from './refs.js';
|
|
|
15
15
|
import { asPathSource, composePacks, EXTRACTOR_VERSION, resolveRelativePath, type ComposedPacks } from './sources.js';
|
|
16
16
|
|
|
17
17
|
/** Everything the extractor needs for one file, as structured-cloneable data. */
|
|
18
|
-
|
|
18
|
+
/** What every job carries, whichever way the file reaches the worker. */
|
|
19
|
+
export interface ExtractJobBase {
|
|
19
20
|
rootId: string;
|
|
20
21
|
/** Root-relative path. */
|
|
21
22
|
path: string;
|
|
22
23
|
/** Content hash of the file. */
|
|
23
24
|
hash: string;
|
|
24
|
-
/** The document as read (plain data). */
|
|
25
|
-
doc: SourceDocument;
|
|
26
25
|
/** The known entity keys (`mentions`), as entries of the review's map. */
|
|
27
26
|
knownKeys: ReadonlyArray<readonly [string, NodeRef]>;
|
|
28
27
|
/** The file will be judged: return its parsed sections too (the main thread never parses when a pool is supplied). */
|
|
@@ -31,8 +30,25 @@ export interface ExtractJob {
|
|
|
31
30
|
sectionsOnly?: boolean;
|
|
32
31
|
}
|
|
33
32
|
|
|
33
|
+
/**
|
|
34
|
+
* How the file reaches the worker (PRD 41 A10 rule 8): `doc` is the document the review read (plain data); `readByPool` says the
|
|
35
|
+
* worker reads and binary-checks `path` itself at the planned `hash` — no stand-in document, no text copied across the thread.
|
|
36
|
+
*/
|
|
37
|
+
export type ExtractJobSource =
|
|
38
|
+
| { doc: SourceDocument; readByPool?: never }
|
|
39
|
+
| { doc?: never; readByPool: { path: string; hash: string } };
|
|
40
|
+
|
|
41
|
+
export type ExtractJob = ExtractJobBase & ExtractJobSource;
|
|
42
|
+
|
|
43
|
+
/** Thrown by the extract stage when the pool found the file binary; the review records a `skipped` step. */
|
|
44
|
+
export class BinaryContent extends Error {
|
|
45
|
+
constructor() { super('binary'); this.name = 'BinaryContent'; }
|
|
46
|
+
}
|
|
47
|
+
|
|
34
48
|
/** What a worker returns: the file's extract(s) — `[]` when no pack accepts it — and, if asked, its sections. */
|
|
35
49
|
export interface ExtractJobResult {
|
|
50
|
+
/** The pool read the file itself (see `ExtractJob.readByPool`) and found it binary: nothing was extracted. */
|
|
51
|
+
binary?: true;
|
|
36
52
|
extracted: Extracted[];
|
|
37
53
|
sections?: ParsedSection[];
|
|
38
54
|
}
|
|
@@ -64,14 +80,15 @@ export function runExtractor(
|
|
|
64
80
|
/** The job as a serializable value for `doc` (what a pool receives). */
|
|
65
81
|
export function jobOf(
|
|
66
82
|
f: {
|
|
67
|
-
rootId: string; path: string; hash: string;
|
|
83
|
+
rootId: string; path: string; hash: string; knownKeys: ReadonlyMap<string, NodeRef>;
|
|
68
84
|
needSections?: boolean; sectionsOnly?: boolean;
|
|
69
|
-
},
|
|
85
|
+
} & ({ doc: SourceDocument; readByPool?: false } | { doc?: undefined; readByPool: true }),
|
|
70
86
|
): ExtractJob {
|
|
71
87
|
return {
|
|
72
|
-
rootId: f.rootId, path: f.path, hash: f.hash,
|
|
88
|
+
rootId: f.rootId, path: f.path, hash: f.hash, knownKeys: [...f.knownKeys],
|
|
73
89
|
...(f.needSections ? { needSections: true } : {}), ...(f.sectionsOnly ? { sectionsOnly: true } : {}),
|
|
74
|
-
|
|
90
|
+
...(f.readByPool ? { readByPool: { path: f.path, hash: f.hash } } : { doc: f.doc! }),
|
|
91
|
+
} as ExtractJob;
|
|
75
92
|
}
|
|
76
93
|
|
|
77
94
|
/**
|
|
@@ -80,6 +97,8 @@ export function jobOf(
|
|
|
80
97
|
*/
|
|
81
98
|
export function extractJob(job: ExtractJob, packs: readonly KnowledgePack[] | ComposedPacks): ExtractJobResult {
|
|
82
99
|
const composed = Array.isArray(packs) ? composePacks(packs as readonly KnowledgePack[]) : (packs as ComposedPacks);
|
|
100
|
+
// A pure job has no filesystem: a `readByPool` job is for a worker that reads (the host's handler), not for this function.
|
|
101
|
+
if (!job.doc) throw new Error(`extract job for ${job.path} carries no document (readByPool needs a reading worker)`);
|
|
83
102
|
const src = asPathSource(job.doc, job.path, job.hash);
|
|
84
103
|
const hit = composed.resolve(src);
|
|
85
104
|
if (!hit) return { extracted: [] };
|
package/src/knowledge/index.ts
CHANGED
|
@@ -43,6 +43,8 @@ export { planReview, planDetail, refreshPlan, AVG_SECTION_BYTES } from './plan.j
|
|
|
43
43
|
export type { PlanOptions, PlannedFile, PlanDetail } from './plan.js';
|
|
44
44
|
export type { ExtractorState } from './owedFiles.js';
|
|
45
45
|
export { reviewDirectory, assertStoredBatch } from './review.js';
|
|
46
|
+
export { orderForJudging } from './judgePriority.js';
|
|
47
|
+
export type { JudgeSignals } from './judgePriority.js';
|
|
46
48
|
export { extractFile, extractFileDetailed, knownKeysOfEntities } from './extractFile.js';
|
|
47
49
|
export type { ExtractFileArgs, FileExtraction } from './extractFile.js';
|
|
48
50
|
export { extractJob, jobOf } from './extractJob.js';
|
|
@@ -52,8 +54,8 @@ export { createModelLimiter, isRateLimit } from './modelLimiter.js';
|
|
|
52
54
|
export type { ModelLimiter } from './modelLimiter.js';
|
|
53
55
|
export { reasonOf } from './reviewRunModel.js';
|
|
54
56
|
export type { ReviewFailure, ReviewPhase, ReviewStep, ReviewStepOutcome } from './reviewRunModel.js';
|
|
55
|
-
export { startRun, applyRunEvent, runRate, runEta, REVIEW_RUN_STEP_RING } from './reviewRun.js';
|
|
56
|
-
export type { ReviewRun, ReviewRunEvent, ReviewRunKind, ReviewRunLane, ReviewRunOutcome, ReviewRunPhase } from './reviewRun.js';
|
|
57
|
+
export { startRun, applyRunEvent, runRate, runEta, slowestSteps, failuresOf, failureTotal, REVIEW_RUN_STEP_RING, REVIEW_RUN_FAILURE_CHUNK } from './reviewRun.js';
|
|
58
|
+
export type { ReviewFailureChunks, ReviewRun, ReviewRunEvent, ReviewRunKind, ReviewRunLane, ReviewRunOutcome, ReviewRunPhase } from './reviewRun.js';
|
|
57
59
|
export {
|
|
58
60
|
validateExtract, validateCompare, clampQuote, clampClaim, MAX_QUOTE_LINES, MAX_QUOTE_CHARS, MAX_CLAIM_TEXT_CHARS,
|
|
59
61
|
DEFAULT_REVIEW_MODEL_CALLS, DEFAULT_REVIEW_JUDGE_CONCURRENCY, REVIEW_FACT_SOURCE,
|
|
@@ -69,7 +71,7 @@ export {
|
|
|
69
71
|
export { DOCS_PACK, DOCS_PACK_ID, brokenLinkRule, orphanDocumentRule, contradictionRule } from './packs/docs.js';
|
|
70
72
|
export { frontMatterOf, SECTION_INDEX_BADGE } from '../ingest/docsExtract.js';
|
|
71
73
|
export { LocalSnapshotStore, localSnapshotStore } from './stores/localSnapshotStore.js';
|
|
72
|
-
export type { SnapshotPersistence, KnowledgeSnapshot, LocalSnapshotStoreOptions } from './stores/localSnapshotStore.js';
|
|
74
|
+
export type { SnapshotPersistence, KnowledgeSnapshot, LocalSnapshotStoreOptions, ExtractedLogPersistence } from './stores/localSnapshotStore.js';
|
|
73
75
|
|
|
74
76
|
// The knowledge index (search, expand, near-duplicate pairs) ships on the same subpath.
|
|
75
77
|
export * from '../retrieval/knowledge-index/index.js';
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/jobDeadline.ts — a per-job ceiling for the extract path (PRD 41 A10 rule 2).
|
|
3
|
+
*
|
|
4
|
+
* `createDeadlines(parent)` returns `withDeadline(ms, work)`: it runs `work(signal)` and rejects with a {@link JobTimeout}
|
|
5
|
+
* (message `timeout`) when it has not settled in `ms`. `signal` is the job's OWN: it aborts on the deadline and when
|
|
6
|
+
* `parent` aborts, so a pool terminates (recycles) the worker that holds the job. A job over its ceiling never
|
|
7
|
+
* holds the run: the caller records a failed step and moves on. A late result of the work is discarded.
|
|
8
|
+
*
|
|
9
|
+
* ONE listener sits on `parent` for the whole run (it aborts every job still in flight), so thousands of jobs, 32+ of them at once,
|
|
10
|
+
* never stack listeners on the run's signal.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export class JobTimeout extends Error {
|
|
14
|
+
constructor() { super('timeout'); this.name = 'JobTimeout'; }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export type WithDeadline = <T>(ms: number, work: (signal: AbortSignal) => Promise<T>) => Promise<T>;
|
|
18
|
+
|
|
19
|
+
export function createDeadlines(parent?: AbortSignal): WithDeadline {
|
|
20
|
+
const live = new Set<AbortController>();
|
|
21
|
+
if (parent) {
|
|
22
|
+
const stop = (): void => { for (const c of [...live]) c.abort(parent.reason); };
|
|
23
|
+
if (parent.aborted) queueMicrotask(stop); else parent.addEventListener('abort', stop, { once: true });
|
|
24
|
+
}
|
|
25
|
+
return async <T>(ms: number, work: (signal: AbortSignal) => Promise<T>): Promise<T> => {
|
|
26
|
+
const own = new AbortController();
|
|
27
|
+
if (parent?.aborted) own.abort(parent.reason);
|
|
28
|
+
live.add(own);
|
|
29
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
30
|
+
const deadline = new Promise<never>((_, reject) => {
|
|
31
|
+
timer = setTimeout(() => { const e = new JobTimeout(); own.abort(e); reject(e); }, ms);
|
|
32
|
+
});
|
|
33
|
+
const running = (async () => work(own.signal))();
|
|
34
|
+
// The deadline can win the race: a late rejection of the work (an abort it was told about) is not an unhandled one.
|
|
35
|
+
running.catch(() => undefined);
|
|
36
|
+
try {
|
|
37
|
+
return await Promise.race([running, deadline]);
|
|
38
|
+
} finally {
|
|
39
|
+
clearTimeout(timer);
|
|
40
|
+
live.delete(own);
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
}
|
|
@@ -25,6 +25,20 @@ import { reasonOf } from './reviewRunModel.js';
|
|
|
25
25
|
/** A section's validated answer: the output of the call stage, applied later by {@link applyAnswers}. */
|
|
26
26
|
export interface SectionAnswer { section: SectionToJudge; v: ReturnType<typeof validateExtract> }
|
|
27
27
|
|
|
28
|
+
/**
|
|
29
|
+
* Stops a run's judging after consecutive provider failures (PRD 41 A10 rule 9): with the network down every
|
|
30
|
+
* section would otherwise cost the full call timeout. Sections cut by it stay unjudged and owed.
|
|
31
|
+
*/
|
|
32
|
+
export class JudgeBreaker {
|
|
33
|
+
private streak = 0;
|
|
34
|
+
private reason: string | undefined;
|
|
35
|
+
constructor(private readonly limit: number = 5) {}
|
|
36
|
+
/** Why judging stopped; undefined while it runs. */
|
|
37
|
+
get stopped(): string | undefined { return this.reason; }
|
|
38
|
+
ok(): void { this.streak = 0; }
|
|
39
|
+
fail(reason: string): void { this.streak += 1; if (this.streak >= this.limit) this.reason ??= `${this.streak} model calls failed in a row: ${reason}`; }
|
|
40
|
+
}
|
|
41
|
+
|
|
28
42
|
export interface CallSectionsArgs {
|
|
29
43
|
port: JudgementPort;
|
|
30
44
|
fileHash: string;
|
|
@@ -34,6 +48,8 @@ export interface CallSectionsArgs {
|
|
|
34
48
|
/** Shared across the files of a review: caps the calls in flight and adapts to rate limits. */
|
|
35
49
|
limiter?: ModelLimiter;
|
|
36
50
|
signal?: AbortSignal;
|
|
51
|
+
/** Counts consecutive failures across the files of a run; once it trips, no further call is made. */
|
|
52
|
+
breaker?: JudgeBreaker;
|
|
37
53
|
}
|
|
38
54
|
|
|
39
55
|
export interface CallSectionsResult {
|
|
@@ -63,13 +79,14 @@ export async function callSections(a: CallSectionsArgs): Promise<CallSectionsRes
|
|
|
63
79
|
await runPool(a.sections.map((section, idx) => ({ section, idx })), JUDGE_CONCURRENCY, async ({ section, idx }) => {
|
|
64
80
|
// Honoured per section, not only when the port throws: the caller drops this file whole.
|
|
65
81
|
if (a.signal?.aborted) throw abortError();
|
|
66
|
-
if (!budgetLeft(a.budget)) { unjudged += 1; return; }
|
|
82
|
+
if (!budgetLeft(a.budget) || a.breaker?.stopped) { unjudged += 1; return; }
|
|
67
83
|
const answer = await call(a.port, {
|
|
68
84
|
kind: 'extract', items: [{ ref: section.ref, text: section.text, sourceHash: a.fileHash }],
|
|
69
85
|
...(a.signal ? { signal: a.signal } : {}),
|
|
70
86
|
}, a.budget, hooks);
|
|
71
87
|
// A failed call judged nothing: not counted judged, so the file stays changed and is retried.
|
|
72
|
-
if (!answer) { unjudged += 1; return; }
|
|
88
|
+
if (!answer) { unjudged += 1; a.breaker?.fail(firstError ?? 'model call failed'); return; }
|
|
89
|
+
a.breaker?.ok();
|
|
73
90
|
// The abort can land while a call is in flight (the port sees the signal): a section that
|
|
74
91
|
// finished after the abort must not count as judged, or the caller would not re-judge it.
|
|
75
92
|
if (a.signal?.aborted) throw abortError();
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/judgePriority.ts — the order pass 2 judges owed files in (PRD 41 A10 rule 1).
|
|
3
|
+
*
|
|
4
|
+
* 1. entry points and manifests,
|
|
5
|
+
* 2. files with the most inbound references,
|
|
6
|
+
* 3. recently changed files,
|
|
7
|
+
* 4. the rest.
|
|
8
|
+
*
|
|
9
|
+
* Pure and deterministic: ties break by path, so equal input is the same order on every host. The caller
|
|
10
|
+
* supplies the signals (it owns the graph and the history); a missing signal simply ranks nobody.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { compareStr } from './refs.js';
|
|
14
|
+
|
|
15
|
+
export interface JudgeSignals {
|
|
16
|
+
/** Entry points and manifests (a package.json, a README, a declared `main`). */
|
|
17
|
+
entry?: (path: string) => boolean;
|
|
18
|
+
/** Inbound reference count per path. */
|
|
19
|
+
inbound?: ReadonlyMap<string, number>;
|
|
20
|
+
/** Files changed since the last review (or by the latest commits). */
|
|
21
|
+
recent?: ReadonlySet<string>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** `paths` in judging order. The input is not mutated. */
|
|
25
|
+
export function orderForJudging(paths: readonly string[], signals: JudgeSignals = {}): string[] {
|
|
26
|
+
const tier = (p: string): number => (signals.entry?.(p) ? 0 : (signals.inbound?.get(p) ?? 0) > 0 ? 1 : signals.recent?.has(p) ? 2 : 3);
|
|
27
|
+
return [...paths].sort((a, b) => {
|
|
28
|
+
const ta = tier(a), tb = tier(b);
|
|
29
|
+
if (ta !== tb) return ta - tb;
|
|
30
|
+
if (ta === 1) {
|
|
31
|
+
const d = (signals.inbound!.get(b) ?? 0) - (signals.inbound!.get(a) ?? 0);
|
|
32
|
+
if (d !== 0) return d;
|
|
33
|
+
}
|
|
34
|
+
return compareStr(a, b);
|
|
35
|
+
});
|
|
36
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/pack/crc32.ts — CRC-32 (IEEE 802.3) of a byte range; the trailer of a BFKP frame (PRD 41 A11).
|
|
3
|
+
* `crc32(b, crc32(a))` equals `crc32(a ++ b)`, so a frame's CRC covers its header and its body without a copy.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const TABLE: Uint32Array = (() => {
|
|
7
|
+
const t = new Uint32Array(256);
|
|
8
|
+
for (let n = 0; n < 256; n++) {
|
|
9
|
+
let c = n;
|
|
10
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
11
|
+
t[n] = c >>> 0;
|
|
12
|
+
}
|
|
13
|
+
return t;
|
|
14
|
+
})();
|
|
15
|
+
|
|
16
|
+
/** The CRC-32 of `data`, continuing from `previous` (the CRC of what came before; 0 to start). */
|
|
17
|
+
export function crc32(data: Uint8Array, previous = 0): number {
|
|
18
|
+
let c = (previous ^ 0xffffffff) >>> 0;
|
|
19
|
+
for (let i = 0; i < data.length; i++) c = TABLE[(c ^ data[i]!) & 0xff]! ^ (c >>> 8);
|
|
20
|
+
return (c ^ 0xffffffff) >>> 0;
|
|
21
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/pack/decode.ts — `decodePack` (PRD 41 A11). Guards run before any row is built: the
|
|
3
|
+
* magic and version, the CRC-32 of the header and the decoded body, the inflate cap (`PackTooLargeError` past
|
|
4
|
+
* `maxDecodedBytes`) and the string/row counts. A malformed pack is a `PackFormatError`.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { crc32 } from './crc32.js';
|
|
8
|
+
import { inflateRaw } from './deflate.js';
|
|
9
|
+
import { FLAG_DEFLATED, readFrame, readSections } from './frame.js';
|
|
10
|
+
import { ROW_SECTIONS, TAG } from './sections/index.js';
|
|
11
|
+
import { readHashTable, readStringTable, readTables } from './strings.js';
|
|
12
|
+
import { DEFAULT_PACK_LIMITS, PackTooLargeError, type Pack, type PackLimits, type ReadLimits } from './types.js';
|
|
13
|
+
import { PackFormatError } from './varint.js';
|
|
14
|
+
|
|
15
|
+
const NONE = new Uint8Array([0]);
|
|
16
|
+
|
|
17
|
+
/** The frame's header, without inflating the body (cheap: for routing and the generation check). */
|
|
18
|
+
export function peekPack(bytes: Uint8Array): { rootId: string; baseGeneration: number; targetDigest: string } {
|
|
19
|
+
const { header } = readFrame(bytes);
|
|
20
|
+
return { rootId: header.rootId, baseGeneration: header.baseGeneration, targetDigest: header.targetDigest };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function decodePack(bytes: Uint8Array, limits: Partial<PackLimits> = {}): Promise<Pack> {
|
|
24
|
+
const base0: PackLimits = { ...DEFAULT_PACK_LIMITS, ...limits };
|
|
25
|
+
// ONE row budget for the whole pack: every list of every section draws from it.
|
|
26
|
+
const lim: ReadLimits = { ...base0, budget: { left: base0.maxRows } };
|
|
27
|
+
const { header, headerBytes, stored, crc } = readFrame(bytes);
|
|
28
|
+
let body: Uint8Array;
|
|
29
|
+
if (header.flags & FLAG_DEFLATED) {
|
|
30
|
+
try {
|
|
31
|
+
body = await inflateRaw(stored, lim.maxDecodedBytes);
|
|
32
|
+
} catch (error) {
|
|
33
|
+
if (error instanceof PackTooLargeError) throw error;
|
|
34
|
+
throw new PackFormatError('corrupt deflate stream');
|
|
35
|
+
}
|
|
36
|
+
} else {
|
|
37
|
+
if (stored.length > lim.maxDecodedBytes) throw new PackTooLargeError(lim.maxDecodedBytes);
|
|
38
|
+
body = stored;
|
|
39
|
+
}
|
|
40
|
+
if (crc32(body, crc32(headerBytes)) !== crc) throw new PackFormatError('CRC-32 mismatch');
|
|
41
|
+
try {
|
|
42
|
+
const sections = readSections(body);
|
|
43
|
+
const strings = readStringTable(sections.get(TAG.STR) ?? NONE, lim.maxStrings, lim.maxDecodedBytes);
|
|
44
|
+
const hashes = readHashTable(sections.get(TAG.HASH) ?? NONE, lim.maxStrings);
|
|
45
|
+
const used = new Set<string>();
|
|
46
|
+
const base = readTables(strings, hashes);
|
|
47
|
+
const tables = { str: base.str, hash: (i: number) => { const h = base.hash(i); used.add(h); return h; } };
|
|
48
|
+
const pack: Pack = { rootId: header.rootId, baseGeneration: header.baseGeneration, targetDigest: header.targetDigest };
|
|
49
|
+
for (const s of ROW_SECTIONS) {
|
|
50
|
+
const bytes = sections.get(s.tag);
|
|
51
|
+
if (bytes) s.read(bytes, tables, lim, pack);
|
|
52
|
+
}
|
|
53
|
+
const extra = hashes.filter((h) => !used.has(h));
|
|
54
|
+
if (extra.length > 0) pack.hashes = extra;
|
|
55
|
+
return pack;
|
|
56
|
+
} catch (error) {
|
|
57
|
+
if (error instanceof PackFormatError || error instanceof PackTooLargeError) throw error;
|
|
58
|
+
throw new PackFormatError(error instanceof Error ? error.message : 'malformed pack');
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/pack/deflate.ts — `deflate-raw` through `CompressionStream` / `DecompressionStream`, which
|
|
3
|
+
* Node 18+, Cloudflare Workers and browsers all have (PRD 41 A11). Inflation is CAPPED: a stream that
|
|
4
|
+
* produces more than `maxBytes` is cancelled at once, so a bomb never holds more than the cap.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { PackTooLargeError } from './types.js';
|
|
8
|
+
|
|
9
|
+
async function drain(stream: ReadableStream<Uint8Array>, maxBytes: number): Promise<Uint8Array> {
|
|
10
|
+
const reader = stream.getReader();
|
|
11
|
+
const chunks: Uint8Array[] = [];
|
|
12
|
+
let total = 0;
|
|
13
|
+
for (;;) {
|
|
14
|
+
const { done, value } = await reader.read();
|
|
15
|
+
if (done) break;
|
|
16
|
+
total += value.length;
|
|
17
|
+
if (total > maxBytes) { await reader.cancel().catch(() => undefined); throw new PackTooLargeError(maxBytes); }
|
|
18
|
+
chunks.push(value);
|
|
19
|
+
}
|
|
20
|
+
const out = new Uint8Array(total);
|
|
21
|
+
let at = 0;
|
|
22
|
+
for (const c of chunks) { out.set(c, at); at += c.length; }
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function through(data: Uint8Array, transform: { readable: ReadableStream<Uint8Array>; writable: WritableStream<BufferSource> }, maxBytes: number): Promise<Uint8Array> {
|
|
27
|
+
const writer = transform.writable.getWriter();
|
|
28
|
+
// Written without waiting: the reader below must drain it, or a large input would stall on backpressure.
|
|
29
|
+
const wrote = writer.write(data as unknown as BufferSource).then(() => writer.close());
|
|
30
|
+
wrote.catch(() => undefined);
|
|
31
|
+
try {
|
|
32
|
+
return await drain(transform.readable, maxBytes);
|
|
33
|
+
} finally {
|
|
34
|
+
await wrote.catch(() => undefined);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const deflateRaw = (data: Uint8Array): Promise<Uint8Array> =>
|
|
39
|
+
through(data, new CompressionStream('deflate-raw') as never, Number.MAX_SAFE_INTEGER);
|
|
40
|
+
|
|
41
|
+
/** Throws {@link PackTooLargeError} past `maxBytes` of output, and `Error` on a corrupt stream. */
|
|
42
|
+
export const inflateRaw = (data: Uint8Array, maxBytes: number): Promise<Uint8Array> =>
|
|
43
|
+
through(data, new DecompressionStream('deflate-raw') as never, maxBytes);
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/pack/encode.ts — `encodePack` and `normalizePack` (PRD 41 A11).
|
|
3
|
+
*
|
|
4
|
+
* Deterministic: rows are put in canonical order first, the tables are sorted, and every section
|
|
5
|
+
* is written from the same normalized pack, so equal input (in any row order) gives equal bytes.
|
|
6
|
+
* Two passes over the section writers: the first collects every string and hash they use, the
|
|
7
|
+
* second writes real table indexes.
|
|
8
|
+
*
|
|
9
|
+
* NORMALISATION (lossless for every value the model produces, documented where it is not): rows are sorted and
|
|
10
|
+
* empty parts dropped; object keys of badges and of the analysis document are written in sorted order; a
|
|
11
|
+
* negative zero is written as zero; a string holding a lone UTF-16 surrogate is written with U+FFFD in its place
|
|
12
|
+
* (UTF-8 cannot carry it). Equal normalised input gives equal bytes.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { deflateRaw } from './deflate.js';
|
|
16
|
+
import { FLAG_DEFLATED, writeFrame, writeSection } from './frame.js';
|
|
17
|
+
import { ROW_SECTIONS, TAG } from './sections/index.js';
|
|
18
|
+
import { compare } from './sections/columns.js';
|
|
19
|
+
import { collector, tablesOf, writeHashTable, writeStringTable } from './strings.js';
|
|
20
|
+
import type { Pack, RelationId } from './types.js';
|
|
21
|
+
import { ByteWriter } from './varint.js';
|
|
22
|
+
|
|
23
|
+
const nonEmpty = <T>(xs: readonly T[] | undefined): T[] | undefined => (xs && xs.length > 0 ? [...xs] : undefined);
|
|
24
|
+
const byRelation = (a: RelationId, b: RelationId): number => compare(a.from, b.from) || compare(a.to, b.to) || compare(a.kind, b.kind);
|
|
25
|
+
|
|
26
|
+
/** The hashes the row sections reference (a `have` request's explicit hashes are not among them). */
|
|
27
|
+
function referencedHashes(pack: Pack): Set<string> {
|
|
28
|
+
const col = collector();
|
|
29
|
+
for (const s of ROW_SECTIONS) s.write(pack, col);
|
|
30
|
+
return col.hashes;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The pack in canonical form: rows sorted, empty parts dropped, `hashes` reduced to those no section references. */
|
|
34
|
+
export function normalizePack(pack: Pack): Pack {
|
|
35
|
+
const out: Pack = { rootId: pack.rootId, baseGeneration: pack.baseGeneration, targetDigest: pack.targetDigest };
|
|
36
|
+
const files = nonEmpty(pack.files)?.sort((a, b) => compare(a.path, b.path));
|
|
37
|
+
if (files) out.files = files;
|
|
38
|
+
const extracted = nonEmpty(pack.extracted)?.sort((a, b) => compare(a.hash, b.hash));
|
|
39
|
+
if (extracted) out.extracted = extracted;
|
|
40
|
+
const facts = nonEmpty(pack.facts)?.sort((a, b) => compare(a.key, b.key));
|
|
41
|
+
if (facts) out.facts = facts;
|
|
42
|
+
const relations = nonEmpty(pack.relations)?.sort((a, b) => byRelation(a, b));
|
|
43
|
+
if (relations) out.relations = relations;
|
|
44
|
+
const stale = nonEmpty(pack.stale)?.sort((a, b) => compare(a.sourceRef, b.sourceRef));
|
|
45
|
+
if (stale) out.stale = stale;
|
|
46
|
+
const d = pack.deletes;
|
|
47
|
+
if (d && d.files.length + d.facts.length + d.relations.length > 0) {
|
|
48
|
+
out.deletes = { files: [...d.files].sort(compare), facts: [...d.facts].sort(compare), relations: [...d.relations].sort(byRelation) };
|
|
49
|
+
}
|
|
50
|
+
if (pack.scope) out.scope = pack.scope;
|
|
51
|
+
if (pack.analysis !== undefined) out.analysis = pack.analysis;
|
|
52
|
+
const leaves = nonEmpty(pack.leaves)?.sort((a, b) => compare(a.key, b.key));
|
|
53
|
+
if (leaves) out.leaves = leaves;
|
|
54
|
+
if (pack.buckets) out.buckets = pack.buckets;
|
|
55
|
+
const used = referencedHashes(out);
|
|
56
|
+
const extra = [...new Set(pack.hashes ?? [])].filter((h) => !used.has(h)).sort(compare);
|
|
57
|
+
if (extra.length > 0) out.hashes = extra;
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface EncodeOptions {
|
|
62
|
+
/** Deflate the body (default true). Off, the bytes are the plain columnar form (tests, size comparisons). */
|
|
63
|
+
deflate?: boolean;
|
|
64
|
+
/** Filled with the size of the DECODED body: a client cuts a pack by it before the server's cap refuses it. */
|
|
65
|
+
stats?: { decodedBytes: number };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export async function encodePack(input: Pack, opts: EncodeOptions = {}): Promise<Uint8Array> {
|
|
69
|
+
const pack = normalizePack(input);
|
|
70
|
+
const col = collector();
|
|
71
|
+
for (const s of ROW_SECTIONS) s.write(pack, col);
|
|
72
|
+
const tables = tablesOf(col.strings, [...col.hashes, ...(pack.hashes ?? [])]);
|
|
73
|
+
|
|
74
|
+
const body = new ByteWriter();
|
|
75
|
+
writeSection(body, TAG.STR, writeStringTable(tables.strings));
|
|
76
|
+
writeSection(body, TAG.HASH, writeHashTable(tables.hashes));
|
|
77
|
+
for (const s of ROW_SECTIONS) {
|
|
78
|
+
const bytes = s.write(pack, tables);
|
|
79
|
+
if (bytes) writeSection(body, s.tag, bytes);
|
|
80
|
+
}
|
|
81
|
+
const plain = body.finish();
|
|
82
|
+
if (opts.stats) opts.stats.decodedBytes = plain.length;
|
|
83
|
+
const deflate = opts.deflate ?? true;
|
|
84
|
+
return writeFrame(
|
|
85
|
+
{ flags: deflate ? FLAG_DEFLATED : 0, rootId: pack.rootId, baseGeneration: pack.baseGeneration, targetDigest: pack.targetDigest },
|
|
86
|
+
plain,
|
|
87
|
+
deflate ? await deflateRaw(plain) : plain,
|
|
88
|
+
);
|
|
89
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/pack/extrDiff.ts — within-file diff (PRD 41 A11 rule 2): a re-extracted file sends the
|
|
3
|
+
* nodes, edges and keys that changed against the acknowledged prior extraction of the same source,
|
|
4
|
+
* plus the identities that vanished, instead of its whole extraction.
|
|
5
|
+
*
|
|
6
|
+
* Lossless by construction: `applyEntryDiff(prior, diffEntry(prior, next))` deep-equals `next`
|
|
7
|
+
* (order included). `diffEntry` returns undefined when it cannot promise that — an identity that
|
|
8
|
+
* repeats within a list, or surviving items that changed relative order — and the caller sends the whole entry.
|
|
9
|
+
*
|
|
10
|
+
* A diff arrives from an untrusted pack: `applyEntryDiff` validates it (positions integer, strictly increasing,
|
|
11
|
+
* inside the rebuilt list) and throws on a malformed one.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { Extracted, KEdge, KNode } from './types.js';
|
|
15
|
+
import type { ExtrEntryDiff, ListDiff } from './types.js';
|
|
16
|
+
|
|
17
|
+
export function deepEqual(a: unknown, b: unknown): boolean {
|
|
18
|
+
if (a === b) return true;
|
|
19
|
+
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return Object.is(a, b);
|
|
20
|
+
if (Array.isArray(a) !== Array.isArray(b)) return false;
|
|
21
|
+
if (Array.isArray(a)) return a.length === (b as unknown[]).length && a.every((x, i) => deepEqual(x, (b as unknown[])[i]));
|
|
22
|
+
const ka = Object.keys(a as object).filter((k) => (a as Record<string, unknown>)[k] !== undefined);
|
|
23
|
+
const kb = Object.keys(b as object).filter((k) => (b as Record<string, unknown>)[k] !== undefined);
|
|
24
|
+
return ka.length === kb.length && ka.every((k) => deepEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function diffList<T>(prior: readonly T[], next: readonly T[], id: (x: T) => string, same: (p: T, n: T) => boolean = deepEqual): ListDiff<T> | undefined {
|
|
28
|
+
const before = new Map<string, T>();
|
|
29
|
+
for (const p of prior) { const k = id(p); if (before.has(k)) return undefined; before.set(k, p); }
|
|
30
|
+
const seen = new Set<string>();
|
|
31
|
+
for (const n of next) { const k = id(n); if (seen.has(k)) return undefined; seen.add(k); }
|
|
32
|
+
const survives = (n: T): boolean => before.has(id(n)) && same(before.get(id(n))!, n);
|
|
33
|
+
const survivorsNext = next.filter(survives).map(id);
|
|
34
|
+
const after = new Map(next.map((n) => [id(n), n] as const));
|
|
35
|
+
const survivorsPrior = prior.filter((p) => after.has(id(p)) && same(p, after.get(id(p))!)).map(id);
|
|
36
|
+
if (survivorsNext.length !== survivorsPrior.length || survivorsNext.some((k, i) => k !== survivorsPrior[i])) return undefined;
|
|
37
|
+
const keep = new Set(survivorsNext);
|
|
38
|
+
return {
|
|
39
|
+
remove: prior.map(id).filter((k) => !keep.has(k)),
|
|
40
|
+
add: next.flatMap((item, at) => (keep.has(id(item)) ? [] : [{ at, item }])),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function applyList<T>(prior: readonly T[], diff: ListDiff<T>, id: (x: T) => string, restamp: (x: T) => T = (x) => x): T[] {
|
|
45
|
+
const gone = new Set(diff.remove);
|
|
46
|
+
const kept = prior.filter((p) => !gone.has(id(p))).map(restamp);
|
|
47
|
+
const total = kept.length + diff.add.length;
|
|
48
|
+
let last = -1;
|
|
49
|
+
for (const a of diff.add) {
|
|
50
|
+
if (!Number.isInteger(a.at) || a.at <= last || a.at >= total) throw new Error('malformed diff: add position out of order or out of range');
|
|
51
|
+
last = a.at;
|
|
52
|
+
}
|
|
53
|
+
const out: T[] = new Array(total);
|
|
54
|
+
for (const a of diff.add) out[a.at] = a.item;
|
|
55
|
+
let k = 0;
|
|
56
|
+
for (let i = 0; i < total; i++) if (!(i in out)) out[i] = kept[k++]!;
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const nodeId = (n: KNode): string => n.ref;
|
|
61
|
+
/**
|
|
62
|
+
* A node carries its file's hash as `sourceHash`, so every node of a changed file differs from its prior by that
|
|
63
|
+
* field alone. Compared with it replaced by a marker, a node that changed in nothing else survives, and is re-stamped
|
|
64
|
+
* with the new entry's hash on apply.
|
|
65
|
+
*/
|
|
66
|
+
const stamped = (n: KNode, entryHash: string): KNode => (n.sourceHash === entryHash ? { ...n, sourceHash: '\u0000entry' } : n);
|
|
67
|
+
const edgeId = (e: KEdge): string => `${e.from}\u0000${e.to}\u0000${e.kind}`;
|
|
68
|
+
const keyId = (k: { ref: string; key: string }): string => `${k.ref}\u0000${k.key}`;
|
|
69
|
+
|
|
70
|
+
export function diffEntry(prior: Extracted, next: Extracted): ExtrEntryDiff | undefined {
|
|
71
|
+
if (prior.sourceRef !== next.sourceRef) return undefined;
|
|
72
|
+
const nodes = diffList(prior.nodes, next.nodes, nodeId, (p, n) => deepEqual(stamped(p, prior.sourceHash), stamped(n, next.sourceHash)));
|
|
73
|
+
const edges = diffList(prior.edges, next.edges, edgeId);
|
|
74
|
+
const keys = diffList(prior.keys, next.keys, keyId);
|
|
75
|
+
if (!nodes || !edges || !keys) return undefined;
|
|
76
|
+
return {
|
|
77
|
+
sourceRef: next.sourceRef, sourceHash: next.sourceHash,
|
|
78
|
+
...(next.extractorVersion !== undefined ? { extractorVersion: next.extractorVersion } : {}),
|
|
79
|
+
nodes, edges, keys,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function applyEntryDiff(prior: Extracted, diff: ExtrEntryDiff): Extracted {
|
|
84
|
+
return {
|
|
85
|
+
sourceRef: diff.sourceRef as Extracted['sourceRef'], sourceHash: diff.sourceHash,
|
|
86
|
+
...(diff.extractorVersion !== undefined ? { extractorVersion: diff.extractorVersion } : {}),
|
|
87
|
+
nodes: applyList(prior.nodes, diff.nodes, nodeId, (n) => (n.sourceHash === prior.sourceHash ? { ...n, sourceHash: diff.sourceHash } : n)),
|
|
88
|
+
edges: applyList(prior.edges, diff.edges, edgeId),
|
|
89
|
+
keys: applyList(prior.keys, diff.keys, keyId) as Extracted['keys'],
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The entries of `next` as diffs against the entries of `prior` with the same `sourceRef`, or undefined
|
|
95
|
+
* when any entry has no usable prior (then the hash is sent whole). A diff only pays when it is smaller:
|
|
96
|
+
* the caller compares sizes if it cares; this decides only what is possible.
|
|
97
|
+
*/
|
|
98
|
+
export function diffEntries(prior: readonly Extracted[], next: readonly Extracted[]): ExtrEntryDiff[] | undefined {
|
|
99
|
+
const out: ExtrEntryDiff[] = [];
|
|
100
|
+
for (const n of next) {
|
|
101
|
+
const p = prior.find((x) => x.sourceRef === n.sourceRef);
|
|
102
|
+
const d = p && diffEntry(p, n);
|
|
103
|
+
if (!d) return undefined;
|
|
104
|
+
out.push(d);
|
|
105
|
+
}
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Rebuilds a hash's entries from its diffs and the prior hash's entries; throws when a prior entry is missing or a diff is malformed. */
|
|
110
|
+
export function applyEntryDiffs(prior: readonly Extracted[], diffs: readonly ExtrEntryDiff[]): Extracted[] {
|
|
111
|
+
return diffs.map((d) => {
|
|
112
|
+
const p = prior.find((x) => x.sourceRef === d.sourceRef);
|
|
113
|
+
if (!p) throw new Error(`no prior extraction for ${d.sourceRef}`);
|
|
114
|
+
return applyEntryDiff(p, d);
|
|
115
|
+
});
|
|
116
|
+
}
|