@seanhogg/builderforce-memory 2026.10.43 → 2026.10.45

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 (85) hide show
  1. package/dist/knowledge/build.d.ts.map +1 -1
  2. package/dist/knowledge/build.js +28 -2
  3. package/dist/knowledge/build.js.map +1 -1
  4. package/dist/knowledge/extractFile.d.ts +15 -0
  5. package/dist/knowledge/extractFile.d.ts.map +1 -1
  6. package/dist/knowledge/extractFile.js +40 -17
  7. package/dist/knowledge/extractFile.js.map +1 -1
  8. package/dist/knowledge/extractJob.d.ts +64 -0
  9. package/dist/knowledge/extractJob.d.ts.map +1 -0
  10. package/dist/knowledge/extractJob.js +47 -0
  11. package/dist/knowledge/extractJob.js.map +1 -0
  12. package/dist/knowledge/findings.d.ts.map +1 -1
  13. package/dist/knowledge/findings.js +9 -1
  14. package/dist/knowledge/findings.js.map +1 -1
  15. package/dist/knowledge/index.d.ts +12 -2
  16. package/dist/knowledge/index.d.ts.map +1 -1
  17. package/dist/knowledge/index.js +7 -1
  18. package/dist/knowledge/index.js.map +1 -1
  19. package/dist/knowledge/judge.d.ts +23 -5
  20. package/dist/knowledge/judge.d.ts.map +1 -1
  21. package/dist/knowledge/judge.js +14 -76
  22. package/dist/knowledge/judge.js.map +1 -1
  23. package/dist/knowledge/judgeCalls.d.ts +52 -0
  24. package/dist/knowledge/judgeCalls.d.ts.map +1 -0
  25. package/dist/knowledge/judgeCalls.js +107 -0
  26. package/dist/knowledge/judgeCalls.js.map +1 -0
  27. package/dist/knowledge/model.d.ts +57 -0
  28. package/dist/knowledge/model.d.ts.map +1 -1
  29. package/dist/knowledge/modelLimiter.d.ts +20 -0
  30. package/dist/knowledge/modelLimiter.d.ts.map +1 -0
  31. package/dist/knowledge/modelLimiter.js +63 -0
  32. package/dist/knowledge/modelLimiter.js.map +1 -0
  33. package/dist/knowledge/outline.d.ts.map +1 -1
  34. package/dist/knowledge/outline.js +14 -1
  35. package/dist/knowledge/outline.js.map +1 -1
  36. package/dist/knowledge/review.d.ts +6 -2
  37. package/dist/knowledge/review.d.ts.map +1 -1
  38. package/dist/knowledge/review.js +108 -112
  39. package/dist/knowledge/review.js.map +1 -1
  40. package/dist/knowledge/reviewJudge.d.ts +95 -0
  41. package/dist/knowledge/reviewJudge.d.ts.map +1 -0
  42. package/dist/knowledge/reviewJudge.js +119 -0
  43. package/dist/knowledge/reviewJudge.js.map +1 -0
  44. package/dist/knowledge/reviewModel.d.ts +30 -2
  45. package/dist/knowledge/reviewModel.d.ts.map +1 -1
  46. package/dist/knowledge/reviewPrefetch.d.ts +53 -0
  47. package/dist/knowledge/reviewPrefetch.d.ts.map +1 -0
  48. package/dist/knowledge/reviewPrefetch.js +65 -0
  49. package/dist/knowledge/reviewPrefetch.js.map +1 -0
  50. package/dist/knowledge/reviewRun.d.ts +70 -0
  51. package/dist/knowledge/reviewRun.d.ts.map +1 -0
  52. package/dist/knowledge/reviewRun.js +88 -0
  53. package/dist/knowledge/reviewRun.js.map +1 -0
  54. package/dist/knowledge/reviewRunModel.d.ts +35 -0
  55. package/dist/knowledge/reviewRunModel.d.ts.map +1 -0
  56. package/dist/knowledge/reviewRunModel.js +27 -0
  57. package/dist/knowledge/reviewRunModel.js.map +1 -0
  58. package/dist/knowledge/systems.d.ts +18 -0
  59. package/dist/knowledge/systems.d.ts.map +1 -0
  60. package/dist/knowledge/systems.js +29 -0
  61. package/dist/knowledge/systems.js.map +1 -0
  62. package/package.json +3 -3
  63. package/src/knowledge/build.ts +25 -3
  64. package/src/knowledge/extractFile.ts +49 -17
  65. package/src/knowledge/extractJob.ts +91 -0
  66. package/src/knowledge/findings.ts +9 -1
  67. package/src/knowledge/index.ts +12 -1
  68. package/src/knowledge/judge.ts +24 -70
  69. package/src/knowledge/judgeCalls.ts +136 -0
  70. package/src/knowledge/model.ts +49 -0
  71. package/src/knowledge/modelLimiter.test.ts +68 -0
  72. package/src/knowledge/modelLimiter.ts +68 -0
  73. package/src/knowledge/outline.test.ts +50 -0
  74. package/src/knowledge/outline.ts +15 -1
  75. package/src/knowledge/review.failures.test.ts +277 -0
  76. package/src/knowledge/review.ordered.test.ts +114 -0
  77. package/src/knowledge/review.ts +102 -100
  78. package/src/knowledge/reviewJudge.ts +155 -0
  79. package/src/knowledge/reviewModel.ts +30 -2
  80. package/src/knowledge/reviewPrefetch.ts +86 -0
  81. package/src/knowledge/reviewRun.test.ts +96 -0
  82. package/src/knowledge/reviewRun.ts +137 -0
  83. package/src/knowledge/reviewRunModel.ts +53 -0
  84. package/src/knowledge/systems.test.ts +107 -0
  85. package/src/knowledge/systems.ts +32 -0
@@ -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"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * knowledge/systems.ts — which system (and app) a root-relative path belongs to (PRD 41 A9).
3
+ *
4
+ * Memory does not DETECT systems (that reads manifests and `.git` folders: the host's job); it
5
+ * is handed the detected {@link GraphSystem}s and stamps every file node with its placement, so
6
+ * edges between two systems can be told from edges inside one. Pure and deterministic.
7
+ */
8
+ import type { GraphSystem, KNode } from './model.js';
9
+ export interface SystemPlacement {
10
+ system: string;
11
+ app?: string;
12
+ copyOf?: string;
13
+ }
14
+ /** The deepest system containing `path` (a system at '' contains every path), with its deepest app and copy mark; undefined when none does. */
15
+ export declare function placeInSystem(systems: readonly GraphSystem[], path: string): SystemPlacement | undefined;
16
+ /** Whether an edge between two nodes crosses systems: both are placed, and in different ones. */
17
+ export declare function crossesSystems(from: Pick<KNode, 'system'>, to: Pick<KNode, 'system'>): boolean;
18
+ //# sourceMappingURL=systems.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"systems.d.ts","sourceRoot":"","sources":["../../src/knowledge/systems.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAIrD,MAAM,WAAW,eAAe;IAAG,MAAM,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE;AAElF,+IAA+I;AAC/I,wBAAgB,aAAa,CAAC,OAAO,EAAE,SAAS,WAAW,EAAE,EAAE,IAAI,EAAE,MAAM,GAAG,eAAe,GAAG,SAAS,CAWxG;AAED,iGAAiG;AACjG,wBAAgB,cAAc,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,EAAE,QAAQ,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,KAAK,EAAE,QAAQ,CAAC,GAAG,OAAO,CAE9F"}
@@ -0,0 +1,29 @@
1
+ /**
2
+ * knowledge/systems.ts — which system (and app) a root-relative path belongs to (PRD 41 A9).
3
+ *
4
+ * Memory does not DETECT systems (that reads manifests and `.git` folders: the host's job); it
5
+ * is handed the detected {@link GraphSystem}s and stamps every file node with its placement, so
6
+ * edges between two systems can be told from edges inside one. Pure and deterministic.
7
+ */
8
+ const within = (path, folder) => folder === '' || path === folder || path.startsWith(`${folder}/`);
9
+ /** The deepest system containing `path` (a system at '' contains every path), with its deepest app and copy mark; undefined when none does. */
10
+ export function placeInSystem(systems, path) {
11
+ let best;
12
+ for (const s of systems) {
13
+ if (within(path, s.path) && (!best || s.path.length > best.path.length))
14
+ best = s;
15
+ }
16
+ if (!best)
17
+ return undefined;
18
+ let app;
19
+ for (const a of best.apps) {
20
+ if (a.path !== '' && within(path, a.path) && (app === undefined || a.path.length > app.length))
21
+ app = a.path;
22
+ }
23
+ return { system: best.path, ...(app !== undefined ? { app } : {}), ...(best.copyOf !== undefined ? { copyOf: best.copyOf } : {}) };
24
+ }
25
+ /** Whether an edge between two nodes crosses systems: both are placed, and in different ones. */
26
+ export function crossesSystems(from, to) {
27
+ return from.system !== undefined && to.system !== undefined && from.system !== to.system;
28
+ }
29
+ //# sourceMappingURL=systems.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"systems.js","sourceRoot":"","sources":["../../src/knowledge/systems.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH,MAAM,MAAM,GAAG,CAAC,IAAY,EAAE,MAAc,EAAW,EAAE,CAAC,MAAM,KAAK,EAAE,IAAI,IAAI,KAAK,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,MAAM,GAAG,CAAC,CAAC;AAI5H,+IAA+I;AAC/I,MAAM,UAAU,aAAa,CAAC,OAA+B,EAAE,IAAY;IACvE,IAAI,IAA6B,CAAC;IAClC,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACtB,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC;YAAE,IAAI,GAAG,CAAC,CAAC;IACtF,CAAC;IACD,IAAI,CAAC,IAAI;QAAE,OAAO,SAAS,CAAC;IAC5B,IAAI,GAAuB,CAAC;IAC5B,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;QACxB,IAAI,CAAC,CAAC,IAAI,KAAK,EAAE,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,KAAK,SAAS,IAAI,CAAC,CAAC,IAAI,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC;YAAE,GAAG,GAAG,CAAC,CAAC,IAAI,CAAC;IACjH,CAAC;IACD,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,IAAI,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;AACvI,CAAC;AAED,iGAAiG;AACjG,MAAM,UAAU,cAAc,CAAC,IAA2B,EAAE,EAAyB;IACjF,OAAO,IAAI,CAAC,MAAM,KAAK,SAAS,IAAI,EAAE,CAAC,MAAM,KAAK,SAAS,IAAI,IAAI,CAAC,MAAM,KAAK,EAAE,CAAC,MAAM,CAAC;AAC7F,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.45",
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.45"
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.45"
131
131
  },
132
132
  "jest": {
133
133
  "preset": "ts-jest/presets/default-esm",
@@ -17,9 +17,10 @@
17
17
  import { areaOfPath } from '../working/codemapAreas.js';
18
18
  import { sha256Hex } from '../retrieval/knowledge-index/sha256.js';
19
19
  import type {
20
- BuildGraphInput, BuildGraphOptions, Extracted, KEdge, KNode, KnowledgeGraph, NodeRef,
20
+ BuildGraphInput, BuildGraphOptions, Extracted, GraphSystem, KEdge, KNode, KnowledgeGraph, NodeRef,
21
21
  PartitionRegistry, StoredFact,
22
22
  } from './model.js';
23
+ import { crossesSystems, placeInSystem } from './systems.js';
23
24
  import { computeFindings } from './findings.js';
24
25
  import { pageRank } from './importance.js';
25
26
  import { loadPartitions, partitionOf, verdictOf } from './partitions.js';
@@ -52,9 +53,17 @@ export function graphDigest(input: BuildGraphInput): string {
52
53
  runFiles: nonEmpty(input.live.runFiles) && [...input.live.runFiles!].sort(compareStr),
53
54
  },
54
55
  nearDuplicates: nonEmpty(input.nearDuplicates) && sortBy(input.nearDuplicates!, (p) => p.a, (p) => p.b),
56
+ systems: nonEmpty(input.systems) && sortBy(input.systems!, (s) => s.path),
55
57
  }));
56
58
  }
57
59
 
60
+ /** The systems with the file nodes each holds (the graph's own count, before any cut). */
61
+ function systemsMeta(systems: readonly GraphSystem[], nodes: readonly KNode[]): GraphSystem[] {
62
+ const files = new Map<string, number>();
63
+ for (const n of nodes) if (n.kind === 'file' && n.system !== undefined) files.set(n.system, (files.get(n.system) ?? 0) + 1);
64
+ return systems.map((s) => ({ ...s, files: files.get(s.path) ?? 0 }));
65
+ }
66
+
58
67
  /** An absent list and an empty list mean the same input, so they hash the same. */
59
68
  const nonEmpty = (xs: readonly unknown[] | undefined): boolean | undefined => (xs && xs.length > 0) || undefined;
60
69
 
@@ -180,7 +189,8 @@ export function buildGraph(input: BuildGraphInput, opts: BuildGraphOptions = {})
180
189
  const changed = applyLive(input, g);
181
190
  closeEndpoints(g);
182
191
  const registries = new Map(input.packs.map((p) => [p.id, loadPartitions(p)] as const));
183
- placeNodes(rootId, g, registries);
192
+ const systems = [...(input.systems ?? [])].sort((a, b) => compareStr(a.path, b.path));
193
+ placeNodes(rootId, g, registries, systems);
184
194
 
185
195
  const rank = pageRank([...g.nodes.keys()], [...g.edges.values()]);
186
196
  for (const n of g.nodes.values()) n.importance = rank.get(n.ref) ?? 0;
@@ -191,6 +201,7 @@ export function buildGraph(input: BuildGraphInput, opts: BuildGraphOptions = {})
191
201
  const full: KnowledgeGraph = {
192
202
  scope: { rootId, packs, digest: graphDigest(input) },
193
203
  nodes: allNodes, edges: allEdges, findings: [],
204
+ ...(systems.length > 0 ? { meta: { systems: systemsMeta(systems, allNodes) } } : {}),
194
205
  stats: { sources: sources.size, nodes: allNodes.length, edges: allEdges.length, stale: 0, truncated: false },
195
206
  };
196
207
  full.findings = computeFindings(full, input.packs, registries, input.nearDuplicates ?? []);
@@ -255,7 +266,7 @@ function closeEndpoints(g: GraphBuilder): void {
255
266
  }
256
267
  }
257
268
 
258
- function placeNodes(rootId: string, g: GraphBuilder, registries: Map<string, PartitionRegistry>): void {
269
+ function placeNodes(rootId: string, g: GraphBuilder, registries: Map<string, PartitionRegistry>, systems: readonly GraphSystem[]): void {
259
270
  for (const n of g.nodes.values()) {
260
271
  const path = pathOfRef(n.ref);
261
272
  if (path === undefined) continue;
@@ -265,11 +276,19 @@ function placeNodes(rootId: string, g: GraphBuilder, registries: Map<string, Par
265
276
  if (partition !== undefined) n.partition = partition;
266
277
  const area = areaOfPath(path);
267
278
  if (area) n.area = srcRef(rootId, area);
279
+ const placed = n.kind === 'file' && systems.length > 0 ? placeInSystem(systems, path) : undefined;
280
+ if (placed) {
281
+ n.system = placed.system;
282
+ if (placed.app !== undefined) n.app = placed.app;
283
+ if (placed.copyOf !== undefined) n.copyOf = placed.copyOf;
284
+ }
268
285
  }
269
286
  for (const e of g.edges.values()) {
270
287
  const from = g.nodes.get(e.from), to = g.nodes.get(e.to);
271
288
  const reg = from && registries.get(from.pack);
272
289
  if (!from || !to || !reg || from.pack !== to.pack) continue;
290
+ // Layers are a system's own: a reference into another system is neither upward nor skipping.
291
+ if (crossesSystems(from, to)) continue;
273
292
  const verdict = verdictOf(from.partition, to.partition, reg);
274
293
  if (verdict) e.verdict = verdict;
275
294
  }
@@ -283,6 +302,9 @@ function finalNode(n: KNode): KNode {
283
302
  ref: n.ref, kind: n.kind, label: n.label, pack: n.pack,
284
303
  ...(n.partition !== undefined ? { partition: n.partition } : {}),
285
304
  ...(n.area !== undefined ? { area: n.area } : {}),
305
+ ...(n.system !== undefined ? { system: n.system } : {}),
306
+ ...(n.app !== undefined ? { app: n.app } : {}),
307
+ ...(n.copyOf !== undefined ? { copyOf: n.copyOf } : {}),
286
308
  importance: n.importance, origin: n.origin,
287
309
  ...(n.sourceHash !== undefined ? { sourceHash: n.sourceHash } : {}),
288
310
  ...(n.stale ? { stale: true } : {}),
@@ -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
+ }
@@ -12,7 +12,7 @@ import { hashText } from '../ingest/hash.js';
12
12
  import type { EdgeVerdict, Finding, KEdge, KNode, KnowledgeGraph, KnowledgePack, NodeRef, PartitionRegistry } from './model.js';
13
13
  import type { SimilarPair } from '../retrieval/knowledge-index/types.js';
14
14
  import { possibleSameFindings } from './resolve.js';
15
- import { aboutTargets, compareStr, round6 } from './refs.js';
15
+ import { aboutTargets, compareStr, round6, srcRef } from './refs.js';
16
16
 
17
17
  /** Node badge naming the clone group (e.g. a jscpd issue id) its `duplicate` edges belong to. */
18
18
  export const CLONE_GROUP_BADGE = 'cloneGroup';
@@ -116,6 +116,14 @@ export function genericFindings(g: KnowledgeGraph, registries: ReadonlyMap<strin
116
116
  }
117
117
  }
118
118
 
119
+ // A copy of another system in the same root (PRD 41 A9): its refs name the two systems' folders.
120
+ for (const s of g.meta?.systems ?? []) {
121
+ if (s.copyOf === undefined) continue;
122
+ out.push(finding('duplicate-copy', 'memory', [srcRef(g.scope.rootId, s.path), srcRef(g.scope.rootId, s.copyOf)], 'warn', {
123
+ copy: s.path, original: s.copyOf, similarity: s.copySimilarity ?? 1, reason: s.copyReason ?? 'later-name',
124
+ }, [s.path, s.copyOf]));
125
+ }
126
+
119
127
  for (const [pack, reg] of [...registries].sort((a, b) => compareStr(a[0], b[0]))) {
120
128
  if (!reg.allow) continue;
121
129
  const files = g.nodes.filter((n) => n.pack === pack && n.kind === 'file');
@@ -12,6 +12,7 @@ export type {
12
12
  JudgementPort, AnalyzerPort, KnowledgeParser, KnowledgePack, StoredFact, StoredRelation, Scope, ScopeRecord,
13
13
  KnowledgeStore, DirectorySource, LiveOverlay, KnowledgeGraph, ReviewPlan, ReviewProgress, ReviewReport,
14
14
  ReviewArgs, BuildGraphInput, BuildGraphOptions, TraceStep, Trace, GraphOutline, OutlineFile,
15
+ GraphSystem, GraphApp, GraphReadSkip,
15
16
  } from './model.js';
16
17
  export {
17
18
  buildOutline, outlineOf, outlineRef, OUTLINE_MAX_FILES, OUTLINE_MAX_LINKS, OUTLINE_BADGE_KEYS, OUTLINE_VERDICTS, OUTLINE_FLAG_CYCLE,
@@ -19,6 +20,7 @@ export {
19
20
  export { EXTERNAL_SERVICE_IDS, type ExternalServiceId } from './externals.js';
20
21
 
21
22
  export { buildGraph, graphDigest, oneLineLabel, DEFAULT_MAX_NODES, MAX_NODES_CAP } from './build.js';
23
+ export { placeInSystem, crossesSystems, type SystemPlacement } from './systems.js';
22
24
  export { truncateGraph, TRUNCATION_HARD_CAP, UNANCHORED_AREA } from './truncate.js';
23
25
  export type { TruncateOptions } from './truncate.js';
24
26
  export { pageRank, byImportance, areaImportance, PAGERANK_DAMPING, PAGERANK_ITERATIONS } from './importance.js';
@@ -43,9 +45,18 @@ export type { ExtractorState } from './owedFiles.js';
43
45
  export { reviewDirectory, assertStoredBatch } from './review.js';
44
46
  export { extractFile, extractFileDetailed, knownKeysOfEntities } from './extractFile.js';
45
47
  export type { ExtractFileArgs, FileExtraction } from './extractFile.js';
48
+ export { extractJob, jobOf } from './extractJob.js';
49
+ export type { ExtractJob, ExtractJobResult, ExtractPool } from './extractJob.js';
50
+ export { putExtract } from './extractFile.js';
51
+ export { createModelLimiter, isRateLimit } from './modelLimiter.js';
52
+ export type { ModelLimiter } from './modelLimiter.js';
53
+ export { reasonOf } from './reviewRunModel.js';
54
+ 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';
46
57
  export {
47
58
  validateExtract, validateCompare, clampQuote, clampClaim, MAX_QUOTE_LINES, MAX_QUOTE_CHARS, MAX_CLAIM_TEXT_CHARS,
48
- DEFAULT_REVIEW_MODEL_CALLS, REVIEW_FACT_SOURCE,
59
+ DEFAULT_REVIEW_MODEL_CALLS, DEFAULT_REVIEW_JUDGE_CONCURRENCY, REVIEW_FACT_SOURCE,
49
60
  } from './judge.js';
50
61
  export {
51
62
  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[];