@seanhogg/builderforce-memory 2026.10.45 → 2026.10.46
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/knowledge/build.d.ts.map +1 -1
- package/dist/knowledge/build.js +13 -7
- package/dist/knowledge/build.js.map +1 -1
- package/dist/knowledge/extractFile.d.ts +9 -1
- package/dist/knowledge/extractFile.d.ts.map +1 -1
- package/dist/knowledge/extractFile.js +22 -5
- package/dist/knowledge/extractFile.js.map +1 -1
- package/dist/knowledge/extractJob.d.ts +30 -5
- package/dist/knowledge/extractJob.d.ts.map +1 -1
- package/dist/knowledge/extractJob.js +9 -1
- package/dist/knowledge/extractJob.js.map +1 -1
- package/dist/knowledge/index.d.ts +5 -3
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +2 -1
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge/jobDeadline.d.ts +17 -0
- package/dist/knowledge/jobDeadline.d.ts.map +1 -0
- package/dist/knowledge/jobDeadline.js +46 -0
- package/dist/knowledge/jobDeadline.js.map +1 -0
- package/dist/knowledge/judgeCalls.d.ts +16 -0
- package/dist/knowledge/judgeCalls.d.ts.map +1 -1
- package/dist/knowledge/judgeCalls.js +20 -1
- package/dist/knowledge/judgeCalls.js.map +1 -1
- package/dist/knowledge/judgePriority.d.ts +22 -0
- package/dist/knowledge/judgePriority.d.ts.map +1 -0
- package/dist/knowledge/judgePriority.js +28 -0
- package/dist/knowledge/judgePriority.js.map +1 -0
- package/dist/knowledge/pack/crc32.d.ts +3 -0
- package/dist/knowledge/pack/crc32.d.ts.map +1 -0
- package/dist/knowledge/pack/crc32.js +18 -0
- package/dist/knowledge/pack/crc32.js.map +1 -0
- package/dist/knowledge/pack/decode.d.ts +14 -0
- package/dist/knowledge/pack/decode.d.ts.map +1 -0
- package/dist/knowledge/pack/decode.js +64 -0
- package/dist/knowledge/pack/decode.js.map +1 -0
- package/dist/knowledge/pack/deflate.d.ts +9 -0
- package/dist/knowledge/pack/deflate.d.ts.map +1 -0
- package/dist/knowledge/pack/deflate.js +45 -0
- package/dist/knowledge/pack/deflate.js.map +1 -0
- package/dist/knowledge/pack/encode.d.ts +17 -0
- package/dist/knowledge/pack/encode.d.ts.map +1 -0
- package/dist/knowledge/pack/encode.js +79 -0
- package/dist/knowledge/pack/encode.js.map +1 -0
- package/dist/knowledge/pack/extrDiff.d.ts +23 -0
- package/dist/knowledge/pack/extrDiff.d.ts.map +1 -0
- package/dist/knowledge/pack/extrDiff.js +0 -0
- package/dist/knowledge/pack/extrDiff.js.map +1 -0
- package/dist/knowledge/pack/frame.d.ts +37 -0
- package/dist/knowledge/pack/frame.d.ts.map +1 -0
- package/dist/knowledge/pack/frame.js +94 -0
- package/dist/knowledge/pack/frame.js.map +1 -0
- package/dist/knowledge/pack/index.d.ts +19 -0
- package/dist/knowledge/pack/index.d.ts.map +1 -0
- package/dist/knowledge/pack/index.js +17 -0
- package/dist/knowledge/pack/index.js.map +1 -0
- package/dist/knowledge/pack/jsonSize.d.ts +5 -0
- package/dist/knowledge/pack/jsonSize.d.ts.map +1 -0
- package/dist/knowledge/pack/jsonSize.js +8 -0
- package/dist/knowledge/pack/jsonSize.js.map +1 -0
- package/dist/knowledge/pack/manifest.d.ts +66 -0
- package/dist/knowledge/pack/manifest.d.ts.map +1 -0
- package/dist/knowledge/pack/manifest.js +104 -0
- package/dist/knowledge/pack/manifest.js.map +1 -0
- package/dist/knowledge/pack/sections/columns.d.ts +32 -0
- package/dist/knowledge/pack/sections/columns.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/columns.js +53 -0
- package/dist/knowledge/pack/sections/columns.js.map +1 -0
- package/dist/knowledge/pack/sections/extr.d.ts +8 -0
- package/dist/knowledge/pack/sections/extr.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/extr.js +99 -0
- package/dist/knowledge/pack/sections/extr.js.map +1 -0
- package/dist/knowledge/pack/sections/extrLists.d.ts +23 -0
- package/dist/knowledge/pack/sections/extrLists.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/extrLists.js +194 -0
- package/dist/knowledge/pack/sections/extrLists.js.map +1 -0
- package/dist/knowledge/pack/sections/facts.d.ts +8 -0
- package/dist/knowledge/pack/sections/facts.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/facts.js +167 -0
- package/dist/knowledge/pack/sections/facts.js.map +1 -0
- package/dist/knowledge/pack/sections/index.d.ts +6 -0
- package/dist/knowledge/pack/sections/index.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/index.js +9 -0
- package/dist/knowledge/pack/sections/index.js.map +1 -0
- package/dist/knowledge/pack/sections/rows.d.ts +31 -0
- package/dist/knowledge/pack/sections/rows.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/rows.js +226 -0
- package/dist/knowledge/pack/sections/rows.js.map +1 -0
- package/dist/knowledge/pack/strings.d.ts +39 -0
- package/dist/knowledge/pack/strings.d.ts.map +1 -0
- package/dist/knowledge/pack/strings.js +115 -0
- package/dist/knowledge/pack/strings.js.map +1 -0
- package/dist/knowledge/pack/types.d.ts +109 -0
- package/dist/knowledge/pack/types.d.ts.map +1 -0
- package/dist/knowledge/pack/types.js +17 -0
- package/dist/knowledge/pack/types.js.map +1 -0
- package/dist/knowledge/pack/varint.d.ts +50 -0
- package/dist/knowledge/pack/varint.d.ts.map +1 -0
- package/dist/knowledge/pack/varint.js +141 -0
- package/dist/knowledge/pack/varint.js.map +1 -0
- package/dist/knowledge/partitions.d.ts +1 -1
- package/dist/knowledge/partitions.d.ts.map +1 -1
- package/dist/knowledge/partitions.js +6 -1
- package/dist/knowledge/partitions.js.map +1 -1
- package/dist/knowledge/review.d.ts.map +1 -1
- package/dist/knowledge/review.js +58 -16
- package/dist/knowledge/review.js.map +1 -1
- package/dist/knowledge/reviewJudge.d.ts +8 -1
- package/dist/knowledge/reviewJudge.d.ts.map +1 -1
- package/dist/knowledge/reviewJudge.js +14 -8
- package/dist/knowledge/reviewJudge.js.map +1 -1
- package/dist/knowledge/reviewModel.d.ts +35 -1
- package/dist/knowledge/reviewModel.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.d.ts +8 -2
- package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.js +50 -25
- package/dist/knowledge/reviewPrefetch.js.map +1 -1
- package/dist/knowledge/reviewRun.d.ts +15 -3
- package/dist/knowledge/reviewRun.d.ts.map +1 -1
- package/dist/knowledge/reviewRun.js +19 -2
- package/dist/knowledge/reviewRun.js.map +1 -1
- package/dist/knowledge/reviewRunModel.d.ts +8 -1
- package/dist/knowledge/reviewRunModel.d.ts.map +1 -1
- package/dist/knowledge/reviewRunModel.js.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.d.ts +72 -6
- package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.js +279 -75
- package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
- package/package.json +7 -3
- package/src/knowledge/build.ts +11 -5
- package/src/knowledge/extractFile.ts +26 -6
- package/src/knowledge/extractJob.ts +26 -7
- package/src/knowledge/index.ts +5 -3
- package/src/knowledge/jobDeadline.ts +43 -0
- package/src/knowledge/judgeCalls.ts +19 -2
- package/src/knowledge/judgePriority.ts +36 -0
- package/src/knowledge/pack/crc32.ts +17 -0
- package/src/knowledge/pack/decode.ts +58 -0
- package/src/knowledge/pack/deflate.ts +43 -0
- package/src/knowledge/pack/encode.ts +81 -0
- package/src/knowledge/pack/extrDiff.ts +0 -0
- package/src/knowledge/pack/frame.ts +86 -0
- package/src/knowledge/pack/index.ts +26 -0
- package/src/knowledge/pack/jsonSize.ts +11 -0
- package/src/knowledge/pack/manifest.ts +128 -0
- package/src/knowledge/pack/pack.guards.test.ts +77 -0
- package/src/knowledge/pack/pack.reconcile.test.ts +96 -0
- package/src/knowledge/pack/pack.roundtrip.test.ts +50 -0
- package/src/knowledge/pack/pack.size.test.ts +22 -0
- package/src/knowledge/pack/pack.testkit.test-util.ts +90 -0
- package/src/knowledge/pack/sections/columns.ts +61 -0
- package/src/knowledge/pack/sections/extr.ts +90 -0
- package/src/knowledge/pack/sections/extrLists.ts +147 -0
- package/src/knowledge/pack/sections/facts.ts +123 -0
- package/src/knowledge/pack/sections/index.ts +13 -0
- package/src/knowledge/pack/sections/rows.ts +184 -0
- package/src/knowledge/pack/strings.ts +123 -0
- package/src/knowledge/pack/types.ts +89 -0
- package/src/knowledge/pack/varint.ts +138 -0
- package/src/knowledge/partitions.test.ts +4 -0
- package/src/knowledge/partitions.ts +3 -1
- package/src/knowledge/review.throughput.test.ts +122 -0
- package/src/knowledge/review.ts +54 -16
- package/src/knowledge/review.twoPass.test.ts +224 -0
- package/src/knowledge/reviewJudge.ts +19 -8
- package/src/knowledge/reviewModel.ts +32 -1
- package/src/knowledge/reviewPrefetch.ts +51 -24
- package/src/knowledge/reviewRun.test.ts +20 -3
- package/src/knowledge/reviewRun.ts +33 -6
- package/src/knowledge/reviewRunModel.ts +4 -1
- package/src/knowledge/stores/localSnapshotStore.batched.test.ts +25 -3
- package/src/knowledge/stores/localSnapshotStore.extractedLog.test.ts +280 -0
- package/src/knowledge/stores/localSnapshotStore.ts +283 -76
- package/src/knowledge/systems.test.ts +12 -0
|
@@ -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,29 +71,39 @@ 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}`);
|
|
@@ -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,17 @@
|
|
|
1
|
+
/** knowledge/pack/crc32.ts — CRC-32 (IEEE 802.3) of a byte range; the trailer of a BFKP frame (PRD 41 A11). */
|
|
2
|
+
|
|
3
|
+
const TABLE: Uint32Array = (() => {
|
|
4
|
+
const t = new Uint32Array(256);
|
|
5
|
+
for (let n = 0; n < 256; n++) {
|
|
6
|
+
let c = n;
|
|
7
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
8
|
+
t[n] = c >>> 0;
|
|
9
|
+
}
|
|
10
|
+
return t;
|
|
11
|
+
})();
|
|
12
|
+
|
|
13
|
+
export function crc32(data: Uint8Array): number {
|
|
14
|
+
let c = 0xffffffff;
|
|
15
|
+
for (let i = 0; i < data.length; i++) c = TABLE[(c ^ data[i]!) & 0xff]! ^ (c >>> 8);
|
|
16
|
+
return (c ^ 0xffffffff) >>> 0;
|
|
17
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/pack/decode.ts — `decodePack` (PRD 41 A11). Guards run before any row is built: the
|
|
3
|
+
* magic and version, the CRC-32 of the decoded body, the inflate cap (`PackTooLargeError` past
|
|
4
|
+
* `maxDecodedBytes`) and the string/row counts. A malformed pack is a `PackFormatError`.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { crc32 } from './crc32.js';
|
|
8
|
+
import { inflateRaw } from './deflate.js';
|
|
9
|
+
import { FLAG_DEFLATED, readFrame, readSections } from './frame.js';
|
|
10
|
+
import { ROW_SECTIONS, TAG } from './sections/index.js';
|
|
11
|
+
import { readHashTable, readStringTable, readTables } from './strings.js';
|
|
12
|
+
import { DEFAULT_PACK_LIMITS, PackTooLargeError, type Pack, type PackLimits } from './types.js';
|
|
13
|
+
import { PackFormatError } from './varint.js';
|
|
14
|
+
|
|
15
|
+
const NONE = new Uint8Array([0]);
|
|
16
|
+
|
|
17
|
+
/** The frame's header, without inflating the body (cheap: for routing and the generation check). */
|
|
18
|
+
export function peekPack(bytes: Uint8Array): { rootId: string; baseGeneration: number; targetDigest: string } {
|
|
19
|
+
const { header } = readFrame(bytes);
|
|
20
|
+
return { rootId: header.rootId, baseGeneration: header.baseGeneration, targetDigest: header.targetDigest };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function decodePack(bytes: Uint8Array, limits: Partial<PackLimits> = {}): Promise<Pack> {
|
|
24
|
+
const lim: PackLimits = { ...DEFAULT_PACK_LIMITS, ...limits };
|
|
25
|
+
const { header, stored, crc } = readFrame(bytes);
|
|
26
|
+
let body: Uint8Array;
|
|
27
|
+
if (header.flags & FLAG_DEFLATED) {
|
|
28
|
+
try {
|
|
29
|
+
body = await inflateRaw(stored, lim.maxDecodedBytes);
|
|
30
|
+
} catch (error) {
|
|
31
|
+
if (error instanceof PackTooLargeError) throw error;
|
|
32
|
+
throw new PackFormatError('corrupt deflate stream');
|
|
33
|
+
}
|
|
34
|
+
} else {
|
|
35
|
+
if (stored.length > lim.maxDecodedBytes) throw new PackTooLargeError(lim.maxDecodedBytes);
|
|
36
|
+
body = stored;
|
|
37
|
+
}
|
|
38
|
+
if (crc32(body) !== crc) throw new PackFormatError('CRC-32 mismatch');
|
|
39
|
+
try {
|
|
40
|
+
const sections = readSections(body);
|
|
41
|
+
const strings = readStringTable(sections.get(TAG.STR) ?? NONE, lim.maxStrings);
|
|
42
|
+
const hashes = readHashTable(sections.get(TAG.HASH) ?? NONE, lim.maxStrings);
|
|
43
|
+
const used = new Set<string>();
|
|
44
|
+
const base = readTables(strings, hashes);
|
|
45
|
+
const tables = { str: base.str, hash: (i: number) => { const h = base.hash(i); used.add(h); return h; } };
|
|
46
|
+
const pack: Pack = { rootId: header.rootId, baseGeneration: header.baseGeneration, targetDigest: header.targetDigest };
|
|
47
|
+
for (const s of ROW_SECTIONS) {
|
|
48
|
+
const bytes = sections.get(s.tag);
|
|
49
|
+
if (bytes) s.read(bytes, tables, lim, pack);
|
|
50
|
+
}
|
|
51
|
+
const extra = hashes.filter((h) => !used.has(h));
|
|
52
|
+
if (extra.length > 0) pack.hashes = extra;
|
|
53
|
+
return pack;
|
|
54
|
+
} catch (error) {
|
|
55
|
+
if (error instanceof PackFormatError || error instanceof PackTooLargeError) throw error;
|
|
56
|
+
throw new PackFormatError(error instanceof Error ? error.message : 'malformed pack');
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/pack/deflate.ts — `deflate-raw` through `CompressionStream` / `DecompressionStream`, which
|
|
3
|
+
* Node 18+, Cloudflare Workers and browsers all have (PRD 41 A11). Inflation is CAPPED: a stream that
|
|
4
|
+
* produces more than `maxBytes` is cancelled at once, so a bomb never holds more than the cap.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { PackTooLargeError } from './types.js';
|
|
8
|
+
|
|
9
|
+
async function drain(stream: ReadableStream<Uint8Array>, maxBytes: number): Promise<Uint8Array> {
|
|
10
|
+
const reader = stream.getReader();
|
|
11
|
+
const chunks: Uint8Array[] = [];
|
|
12
|
+
let total = 0;
|
|
13
|
+
for (;;) {
|
|
14
|
+
const { done, value } = await reader.read();
|
|
15
|
+
if (done) break;
|
|
16
|
+
total += value.length;
|
|
17
|
+
if (total > maxBytes) { await reader.cancel().catch(() => undefined); throw new PackTooLargeError(maxBytes); }
|
|
18
|
+
chunks.push(value);
|
|
19
|
+
}
|
|
20
|
+
const out = new Uint8Array(total);
|
|
21
|
+
let at = 0;
|
|
22
|
+
for (const c of chunks) { out.set(c, at); at += c.length; }
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function through(data: Uint8Array, transform: { readable: ReadableStream<Uint8Array>; writable: WritableStream<BufferSource> }, maxBytes: number): Promise<Uint8Array> {
|
|
27
|
+
const writer = transform.writable.getWriter();
|
|
28
|
+
// Written without waiting: the reader below must drain it, or a large input would stall on backpressure.
|
|
29
|
+
const wrote = writer.write(data as unknown as BufferSource).then(() => writer.close());
|
|
30
|
+
wrote.catch(() => undefined);
|
|
31
|
+
try {
|
|
32
|
+
return await drain(transform.readable, maxBytes);
|
|
33
|
+
} finally {
|
|
34
|
+
await wrote.catch(() => undefined);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const deflateRaw = (data: Uint8Array): Promise<Uint8Array> =>
|
|
39
|
+
through(data, new CompressionStream('deflate-raw') as never, Number.MAX_SAFE_INTEGER);
|
|
40
|
+
|
|
41
|
+
/** Throws {@link PackTooLargeError} past `maxBytes` of output, and `Error` on a corrupt stream. */
|
|
42
|
+
export const inflateRaw = (data: Uint8Array, maxBytes: number): Promise<Uint8Array> =>
|
|
43
|
+
through(data, new DecompressionStream('deflate-raw') as never, maxBytes);
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/pack/encode.ts — `encodePack` and `normalizePack` (PRD 41 A11).
|
|
3
|
+
*
|
|
4
|
+
* Deterministic: rows are put in canonical order first, the tables are sorted, and every section
|
|
5
|
+
* is written from the same normalized pack, so equal input (in any row order) gives equal bytes.
|
|
6
|
+
* Two passes over the section writers: the first collects every string and hash they use, the
|
|
7
|
+
* second writes real table indexes.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { deflateRaw } from './deflate.js';
|
|
11
|
+
import { FLAG_DEFLATED, writeFrame, writeSection } from './frame.js';
|
|
12
|
+
import { ROW_SECTIONS, TAG } from './sections/index.js';
|
|
13
|
+
import { compare } from './sections/columns.js';
|
|
14
|
+
import { collector, tablesOf, writeHashTable, writeStringTable } from './strings.js';
|
|
15
|
+
import type { Pack, RelationId } from './types.js';
|
|
16
|
+
import { ByteWriter } from './varint.js';
|
|
17
|
+
|
|
18
|
+
const nonEmpty = <T>(xs: readonly T[] | undefined): T[] | undefined => (xs && xs.length > 0 ? [...xs] : undefined);
|
|
19
|
+
const byRelation = (a: RelationId, b: RelationId): number => compare(a.from, b.from) || compare(a.to, b.to) || compare(a.kind, b.kind);
|
|
20
|
+
|
|
21
|
+
/** The hashes the row sections reference (a `have` request's explicit hashes are not among them). */
|
|
22
|
+
function referencedHashes(pack: Pack): Set<string> {
|
|
23
|
+
const col = collector();
|
|
24
|
+
for (const s of ROW_SECTIONS) s.write(pack, col);
|
|
25
|
+
return col.hashes;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The pack in canonical form: rows sorted, empty parts dropped, `hashes` reduced to those no section references. */
|
|
29
|
+
export function normalizePack(pack: Pack): Pack {
|
|
30
|
+
const out: Pack = { rootId: pack.rootId, baseGeneration: pack.baseGeneration, targetDigest: pack.targetDigest };
|
|
31
|
+
const files = nonEmpty(pack.files)?.sort((a, b) => compare(a.path, b.path));
|
|
32
|
+
if (files) out.files = files;
|
|
33
|
+
const extracted = nonEmpty(pack.extracted)?.sort((a, b) => compare(a.hash, b.hash));
|
|
34
|
+
if (extracted) out.extracted = extracted;
|
|
35
|
+
const facts = nonEmpty(pack.facts)?.sort((a, b) => compare(a.key, b.key));
|
|
36
|
+
if (facts) out.facts = facts;
|
|
37
|
+
const relations = nonEmpty(pack.relations)?.sort((a, b) => byRelation(a, b));
|
|
38
|
+
if (relations) out.relations = relations;
|
|
39
|
+
const stale = nonEmpty(pack.stale)?.sort((a, b) => compare(a.sourceRef, b.sourceRef));
|
|
40
|
+
if (stale) out.stale = stale;
|
|
41
|
+
const d = pack.deletes;
|
|
42
|
+
if (d && d.files.length + d.facts.length + d.relations.length > 0) {
|
|
43
|
+
out.deletes = { files: [...d.files].sort(compare), facts: [...d.facts].sort(compare), relations: [...d.relations].sort(byRelation) };
|
|
44
|
+
}
|
|
45
|
+
if (pack.scope) out.scope = pack.scope;
|
|
46
|
+
if (pack.analysis !== undefined) out.analysis = pack.analysis;
|
|
47
|
+
const leaves = nonEmpty(pack.leaves)?.sort((a, b) => compare(a.key, b.key));
|
|
48
|
+
if (leaves) out.leaves = leaves;
|
|
49
|
+
if (pack.buckets) out.buckets = pack.buckets;
|
|
50
|
+
const used = referencedHashes(out);
|
|
51
|
+
const extra = [...new Set(pack.hashes ?? [])].filter((h) => !used.has(h)).sort(compare);
|
|
52
|
+
if (extra.length > 0) out.hashes = extra;
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface EncodeOptions {
|
|
57
|
+
/** Deflate the body (default true). Off, the bytes are the plain columnar form (tests, size comparisons). */
|
|
58
|
+
deflate?: boolean;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function encodePack(input: Pack, opts: EncodeOptions = {}): Promise<Uint8Array> {
|
|
62
|
+
const pack = normalizePack(input);
|
|
63
|
+
const col = collector();
|
|
64
|
+
for (const s of ROW_SECTIONS) s.write(pack, col);
|
|
65
|
+
const tables = tablesOf(col.strings, [...col.hashes, ...(pack.hashes ?? [])]);
|
|
66
|
+
|
|
67
|
+
const body = new ByteWriter();
|
|
68
|
+
writeSection(body, TAG.STR, writeStringTable(tables.strings));
|
|
69
|
+
writeSection(body, TAG.HASH, writeHashTable(tables.hashes));
|
|
70
|
+
for (const s of ROW_SECTIONS) {
|
|
71
|
+
const bytes = s.write(pack, tables);
|
|
72
|
+
if (bytes) writeSection(body, s.tag, bytes);
|
|
73
|
+
}
|
|
74
|
+
const plain = body.finish();
|
|
75
|
+
const deflate = opts.deflate ?? true;
|
|
76
|
+
return writeFrame(
|
|
77
|
+
{ flags: deflate ? FLAG_DEFLATED : 0, rootId: pack.rootId, baseGeneration: pack.baseGeneration, targetDigest: pack.targetDigest },
|
|
78
|
+
plain,
|
|
79
|
+
deflate ? await deflateRaw(plain) : plain,
|
|
80
|
+
);
|
|
81
|
+
}
|
|
Binary file
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/pack/frame.ts — the BFKP v1 frame (PRD 41 A11):
|
|
3
|
+
*
|
|
4
|
+
* magic "BFKP" · version u8 · flags u8 (bit 0 = body deflated) · rootId · baseGeneration varint ·
|
|
5
|
+
* targetDigest (32 raw bytes) · body · trailer: CRC-32 (u32 LE) of the DECODED body
|
|
6
|
+
*
|
|
7
|
+
* The body is sections `{ tag u8, length varint, bytes }`; an unknown tag is skipped.
|
|
8
|
+
* Also: the multi-part split a large pack travels in.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { crc32 } from './crc32.js';
|
|
12
|
+
import { ByteReader, ByteWriter, PackFormatError } from './varint.js';
|
|
13
|
+
|
|
14
|
+
export const MAGIC = [0x42, 0x46, 0x4b, 0x50] as const; // "BFKP"
|
|
15
|
+
export const VERSION = 1;
|
|
16
|
+
export const FLAG_DEFLATED = 1;
|
|
17
|
+
export const KPACK_CONTENT_TYPE = 'application/vnd.builderforce.kpack';
|
|
18
|
+
/** A compressed pack larger than this travels as several parts. */
|
|
19
|
+
export const MAX_PART_BYTES = 8 * 1024 * 1024;
|
|
20
|
+
|
|
21
|
+
export interface FrameHeader { flags: number; rootId: string; baseGeneration: number; targetDigest: string }
|
|
22
|
+
|
|
23
|
+
const hexOf = (b: Uint8Array): string => { let s = ''; for (const x of b) s += (x < 16 ? '0' : '') + x.toString(16); return s; };
|
|
24
|
+
|
|
25
|
+
export function writeFrame(h: FrameHeader, body: Uint8Array, storedBody: Uint8Array): Uint8Array {
|
|
26
|
+
if (!/^[0-9a-f]{64}$/.test(h.targetDigest)) throw new PackFormatError('targetDigest is 64 lowercase hex characters');
|
|
27
|
+
const w = new ByteWriter();
|
|
28
|
+
for (const m of MAGIC) w.u8(m);
|
|
29
|
+
w.u8(VERSION);
|
|
30
|
+
w.u8(h.flags);
|
|
31
|
+
w.str(h.rootId);
|
|
32
|
+
w.varint(h.baseGeneration);
|
|
33
|
+
const raw = new Uint8Array(32);
|
|
34
|
+
for (let i = 0; i < 32; i++) raw[i] = parseInt(h.targetDigest.slice(i * 2, i * 2 + 2), 16);
|
|
35
|
+
w.bytes(raw);
|
|
36
|
+
w.bytes(storedBody);
|
|
37
|
+
w.u32le(crc32(body));
|
|
38
|
+
return w.finish();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Splits a frame into header fields, the stored (possibly deflated) body, and the CRC the trailer claims. */
|
|
42
|
+
export function readFrame(bytes: Uint8Array): { header: FrameHeader; stored: Uint8Array; crc: number } {
|
|
43
|
+
if (bytes.length < 4 + 2 + 1 + 1 + 32 + 4) throw new PackFormatError('truncated frame');
|
|
44
|
+
const r = new ByteReader(bytes);
|
|
45
|
+
for (const m of MAGIC) if (r.u8() !== m) throw new PackFormatError('not a BFKP pack (bad magic)');
|
|
46
|
+
const version = r.u8();
|
|
47
|
+
if (version !== VERSION) throw new PackFormatError(`unsupported BFKP version ${version}`);
|
|
48
|
+
const flags = r.u8();
|
|
49
|
+
const rootId = r.str();
|
|
50
|
+
const baseGeneration = r.varint();
|
|
51
|
+
const targetDigest = hexOf(r.bytes(32));
|
|
52
|
+
if (r.remaining < 4) throw new PackFormatError('truncated frame');
|
|
53
|
+
const stored = r.bytes(r.remaining - 4);
|
|
54
|
+
return { header: { flags, rootId, baseGeneration, targetDigest }, stored, crc: r.u32le() };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function writeSection(w: ByteWriter, tag: number, bytes: Uint8Array): void {
|
|
58
|
+
w.u8(tag);
|
|
59
|
+
w.varint(bytes.length);
|
|
60
|
+
w.bytes(bytes);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The sections of a decoded body by tag (a repeated tag keeps the last); unknown tags are returned too, for the caller to skip. */
|
|
64
|
+
export function readSections(body: Uint8Array): Map<number, Uint8Array> {
|
|
65
|
+
const r = new ByteReader(body);
|
|
66
|
+
const out = new Map<number, Uint8Array>();
|
|
67
|
+
while (!r.done) { const tag = r.u8(); out.set(tag, r.bytes(r.varint())); }
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Cuts a pack into ordered parts of at most `max` bytes. A pack within `max` is one part. */
|
|
72
|
+
export function splitParts(pack: Uint8Array, max: number = MAX_PART_BYTES): Uint8Array[] {
|
|
73
|
+
if (pack.length <= max) return [pack];
|
|
74
|
+
const parts: Uint8Array[] = [];
|
|
75
|
+
for (let at = 0; at < pack.length; at += max) parts.push(pack.subarray(at, Math.min(at + max, pack.length)));
|
|
76
|
+
return parts;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The inverse of {@link splitParts}. */
|
|
80
|
+
export function joinParts(parts: readonly Uint8Array[]): Uint8Array {
|
|
81
|
+
if (parts.length === 1) return parts[0]!;
|
|
82
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
83
|
+
let at = 0;
|
|
84
|
+
for (const p of parts) { out.set(p, at); at += p.length; }
|
|
85
|
+
return out;
|
|
86
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@seanhogg/builderforce-memory/knowledge/pack` — BFKP v1, "Builderforce Knowledge Pack" (PRD 41 A11):
|
|
3
|
+
* the one compact, lossless wire format a client syncs to the server in, and the server expands.
|
|
4
|
+
*
|
|
5
|
+
* Pure TypeScript with no Node APIs (`CompressionStream` is the only runtime dependency): the VS Code
|
|
6
|
+
* host and the API Worker run this same module. There is no second copy of the codec.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export { encodePack, normalizePack, type EncodeOptions } from './encode.js';
|
|
10
|
+
export { decodePack, peekPack } from './decode.js';
|
|
11
|
+
export { KPACK_CONTENT_TYPE, MAX_PART_BYTES, splitParts, joinParts } from './frame.js';
|
|
12
|
+
export { PackFormatError } from './varint.js';
|
|
13
|
+
export { crc32 } from './crc32.js';
|
|
14
|
+
export {
|
|
15
|
+
ZERO_DIGEST, DEFAULT_PACK_LIMITS, PackTooLargeError,
|
|
16
|
+
} from './types.js';
|
|
17
|
+
export type {
|
|
18
|
+
Pack, PackBody, PackFileRow, PackStaleRow, PackDeletes, RelationId, PackExtr, ExtrEntryDiff, ListDiff, ManifestLeaf, PackLimits,
|
|
19
|
+
} from './types.js';
|
|
20
|
+
export { diffEntries, applyEntryDiffs, diffEntry, applyEntryDiff, deepEqual } from './extrDiff.js';
|
|
21
|
+
export {
|
|
22
|
+
MANIFEST_BUCKETS, manifestTree, bucketOf, keyHash, differingBuckets, leafDelta, rootLeaves, rootDigestOf,
|
|
23
|
+
fileLeafKey, factLeafKey, relationLeafKey, factDigest, relationDigest,
|
|
24
|
+
} from './manifest.js';
|
|
25
|
+
export type { ManifestTree, LeafDelta, RootRows } from './manifest.js';
|
|
26
|
+
export { jsonBytesOf } from './jsonSize.js';
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** knowledge/pack/jsonSize.ts — the bytes the same rows would take as JSON: the baseline a pack's size is shown against (PRD 41 A11 rule 6). */
|
|
2
|
+
|
|
3
|
+
import type { Pack } from './types.js';
|
|
4
|
+
|
|
5
|
+
const ENCODER = new TextEncoder();
|
|
6
|
+
|
|
7
|
+
/** UTF-8 bytes of the pack's rows as JSON (frame fields and manifest sections excluded). */
|
|
8
|
+
export function jsonBytesOf(pack: Pack): number {
|
|
9
|
+
const { files, extracted, facts, relations, stale, deletes, scope, analysis } = pack;
|
|
10
|
+
return ENCODER.encode(JSON.stringify({ files, extracted, facts, relations, stale, deletes, scope, analysis })).length;
|
|
11
|
+
}
|