@seanhogg/builderforce-memory 2026.10.44 → 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.
Files changed (190) hide show
  1. package/dist/knowledge/build.d.ts.map +1 -1
  2. package/dist/knowledge/build.js +34 -2
  3. package/dist/knowledge/build.js.map +1 -1
  4. package/dist/knowledge/extractFile.d.ts +9 -1
  5. package/dist/knowledge/extractFile.d.ts.map +1 -1
  6. package/dist/knowledge/extractFile.js +22 -5
  7. package/dist/knowledge/extractFile.js.map +1 -1
  8. package/dist/knowledge/extractJob.d.ts +30 -5
  9. package/dist/knowledge/extractJob.d.ts.map +1 -1
  10. package/dist/knowledge/extractJob.js +9 -1
  11. package/dist/knowledge/extractJob.js.map +1 -1
  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 +7 -4
  16. package/dist/knowledge/index.d.ts.map +1 -1
  17. package/dist/knowledge/index.js +3 -1
  18. package/dist/knowledge/index.js.map +1 -1
  19. package/dist/knowledge/jobDeadline.d.ts +17 -0
  20. package/dist/knowledge/jobDeadline.d.ts.map +1 -0
  21. package/dist/knowledge/jobDeadline.js +46 -0
  22. package/dist/knowledge/jobDeadline.js.map +1 -0
  23. package/dist/knowledge/judgeCalls.d.ts +16 -0
  24. package/dist/knowledge/judgeCalls.d.ts.map +1 -1
  25. package/dist/knowledge/judgeCalls.js +20 -1
  26. package/dist/knowledge/judgeCalls.js.map +1 -1
  27. package/dist/knowledge/judgePriority.d.ts +22 -0
  28. package/dist/knowledge/judgePriority.d.ts.map +1 -0
  29. package/dist/knowledge/judgePriority.js +28 -0
  30. package/dist/knowledge/judgePriority.js.map +1 -0
  31. package/dist/knowledge/model.d.ts +57 -0
  32. package/dist/knowledge/model.d.ts.map +1 -1
  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/pack/crc32.d.ts +3 -0
  37. package/dist/knowledge/pack/crc32.d.ts.map +1 -0
  38. package/dist/knowledge/pack/crc32.js +18 -0
  39. package/dist/knowledge/pack/crc32.js.map +1 -0
  40. package/dist/knowledge/pack/decode.d.ts +14 -0
  41. package/dist/knowledge/pack/decode.d.ts.map +1 -0
  42. package/dist/knowledge/pack/decode.js +64 -0
  43. package/dist/knowledge/pack/decode.js.map +1 -0
  44. package/dist/knowledge/pack/deflate.d.ts +9 -0
  45. package/dist/knowledge/pack/deflate.d.ts.map +1 -0
  46. package/dist/knowledge/pack/deflate.js +45 -0
  47. package/dist/knowledge/pack/deflate.js.map +1 -0
  48. package/dist/knowledge/pack/encode.d.ts +17 -0
  49. package/dist/knowledge/pack/encode.d.ts.map +1 -0
  50. package/dist/knowledge/pack/encode.js +79 -0
  51. package/dist/knowledge/pack/encode.js.map +1 -0
  52. package/dist/knowledge/pack/extrDiff.d.ts +23 -0
  53. package/dist/knowledge/pack/extrDiff.d.ts.map +1 -0
  54. package/dist/knowledge/pack/extrDiff.js +0 -0
  55. package/dist/knowledge/pack/extrDiff.js.map +1 -0
  56. package/dist/knowledge/pack/frame.d.ts +37 -0
  57. package/dist/knowledge/pack/frame.d.ts.map +1 -0
  58. package/dist/knowledge/pack/frame.js +94 -0
  59. package/dist/knowledge/pack/frame.js.map +1 -0
  60. package/dist/knowledge/pack/index.d.ts +19 -0
  61. package/dist/knowledge/pack/index.d.ts.map +1 -0
  62. package/dist/knowledge/pack/index.js +17 -0
  63. package/dist/knowledge/pack/index.js.map +1 -0
  64. package/dist/knowledge/pack/jsonSize.d.ts +5 -0
  65. package/dist/knowledge/pack/jsonSize.d.ts.map +1 -0
  66. package/dist/knowledge/pack/jsonSize.js +8 -0
  67. package/dist/knowledge/pack/jsonSize.js.map +1 -0
  68. package/dist/knowledge/pack/manifest.d.ts +66 -0
  69. package/dist/knowledge/pack/manifest.d.ts.map +1 -0
  70. package/dist/knowledge/pack/manifest.js +104 -0
  71. package/dist/knowledge/pack/manifest.js.map +1 -0
  72. package/dist/knowledge/pack/sections/columns.d.ts +32 -0
  73. package/dist/knowledge/pack/sections/columns.d.ts.map +1 -0
  74. package/dist/knowledge/pack/sections/columns.js +53 -0
  75. package/dist/knowledge/pack/sections/columns.js.map +1 -0
  76. package/dist/knowledge/pack/sections/extr.d.ts +8 -0
  77. package/dist/knowledge/pack/sections/extr.d.ts.map +1 -0
  78. package/dist/knowledge/pack/sections/extr.js +99 -0
  79. package/dist/knowledge/pack/sections/extr.js.map +1 -0
  80. package/dist/knowledge/pack/sections/extrLists.d.ts +23 -0
  81. package/dist/knowledge/pack/sections/extrLists.d.ts.map +1 -0
  82. package/dist/knowledge/pack/sections/extrLists.js +194 -0
  83. package/dist/knowledge/pack/sections/extrLists.js.map +1 -0
  84. package/dist/knowledge/pack/sections/facts.d.ts +8 -0
  85. package/dist/knowledge/pack/sections/facts.d.ts.map +1 -0
  86. package/dist/knowledge/pack/sections/facts.js +167 -0
  87. package/dist/knowledge/pack/sections/facts.js.map +1 -0
  88. package/dist/knowledge/pack/sections/index.d.ts +6 -0
  89. package/dist/knowledge/pack/sections/index.d.ts.map +1 -0
  90. package/dist/knowledge/pack/sections/index.js +9 -0
  91. package/dist/knowledge/pack/sections/index.js.map +1 -0
  92. package/dist/knowledge/pack/sections/rows.d.ts +31 -0
  93. package/dist/knowledge/pack/sections/rows.d.ts.map +1 -0
  94. package/dist/knowledge/pack/sections/rows.js +226 -0
  95. package/dist/knowledge/pack/sections/rows.js.map +1 -0
  96. package/dist/knowledge/pack/strings.d.ts +39 -0
  97. package/dist/knowledge/pack/strings.d.ts.map +1 -0
  98. package/dist/knowledge/pack/strings.js +115 -0
  99. package/dist/knowledge/pack/strings.js.map +1 -0
  100. package/dist/knowledge/pack/types.d.ts +109 -0
  101. package/dist/knowledge/pack/types.d.ts.map +1 -0
  102. package/dist/knowledge/pack/types.js +17 -0
  103. package/dist/knowledge/pack/types.js.map +1 -0
  104. package/dist/knowledge/pack/varint.d.ts +50 -0
  105. package/dist/knowledge/pack/varint.d.ts.map +1 -0
  106. package/dist/knowledge/pack/varint.js +141 -0
  107. package/dist/knowledge/pack/varint.js.map +1 -0
  108. package/dist/knowledge/partitions.d.ts +1 -1
  109. package/dist/knowledge/partitions.d.ts.map +1 -1
  110. package/dist/knowledge/partitions.js +6 -1
  111. package/dist/knowledge/partitions.js.map +1 -1
  112. package/dist/knowledge/review.d.ts.map +1 -1
  113. package/dist/knowledge/review.js +58 -16
  114. package/dist/knowledge/review.js.map +1 -1
  115. package/dist/knowledge/reviewJudge.d.ts +8 -1
  116. package/dist/knowledge/reviewJudge.d.ts.map +1 -1
  117. package/dist/knowledge/reviewJudge.js +14 -8
  118. package/dist/knowledge/reviewJudge.js.map +1 -1
  119. package/dist/knowledge/reviewModel.d.ts +35 -1
  120. package/dist/knowledge/reviewModel.d.ts.map +1 -1
  121. package/dist/knowledge/reviewPrefetch.d.ts +8 -2
  122. package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
  123. package/dist/knowledge/reviewPrefetch.js +50 -25
  124. package/dist/knowledge/reviewPrefetch.js.map +1 -1
  125. package/dist/knowledge/reviewRun.d.ts +15 -3
  126. package/dist/knowledge/reviewRun.d.ts.map +1 -1
  127. package/dist/knowledge/reviewRun.js +19 -2
  128. package/dist/knowledge/reviewRun.js.map +1 -1
  129. package/dist/knowledge/reviewRunModel.d.ts +8 -1
  130. package/dist/knowledge/reviewRunModel.d.ts.map +1 -1
  131. package/dist/knowledge/reviewRunModel.js.map +1 -1
  132. package/dist/knowledge/stores/localSnapshotStore.d.ts +72 -6
  133. package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
  134. package/dist/knowledge/stores/localSnapshotStore.js +279 -75
  135. package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
  136. package/dist/knowledge/systems.d.ts +18 -0
  137. package/dist/knowledge/systems.d.ts.map +1 -0
  138. package/dist/knowledge/systems.js +29 -0
  139. package/dist/knowledge/systems.js.map +1 -0
  140. package/package.json +7 -3
  141. package/src/knowledge/build.ts +31 -3
  142. package/src/knowledge/extractFile.ts +26 -6
  143. package/src/knowledge/extractJob.ts +26 -7
  144. package/src/knowledge/findings.ts +9 -1
  145. package/src/knowledge/index.ts +7 -3
  146. package/src/knowledge/jobDeadline.ts +43 -0
  147. package/src/knowledge/judgeCalls.ts +19 -2
  148. package/src/knowledge/judgePriority.ts +36 -0
  149. package/src/knowledge/model.ts +49 -0
  150. package/src/knowledge/outline.test.ts +50 -0
  151. package/src/knowledge/outline.ts +15 -1
  152. package/src/knowledge/pack/crc32.ts +17 -0
  153. package/src/knowledge/pack/decode.ts +58 -0
  154. package/src/knowledge/pack/deflate.ts +43 -0
  155. package/src/knowledge/pack/encode.ts +81 -0
  156. package/src/knowledge/pack/extrDiff.ts +0 -0
  157. package/src/knowledge/pack/frame.ts +86 -0
  158. package/src/knowledge/pack/index.ts +26 -0
  159. package/src/knowledge/pack/jsonSize.ts +11 -0
  160. package/src/knowledge/pack/manifest.ts +128 -0
  161. package/src/knowledge/pack/pack.guards.test.ts +77 -0
  162. package/src/knowledge/pack/pack.reconcile.test.ts +96 -0
  163. package/src/knowledge/pack/pack.roundtrip.test.ts +50 -0
  164. package/src/knowledge/pack/pack.size.test.ts +22 -0
  165. package/src/knowledge/pack/pack.testkit.test-util.ts +90 -0
  166. package/src/knowledge/pack/sections/columns.ts +61 -0
  167. package/src/knowledge/pack/sections/extr.ts +90 -0
  168. package/src/knowledge/pack/sections/extrLists.ts +147 -0
  169. package/src/knowledge/pack/sections/facts.ts +123 -0
  170. package/src/knowledge/pack/sections/index.ts +13 -0
  171. package/src/knowledge/pack/sections/rows.ts +184 -0
  172. package/src/knowledge/pack/strings.ts +123 -0
  173. package/src/knowledge/pack/types.ts +89 -0
  174. package/src/knowledge/pack/varint.ts +138 -0
  175. package/src/knowledge/partitions.test.ts +4 -0
  176. package/src/knowledge/partitions.ts +3 -1
  177. package/src/knowledge/review.throughput.test.ts +122 -0
  178. package/src/knowledge/review.ts +54 -16
  179. package/src/knowledge/review.twoPass.test.ts +224 -0
  180. package/src/knowledge/reviewJudge.ts +19 -8
  181. package/src/knowledge/reviewModel.ts +32 -1
  182. package/src/knowledge/reviewPrefetch.ts +51 -24
  183. package/src/knowledge/reviewRun.test.ts +20 -3
  184. package/src/knowledge/reviewRun.ts +33 -6
  185. package/src/knowledge/reviewRunModel.ts +4 -1
  186. package/src/knowledge/stores/localSnapshotStore.batched.test.ts +25 -3
  187. package/src/knowledge/stores/localSnapshotStore.extractedLog.test.ts +280 -0
  188. package/src/knowledge/stores/localSnapshotStore.ts +283 -76
  189. package/src/knowledge/systems.test.ts +119 -0
  190. package/src/knowledge/systems.ts +32 -0
@@ -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,10 @@ 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 {
270
+ // The system of EVERY node with a path (a `missing` node too): a file's link to a path in another system crosses systems.
271
+ // Only file nodes are stamped with it (`KNode.system` is a file field); the rest are kept here.
272
+ const systemOfRef = new Map<string, Pick<KNode, 'system'>>();
259
273
  for (const n of g.nodes.values()) {
260
274
  const path = pathOfRef(n.ref);
261
275
  if (path === undefined) continue;
@@ -265,11 +279,22 @@ function placeNodes(rootId: string, g: GraphBuilder, registries: Map<string, Par
265
279
  if (partition !== undefined) n.partition = partition;
266
280
  const area = areaOfPath(path);
267
281
  if (area) n.area = srcRef(rootId, area);
282
+ const placed = systems.length > 0 ? placeInSystem(systems, path) : undefined;
283
+ if (placed) {
284
+ systemOfRef.set(n.ref, { system: placed.system });
285
+ if (n.kind === 'file') {
286
+ n.system = placed.system;
287
+ if (placed.app !== undefined) n.app = placed.app;
288
+ if (placed.copyOf !== undefined) n.copyOf = placed.copyOf;
289
+ }
290
+ }
268
291
  }
269
292
  for (const e of g.edges.values()) {
270
293
  const from = g.nodes.get(e.from), to = g.nodes.get(e.to);
271
294
  const reg = from && registries.get(from.pack);
272
295
  if (!from || !to || !reg || from.pack !== to.pack) continue;
296
+ // Layers are a system's own: a reference into another system is neither upward nor skipping.
297
+ if (crossesSystems(systemOfRef.get(from.ref) ?? from, systemOfRef.get(to.ref) ?? to)) continue;
273
298
  const verdict = verdictOf(from.partition, to.partition, reg);
274
299
  if (verdict) e.verdict = verdict;
275
300
  }
@@ -283,6 +308,9 @@ function finalNode(n: KNode): KNode {
283
308
  ref: n.ref, kind: n.kind, label: n.label, pack: n.pack,
284
309
  ...(n.partition !== undefined ? { partition: n.partition } : {}),
285
310
  ...(n.area !== undefined ? { area: n.area } : {}),
311
+ ...(n.system !== undefined ? { system: n.system } : {}),
312
+ ...(n.app !== undefined ? { app: n.app } : {}),
313
+ ...(n.copyOf !== undefined ? { copyOf: n.copyOf } : {}),
286
314
  importance: n.importance, origin: n.origin,
287
315
  ...(n.sourceHash !== undefined ? { sourceHash: n.sourceHash } : {}),
288
316
  ...(n.stale ? { stale: true } : {}),
@@ -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
- doc: SourceDocument;
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
- const src = asPathSource(a.doc, a.path, a.hash);
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, doc: a.doc, knownKeys: new Map(), sectionsOnly: true }), a.signal);
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 out = await a.pool(jobOf({ rootId: a.rootId, path: a.path, hash: a.hash, doc: a.doc, knownKeys, needSections: wants }), a.signal);
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
- export interface ExtractJob {
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; doc: SourceDocument; knownKeys: ReadonlyMap<string, NodeRef>;
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, doc: f.doc, knownKeys: [...f.knownKeys],
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: [] };
@@ -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';
@@ -41,6 +43,8 @@ export { planReview, planDetail, refreshPlan, AVG_SECTION_BYTES } from './plan.j
41
43
  export type { PlanOptions, PlannedFile, PlanDetail } from './plan.js';
42
44
  export type { ExtractorState } from './owedFiles.js';
43
45
  export { reviewDirectory, assertStoredBatch } from './review.js';
46
+ export { orderForJudging } from './judgePriority.js';
47
+ export type { JudgeSignals } from './judgePriority.js';
44
48
  export { extractFile, extractFileDetailed, knownKeysOfEntities } from './extractFile.js';
45
49
  export type { ExtractFileArgs, FileExtraction } from './extractFile.js';
46
50
  export { extractJob, jobOf } from './extractJob.js';
@@ -50,8 +54,8 @@ export { createModelLimiter, isRateLimit } from './modelLimiter.js';
50
54
  export type { ModelLimiter } from './modelLimiter.js';
51
55
  export { reasonOf } from './reviewRunModel.js';
52
56
  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';
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';
55
59
  export {
56
60
  validateExtract, validateCompare, clampQuote, clampClaim, MAX_QUOTE_LINES, MAX_QUOTE_CHARS, MAX_CLAIM_TEXT_CHARS,
57
61
  DEFAULT_REVIEW_MODEL_CALLS, DEFAULT_REVIEW_JUDGE_CONCURRENCY, REVIEW_FACT_SOURCE,
@@ -67,7 +71,7 @@ export {
67
71
  export { DOCS_PACK, DOCS_PACK_ID, brokenLinkRule, orphanDocumentRule, contradictionRule } from './packs/docs.js';
68
72
  export { frontMatterOf, SECTION_INDEX_BADGE } from '../ingest/docsExtract.js';
69
73
  export { LocalSnapshotStore, localSnapshotStore } from './stores/localSnapshotStore.js';
70
- export type { SnapshotPersistence, KnowledgeSnapshot, LocalSnapshotStoreOptions } from './stores/localSnapshotStore.js';
74
+ export type { SnapshotPersistence, KnowledgeSnapshot, LocalSnapshotStoreOptions, ExtractedLogPersistence } from './stores/localSnapshotStore.js';
71
75
 
72
76
  // The knowledge index (search, expand, near-duplicate pairs) ships on the same subpath.
73
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
+ }
@@ -34,6 +34,12 @@ export interface KNode {
34
34
  stale?: boolean;
35
35
  /** Pack data, e.g. { added, removed }, { unused: 'file' }, { line: 12 }. */
36
36
  badges?: Record<string, number | string>;
37
+ /** The system (a repository or project folder of the root) a file belongs to; '' when the root is one system. File nodes only. */
38
+ system?: string;
39
+ /** The workspace package (app) of the system the file belongs to, as a root-relative folder. */
40
+ app?: string;
41
+ /** On a file of a duplicated copy: the path of the system it is a copy of, so a view can fold it. */
42
+ copyOf?: string;
37
43
  }
38
44
 
39
45
  export type EdgeVerdict = 'allowed' | 'same' | 'skips' | 'upward';
@@ -233,11 +239,40 @@ export interface LiveOverlay {
233
239
  runFiles?: string[];
234
240
  }
235
241
 
242
+ /** A workspace package of a system. */
243
+ export interface GraphApp { path: string; name: string }
244
+
245
+ /** Why a file the repo graph could have read was not read. */
246
+ export interface GraphReadSkip { reason: string; count: number }
247
+
248
+ /**
249
+ * One system of a review root (a repository, or a folder whose manifest names a project): the unit
250
+ * the reference graph, layer verdicts and partition violations are computed within (PRD 41 A9).
251
+ * `path` is root-relative, '' when the root itself is the system.
252
+ */
253
+ export interface GraphSystem {
254
+ path: string;
255
+ name: string;
256
+ /** File nodes the graph holds under it. */
257
+ files: number;
258
+ apps: GraphApp[];
259
+ /** The repo graph did not read every file of it (see `graphRead.skipped`). */
260
+ truncated?: boolean;
261
+ /** Set on a duplicated copy: the path of the system it copies. */
262
+ copyOf?: string;
263
+ copySimilarity?: number;
264
+ copyReason?: 'no-git' | 'name-mismatch' | 'later-name';
265
+ /** The reference graph's reading of this system: files read, and files left out by reason. */
266
+ graphRead?: { read: number; skipped: GraphReadSkip[] };
267
+ }
268
+
236
269
  export interface KnowledgeGraph {
237
270
  scope: { rootId: string; packs: string[]; digest: string };
238
271
  nodes: KNode[];
239
272
  edges: KEdge[];
240
273
  findings: Finding[];
274
+ /** Present only when the root held systems to report (see {@link GraphSystem}). */
275
+ meta?: { systems?: GraphSystem[] };
241
276
  stats: { sources: number; nodes: number; edges: number; stale: number; truncated: boolean };
242
277
  /**
243
278
  * Attached only when the graph was truncated (`stats.truncated`): the whole graph's files,
@@ -258,6 +293,12 @@ export interface GraphOutline {
258
293
  areas: NodeRef[];
259
294
  /** Distinct partitions, sorted; `OutlineFile.partition` indexes into it. */
260
295
  partitions: string[];
296
+ /** Distinct system paths of the files (and the systems they copy), sorted; `OutlineFile.system` / `copyOf` index into it. Absent when no file has a system. */
297
+ systems?: string[];
298
+ /** Distinct app paths, sorted; `OutlineFile.app` indexes into it. Absent when no file has an app. */
299
+ apps?: string[];
300
+ /** The root's systems with their file counts, copies and graph reads — `KnowledgeGraph.meta.systems`, carried so the outline stands alone. */
301
+ systemInfo?: GraphSystem[];
261
302
  /** File nodes of the full graph, sorted by ref. */
262
303
  files: OutlineFile[];
263
304
  /**
@@ -277,6 +318,12 @@ export interface OutlineFile {
277
318
  area?: number;
278
319
  /** Index into `GraphOutline.partitions`, when the file has a partition. */
279
320
  partition?: number;
321
+ /** Index into `GraphOutline.systems`, when the file has a system ('' is a system too). */
322
+ system?: number;
323
+ /** Index into `GraphOutline.apps`, when the file has an app. */
324
+ app?: number;
325
+ /** Index into `GraphOutline.systems` of the system this file's system copies. */
326
+ copyOf?: number;
280
327
  importance: number;
281
328
  /** The first 12 characters of the node's sourceHash. */
282
329
  hash?: string;
@@ -292,6 +339,8 @@ export interface BuildGraphInput {
292
339
  packs: KnowledgePack[];
293
340
  live?: LiveOverlay;
294
341
  nearDuplicates?: SimilarPair[];
342
+ /** The root's systems (file counts are computed by the build): each file node is stamped with its system, app and copyOf. */
343
+ systems?: GraphSystem[];
295
344
  }
296
345
 
297
346
  export interface BuildGraphOptions {
@@ -166,3 +166,53 @@ describe('buildOutline caps', () => {
166
166
  expect(buildOutline(synthetic(10, [refEdge(0, 1)])).capped).toBe(false);
167
167
  });
168
168
  });
169
+
170
+ describe('buildOutline — systems', () => {
171
+ const files = ['a/x.ts', 'a/packages/web/y.ts', 'b/z.ts'];
172
+ const withSystems = (): KnowledgeGraph => {
173
+ const g = buildGraph({
174
+ rootId: ROOT, packs: [PACK], facts: [], relations: [],
175
+ extracted: files.map((p) => extractedOf(fileNode(p))),
176
+ systems: [
177
+ { path: 'a', name: 'a', files: 0, apps: [{ path: 'a/packages/web', name: 'web' }] },
178
+ { path: 'b', name: 'b', files: 0, apps: [], copyOf: 'a', copySimilarity: 1, copyReason: 'no-git' },
179
+ ],
180
+ });
181
+ return g;
182
+ };
183
+
184
+ it('files carry system, app and copyOf as indexes into the outline pools, and the outline carries the systems', () => {
185
+ const o = buildOutline(withSystems());
186
+ expect(o.systems).toEqual(['a', 'b']);
187
+ expect(o.apps).toEqual(['a/packages/web']);
188
+ const byPath = (p: string) => o.files.find((f) => f.path.endsWith(p))!;
189
+ expect(byPath('a/x.ts')).toMatchObject({ system: 0 });
190
+ expect(byPath('a/x.ts').app).toBeUndefined();
191
+ expect(byPath('y.ts')).toMatchObject({ system: 0, app: 0 });
192
+ expect(byPath('b/z.ts')).toMatchObject({ system: 1, copyOf: 0 });
193
+ expect(o.systemInfo?.map((s) => [s.path, s.files, s.copyOf])).toEqual([['a', 2, undefined], ['b', 1, 'a']]);
194
+ });
195
+
196
+ it('a root without systems has none of these fields', () => {
197
+ const o = buildOutline(buildGraph({ rootId: ROOT, packs: [PACK], facts: [], relations: [], extracted: files.map((p) => extractedOf(fileNode(p))) }));
198
+ expect(o.systems).toBeUndefined();
199
+ expect(o.apps).toBeUndefined();
200
+ expect(o.systemInfo).toBeUndefined();
201
+ expect(o.files.every((f) => f.system === undefined)).toBe(true);
202
+ });
203
+
204
+ it('a one-system root keeps the empty system as index 0', () => {
205
+ const g = buildGraph({
206
+ rootId: ROOT, packs: [PACK], facts: [], relations: [], extracted: files.map((p) => extractedOf(fileNode(p))),
207
+ systems: [{ path: '', name: 'r', files: 0, apps: [] }],
208
+ });
209
+ const o = buildOutline(g);
210
+ expect(o.systems).toEqual(['']);
211
+ expect(o.files.every((f) => f.system === 0)).toBe(true);
212
+ });
213
+
214
+ it('survives a JSON round trip (the wire form)', () => {
215
+ const o = buildOutline(withSystems());
216
+ expect(JSON.parse(JSON.stringify(o))).toEqual(o);
217
+ });
218
+ });
@@ -60,6 +60,11 @@ export function buildOutline(full: KnowledgeGraph): GraphOutline {
60
60
  const areaIndex = new Map<NodeRef, number>(areas.map((a, i) => [a, i] as const));
61
61
  const partitionIndex = new Map<string, number>(partitions.map((p, i) => [p, i] as const));
62
62
 
63
+ const systems = [...new Set(fileNodes.flatMap((n) => [...(n.system !== undefined ? [n.system] : []), ...(n.copyOf !== undefined ? [n.copyOf] : [])]))].sort(compareStr);
64
+ const apps = [...new Set(fileNodes.flatMap((n) => (n.app !== undefined ? [n.app] : [])))].sort(compareStr);
65
+ const systemIndex = new Map<string, number>(systems.map((s, i) => [s, i] as const));
66
+ const appIndex = new Map<string, number>(apps.map((a, i) => [a, i] as const));
67
+
63
68
  const files: OutlineFile[] = fileNodes.map((n) => {
64
69
  const badges: Record<string, number | string> = {};
65
70
  for (const k of OUTLINE_BADGE_KEYS) {
@@ -70,6 +75,9 @@ export function buildOutline(full: KnowledgeGraph): GraphOutline {
70
75
  path: n.ref.slice(prefix.length),
71
76
  ...(n.area !== undefined ? { area: areaIndex.get(n.area)! } : {}),
72
77
  ...(n.partition !== undefined ? { partition: partitionIndex.get(n.partition)! } : {}),
78
+ ...(n.system !== undefined ? { system: systemIndex.get(n.system)! } : {}),
79
+ ...(n.app !== undefined ? { app: appIndex.get(n.app)! } : {}),
80
+ ...(n.copyOf !== undefined ? { copyOf: systemIndex.get(n.copyOf)! } : {}),
73
81
  importance: n.importance,
74
82
  ...(n.sourceHash !== undefined ? { hash: n.sourceHash.slice(0, HASH_CHARS) } : {}),
75
83
  ...(Object.keys(badges).length > 0 ? { badges } : {}),
@@ -104,5 +112,11 @@ export function buildOutline(full: KnowledgeGraph): GraphOutline {
104
112
  }
105
113
  list.sort((a, b) => a.from - b.from || a.to - b.to);
106
114
  const links = list.map((m) => [m.from, m.to, m.verdict, m.cycle ? OUTLINE_FLAG_CYCLE : 0] as [number, number, number, number]);
107
- return { prefix, areas, partitions, files, links, capped };
115
+ return {
116
+ prefix, areas, partitions,
117
+ ...(systems.length > 0 ? { systems } : {}),
118
+ ...(apps.length > 0 ? { apps } : {}),
119
+ ...(full.meta?.systems ? { systemInfo: full.meta.systems } : {}),
120
+ files, links, capped,
121
+ };
108
122
  }
@@ -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
+ }