@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
@@ -0,0 +1,305 @@
1
+ /**
2
+ * knowledge/facts/fileFacts.ts — the per-file fact contract, `FileFacts` v3 (PRD 41 §B1, §B3, §4).
3
+ *
4
+ * What ONE extractor (tree-sitter in Node hosts, regex in the Worker) emits for one file. Pure data: no
5
+ * positions (a line number would move every fact on an edit above it and defeat early cutoff), every
6
+ * array sorted by a declared key ({@link canonicalFileFacts}), canonical-serialized for every hash.
7
+ *
8
+ * The fields split into three FACT KINDS ({@link FACT_KIND_FIELDS}), each with its own hash, so a rule
9
+ * that `reads` only `structure` never reruns for a body or comment edit (early cutoff, §B1):
10
+ * - `structure`: symbols, imports, exports, entry points (the declared surface; a guard added to or
11
+ * removed from a route registration moves it);
12
+ * - `body`: calls, complexity, capability imports, test facts;
13
+ * - `content`: the EOL-normalized bytes themselves, i.e. `contentHash` (contentHash.ts).
14
+ *
15
+ * The header (`factsVersion`, `extractor`, `language`) enters every kind's hash: facts of another
16
+ * extractor are never "the same structure". The extractors live in the hosts (Builderforce.ai
17
+ * agent-tools); memory owns only this shape and its hashing.
18
+ */
19
+
20
+ import { canonicalJson, compareStr, normalizePath, sortBy } from '../refs.js';
21
+ import { sha256Hex } from '../../retrieval/knowledge-index/sha256.js';
22
+ import { FACTS_EXTRACTOR_VERSION } from './extractorVersion.js';
23
+
24
+ /** The three fact kinds a rule may read (§B1). Sorted. */
25
+ export type FactKind = 'body' | 'content' | 'structure';
26
+ export const FACT_KINDS: readonly FactKind[] = Object.freeze(['body', 'content', 'structure'] as const);
27
+
28
+ /** A definition. `name` is the symbol path (`Class.method`); `signatureHash` hashes its normalized signature text. */
29
+ export interface SymbolFact {
30
+ name: string;
31
+ /** 'function' | 'class' | 'method' | 'interface' | 'type' | 'enum' | 'variable' | 'constant' | 'module' … */
32
+ kind: string;
33
+ signatureHash?: string;
34
+ }
35
+
36
+ /** One import statement. `resolved` is the root-relative target file when the host resolved it. */
37
+ export interface ImportFact {
38
+ specifier: string;
39
+ resolved?: string;
40
+ /** Imported binding names (sorted); `*` for a namespace import, `default` for the default binding. */
41
+ names: string[];
42
+ typeOnly?: boolean;
43
+ dynamic?: boolean;
44
+ }
45
+
46
+ /** One exported name (§B3): its kind and the hash of its signature, so a changed signature is a changed export (C7 `api-breaking`). */
47
+ export interface ExportFact {
48
+ name: string;
49
+ kind: string;
50
+ signatureHash: string;
51
+ /** A re-export's source specifier. */
52
+ from?: string;
53
+ }
54
+
55
+ /** Calls of one callee from one enclosing symbol, deduped by every field but `count` (no positions). */
56
+ export interface CallFact {
57
+ /** The callee as written (`db.select`, `fetch`, `fs.readFileSync`). */
58
+ callee: string;
59
+ /** The enclosing symbol path; '' at module top level. */
60
+ enclosing: string;
61
+ awaited?: boolean;
62
+ /** Inside `for` / `while` / `.map` / `.forEach` / `.reduce` (C6.1 `io-in-loop`). */
63
+ inLoop?: boolean;
64
+ count: number;
65
+ }
66
+
67
+ /** McCabe cyclomatic complexity of one function-like symbol. */
68
+ export interface ComplexityFact {
69
+ symbol: string;
70
+ cyclomatic: number;
71
+ }
72
+
73
+ export type EntryPointKind = 'http-route' | 'ws-handler' | 'webview-message' | 'vscode-command' | 'cli-command'
74
+ | 'mcp-tool' | 'queue-consumer' | 'cron' | 'exported-api';
75
+
76
+ /** One entry point (§C5.1, Manadhata–Wing attack surface). */
77
+ export interface EntryPointFact {
78
+ kind: EntryPointKind;
79
+ /** e.g. 'POST /api/projects/:id/knowledge/write'. */
80
+ key: string;
81
+ /** The handler symbol path. */
82
+ symbol: string;
83
+ /** Guard names found on its chain (middleware, wrappers), sorted. Which names are guards is registry data (run-delta). */
84
+ guards: string[];
85
+ /** Untrusted input accessors the handler uses (`req.body`, `c.req.json`, `msg.data`, `argv`), sorted. */
86
+ inputs: string[];
87
+ /**
88
+ * The GUARD CHAIN (§B5): root-relative files of the router, middleware and wrappers resolved from the route
89
+ * registration, sorted. A neighbourhood rule with `readsGuardChain` reads these files' facts whatever their import distance.
90
+ */
91
+ chain: string[];
92
+ }
93
+
94
+ export type CapabilityKind = 'process-exec' | 'fs-write' | 'network-client' | 'network-server' | 'dynamic-code' | 'native-addon'
95
+ | 'crypto' | 'env-read' | 'secret-read';
96
+
97
+ /** One capability the file reaches (§C5.3): the module (and member) that grants it, and the algorithm for crypto. */
98
+ export interface CapabilityImportFact {
99
+ capability: CapabilityKind;
100
+ module: string;
101
+ symbol?: string;
102
+ /** Crypto only: the algorithm named at the call (`md5`, `sha1`, `aes-128-ecb`); weak ones are registry data. */
103
+ algorithm?: string;
104
+ }
105
+
106
+ /** Matcher strength class (§C8.2), strongest first: `exact` (toEqual, toBe) > `partial` (toMatchObject, toContain) > `presence` (toBeTruthy, toBeDefined). */
107
+ export type MatcherStrength = 'exact' | 'partial' | 'presence';
108
+ export const MATCHER_STRENGTH_ORDER: readonly MatcherStrength[] = Object.freeze(['exact', 'partial', 'presence'] as const);
109
+
110
+ export interface MatcherUse {
111
+ matcher: string;
112
+ strength: MatcherStrength;
113
+ count: number;
114
+ }
115
+
116
+ export type TestModifier = 'skip' | 'only' | 'todo';
117
+
118
+ /** One test case (§C8.2). */
119
+ export interface TestCaseFact {
120
+ /** The full title path, `describe › it`. */
121
+ name: string;
122
+ assertions: number;
123
+ matchers: MatcherUse[];
124
+ /** `.skip` / `.only` / `.todo` / `xit`. */
125
+ modifier?: TestModifier;
126
+ timeoutMs?: number;
127
+ /** Hash of the test's normalized expected-value texts, so an edited expectation is detectable (`assertion-edited-with-impl`). */
128
+ expectedHash?: string;
129
+ }
130
+
131
+ /** A test file's facts (§C8.2). Absent on a file that is not a test file. */
132
+ export interface TestFacts {
133
+ framework?: string;
134
+ tests: TestCaseFact[];
135
+ /** Snapshot files the tests read, root-relative, sorted. */
136
+ snapshotFiles: string[];
137
+ }
138
+
139
+ /** FileFacts v3. Every array is sorted by its declared key ({@link canonicalFileFacts}). */
140
+ export interface FileFacts {
141
+ /** {@link FACTS_EXTRACTOR_VERSION} for v3; 2 for facts read through {@link readFileFacts} from a v2 producer. */
142
+ factsVersion: number;
143
+ /** The composite extractor tag for this file's language (`factsExtractorTag`, e.g. `tree-sitter@3.0/typescript=0.23.2/eol-lf@1`). */
144
+ extractor: string;
145
+ language: string;
146
+ /** `contentHash()` of the file's bytes — the `content` kind. */
147
+ contentHash: string;
148
+ // structure
149
+ symbols: SymbolFact[];
150
+ imports: ImportFact[];
151
+ exports: ExportFact[];
152
+ entryPoints: EntryPointFact[];
153
+ // body
154
+ calls: CallFact[];
155
+ complexity: ComplexityFact[];
156
+ capabilityImports: CapabilityImportFact[];
157
+ testFacts?: TestFacts;
158
+ }
159
+
160
+ /** Which fields each kind hashes (data: the ONE place the split is declared). */
161
+ export const FACT_KIND_FIELDS: Readonly<Record<FactKind, readonly (keyof FileFacts)[]>> = Object.freeze({
162
+ structure: ['symbols', 'imports', 'exports', 'entryPoints'],
163
+ body: ['calls', 'complexity', 'capabilityImports', 'testFacts'],
164
+ content: ['contentHash'],
165
+ });
166
+
167
+ const str = (v: unknown) => (v === undefined ? '' : String(v));
168
+ const sorted = (xs: readonly string[] | undefined) => [...(xs ?? [])].sort(compareStr);
169
+ const paths = (xs: readonly string[] | undefined) => sorted((xs ?? []).map(normalizePath));
170
+ /** The final sort key of every list: the whole item, so items equal on the declared keys still sort one way. */
171
+ const whole = (x: unknown) => canonicalJson(x);
172
+
173
+ /** Facts objects produced by {@link canonicalFileFacts}: deep-frozen, so every cache keyed by object identity holds. */
174
+ const canonicalSet = new WeakSet<FileFacts>();
175
+
176
+ function deepFreeze<T>(value: T): T {
177
+ if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
178
+ for (const v of Object.values(value as Record<string, unknown>)) deepFreeze(v);
179
+ Object.freeze(value);
180
+ }
181
+ return value;
182
+ }
183
+
184
+ /**
185
+ * The canonical form: a deep copy with every array sorted by its declared keys then by the whole item, nested string
186
+ * lists sorted, and every path field (`imports[].resolved`, `entryPoints[].chain`, `testFacts.snapshotFiles`) in the
187
+ * ONE path form (`normalizePath`, §B8.1). The result is DEEP-FROZEN: facts are immutable values, and the kind-hash and
188
+ * projection caches key on the object. Idempotent; a canonical object is returned as is.
189
+ */
190
+ export function canonicalFileFacts(f: FileFacts): FileFacts {
191
+ if (canonicalSet.has(f)) return f;
192
+ const out: FileFacts = {
193
+ ...f,
194
+ symbols: sortBy(f.symbols.map((s) => ({ ...s })), (s) => s.name, (s) => s.kind, (s) => str(s.signatureHash), whole),
195
+ imports: sortBy(
196
+ f.imports.map((i) => ({ ...i, names: sorted(i.names), ...(i.resolved !== undefined ? { resolved: normalizePath(i.resolved) } : {}) })),
197
+ (i) => i.specifier, (i) => str(i.resolved), (i) => i.names.join('\u0000'), whole,
198
+ ),
199
+ exports: sortBy(f.exports.map((e) => ({ ...e })), (e) => e.name, (e) => e.kind, (e) => e.signatureHash, (e) => str(e.from), whole),
200
+ entryPoints: sortBy(
201
+ f.entryPoints.map((e) => ({ ...e, guards: sorted(e.guards), inputs: sorted(e.inputs), chain: paths(e.chain) })),
202
+ (e) => e.kind, (e) => e.key, (e) => e.symbol, whole,
203
+ ),
204
+ calls: sortBy(f.calls.map((c) => ({ ...c })), (c) => c.enclosing, (c) => c.callee, (c) => str(c.awaited), (c) => str(c.inLoop), whole),
205
+ complexity: sortBy(f.complexity.map((c) => ({ ...c })), (c) => c.symbol, whole),
206
+ capabilityImports: sortBy(f.capabilityImports.map((c) => ({ ...c })), (c) => c.capability, (c) => c.module, (c) => str(c.symbol), (c) => str(c.algorithm), whole),
207
+ };
208
+ if (f.testFacts) {
209
+ out.testFacts = {
210
+ ...f.testFacts,
211
+ tests: sortBy(
212
+ f.testFacts.tests.map((t) => ({ ...t, matchers: sortBy(t.matchers.map((m) => ({ ...m })), (m) => m.matcher, (m) => m.strength, whole) })),
213
+ (t) => t.name, whole,
214
+ ),
215
+ snapshotFiles: paths(f.testFacts.snapshotFiles),
216
+ };
217
+ }
218
+ deepFreeze(out);
219
+ canonicalSet.add(out);
220
+ return out;
221
+ }
222
+
223
+ /** The header every kind hash includes. */
224
+ const headerOf = (f: FileFacts) => ({ factsVersion: f.factsVersion, extractor: f.extractor, language: f.language });
225
+
226
+ const kindCache = new WeakMap<FileFacts, Readonly<Record<FactKind, string>>>();
227
+
228
+ /**
229
+ * The hash of each fact kind of `f` (canonicalized first). `content` is the content hash itself; `structure` and `body`
230
+ * are sha256 over the canonical JSON of the header plus that kind's fields. Cached per CANONICAL (deep-frozen) object;
231
+ * a non-canonical input is canonicalized and hashed again on every call, so mutating it can never serve a stale hash.
232
+ */
233
+ export function factKindHashes(f: FileFacts): Readonly<Record<FactKind, string>> {
234
+ const c = canonicalFileFacts(f);
235
+ const hit = kindCache.get(c);
236
+ if (hit) return hit;
237
+ const of = (kind: FactKind) => {
238
+ const body: Record<string, unknown> = { header: headerOf(c) };
239
+ for (const field of FACT_KIND_FIELDS[kind]) body[field] = c[field];
240
+ return sha256Hex(canonicalJson(body));
241
+ };
242
+ const hashes = Object.freeze({ body: of('body'), content: c.contentHash, structure: of('structure') });
243
+ kindCache.set(c, hashes);
244
+ return hashes;
245
+ }
246
+
247
+ /** The empty value of every kind's fields: what a rule that does not read that kind sees. */
248
+ const EMPTY_FIELDS: Readonly<Record<FactKind, Partial<FileFacts>>> = Object.freeze({
249
+ structure: { symbols: [], imports: [], exports: [], entryPoints: [] },
250
+ body: { calls: [], complexity: [], capabilityImports: [], testFacts: undefined },
251
+ content: { contentHash: '' },
252
+ });
253
+
254
+ const projectionCache = new WeakMap<FileFacts, Map<string, FileFacts>>();
255
+
256
+ /**
257
+ * `f` (canonicalized) as a rule that reads `reads` sees it: the header plus the fields of the read kinds; every other
258
+ * kind's fields empty. So an undeclared read sees nothing, and can never hide a dependency from the trace (§B5).
259
+ * Deep-frozen; cached per (canonical object, reads).
260
+ */
261
+ export function projectFileFacts(f: FileFacts, reads: readonly FactKind[]): FileFacts {
262
+ const c = canonicalFileFacts(f);
263
+ const key = [...reads].sort().join(',');
264
+ let byReads = projectionCache.get(c);
265
+ if (!byReads) projectionCache.set(c, (byReads = new Map()));
266
+ let hit = byReads.get(key);
267
+ if (!hit) {
268
+ const out: FileFacts = { ...c };
269
+ for (const kind of FACT_KINDS) if (!reads.includes(kind)) Object.assign(out, EMPTY_FIELDS[kind]);
270
+ if (out.testFacts === undefined) delete out.testFacts;
271
+ hit = deepFreeze(out);
272
+ byReads.set(key, hit);
273
+ }
274
+ return hit;
275
+ }
276
+
277
+ /** The content address of a facts object: sha256 of its canonical JSON. */
278
+ export function factsHash(f: FileFacts): string {
279
+ return sha256Hex(canonicalJson(canonicalFileFacts(f)));
280
+ }
281
+
282
+ /**
283
+ * Reads facts from any producer: a v3 object as is (canonicalized), a v2 one (repo-map's symbols + imports, no
284
+ * `factsVersion`) with every v3 list empty and `factsVersion: 2`. A v2 fact set is never comparable with a v3 one
285
+ * (its `factsVersion` and extractor tag differ, C9), so the empty lists never read as "everything was removed".
286
+ */
287
+ export function readFileFacts(raw: Partial<FileFacts> & Pick<FileFacts, 'contentHash'>): FileFacts {
288
+ return canonicalFileFacts({
289
+ factsVersion: raw.factsVersion ?? 2,
290
+ extractor: raw.extractor ?? '',
291
+ language: raw.language ?? '',
292
+ contentHash: raw.contentHash,
293
+ symbols: raw.symbols ?? [],
294
+ imports: raw.imports ?? [],
295
+ exports: raw.exports ?? [],
296
+ entryPoints: raw.entryPoints ?? [],
297
+ calls: raw.calls ?? [],
298
+ complexity: raw.complexity ?? [],
299
+ capabilityImports: raw.capabilityImports ?? [],
300
+ ...(raw.testFacts ? { testFacts: raw.testFacts } : {}),
301
+ });
302
+ }
303
+
304
+ /** Whether a facts object is v3 (current shape). */
305
+ export const isFileFactsV3 = (f: Pick<FileFacts, 'factsVersion'>): boolean => f.factsVersion === FACTS_EXTRACTOR_VERSION;
@@ -1,141 +1,44 @@
1
1
  /**
2
- * knowledge/findings.ts — what a person can act on (PRD 38 §3.5).
2
+ * knowledge/findings.ts — what a person can act on (PRD 38 §3.5): the REGISTRY of the generic finding
3
+ * rules and the compat facade over them (PRD 41 §B5).
3
4
  *
4
- * Generic findings, for every pack: cycle, clone group, near-duplicate, partition
5
- * violation, unpartitioned share, stale knowledge — plus `possible-same` entities. Packs
6
- * add their own through {@link FindingRule}s. Every finding has a stable id (a hash of its
7
- * kind and refs) and a `requestKey` under `knowledgeGraph.fix.*`: the fixed, prefilled
8
- * Fix-with-agent request, never a model call.
5
+ * Generic findings, for every pack: cycle, clone group, near-duplicate, partition violation,
6
+ * duplicate copy, unpartitioned share, stale knowledge, god module — plus `possible-same` entities.
7
+ * Each is ONE FactRule under knowledge/rules/, registered here as data. Packs add their own through
8
+ * {@link FindingRule}s. Every finding has a stable id (a hash of its kind and refs) and a `requestKey`
9
+ * under `knowledgeGraph.fix.*`: the fixed, prefilled Fix-with-agent request, never a model call.
9
10
  */
10
11
 
11
- import { finding, findingId, MAX_FINDING_NODES, refAnchor, requestKeyFor, type FindingAnchor } from './findingBuilder.js';
12
- import type { EdgeVerdict, Finding, KEdge, KNode, KnowledgeGraph, KnowledgePack, NodeRef, PartitionRegistry } from './model.js';
12
+ import { finding, findingId, MAX_FINDING_NODES, requestKeyFor } from './findingBuilder.js';
13
+ import type { Finding, KnowledgeGraph, KnowledgePack, PartitionRegistry } from './model.js';
13
14
  import type { SimilarPair } from '../retrieval/knowledge-index/types.js';
14
- import { godModuleFindings } from './godModule.js';
15
- import { possibleSameFindings } from './resolve.js';
16
- import { aboutTargets, compareStr, FALLBACK_PACK_ID, fileRefOf, round6, srcRef } from './refs.js';
15
+ import { compareStr } from './refs.js';
16
+ import { knowledgeFacts, runKnowledgeRules, type KnowledgeRule } from './rules/knowledgeInput.js';
17
+ import { cycleRule } from './rules/cycle.js';
18
+ import { cloneGroupRule, CLONE_GROUP_BADGE } from './rules/cloneGroup.js';
19
+ import { nearDuplicateRule } from './rules/nearDuplicate.js';
20
+ import { partitionSeverity, partitionViolationRule } from './rules/partitionViolation.js';
21
+ import { duplicateCopyRule } from './rules/duplicateCopy.js';
22
+ import { unpartitionedRule } from './rules/unpartitioned.js';
23
+ import { staleRule } from './rules/stale.js';
24
+ import { godModuleRule } from './rules/godModule.js';
25
+ import { possibleSameRule } from './rules/possibleSame.js';
26
+ import { components } from './rules/components.js';
17
27
 
18
- /** Node badge naming the clone group (e.g. a jscpd issue id) its `duplicate` edges belong to. */
19
- export const CLONE_GROUP_BADGE = 'cloneGroup';
28
+ export { finding, findingId, requestKeyFor, MAX_FINDING_NODES, CLONE_GROUP_BADGE, partitionSeverity, components };
20
29
 
21
30
  const SEVERITY_RANK = { error: 0, warn: 1, info: 2 } as const;
22
31
 
23
- /** A partition violation's severity: an upward edge is an error, a skipped layer a warning. */
24
- export function partitionSeverity(verdict: EdgeVerdict): Finding['severity'] {
25
- return verdict === 'upward' ? 'error' : 'warn';
26
- }
27
-
28
- export { finding, findingId, requestKeyFor, MAX_FINDING_NODES };
32
+ /** The generic finding rules, in emission order. */
33
+ export const GENERIC_FINDING_RULES: readonly KnowledgeRule[] = Object.freeze([
34
+ cycleRule, cloneGroupRule, nearDuplicateRule, partitionViolationRule, duplicateCopyRule, unpartitionedRule, staleRule, godModuleRule,
35
+ ]);
29
36
 
30
- /** Connected components over edges, each sorted; components sorted by first ref. */
31
- export function components(edges: readonly KEdge[]): NodeRef[][] {
32
- const parent = new Map<NodeRef, NodeRef>();
33
- const find = (x: NodeRef): NodeRef => {
34
- let r = x;
35
- while (parent.get(r) !== r) r = parent.get(r)!;
36
- parent.set(x, r);
37
- return r;
38
- };
39
- for (const e of edges) {
40
- for (const r of [e.from, e.to]) if (!parent.has(r)) parent.set(r, r);
41
- const a = find(e.from), b = find(e.to);
42
- if (a !== b) parent.set(compareStr(a, b) < 0 ? b : a, compareStr(a, b) < 0 ? a : b);
43
- }
44
- const groups = new Map<NodeRef, NodeRef[]>();
45
- for (const r of [...parent.keys()].sort(compareStr)) {
46
- const root = find(r);
47
- let g = groups.get(root);
48
- if (!g) groups.set(root, (g = []));
49
- g.push(r);
50
- }
51
- return [...groups.values()].sort((a, b) => compareStr(a[0]!, b[0]!));
52
- }
37
+ /** Every knowledge rule `computeFindings` runs: the generic ones plus `possible-same`. */
38
+ export const KNOWLEDGE_FINDING_RULES: readonly KnowledgeRule[] = Object.freeze([...GENERIC_FINDING_RULES, possibleSameRule]);
53
39
 
54
40
  export function genericFindings(g: KnowledgeGraph, registries: ReadonlyMap<string, PartitionRegistry>): Finding[] {
55
- const byRef = new Map(g.nodes.map((n) => [n.ref, n] as const));
56
- const packOf = (ref: NodeRef) => byRef.get(ref)?.pack ?? FALLBACK_PACK_ID;
57
- const out: Finding[] = [];
58
-
59
- // Anchors (PRD 41 §C3) — one primary per kind, never a line or the member set:
60
- // cycle → its sorted-first member · clone-group → the clone-group badge, else its sorted-first member ·
61
- // near-duplicate → the sorted-first of the pair · partition-violation → from→to layer pair @ the from FILE ·
62
- // duplicate-copy → the copy's FILE · unpartitioned → the pack · stale → the stale source.
63
- for (const refs of components(g.edges.filter((e) => e.cycle))) {
64
- out.push(finding('cycle', packOf(refs[0]!), refs, 'warn', { nodes: refs.length }, undefined, refAnchor(refs[0]!)));
65
- }
66
-
67
- // Clone groups: duplicate edges grouped by the clone-group badge, else by component.
68
- const dup = g.edges.filter((e) => e.kind === 'duplicate');
69
- const byBadge = new Map<string, KEdge[]>();
70
- const unbadged: KEdge[] = [];
71
- for (const e of dup) {
72
- const badge = byRef.get(e.from)?.badges?.[CLONE_GROUP_BADGE] ?? byRef.get(e.to)?.badges?.[CLONE_GROUP_BADGE];
73
- if (badge === undefined) { unbadged.push(e); continue; }
74
- const list = byBadge.get(String(badge)) ?? [];
75
- list.push(e);
76
- byBadge.set(String(badge), list);
77
- }
78
- const groups: Array<{ group: string; refs: NodeRef[] }> = [
79
- ...[...byBadge].map(([group, es]) => ({ group, refs: es.flatMap((e) => [e.from, e.to]) })),
80
- ...components(unbadged).map((refs) => ({ group: '', refs })),
81
- ];
82
- for (const { group, refs } of groups) {
83
- const unique = [...new Set(refs)];
84
- const first = unique.sort(compareStr)[0]!;
85
- const anchor: FindingAnchor = group ? { anchor: `${CLONE_GROUP_BADGE}:${group}`, anchorKind: 'group' } : refAnchor(first);
86
- out.push(finding('clone-group', packOf(first), unique, 'warn', { group, members: unique.length }, undefined, anchor));
87
- }
88
-
89
- for (const e of g.edges) {
90
- if (e.kind === 'near-duplicate') {
91
- const first = compareStr(e.from, e.to) <= 0 ? e.from : e.to;
92
- out.push(finding('near-duplicate', packOf(e.from), [e.from, e.to], 'info', { similarity: round6(e.weight) }, undefined, refAnchor(first)));
93
- }
94
- if (e.verdict === 'upward' || e.verdict === 'skips') {
95
- const from = byRef.get(e.from), to = byRef.get(e.to);
96
- const layers = `${from?.partition ?? ''}->${to?.partition ?? ''}`;
97
- out.push(finding('partition-violation', packOf(e.from), [e.from, e.to], partitionSeverity(e.verdict), {
98
- verdict: e.verdict, from: from?.partition ?? '', to: to?.partition ?? '', kind: e.kind,
99
- }, undefined, { anchor: `${layers}@${fileRefOf(e.from)}`, anchorKind: 'file' }));
100
- }
101
- }
102
-
103
- // A copy of another system in the same root (PRD 41 A9): its refs name the two systems' folders.
104
- for (const s of g.meta?.systems ?? []) {
105
- if (s.copyOf === undefined) continue;
106
- out.push(finding('duplicate-copy', FALLBACK_PACK_ID, [srcRef(g.scope.rootId, s.path), srcRef(g.scope.rootId, s.copyOf)], 'warn', {
107
- copy: s.path, original: s.copyOf, similarity: s.copySimilarity ?? 1, reason: s.copyReason ?? 'later-name',
108
- }, [s.path, s.copyOf], { anchor: srcRef(g.scope.rootId, s.path), anchorKind: 'file' }));
109
- }
110
-
111
- for (const [pack, reg] of [...registries].sort((a, b) => compareStr(a[0], b[0]))) {
112
- if (!reg.allow) continue;
113
- const files = g.nodes.filter((n) => n.pack === pack && n.kind === 'file');
114
- const loose = files.filter((n) => n.partition === undefined).map((n) => n.ref);
115
- if (loose.length === 0) continue;
116
- out.push(finding('unpartitioned', pack, loose, 'info', {
117
- count: loose.length, total: files.length, share: Math.round((loose.length / files.length) * 100),
118
- }, undefined, { anchor: `pack:${pack}`, anchorKind: 'group' }));
119
- }
120
-
121
- out.push(...staleFindings(g, byRef));
122
- out.push(...godModuleFindings(g));
123
- return out;
124
- }
125
-
126
- /** One finding per source whose stored knowledge went stale (unanchored stale nodes: one each). */
127
- function staleFindings(g: KnowledgeGraph, byRef: ReadonlyMap<NodeRef, KNode>): Finding[] {
128
- const about = aboutTargets(g.edges);
129
- const bySource = new Map<NodeRef, NodeRef[]>();
130
- for (const n of g.nodes) {
131
- if (!n.stale) continue;
132
- const target = about.get(n.ref) ?? n.ref;
133
- const list = bySource.get(target) ?? [];
134
- list.push(n.ref);
135
- bySource.set(target, list);
136
- }
137
- return [...bySource].map(([source, refs]) =>
138
- finding('stale', byRef.get(source)?.pack ?? FALLBACK_PACK_ID, [source, ...refs], 'warn', { count: refs.length }, undefined, refAnchor(source)));
41
+ return runKnowledgeRules(GENERIC_FINDING_RULES, knowledgeFacts(g, registries));
139
42
  }
140
43
 
141
44
  /** Generic + possible-same + every pack's rules; deduped by id; severity, then id. */
@@ -145,7 +48,7 @@ export function computeFindings(
145
48
  registries: ReadonlyMap<string, PartitionRegistry>,
146
49
  nearDuplicates: readonly SimilarPair[],
147
50
  ): Finding[] {
148
- const all = [...genericFindings(g, registries), ...possibleSameFindings(nearDuplicates)];
51
+ const all = runKnowledgeRules(KNOWLEDGE_FINDING_RULES, knowledgeFacts(g, registries, nearDuplicates));
149
52
  for (const pack of [...packs].sort((a, b) => compareStr(a.id, b.id))) {
150
53
  for (const rule of pack.findings ?? []) {
151
54
  for (const f of rule.find(g)) {
@@ -49,7 +49,26 @@ export {
49
49
  export type { LanedTrace, TraceOptions } from './trace.js';
50
50
  export {
51
51
  computeFindings, genericFindings, finding, findingId, partitionSeverity, requestKeyFor, components, CLONE_GROUP_BADGE, MAX_FINDING_NODES,
52
+ GENERIC_FINDING_RULES, KNOWLEDGE_FINDING_RULES,
52
53
  } from './findings.js';
54
+ // PRD 41 §B1/§B3/§B5: FileFacts v3, the composite extractor version, FactRule + the incremental evaluator, the fact graph.
55
+ export {
56
+ FACT_KINDS, FACT_KIND_FIELDS, MATCHER_STRENGTH_ORDER, canonicalFileFacts, factKindHashes, factsHash, readFileFacts, isFileFactsV3, projectFileFacts,
57
+ } from './facts/fileFacts.js';
58
+ export type {
59
+ FactKind, FileFacts, SymbolFact, ImportFact, ExportFact, CallFact, ComplexityFact, EntryPointKind, EntryPointFact, CapabilityKind,
60
+ CapabilityImportFact, MatcherStrength, MatcherUse, TestModifier, TestCaseFact, TestFacts,
61
+ } from './facts/fileFacts.js';
62
+ export { FACTS_EXTRACTOR_VERSION, factsExtractorTag, isFactsCurrent, extractorStampMeta } from './facts/extractorVersion.js';
63
+ export type { ExtractorFamily, ExtractorStamp } from './facts/extractorVersion.js';
64
+ export { defineRule, DEFAULT_RULE_HOPS, MAX_RULE_HOPS } from './rules/factRule.js';
65
+ export type { FactRule, RuleInput, RuleScope } from './rules/factRule.js';
66
+ export { evaluateRules, importNeighbours, derivedRowKey } from './rules/evaluateRules.js';
67
+ export type { RuleWorld, DerivedRow, DerivedRows, RuleTraceEntry, RuleEvaluation } from './rules/evaluateRules.js';
68
+ export { emptyFactGraph, updateFactGraph, buildFactGraph, factGraphDump, FACT_GRAPH_DUMP_VERSION } from './rules/factGraph.js';
69
+ export type { FactGraph, FactManifestEntry, FactChange, FactGraphOptions, FactGraphUpdate } from './rules/factGraph.js';
70
+ export { knowledgeFacts, knowledgeInputHash, runKnowledgeRules, packOfRef, KNOWLEDGE_INPUT } from './rules/knowledgeInput.js';
71
+ export type { KnowledgeFacts, KnowledgeRuleExtra, KnowledgeRule } from './rules/knowledgeInput.js';
53
72
  export { refAnchor, type FindingAnchor } from './findingBuilder.js';
54
73
  export {
55
74
  identityOf, defaultAnchorOf, composeAnchor, anchorWithSnippet, anchorKindOfRef, kindOfAnchor, normalizeSnippet, DEFAULT_RULE_VERSION,
@@ -92,6 +92,12 @@ export interface Extracted {
92
92
  sourceHash: string;
93
93
  /** The extractor version (`EXTRACTOR_VERSION`) that produced it; a cached entry of another version is ignored. */
94
94
  extractorVersion?: number;
95
+ /**
96
+ * The caller's extractor key it was made under (`ExtractFileArgs.extractorKey`), absent when none was given. A cached entry
97
+ * made under another key, or with none when one is now given, is ignored (`isCurrentExtractor`). Not carried by the BFKP
98
+ * pack: an extract that went through a pack reads as keyless, so a keyed host re-extracts it once.
99
+ */
100
+ extractorKey?: string;
95
101
  nodes: KNode[];
96
102
  edges: KEdge[];
97
103
  /** Exact keys for entity resolution and the index's exact tier. */
@@ -13,6 +13,8 @@
13
13
  *
14
14
  * Stored under {@link extractorManifestKey} as fingerprints: `{ id: 'version', hash: '<version>' }`
15
15
  * plus `{ id: 'documents', hash: '<pdf,docx|->' }` (the document types the packs claimed, see {@link withDocuments}),
16
+ * `{ id: 'extractorKey', hash: '<key>' }` when the run had a caller-supplied extractor key (another key, or none recorded while one is
17
+ * given, owes every file like a version change; see `isCurrentExtractor`),
16
18
  * `{ id: 'contentHash', hash: '<rule>' }` once {@link CONTENT_HASH_RULE} moves past {@link BASELINE_CONTENT_HASH_RULE} (no record reads as the baseline; another rule is an upgrade),
17
19
  * and one `{ id: 'owed:<path>', hash: '<calls>' }` per owed file, where `<calls>` is the
18
20
  * decimal number of model calls the file is still expected to cost (the plan's estimate):
@@ -30,11 +32,12 @@
30
32
  import type { IngestManifest } from '../ingest/types.js';
31
33
  import { BASELINE_CONTENT_HASH_RULE, CONTENT_HASH_RULE, contentHashRuleOf } from './contentHash.js';
32
34
  import { compareStr } from './refs.js';
33
- import { EXTRACTOR_VERSION, extOf, extractorManifestKey, isBinaryPath, isDocumentPath } from './sources.js';
35
+ import { EXTRACTOR_VERSION, extOf, extractorManifestKey, isBinaryPath, isCurrentExtractor, isDocumentPath } from './sources.js';
34
36
 
35
37
  const VERSION_ID = 'version';
36
38
  const DOCUMENTS_ID = 'documents';
37
39
  const CONTENT_HASH_ID = 'contentHash';
40
+ const EXTRACTOR_KEY_ID = 'extractorKey';
38
41
  /** No document type claimed — also what an entry with no `documents` record means, so a root that never had a host parser stores nothing extra. */
39
42
  const NO_DOCUMENTS = '-';
40
43
  const OWED_PREFIX = 'owed:';
@@ -47,6 +50,10 @@ export interface ExtractorState {
47
50
  version: number | undefined;
48
51
  /** The content-hash rule (contentHash.ts) the files were hashed under, when the entry records one; absent for `eol-lf@1` and for every entry written before the rule existed. */
49
52
  contentHashRule?: string;
53
+ /** The caller's extractor key the files were last reviewed under (`ReviewArgs.extractorKey`); absent when none was given. */
54
+ extractorKey?: string;
55
+ /** The key this run extracts under: set by the plan, carried to *Continue*, saved by the run. Another key than `extractorKey` owes every file. */
56
+ extractorKeyNow?: string;
50
57
  /** Paths a previous run left unfinished under that version → model calls each still costs. */
51
58
  owed: ReadonlyMap<string, number>;
52
59
  /** Consecutive transient failures of a path at one content hash (stored beside its owed entry); a success or a new hash resets it. Optional: a caller that builds a state by hand need not know it. */
@@ -88,6 +95,7 @@ export async function loadExtractorState(manifest: IngestManifest, rootId: strin
88
95
  let version: number | undefined;
89
96
  let documents: string | undefined;
90
97
  let contentHashRule: string | undefined;
98
+ let extractorKey: string | undefined;
91
99
  const owed = new Map<string, number>();
92
100
  const failures = new Map<string, { hash: string; count: number }>();
93
101
  for (const { id, hash } of (await manifest.get(extractorManifestKey(rootId))) ?? []) {
@@ -98,6 +106,8 @@ export async function loadExtractorState(manifest: IngestManifest, rootId: strin
98
106
  documents = hash;
99
107
  } else if (id === CONTENT_HASH_ID) {
100
108
  contentHashRule = hash;
109
+ } else if (id === EXTRACTOR_KEY_ID) {
110
+ extractorKey = hash;
101
111
  } else if (id.startsWith(FAIL_PREFIX)) {
102
112
  const at = hash.indexOf(':');
103
113
  const count = Number(hash.slice(0, at));
@@ -107,7 +117,15 @@ export async function loadExtractorState(manifest: IngestManifest, rootId: strin
107
117
  owed.set(id.slice(OWED_PREFIX.length), Number.isFinite(calls) && calls >= 0 ? calls : UPGRADE_CALLS);
108
118
  }
109
119
  }
110
- return { version, owed, failures, documents: documents ?? NO_DOCUMENTS, ...(contentHashRule !== undefined ? { contentHashRule } : {}) };
120
+ return {
121
+ version, owed, failures, documents: documents ?? NO_DOCUMENTS,
122
+ ...(contentHashRule !== undefined ? { contentHashRule } : {}), ...(extractorKey !== undefined ? { extractorKey } : {}),
123
+ };
124
+ }
125
+
126
+ /** The state with the key this run extracts under (absent or empty: none, as before keys existed). */
127
+ export function withExtractorKey(state: ExtractorState, keyNow: string | undefined): ExtractorState {
128
+ return keyNow ? { ...state, extractorKeyNow: keyNow } : state;
111
129
  }
112
130
 
113
131
  /**
@@ -116,9 +134,16 @@ export async function loadExtractorState(manifest: IngestManifest, rootId: strin
116
134
  * nothing by itself — a host switching to `contentHash` moves the hash of every CRLF file, and those re-extract by content
117
135
  * (`contentChanged`, an extract-cache miss). The entry writes no record for the baseline; a later rule writes one.
118
136
  */
119
- const upgradePending = (state: ExtractorState): boolean =>
137
+ const versionUpgradePending = (state: ExtractorState): boolean =>
120
138
  state.version !== EXTRACTOR_VERSION || contentHashRuleOf(state.contentHashRule) !== CONTENT_HASH_RULE;
121
139
 
140
+ /**
141
+ * True while the files were last reviewed under another extractor version, content-hash rule or caller extractor key
142
+ * ({@link isCurrentExtractor}): every file owes one re-extraction.
143
+ */
144
+ const upgradePending = (state: ExtractorState): boolean =>
145
+ !isCurrentExtractor({ version: state.version, key: state.extractorKey }, state.extractorKeyNow) || versionUpgradePending(state);
146
+
122
147
  /** The file's document extension when its asset-ness flipped (a host parser arrived or left since the last run). */
123
148
  const isFlipped = (state: ExtractorState, path: string): boolean => !!state.flipped?.size && state.flipped.has(extOf(path));
124
149
 
@@ -136,11 +161,13 @@ const isAssetNow = (state: ExtractorState, path: string): boolean => {
136
161
  };
137
162
 
138
163
  /**
139
- * Model calls an owed `path` is expected to cost: its recorded count, plus one while an upgrade is pending or its asset-ness flipped.
140
- * An asset costs none (it is never read or judged); a file that flipped TO a document does.
164
+ * Model calls an owed `path` is expected to cost: its recorded count, plus one while a version (or content-hash rule) upgrade is
165
+ * pending or its asset-ness flipped. A change of the caller's extractor key alone adds nothing: the files re-extract, but their
166
+ * sections' text is the same, so the judgements are re-anchored, not made again. An asset costs none (it is never read or judged);
167
+ * a file that flipped TO a document does.
141
168
  */
142
169
  export const owedCalls = (state: ExtractorState, path: string): number =>
143
- isAssetNow(state, path) ? 0 : (upgradePending(state) || isFlipped(state, path) ? UPGRADE_CALLS : 0) + (state.owed.get(path) ?? 0);
170
+ isAssetNow(state, path) ? 0 : (versionUpgradePending(state) || isFlipped(state, path) ? UPGRADE_CALLS : 0) + (state.owed.get(path) ?? 0);
144
171
 
145
172
  /**
146
173
  * Paths in the files manifest that the plan does not list yet are owed: ignored, claimed by
@@ -179,14 +206,15 @@ export function owedAfterRun(a: {
179
206
  return out;
180
207
  }
181
208
 
182
- /** Records today's version and exactly the files still owed after this run. */
209
+ /** Records today's version (and extractor key, when the run had one) and exactly the files still owed after this run. */
183
210
  export async function saveExtractorState(
184
211
  manifest: IngestManifest, rootId: string, owed: ReadonlyMap<string, number>, failures: ReadonlyMap<string, { hash: string; count: number }> = new Map(),
185
- documents?: string,
212
+ documents?: string, extractorKey?: string,
186
213
  ): Promise<void> {
187
214
  await manifest.set(extractorManifestKey(rootId), [
188
215
  { id: VERSION_ID, hash: String(EXTRACTOR_VERSION) },
189
216
  ...(CONTENT_HASH_RULE !== BASELINE_CONTENT_HASH_RULE ? [{ id: CONTENT_HASH_ID, hash: CONTENT_HASH_RULE }] : []),
217
+ ...(extractorKey ? [{ id: EXTRACTOR_KEY_ID, hash: extractorKey }] : []),
190
218
  ...(documents !== undefined && documents !== NO_DOCUMENTS ? [{ id: DOCUMENTS_ID, hash: documents }] : []),
191
219
  ...[...owed].sort((a, b) => compareStr(a[0], b[0])).map(([path, calls]) => ({ id: `${OWED_PREFIX}${path}`, hash: String(calls) })),
192
220
  ...[...failures].filter(([path]) => owed.has(path)).sort((a, b) => compareStr(a[0], b[0])).map(([path, f]) => ({ id: `${FAIL_PREFIX}${path}`, hash: `${f.count}:${f.hash}` })),