@seanhogg/builderforce-memory 2026.10.43 → 2026.10.44

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.
Files changed (63) hide show
  1. package/dist/knowledge/extractFile.d.ts +15 -0
  2. package/dist/knowledge/extractFile.d.ts.map +1 -1
  3. package/dist/knowledge/extractFile.js +40 -17
  4. package/dist/knowledge/extractFile.js.map +1 -1
  5. package/dist/knowledge/extractJob.d.ts +64 -0
  6. package/dist/knowledge/extractJob.d.ts.map +1 -0
  7. package/dist/knowledge/extractJob.js +47 -0
  8. package/dist/knowledge/extractJob.js.map +1 -0
  9. package/dist/knowledge/index.d.ts +10 -1
  10. package/dist/knowledge/index.d.ts.map +1 -1
  11. package/dist/knowledge/index.js +6 -1
  12. package/dist/knowledge/index.js.map +1 -1
  13. package/dist/knowledge/judge.d.ts +23 -5
  14. package/dist/knowledge/judge.d.ts.map +1 -1
  15. package/dist/knowledge/judge.js +14 -76
  16. package/dist/knowledge/judge.js.map +1 -1
  17. package/dist/knowledge/judgeCalls.d.ts +52 -0
  18. package/dist/knowledge/judgeCalls.d.ts.map +1 -0
  19. package/dist/knowledge/judgeCalls.js +107 -0
  20. package/dist/knowledge/judgeCalls.js.map +1 -0
  21. package/dist/knowledge/modelLimiter.d.ts +20 -0
  22. package/dist/knowledge/modelLimiter.d.ts.map +1 -0
  23. package/dist/knowledge/modelLimiter.js +63 -0
  24. package/dist/knowledge/modelLimiter.js.map +1 -0
  25. package/dist/knowledge/review.d.ts +6 -2
  26. package/dist/knowledge/review.d.ts.map +1 -1
  27. package/dist/knowledge/review.js +108 -112
  28. package/dist/knowledge/review.js.map +1 -1
  29. package/dist/knowledge/reviewJudge.d.ts +95 -0
  30. package/dist/knowledge/reviewJudge.d.ts.map +1 -0
  31. package/dist/knowledge/reviewJudge.js +119 -0
  32. package/dist/knowledge/reviewJudge.js.map +1 -0
  33. package/dist/knowledge/reviewModel.d.ts +30 -2
  34. package/dist/knowledge/reviewModel.d.ts.map +1 -1
  35. package/dist/knowledge/reviewPrefetch.d.ts +53 -0
  36. package/dist/knowledge/reviewPrefetch.d.ts.map +1 -0
  37. package/dist/knowledge/reviewPrefetch.js +65 -0
  38. package/dist/knowledge/reviewPrefetch.js.map +1 -0
  39. package/dist/knowledge/reviewRun.d.ts +70 -0
  40. package/dist/knowledge/reviewRun.d.ts.map +1 -0
  41. package/dist/knowledge/reviewRun.js +88 -0
  42. package/dist/knowledge/reviewRun.js.map +1 -0
  43. package/dist/knowledge/reviewRunModel.d.ts +35 -0
  44. package/dist/knowledge/reviewRunModel.d.ts.map +1 -0
  45. package/dist/knowledge/reviewRunModel.js +27 -0
  46. package/dist/knowledge/reviewRunModel.js.map +1 -0
  47. package/package.json +3 -3
  48. package/src/knowledge/extractFile.ts +49 -17
  49. package/src/knowledge/extractJob.ts +91 -0
  50. package/src/knowledge/index.ts +10 -1
  51. package/src/knowledge/judge.ts +24 -70
  52. package/src/knowledge/judgeCalls.ts +136 -0
  53. package/src/knowledge/modelLimiter.test.ts +68 -0
  54. package/src/knowledge/modelLimiter.ts +68 -0
  55. package/src/knowledge/review.failures.test.ts +277 -0
  56. package/src/knowledge/review.ordered.test.ts +114 -0
  57. package/src/knowledge/review.ts +102 -100
  58. package/src/knowledge/reviewJudge.ts +155 -0
  59. package/src/knowledge/reviewModel.ts +30 -2
  60. package/src/knowledge/reviewPrefetch.ts +86 -0
  61. package/src/knowledge/reviewRun.test.ts +96 -0
  62. package/src/knowledge/reviewRun.ts +137 -0
  63. package/src/knowledge/reviewRunModel.ts +53 -0
@@ -0,0 +1,88 @@
1
+ /**
2
+ * knowledge/reviewRun.ts — the PURE recorder of a review run (PRD 41 A8): fold the events a review
3
+ * emits (`onProgress`, `onStep`, the end) into a {@link ReviewRun} a host can persist and a view can
4
+ * draw — phase timeline, worker lanes, the last steps, every failure, the rate and ETA.
5
+ *
6
+ * No clock, no I/O: every function takes the time it should use, so the reducer is deterministic and a
7
+ * stored run replays the same. The host owns persistence (last N runs per root) and throttling.
8
+ */
9
+ /** How many of the latest steps a run keeps (failures are kept whole). */
10
+ export const REVIEW_RUN_STEP_RING = 200;
11
+ export function startRun(a) {
12
+ return { id: a.id, root: a.root, kind: a.kind, startedAt: a.at, updatedAt: a.at, phases: [], lanes: [], steps: [], failures: [] };
13
+ }
14
+ /** Phases whose progress `done` is the index of the file being reached. */
15
+ const PER_FILE = new Set(['extract', 'judge', 'write']);
16
+ function withProgress(phases, p, at) {
17
+ const done = PER_FILE.has(p.phase) ? p.done + 1 : p.done;
18
+ const i = phases.findIndex((x) => x.phase === p.phase);
19
+ const prior = i < 0 ? undefined : phases[i];
20
+ const next = {
21
+ phase: p.phase, startedAt: prior?.startedAt ?? at, done: Math.max(prior?.done ?? 0, done), total: p.total,
22
+ };
23
+ // Once ended it stays ended (a stale or repeated event never reopens it) unless the total grew past what is done.
24
+ if (p.phase === 'done' || next.done >= next.total)
25
+ next.endedAt = prior?.endedAt ?? at;
26
+ if (i < 0)
27
+ return [...phases, next];
28
+ return phases.map((x, j) => (j === i ? next : x));
29
+ }
30
+ const PHASE_ORDER = ['plan', 'extract', 'resolve', 'judge', 'compare', 'write', 'index', 'done'];
31
+ /** Lanes are keyed by phase and id: extract workers and judge lanes are different workers. */
32
+ function withLane(lanes, step) {
33
+ if (step.lane === undefined)
34
+ return lanes;
35
+ const same = (l) => l.phase === step.phase && l.id === step.lane;
36
+ const prior = lanes.find(same);
37
+ const next = {
38
+ phase: step.phase, id: step.lane, path: step.path, done: (prior?.done ?? 0) + 1, busyMs: (prior?.busyMs ?? 0) + step.ms,
39
+ };
40
+ return [...lanes.filter((l) => !same(l)), next]
41
+ .sort((a, b) => PHASE_ORDER.indexOf(a.phase) - PHASE_ORDER.indexOf(b.phase) || a.id - b.id);
42
+ }
43
+ /** Folds one event into the run; the input run is never mutated. */
44
+ export function applyRunEvent(run, event, at) {
45
+ const base = { ...run, updatedAt: at };
46
+ switch (event.type) {
47
+ case 'progress': {
48
+ const phases = withProgress(run.phases, event.progress, at);
49
+ // A new phase reached: the plan is over (it is never revisited).
50
+ return { ...base, phases: phases.map((p) => (p.phase === 'plan' && p.endedAt === undefined ? { ...p, endedAt: at } : p)) };
51
+ }
52
+ case 'step': {
53
+ const s = event.step;
54
+ return {
55
+ ...base,
56
+ lanes: withLane(run.lanes, s),
57
+ steps: [...run.steps, s].slice(-REVIEW_RUN_STEP_RING),
58
+ failures: s.outcome === 'failed' ? [...run.failures, { path: s.path, phase: s.phase, reason: s.reason ?? 'failed' }] : run.failures,
59
+ };
60
+ }
61
+ case 'end':
62
+ return {
63
+ ...base, endedAt: at, outcome: event.outcome, ...(event.report ? { report: event.report } : {}),
64
+ phases: run.phases.map((p) => (p.endedAt === undefined ? { ...p, endedAt: at } : p)),
65
+ };
66
+ }
67
+ }
68
+ const phaseOf = (run, phase) => run.phases.find((p) => p.phase === phase);
69
+ /** Items per second a phase has sustained so far; 0 when it has not started or no time has passed. */
70
+ export function runRate(run, phase) {
71
+ const p = phaseOf(run, phase);
72
+ if (!p)
73
+ return 0;
74
+ const ms = (p.endedAt ?? run.endedAt ?? run.updatedAt) - p.startedAt;
75
+ return ms > 0 && p.done > 0 ? (p.done * 1000) / ms : 0;
76
+ }
77
+ /** Milliseconds until a phase finishes at its measured rate; 0 when it is complete, undefined when it cannot be told. */
78
+ export function runEta(run, phase) {
79
+ const p = phaseOf(run, phase);
80
+ if (!p)
81
+ return undefined;
82
+ const remaining = p.total - p.done;
83
+ if (remaining <= 0)
84
+ return 0;
85
+ const rate = runRate(run, phase);
86
+ return rate > 0 ? Math.round((remaining / rate) * 1000) : undefined;
87
+ }
88
+ //# sourceMappingURL=reviewRun.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reviewRun.js","sourceRoot":"","sources":["../../src/knowledge/reviewRun.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAQH,0EAA0E;AAC1E,MAAM,CAAC,MAAM,oBAAoB,GAAG,GAAG,CAAC;AA0CxC,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,SAAS,CAAC,GAAG,CAAC,CAAC,SAAS,CAAC;IACrE,OAAO,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;AAC3D,CAAC;AAED,yHAAyH;AACzH,MAAM,UAAU,MAAM,CAAC,GAAc,EAAE,KAAkB;IACrD,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IAC9B,IAAI,CAAC,CAAC;QAAE,OAAO,SAAS,CAAC;IACzB,MAAM,SAAS,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC;IACnC,IAAI,SAAS,IAAI,CAAC;QAAE,OAAO,CAAC,CAAC;IAC7B,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACjC,OAAO,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,SAAS,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AACxE,CAAC"}
@@ -0,0 +1,35 @@
1
+ /**
2
+ * knowledge/reviewRunModel.ts — the vocabulary of a watchable review (PRD 41 A8): phases, the
3
+ * per-file step events a review emits, and the failures it records instead of throwing.
4
+ */
5
+ export type ReviewPhase = 'plan' | 'extract' | 'resolve' | 'judge' | 'compare' | 'write' | 'index' | 'done';
6
+ export type ReviewStepOutcome = 'ok' | 'cached' | 'skipped' | 'failed';
7
+ /**
8
+ * One file in one phase. `cached` = reused prior knowledge or an extract-cache hit; `skipped` = binary
9
+ * or too large; `failed` carries `reason`. `lane` is the worker/lane id (0..width-1) where known.
10
+ */
11
+ export interface ReviewStep {
12
+ path: string;
13
+ phase: ReviewPhase;
14
+ ms: number;
15
+ outcome: ReviewStepOutcome;
16
+ reason?: string;
17
+ lane?: number;
18
+ }
19
+ /** A file a review could not finish: its prior knowledge and manifest hash are kept, so the next review retries it. */
20
+ export interface ReviewFailure {
21
+ path: string;
22
+ phase: ReviewPhase;
23
+ reason: string;
24
+ }
25
+ /** Lane ids 0..width-1 for in-flight work: `take` the lowest free one, `free` it when the work settles. */
26
+ export declare class Lanes {
27
+ private readonly busy;
28
+ private readonly width;
29
+ constructor(width: number);
30
+ take(): number;
31
+ free(id: number): void;
32
+ }
33
+ /** A thrown value as a short, single-line reason. */
34
+ export declare const reasonOf: (error: unknown) => string;
35
+ //# sourceMappingURL=reviewRunModel.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reviewRunModel.d.ts","sourceRoot":"","sources":["../../src/knowledge/reviewRunModel.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,SAAS,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,GAAG,OAAO,GAAG,OAAO,GAAG,MAAM,CAAC;AAE5G,MAAM,MAAM,iBAAiB,GAAG,IAAI,GAAG,QAAQ,GAAG,SAAS,GAAG,QAAQ,CAAC;AAEvE;;;GAGG;AACH,MAAM,WAAW,UAAU;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,WAAW,CAAC;IACnB,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,iBAAiB,CAAC;IAC3B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,uHAAuH;AACvH,MAAM,WAAW,aAAa;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,WAAW,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;CAClB;AAED,2GAA2G;AAC3G,qBAAa,KAAK;IACd,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAqB;IAC1C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;IAE/B,YAAY,KAAK,EAAE,MAAM,EAAyB;IAElD,IAAI,IAAI,MAAM,CAOb;IAED,IAAI,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAA0B;CACnD;AAED,qDAAqD;AACrD,eAAO,MAAM,QAAQ,UAAW,OAAO,KAAG,MAGzC,CAAC"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * knowledge/reviewRunModel.ts — the vocabulary of a watchable review (PRD 41 A8): phases, the
3
+ * per-file step events a review emits, and the failures it records instead of throwing.
4
+ */
5
+ /** Lane ids 0..width-1 for in-flight work: `take` the lowest free one, `free` it when the work settles. */
6
+ export class Lanes {
7
+ busy = new Set();
8
+ width;
9
+ constructor(width) { this.width = width; }
10
+ take() {
11
+ // More work in flight than lanes means the stage that bounds it is broken: say so, never share a lane.
12
+ if (this.busy.size >= this.width)
13
+ throw new Error(`Lanes: invariant violated — all ${this.width} lanes are busy`);
14
+ let id = 0;
15
+ while (this.busy.has(id))
16
+ id += 1;
17
+ this.busy.add(id);
18
+ return id;
19
+ }
20
+ free(id) { this.busy.delete(id); }
21
+ }
22
+ /** A thrown value as a short, single-line reason. */
23
+ export const reasonOf = (error) => {
24
+ const text = error instanceof Error ? error.message : String(error);
25
+ return text.split(/\r?\n/)[0].slice(0, 300) || 'unknown error';
26
+ };
27
+ //# sourceMappingURL=reviewRunModel.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reviewRunModel.js","sourceRoot":"","sources":["../../src/knowledge/reviewRunModel.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA0BH,2GAA2G;AAC3G,MAAM,OAAO,KAAK;IACG,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IACzB,KAAK,CAAS;IAE/B,YAAY,KAAa,IAAI,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC;IAElD,IAAI;QACA,uGAAuG;QACvG,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,KAAK;YAAE,MAAM,IAAI,KAAK,CAAC,mCAAmC,IAAI,CAAC,KAAK,iBAAiB,CAAC,CAAC;QAClH,IAAI,EAAE,GAAG,CAAC,CAAC;QACX,OAAO,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YAAE,EAAE,IAAI,CAAC,CAAC;QAClC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAClB,OAAO,EAAE,CAAC;IACd,CAAC;IAED,IAAI,CAAC,EAAU,IAAU,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;CACnD;AAED,qDAAqD;AACrD,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,KAAc,EAAU,EAAE;IAC/C,MAAM,IAAI,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACpE,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAE,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,eAAe,CAAC;AACpE,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seanhogg/builderforce-memory",
3
- "version": "2026.10.43",
3
+ "version": "2026.10.44",
4
4
  "description": "BuilderForce Agent Memory — runtime layer. SSM execution, Transformer orchestration, online distillation, enterprise RAG (ingestion pipelines, vector-store adapters, tenant/ACL-scoped hybrid retrieval), multi-agent graph orchestration, LLM telemetry and cost accounting, persistent agent memory, and token-saving agent-run memory (code maps, a prompt-cache-safe working memory, chunked transcript windowing) for BuilderForce.ai agents.",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",
@@ -113,7 +113,7 @@
113
113
  },
114
114
  "homepage": "https://github.com/SeanHogg/builderforce-memory/tree/main/packages/memory#readme",
115
115
  "peerDependencies": {
116
- "@seanhogg/builderforce-memory-engine": "^2026.10.43"
116
+ "@seanhogg/builderforce-memory-engine": "^2026.10.44"
117
117
  },
118
118
  "devDependencies": {
119
119
  "@jest/globals": "^29.7.0",
@@ -127,7 +127,7 @@
127
127
  "ts-jest": "^29.2.0",
128
128
  "typescript": "npm:@typescript/typescript6@^6.0.2",
129
129
  "typescript-7": "npm:typescript@^7.0.2",
130
- "@seanhogg/builderforce-memory-engine": "2026.10.43"
130
+ "@seanhogg/builderforce-memory-engine": "2026.10.44"
131
131
  },
132
132
  "jest": {
133
133
  "preset": "ts-jest/presets/default-esm",
@@ -7,8 +7,9 @@
7
7
  */
8
8
 
9
9
  import type { ParsedSection, SourceDocument } from '../ingest/types.js';
10
- import type { ExtractContext, Extracted, KnowledgePack, KnowledgeParser, KnowledgeStore, NodeRef } from './model.js';
11
- import { basenameOf, srcRef } from './refs.js';
10
+ import type { Extracted, KnowledgePack, KnowledgeParser, KnowledgeStore, NodeRef } from './model.js';
11
+ import { jobOf, runExtractor, type ExtractPool } from './extractJob.js';
12
+ import { srcRef } from './refs.js';
12
13
  import { entityName, knownKeysOf, resolveEntities } from './resolve.js';
13
14
  import { asPathSource, composePacks, EXTRACTOR_VERSION, resolveRelativePath, type ComposedPacks } from './sources.js';
14
15
 
@@ -30,6 +31,16 @@ export interface ExtractFileArgs {
30
31
  composed?: ComposedPacks;
31
32
  /** Already known entity keys (a review reads them once); default: the store's `ent:` facts. */
32
33
  knownKeys?: ReadonlyMap<string, NodeRef>;
34
+ /**
35
+ * A host's extraction pool (PRD 41 A8): a cache miss is extracted by `pool(job, signal)` instead of in
36
+ * this thread, which then never parses. The extract cache is still read and written here.
37
+ */
38
+ pool?: ExtractPool;
39
+ signal?: AbortSignal;
40
+ /** With a `pool`: whether the file's pack judges it, i.e. the worker must return its sections (default: never). */
41
+ wantsSections?: (pack: KnowledgePack) => boolean;
42
+ /** Leave the extract cache write to the caller (the review writes it in plan order); default: write it. */
43
+ writeCache?: boolean;
33
44
  }
34
45
 
35
46
  export interface FileExtraction {
@@ -38,6 +49,14 @@ export interface FileExtraction {
38
49
  pack: KnowledgePack;
39
50
  /** The parser's sections of the file (the review judges these). */
40
51
  sections: ParsedSection[];
52
+ /** The extract came from the content-hash cache — nothing was extracted. */
53
+ cached: boolean;
54
+ }
55
+
56
+ /** Adds `extracted` to the content-hash cache, keeping the entries of the other files that share the hash. */
57
+ export async function putExtract(store: KnowledgeStore, hash: string, extracted: Extracted, prior?: readonly Extracted[]): Promise<void> {
58
+ const cached = prior ?? (await store.getExtracted?.(hash)) ?? [];
59
+ await store.putExtracted?.(hash, [...cached.filter((e) => e.sourceRef !== extracted.sourceRef), extracted]);
41
60
  }
42
61
 
43
62
  /** Extraction plus what produced it; undefined when no pack's parser accepts the file. */
@@ -45,26 +64,39 @@ export async function extractFileDetailed(a: ExtractFileArgs): Promise<FileExtra
45
64
  const src = asPathSource(a.doc, a.path, a.hash);
46
65
  const hit = (a.composed ?? composePacks(a.packs)).resolve(src);
47
66
  if (!hit) return undefined;
48
- const sections = hit.parser.parse(src);
49
67
  const ref = srcRef(a.rootId, a.path);
68
+ // With a pool the main thread never parses: the worker returns the sections when the file will be judged.
69
+ const wants = !!a.pool && !!a.wantsSections?.(hit.pack);
70
+ let sections: ParsedSection[] = a.pool ? [] : hit.parser.parse(src);
50
71
  const cached = await a.store.getExtracted?.(a.hash);
51
72
  // A cached entry of another extractor version is ignored: its output may differ from today's.
52
73
  const found = cached?.find((e) => e.sourceRef === ref && e.extractorVersion === EXTRACTOR_VERSION);
53
- if (found) return { extracted: found, parser: hit.parser, pack: hit.pack, sections };
74
+ if (found) {
75
+ if (a.pool && wants) {
76
+ const out = await a.pool(jobOf({ rootId: a.rootId, path: a.path, hash: a.hash, doc: a.doc, knownKeys: new Map(), sectionsOnly: true }), a.signal);
77
+ if (!out.sections) throw new Error(`extract pool returned no sections for ${a.path}`);
78
+ sections = out.sections;
79
+ }
80
+ return { extracted: found, parser: hit.parser, pack: hit.pack, sections, cached: true };
81
+ }
54
82
 
55
- const ctx: ExtractContext = {
56
- rootId: a.rootId,
57
- knownKeys: a.knownKeys ?? knownKeysOfEntities((await a.store.facts({ rootId: a.rootId })).map((f) => f.key)),
58
- resolvePath: resolveRelativePath,
59
- };
60
- const extracted: Extracted = hit.parser.extract
61
- ? { ...hit.parser.extract(src, sections, ctx), sourceHash: a.hash, extractorVersion: EXTRACTOR_VERSION }
62
- : {
63
- sourceRef: ref, sourceHash: a.hash, extractorVersion: EXTRACTOR_VERSION, edges: [], keys: [{ ref, key: a.path }],
64
- nodes: [{ ref, kind: 'file', label: basenameOf(a.path), pack: hit.pack.id, importance: 0, origin: 'extracted', sourceHash: a.hash }],
65
- };
66
- await a.store.putExtracted?.(a.hash, [...(cached ?? []).filter((e) => e.sourceRef !== ref), extracted]);
67
- return { extracted, parser: hit.parser, pack: hit.pack, sections };
83
+ const knownKeys = a.knownKeys ?? knownKeysOfEntities((await a.store.facts({ rootId: a.rootId })).map((f) => f.key));
84
+ let extracted: Extracted;
85
+ if (a.pool) {
86
+ const out = await a.pool(jobOf({ rootId: a.rootId, path: a.path, hash: a.hash, doc: a.doc, knownKeys, needSections: wants }), a.signal);
87
+ // Exact match only: a result for another file, or none although the packs accept this one, is a failure.
88
+ const mine = out.extracted.find((e) => e.sourceRef === ref);
89
+ if (!mine) throw new Error(`extract pool returned no extract for ${a.path}`);
90
+ if (wants) {
91
+ if (!out.sections) throw new Error(`extract pool returned no sections for ${a.path}`);
92
+ sections = out.sections;
93
+ }
94
+ extracted = mine;
95
+ } else {
96
+ extracted = runExtractor(hit, src, sections, { rootId: a.rootId, knownKeys, resolvePath: resolveRelativePath }, a);
97
+ }
98
+ if (a.writeCache !== false) await putExtract(a.store, a.hash, extracted, cached ?? []);
99
+ return { extracted, parser: hit.parser, pack: hit.pack, sections, cached: false };
68
100
  }
69
101
 
70
102
  /**
@@ -0,0 +1,91 @@
1
+ /**
2
+ * knowledge/extractJob.ts — the pure, serializable unit of extraction (PRD 41 A8).
3
+ *
4
+ * An {@link ExtractJob} is plain data (no functions, no store), so it can cross a
5
+ * `worker_threads` boundary: a host's pool posts the job to a worker, the worker calls
6
+ * {@link extractJob} with the packs it loaded itself, and the {@link Extracted} comes back.
7
+ * The in-thread default of `reviewDirectory` runs the very same {@link runExtractor}, so a
8
+ * review with and without `ReviewArgs.extractPool` extracts the same bytes. The extract
9
+ * CACHE (store reads/writes) never crosses the boundary: the review consults it around the pool.
10
+ */
11
+
12
+ import type { ParsedSection, SourceDocument } from '../ingest/types.js';
13
+ import type { ExtractContext, Extracted, KnowledgePack, KnowledgeParser, NodeRef } from './model.js';
14
+ import { basenameOf, srcRef } from './refs.js';
15
+ import { asPathSource, composePacks, EXTRACTOR_VERSION, resolveRelativePath, type ComposedPacks } from './sources.js';
16
+
17
+ /** Everything the extractor needs for one file, as structured-cloneable data. */
18
+ export interface ExtractJob {
19
+ rootId: string;
20
+ /** Root-relative path. */
21
+ path: string;
22
+ /** Content hash of the file. */
23
+ hash: string;
24
+ /** The document as read (plain data). */
25
+ doc: SourceDocument;
26
+ /** The known entity keys (`mentions`), as entries of the review's map. */
27
+ knownKeys: ReadonlyArray<readonly [string, NodeRef]>;
28
+ /** The file will be judged: return its parsed sections too (the main thread never parses when a pool is supplied). */
29
+ needSections?: boolean;
30
+ /** The extract is already cached and only the sections are wanted: skip extracting. Implies `needSections`. */
31
+ sectionsOnly?: boolean;
32
+ }
33
+
34
+ /** What a worker returns: the file's extract(s) — `[]` when no pack accepts it — and, if asked, its sections. */
35
+ export interface ExtractJobResult {
36
+ extracted: Extracted[];
37
+ sections?: ParsedSection[];
38
+ }
39
+
40
+ /**
41
+ * A host's extraction pool: called for a changed file whose extract is not cached (or, with
42
+ * `sectionsOnly`, whose sections are needed). `signal` is the review's: a stopped review should
43
+ * terminate in-flight worker jobs.
44
+ */
45
+ export type ExtractPool = (job: ExtractJob, signal?: AbortSignal) => Promise<ExtractJobResult>;
46
+
47
+ /** The ONE extraction of an already-resolved source: stamps {@link EXTRACTOR_VERSION}. */
48
+ export function runExtractor(
49
+ hit: { parser: KnowledgeParser; pack: KnowledgePack },
50
+ src: SourceDocument,
51
+ sections: ParsedSection[],
52
+ ctx: ExtractContext,
53
+ file: { path: string; hash: string },
54
+ ): Extracted {
55
+ const ref = srcRef(ctx.rootId, file.path);
56
+ return hit.parser.extract
57
+ ? { ...hit.parser.extract(src, sections, ctx), sourceHash: file.hash, extractorVersion: EXTRACTOR_VERSION }
58
+ : {
59
+ sourceRef: ref, sourceHash: file.hash, extractorVersion: EXTRACTOR_VERSION, edges: [], keys: [{ ref, key: file.path }],
60
+ nodes: [{ ref, kind: 'file', label: basenameOf(file.path), pack: hit.pack.id, importance: 0, origin: 'extracted', sourceHash: file.hash }],
61
+ };
62
+ }
63
+
64
+ /** The job as a serializable value for `doc` (what a pool receives). */
65
+ export function jobOf(
66
+ f: {
67
+ rootId: string; path: string; hash: string; doc: SourceDocument; knownKeys: ReadonlyMap<string, NodeRef>;
68
+ needSections?: boolean; sectionsOnly?: boolean;
69
+ },
70
+ ): ExtractJob {
71
+ return {
72
+ rootId: f.rootId, path: f.path, hash: f.hash, doc: f.doc, knownKeys: [...f.knownKeys],
73
+ ...(f.needSections ? { needSections: true } : {}), ...(f.sectionsOnly ? { sectionsOnly: true } : {}),
74
+ };
75
+ }
76
+
77
+ /**
78
+ * Extracts one file from a job — pure: no store, no clock. `extracted` is `[]` when no pack's parser
79
+ * accepts the file. `packs` is the worker's own pack list (or its composition, to compose once).
80
+ */
81
+ export function extractJob(job: ExtractJob, packs: readonly KnowledgePack[] | ComposedPacks): ExtractJobResult {
82
+ const composed = Array.isArray(packs) ? composePacks(packs as readonly KnowledgePack[]) : (packs as ComposedPacks);
83
+ const src = asPathSource(job.doc, job.path, job.hash);
84
+ const hit = composed.resolve(src);
85
+ if (!hit) return { extracted: [] };
86
+ const sections = hit.parser.parse(src);
87
+ const wantSections = job.needSections || job.sectionsOnly;
88
+ if (job.sectionsOnly) return { extracted: [], sections };
89
+ const ctx: ExtractContext = { rootId: job.rootId, knownKeys: new Map(job.knownKeys), resolvePath: resolveRelativePath };
90
+ return { extracted: [runExtractor(hit, src, sections, ctx, job)], ...(wantSections ? { sections } : {}) };
91
+ }
@@ -43,9 +43,18 @@ export type { ExtractorState } from './owedFiles.js';
43
43
  export { reviewDirectory, assertStoredBatch } from './review.js';
44
44
  export { extractFile, extractFileDetailed, knownKeysOfEntities } from './extractFile.js';
45
45
  export type { ExtractFileArgs, FileExtraction } from './extractFile.js';
46
+ export { extractJob, jobOf } from './extractJob.js';
47
+ export type { ExtractJob, ExtractJobResult, ExtractPool } from './extractJob.js';
48
+ export { putExtract } from './extractFile.js';
49
+ export { createModelLimiter, isRateLimit } from './modelLimiter.js';
50
+ export type { ModelLimiter } from './modelLimiter.js';
51
+ export { reasonOf } from './reviewRunModel.js';
52
+ export type { ReviewFailure, ReviewPhase, ReviewStep, ReviewStepOutcome } from './reviewRunModel.js';
53
+ export { startRun, applyRunEvent, runRate, runEta, REVIEW_RUN_STEP_RING } from './reviewRun.js';
54
+ export type { ReviewRun, ReviewRunEvent, ReviewRunKind, ReviewRunLane, ReviewRunOutcome, ReviewRunPhase } from './reviewRun.js';
46
55
  export {
47
56
  validateExtract, validateCompare, clampQuote, clampClaim, MAX_QUOTE_LINES, MAX_QUOTE_CHARS, MAX_CLAIM_TEXT_CHARS,
48
- DEFAULT_REVIEW_MODEL_CALLS, REVIEW_FACT_SOURCE,
57
+ DEFAULT_REVIEW_MODEL_CALLS, DEFAULT_REVIEW_JUDGE_CONCURRENCY, REVIEW_FACT_SOURCE,
49
58
  } from './judge.js';
50
59
  export {
51
60
  composePacks, ignoreMatcher, ignoreSourcesOf, isBinaryPath, isBinaryText, isDocumentPath, mediaTypeOfPath,
@@ -11,17 +11,19 @@
11
11
  * (calls and a deadline) is shared across the whole review.
12
12
  */
13
13
 
14
- import { hashText } from '../ingest/hash.js';
15
14
  import type {
16
15
  JudgedClaim, JudgedEntity, JudgementPort, JudgementResult, NodeRef, StoredFact, StoredRelation,
17
16
  } from './model.js';
18
17
  import type { SimilarPair } from '../retrieval/knowledge-index/types.js';
19
- import { entityKey, normalizeKey } from './resolve.js';
20
- import { compareStr, factRef } from './refs.js';
18
+ import type { ModelLimiter } from './modelLimiter.js';
19
+ import { normalizeKey } from './resolve.js';
20
+ import { compareStr } from './refs.js';
21
21
 
22
22
  export const DEFAULT_REVIEW_MODEL_CALLS = 200;
23
23
  /** How many changed files a review reads + extracts ahead of its (sequential) judge/write stage. */
24
24
  export const DEFAULT_REVIEW_CONCURRENCY = 8;
25
+ /** How many files a review judges at once (writes stay in plan order; PRD 41 A8). */
26
+ export const DEFAULT_REVIEW_JUDGE_CONCURRENCY = 4;
25
27
  export const REVIEW_FACT_SOURCE = 'knowledge-review';
26
28
  const MAX_TERM = 200;
27
29
  const MAX_NAME = 120;
@@ -101,7 +103,7 @@ export const JUDGE_CONCURRENCY = 6;
101
103
  * the pool immediately — in-flight calls keep running but no new work is scheduled, matching the
102
104
  * serial loops' "stop at the first throw" behaviour.
103
105
  */
104
- async function runPool<T>(items: readonly T[], concurrency: number, worker: (item: T) => Promise<void>): Promise<void> {
106
+ export async function runPool<T>(items: readonly T[], concurrency: number, worker: (item: T) => Promise<void>): Promise<void> {
105
107
  let next = 0;
106
108
  let error: Error | null = null;
107
109
  const lanes = Array.from({ length: Math.max(1, Math.min(concurrency, items.length)) }, async () => {
@@ -194,17 +196,32 @@ export function validateCompare(result: unknown, a: NodeRef, b: NodeRef): { rela
194
196
  return { confidence: 0, invalid: Math.max(invalid, 1) };
195
197
  }
196
198
 
197
- /** One model call; `undefined` when the port throws (an abort is re-thrown) — the item was NOT judged. */
198
- async function call(port: JudgementPort, req: Parameters<JudgementPort['judge']>[0], b: JudgeBudget): Promise<{ result: unknown } | undefined> {
199
+ /** What a host of many concurrent calls adds to {@link call}: a shared in-flight cap and a look at each failure. */
200
+ export interface CallHooks {
201
+ limiter?: ModelLimiter;
202
+ onError?(err: unknown): void;
203
+ }
204
+
205
+ /**
206
+ * One model call; `undefined` when the port throws (an abort is re-thrown) — the item was NOT judged.
207
+ * `used` is counted before any wait for the limiter, so the budget cannot be overshot by queued calls.
208
+ */
209
+ export async function call(
210
+ port: JudgementPort, req: Parameters<JudgementPort['judge']>[0], b: JudgeBudget, hooks: CallHooks = {},
211
+ ): Promise<{ result: unknown } | undefined> {
199
212
  b.used += 1;
200
213
  try {
201
- return { result: await port.judge(req) };
214
+ const run = () => port.judge(req);
215
+ return { result: await (hooks.limiter ? hooks.limiter.run(run, req.signal) : run()) };
202
216
  } catch (err) {
203
217
  if (req.signal?.aborted) throw err;
218
+ hooks.onError?.(err);
204
219
  return undefined;
205
220
  }
206
221
  }
207
222
 
223
+ export { judgeSections } from './judgeCalls.js';
224
+
208
225
  export interface SectionToJudge { ref: NodeRef; text: string }
209
226
 
210
227
  export interface ExtractArgs {
@@ -222,69 +239,6 @@ export interface ExtractArgs {
222
239
  onJudged(ref: NodeRef): void;
223
240
  }
224
241
 
225
- /** Judges each section within the budget; the rest — and any whose call failed — are counted `unjudged`. */
226
- export async function judgeSections(a: ExtractArgs): Promise<Array<{ ref: NodeRef; text: string }>> {
227
- const claims: Array<{ ref: NodeRef; text: string }> = [];
228
- const anchor = { path: a.path, contentHash: a.fileHash };
229
- // Judged in a bounded pool: the budget check and `call`'s synchronous `used` increment happen
230
- // on the same tick (no await between), so concurrency cannot overshoot `modelCalls`; the
231
- // batch/entities/onJudged mutations below are synchronous, hence race-free across workers.
232
- // The claims array's order may differ from serial execution — its consumer is order-insensitive.
233
- const abortError = () => a.signal?.reason ?? new Error('aborted');
234
- await runPool(a.sections, JUDGE_CONCURRENCY, async (section) => {
235
- // Honoured per section, not only when the port throws: the caller drops this file whole.
236
- if (a.signal?.aborted) throw abortError();
237
- if (!budgetLeft(a.budget)) { a.batch.unjudged += 1; return; }
238
- const answer = await call(a.port, {
239
- kind: 'extract', items: [{ ref: section.ref, text: section.text, sourceHash: a.fileHash }],
240
- ...(a.signal ? { signal: a.signal } : {}),
241
- }, a.budget);
242
- // A failed call judged nothing: not counted judged, so the file stays changed and is retried.
243
- if (!answer) { a.batch.unjudged += 1; return; }
244
- // The abort can land while a call is in flight (the port sees the signal): a section that
245
- // finished after the abort must not count as judged, or the caller would not re-judge it.
246
- if (a.signal?.aborted) throw abortError();
247
- const v = validateExtract(answer.result, section.ref);
248
- a.batch.invalid += v.invalid;
249
- a.batch.judged += 1;
250
- a.onJudged(section.ref);
251
- const rel = (from: NodeRef, to: NodeRef, kind: string) =>
252
- a.batch.relation({ from, to, kind, weight: 1, origin: 'model', sourceHash: a.fileHash });
253
-
254
- const entityRefs = new Map<string, NodeRef>();
255
- for (const e of v.entities) {
256
- const key = entityKey(a.pack, e.name);
257
- const prior = a.entities.get(key);
258
- const anchors = [...(prior?.fileAnchors ?? []).filter((x) => x.path !== a.path), anchor]
259
- .sort((x, y) => compareStr(x.path, y.path));
260
- const fact: StoredFact = {
261
- key, content: prior?.content ?? `${e.name} (${e.type})`, source: REVIEW_FACT_SOURCE,
262
- importance: prior?.importance ?? 0.5, origin: prior?.origin ?? 'model', fileAnchors: anchors,
263
- };
264
- a.entities.set(key, fact);
265
- a.batch.fact(fact);
266
- entityRefs.set(normalizeKey(e.name), key);
267
- rel(section.ref, key, 'mentions');
268
- }
269
- for (const c of v.claims) {
270
- const key = `claim:${hashText([section.ref, c.subject, c.predicate, c.object].join('\u0000'))}`;
271
- const text = `${c.subject} ${c.predicate} ${c.object}`;
272
- a.batch.fact({
273
- key, content: claimContent(text, c.quote), source: REVIEW_FACT_SOURCE,
274
- importance: 0.5, origin: 'model', fileAnchors: [anchor],
275
- });
276
- const ref = factRef(key);
277
- rel(ref, section.ref, 'about');
278
- for (const term of [c.subject, c.object]) {
279
- const ent = entityRefs.get(normalizeKey(term));
280
- if (ent) rel(ref, ent, 'mentions');
281
- }
282
- claims.push({ ref, text });
283
- }
284
- });
285
- return claims;
286
- }
287
-
288
242
  export interface CompareArgs {
289
243
  port: JudgementPort;
290
244
  pairs: readonly SimilarPair[];