@seanhogg/builderforce-memory 2026.10.71 → 2026.10.72

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 (188) hide show
  1. package/dist/knowledge/coChange.d.ts +3 -1
  2. package/dist/knowledge/coChange.d.ts.map +1 -1
  3. package/dist/knowledge/coChange.js +24 -12
  4. package/dist/knowledge/coChange.js.map +1 -1
  5. package/dist/knowledge/extractFile.d.ts +10 -0
  6. package/dist/knowledge/extractFile.d.ts.map +1 -1
  7. package/dist/knowledge/extractFile.js +16 -5
  8. package/dist/knowledge/extractFile.js.map +1 -1
  9. package/dist/knowledge/extractJob.d.ts +18 -1
  10. package/dist/knowledge/extractJob.d.ts.map +1 -1
  11. package/dist/knowledge/extractJob.js +10 -4
  12. package/dist/knowledge/extractJob.js.map +1 -1
  13. package/dist/knowledge/facts/extractorVersion.d.ts +45 -0
  14. package/dist/knowledge/facts/extractorVersion.d.ts.map +1 -0
  15. package/dist/knowledge/facts/extractorVersion.js +56 -0
  16. package/dist/knowledge/facts/extractorVersion.js.map +1 -0
  17. package/dist/knowledge/facts/fileFacts.d.ts +166 -0
  18. package/dist/knowledge/facts/fileFacts.d.ts.map +1 -0
  19. package/dist/knowledge/facts/fileFacts.js +156 -0
  20. package/dist/knowledge/facts/fileFacts.js.map +1 -0
  21. package/dist/knowledge/findings.d.ts +17 -14
  22. package/dist/knowledge/findings.d.ts.map +1 -1
  23. package/dist/knowledge/findings.js +29 -129
  24. package/dist/knowledge/findings.js.map +1 -1
  25. package/dist/knowledge/index.d.ts +13 -1
  26. package/dist/knowledge/index.d.ts.map +1 -1
  27. package/dist/knowledge/index.js +8 -1
  28. package/dist/knowledge/index.js.map +1 -1
  29. package/dist/knowledge/model.d.ts +6 -0
  30. package/dist/knowledge/model.d.ts.map +1 -1
  31. package/dist/knowledge/owedFiles.d.ts +14 -4
  32. package/dist/knowledge/owedFiles.d.ts.map +1 -1
  33. package/dist/knowledge/owedFiles.js +30 -8
  34. package/dist/knowledge/owedFiles.js.map +1 -1
  35. package/dist/knowledge/plan.d.ts +10 -1
  36. package/dist/knowledge/plan.d.ts.map +1 -1
  37. package/dist/knowledge/plan.js +9 -4
  38. package/dist/knowledge/plan.js.map +1 -1
  39. package/dist/knowledge/review.js +1 -0
  40. package/dist/knowledge/review.js.map +1 -1
  41. package/dist/knowledge/reviewContext.d.ts.map +1 -1
  42. package/dist/knowledge/reviewContext.js +5 -2
  43. package/dist/knowledge/reviewContext.js.map +1 -1
  44. package/dist/knowledge/reviewFinish.d.ts.map +1 -1
  45. package/dist/knowledge/reviewFinish.js +3 -1
  46. package/dist/knowledge/reviewFinish.js.map +1 -1
  47. package/dist/knowledge/reviewModel.d.ts +12 -0
  48. package/dist/knowledge/reviewModel.d.ts.map +1 -1
  49. package/dist/knowledge/reviewPrefetch.d.ts +2 -0
  50. package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
  51. package/dist/knowledge/reviewPrefetch.js +1 -0
  52. package/dist/knowledge/reviewPrefetch.js.map +1 -1
  53. package/dist/knowledge/rules/cloneGroup.d.ts +10 -0
  54. package/dist/knowledge/rules/cloneGroup.d.ts.map +1 -0
  55. package/dist/knowledge/rules/cloneGroup.js +46 -0
  56. package/dist/knowledge/rules/cloneGroup.js.map +1 -0
  57. package/dist/knowledge/rules/components.d.ts +8 -0
  58. package/dist/knowledge/rules/components.d.ts.map +1 -0
  59. package/dist/knowledge/rules/components.js +34 -0
  60. package/dist/knowledge/rules/components.js.map +1 -0
  61. package/dist/knowledge/rules/cycle.d.ts +7 -0
  62. package/dist/knowledge/rules/cycle.d.ts.map +1 -0
  63. package/dist/knowledge/rules/cycle.js +18 -0
  64. package/dist/knowledge/rules/cycle.js.map +1 -0
  65. package/dist/knowledge/rules/duplicateCopy.d.ts +7 -0
  66. package/dist/knowledge/rules/duplicateCopy.d.ts.map +1 -0
  67. package/dist/knowledge/rules/duplicateCopy.js +18 -0
  68. package/dist/knowledge/rules/duplicateCopy.js.map +1 -0
  69. package/dist/knowledge/rules/evaluateRules.d.ts +60 -0
  70. package/dist/knowledge/rules/evaluateRules.d.ts.map +1 -0
  71. package/dist/knowledge/rules/evaluateRules.js +164 -0
  72. package/dist/knowledge/rules/evaluateRules.js.map +1 -0
  73. package/dist/knowledge/rules/factGraph.d.ts +51 -0
  74. package/dist/knowledge/rules/factGraph.d.ts.map +1 -0
  75. package/dist/knowledge/rules/factGraph.js +77 -0
  76. package/dist/knowledge/rules/factGraph.js.map +1 -0
  77. package/dist/knowledge/rules/factRule.d.ts +56 -0
  78. package/dist/knowledge/rules/factRule.d.ts.map +1 -0
  79. package/dist/knowledge/rules/factRule.js +46 -0
  80. package/dist/knowledge/rules/factRule.js.map +1 -0
  81. package/dist/knowledge/rules/godModule.d.ts +8 -0
  82. package/dist/knowledge/rules/godModule.d.ts.map +1 -0
  83. package/dist/knowledge/rules/godModule.js +16 -0
  84. package/dist/knowledge/rules/godModule.js.map +1 -0
  85. package/dist/knowledge/rules/knowledgeInput.d.ts +35 -0
  86. package/dist/knowledge/rules/knowledgeInput.d.ts.map +1 -0
  87. package/dist/knowledge/rules/knowledgeInput.js +33 -0
  88. package/dist/knowledge/rules/knowledgeInput.js.map +1 -0
  89. package/dist/knowledge/rules/nearDuplicate.d.ts +7 -0
  90. package/dist/knowledge/rules/nearDuplicate.d.ts.map +1 -0
  91. package/dist/knowledge/rules/nearDuplicate.js +20 -0
  92. package/dist/knowledge/rules/nearDuplicate.js.map +1 -0
  93. package/dist/knowledge/rules/partitionViolation.d.ts +10 -0
  94. package/dist/knowledge/rules/partitionViolation.d.ts.map +1 -0
  95. package/dist/knowledge/rules/partitionViolation.js +27 -0
  96. package/dist/knowledge/rules/partitionViolation.js.map +1 -0
  97. package/dist/knowledge/rules/possibleSame.d.ts +7 -0
  98. package/dist/knowledge/rules/possibleSame.d.ts.map +1 -0
  99. package/dist/knowledge/rules/possibleSame.js +15 -0
  100. package/dist/knowledge/rules/possibleSame.js.map +1 -0
  101. package/dist/knowledge/rules/stale.d.ts +7 -0
  102. package/dist/knowledge/rules/stale.d.ts.map +1 -0
  103. package/dist/knowledge/rules/stale.js +28 -0
  104. package/dist/knowledge/rules/stale.js.map +1 -0
  105. package/dist/knowledge/rules/unpartitioned.d.ts +7 -0
  106. package/dist/knowledge/rules/unpartitioned.d.ts.map +1 -0
  107. package/dist/knowledge/rules/unpartitioned.js +26 -0
  108. package/dist/knowledge/rules/unpartitioned.js.map +1 -0
  109. package/dist/knowledge/sources.d.ts +13 -0
  110. package/dist/knowledge/sources.d.ts.map +1 -1
  111. package/dist/knowledge/sources.js +14 -0
  112. package/dist/knowledge/sources.js.map +1 -1
  113. package/dist/retrieval/knowledge-index/sha256.d.ts.map +1 -1
  114. package/dist/retrieval/knowledge-index/sha256.js +2 -2
  115. package/dist/retrieval/knowledge-index/sha256.js.map +1 -1
  116. package/dist/stats/distributions.d.ts +17 -1
  117. package/dist/stats/distributions.d.ts.map +1 -1
  118. package/dist/stats/distributions.js +26 -1
  119. package/dist/stats/distributions.js.map +1 -1
  120. package/dist/stats/fitting.d.ts.map +1 -1
  121. package/dist/stats/fitting.js +1 -6
  122. package/dist/stats/fitting.js.map +1 -1
  123. package/dist/stats/index.d.ts +10 -3
  124. package/dist/stats/index.d.ts.map +1 -1
  125. package/dist/stats/index.js +10 -3
  126. package/dist/stats/index.js.map +1 -1
  127. package/dist/stats/logistic.d.ts +30 -0
  128. package/dist/stats/logistic.d.ts.map +1 -0
  129. package/dist/stats/logistic.js +43 -0
  130. package/dist/stats/logistic.js.map +1 -0
  131. package/dist/stats/multivariate.d.ts +8 -13
  132. package/dist/stats/multivariate.d.ts.map +1 -1
  133. package/dist/stats/multivariate.js +7 -53
  134. package/dist/stats/multivariate.js.map +1 -1
  135. package/dist/stats/policies.d.ts.map +1 -1
  136. package/dist/stats/policies.js +4 -22
  137. package/dist/stats/policies.js.map +1 -1
  138. package/package.json +4 -3
  139. package/src/contract/exports.snapshot.json +37 -1
  140. package/src/contract/regression.extractorKey.test.ts +202 -0
  141. package/src/contract/regression.statsEngineFree.test.ts +70 -0
  142. package/src/contract/regression.thompsonDeterminism.test.ts +23 -0
  143. package/src/contract/types.contract.test.ts +59 -2
  144. package/src/knowledge/coChange.test.ts +15 -2
  145. package/src/knowledge/coChange.ts +22 -10
  146. package/src/knowledge/extractFile.ts +27 -5
  147. package/src/knowledge/extractJob.ts +24 -5
  148. package/src/knowledge/facts/extractorVersion.ts +73 -0
  149. package/src/knowledge/facts/fileFacts.test.ts +157 -0
  150. package/src/knowledge/facts/fileFacts.ts +305 -0
  151. package/src/knowledge/findings.ts +30 -127
  152. package/src/knowledge/index.ts +19 -0
  153. package/src/knowledge/model.ts +6 -0
  154. package/src/knowledge/owedFiles.ts +36 -8
  155. package/src/knowledge/plan.ts +16 -4
  156. package/src/knowledge/review.ts +1 -0
  157. package/src/knowledge/reviewContext.ts +5 -2
  158. package/src/knowledge/reviewFinish.ts +3 -1
  159. package/src/knowledge/reviewModel.ts +12 -0
  160. package/src/knowledge/reviewPrefetch.ts +3 -0
  161. package/src/knowledge/rules/cloneGroup.ts +45 -0
  162. package/src/knowledge/rules/components.ts +31 -0
  163. package/src/knowledge/rules/cycle.ts +20 -0
  164. package/src/knowledge/rules/duplicateCopy.ts +22 -0
  165. package/src/knowledge/rules/evaluateRules.test.ts +172 -0
  166. package/src/knowledge/rules/evaluateRules.ts +186 -0
  167. package/src/knowledge/rules/factGraph.oracle.test.ts +174 -0
  168. package/src/knowledge/rules/factGraph.ts +107 -0
  169. package/src/knowledge/rules/factRule.ts +74 -0
  170. package/src/knowledge/rules/godModule.ts +18 -0
  171. package/src/knowledge/rules/knowledgeInput.ts +60 -0
  172. package/src/knowledge/rules/knowledgeRules.test.ts +78 -0
  173. package/src/knowledge/rules/nearDuplicate.ts +22 -0
  174. package/src/knowledge/rules/partitionViolation.ts +31 -0
  175. package/src/knowledge/rules/possibleSame.ts +17 -0
  176. package/src/knowledge/rules/rules.testkit.test-util.ts +78 -0
  177. package/src/knowledge/rules/stale.ts +31 -0
  178. package/src/knowledge/rules/unpartitioned.ts +27 -0
  179. package/src/knowledge/sources.ts +16 -0
  180. package/src/retrieval/knowledge-index/sha256.test.ts +25 -0
  181. package/src/retrieval/knowledge-index/sha256.ts +2 -1
  182. package/src/stats/distributions.ts +29 -2
  183. package/src/stats/fitting.ts +1 -6
  184. package/src/stats/index.ts +12 -2
  185. package/src/stats/logistic.test.ts +89 -0
  186. package/src/stats/logistic.ts +49 -0
  187. package/src/stats/multivariate.ts +8 -59
  188. package/src/stats/policies.ts +4 -24
@@ -12,7 +12,7 @@
12
12
  import type { IngestManifest } from '../ingest/types.js';
13
13
  import type { DirectorySource, KnowledgePack, ReviewPlan } from './model.js';
14
14
  import { canonicalListing, merkleTree, type MerkleTree } from './merkle.js';
15
- import { carriedOwed, type ExtractorState, isOwed, loadExtractorState, owedCalls, withDocuments } from './owedFiles.js';
15
+ import { carriedOwed, type ExtractorState, isOwed, loadExtractorState, owedCalls, withDocuments, withExtractorKey } from './owedFiles.js';
16
16
  import {
17
17
  claimedDocumentExts, compareManifestKey, composePacks, DEFAULT_MAX_FILE_BYTES, filesManifestKey, ignoreMatcher, ignoreSourcesOf,
18
18
  isAssetPath, isDocumentPath, manifestMap, resolveDocument, stubSource,
@@ -44,6 +44,13 @@ export interface PlanOptions {
44
44
  * estimate of the plan it continues; it is not recomputed.)
45
45
  */
46
46
  compare?: boolean;
47
+ /**
48
+ * An input the host's extractors read besides the file bytes (agent-tools: a digest of the tsconfig path aliases). When it
49
+ * differs from the key the root was last reviewed under (or one is given where none was recorded), every file is owed a
50
+ * re-extraction, its content unchanged or not — at no estimated model calls (the judgements are re-anchored). Absent or '':
51
+ * no key, as before keys existed.
52
+ */
53
+ extractorKey?: string;
47
54
  }
48
55
 
49
56
  export interface PlannedFile {
@@ -133,7 +140,10 @@ export async function planDetail(
133
140
  // A file's asset-ness depends on the packs (a pdf is an asset until a host parser claims it): a change in the document types the
134
141
  // packs claim since the last run owes the files of those types a re-processing, whatever their hash (see withDocuments).
135
142
  const oversized = new Set<string>();
136
- const extractor: ExtractorState = { ...withDocuments(await loadExtractorState(manifest, source.rootId), claimedDocumentExts(composed)), oversized };
143
+ const extractor: ExtractorState = {
144
+ ...withExtractorKey(withDocuments(await loadExtractorState(manifest, source.rootId), claimedDocumentExts(composed)), opts.extractorKey),
145
+ oversized,
146
+ };
137
147
  const packById = new Map(packs.map((p) => [p.id, p] as const));
138
148
 
139
149
  const files: PlannedFile[] = [];
@@ -212,11 +222,13 @@ export async function planDetail(
212
222
  * *Continue*: the confirmed plan without a re-walk. Only `changed` is re-read — against the
213
223
  * manifest and owed list as the last run left them — so files finished since are not reviewed
214
224
  * again, and files it left owed (an upgrade cut short, a failed read) are picked up.
225
+ * `extractorKey` is the key this run extracts under (`PlanOptions.extractorKey`; `''` = no key). A host must pass a FRESHLY
226
+ * computed key: the default, the plan's, is stale when the extractor inputs changed since the plan was made.
215
227
  */
216
- export async function refreshPlan(detail: PlanDetail, manifest: IngestManifest): Promise<PlanDetail> {
228
+ export async function refreshPlan(detail: PlanDetail, manifest: IngestManifest, extractorKey = detail.extractor.extractorKeyNow): Promise<PlanDetail> {
217
229
  const prior = await manifestMap(manifest, filesManifestKey(detail.plan.rootId));
218
230
  const extractor: ExtractorState = {
219
- ...withDocuments(await loadExtractorState(manifest, detail.plan.rootId), detail.extractor.documentsNow),
231
+ ...withExtractorKey(withDocuments(await loadExtractorState(manifest, detail.plan.rootId), detail.extractor.documentsNow), extractorKey),
220
232
  ...(detail.extractor.oversized ? { oversized: detail.extractor.oversized } : {}),
221
233
  };
222
234
  const files = detail.files.map((f) => {
@@ -115,6 +115,7 @@ async function applyChangedFiles(c: ReviewContext): Promise<AbortSignal> {
115
115
  const prefetch = createPrefetch({
116
116
  args, signal: runSignal, rootId: c.rootId, packs: args.packs, store: args.store, composed: c.composed, knownKeys: c.knownKeys,
117
117
  width: readAhead, extractWidth: concurrency,
118
+ ...(c.detail.extractor.extractorKeyNow ? { extractorKey: c.detail.extractor.extractorKeyNow } : {}),
118
119
  });
119
120
  const dispatch = {
120
121
  // A mechanical run (pass 1) makes no model call: judged files stay owed.
@@ -78,8 +78,11 @@ export async function openReview(args: ReviewArgs): Promise<ReviewContext> {
78
78
  const progress = (p: ReviewProgressEvent) => args.onProgress?.(p);
79
79
 
80
80
  const detail = args.plan
81
- ? await refreshPlan(args.plan, manifest)
82
- : await planDetail(source, manifest, packs, { ...(args.force ? { force: true } : {}), compare: !!args.similar && !!args.judgement });
81
+ ? await refreshPlan(args.plan, manifest, args.extractorKey ?? args.plan.extractor.extractorKeyNow)
82
+ : await planDetail(source, manifest, packs, {
83
+ ...(args.force ? { force: true } : {}), compare: !!args.similar && !!args.judgement,
84
+ ...(args.extractorKey ? { extractorKey: args.extractorKey } : {}),
85
+ });
83
86
  progress({ phase: 'plan', done: detail.files.length, total: detail.files.length });
84
87
  const packIds = packs.map((p) => p.id).sort(compareStr);
85
88
  const [storedFacts, storedRelations] = await Promise.all([store.facts(scope), store.relations(scope)]);
@@ -55,7 +55,9 @@ export async function finishReview(c: ReviewContext, flush: () => Promise<void>)
55
55
  await saveExtractorState(manifest, c.rootId, owedAfterRun({
56
56
  state: c.detail.extractor, changed: c.changed, prior: c.detail.prior, finished: c.finished, carried: c.detail.carried,
57
57
  live: c.filesNow, measured: c.measured, unreadable: c.unreadable,
58
- }), c.failures, c.detail.extractor.documentsNow);
58
+ }), c.failures, c.detail.extractor.documentsNow,
59
+ // An aborted run keeps the key the root was last reviewed under: every file stays owed until a run under the new key finishes.
60
+ report.aborted ? c.detail.extractor.extractorKey : c.detail.extractor.extractorKeyNow);
59
61
  await writeBatch(c, report.aborted ? c.scopeRecord : { ...c.scopeRecord, lastDigest: report.digest, lastReviewedAt: new Date(c.now()).toISOString() });
60
62
  report.durationMs = c.now() - c.started;
61
63
  c.progress({ phase: 'done', done: c.work.length, total: c.work.length });
@@ -124,6 +124,18 @@ export interface ReviewArgs {
124
124
  plan?: PlanDetail;
125
125
  /** *Re-review all*: every file is reviewed whatever its hash (see `PlanOptions.force`). Ignored with `plan`. */
126
126
  force?: boolean;
127
+ /**
128
+ * An input the host's extractors read besides the file bytes (agent-tools: a digest of the tsconfig path aliases); see
129
+ * `PlanOptions.extractorKey`. A changed key owes every file and bypasses extracts cached under another key.
130
+ * - Pass a FRESHLY computed key on every run, *Continue* included: with `plan`, an absent key falls back to the plan's,
131
+ * which is stale if the inputs changed since the plan (new-alias extracts would be stamped with the old key).
132
+ * - `''` is an explicit "no key" (also with `plan`); absent without `plan` is no key too — as before keys existed.
133
+ * - With `extractPool`, the pool must rebuild its key-dependent inputs when the key changes: a worker echoing another key
134
+ * (`ExtractJobResult.extractorKey`) has its result dropped and the file stays owed.
135
+ * - An aborted run does not record the new key: the next run owes every file again (cheap — the extracts made under the
136
+ * new key are reused).
137
+ */
138
+ extractorKey?: string;
127
139
  signal?: AbortSignal;
128
140
  /**
129
141
  * Files read + extracted ahead of judging (1..32, default 8). With an `extractPool` this is the pool's width.
@@ -43,6 +43,8 @@ export interface PrefetchContext {
43
43
  width: number;
44
44
  /** Files in the extract stage at once (the pool's width); default `width`. */
45
45
  extractWidth?: number;
46
+ /** The run's extractor key (the plan's `extractor.extractorKeyNow`), passed to every extraction. */
47
+ extractorKey?: string;
46
48
  }
47
49
 
48
50
  /** A {@link Prefetch} before its timing is stamped. */
@@ -110,6 +112,7 @@ export function createPrefetch(c: PrefetchContext): (f: PrefetchFile) => Promise
110
112
  try { return await withDeadline(byPool ? extractMs + (readOverrideOf(readPath) ?? 0) : extractMs,(signal) => extractFileDetailed({
111
113
  rootId: c.rootId, path: f.path, hash: f.hash, ...(doc ? { doc } : {}), packs: c.packs, store: c.store, composed: c.composed,
112
114
  knownKeys: c.knownKeys, writeCache: false,
115
+ ...(c.extractorKey ? { extractorKey: c.extractorKey } : {}),
113
116
  onTiming: (t) => { parts.lookupMs = t.lookupMs; parts.poolMs = t.poolMs; },
114
117
  ...(c.args.extractPool ? { pool: c.args.extractPool, signal, wantsSections, ...(byPool ? {
115
118
  readByPool: true, ...(f.listedPath !== undefined ? { readPath } : {}), ...(readOverrideOf(readPath) ? { readMs: readOverrideOf(readPath)! } : {}),
@@ -0,0 +1,45 @@
1
+ /**
2
+ * knowledge/rules/cloneGroup.ts — `clone-group`: duplicate edges grouped by the clone-group badge
3
+ * (e.g. a jscpd issue id), else by connected component. Anchor (PRD 41 §C3): the badge, else the
4
+ * sorted-first member — so a group that gains a member keeps its identity (lineage `changed (grew)`).
5
+ */
6
+
7
+ import { finding, refAnchor, type FindingAnchor } from '../findingBuilder.js';
8
+ import type { KEdge, NodeRef } from '../model.js';
9
+ import { compareStr } from '../refs.js';
10
+ import { defineRule } from './factRule.js';
11
+ import { components } from './components.js';
12
+ import { packOfRef, type KnowledgeRuleExtra } from './knowledgeInput.js';
13
+
14
+ /** Node badge naming the clone group (e.g. a jscpd issue id) its `duplicate` edges belong to. */
15
+ export const CLONE_GROUP_BADGE = 'cloneGroup';
16
+
17
+ export const cloneGroupRule = defineRule<KnowledgeRuleExtra>({
18
+ id: 'clone-group',
19
+ version: 1,
20
+ reads: [], // the knowledge graph only (its digest covers the duplicate edges)
21
+ scope: 'global',
22
+ extraInputs: ['knowledge'],
23
+ derive: ({ extra: { knowledge: k } }) => {
24
+ const byBadge = new Map<string, KEdge[]>();
25
+ const unbadged: KEdge[] = [];
26
+ for (const e of k.graph.edges) {
27
+ if (e.kind !== 'duplicate') continue;
28
+ const badge = k.byRef.get(e.from)?.badges?.[CLONE_GROUP_BADGE] ?? k.byRef.get(e.to)?.badges?.[CLONE_GROUP_BADGE];
29
+ if (badge === undefined) { unbadged.push(e); continue; }
30
+ const list = byBadge.get(String(badge)) ?? [];
31
+ list.push(e);
32
+ byBadge.set(String(badge), list);
33
+ }
34
+ const groups: Array<{ group: string; refs: NodeRef[] }> = [
35
+ ...[...byBadge].map(([group, es]) => ({ group, refs: es.flatMap((e) => [e.from, e.to]) })),
36
+ ...components(unbadged).map((refs) => ({ group: '', refs })),
37
+ ];
38
+ return groups.map(({ group, refs }) => {
39
+ const unique = [...new Set(refs)];
40
+ const first = unique.sort(compareStr)[0]!;
41
+ const anchor: FindingAnchor = group ? { anchor: `${CLONE_GROUP_BADGE}:${group}`, anchorKind: 'group' } : refAnchor(first);
42
+ return finding('clone-group', packOfRef(k, first), unique, 'warn', { group, members: unique.length }, undefined, anchor);
43
+ });
44
+ },
45
+ });
@@ -0,0 +1,31 @@
1
+ /**
2
+ * knowledge/rules/components.ts — connected components over edges (union-find), shared by the
3
+ * `cycle` and `clone-group` rules. Moved from findings.ts, which re-exports it.
4
+ */
5
+
6
+ import type { KEdge, NodeRef } from '../model.js';
7
+ import { compareStr } from '../refs.js';
8
+
9
+ /** Connected components over edges, each sorted; components sorted by first ref. */
10
+ export function components(edges: readonly KEdge[]): NodeRef[][] {
11
+ const parent = new Map<NodeRef, NodeRef>();
12
+ const find = (x: NodeRef): NodeRef => {
13
+ let r = x;
14
+ while (parent.get(r) !== r) r = parent.get(r)!;
15
+ parent.set(x, r);
16
+ return r;
17
+ };
18
+ for (const e of edges) {
19
+ for (const r of [e.from, e.to]) if (!parent.has(r)) parent.set(r, r);
20
+ const a = find(e.from), b = find(e.to);
21
+ if (a !== b) parent.set(compareStr(a, b) < 0 ? b : a, compareStr(a, b) < 0 ? a : b);
22
+ }
23
+ const groups = new Map<NodeRef, NodeRef[]>();
24
+ for (const r of [...parent.keys()].sort(compareStr)) {
25
+ const root = find(r);
26
+ let g = groups.get(root);
27
+ if (!g) groups.set(root, (g = []));
28
+ g.push(r);
29
+ }
30
+ return [...groups.values()].sort((a, b) => compareStr(a[0]!, b[0]!));
31
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * knowledge/rules/cycle.ts — `cycle`: one finding per connected group of cycle edges (PRD 38 §3.5).
3
+ * Anchor (PRD 41 §C3): the group's sorted-first member.
4
+ */
5
+
6
+ import { finding, refAnchor } from '../findingBuilder.js';
7
+ import { defineRule } from './factRule.js';
8
+ import { components } from './components.js';
9
+ import { packOfRef, type KnowledgeRuleExtra } from './knowledgeInput.js';
10
+
11
+ export const cycleRule = defineRule<KnowledgeRuleExtra>({
12
+ id: 'cycle',
13
+ version: 1,
14
+ reads: [], // the knowledge graph only
15
+ scope: 'global',
16
+ extraInputs: ['knowledge'],
17
+ derive: ({ extra: { knowledge: k } }) =>
18
+ components(k.graph.edges.filter((e) => e.cycle))
19
+ .map((refs) => finding('cycle', packOfRef(k, refs[0]!), refs, 'warn', { nodes: refs.length }, undefined, refAnchor(refs[0]!))),
20
+ });
@@ -0,0 +1,22 @@
1
+ /**
2
+ * knowledge/rules/duplicateCopy.ts — `duplicate-copy`: a copy of another system in the same root (PRD 41 A9).
3
+ * Its refs name the two systems' folders. Anchor (PRD 41 §C3): the copy's folder.
4
+ */
5
+
6
+ import { finding } from '../findingBuilder.js';
7
+ import { FALLBACK_PACK_ID, srcRef } from '../refs.js';
8
+ import { defineRule } from './factRule.js';
9
+ import type { KnowledgeRuleExtra } from './knowledgeInput.js';
10
+
11
+ export const duplicateCopyRule = defineRule<KnowledgeRuleExtra>({
12
+ id: 'duplicate-copy',
13
+ version: 1,
14
+ reads: [], // the knowledge graph only
15
+ scope: 'global',
16
+ extraInputs: ['knowledge'],
17
+ derive: ({ extra: { knowledge: { graph: g } } }) =>
18
+ (g.meta?.systems ?? []).filter((s) => s.copyOf !== undefined).map((s) =>
19
+ finding('duplicate-copy', FALLBACK_PACK_ID, [srcRef(g.scope.rootId, s.path), srcRef(g.scope.rootId, s.copyOf!)], 'warn', {
20
+ copy: s.path, original: s.copyOf!, similarity: s.copySimilarity ?? 1, reason: s.copyReason ?? 'later-name',
21
+ }, [s.path, s.copyOf!], { anchor: srcRef(g.scope.rootId, s.path), anchorKind: 'file' })),
22
+ });
@@ -0,0 +1,172 @@
1
+ /**
2
+ * src/knowledge/rules/evaluateRules.test.ts — the trace tests (PRD 41 §8 Part B):
3
+ * - a body-only edit reruns `body`-reading rules (io-in-loop) and skips `structure`-only rules;
4
+ * - global rules are skipped when the fact kinds they read did not change anywhere;
5
+ * plus neighbourhood hops, guard chains, extra inputs and rule validation.
6
+ */
7
+
8
+ import type { FileFacts } from '../facts/fileFacts.js';
9
+ import { defineRule } from './factRule.js';
10
+ import { evaluateRules, type RuleEvaluation } from './evaluateRules.js';
11
+ import { callTotal, contentTag, emptyFacts, exportCount, FIXTURE_RULES, ioInLoop, mutualImport, routeGuard, unresolvedImport } from './rules.testkit.test-util.js';
12
+
13
+ const base = (): Map<string, FileFacts> => new Map([
14
+ ['a.ts', { ...emptyFacts('ha'), imports: [{ specifier: './b', resolved: 'b.ts', names: [] }], exports: [{ name: 'a', kind: 'function', signatureHash: 's' }],
15
+ calls: [{ callee: 'db.get', enclosing: 'a', awaited: true, inLoop: true, count: 1 }] }],
16
+ ['b.ts', { ...emptyFacts('hb'), imports: [{ specifier: './c', resolved: 'c.ts', names: [] }] }],
17
+ ['c.ts', emptyFacts('hc')],
18
+ ['d.ts', emptyFacts('hd')],
19
+ ]);
20
+
21
+ const ran = (e: RuleEvaluation) => e.trace.filter((t) => t.outcome === 'ran').map((t) => `${t.rule}@${t.focus}`).sort();
22
+ const outcome = (e: RuleEvaluation, rule: string, focus = '') => e.trace.find((t) => t.rule === rule && t.focus === focus)?.outcome;
23
+
24
+ describe('evaluateRules: verifying traces and early cutoff', () => {
25
+ it('a first evaluation runs every row; an identical one reuses every row', () => {
26
+ const files = base();
27
+ const first = evaluateRules(FIXTURE_RULES, { files });
28
+ expect(first.trace.every((t) => t.outcome === 'ran')).toBe(true);
29
+ const second = evaluateRules(FIXTURE_RULES, { files: base() }, first.rows);
30
+ expect(ran(second)).toEqual([]);
31
+ expect(second.findings).toEqual(first.findings);
32
+ });
33
+
34
+ it('a body-only edit reruns body-reading rules (io-in-loop) and skips structure-only rules', () => {
35
+ const first = evaluateRules(FIXTURE_RULES, { files: base() });
36
+ const files = base();
37
+ files.set('a.ts', { ...files.get('a.ts')!, calls: [] });
38
+ const second = evaluateRules(FIXTURE_RULES, { files }, first.rows);
39
+ expect(ran(second)).toEqual(['call-total@', 'io-in-loop@a.ts']);
40
+ expect(outcome(second, 'export-count', 'a.ts')).toBe('reused');
41
+ expect(outcome(second, 'unresolved-import', 'a.ts')).toBe('reused');
42
+ expect(outcome(second, 'mutual-import')).toBe('reused');
43
+ expect(second.findings.some((x) => x.kind === 'io-in-loop')).toBe(false);
44
+ });
45
+
46
+ it('global rules are skipped when their read kinds did not change anywhere (a comment edit)', () => {
47
+ const first = evaluateRules(FIXTURE_RULES, { files: base() });
48
+ const files = base();
49
+ files.set('c.ts', { ...files.get('c.ts')!, contentHash: 'hc2' });
50
+ const second = evaluateRules(FIXTURE_RULES, { files }, first.rows);
51
+ expect(ran(second)).toEqual(['content-tag@c.ts']);
52
+ expect(outcome(second, 'mutual-import')).toBe('reused');
53
+ expect(outcome(second, 'call-total')).toBe('reused');
54
+ });
55
+
56
+ it('a structure edit reruns the global structure rule and the neighbourhood of the edited file only', () => {
57
+ const first = evaluateRules(FIXTURE_RULES, { files: base() });
58
+ const files = base();
59
+ files.set('c.ts', { ...files.get('c.ts')!, imports: [{ specifier: './b', resolved: 'b.ts', names: [] }] });
60
+ const second = evaluateRules(FIXTURE_RULES, { files }, first.rows);
61
+ // Graph a–b–c, d alone. unresolved-import (1 hop): b {a,b,c} and c {b,c} see c; a {a,b} and d do not.
62
+ // route-guard (2 hops): a, b and c all reach c; d does not.
63
+ expect(ran(second)).toEqual([
64
+ 'export-count@c.ts', 'mutual-import@', 'route-guard@a.ts', 'route-guard@b.ts', 'route-guard@c.ts',
65
+ 'unresolved-import@b.ts', 'unresolved-import@c.ts',
66
+ ]);
67
+ expect(second.findings.map((x) => x.id)).toContain('mutual-import:b.ts<->c.ts');
68
+ });
69
+
70
+ it('a file added or deleted drops or adds its rows, and its neighbours see the new set', () => {
71
+ const first = evaluateRules(FIXTURE_RULES, { files: base() });
72
+ const files = base();
73
+ files.delete('c.ts');
74
+ const second = evaluateRules(FIXTURE_RULES, { files }, first.rows);
75
+ expect([...second.rows.keys()].some((k) => k.endsWith('\u0000c.ts'))).toBe(false);
76
+ expect(second.findings.map((x) => x.id)).toContain('unresolved-import:b.ts->c.ts');
77
+ expect(outcome(second, 'unresolved-import', 'b.ts')).toBe('ran');
78
+ expect(outcome(second, 'unresolved-import', 'd.ts')).toBe('reused');
79
+ });
80
+ });
81
+
82
+ describe('evaluateRules: derive sees only what its trace covers', () => {
83
+ it('a rule that reads an undeclared field sees it empty, and an undeclared extra input absent', () => {
84
+ const seen: unknown[] = [];
85
+ const sneaky = defineRule<{ secret: string }>({
86
+ id: 'sneaky', version: 1, reads: ['body'], scope: 'file',
87
+ derive: ({ focus, files, extra }) => {
88
+ const f = files.get(focus!)!;
89
+ seen.push({ exports: f.exports, imports: f.imports, contentHash: f.contentHash, calls: f.calls.length, secret: extra.secret });
90
+ return [];
91
+ },
92
+ });
93
+ evaluateRules([sneaky], { files: new Map([['a.ts', base().get('a.ts')!]]), extra: { secret: 's' } });
94
+ expect(seen).toEqual([{ exports: [], imports: [], contentHash: '', calls: 1, secret: undefined }]);
95
+ });
96
+
97
+ it('a global rule reading only extra inputs (reads: []) sees no files', () => {
98
+ let count = -1;
99
+ const onlyExtra = defineRule<{ g: string }>({
100
+ id: 'only-extra', version: 1, reads: [], scope: 'global', extraInputs: ['g'],
101
+ derive: ({ files }) => { count = files.size; return []; },
102
+ });
103
+ evaluateRules([onlyExtra], { files: base(), extra: { g: 'x' }, extraHashes: { g: 'h' } });
104
+ expect(count).toBe(0);
105
+ });
106
+ });
107
+
108
+ describe('evaluateRules: guard chains', () => {
109
+ const routed = (): Map<string, FileFacts> => new Map([
110
+ ['routes.ts', { ...emptyFacts('r'), entryPoints: [{ kind: 'http-route', key: 'POST /x', symbol: 'h', guards: ['requireAuth'], inputs: [], chain: ['far/auth.ts'] }] }],
111
+ ['far/auth.ts', { ...emptyFacts('m'), exports: [{ name: 'requireAuth', kind: 'function', signatureHash: 's' }] }],
112
+ ]);
113
+
114
+ it('a route reads its guard-chain file however far it is, and reruns when that file loses the guard', () => {
115
+ const first = evaluateRules([routeGuard], { files: routed() });
116
+ expect(first.findings).toEqual([]);
117
+ const files = routed();
118
+ files.set('far/auth.ts', { ...files.get('far/auth.ts')!, exports: [] });
119
+ const second = evaluateRules([routeGuard], { files }, first.rows);
120
+ expect(outcome(second, 'route-guard', 'routes.ts')).toBe('ran');
121
+ expect(second.findings.map((x) => x.id)).toEqual(['route-guard:routes.ts#POST /x']);
122
+ });
123
+ });
124
+
125
+ describe('evaluateRules: extra inputs', () => {
126
+ const readsGraph = defineRule<{ graph: string }>({
127
+ id: 'reads-graph', version: 1, reads: ['structure'], scope: 'global', extraInputs: ['graph'],
128
+ derive: ({ extra }) => [{ id: `g:${extra.graph}`, kind: 'g', pack: 'p', nodes: [], severity: 'info', params: {} }],
129
+ });
130
+
131
+ it('reruns when the extra input hash moves, and reuses when it holds', () => {
132
+ const files = base();
133
+ const first = evaluateRules([readsGraph], { files, extra: { graph: 'v1' }, extraHashes: { graph: 'h1' } });
134
+ expect(outcome(evaluateRules([readsGraph], { files, extra: { graph: 'v1' }, extraHashes: { graph: 'h1' } }, first.rows), 'reads-graph')).toBe('reused');
135
+ const moved = evaluateRules([readsGraph], { files, extra: { graph: 'v2' }, extraHashes: { graph: 'h2' } }, first.rows);
136
+ expect(outcome(moved, 'reads-graph')).toBe('ran');
137
+ expect(moved.findings.map((x) => x.id)).toEqual(['g:v2']);
138
+ });
139
+
140
+ it('throws when a declared extra input has no hash', () => {
141
+ expect(() => evaluateRules([readsGraph], { files: base(), extra: { graph: 'v1' } })).toThrow('rule_extra_input_unhashed:reads-graph:graph');
142
+ });
143
+
144
+ it('a rule version bump reruns the rule', () => {
145
+ const first = evaluateRules([ioInLoop], { files: base() });
146
+ const bumped = defineRule({ ...ioInLoop, version: 2 });
147
+ expect(ran(evaluateRules([bumped], { files: base() }, first.rows))).toEqual(['io-in-loop@a.ts', 'io-in-loop@b.ts', 'io-in-loop@c.ts', 'io-in-loop@d.ts']);
148
+ });
149
+ });
150
+
151
+ describe('defineRule', () => {
152
+ it('rejects invalid declarations', () => {
153
+ const ok = { id: 'r', version: 1, reads: ['body'] as const, scope: 'neighbourhood' as const, derive: () => [] };
154
+ expect(() => defineRule({ ...ok, hops: 3 })).toThrow('fact_rule_invalid:r:hops');
155
+ expect(() => defineRule({ ...ok, scope: 'file', hops: 1 })).toThrow('fact_rule_invalid:r:hops-outside-neighbourhood');
156
+ expect(() => defineRule({ ...ok, reads: [] })).toThrow('fact_rule_invalid:r:reads');
157
+ expect(() => defineRule({ ...ok, scope: 'global', reads: [] })).toThrow('fact_rule_invalid:r:reads');
158
+ expect(defineRule<{ g: number }>({ ...ok, scope: 'global', reads: [], extraInputs: ['g'] }).reads).toEqual([]);
159
+ expect(() => defineRule({ ...ok, version: 0 })).toThrow('fact_rule_invalid:r:version');
160
+ expect(() => defineRule({ ...ok, scope: 'global', readsGuardChain: true })).toThrow('fact_rule_invalid:r:guard-chain-outside-neighbourhood');
161
+ expect(defineRule({ ...ok, reads: ['structure', 'body', 'body'] }).reads).toEqual(['body', 'structure']);
162
+ });
163
+
164
+ it('evaluateRules refuses two rules with one id', () => {
165
+ expect(() => evaluateRules([exportCount, { ...contentTag, id: 'export-count' }], { files: base() })).toThrow('fact_rule_duplicate:export-count');
166
+ });
167
+
168
+ it('uses every fixture rule', () => {
169
+ expect([ioInLoop, exportCount, contentTag, unresolvedImport, routeGuard, mutualImport, callTotal].map((r) => r.id).sort())
170
+ .toEqual(FIXTURE_RULES.map((r) => r.id).sort());
171
+ });
172
+ });
@@ -0,0 +1,186 @@
1
+ /**
2
+ * knowledge/rules/evaluateRules.ts — the incremental FactRule evaluator (PRD 41 §B1, §B5).
3
+ *
4
+ * Verifying traces with early cutoff (Mokhov, Mitchell, Peyton Jones, *Build Systems à la Carte*): every
5
+ * derived row stores the hash of the inputs it read — the rule's id and version, its focus, and for each
6
+ * file in its scope the hash of each fact kind it `reads`, plus the hash of each declared extra input. On
7
+ * the next evaluation a row whose input hash is unchanged is REUSED without calling `derive`; otherwise
8
+ * the rule reruns. No dirty flags: validity is recomputed from the current facts, so a thrown-away row
9
+ * store rebuilds to the same rows.
10
+ *
11
+ * The trace is ENFORCED, not trusted: `derive` receives each file projected to the kinds the rule reads
12
+ * (`projectFileFacts`, every other field empty) and `extra` cut to its declared `extraInputs`, so an undeclared
13
+ * read sees nothing instead of silently breaking early cutoff.
14
+ *
15
+ * Consequences the trace tests pin: a body-only edit reruns `body`-reading rules for that file and skips
16
+ * `structure`-only rules; a global rule is skipped when no file's read kinds changed anywhere.
17
+ */
18
+
19
+ import { compareStr } from '../refs.js';
20
+ import { sha256Hex } from '../../retrieval/knowledge-index/sha256.js';
21
+ import type { Finding } from '../findingModel.js';
22
+ import { canonicalFileFacts, factKindHashes, projectFileFacts, type FactKind, type FileFacts } from '../facts/fileFacts.js';
23
+ import { DEFAULT_RULE_HOPS, type FactRule } from './factRule.js';
24
+
25
+ /** What the evaluator reads: the current facts by path, the import neighbourhood, and the hashed extra inputs. */
26
+ export interface RuleWorld<X = Record<never, never>> {
27
+ files: ReadonlyMap<string, FileFacts>;
28
+ /** Undirected one-hop neighbours of a path. Default: from the facts' resolved imports ({@link importNeighbours}). */
29
+ neighbours?: (path: string) => readonly string[];
30
+ extra?: X;
31
+ /** The hash of each extra input. A rule that declares an extra input with no hash here throws `rule_extra_input_unhashed`. */
32
+ extraHashes?: Readonly<Record<string, string>>;
33
+ }
34
+
35
+ /** One derived result and the hash of the inputs it read. `focus` is '' for a global rule. */
36
+ export interface DerivedRow {
37
+ rule: string;
38
+ version: number;
39
+ focus: string;
40
+ inputs: string;
41
+ findings: Finding[];
42
+ }
43
+
44
+ export type DerivedRows = ReadonlyMap<string, DerivedRow>;
45
+
46
+ /** What happened to one row in an evaluation. Sorted by rule, then focus. */
47
+ export interface RuleTraceEntry {
48
+ rule: string;
49
+ focus: string;
50
+ outcome: 'ran' | 'reused';
51
+ }
52
+
53
+ export interface RuleEvaluation {
54
+ rows: Map<string, DerivedRow>;
55
+ trace: RuleTraceEntry[];
56
+ /** Every row's findings, deduped by id, sorted by id. */
57
+ findings: Finding[];
58
+ }
59
+
60
+ /** The key of a derived row. */
61
+ export const derivedRowKey = (rule: string, focus: string): string => `${rule}\u0000${focus}`;
62
+
63
+ /** Undirected one-hop import neighbours from each file's resolved imports (only files present), each list sorted. */
64
+ export function importNeighbours(files: ReadonlyMap<string, FileFacts>): (path: string) => readonly string[] {
65
+ const adj = new Map<string, Set<string>>();
66
+ const link = (a: string, b: string) => {
67
+ let s = adj.get(a);
68
+ if (!s) adj.set(a, (s = new Set()));
69
+ s.add(b);
70
+ };
71
+ for (const [path, f] of files) {
72
+ for (const i of f.imports) {
73
+ if (i.resolved === undefined || i.resolved === path || !files.has(i.resolved)) continue;
74
+ link(path, i.resolved);
75
+ link(i.resolved, path);
76
+ }
77
+ }
78
+ const sorted = new Map([...adj].map(([k, v]) => [k, [...v].sort(compareStr)] as const));
79
+ return (path) => sorted.get(path) ?? [];
80
+ }
81
+
82
+ /** The paths a neighbourhood evaluation reads: BFS to `hops`, plus the guard-chain files when declared. Sorted. */
83
+ function neighbourhoodOf(rule: FactRule<any>, focus: string, world: RuleWorld<any>, neighbours: (p: string) => readonly string[]): string[] {
84
+ const seen = new Set([focus]);
85
+ let frontier = [focus];
86
+ for (let hop = 0; hop < (rule.hops ?? DEFAULT_RULE_HOPS); hop++) {
87
+ const next: string[] = [];
88
+ for (const p of frontier) for (const n of neighbours(p)) if (!seen.has(n)) { seen.add(n); next.push(n); }
89
+ frontier = next;
90
+ }
91
+ if (rule.readsGuardChain) {
92
+ for (const e of world.files.get(focus)?.entryPoints ?? []) for (const c of e.chain) if (world.files.has(c)) seen.add(c);
93
+ }
94
+ return [...seen].sort(compareStr);
95
+ }
96
+
97
+ /** `path\0hash\n` of one kind over every file, hashed once per evaluation and shared by every global rule reading that kind. */
98
+ function kindRoots(world: RuleWorld<any>, paths: readonly string[]): (kind: FactKind) => string {
99
+ const roots = new Map<FactKind, string>();
100
+ return (kind) => {
101
+ let root = roots.get(kind);
102
+ if (root === undefined) {
103
+ root = sha256Hex(paths.map((p) => `${p}\u0000${factKindHashes(world.files.get(p)!)[kind]}\n`).join(''));
104
+ roots.set(kind, root);
105
+ }
106
+ return root;
107
+ };
108
+ }
109
+
110
+ /**
111
+ * The trace hash: rule identity, focus, the read kind hashes of each in-scope file (a global rule: the kind roots,
112
+ * which cover every file), each declared extra input's hash.
113
+ */
114
+ function inputsHash(rule: FactRule<any>, focus: string, paths: readonly string[], world: RuleWorld<any>, roots: (kind: FactKind) => string): string {
115
+ const parts = [`${rule.id}\u0000${rule.version}\u0000${rule.scope}\u0000${focus}\n`];
116
+ if (rule.scope === 'global') {
117
+ for (const k of rule.reads) parts.push(`#${k}=${roots(k)}\n`);
118
+ } else {
119
+ for (const p of paths) {
120
+ const kinds = factKindHashes(world.files.get(p)!);
121
+ parts.push(p);
122
+ for (const k of rule.reads) parts.push(`\u0000${k}=${kinds[k]}`);
123
+ parts.push('\n');
124
+ }
125
+ }
126
+ for (const name of [...(rule.extraInputs ?? [])].sort(compareStr)) {
127
+ const hash = world.extraHashes?.[name];
128
+ if (hash === undefined) throw new Error(`rule_extra_input_unhashed:${rule.id}:${name}`);
129
+ parts.push(`@${name}=${hash}\n`);
130
+ }
131
+ return sha256Hex(parts.join(''));
132
+ }
133
+
134
+ const byId = (a: Finding, b: Finding) => compareStr(a.id, b.id);
135
+
136
+ /**
137
+ * Evaluates `rules` against `world`, reusing every row of `previous` whose input hash still holds. Rows for files
138
+ * that no longer exist (and for rules no longer registered) are dropped. Pure: `previous` is not mutated.
139
+ */
140
+ export function evaluateRules<X>(rules: readonly FactRule<X>[], world: RuleWorld<X>, previous: DerivedRows = new Map()): RuleEvaluation {
141
+ const ids = new Set<string>();
142
+ for (const r of rules) {
143
+ if (ids.has(r.id)) throw new Error(`fact_rule_duplicate:${r.id}`);
144
+ ids.add(r.id);
145
+ }
146
+ const paths = [...world.files.keys()].sort(compareStr);
147
+ // Canonical (deep-frozen) facts: the hash and projection caches key on them, and a caller's later mutation never reaches a row.
148
+ const w: RuleWorld<X> = { ...world, files: new Map(paths.map((p) => [p, canonicalFileFacts(world.files.get(p)!)] as const)) };
149
+ let neighbours = w.neighbours;
150
+ const rows = new Map<string, DerivedRow>();
151
+ const trace: RuleTraceEntry[] = [];
152
+ const roots = kindRoots(w, paths);
153
+
154
+ const evaluate = (rule: FactRule<X>, focus: string, scopePaths: readonly string[]) => {
155
+ const key = derivedRowKey(rule.id, focus);
156
+ // The version is part of the hash, so a bumped rule never matches its old row.
157
+ const inputs = inputsHash(rule, focus, scopePaths, w, roots);
158
+ const prior = previous.get(key);
159
+ if (prior && prior.inputs === inputs) {
160
+ rows.set(key, prior);
161
+ trace.push({ rule: rule.id, focus, outcome: 'reused' });
162
+ return;
163
+ }
164
+ // `derive` sees ONLY what its trace covers: each file projected to the kinds it reads, `extra` cut to its declared inputs.
165
+ // A rule reading no fact kind (extra inputs only) sees no files: not even which paths exist is in its trace.
166
+ const files = new Map(rule.reads.length === 0 ? [] : scopePaths.map((p) => [p, projectFileFacts(w.files.get(p)!, rule.reads)] as const));
167
+ const all = (w.extra ?? {}) as Record<string, unknown>;
168
+ const extra = Object.fromEntries((rule.extraInputs ?? []).filter((n) => n in all).map((n) => [n, all[n]])) as X;
169
+ const findings = rule.derive({ scope: rule.scope, ...(focus ? { focus } : {}), files, extra });
170
+ rows.set(key, { rule: rule.id, version: rule.version, focus, inputs, findings: [...findings].sort(byId) });
171
+ trace.push({ rule: rule.id, focus, outcome: 'ran' });
172
+ };
173
+
174
+ for (const rule of [...rules].sort((a, b) => compareStr(a.id, b.id))) {
175
+ if (rule.scope === 'global') { evaluate(rule, '', paths); continue; }
176
+ for (const p of paths) {
177
+ if (rule.scope === 'file') { evaluate(rule, p, [p]); continue; }
178
+ neighbours ??= importNeighbours(w.files);
179
+ evaluate(rule, p, neighbourhoodOf(rule, p, w, neighbours));
180
+ }
181
+ }
182
+
183
+ const found = new Map<string, Finding>();
184
+ for (const row of rows.values()) for (const f of row.findings) if (!found.has(f.id)) found.set(f.id, f);
185
+ return { rows, trace, findings: [...found.values()].sort(byId) };
186
+ }