@seanhogg/builderforce-memory 2026.10.67 → 2026.10.69

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 (159) hide show
  1. package/dist/knowledge/build.d.ts.map +1 -1
  2. package/dist/knowledge/build.js +7 -2
  3. package/dist/knowledge/build.js.map +1 -1
  4. package/dist/knowledge/comparability.d.ts +100 -0
  5. package/dist/knowledge/comparability.d.ts.map +1 -0
  6. package/dist/knowledge/comparability.js +149 -0
  7. package/dist/knowledge/comparability.js.map +1 -0
  8. package/dist/knowledge/contentHash.d.ts +28 -0
  9. package/dist/knowledge/contentHash.d.ts.map +1 -0
  10. package/dist/knowledge/contentHash.js +54 -0
  11. package/dist/knowledge/contentHash.js.map +1 -0
  12. package/dist/knowledge/extractFile.d.ts +2 -0
  13. package/dist/knowledge/extractFile.d.ts.map +1 -1
  14. package/dist/knowledge/extractFile.js +1 -1
  15. package/dist/knowledge/extractFile.js.map +1 -1
  16. package/dist/knowledge/extractJob.d.ts +5 -2
  17. package/dist/knowledge/extractJob.d.ts.map +1 -1
  18. package/dist/knowledge/extractJob.js +1 -1
  19. package/dist/knowledge/extractJob.js.map +1 -1
  20. package/dist/knowledge/findingBuilder.d.ts +12 -2
  21. package/dist/knowledge/findingBuilder.d.ts.map +1 -1
  22. package/dist/knowledge/findingBuilder.js +9 -2
  23. package/dist/knowledge/findingBuilder.js.map +1 -1
  24. package/dist/knowledge/findingIdentity.d.ts +52 -0
  25. package/dist/knowledge/findingIdentity.d.ts.map +1 -0
  26. package/dist/knowledge/findingIdentity.js +70 -0
  27. package/dist/knowledge/findingIdentity.js.map +1 -0
  28. package/dist/knowledge/findingModel.d.ts +30 -0
  29. package/dist/knowledge/findingModel.d.ts.map +1 -0
  30. package/dist/knowledge/findingModel.js +6 -0
  31. package/dist/knowledge/findingModel.js.map +1 -0
  32. package/dist/knowledge/findings.d.ts.map +1 -1
  33. package/dist/knowledge/findings.js +17 -9
  34. package/dist/knowledge/findings.js.map +1 -1
  35. package/dist/knowledge/godModule.js +2 -2
  36. package/dist/knowledge/godModule.js.map +1 -1
  37. package/dist/knowledge/index.d.ts +13 -1
  38. package/dist/knowledge/index.d.ts.map +1 -1
  39. package/dist/knowledge/index.js +8 -0
  40. package/dist/knowledge/index.js.map +1 -1
  41. package/dist/knowledge/lineage.d.ts +35 -0
  42. package/dist/knowledge/lineage.d.ts.map +1 -0
  43. package/dist/knowledge/lineage.js +114 -0
  44. package/dist/knowledge/lineage.js.map +1 -0
  45. package/dist/knowledge/merkle.d.ts +65 -0
  46. package/dist/knowledge/merkle.d.ts.map +1 -0
  47. package/dist/knowledge/merkle.js +158 -0
  48. package/dist/knowledge/merkle.js.map +1 -0
  49. package/dist/knowledge/model.d.ts +20 -17
  50. package/dist/knowledge/model.d.ts.map +1 -1
  51. package/dist/knowledge/owedFiles.d.ts +5 -2
  52. package/dist/knowledge/owedFiles.d.ts.map +1 -1
  53. package/dist/knowledge/owedFiles.js +20 -5
  54. package/dist/knowledge/owedFiles.js.map +1 -1
  55. package/dist/knowledge/pack/encode.d.ts +2 -1
  56. package/dist/knowledge/pack/encode.d.ts.map +1 -1
  57. package/dist/knowledge/pack/encode.js +2 -1
  58. package/dist/knowledge/pack/encode.js.map +1 -1
  59. package/dist/knowledge/pack/extrDiff.d.ts.map +1 -1
  60. package/dist/knowledge/pack/extrDiff.js +4 -1
  61. package/dist/knowledge/pack/extrDiff.js.map +1 -1
  62. package/dist/knowledge/pack/sections/columns.d.ts +15 -2
  63. package/dist/knowledge/pack/sections/columns.d.ts.map +1 -1
  64. package/dist/knowledge/pack/sections/columns.js +16 -1
  65. package/dist/knowledge/pack/sections/columns.js.map +1 -1
  66. package/dist/knowledge/pack/sections/extrLists.js +2 -2
  67. package/dist/knowledge/pack/sections/extrLists.js.map +1 -1
  68. package/dist/knowledge/pack/sections/facts.d.ts.map +1 -1
  69. package/dist/knowledge/pack/sections/facts.js +2 -2
  70. package/dist/knowledge/pack/sections/facts.js.map +1 -1
  71. package/dist/knowledge/pack/sections/index.d.ts +1 -0
  72. package/dist/knowledge/pack/sections/index.d.ts.map +1 -1
  73. package/dist/knowledge/pack/sections/index.js +3 -1
  74. package/dist/knowledge/pack/sections/index.js.map +1 -1
  75. package/dist/knowledge/pack/sections/rows.d.ts +1 -0
  76. package/dist/knowledge/pack/sections/rows.d.ts.map +1 -1
  77. package/dist/knowledge/pack/sections/rows.js +1 -1
  78. package/dist/knowledge/pack/sections/rows.js.map +1 -1
  79. package/dist/knowledge/pack/sections/sites.d.ts +24 -0
  80. package/dist/knowledge/pack/sections/sites.d.ts.map +1 -0
  81. package/dist/knowledge/pack/sections/sites.js +96 -0
  82. package/dist/knowledge/pack/sections/sites.js.map +1 -0
  83. package/dist/knowledge/pack/types.d.ts +2 -2
  84. package/dist/knowledge/pack/types.d.ts.map +1 -1
  85. package/dist/knowledge/plan.d.ts +8 -0
  86. package/dist/knowledge/plan.d.ts.map +1 -1
  87. package/dist/knowledge/plan.js +20 -6
  88. package/dist/knowledge/plan.js.map +1 -1
  89. package/dist/knowledge/refs.d.ts +4 -0
  90. package/dist/knowledge/refs.d.ts.map +1 -1
  91. package/dist/knowledge/refs.js +8 -0
  92. package/dist/knowledge/refs.js.map +1 -1
  93. package/dist/knowledge/resolve.d.ts.map +1 -1
  94. package/dist/knowledge/resolve.js +2 -0
  95. package/dist/knowledge/resolve.js.map +1 -1
  96. package/dist/knowledge/reviewModel.d.ts +8 -1
  97. package/dist/knowledge/reviewModel.d.ts.map +1 -1
  98. package/dist/knowledge/reviewPrefetch.d.ts +2 -1
  99. package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
  100. package/dist/knowledge/reviewPrefetch.js +8 -4
  101. package/dist/knowledge/reviewPrefetch.js.map +1 -1
  102. package/dist/knowledge/sources.d.ts +11 -2
  103. package/dist/knowledge/sources.d.ts.map +1 -1
  104. package/dist/knowledge/sources.js +19 -3
  105. package/dist/knowledge/sources.js.map +1 -1
  106. package/dist/knowledge/symbolEdges.d.ts +39 -0
  107. package/dist/knowledge/symbolEdges.d.ts.map +1 -0
  108. package/dist/knowledge/symbolEdges.js +71 -0
  109. package/dist/knowledge/symbolEdges.js.map +1 -0
  110. package/dist/knowledge/truncate.d.ts.map +1 -1
  111. package/dist/knowledge/truncate.js +4 -0
  112. package/dist/knowledge/truncate.js.map +1 -1
  113. package/package.json +1 -1
  114. package/src/contract/exports.snapshot.json +34 -0
  115. package/src/contract/regression.contentHash.test.ts +30 -0
  116. package/src/contract/regression.lineage.test.ts +27 -0
  117. package/src/contract/regression.listing.test.ts +85 -0
  118. package/src/contract/regression.symbolEdges.test.ts +323 -0
  119. package/src/contract/symbolEdges.golden.json +345 -0
  120. package/src/contract/types.contract.test.ts +68 -1
  121. package/src/knowledge/build.ts +7 -2
  122. package/src/knowledge/comparability.analysis.test.ts +73 -0
  123. package/src/knowledge/comparability.test.ts +44 -0
  124. package/src/knowledge/comparability.ts +182 -0
  125. package/src/knowledge/contentHash.test.ts +81 -0
  126. package/src/knowledge/contentHash.ts +55 -0
  127. package/src/knowledge/extractFile.ts +4 -2
  128. package/src/knowledge/extractJob.ts +5 -3
  129. package/src/knowledge/findingBuilder.ts +17 -2
  130. package/src/knowledge/findingIdentity.test.ts +102 -0
  131. package/src/knowledge/findingIdentity.ts +92 -0
  132. package/src/knowledge/findingModel.ts +32 -0
  133. package/src/knowledge/findings.ts +17 -9
  134. package/src/knowledge/godModule.ts +2 -2
  135. package/src/knowledge/index.ts +22 -1
  136. package/src/knowledge/lineage.test.ts +106 -0
  137. package/src/knowledge/lineage.ts +123 -0
  138. package/src/knowledge/merkle.test.ts +137 -0
  139. package/src/knowledge/merkle.ts +164 -0
  140. package/src/knowledge/model.ts +22 -19
  141. package/src/knowledge/owedFiles.contentHash.test.ts +58 -0
  142. package/src/knowledge/owedFiles.ts +23 -5
  143. package/src/knowledge/pack/encode.ts +2 -1
  144. package/src/knowledge/pack/extrDiff.ts +4 -1
  145. package/src/knowledge/pack/sections/columns.ts +16 -1
  146. package/src/knowledge/pack/sections/extrLists.ts +2 -2
  147. package/src/knowledge/pack/sections/facts.ts +2 -2
  148. package/src/knowledge/pack/sections/index.ts +3 -1
  149. package/src/knowledge/pack/sections/rows.ts +1 -1
  150. package/src/knowledge/pack/sections/sites.ts +87 -0
  151. package/src/knowledge/pack/types.ts +2 -2
  152. package/src/knowledge/plan.ts +28 -6
  153. package/src/knowledge/refs.ts +10 -0
  154. package/src/knowledge/resolve.ts +2 -0
  155. package/src/knowledge/reviewModel.ts +8 -1
  156. package/src/knowledge/reviewPrefetch.ts +10 -6
  157. package/src/knowledge/sources.ts +22 -3
  158. package/src/knowledge/symbolEdges.ts +72 -0
  159. package/src/knowledge/truncate.ts +3 -1
@@ -12,13 +12,20 @@
12
12
  */
13
13
 
14
14
  import type { ParsedSection, SourceDocument } from '../ingest/types.js';
15
+ import type { changedPaths, contentHash, CONTENT_HASH_RULE, merkleTree, MerkleEntry, MerkleTree, PlanDetail, ReviewPlan } from '../knowledge/index.js';
16
+ import type { BASELINE_CONTENT_HASH_RULE, canonicalListing, contentHashRuleOf, ListingSkipReason } from '../knowledge/index.js';
15
17
  import type {
16
18
  DirectorySource, Extracted, ExtractJob, ExtractJobResult, GraphApp, GraphOutline, GraphReadSkip, GraphSystem, KEdge, KNode, KnowledgeGraph, KnowledgeStore,
17
19
  OutlineFile, OutlineCommunity, NodePlacement, ReviewFailure, ReviewFailureChunks, ReviewPhase, ReviewReport, ReviewRun, ReviewRunPhase, ReviewStep, ScopeRecord,
18
20
  StoredFact, StoredRelation, ExtractedLogPersistence, KnowledgeSnapshot, LocalSnapshotStoreOptions, SnapshotPersistence,
19
- RowChange, RowPersistence,
21
+ RowChange, RowPersistence, CallSite, SymbolEdgeKind,
20
22
  } from '../knowledge/index.js';
23
+ import type { dedupeSymbolEdges } from '../knowledge/index.js';
21
24
  import type { PlannedFile } from '../knowledge/index.js';
25
+ import type {
26
+ AnalysisIssue, AnchorKind, CodeAnalysisSnapshot, ComparabilityMeta, Finding, FindingIdentity, LineageEntry,
27
+ comparable, compareAnalysis, identityOf, matchLineage,
28
+ } from '../knowledge/index.js';
22
29
  import { placementOf } from '../knowledge/index.js';
23
30
  import { canonicalDump, ExtractFailed, failuresOf, failureTotal, LocalSnapshotStore, localSnapshotStore, type ExtractorState } from '../knowledge/index.js';
24
31
 
@@ -103,6 +110,31 @@ export type ExtractFailed_constructor = Expect<Equal<ConstructorParameters<typeo
103
110
  export type ExtractorState_failures = Expect<Equal<ExtractorState['failures'], ReadonlyMap<string, { hash: string; count: number }> | undefined>>;
104
111
  // ExtractorState.oversized: claimed documents over the size cap, planned as assets; optional so a hand-built state stays valid.
105
112
  export type ExtractorState_oversized = Expect<Equal<ExtractorState['oversized'], ReadonlySet<string> | undefined>>;
113
+ // 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.
114
+ export type ExtractorState_contentHashRule = Expect<Equal<ExtractorState['contentHashRule'], string | undefined>>;
115
+
116
+ /* ── Content identity and directory Merkle hashes (PRD 41 §B2 steps 0 and 4) ───────────────────────────────── */
117
+ export type contentHash_signature = Expect<Equal<typeof contentHash, (bytes: Uint8Array) => string>>;
118
+ export type CONTENT_HASH_RULE_type = Expect<Equal<typeof CONTENT_HASH_RULE, 'eol-lf@1'>>;
119
+ export type MerkleEntry_shape = Expect<Equal<MerkleEntry, { name: string; kind: 'file' | 'dir'; hash: string }>>;
120
+ export type MerkleTree_shape = Expect<Equal<MerkleTree, {
121
+ root: string; dirs: ReadonlyMap<string, string>; entries: ReadonlyMap<string, ReadonlyArray<MerkleEntry>>;
122
+ }>>;
123
+ export type merkleTree_signature = Expect<Equal<typeof merkleTree, (files: ReadonlyArray<{ path: string; hash: string }>) => MerkleTree>>;
124
+ export type changedPaths_signature = Expect<Equal<typeof changedPaths, (before: MerkleTree, after: MerkleTree) => string[]>>;
125
+ export type ReviewPlan_merkleRoot = Expect<Equal<ReviewPlan['merkleRoot'], string | undefined>>;
126
+ export type PlanDetail_merkle = Expect<Equal<PlanDetail['merkle'], MerkleTree | undefined>>;
127
+ export type BASELINE_CONTENT_HASH_RULE_type = Expect<Equal<typeof BASELINE_CONTENT_HASH_RULE, 'eol-lf@1'>>;
128
+ export type contentHashRuleOf_signature = Expect<Equal<typeof contentHashRuleOf, (recorded: string | undefined) => string>>;
129
+ // The plan never throws over a listing: invalid and colliding paths are skipped with a reason; a re-spelled path keeps the source's spelling for reads.
130
+ export type ReviewPlan_skipped_reason = Expect<Equal<
131
+ ReviewPlan['skipped'][number]['reason'], 'ignored' | 'too-large' | 'no-pack' | 'invalid-path' | 'duplicate-path'
132
+ >>;
133
+ export type PlannedFile_listedPath = Expect<Equal<PlannedFile['listedPath'], string | undefined>>;
134
+ export type canonicalListing_skipped = Expect<Equal<
135
+ ReturnType<typeof canonicalListing<{ path: string }>>['skipped'], Array<{ path: string; reason: ListingSkipReason }>
136
+ >>;
137
+ export type ListingSkipReason_values = Expect<Equal<ListingSkipReason, 'invalid-path' | 'duplicate-path'>>;
106
138
 
107
139
  /* ── DirectorySource: optional per-path hooks ──────────────────────────────────────────────────────────────── */
108
140
  // hashOf takes the path (a host whose read() transforms bytes returns the listing hash for it); a one-argument hashOf still satisfies it.
@@ -228,6 +260,41 @@ export type NodePlacement_shape = Expect<Equal<NodePlacement, { kind: 'partition
228
260
  export type placementOf_signature = Expect<Equal<ReturnType<typeof placementOf>, NodePlacement | undefined>>;
229
261
  export type KEdge_verdict = Expect<Equal<KEdge['verdict'], 'allowed' | 'same' | 'skips' | 'upward' | undefined>>;
230
262
 
263
+ /* ── Symbol-level edges (PRD 43 P0b): `calls` edges carry their call sites ─────────────────────────────────── */
264
+ export type KEdge_sites = Expect<Equal<KEdge['sites'], CallSite[] | undefined>>;
265
+ export type KEdge_sites_is_optional = Expect<Equal<IsOptional<KEdge, 'sites'>, true>>;
266
+ export type CallSite_shape = Expect<Equal<CallSite, { path: string; line: number; column: number; order: number }>>;
267
+ export type SymbolEdgeKind_values = Expect<Equal<SymbolEdgeKind, 'extends' | 'implements' | 'composes' | 'uses' | 'calls'>>;
268
+ export type dedupeSymbolEdges_signature = Expect<Equal<
269
+ typeof dedupeSymbolEdges, (edges: readonly KEdge[], opts?: { maxPerSymbol?: number; maxSites?: number }) => KEdge[]
270
+ >>;
271
+
272
+ /* ── Finding identity v2, lineage, comparability (PRD 41 §C3/§C9) ─────────────────────────────────────────── */
273
+ export type AnchorKind_values = Expect<Equal<AnchorKind, 'symbol' | 'route' | 'package' | 'file' | 'group'>>;
274
+ export type Finding_anchor_is_optional = Expect<Equal<IsOptional<Finding, 'anchor'>, true>>;
275
+ export type Finding_anchorKind = Expect<Equal<Finding['anchorKind'], AnchorKind | undefined>>;
276
+ export type FindingIdentity_shape = Expect<Equal<FindingIdentity, { id: string; anchor: string; anchorKind: AnchorKind; members: string[] }>>;
277
+ export type identityOf_signature = Expect<Equal<typeof identityOf, (f: Finding, ruleVersion?: number) => FindingIdentity>>;
278
+ export type LineageEntry_shape = Expect<Equal<LineageEntry, {
279
+ lineage: 'introduced' | 'resolved' | 'changed' | 'persisting'; change?: 'grew' | 'shrank' | 'moved'; before?: string; after?: string;
280
+ }>>;
281
+ export type matchLineage_signature = Expect<Equal<
282
+ typeof matchLineage, (before: readonly FindingIdentity[], after: readonly FindingIdentity[]) => LineageEntry[]
283
+ >>;
284
+ export type ComparabilityMeta_shape = Expect<Equal<ComparabilityMeta, {
285
+ extractor?: string; extractorVersion?: string | number; contentHashRule?: string; tools?: Record<string, string>;
286
+ scope?: string; repo?: string; branch?: string; truncated?: boolean; failed?: string[];
287
+ }>>;
288
+ export type comparable_signature = Expect<Equal<
289
+ typeof comparable, (before: ComparabilityMeta, after: ComparabilityMeta) => { comparable: boolean; reasons: string[] }
290
+ >>;
291
+ export type AnalysisIssue_anchor_is_optional = Expect<Equal<IsOptional<AnalysisIssue, 'anchor'>, true>>;
292
+ export type compareAnalysis_result = Expect<Equal<
293
+ ReturnType<typeof compareAnalysis>,
294
+ { comparable: boolean; reasons: string[]; added: AnalysisIssue[]; unchanged: AnalysisIssue[]; resolved: AnalysisIssue[] }
295
+ >>;
296
+ export type CodeAnalysisSnapshot_version = Expect<Equal<CodeAnalysisSnapshot['version'], 1>>;
297
+
231
298
  describe('type contract', () => {
232
299
  it('is enforced by `npm run check:contract-types` (tsc over tsconfig.contract.json), not at run time', () => {
233
300
  // The values above only exist so the `satisfies` / `@ts-expect-error` lines are real code; this proves the file loads.
@@ -27,6 +27,7 @@ import { pageRank } from './importance.js';
27
27
  import { applyCommunities } from './communities.js';
28
28
  import { loadPartitions, partitionOf, verdictOf } from './partitions.js';
29
29
  import { entityName } from './resolve.js';
30
+ import { isSymbolEdgeKind } from './symbolEdges.js';
30
31
  import {
31
32
  basenameOf, canonicalJson, compareStr, factRef, FALLBACK_PACK_ID, fileRefOf, nameResolver, pathOfRef, round6, sortBy, srcRef,
32
33
  } from './refs.js';
@@ -199,7 +200,9 @@ export function buildGraph(input: BuildGraphInput, opts: BuildGraphOptions = {})
199
200
  const systems = [...(input.systems ?? [])].sort((a, b) => compareStr(a.path, b.path));
200
201
  placeNodes(rootId, g, registries, systems);
201
202
 
202
- const rank = pageRank([...g.nodes.keys()], [...g.edges.values()]);
203
+ // The symbol-level kinds restate a dependency the file's `references` already carry (the code pack's rollup):
204
+ // they draw the class/method bands and never re-weigh importance.
205
+ const rank = pageRank([...g.nodes.keys()], [...g.edges.values()].filter((e) => !isSymbolEdgeKind(e.kind)));
203
206
  for (const n of g.nodes.values()) n.importance = rank.get(n.ref) ?? 0;
204
207
  const { modularity, method: communityMethod } = applyCommunities(g.nodes.values(), g.edges.values());
205
208
 
@@ -300,7 +303,8 @@ function placeNodes(rootId: string, g: GraphBuilder, registries: Map<string, Par
300
303
  for (const e of g.edges.values()) {
301
304
  const from = g.nodes.get(e.from), to = g.nodes.get(e.to);
302
305
  const reg = from && registries.get(from.pack);
303
- if (!from || !to || !reg || from.pack !== to.pack) continue;
306
+ // A symbol-level edge restates its file's import: the layer verdict (and its finding) is the import's alone.
307
+ if (!from || !to || !reg || from.pack !== to.pack || isSymbolEdgeKind(e.kind)) continue;
304
308
  // Layers are a system's own: a reference into another system is neither upward nor skipping.
305
309
  if (crossesSystems(systemOfRef.get(from.ref) ?? from, systemOfRef.get(to.ref) ?? to)) continue;
306
310
  const verdict = verdictOf(from.partition, to.partition, reg);
@@ -333,5 +337,6 @@ export function finalEdge(e: KEdge): KEdge {
333
337
  ...(e.verdict ? { verdict: e.verdict } : {}),
334
338
  ...(e.cycle ? { cycle: true } : {}),
335
339
  ...(e.stale ? { stale: true } : {}),
340
+ ...(e.sites?.length ? { sites: e.sites } : {}),
336
341
  };
337
342
  }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * src/knowledge/comparability.analysis.test.ts — the `normalizeAnalysis` / `compareAnalysis` cases ported
3
+ * from Builderforce.ai agent-tools `codeAnalysis.test.ts`, assertions unchanged (the parity oracle).
4
+ * Only the imports changed: the analyzer list comes from agent-tools' `codeAnalysisTool.ts` there, so its
5
+ * names/versions are restated below; the analyzer-RUNNING cases stay in agent-tools.
6
+ */
7
+
8
+ import { compareAnalysis, identityOfIssue, normalizeAnalysis, type CodeAnalysisSnapshot } from './comparability.js';
9
+
10
+ const ANALYZERS = [{ name: 'dependency-cruiser', version: '16.10.4' }, { name: 'jscpd', version: '4.0.5' }, { name: 'knip', version: '5.62.0' }];
11
+
12
+ const dependency = { modules: [{ source: 'src/a.ts', dependencies: [{ resolved: 'src/b.ts', circular: true }, { resolved: 'node:fs', coreModule: true }] }, { source: 'src/b.ts', dependencies: [] }] };
13
+ const duplicates = { duplicates: [{ fragment: 'return input + 1;', firstFile: { name: 'src/a.ts', start: 2, end: 7 }, secondFile: { name: 'src/b.ts', start: 5, end: 10 } }] };
14
+ const unused = { files: ['src/dead.ts'], issues: [{ file: 'src/b.ts', exports: [{ name: 'unused', line: 20 }], dependencies: [{ name: 'abandoned-library' }], unlisted: [{ name: 'missing-library' }] }] };
15
+ const snapshot = (): CodeAnalysisSnapshot => ({ version: 1, id: 'scan', capturedAt: '2026-10-18T12:00:00.000Z', source: { branch: 'main', commit: 'abc', dirty: false }, tools: ANALYZERS.map((a) => ({ name: a.name, version: a.version, status: 'complete' })), ...normalizeAnalysis(dependency, duplicates, unused) });
16
+
17
+ describe('measured code analysis', () => {
18
+ it('normalizes edges, clone locations, unused files, exports and dependencies separately', () => {
19
+ const value = snapshot();
20
+ expect(value.edges).toEqual([{ from: 'src/a.ts', to: 'src/b.ts', circular: true }]);
21
+ expect(value.issues.map((i) => i.kind)).toEqual(['duplicate', 'unused-file', 'unused-export', 'unused-dependency']);
22
+ expect(value.issues[0]?.locations[1]).toEqual({ path: 'src/b.ts', startLine: 5, endLine: 10 });
23
+ expect(value.issues[0]?.snippet).toBe('return input + 1;');
24
+ });
25
+ it('retains clone identity when code shifts lines', () => {
26
+ const shifted = structuredClone(duplicates); shifted.duplicates[0]!.firstFile.start = 80;
27
+ expect(normalizeAnalysis(dependency, shifted, unused).issues[0]?.id).toBe(snapshot().issues[0]?.id);
28
+ });
29
+ it('measures resolved and unchanged findings rather than assuming every missing result is fixed', () => {
30
+ const baseline = snapshot(); const current = snapshot(); current.issues = current.issues.slice(1);
31
+ expect(compareAnalysis(current, baseline)).toMatchObject({ comparable: true, resolved: [baseline.issues[0]], unchanged: current.issues });
32
+ current.tools[1]!.status = 'failed';
33
+ expect(compareAnalysis(current, baseline)).toMatchObject({ comparable: false, resolved: [] });
34
+ expect(compareAnalysis(current)).toMatchObject({ comparable: false, resolved: [] });
35
+ });
36
+ });
37
+
38
+ describe('identityOfIssue: an issue saved before anchors existed', () => {
39
+ it('recomposes the anchor normalizeAnalysis writes, snippet hash included — also for a fragment over 4000 characters', () => {
40
+ const long = { duplicates: [{ ...duplicates.duplicates[0]!, fragment: `${'x = x + 1;\n'.repeat(500)}tail` }] };
41
+ for (const dups of [duplicates, long]) {
42
+ for (const issue of normalizeAnalysis(dependency, dups, unused).issues) {
43
+ const { anchor, ...legacy } = issue;
44
+ expect(identityOfIssue(legacy).anchor).toBe(anchor);
45
+ expect(identityOfIssue(issue).anchor).toBe(anchor);
46
+ }
47
+ }
48
+ });
49
+ });
50
+
51
+ describe('compareAnalysis reasons', () => {
52
+ it('are sorted and deduped after tools-incomplete is added', () => {
53
+ const fewer = snapshot(); fewer.tools = fewer.tools.slice(1); // drops dependency-cruiser: sorts before tools-incomplete
54
+ fewer.source.scope = 'z';
55
+ const { reasons } = compareAnalysis(fewer, snapshot());
56
+ expect(reasons).toEqual(['scope-changed', 'tool-missing:dependency-cruiser', 'tools-incomplete']);
57
+ expect([...reasons].sort()).toEqual(reasons);
58
+ });
59
+ });
60
+
61
+ describe('compareAnalysis delegates to comparable()', () => {
62
+ it('names why two snapshots are not comparable', () => {
63
+ const baseline = snapshot(); const current = snapshot();
64
+ expect(compareAnalysis(current, baseline).reasons).toEqual([]);
65
+ current.tools[1]!.status = 'failed';
66
+ expect(compareAnalysis(current, baseline).reasons).toEqual(['analyzer-failed:jscpd']);
67
+ expect(compareAnalysis(current).reasons).toEqual(['no-baseline']);
68
+ const fewer = snapshot(); fewer.tools = fewer.tools.slice(0, 2);
69
+ expect(compareAnalysis(fewer, snapshot()).reasons).toEqual(['tool-missing:knip', 'tools-incomplete']);
70
+ const scoped = snapshot(); scoped.source.scope = 'packages/app';
71
+ expect(compareAnalysis(scoped, snapshot()).reasons).toEqual(['scope-changed']);
72
+ });
73
+ });
@@ -0,0 +1,44 @@
1
+ /**
2
+ * src/knowledge/comparability.test.ts — `comparable()` (PRD 41 §C9): each stable reason code.
3
+ */
4
+
5
+ import { comparable, type ComparabilityMeta } from './comparability.js';
6
+
7
+ const base: ComparabilityMeta = {
8
+ extractor: 'tree-sitter@0.25', extractorVersion: 3, contentHashRule: 'sha256-lf', tools: { jscpd: '4.0.5', knip: '5.1.0' },
9
+ scope: '.', repo: 'r', branch: 'main', truncated: false, failed: [],
10
+ };
11
+ const reasonsOf = (after: Partial<ComparabilityMeta>, before: Partial<ComparabilityMeta> = {}) =>
12
+ comparable({ ...base, ...before }, { ...base, ...after }).reasons;
13
+
14
+ describe('comparable', () => {
15
+ it('two equal sides are comparable with no reasons', () => {
16
+ expect(comparable(base, { ...base })).toEqual({ comparable: true, reasons: [] });
17
+ expect(comparable({}, {})).toEqual({ comparable: true, reasons: [] });
18
+ });
19
+
20
+ it('names each reason with a stable code', () => {
21
+ expect(reasonsOf({ extractor: 'regex@1' })).toEqual(['extractor-mismatch']);
22
+ expect(reasonsOf({ extractor: 'tree-sitter@0.26' })).toEqual(['extractor-version-changed']);
23
+ expect(reasonsOf({ extractorVersion: 4 })).toEqual(['extractor-version-changed']);
24
+ expect(reasonsOf({ contentHashRule: 'sha256-raw' })).toEqual(['content-hash-rule-changed']);
25
+ expect(reasonsOf({ tools: { jscpd: '4.0.6', knip: '5.1.0' } })).toEqual(['tool-version-changed:jscpd']);
26
+ expect(reasonsOf({ tools: { jscpd: '4.0.5' } })).toEqual(['tool-missing:knip']);
27
+ expect(reasonsOf({ failed: ['knip'] }, { failed: ['jscpd'] })).toEqual(['analyzer-failed:jscpd', 'analyzer-failed:knip']);
28
+ expect(reasonsOf({ scope: 'packages/app' })).toEqual(['scope-changed']);
29
+ expect(reasonsOf({ repo: 'other' })).toEqual(['repo-changed']);
30
+ expect(reasonsOf({ branch: 'dev' })).toEqual(['branch-changed']);
31
+ expect(reasonsOf({}, { truncated: true })).toEqual(['truncated']);
32
+ });
33
+
34
+ it('an absent content-hash rule IS the baseline rule (eol-lf@1), not a change', () => {
35
+ expect(comparable({}, { contentHashRule: 'eol-lf@1' })).toEqual({ comparable: true, reasons: [] });
36
+ expect(comparable({ contentHashRule: 'eol-lf@1' }, {})).toEqual({ comparable: true, reasons: [] });
37
+ expect(comparable({}, { contentHashRule: 'eol-lf@2' }).reasons).toEqual(['content-hash-rule-changed']);
38
+ });
39
+
40
+ it('collects every reason, sorted and deduped, and is not comparable', () => {
41
+ const r = comparable({ ...base, failed: ['knip'] }, { ...base, failed: ['knip'], scope: 'x', truncated: true });
42
+ expect(r).toEqual({ comparable: false, reasons: ['analyzer-failed:knip', 'scope-changed', 'truncated'] });
43
+ });
44
+ });
@@ -0,0 +1,182 @@
1
+ /**
2
+ * knowledge/comparability.ts — the ONE comparability module (PRD 41 §C9), and the portable analyzer
3
+ * artifacts (`CodeAnalysisSnapshot`) whose compare it gates — moved here from Builderforce.ai's
4
+ * agent-tools `codeAnalysis.ts` so the web analysis compare and the knowledge compare share one
5
+ * identity (§C3) and one rule set. No filesystem or UI dependencies.
6
+ *
7
+ * Two sides are comparable only when NONE of the {@link ComparabilityReason} codes hold. A kind that
8
+ * is not comparable contributes no `introduced` / `resolved` entries: missing analyzer output must
9
+ * never be presented as a fix.
10
+ */
11
+
12
+ import { contentHashRuleOf } from './contentHash.js';
13
+ import { anchorWithSnippet, composeAnchor, type FindingIdentity } from './findingIdentity.js';
14
+ import { compareStr } from './refs.js';
15
+
16
+ /* ── comparable() ───────────────────────────────────────────────────────────────────────────────────── */
17
+
18
+ /** What one side was measured with. Absent fields compare equal only to absent fields — except `contentHashRule`, where absent IS the baseline rule. */
19
+ export interface ComparabilityMeta {
20
+ /** `'tree-sitter@<v>'` | `'regex@<v>'` — the family is the part before `@`. */
21
+ extractor?: string;
22
+ extractorVersion?: string | number;
23
+ contentHashRule?: string;
24
+ /** Tool (or rule) name → version. */
25
+ tools?: Record<string, string>;
26
+ scope?: string;
27
+ repo?: string;
28
+ branch?: string;
29
+ truncated?: boolean;
30
+ /** Tools that failed or timed out on this side. */
31
+ failed?: string[];
32
+ }
33
+
34
+ /**
35
+ * Stable reason codes (localized at render): `extractor-mismatch` (family differs), `extractor-version-changed`,
36
+ * `content-hash-rule-changed`, `tool-missing:<tool>` (measured on one side only), `tool-version-changed:<tool>`,
37
+ * `analyzer-failed:<tool>`, `scope-changed`, `repo-changed`, `branch-changed`, `truncated`.
38
+ * `compareAnalysis` adds `no-baseline` and `tools-incomplete`.
39
+ */
40
+ export type ComparabilityReason = string;
41
+
42
+ const familyOf = (extractor: string | undefined) => extractor?.split('@')[0];
43
+ const versionOf = (extractor: string | undefined) => {
44
+ const at = extractor?.indexOf('@') ?? -1;
45
+ return at < 0 ? undefined : extractor!.slice(at + 1);
46
+ };
47
+
48
+ /** Whether two sides can be compared, and every reason they cannot (sorted, deduped). */
49
+ export function comparable(before: ComparabilityMeta, after: ComparabilityMeta): { comparable: boolean; reasons: ComparabilityReason[] } {
50
+ const reasons = new Set<string>();
51
+ if (familyOf(before.extractor) !== familyOf(after.extractor)) reasons.add('extractor-mismatch');
52
+ else if (versionOf(before.extractor) !== versionOf(after.extractor)
53
+ || String(before.extractorVersion ?? '') !== String(after.extractorVersion ?? '')) reasons.add('extractor-version-changed');
54
+ if (contentHashRuleOf(before.contentHashRule) !== contentHashRuleOf(after.contentHashRule)) reasons.add('content-hash-rule-changed');
55
+ const bt = before.tools ?? {}, at = after.tools ?? {};
56
+ for (const tool of new Set([...Object.keys(bt), ...Object.keys(at)])) {
57
+ if (!(tool in bt) || !(tool in at)) reasons.add(`tool-missing:${tool}`);
58
+ else if (bt[tool] !== at[tool]) reasons.add(`tool-version-changed:${tool}`);
59
+ }
60
+ for (const tool of [...(before.failed ?? []), ...(after.failed ?? [])]) reasons.add(`analyzer-failed:${tool}`);
61
+ if (before.scope !== after.scope) reasons.add('scope-changed');
62
+ if (before.repo !== after.repo) reasons.add('repo-changed');
63
+ if (before.branch !== after.branch) reasons.add('branch-changed');
64
+ if (before.truncated || after.truncated) reasons.add('truncated');
65
+ const sorted = [...reasons].sort(compareStr);
66
+ return { comparable: sorted.length === 0, reasons: sorted };
67
+ }
68
+
69
+ /* ── Code analysis snapshots (ported from agent-tools codeAnalysis.ts) ──────────────────────────────── */
70
+
71
+ export interface AnalysisLocation { path: string; startLine: number; endLine: number }
72
+ export interface AnalysisIssue {
73
+ id: string; kind: 'duplicate' | 'unused-file' | 'unused-export' | 'unused-dependency'; locations: AnalysisLocation[]; symbol?: string; snippet?: string;
74
+ /** The §C3 anchor ({@link composeAnchor}, version {@link ANALYSIS_ANCHOR_VERSION}): no line numbers, no location set. */
75
+ anchor?: string;
76
+ }
77
+ export interface CodeAnalysisSnapshot {
78
+ version: 1;
79
+ id: string;
80
+ capturedAt: string;
81
+ source: { commit: string | null; branch: string | null; dirty: boolean | null; dirtyHash?: string; repository?: string; scope?: string };
82
+ tools: Array<{ name: string; version: string; status: 'complete' | 'failed' | 'not_measured'; error?: string; reason?: 'analyzer-unavailable' }>;
83
+ nodes: string[];
84
+ edges: Array<{ from: string; to: string; circular: boolean }>;
85
+ issues: AnalysisIssue[];
86
+ }
87
+ export interface CodeAnalysisComparison { current: CodeAnalysisSnapshot; baseline?: CodeAnalysisSnapshot }
88
+
89
+ /** The rule version the jscpd / knip issue anchors are composed with. */
90
+ export const ANALYSIS_ANCHOR_VERSION = 1;
91
+ /** dependency-cruiser, jscpd, knip: a snapshot missing one is never comparable. */
92
+ export const ANALYSIS_TOOL_COUNT = 3;
93
+ /** A duplicate's stored `snippet` is its fragment cut to this many characters; its anchor hashes exactly that text. */
94
+ const MAX_SNIPPET_CHARS = 4000;
95
+
96
+ const record = (v: unknown): Record<string, any> => v && typeof v === 'object' ? v as Record<string, any> : {};
97
+ const list = (v: unknown): any[] => Array.isArray(v) ? v : [];
98
+ const path = (v: unknown) => String(v ?? '').replace(/\\/g, '/').replace(/^\.\//, '');
99
+ const line = (v: unknown) => Math.max(1, Number(v) || 1);
100
+ const hash = (value: string) => { let n = BigInt('14695981039346656037'); const prime = BigInt('1099511628211'); for (let i = 0; i < value.length; i++) n = BigInt.asUintN(64, (n ^ BigInt(value.charCodeAt(i))) * prime); return n.toString(16); };
101
+
102
+ export function normalizeAnalysis(dependencies: unknown, duplicates: unknown, unused: unknown, scope = '.'): Pick<CodeAnalysisSnapshot, 'nodes' | 'edges' | 'issues'> {
103
+ const unusedPath = (value: unknown) => { const file = path(value); return scope === '.' || file.startsWith(`${scope}/`) ? file : `${scope}/${file}`; };
104
+ const nodes = new Set<string>();
105
+ const edges = new Map<string, { from: string; to: string; circular: boolean }>();
106
+ for (const module of list(record(dependencies).modules)) {
107
+ const from = path(module.source); if (!from) continue;
108
+ nodes.add(from);
109
+ for (const dependency of list(module.dependencies)) {
110
+ if (dependency.couldNotResolve || dependency.coreModule || dependency.dependencyTypes?.some((t: string) => t.startsWith('npm'))) continue;
111
+ const to = path(dependency.resolved); if (!to || to.includes('node_modules/')) continue;
112
+ nodes.add(to); edges.set(JSON.stringify([from, to]), { from, to, circular: !!dependency.circular });
113
+ }
114
+ }
115
+ const issues: AnalysisIssue[] = [];
116
+ for (const clone of list(record(duplicates).duplicates)) {
117
+ const locations = [clone.firstFile, clone.secondFile].map((raw) => {
118
+ const file = record(raw); return { path: path(file.name), startLine: line(file.start), endLine: line(file.end) };
119
+ });
120
+ // jscpd's fragment survives line movement. Range identity is a fallback for reporters without fragments.
121
+ locations.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.startLine - b.startLine);
122
+ const identity = typeof clone.fragment === 'string' ? clone.fragment.replace(/\r\n/g, '\n') : locations.map((l) => `${l.path}:${l.startLine}-${l.endLine}`).sort().join('|');
123
+ // Anchor: the first location's FILE plus the hash of the STORED snippet — never its lines. The stored (sliced) text is hashed,
124
+ // so identityOfIssue recomputes the same anchor from an issue saved before anchors existed.
125
+ const snippet = typeof clone.fragment === 'string' ? clone.fragment.slice(0, MAX_SNIPPET_CHARS) : undefined;
126
+ const anchor = composeAnchor('duplicate', ANALYSIS_ANCHOR_VERSION, 'file', anchorWithSnippet(locations[0]?.path ?? '', snippet));
127
+ issues.push({ id: `duplicate:${hash(JSON.stringify([locations.map((l) => l.path).sort(), identity]))}`, kind: 'duplicate', locations,
128
+ ...(snippet !== undefined ? { snippet } : {}), anchor });
129
+ }
130
+ for (const file of list(record(unused).files)) issues.push({ id: `unused-file:${unusedPath(file)}`, kind: 'unused-file', locations: [{ path: unusedPath(file), startLine: 1, endLine: 1 }],
131
+ anchor: composeAnchor('unused-file', ANALYSIS_ANCHOR_VERSION, 'file', unusedPath(file)) });
132
+ for (const issue of list(record(unused).issues)) {
133
+ const file = unusedPath(issue.file);
134
+ for (const field of ['exports', 'types', 'dependencies', 'devDependencies', 'unlisted']) {
135
+ for (const raw of list(issue[field])) {
136
+ const item = typeof raw === 'string' ? { name: raw } : record(raw);
137
+ const kind = field === 'exports' || field === 'types' ? 'unused-export' : 'unused-dependency';
138
+ if (field === 'unlisted') continue; // Missing dependencies are not unused dependencies.
139
+ // Anchor: the export as `<file>#<name>` (symbol) / the dependency as `<manifest>#<name>` (package).
140
+ const anchor = composeAnchor(kind, ANALYSIS_ANCHOR_VERSION, kind === 'unused-export' ? 'symbol' : 'package', `${file}#${String(item.name)}`);
141
+ issues.push({ id: `${kind}:${file}:${item.name}`, kind, symbol: String(item.name), locations: [{ path: file, startLine: line(item.line), endLine: line(item.line) }], anchor });
142
+ }
143
+ }
144
+ }
145
+ return { nodes: [...nodes].sort(), edges: [...edges.values()], issues: [...new Map(issues.map((i) => [i.id, i])).values()] };
146
+ }
147
+
148
+ /** The v2 identity of an analysis issue (members: its sorted location paths), for {@link matchLineage}. */
149
+ export function identityOfIssue(issue: AnalysisIssue): FindingIdentity {
150
+ const members = [...new Set(issue.locations.map((l) => l.path))].sort(compareStr);
151
+ const anchorKind = issue.kind === 'unused-export' ? 'symbol' : issue.kind === 'unused-dependency' ? 'package' : 'file';
152
+ // An issue saved before anchors existed: recompose what normalizeAnalysis writes — the file (`<file>#<name>` for a symbol or package)
153
+ // plus the hash of the stored snippet — so a pre-upgrade baseline matches by anchor.
154
+ const primary = anchorKind !== 'file' && issue.symbol !== undefined ? `${members[0] ?? ''}#${issue.symbol}` : (members[0] ?? '');
155
+ return { id: issue.id, anchor: issue.anchor ?? composeAnchor(issue.kind, ANALYSIS_ANCHOR_VERSION, anchorKind, anchorWithSnippet(primary, issue.snippet)), anchorKind, members };
156
+ }
157
+
158
+ /** A snapshot's comparability meta: source scope/repo/branch, tool versions, and every tool not `complete` as failed. */
159
+ export function analysisMeta(snapshot: CodeAnalysisSnapshot): ComparabilityMeta {
160
+ return {
161
+ scope: snapshot.source.scope, repo: snapshot.source.repository, branch: snapshot.source.branch ?? undefined,
162
+ tools: Object.fromEntries(snapshot.tools.map((t) => [t.name, t.version])),
163
+ failed: snapshot.tools.filter((t) => t.status !== 'complete').map((t) => t.name),
164
+ };
165
+ }
166
+
167
+ export function compareAnalysis(current: CodeAnalysisSnapshot, baseline?: CodeAnalysisSnapshot) {
168
+ const before = new Set(baseline?.issues.map((i) => i.id) ?? []);
169
+ const after = new Set(current.issues.map((i) => i.id));
170
+ const found = baseline ? comparable(analysisMeta(baseline), analysisMeta(current)).reasons : ['no-baseline'];
171
+ if (baseline && (current.tools.length !== ANALYSIS_TOOL_COUNT || baseline.tools.length !== ANALYSIS_TOOL_COUNT)) found.push('tools-incomplete');
172
+ const reasons = [...new Set(found)].sort(compareStr);
173
+ const complete = reasons.length === 0;
174
+ return {
175
+ comparable: complete,
176
+ reasons,
177
+ added: complete ? current.issues.filter((i) => !before.has(i.id)) : [],
178
+ unchanged: current.issues.filter((i) => before.has(i.id)),
179
+ // Missing analyzer output must never be presented as a fix.
180
+ resolved: complete ? baseline!.issues.filter((i) => !after.has(i.id)) : [],
181
+ };
182
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * src/knowledge/contentHash.test.ts — the EOL-normalized content identity (PRD 41 §B2 step 0).
3
+ */
4
+
5
+ import { sha256Hex } from '../retrieval/knowledge-index/sha256.js';
6
+ import { BASELINE_CONTENT_HASH_RULE, contentHash, CONTENT_HASH_RULE, contentHashRuleOf } from './contentHash.js';
7
+ import { isBinaryBytes, isBinaryText } from './sources.js';
8
+
9
+ const utf8 = (s: string) => new TextEncoder().encode(s);
10
+
11
+ describe('contentHash', () => {
12
+ it('names its rule; an absent record reads as the baseline rule', () => {
13
+ expect(CONTENT_HASH_RULE).toBe('eol-lf@1');
14
+ expect(BASELINE_CONTENT_HASH_RULE).toBe('eol-lf@1');
15
+ expect(contentHashRuleOf(undefined)).toBe(BASELINE_CONTENT_HASH_RULE);
16
+ expect(contentHashRuleOf('eol-lf@2')).toBe('eol-lf@2');
17
+ });
18
+
19
+ it('CRLF, LF and lone-CR versions of one text hash identically, as the raw sha256 of the LF text', () => {
20
+ const lf = 'line one\nline två\n\nlast';
21
+ const crlf = 'line one\r\nline två\r\n\r\nlast';
22
+ const cr = 'line one\rline två\r\rlast';
23
+ const mixed = 'line one\r\nline två\r\nlast'.replace('två\r\n', 'två\r\r\n'); // CR + CRLF = two line ends
24
+ expect(contentHash(utf8(crlf))).toBe(contentHash(utf8(lf)));
25
+ expect(contentHash(utf8(cr))).toBe(contentHash(utf8(lf)));
26
+ expect(contentHash(utf8(mixed))).toBe(contentHash(utf8(lf)));
27
+ expect(contentHash(utf8(lf))).toBe(sha256Hex(utf8(lf)));
28
+ expect(contentHash(utf8(lf))).toMatch(/^[0-9a-f]{64}$/);
29
+ });
30
+
31
+ it('a trailing CR and a trailing CRLF are one LF', () => {
32
+ expect(contentHash(utf8('a\r'))).toBe(sha256Hex('a\n'));
33
+ expect(contentHash(utf8('a\r\n'))).toBe(sha256Hex('a\n'));
34
+ expect(contentHash(utf8('\r\n\r'))).toBe(sha256Hex('\n\n'));
35
+ });
36
+
37
+ it('a binary file (a NUL in the first 8 KB) holding CRLF is hashed raw', () => {
38
+ const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x0d]);
39
+ expect(contentHash(bytes)).toBe(sha256Hex(bytes));
40
+ expect(contentHash(bytes)).not.toBe(sha256Hex(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0a, 0x0a])));
41
+ });
42
+
43
+ it('ONE binary rule: text and bytes agree on where the 8 KB sniff ends (bytes, not UTF-16 units)', () => {
44
+ // 5000 × 'é' is 10000 UTF-8 bytes: the NUL sits past byte 8192 though within the first 8192 code units.
45
+ const late = `${'é'.repeat(5000)}\u0000\r\n`;
46
+ expect(isBinaryText(late)).toBe(false);
47
+ expect(isBinaryBytes(utf8(late))).toBe(false);
48
+ expect(contentHash(utf8(late))).toBe(sha256Hex(utf8(`${'é'.repeat(5000)}\u0000\n`))); // text: its CRLF normalized
49
+ // 4000 × 'é' is 8000 bytes: the NUL is byte 8000, inside the sniff on both sides.
50
+ const early = `${'é'.repeat(4000)}\u0000\r\n`;
51
+ expect(isBinaryText(early)).toBe(true);
52
+ expect(isBinaryBytes(utf8(early))).toBe(true);
53
+ expect(contentHash(utf8(early))).toBe(sha256Hex(utf8(early))); // binary: raw
54
+ // The boundary: a NUL at byte 8191 is in, at byte 8192 is out.
55
+ expect(isBinaryText(`${'a'.repeat(8191)}\u0000`)).toBe(true);
56
+ expect(isBinaryText(`${'a'.repeat(8192)}\u0000`)).toBe(false);
57
+ expect(isBinaryBytes(utf8(`${'a'.repeat(8191)}\u0000`))).toBe(true);
58
+ expect(isBinaryBytes(utf8(`${'a'.repeat(8192)}\u0000`))).toBe(false);
59
+ });
60
+
61
+ it('the empty file is the sha256 of nothing', () => {
62
+ expect(contentHash(new Uint8Array(0))).toBe('e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855');
63
+ });
64
+
65
+ it('does not mutate its input', () => {
66
+ const bytes = utf8('a\r\nb\r');
67
+ const copy = bytes.slice();
68
+ contentHash(bytes);
69
+ expect(bytes).toEqual(copy);
70
+ });
71
+
72
+ it('hashes a 2 MB CRLF text quickly', () => {
73
+ const line = utf8('const x = 1; // a typical line of source code\r\n');
74
+ const big = new Uint8Array(2 * 1024 * 1024);
75
+ for (let at = 0; at + line.length <= big.length; at += line.length) big.set(line, at);
76
+ big.fill(0x20, big.length - (big.length % line.length)); // pad with spaces, never a NUL
77
+ const started = Date.now();
78
+ contentHash(big);
79
+ expect(Date.now() - started).toBeLessThan(2000);
80
+ });
81
+ });
@@ -0,0 +1,55 @@
1
+ /**
2
+ * knowledge/contentHash.ts — the ONE content identity of a file (PRD 41 §B2 step 0).
3
+ *
4
+ * sha256 (lowercase hex) over the file's bytes, with CRLF and lone CR converted to LF when the
5
+ * bytes are text; binary bytes (a NUL in the first 8 KB, {@link isBinaryBytes}) are hashed raw.
6
+ * So a Windows `core.autocrlf` checkout and a Linux checkout of one commit hash identically, and
7
+ * an LF-only text file hashes exactly as its raw sha256 did before this rule.
8
+ *
9
+ * Byte-level, never decoded: CR (0x0D) and LF (0x0A) cannot occur inside a UTF-8 multibyte
10
+ * sequence, so the rewrite is safe for any UTF-8 text. A file with no CR is hashed in place.
11
+ *
12
+ * {@link CONTENT_HASH_RULE} is recorded in a root's extractor entry (owedFiles.ts) once it moves past
13
+ * `eol-lf@1`; only a recorded rule that differs from today's owes every file one re-extraction. Adopting
14
+ * this first rule owes nothing: it moves the hash of every CRLF file, which re-extract by content.
15
+ */
16
+
17
+ import { sha256Hex } from '../retrieval/knowledge-index/sha256.js';
18
+ import { isBinaryBytes } from './sources.js';
19
+
20
+ /** Names the normalization {@link contentHash} applies. Change it whenever the hashed bytes of some file would change. */
21
+ export const CONTENT_HASH_RULE = 'eol-lf@1';
22
+
23
+ /**
24
+ * The rule an ABSENT record means — in a root's extractor entry (which writes no record for it) and in a
25
+ * comparability meta. The first rule: every entry written before rules were recorded was hashed under it or under raw
26
+ * sha256, and the two agree on every LF file (a CRLF file re-extracts by its moved hash).
27
+ */
28
+ export const BASELINE_CONTENT_HASH_RULE = 'eol-lf@1';
29
+
30
+ /** The ONE reading of a possibly-absent rule record: absent is {@link BASELINE_CONTENT_HASH_RULE}. */
31
+ export const contentHashRuleOf = (recorded: string | undefined): string => recorded ?? BASELINE_CONTENT_HASH_RULE;
32
+
33
+ const CR = 0x0d;
34
+ const LF = 0x0a;
35
+
36
+ /** The bytes with CRLF → LF and lone CR → LF; the input itself when it holds no CR. */
37
+ function eolNormalized(bytes: Uint8Array): Uint8Array {
38
+ let i = bytes.indexOf(CR);
39
+ if (i < 0) return bytes;
40
+ const out = new Uint8Array(bytes.length);
41
+ out.set(bytes.subarray(0, i));
42
+ let n = i;
43
+ for (; i < bytes.length; i++) {
44
+ const b = bytes[i]!;
45
+ if (b !== CR) { out[n++] = b; continue; }
46
+ out[n++] = LF;
47
+ if (bytes[i + 1] === LF) i++; // CRLF: the LF is the one just written
48
+ }
49
+ return out.subarray(0, n);
50
+ }
51
+
52
+ /** The content identity of a file: lowercase hex sha256 of its EOL-normalized bytes (raw bytes when binary). */
53
+ export function contentHash(bytes: Uint8Array): string {
54
+ return sha256Hex(isBinaryBytes(bytes) ? bytes : eolNormalized(bytes));
55
+ }
@@ -44,6 +44,8 @@ export interface ExtractFileArgs {
44
44
  readByPool?: boolean;
45
45
  /** With `readByPool`: the read deadline for this path (`DirectorySource.readTimeoutMs`), handed to the worker. */
46
46
  readMs?: number;
47
+ /** With `readByPool`: the source's own spelling of `path` (`PlannedFile.listedPath`), the path the worker opens. Default `path`. */
48
+ readPath?: string;
47
49
  /** Told where the time went: the cache lookup and the pool job (PRD 41 A10, so a stall names itself). */
48
50
  onTiming?: (t: { lookupMs: number; poolMs: number }) => void;
49
51
  /** Leave the extract cache write to the caller (the review writes it in plan order); default: write it. */
@@ -61,8 +63,8 @@ export interface FileExtraction {
61
63
  }
62
64
 
63
65
  /** How the file reaches the pool: its document, or `readByPool` when the pool reads it. */
64
- function jobSource(a: ExtractFileArgs): { doc: SourceDocument; readByPool?: false } | { doc?: undefined; readByPool: true } {
65
- return a.readByPool || !a.doc ? { readByPool: true } : { doc: a.doc };
66
+ function jobSource(a: ExtractFileArgs): { doc: SourceDocument; readByPool?: false } | { doc?: undefined; readByPool: true; readPath?: string } {
67
+ return a.readByPool || !a.doc ? { readByPool: true, ...(a.readPath !== undefined ? { readPath: a.readPath } : {}) } : { doc: a.doc };
66
68
  }
67
69
 
68
70
  /** Adds `extracted` to the content-hash cache, keeping the entries of the other files that share the hash. */
@@ -32,7 +32,9 @@ export interface ExtractJobBase {
32
32
 
33
33
  /**
34
34
  * How the file reaches the worker (PRD 41 A10 rule 8): `doc` is the document the review read (plain data); `readByPool` says the
35
- * worker reads and binary-checks `path` itself at the planned `hash` — no stand-in document, no text copied across the thread.
35
+ * worker reads and binary-checks `readByPool.path` itself at the planned `hash` — no stand-in document, no text copied across the thread.
36
+ * A pool host must open `readByPool.path`, the source's listed spelling (`PlannedFile.listedPath`), never `job.path`: `job.path` is the
37
+ * file's identity (normalized: POSIX, NFC) and may differ from the spelling the source can open (an NFD-named file, for one).
36
38
  */
37
39
  export type ExtractJobSource =
38
40
  | { doc: SourceDocument; readByPool?: never }
@@ -93,12 +95,12 @@ export function jobOf(
93
95
  f: {
94
96
  rootId: string; path: string; hash: string; knownKeys: ReadonlyMap<string, NodeRef>;
95
97
  needSections?: boolean; sectionsOnly?: boolean; readMs?: number;
96
- } & ({ doc: SourceDocument; readByPool?: false } | { doc?: undefined; readByPool: true }),
98
+ } & ({ doc: SourceDocument; readByPool?: false } | { doc?: undefined; readByPool: true; /** The path the worker opens (the source's spelling); default `path`. */ readPath?: string }),
97
99
  ): ExtractJob {
98
100
  return {
99
101
  rootId: f.rootId, path: f.path, hash: f.hash, knownKeys: [...f.knownKeys],
100
102
  ...(f.needSections ? { needSections: true } : {}), ...(f.sectionsOnly ? { sectionsOnly: true } : {}),
101
- ...(f.readByPool ? { readByPool: { path: f.path, hash: f.hash, ...(f.readMs ? { readMs: f.readMs } : {}) } } : { doc: f.doc! }),
103
+ ...(f.readByPool ? { readByPool: { path: f.readPath ?? f.path, hash: f.hash, ...(f.readMs ? { readMs: f.readMs } : {}) } } : { doc: f.doc! }),
102
104
  } as ExtractJob;
103
105
  }
104
106