@seanhogg/builderforce-memory 2026.10.71 → 2026.10.73

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 (204) 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 +14 -2
  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 +23 -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/pack/sections/index.d.ts +4 -1
  36. package/dist/knowledge/pack/sections/index.d.ts.map +1 -1
  37. package/dist/knowledge/pack/sections/index.js +7 -3
  38. package/dist/knowledge/pack/sections/index.js.map +1 -1
  39. package/dist/knowledge/pack/sections/rows.d.ts +9 -0
  40. package/dist/knowledge/pack/sections/rows.d.ts.map +1 -1
  41. package/dist/knowledge/pack/sections/rows.js +46 -1
  42. package/dist/knowledge/pack/sections/rows.js.map +1 -1
  43. package/dist/knowledge/plan.d.ts +10 -1
  44. package/dist/knowledge/plan.d.ts.map +1 -1
  45. package/dist/knowledge/plan.js +9 -4
  46. package/dist/knowledge/plan.js.map +1 -1
  47. package/dist/knowledge/review.js +1 -0
  48. package/dist/knowledge/review.js.map +1 -1
  49. package/dist/knowledge/reviewContext.d.ts.map +1 -1
  50. package/dist/knowledge/reviewContext.js +5 -2
  51. package/dist/knowledge/reviewContext.js.map +1 -1
  52. package/dist/knowledge/reviewFinish.d.ts.map +1 -1
  53. package/dist/knowledge/reviewFinish.js +7 -2
  54. package/dist/knowledge/reviewFinish.js.map +1 -1
  55. package/dist/knowledge/reviewModel.d.ts +18 -1
  56. package/dist/knowledge/reviewModel.d.ts.map +1 -1
  57. package/dist/knowledge/reviewPrefetch.d.ts +2 -0
  58. package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
  59. package/dist/knowledge/reviewPrefetch.js +1 -0
  60. package/dist/knowledge/reviewPrefetch.js.map +1 -1
  61. package/dist/knowledge/rules/cloneGroup.d.ts +10 -0
  62. package/dist/knowledge/rules/cloneGroup.d.ts.map +1 -0
  63. package/dist/knowledge/rules/cloneGroup.js +46 -0
  64. package/dist/knowledge/rules/cloneGroup.js.map +1 -0
  65. package/dist/knowledge/rules/components.d.ts +8 -0
  66. package/dist/knowledge/rules/components.d.ts.map +1 -0
  67. package/dist/knowledge/rules/components.js +34 -0
  68. package/dist/knowledge/rules/components.js.map +1 -0
  69. package/dist/knowledge/rules/cycle.d.ts +7 -0
  70. package/dist/knowledge/rules/cycle.d.ts.map +1 -0
  71. package/dist/knowledge/rules/cycle.js +18 -0
  72. package/dist/knowledge/rules/cycle.js.map +1 -0
  73. package/dist/knowledge/rules/duplicateCopy.d.ts +7 -0
  74. package/dist/knowledge/rules/duplicateCopy.d.ts.map +1 -0
  75. package/dist/knowledge/rules/duplicateCopy.js +18 -0
  76. package/dist/knowledge/rules/duplicateCopy.js.map +1 -0
  77. package/dist/knowledge/rules/evaluateRules.d.ts +60 -0
  78. package/dist/knowledge/rules/evaluateRules.d.ts.map +1 -0
  79. package/dist/knowledge/rules/evaluateRules.js +164 -0
  80. package/dist/knowledge/rules/evaluateRules.js.map +1 -0
  81. package/dist/knowledge/rules/factGraph.d.ts +51 -0
  82. package/dist/knowledge/rules/factGraph.d.ts.map +1 -0
  83. package/dist/knowledge/rules/factGraph.js +77 -0
  84. package/dist/knowledge/rules/factGraph.js.map +1 -0
  85. package/dist/knowledge/rules/factRule.d.ts +56 -0
  86. package/dist/knowledge/rules/factRule.d.ts.map +1 -0
  87. package/dist/knowledge/rules/factRule.js +46 -0
  88. package/dist/knowledge/rules/factRule.js.map +1 -0
  89. package/dist/knowledge/rules/godModule.d.ts +8 -0
  90. package/dist/knowledge/rules/godModule.d.ts.map +1 -0
  91. package/dist/knowledge/rules/godModule.js +16 -0
  92. package/dist/knowledge/rules/godModule.js.map +1 -0
  93. package/dist/knowledge/rules/knowledgeInput.d.ts +35 -0
  94. package/dist/knowledge/rules/knowledgeInput.d.ts.map +1 -0
  95. package/dist/knowledge/rules/knowledgeInput.js +33 -0
  96. package/dist/knowledge/rules/knowledgeInput.js.map +1 -0
  97. package/dist/knowledge/rules/nearDuplicate.d.ts +7 -0
  98. package/dist/knowledge/rules/nearDuplicate.d.ts.map +1 -0
  99. package/dist/knowledge/rules/nearDuplicate.js +20 -0
  100. package/dist/knowledge/rules/nearDuplicate.js.map +1 -0
  101. package/dist/knowledge/rules/partitionViolation.d.ts +10 -0
  102. package/dist/knowledge/rules/partitionViolation.d.ts.map +1 -0
  103. package/dist/knowledge/rules/partitionViolation.js +27 -0
  104. package/dist/knowledge/rules/partitionViolation.js.map +1 -0
  105. package/dist/knowledge/rules/possibleSame.d.ts +7 -0
  106. package/dist/knowledge/rules/possibleSame.d.ts.map +1 -0
  107. package/dist/knowledge/rules/possibleSame.js +15 -0
  108. package/dist/knowledge/rules/possibleSame.js.map +1 -0
  109. package/dist/knowledge/rules/stale.d.ts +7 -0
  110. package/dist/knowledge/rules/stale.d.ts.map +1 -0
  111. package/dist/knowledge/rules/stale.js +28 -0
  112. package/dist/knowledge/rules/stale.js.map +1 -0
  113. package/dist/knowledge/rules/unpartitioned.d.ts +7 -0
  114. package/dist/knowledge/rules/unpartitioned.d.ts.map +1 -0
  115. package/dist/knowledge/rules/unpartitioned.js +26 -0
  116. package/dist/knowledge/rules/unpartitioned.js.map +1 -0
  117. package/dist/knowledge/sources.d.ts +13 -0
  118. package/dist/knowledge/sources.d.ts.map +1 -1
  119. package/dist/knowledge/sources.js +14 -0
  120. package/dist/knowledge/sources.js.map +1 -1
  121. package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
  122. package/dist/knowledge/stores/localSnapshotStore.js +5 -0
  123. package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
  124. package/dist/retrieval/knowledge-index/sha256.d.ts.map +1 -1
  125. package/dist/retrieval/knowledge-index/sha256.js +2 -2
  126. package/dist/retrieval/knowledge-index/sha256.js.map +1 -1
  127. package/dist/stats/distributions.d.ts +17 -1
  128. package/dist/stats/distributions.d.ts.map +1 -1
  129. package/dist/stats/distributions.js +26 -1
  130. package/dist/stats/distributions.js.map +1 -1
  131. package/dist/stats/fitting.d.ts.map +1 -1
  132. package/dist/stats/fitting.js +1 -6
  133. package/dist/stats/fitting.js.map +1 -1
  134. package/dist/stats/index.d.ts +10 -3
  135. package/dist/stats/index.d.ts.map +1 -1
  136. package/dist/stats/index.js +10 -3
  137. package/dist/stats/index.js.map +1 -1
  138. package/dist/stats/logistic.d.ts +30 -0
  139. package/dist/stats/logistic.d.ts.map +1 -0
  140. package/dist/stats/logistic.js +43 -0
  141. package/dist/stats/logistic.js.map +1 -0
  142. package/dist/stats/multivariate.d.ts +8 -13
  143. package/dist/stats/multivariate.d.ts.map +1 -1
  144. package/dist/stats/multivariate.js +7 -53
  145. package/dist/stats/multivariate.js.map +1 -1
  146. package/dist/stats/policies.d.ts.map +1 -1
  147. package/dist/stats/policies.js +4 -22
  148. package/dist/stats/policies.js.map +1 -1
  149. package/package.json +4 -3
  150. package/src/contract/exports.snapshot.json +37 -1
  151. package/src/contract/regression.extractorKey.test.ts +202 -0
  152. package/src/contract/regression.scopeMeasured.test.ts +121 -0
  153. package/src/contract/regression.statsEngineFree.test.ts +70 -0
  154. package/src/contract/regression.thompsonDeterminism.test.ts +23 -0
  155. package/src/contract/types.contract.test.ts +66 -2
  156. package/src/knowledge/coChange.test.ts +15 -2
  157. package/src/knowledge/coChange.ts +22 -10
  158. package/src/knowledge/extractFile.ts +27 -5
  159. package/src/knowledge/extractJob.ts +24 -5
  160. package/src/knowledge/facts/extractorVersion.ts +73 -0
  161. package/src/knowledge/facts/fileFacts.test.ts +157 -0
  162. package/src/knowledge/facts/fileFacts.ts +305 -0
  163. package/src/knowledge/findings.ts +30 -127
  164. package/src/knowledge/index.ts +20 -1
  165. package/src/knowledge/model.ts +24 -0
  166. package/src/knowledge/owedFiles.ts +36 -8
  167. package/src/knowledge/pack/pack.testkit.test-util.ts +4 -1
  168. package/src/knowledge/pack/sections/index.ts +7 -3
  169. package/src/knowledge/pack/sections/rows.ts +39 -1
  170. package/src/knowledge/plan.ts +16 -4
  171. package/src/knowledge/review.ts +1 -0
  172. package/src/knowledge/reviewContext.ts +5 -2
  173. package/src/knowledge/reviewFinish.ts +7 -2
  174. package/src/knowledge/reviewModel.ts +18 -1
  175. package/src/knowledge/reviewPrefetch.ts +3 -0
  176. package/src/knowledge/rules/cloneGroup.ts +45 -0
  177. package/src/knowledge/rules/components.ts +31 -0
  178. package/src/knowledge/rules/cycle.ts +20 -0
  179. package/src/knowledge/rules/duplicateCopy.ts +22 -0
  180. package/src/knowledge/rules/evaluateRules.test.ts +172 -0
  181. package/src/knowledge/rules/evaluateRules.ts +186 -0
  182. package/src/knowledge/rules/factGraph.oracle.test.ts +174 -0
  183. package/src/knowledge/rules/factGraph.ts +107 -0
  184. package/src/knowledge/rules/factRule.ts +74 -0
  185. package/src/knowledge/rules/godModule.ts +18 -0
  186. package/src/knowledge/rules/knowledgeInput.ts +60 -0
  187. package/src/knowledge/rules/knowledgeRules.test.ts +78 -0
  188. package/src/knowledge/rules/nearDuplicate.ts +22 -0
  189. package/src/knowledge/rules/partitionViolation.ts +31 -0
  190. package/src/knowledge/rules/possibleSame.ts +17 -0
  191. package/src/knowledge/rules/rules.testkit.test-util.ts +78 -0
  192. package/src/knowledge/rules/stale.ts +31 -0
  193. package/src/knowledge/rules/unpartitioned.ts +27 -0
  194. package/src/knowledge/sources.ts +16 -0
  195. package/src/knowledge/stores/localSnapshotStore.ts +4 -0
  196. package/src/retrieval/knowledge-index/sha256.test.ts +25 -0
  197. package/src/retrieval/knowledge-index/sha256.ts +2 -1
  198. package/src/stats/distributions.ts +29 -2
  199. package/src/stats/fitting.ts +1 -6
  200. package/src/stats/index.ts +12 -2
  201. package/src/stats/logistic.test.ts +89 -0
  202. package/src/stats/logistic.ts +49 -0
  203. package/src/stats/multivariate.ts +8 -59
  204. package/src/stats/policies.ts +4 -24
@@ -22,17 +22,25 @@ import type {
22
22
  } from '../knowledge/index.js';
23
23
  import type { dedupeSymbolEdges } from '../knowledge/index.js';
24
24
  import type { PlannedFile } from '../knowledge/index.js';
25
+ import type { ExtractFileArgs, PlanOptions, ReviewArgs, refreshPlan } from '../knowledge/index.js';
26
+ import type { IngestManifest } from '../ingest/types.js';
25
27
  import type {
26
28
  AnalysisIssue, AnchorKind, CodeAnalysisSnapshot, ComparabilityMeta, Finding, FindingIdentity, LineageEntry,
27
29
  comparable, compareAnalysis, identityOf, matchLineage, isBinaryBytes,
28
30
  } from '../knowledge/index.js';
29
31
  import { placementOf } from '../knowledge/index.js';
32
+ import type { MeasuredWith } from '../knowledge/index.js';
30
33
  import type {
31
34
  applyCoChangeHidden, coChangePartners, coChangeRecallAtK, decodeCoChange, encodeCoChange, mostLikelyWalk, stationTransitions, transitionOf,
32
35
  transitionsFromSequences, transitionsFromWeights, CoChangeBadgeEntry, CoChangeCommit, CoChangeOptions, CoChangePartner, CoChangeRecall,
33
36
  NodeRef, StationTransition, TransitionRow, TransitionSource, TransitionTable,
34
37
  } from '../knowledge/index.js';
35
- import type { rateInterval } from '../stats/index.js';
38
+ import type { betaMoments, logisticProbability, onlineLogisticStep, rateInterval, sigmoid, wilsonInterval } from '../stats/index.js';
39
+ import type {
40
+ CallFact, CapabilityImportFact, DerivedRows, EntryPointFact, EntryPointKind, ExportFact, ExtractorStamp, FactChange, FactGraph, FactGraphOptions,
41
+ FactGraphUpdate, FactKind, FactRule, FileFacts, RuleEvaluation, RuleScope, RuleWorld, TestCaseFact, TestFacts,
42
+ evaluateRules, factGraphDump, factsExtractorTag, updateFactGraph,
43
+ } from '../knowledge/index.js';
36
44
  import { canonicalDump, ExtractFailed, failuresOf, failureTotal, LocalSnapshotStore, localSnapshotStore, type ExtractorState } from '../knowledge/index.js';
37
45
 
38
46
  type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
@@ -52,6 +60,12 @@ export type KnowledgeSnapshot_rows_are_required = Expect<Equal<
52
60
  export const snapshotWithoutExtracted = { version: 1, scopes: [], facts: {}, relations: {} } satisfies KnowledgeSnapshot;
53
61
  export const readsThroughTheEntriesPort = (store: LocalSnapshotStore): Promise<Record<string, Extracted[]>> => store.extractedEntries();
54
62
 
63
+ /* ── ScopeRecord.measured (PRD 41 §C9): recorded when the review runs, carried by the pack's MEAS section ───────────── */
64
+ export type MeasuredWith_shape = Expect<Equal<MeasuredWith, { extractorVersion: string; toolVersions: Record<string, string> }>>;
65
+ export type ScopeRecord_measured_is_optional = Expect<Equal<IsOptional<ScopeRecord, 'measured'>, true>>;
66
+ export type ScopeRecord_measured_shape = Expect<Equal<ScopeRecord['measured'], MeasuredWith | undefined>>;
67
+ export type ReviewArgs_measured = Expect<Equal<Pick<import('../knowledge/index.js').ReviewArgs, 'measured'>, { measured?: MeasuredWith }>>;
68
+
55
69
  /* ── ReviewReport ──────────────────────────────────────────────────────────────────────────────────────────── */
56
70
  export type ReviewReport_judging_fields = Expect<Equal<
57
71
  Pick<ReviewReport, 'awaitingJudge' | 'awaitingJudgeCount' | 'judgedFiles' | 'judgeStopped' | 'failures'>,
@@ -108,7 +122,9 @@ export const jobTheWorkerReadsWithDeadline = { ...base, readByPool: { path: 'a.m
108
122
  // PlannedFile.oversized: an asset only because a claimed document is over the size cap; optional, so a hand-built PlannedFile stays valid.
109
123
  export type PlannedFile_oversized = Expect<Equal<PlannedFile['oversized'], true | undefined>>;
110
124
  export const resultShape = { binary: true, extracted: [anExtract], sections: someSections } satisfies ExtractJobResult;
111
- export type ExtractJobResult_fields = Expect<Equal<ExtractJobResult, { binary?: true; extracted: Extracted[]; sections?: ParsedSection[] }>>;
125
+ // `extractorKey`: the key the worker ACTUALLY extracted under (it echoes its own, never the job's); a mismatch is dropped, not cached.
126
+ export type ExtractJobResult_fields = Expect<Equal<ExtractJobResult, { binary?: true; extracted: Extracted[]; sections?: ParsedSection[]; extractorKey?: string }>>;
127
+ export type ExtractJob_extractorKey = Expect<Equal<Pick<ExtractJob, 'extractorKey'>, { extractorKey?: string }>>;
112
128
  // ExtractFailed: the marker of a PROVEN-final extraction failure (the parser or extractor threw); every other failure is transient.
113
129
  export type ExtractFailed_is_an_Error = Expect<Equal<InstanceType<typeof ExtractFailed> extends Error ? true : false, true>>;
114
130
  export type ExtractFailed_constructor = Expect<Equal<ConstructorParameters<typeof ExtractFailed>, [message: string, options?: { cause?: unknown }]>>;
@@ -118,6 +134,15 @@ export type ExtractorState_failures = Expect<Equal<ExtractorState['failures'], R
118
134
  export type ExtractorState_oversized = Expect<Equal<ExtractorState['oversized'], ReadonlySet<string> | undefined>>;
119
135
  // ExtractorState.contentHashRule: the content-hash rule the entry recorded (absent: none recorded, which never owes a file); optional so a hand-built state stays valid.
120
136
  export type ExtractorState_contentHashRule = Expect<Equal<ExtractorState['contentHashRule'], string | undefined>>;
137
+ // The caller-supplied extractor key (agent-tools: the tsconfig path-alias digest): optional everywhere, so a host passing none is unchanged.
138
+ export type ExtractorState_extractorKey = Expect<Equal<Pick<ExtractorState, 'extractorKey' | 'extractorKeyNow'>, { extractorKey?: string; extractorKeyNow?: string }>>;
139
+ export type Extracted_extractorKey = Expect<Equal<Pick<Extracted, 'extractorKey'>, { extractorKey?: string }>>;
140
+ export type ExtractFileArgs_extractorKey = Expect<Equal<Pick<ExtractFileArgs, 'extractorKey'>, { extractorKey?: string }>>;
141
+ export type PlanOptions_extractorKey = Expect<Equal<Pick<PlanOptions, 'extractorKey'>, { extractorKey?: string }>>;
142
+ export type ReviewArgs_extractorKey = Expect<Equal<Pick<ReviewArgs, 'extractorKey'>, { extractorKey?: string }>>;
143
+ export type refreshPlan_signature = Expect<Equal<
144
+ Parameters<typeof refreshPlan>, [detail: PlanDetail, manifest: IngestManifest, extractorKey?: string]
145
+ >>;
121
146
 
122
147
  /* ── Content identity and directory Merkle hashes (PRD 41 §B2 steps 0 and 4) ───────────────────────────────── */
123
148
  export type contentHash_signature = Expect<Equal<typeof contentHash, (bytes: Uint8Array) => string>>;
@@ -285,6 +310,19 @@ export type coChangeRecallAtK_signature = Expect<Equal<
285
310
  export type applyCoChangeHidden_signature = Expect<Equal<typeof applyCoChangeHidden, (nodes: Iterable<KNode>, edges: Iterable<KEdge>) => void>>;
286
311
  // The one interval of a shown rate (PRD 41 D3), shared by co-change confidence and trace hops.
287
312
  export type rateInterval_signature = Expect<Equal<typeof rateInterval, (k: number, n: number) => { low: number; high: number }>>;
313
+ // PRD 41 D13: the one sigmoid / logistic head, Wilson interval and Beta moments that Builderforce's copies migrate onto.
314
+ export type sigmoid_signature = Expect<Equal<typeof sigmoid, (z: number) => number>>;
315
+ export type logisticProbability_signature = Expect<Equal<
316
+ typeof logisticProbability, (weights: readonly number[], bias: number, x: readonly number[]) => number
317
+ >>;
318
+ export type onlineLogisticStep_signature = Expect<Equal<
319
+ typeof onlineLogisticStep,
320
+ (weights: readonly number[], bias: number, x: readonly number[], label: 0 | 1, learningRate: number) => { weights: number[]; bias: number }
321
+ >>;
322
+ export type wilsonInterval_signature = Expect<Equal<
323
+ typeof wilsonInterval, (successes: number, n: number, z?: number) => { low: number; high: number }
324
+ >>;
325
+ export type betaMoments_signature = Expect<Equal<typeof betaMoments, (alpha: number, beta: number) => { mean: number; variance: number }>>;
288
326
  // PRD 38 P7: station transitions (the view groups stations; memory owns the formula). Reference rows carry no interval.
289
327
  export type TransitionSource_values = Expect<Equal<TransitionSource, 'traces' | 'references'>>;
290
328
  export type StationTransition_fields = Expect<Equal<StationTransition, { to: string; p: number; k: number; n: number; low?: number; high?: number }>>;
@@ -344,6 +382,32 @@ export type CodeAnalysisSnapshot_truncated = Expect<Equal<CodeAnalysisSnapshot['
344
382
  export type CodeAnalysisSnapshot_truncated_is_optional = Expect<Equal<IsOptional<CodeAnalysisSnapshot, 'truncated'>, true>>;
345
383
  export type isBinaryBytes_signature = Expect<Equal<typeof isBinaryBytes, (bytes: Uint8Array) => boolean>>;
346
384
 
385
+ /* ── FileFacts v3, FactRule, the fact graph (PRD 41 §B1/§B3/§B5) ──────────────────────────────────────────── */
386
+ // The Phase 2 extractors (agent-tools, tree-sitter) emit exactly this shape; run-delta rules read it.
387
+ export type FactKind_values = Expect<Equal<FactKind, 'body' | 'content' | 'structure'>>;
388
+ export type FileFacts_keys = Expect<Equal<keyof FileFacts,
389
+ 'factsVersion' | 'extractor' | 'language' | 'contentHash' | 'symbols' | 'imports' | 'exports' | 'entryPoints'
390
+ | 'calls' | 'complexity' | 'capabilityImports' | 'testFacts'>>;
391
+ export type FileFacts_testFacts_is_optional = Expect<Equal<IsOptional<FileFacts, 'testFacts'>, true>>;
392
+ export type EntryPointFact_shape = Expect<Equal<EntryPointFact, {
393
+ kind: EntryPointKind; key: string; symbol: string; guards: string[]; inputs: string[]; chain: string[];
394
+ }>>;
395
+ export type ExportFact_keys = Expect<Equal<keyof ExportFact, 'name' | 'kind' | 'signatureHash' | 'from'>>;
396
+ export type CallFact_keys = Expect<Equal<keyof CallFact, 'callee' | 'enclosing' | 'awaited' | 'inLoop' | 'count'>>;
397
+ export type CapabilityImportFact_keys = Expect<Equal<keyof CapabilityImportFact, 'capability' | 'module' | 'symbol' | 'algorithm'>>;
398
+ export type TestFacts_keys = Expect<Equal<keyof TestFacts, 'framework' | 'tests' | 'snapshotFiles'>>;
399
+ export type TestCaseFact_keys = Expect<Equal<keyof TestCaseFact, 'name' | 'assertions' | 'matchers' | 'modifier' | 'timeoutMs' | 'expectedHash'>>;
400
+ export type FactRule_keys = Expect<Equal<keyof FactRule, 'id' | 'version' | 'reads' | 'scope' | 'hops' | 'readsGuardChain' | 'extraInputs' | 'derive'>>;
401
+ export type RuleScope_values = Expect<Equal<RuleScope, 'file' | 'neighbourhood' | 'global'>>;
402
+ export type factsExtractorTag_signature = Expect<Equal<typeof factsExtractorTag, (stamp: ExtractorStamp, language?: string) => string>>;
403
+ export type evaluateRules_signature = Expect<Equal<
404
+ typeof evaluateRules, <X>(rules: readonly FactRule<X>[], world: RuleWorld<X>, previous?: DerivedRows) => RuleEvaluation
405
+ >>;
406
+ export type updateFactGraph_signature = Expect<Equal<
407
+ typeof updateFactGraph, <X>(graph: FactGraph, changes: readonly FactChange[], rules: readonly FactRule<X>[], opts?: FactGraphOptions<X>) => FactGraphUpdate
408
+ >>;
409
+ export type factGraphDump_signature = Expect<Equal<typeof factGraphDump, (graph: FactGraph) => string>>;
410
+
347
411
  describe('type contract', () => {
348
412
  it('is enforced by `npm run check:contract-types` (tsc over tsconfig.contract.json), not at run time', () => {
349
413
  // The values above only exist so the `satisfies` / `@ts-expect-error` lines are real code; this proves the file loads.
@@ -122,8 +122,8 @@ describe('coChangePartners — partner cap and ranking', () => {
122
122
  expect(coChangePartners(history, { minLift: 2.5 }).size).toBe(0);
123
123
  });
124
124
 
125
- it('computes intervals only for the kept partners', () => {
126
- // Every kept partner carries its interval; the cut ones (p7, p8 of the hub) never reach the output.
125
+ it('every kept partner carries the rate interval of its own together / ofSelf', () => {
126
+ // (That the interval is computed only after the cap is a cost property; the cost guard below covers it.)
127
127
  for (const list of r.values()) for (const p of list) expect([p.low, p.high]).toEqual([round6(rateInterval(p.together, p.ofSelf).low), round6(rateInterval(p.together, p.ofSelf).high)]);
128
128
  });
129
129
 
@@ -164,6 +164,19 @@ describe('co-change badge codec (v1)', () => {
164
164
  expect(decodeCoChange(encodeCoChange(odd)).map((e) => e.ref)).toEqual([ref('b.ts'), ref(path)]);
165
165
  });
166
166
 
167
+ it.each([
168
+ ['an empty ref', { ref: '' }], ['a non-integer together', { together: 2.5 }], ['together 0', { together: 0 }],
169
+ ['a negative together', { together: -1 }], ['together above ofSelf', { together: 7 }], ['a NaN ofSelf', { ofSelf: Number.NaN }],
170
+ ['a NaN low', { low: Number.NaN }], ['a NaN high', { high: Number.NaN }], ['a negative low', { low: -0.1 }],
171
+ ['high above 1', { high: 1.5 }], ['an infinite high', { high: Number.POSITIVE_INFINITY }], ['low above high', { low: 0.9, high: 0.8 }],
172
+ ['a newline in the ref', { ref: `${ref('x')}\ny` }],
173
+ ])('encode drops an entry with %s and keeps the rest decodable', (_name, bad) => {
174
+ const good = partners[0]!;
175
+ const value = encodeCoChange([good, { ...good, ...bad } as CoChangePartner, partners[1]!]);
176
+ expect(value).toBe(encodeCoChange([good, partners[1]!]));
177
+ expect(decodeCoChange(value).map((e) => e.ref)).toEqual([ref('b.ts'), ref('c d.ts')]);
178
+ });
179
+
167
180
  it('an empty list is the bare version line, which decodes to nothing', () => {
168
181
  expect(encodeCoChange([])).toBe('v1');
169
182
  expect(decodeCoChange('v1')).toEqual([]);
@@ -227,8 +227,8 @@ function partnersOf(kept: readonly KeptCommit[], opts: CoChangeOptions): Map<Nod
227
227
  };
228
228
  const out = new Map<NodeRef, CoChangePartner[]>();
229
229
  for (const i of [...lists.keys()].sort((a, b) => a - b)) {
230
- const kept = lists.get(i)!.sort(byRank).slice(0, maxPartners);
231
- out.set(order[i]!, kept.map((c) => ({ ...c, ...intervalOf(c.together, c.ofSelf) })));
230
+ const top = lists.get(i)!.sort(byRank).slice(0, maxPartners);
231
+ out.set(order[i]!, top.map((c) => ({ ...c, ...intervalOf(c.together, c.ofSelf) })));
232
232
  }
233
233
  return out;
234
234
  }
@@ -240,10 +240,15 @@ export function coChangePartners(commits: ReadonlyArray<CoChangeCommit>, opts: C
240
240
 
241
241
  /**
242
242
  * The `coChange` badge value: the line `v1`, then `${together}\t${ofSelf}\t${low}\t${high}\t${ref}` per partner, '\n'-joined
243
- * (the ref is the line remainder). A ref holding a newline cannot be carried and is skipped.
243
+ * (the ref is the line remainder). An entry the decoder would reject is dropped, never written (one bad line would void the
244
+ * whole badge): a ref that is empty or holds a newline, `together` not an integer ≥ 1 or above `ofSelf`, and `low` / `high`
245
+ * that are not numbers in 0 ≤ low ≤ high ≤ 1. Each line is checked by the decoder's own {@link parseLine}.
244
246
  */
245
247
  export function encodeCoChange(partners: readonly CoChangePartner[]): string {
246
- const lines = partners.filter((p) => !p.ref.includes('\n')).map((p) => `${p.together}\t${p.ofSelf}\t${p.low}\t${p.high}\t${p.ref}`);
248
+ const lines = partners
249
+ .filter((p) => !p.ref.includes('\n'))
250
+ .map((p) => `${p.together}\t${p.ofSelf}\t${p.low}\t${p.high}\t${p.ref}`)
251
+ .filter((line) => parseLine(line) !== undefined);
247
252
  return [BADGE_VERSION, ...lines].join('\n');
248
253
  }
249
254
 
@@ -251,6 +256,16 @@ const NUM = String.raw`(\d+(?:\.\d+)?(?:e-\d+)?)`;
251
256
  // `s`: the ref is the line remainder and may hold '\r', U+2028 or U+2029 (the value is already split on '\n').
252
257
  const LINE = new RegExp(String.raw`^(\d+)\t(\d+)\t${NUM}\t${NUM}\t(.+)$`, 's');
253
258
 
259
+ /** THE validity of one partner line, shared by the encoder (to drop) and the decoder (to reject). */
260
+ function parseLine(line: string): CoChangeBadgeEntry | undefined {
261
+ const hit = LINE.exec(line);
262
+ if (!hit) return undefined;
263
+ const together = Number(hit[1]), ofSelf = Number(hit[2]), low = Number(hit[3]), high = Number(hit[4]);
264
+ if (!Number.isSafeInteger(together) || !Number.isSafeInteger(ofSelf) || together < 1 || together > ofSelf) return undefined;
265
+ if (!(low >= 0 && low <= high && high <= 1)) return undefined;
266
+ return { ref: hit[5]! as NodeRef, together, ofSelf, low, high };
267
+ }
268
+
254
269
  /** The partners of a `coChange` badge; [] for anything that is not a well-formed v1 value (one bad line voids it). */
255
270
  export function decodeCoChange(value: unknown): CoChangeBadgeEntry[] {
256
271
  if (typeof value !== 'string') return [];
@@ -258,12 +273,9 @@ export function decodeCoChange(value: unknown): CoChangeBadgeEntry[] {
258
273
  if (version !== BADGE_VERSION) return [];
259
274
  const out: CoChangeBadgeEntry[] = [];
260
275
  for (const line of lines) {
261
- const hit = LINE.exec(line);
262
- if (!hit) return [];
263
- const together = Number(hit[1]), ofSelf = Number(hit[2]), low = Number(hit[3]), high = Number(hit[4]);
264
- if (!Number.isSafeInteger(together) || !Number.isSafeInteger(ofSelf) || together < 1 || together > ofSelf) return [];
265
- if (!(low >= 0 && low <= high && high <= 1)) return [];
266
- out.push({ ref: hit[5]! as NodeRef, together, ofSelf, low, high });
276
+ const entry = parseLine(line);
277
+ if (!entry) return [];
278
+ out.push(entry);
267
279
  }
268
280
  return out;
269
281
  }
@@ -8,10 +8,13 @@
8
8
 
9
9
  import type { ParsedSection, SourceDocument } from '../ingest/types.js';
10
10
  import type { Extracted, KnowledgePack, KnowledgeParser, KnowledgeStore, NodeRef } from './model.js';
11
- import { BinaryContent, CHANGED_SINCE_PLAN, ExtractFailed, jobOf, runExtractor, type ExtractPool } from './extractJob.js';
11
+ import { BinaryContent, CHANGED_SINCE_PLAN, EXTRACTOR_KEY_MISMATCH, ExtractFailed, jobOf, runExtractor, type ExtractPool } from './extractJob.js';
12
12
  import { srcRef } from './refs.js';
13
13
  import { entityName, knownKeysOf, resolveEntities } from './resolve.js';
14
- import { asPathSource, composePacks, EXTRACTOR_VERSION, isAssetExtract, resolveRelativePath, stubSource, type ComposedPacks } from './sources.js';
14
+ import {
15
+ asPathSource, composePacks, EXTRACTOR_VERSION, isAssetExtract, isCurrentExtractor, resolveRelativePath, sameExtractorKey, stubSource,
16
+ type ComposedPacks,
17
+ } from './sources.js';
15
18
 
16
19
  /** The normalized entity keys of `ent:` fact keys, for `mentions`. */
17
20
  export function knownKeysOfEntities(keys: Iterable<string>): ReadonlyMap<string, NodeRef> {
@@ -50,6 +53,16 @@ export interface ExtractFileArgs {
50
53
  onTiming?: (t: { lookupMs: number; poolMs: number }) => void;
51
54
  /** Leave the extract cache write to the caller (the review writes it in plan order); default: write it. */
52
55
  writeCache?: boolean;
56
+ /**
57
+ * An input the extractors read besides the file's bytes (agent-tools: a digest of the tsconfig path aliases). A fresh
58
+ * extract is stamped with it, and a cached one made under another key (or none) is not reused. Absent or '': no key, as
59
+ * before keys existed.
60
+ *
61
+ * With a `pool`, the job carries it but the worker extracts with what IT holds and echoes its own key
62
+ * (`ExtractJobResult.extractorKey`); a different echo is neither cached nor used (the file stays owed). So a host pool MUST
63
+ * rebuild its key-dependent inputs (re-read the aliases) whenever the key it is asked for changes.
64
+ */
65
+ extractorKey?: string;
53
66
  }
54
67
 
55
68
  export interface FileExtraction {
@@ -98,9 +111,10 @@ export async function extractFileDetailed(a: ExtractFileArgs): Promise<FileExtra
98
111
  const tLookup = Date.now();
99
112
  const cached = await a.store.getExtracted?.(a.hash);
100
113
  const lookupMs = Date.now() - tLookup;
101
- // A cached entry of another extractor version is ignored: its output may differ from today's. So is an asset's entry
114
+ // A cached entry of another extractor version or key is ignored: its output may differ from today's. So is an asset's entry
102
115
  // (a document stored as an asset before a host parser claimed it): it holds no extraction.
103
- const found = cached?.find((e) => e.sourceRef === ref && e.extractorVersion === EXTRACTOR_VERSION && !isAssetExtract(e));
116
+ const found = cached?.find((e) => e.sourceRef === ref && !isAssetExtract(e)
117
+ && isCurrentExtractor({ version: e.extractorVersion, key: e.extractorKey }, a.extractorKey));
104
118
  if (found) {
105
119
  const tSections = Date.now();
106
120
  if (a.pool && wants) {
@@ -117,7 +131,10 @@ export async function extractFileDetailed(a: ExtractFileArgs): Promise<FileExtra
117
131
  let extracted: Extracted;
118
132
  if (a.pool) {
119
133
  const tPool = Date.now();
120
- const out = await a.pool(jobOf({ rootId: a.rootId, path: a.path, hash: a.hash, knownKeys, needSections: wants, ...(a.readMs ? { readMs: a.readMs } : {}), ...jobSource(a) }), a.signal);
134
+ const out = await a.pool(jobOf({
135
+ rootId: a.rootId, path: a.path, hash: a.hash, knownKeys, needSections: wants, ...(a.readMs ? { readMs: a.readMs } : {}),
136
+ ...(a.extractorKey ? { extractorKey: a.extractorKey } : {}), ...jobSource(a),
137
+ }), a.signal);
121
138
  a.onTiming?.({ lookupMs, poolMs: Date.now() - tPool });
122
139
  if (out.binary) throw new BinaryContent();
123
140
  // Exact match only: a result for another file, or none although the packs accept this one, is a failure.
@@ -125,6 +142,8 @@ export async function extractFileDetailed(a: ExtractFileArgs): Promise<FileExtra
125
142
  if (!mine) throw new Error(`extract pool returned no extract for ${a.path}`);
126
143
  // The pool read other bytes than the plan hashed: nothing is stored under the planned hash.
127
144
  if (mine.sourceHash !== a.hash) throw new Error(CHANGED_SINCE_PLAN); // transient: the bytes may settle
145
+ // The worker extracted under another key than asked (it still holds old aliases): neither cached nor used, the file stays owed.
146
+ if (a.extractorKey && !sameExtractorKey(out.extractorKey, a.extractorKey)) throw new Error(EXTRACTOR_KEY_MISMATCH);
128
147
  if (wants) {
129
148
  if (!out.sections) throw new Error(`extract pool returned no sections for ${a.path}`);
130
149
  sections = out.sections;
@@ -133,6 +152,9 @@ export async function extractFileDetailed(a: ExtractFileArgs): Promise<FileExtra
133
152
  } else {
134
153
  extracted = proven(() => runExtractor(hit, src, sections, { rootId: a.rootId, knownKeys, resolvePath: resolveRelativePath }, a));
135
154
  }
155
+ // The stamp is the key the extract was made under: the worker's echo (equal to the request, checked above) or, in this thread,
156
+ // the caller's. No key asked: nothing is stamped, as before keys existed.
157
+ if (a.extractorKey) extracted = { ...extracted, extractorKey: a.extractorKey };
136
158
  if (a.writeCache !== false) await putExtract(a.store, a.hash, extracted, cached ?? []);
137
159
  return { extracted, parser: hit.parser, pack: hit.pack, sections, cached: false };
138
160
  }
@@ -28,6 +28,11 @@ export interface ExtractJobBase {
28
28
  needSections?: boolean;
29
29
  /** The extract is already cached and only the sections are wanted: skip extracting. Implies `needSections`. */
30
30
  sectionsOnly?: boolean;
31
+ /**
32
+ * The extractor key the review extracts under (`ExtractFileArgs.extractorKey`). A worker does NOT adopt it: it extracts with
33
+ * the inputs it holds and echoes ITS key in {@link ExtractJobResult.extractorKey}; a mismatch is not cached (the file stays owed).
34
+ */
35
+ extractorKey?: string;
31
36
  }
32
37
 
33
38
  /**
@@ -64,8 +69,18 @@ export interface ExtractJobResult {
64
69
  binary?: true;
65
70
  extracted: Extracted[];
66
71
  sections?: ParsedSection[];
72
+ /**
73
+ * The extractor key the worker ACTUALLY extracted under (e.g. the digest of the path aliases it resolved with), absent when it
74
+ * has none. The review stamps the extract with this key, and when a key was asked for and this one differs (a long-lived worker
75
+ * still holding old aliases), the result is neither cached nor used: the file stays owed. A host pool must rebuild its
76
+ * key-dependent inputs (and so its key) when the requested key changes.
77
+ */
78
+ extractorKey?: string;
67
79
  }
68
80
 
81
+ /** The pool extracted under another extractor key than the review asked for: nothing is cached, the file stays owed. Transient. */
82
+ export const EXTRACTOR_KEY_MISMATCH = 'extractor key mismatch';
83
+
69
84
  /**
70
85
  * A host's extraction pool: called for a changed file whose extract is not cached (or, with
71
86
  * `sectionsOnly`, whose sections are needed). `signal` is the review's: a stopped review should
@@ -94,12 +109,13 @@ export function runExtractor(
94
109
  export function jobOf(
95
110
  f: {
96
111
  rootId: string; path: string; hash: string; knownKeys: ReadonlyMap<string, NodeRef>;
97
- needSections?: boolean; sectionsOnly?: boolean; readMs?: number;
112
+ needSections?: boolean; sectionsOnly?: boolean; readMs?: number; extractorKey?: string;
98
113
  } & ({ doc: SourceDocument; readByPool?: false } | { doc?: undefined; readByPool: true; /** The path the worker opens (the source's spelling); default `path`. */ readPath?: string }),
99
114
  ): ExtractJob {
100
115
  return {
101
116
  rootId: f.rootId, path: f.path, hash: f.hash, knownKeys: [...f.knownKeys],
102
117
  ...(f.needSections ? { needSections: true } : {}), ...(f.sectionsOnly ? { sectionsOnly: true } : {}),
118
+ ...(f.extractorKey ? { extractorKey: f.extractorKey } : {}),
103
119
  ...(f.readByPool ? { readByPool: { path: f.readPath ?? f.path, hash: f.hash, ...(f.readMs ? { readMs: f.readMs } : {}) } } : { doc: f.doc! }),
104
120
  } as ExtractJob;
105
121
  }
@@ -107,17 +123,20 @@ export function jobOf(
107
123
  /**
108
124
  * Extracts one file from a job — pure: no store, no clock. `extracted` is `[]` when no pack's parser
109
125
  * accepts the file. `packs` is the worker's own pack list (or its composition, to compose once).
126
+ * `workerKey` is the extractor key THESE packs were built under (absent: none); it is echoed as the result's `extractorKey`,
127
+ * never copied from the job, so a worker holding stale inputs is caught by the review rather than stamped with the new key.
110
128
  */
111
- export function extractJob(job: ExtractJob, packs: readonly KnowledgePack[] | ComposedPacks): ExtractJobResult {
129
+ export function extractJob(job: ExtractJob, packs: readonly KnowledgePack[] | ComposedPacks, workerKey?: string): ExtractJobResult {
112
130
  const composed = Array.isArray(packs) ? composePacks(packs as readonly KnowledgePack[]) : (packs as ComposedPacks);
113
131
  // A pure job has no filesystem: a `readByPool` job is for a worker that reads (the host's handler), not for this function.
114
132
  if (!job.doc) throw new Error(`extract job for ${job.path} carries no document (readByPool needs a reading worker)`);
133
+ const echo = workerKey ? { extractorKey: workerKey } : {};
115
134
  const src = asPathSource(job.doc, job.path, job.hash);
116
135
  const hit = composed.resolve(src);
117
- if (!hit) return { extracted: [] };
136
+ if (!hit) return { extracted: [], ...echo };
118
137
  const sections = hit.parser.parse(src);
119
138
  const wantSections = job.needSections || job.sectionsOnly;
120
- if (job.sectionsOnly) return { extracted: [], sections };
139
+ if (job.sectionsOnly) return { extracted: [], sections, ...echo };
121
140
  const ctx: ExtractContext = { rootId: job.rootId, knownKeys: new Map(job.knownKeys), resolvePath: resolveRelativePath };
122
- return { extracted: [runExtractor(hit, src, sections, ctx, job)], ...(wantSections ? { sections } : {}) };
141
+ return { extracted: [runExtractor(hit, src, sections, ctx, job)], ...(wantSections ? { sections } : {}), ...echo };
123
142
  }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * knowledge/facts/extractorVersion.ts — the COMPOSITE extractor version of `FileFacts` (PRD 41 §B3).
3
+ *
4
+ * A fact set is identified by more than one number: the extractor code version, each tree-sitter
5
+ * grammar's package version, and the content-hash (EOL) rule. {@link factsExtractorTag} composes them into
6
+ * the `extractor` tag a `FileFacts` carries — per LANGUAGE, so a grammar bump changes the tag of (and so
7
+ * re-extracts) only the files of that language. {@link extractorStampMeta} gives the whole stamp as a
8
+ * `ComparabilityMeta` so `comparable()` (C9) reports a family, code, grammar or EOL change by reason.
9
+ *
10
+ * Separate from `EXTRACTOR_VERSION` (sources.ts), which versions the knowledge packs' `Extracted`
11
+ * nodes and edges; this one versions the fact contract the rules read.
12
+ */
13
+
14
+ import type { ComparabilityMeta } from '../comparability.js';
15
+ import { CONTENT_HASH_RULE, contentHashRuleOf } from '../contentHash.js';
16
+ import { compareStr } from '../refs.js';
17
+
18
+ /** The FileFacts contract version (v3: exports, calls, entry points, capability imports, test facts). Bump on a shape change. */
19
+ export const FACTS_EXTRACTOR_VERSION = 3;
20
+
21
+ /** Tree-sitter in Node hosts; the regex fallback in the Worker. The two never mix in one comparison (§B3, C9). */
22
+ export type ExtractorFamily = 'tree-sitter' | 'regex';
23
+
24
+ /** What a host's extractor is built from. */
25
+ export interface ExtractorStamp {
26
+ family: ExtractorFamily;
27
+ /** The host extractor's own revision within {@link FACTS_EXTRACTOR_VERSION} (queries changed, same shape). Default 0. */
28
+ revision?: number;
29
+ /** Language → grammar package version (`typescript` → `0.23.2`). A regex extractor has none. */
30
+ grammars?: Readonly<Record<string, string>>;
31
+ /** The content-hash rule the host hashes with. Default {@link CONTENT_HASH_RULE}. */
32
+ contentHashRule?: string;
33
+ }
34
+
35
+ const codeOf = (stamp: ExtractorStamp) => `${stamp.family}@${FACTS_EXTRACTOR_VERSION}.${stamp.revision ?? 0}`;
36
+ const ruleOf = (stamp: ExtractorStamp) => contentHashRuleOf(stamp.contentHashRule ?? CONTENT_HASH_RULE);
37
+
38
+ /**
39
+ * The composite tag: `<family>@<version>.<revision>/<language>=<grammar>/<eol rule>` for one language (the grammar
40
+ * part omitted when that language has none), or with every grammar (`a=1,b=2`, sorted) when `language` is omitted.
41
+ * The family is the part before the first `@`, as `comparable()` reads it.
42
+ */
43
+ export function factsExtractorTag(stamp: ExtractorStamp, language?: string): string {
44
+ const grammars = stamp.grammars ?? {};
45
+ const parts = [codeOf(stamp)];
46
+ if (language !== undefined) {
47
+ if (grammars[language] !== undefined) parts.push(`${language}=${grammars[language]}`);
48
+ } else {
49
+ const all = Object.keys(grammars).sort(compareStr).map((l) => `${l}=${grammars[l]}`);
50
+ if (all.length > 0) parts.push(all.join(','));
51
+ }
52
+ parts.push(ruleOf(stamp));
53
+ return parts.join('/');
54
+ }
55
+
56
+ /** Whether facts were produced by this stamp for their language: false ⇒ the file is owed a re-extraction. */
57
+ export function isFactsCurrent(facts: { factsVersion: number; extractor: string; language: string }, stamp: ExtractorStamp): boolean {
58
+ return facts.factsVersion === FACTS_EXTRACTOR_VERSION && facts.extractor === factsExtractorTag(stamp, facts.language);
59
+ }
60
+
61
+ /**
62
+ * The stamp as comparability meta: `extractor` = family@version.revision, the EOL rule, and each grammar as tool
63
+ * `grammar:<language>` — so `comparable()` names exactly which part moved.
64
+ */
65
+ export function extractorStampMeta(stamp: ExtractorStamp): ComparabilityMeta {
66
+ const grammars = stamp.grammars ?? {};
67
+ return {
68
+ extractor: codeOf(stamp),
69
+ extractorVersion: FACTS_EXTRACTOR_VERSION,
70
+ contentHashRule: ruleOf(stamp),
71
+ tools: Object.fromEntries(Object.keys(grammars).sort(compareStr).map((l) => [`grammar:${l}`, grammars[l]!])),
72
+ };
73
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * src/knowledge/facts/fileFacts.test.ts — FileFacts v3 (PRD 41 §B1, §B3): canonical order, per-kind hashes
3
+ * (a body edit never moves the structure hash), v2 reads, and the composite extractor version.
4
+ */
5
+
6
+ import { comparable } from '../comparability.js';
7
+ import { canonicalFileFacts, factKindHashes, factsHash, readFileFacts, isFileFactsV3, projectFileFacts, type FileFacts } from './fileFacts.js';
8
+ import { extractorStampMeta, factsExtractorTag, FACTS_EXTRACTOR_VERSION, isFactsCurrent, type ExtractorStamp } from './extractorVersion.js';
9
+
10
+ const STAMP: ExtractorStamp = { family: 'tree-sitter', grammars: { typescript: '0.23.2', python: '0.23.6' } };
11
+
12
+ const facts = (over: Partial<FileFacts> = {}): FileFacts => ({
13
+ factsVersion: FACTS_EXTRACTOR_VERSION,
14
+ extractor: factsExtractorTag(STAMP, 'typescript'),
15
+ language: 'typescript',
16
+ contentHash: 'c1',
17
+ symbols: [{ name: 'b', kind: 'function' }, { name: 'a', kind: 'function' }],
18
+ imports: [{ specifier: './z', resolved: 'z.ts', names: ['y', 'x'] }, { specifier: './a', resolved: 'a.ts', names: [] }],
19
+ exports: [{ name: 'b', kind: 'function', signatureHash: 's2' }, { name: 'a', kind: 'function', signatureHash: 's1' }],
20
+ entryPoints: [{ kind: 'http-route', key: 'POST /x', symbol: 'h', guards: ['requireAuth', 'audit'], inputs: ['req.body'], chain: ['mw.ts', 'app.ts'] }],
21
+ calls: [{ callee: 'fetch', enclosing: 'b', awaited: true, inLoop: true, count: 1 }, { callee: 'db.select', enclosing: 'a', count: 2 }],
22
+ complexity: [{ symbol: 'b', cyclomatic: 3 }, { symbol: 'a', cyclomatic: 1 }],
23
+ capabilityImports: [{ capability: 'network-client', module: 'node:http' }, { capability: 'crypto', module: 'node:crypto', algorithm: 'md5' }],
24
+ ...over,
25
+ });
26
+
27
+ describe('canonicalFileFacts', () => {
28
+ it('sorts every array by its declared key, so producer order never reaches a hash', () => {
29
+ const a = facts();
30
+ const b = facts({ symbols: [...a.symbols].reverse(), imports: [...a.imports].reverse(), calls: [...a.calls].reverse() });
31
+ expect(factsHash(a)).toBe(factsHash(b));
32
+ const c = canonicalFileFacts(a);
33
+ expect(c.symbols.map((s) => s.name)).toEqual(['a', 'b']);
34
+ expect(c.imports[1]!.names).toEqual(['x', 'y']);
35
+ expect(c.entryPoints[0]!.guards).toEqual(['audit', 'requireAuth']);
36
+ expect(c.entryPoints[0]!.chain).toEqual(['app.ts', 'mw.ts']);
37
+ expect(canonicalFileFacts(c)).toEqual(c);
38
+ });
39
+ });
40
+
41
+ describe('canonicalFileFacts: paths, tie-breaks, immutability', () => {
42
+ it('normalizes every path field (resolved imports, guard chains, snapshot files)', () => {
43
+ const ep = facts().entryPoints[0]!;
44
+ const c = canonicalFileFacts(facts({
45
+ imports: [{ specifier: '..\\b', resolved: 'src\\b.ts', names: [] }],
46
+ entryPoints: [{ ...ep, chain: ['.\\src\\mw.ts', 'src/app.ts'] }],
47
+ testFacts: { tests: [], snapshotFiles: ['__snapshots__\\a.snap'] },
48
+ }));
49
+ expect(c.imports[0]!.resolved).toBe('src/b.ts');
50
+ expect(c.entryPoints[0]!.chain).toEqual(['src/app.ts', 'src/mw.ts']);
51
+ expect(c.testFacts!.snapshotFiles).toEqual(['__snapshots__/a.snap']);
52
+ });
53
+
54
+ it('items equal on the declared keys still sort one way (the whole item breaks the tie)', () => {
55
+ const i1 = { specifier: './a', resolved: 'a.ts', names: [], typeOnly: true };
56
+ const i2 = { specifier: './a', resolved: 'a.ts', names: [], dynamic: true };
57
+ expect(factsHash(facts({ imports: [i1, i2] }))).toBe(factsHash(facts({ imports: [i2, i1] })));
58
+ const t1 = { name: 't', assertions: 1, matchers: [{ matcher: 'toBe', strength: 'exact' as const, count: 1 }] };
59
+ const t2 = { ...t1, assertions: 2 };
60
+ expect(factsHash(facts({ testFacts: { tests: [t1, t2], snapshotFiles: [] } }))).toBe(factsHash(facts({ testFacts: { tests: [t2, t1], snapshotFiles: [] } })));
61
+ expect(factsHash(facts({ complexity: [{ symbol: 'a', cyclomatic: 1 }, { symbol: 'a', cyclomatic: 2 }] })))
62
+ .toBe(factsHash(facts({ complexity: [{ symbol: 'a', cyclomatic: 2 }, { symbol: 'a', cyclomatic: 1 }] })));
63
+ });
64
+
65
+ it('is deep-frozen, copies (never freezes) the input, and returns a canonical object as is', () => {
66
+ const raw = facts();
67
+ const c = canonicalFileFacts(raw);
68
+ expect(Object.isFrozen(c) && Object.isFrozen(c.calls) && Object.isFrozen(c.calls[0])).toBe(true);
69
+ expect(Object.isFrozen(raw.calls[0])).toBe(false);
70
+ expect(canonicalFileFacts(c)).toBe(c);
71
+ // A mutated non-canonical input is hashed again, never served a stale cached hash.
72
+ const before = factKindHashes(raw).body;
73
+ raw.calls = [];
74
+ expect(factKindHashes(raw).body).not.toBe(before);
75
+ });
76
+
77
+ it('projectFileFacts keeps the header and the read kinds, empties the rest', () => {
78
+ const p = projectFileFacts(facts(), ['structure']);
79
+ expect(p.exports).toHaveLength(2);
80
+ expect(p.calls).toEqual([]);
81
+ expect(p.testFacts).toBeUndefined();
82
+ expect(p.contentHash).toBe('');
83
+ expect(p.extractor).toBe(facts().extractor);
84
+ const c = canonicalFileFacts(facts());
85
+ expect(projectFileFacts(c, ['structure'])).toBe(projectFileFacts(c, ['structure']));
86
+ });
87
+ });
88
+
89
+ describe('factKindHashes', () => {
90
+ it('a body-only change moves the body hash and nothing else', () => {
91
+ const before = factKindHashes(facts());
92
+ const after = factKindHashes(facts({ calls: [{ callee: 'fetch', enclosing: 'b', count: 1 }] }));
93
+ expect(after.body).not.toBe(before.body);
94
+ expect(after.structure).toBe(before.structure);
95
+ expect(after.content).toBe(before.content);
96
+ });
97
+
98
+ it('a structure change (a guard removed from a route) moves only the structure hash', () => {
99
+ const before = factKindHashes(facts());
100
+ const ep = facts().entryPoints[0]!;
101
+ const after = factKindHashes(facts({ entryPoints: [{ ...ep, guards: ['audit'] }] }));
102
+ expect(after.structure).not.toBe(before.structure);
103
+ expect(after.body).toBe(before.body);
104
+ });
105
+
106
+ it('content is the content hash; another extractor moves structure and body', () => {
107
+ const h = factKindHashes(facts());
108
+ expect(h.content).toBe('c1');
109
+ const other = factKindHashes(facts({ extractor: factsExtractorTag({ family: 'regex' }, 'typescript') }));
110
+ expect(other.structure).not.toBe(h.structure);
111
+ expect(other.body).not.toBe(h.body);
112
+ });
113
+ });
114
+
115
+ describe('readFileFacts (v2 compatibility)', () => {
116
+ it('reads a v2 object as factsVersion 2 with every v3 list empty', () => {
117
+ const v2 = readFileFacts({ contentHash: 'c', symbols: [{ name: 'f', kind: 'function' }] });
118
+ expect(v2.factsVersion).toBe(2);
119
+ expect(isFileFactsV3(v2)).toBe(false);
120
+ expect(v2.exports).toEqual([]);
121
+ expect(v2.calls).toEqual([]);
122
+ expect(v2.entryPoints).toEqual([]);
123
+ expect(v2.testFacts).toBeUndefined();
124
+ });
125
+
126
+ it('keeps a v3 object (canonicalized)', () => {
127
+ const v3 = readFileFacts(facts());
128
+ expect(isFileFactsV3(v3)).toBe(true);
129
+ expect(factsHash(v3)).toBe(factsHash(facts()));
130
+ });
131
+ });
132
+
133
+ describe('composite extractor version', () => {
134
+ it('composes code version, revision, the language grammar and the EOL rule', () => {
135
+ expect(factsExtractorTag(STAMP, 'typescript')).toBe('tree-sitter@3.0/typescript=0.23.2/eol-lf@1');
136
+ expect(factsExtractorTag({ ...STAMP, revision: 2 }, 'go')).toBe('tree-sitter@3.2/eol-lf@1');
137
+ expect(factsExtractorTag(STAMP)).toBe('tree-sitter@3.0/python=0.23.6,typescript=0.23.2/eol-lf@1');
138
+ });
139
+
140
+ it('a grammar bump owes re-extraction only for files of that language', () => {
141
+ const ts = facts();
142
+ const py = facts({ language: 'python', extractor: factsExtractorTag(STAMP, 'python') });
143
+ const bumped: ExtractorStamp = { ...STAMP, grammars: { ...STAMP.grammars, python: '0.24.0' } };
144
+ expect(isFactsCurrent(ts, bumped)).toBe(true);
145
+ expect(isFactsCurrent(py, bumped)).toBe(false);
146
+ expect(isFactsCurrent(readFileFacts({ ...ts, factsVersion: 2 }), STAMP)).toBe(false);
147
+ });
148
+
149
+ it('comparability names what moved: grammar, family, EOL rule', () => {
150
+ const base = extractorStampMeta(STAMP);
151
+ expect(comparable(base, extractorStampMeta(STAMP))).toEqual({ comparable: true, reasons: [] });
152
+ expect(comparable(base, extractorStampMeta({ ...STAMP, grammars: { ...STAMP.grammars, python: '0.24.0' } })).reasons)
153
+ .toEqual(['tool-version-changed:grammar:python']);
154
+ expect(comparable(base, extractorStampMeta({ family: 'regex' })).reasons).toContain('extractor-mismatch');
155
+ expect(comparable(base, extractorStampMeta({ ...STAMP, contentHashRule: 'eol-lf@2' })).reasons).toEqual(['content-hash-rule-changed']);
156
+ });
157
+ });