@seanhogg/builderforce-memory 2026.10.67 → 2026.10.68
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.
- package/dist/knowledge/comparability.d.ts +100 -0
- package/dist/knowledge/comparability.d.ts.map +1 -0
- package/dist/knowledge/comparability.js +149 -0
- package/dist/knowledge/comparability.js.map +1 -0
- package/dist/knowledge/contentHash.d.ts +28 -0
- package/dist/knowledge/contentHash.d.ts.map +1 -0
- package/dist/knowledge/contentHash.js +54 -0
- package/dist/knowledge/contentHash.js.map +1 -0
- package/dist/knowledge/extractFile.d.ts +2 -0
- package/dist/knowledge/extractFile.d.ts.map +1 -1
- package/dist/knowledge/extractFile.js +1 -1
- package/dist/knowledge/extractFile.js.map +1 -1
- package/dist/knowledge/extractJob.d.ts +5 -2
- package/dist/knowledge/extractJob.d.ts.map +1 -1
- package/dist/knowledge/extractJob.js +1 -1
- package/dist/knowledge/extractJob.js.map +1 -1
- package/dist/knowledge/findingBuilder.d.ts +12 -2
- package/dist/knowledge/findingBuilder.d.ts.map +1 -1
- package/dist/knowledge/findingBuilder.js +9 -2
- package/dist/knowledge/findingBuilder.js.map +1 -1
- package/dist/knowledge/findingIdentity.d.ts +52 -0
- package/dist/knowledge/findingIdentity.d.ts.map +1 -0
- package/dist/knowledge/findingIdentity.js +70 -0
- package/dist/knowledge/findingIdentity.js.map +1 -0
- package/dist/knowledge/findingModel.d.ts +30 -0
- package/dist/knowledge/findingModel.d.ts.map +1 -0
- package/dist/knowledge/findingModel.js +6 -0
- package/dist/knowledge/findingModel.js.map +1 -0
- package/dist/knowledge/findings.d.ts.map +1 -1
- package/dist/knowledge/findings.js +17 -9
- package/dist/knowledge/findings.js.map +1 -1
- package/dist/knowledge/godModule.js +2 -2
- package/dist/knowledge/godModule.js.map +1 -1
- package/dist/knowledge/index.d.ts +11 -0
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +7 -0
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge/lineage.d.ts +35 -0
- package/dist/knowledge/lineage.d.ts.map +1 -0
- package/dist/knowledge/lineage.js +114 -0
- package/dist/knowledge/lineage.js.map +1 -0
- package/dist/knowledge/merkle.d.ts +65 -0
- package/dist/knowledge/merkle.d.ts.map +1 -0
- package/dist/knowledge/merkle.js +158 -0
- package/dist/knowledge/merkle.js.map +1 -0
- package/dist/knowledge/model.d.ts +3 -16
- package/dist/knowledge/model.d.ts.map +1 -1
- package/dist/knowledge/owedFiles.d.ts +5 -2
- package/dist/knowledge/owedFiles.d.ts.map +1 -1
- package/dist/knowledge/owedFiles.js +20 -5
- package/dist/knowledge/owedFiles.js.map +1 -1
- package/dist/knowledge/plan.d.ts +8 -0
- package/dist/knowledge/plan.d.ts.map +1 -1
- package/dist/knowledge/plan.js +20 -6
- package/dist/knowledge/plan.js.map +1 -1
- package/dist/knowledge/refs.d.ts +4 -0
- package/dist/knowledge/refs.d.ts.map +1 -1
- package/dist/knowledge/refs.js +8 -0
- package/dist/knowledge/refs.js.map +1 -1
- package/dist/knowledge/resolve.d.ts.map +1 -1
- package/dist/knowledge/resolve.js +2 -0
- package/dist/knowledge/resolve.js.map +1 -1
- package/dist/knowledge/reviewModel.d.ts +8 -1
- package/dist/knowledge/reviewModel.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.d.ts +2 -1
- package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.js +8 -4
- package/dist/knowledge/reviewPrefetch.js.map +1 -1
- package/dist/knowledge/sources.d.ts +10 -1
- package/dist/knowledge/sources.d.ts.map +1 -1
- package/dist/knowledge/sources.js +17 -2
- package/dist/knowledge/sources.js.map +1 -1
- package/package.json +1 -1
- package/src/contract/exports.snapshot.json +28 -0
- package/src/contract/regression.contentHash.test.ts +30 -0
- package/src/contract/regression.lineage.test.ts +27 -0
- package/src/contract/regression.listing.test.ts +85 -0
- package/src/contract/types.contract.test.ts +57 -0
- package/src/knowledge/comparability.analysis.test.ts +73 -0
- package/src/knowledge/comparability.test.ts +44 -0
- package/src/knowledge/comparability.ts +182 -0
- package/src/knowledge/contentHash.test.ts +81 -0
- package/src/knowledge/contentHash.ts +55 -0
- package/src/knowledge/extractFile.ts +4 -2
- package/src/knowledge/extractJob.ts +5 -3
- package/src/knowledge/findingBuilder.ts +17 -2
- package/src/knowledge/findingIdentity.test.ts +102 -0
- package/src/knowledge/findingIdentity.ts +92 -0
- package/src/knowledge/findingModel.ts +32 -0
- package/src/knowledge/findings.ts +17 -9
- package/src/knowledge/godModule.ts +2 -2
- package/src/knowledge/index.ts +17 -0
- package/src/knowledge/lineage.test.ts +106 -0
- package/src/knowledge/lineage.ts +123 -0
- package/src/knowledge/merkle.test.ts +137 -0
- package/src/knowledge/merkle.ts +164 -0
- package/src/knowledge/model.ts +4 -18
- package/src/knowledge/owedFiles.contentHash.test.ts +58 -0
- package/src/knowledge/owedFiles.ts +23 -5
- package/src/knowledge/plan.ts +28 -6
- package/src/knowledge/refs.ts +10 -0
- package/src/knowledge/resolve.ts +2 -0
- package/src/knowledge/reviewModel.ts +8 -1
- package/src/knowledge/reviewPrefetch.ts +10 -6
- package/src/knowledge/sources.ts +20 -2
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/contract/regression.listing.test.ts — the plan never throws over what a host lists (PRD 41 §B2 step 4, §B8.1).
|
|
3
|
+
* Plan paths go through the ONE normalization (POSIX, NFC), so they are the Merkle paths; a listing that collides once
|
|
4
|
+
* normalized, or names `.`/`..`, is skipped with a reason, and a re-spelled file is still read by the source's spelling.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { hashText } from '../ingest/hash.js';
|
|
8
|
+
import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
|
|
9
|
+
import { extractJob, type ExtractJob, type ExtractPool } from '../knowledge/extractJob.js';
|
|
10
|
+
import { merkleTree } from '../knowledge/merkle.js';
|
|
11
|
+
import { DOCS_PACK } from '../knowledge/packs/docs.js';
|
|
12
|
+
import { planDetail, refreshPlan } from '../knowledge/plan.js';
|
|
13
|
+
import { reviewDirectory } from '../knowledge/review.js';
|
|
14
|
+
import { args, fakeJudge, memSource, memStore } from '../knowledge/testkit.test-util.js';
|
|
15
|
+
|
|
16
|
+
const NFC = 'café.md', NFD = 'café.md';
|
|
17
|
+
|
|
18
|
+
describe('regression: a host listing cannot break the plan', () => {
|
|
19
|
+
it('regression: an NFC/NFD pair of one name with different content plans (one kept, one skipped) instead of throwing', async () => {
|
|
20
|
+
const source = memSource({ [NFC]: '# Café\nnfc\n', [NFD]: '# Café\nnfd\n', 'ok.md': '# OK\n' });
|
|
21
|
+
const detail = await planDetail(source, new InMemoryIngestManifest(), [DOCS_PACK]);
|
|
22
|
+
expect(detail.files.map((f) => f.path)).toEqual([NFC, 'ok.md']);
|
|
23
|
+
expect(detail.files[0]!.listedPath).toBe(NFD); // the first by (normalized, listed) bytewise
|
|
24
|
+
expect(detail.plan.skipped).toContainEqual({ path: NFC, reason: 'duplicate-path' });
|
|
25
|
+
expect(detail.plan.merkleRoot).toBe(merkleTree(detail.files).root);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it('regression: a `.`/`..` path or a path listed twice is skipped with a reason, never thrown', async () => {
|
|
29
|
+
const source = memSource({ 'a.md': '# A\n', './a.md': '# A2\n', '../up.md': '# Up\n', 'd/./x.md': '# X\n' });
|
|
30
|
+
const detail = await planDetail(source, new InMemoryIngestManifest(), [DOCS_PACK]);
|
|
31
|
+
expect(detail.files.map((f) => f.path)).toEqual(['a.md']);
|
|
32
|
+
expect(detail.plan.skipped).toEqual(expect.arrayContaining([
|
|
33
|
+
{ path: '../up.md', reason: 'invalid-path' }, { path: 'd/./x.md', reason: 'invalid-path' }, { path: 'a.md', reason: 'duplicate-path' },
|
|
34
|
+
]));
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it('regression: a file the source lists in NFD is read by that spelling and stored under its NFC path', async () => {
|
|
38
|
+
const source = memSource({ [NFD]: '# Café\nbody\n' });
|
|
39
|
+
const store = memStore();
|
|
40
|
+
const report = await reviewDirectory(args(source, store, new InMemoryIngestManifest(), { judgement: fakeJudge() }));
|
|
41
|
+
expect(report.readErrors).toBe(0);
|
|
42
|
+
expect(source.reads).toContain(NFD);
|
|
43
|
+
expect(source.reads).not.toContain(NFC);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('regression: a pool job for an NFD-named file carries the listed spelling in readByPool.path and the NFC identity in job.path', async () => {
|
|
47
|
+
const source = memSource({ [NFD]: '# Café\nbody\n' });
|
|
48
|
+
const jobs: ExtractJob[] = [];
|
|
49
|
+
const pool: ExtractPool = async (job) => {
|
|
50
|
+
jobs.push(job);
|
|
51
|
+
const doc = await source.read(job.readByPool!.path);
|
|
52
|
+
return extractJob({ ...job, doc } as ExtractJob, [DOCS_PACK]);
|
|
53
|
+
};
|
|
54
|
+
const report = await reviewDirectory(args(source, memStore(), new InMemoryIngestManifest(), { extractPool: pool, deferRead: true }));
|
|
55
|
+
expect(report.failures).toEqual([]);
|
|
56
|
+
expect(report.extracted).toBe(1);
|
|
57
|
+
expect(jobs).toHaveLength(1);
|
|
58
|
+
expect(jobs[0]!.path).toBe(NFC);
|
|
59
|
+
expect(jobs[0]!.readByPool!.path).toBe(NFD);
|
|
60
|
+
expect(jobs[0]!.readByPool!.path).not.toBe(jobs[0]!.path);
|
|
61
|
+
expect(source.reads).toEqual([NFD]);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it('regression: the hashOf and readTimeoutMs hooks receive the listed (NFD) spelling, never the NFC identity', async () => {
|
|
65
|
+
const source = memSource({ [NFD]: '# Café\nbody\n' });
|
|
66
|
+
const hashed: string[] = [], timed: string[] = [];
|
|
67
|
+
source.hashOf = (text: string, path: string) => { hashed.push(path); return hashText(text); };
|
|
68
|
+
source.readTimeoutMs = (path: string) => { timed.push(path); return undefined; };
|
|
69
|
+
const report = await reviewDirectory(args(source, memStore(), new InMemoryIngestManifest(), { judgement: fakeJudge() }));
|
|
70
|
+
expect(report.failures).toEqual([]);
|
|
71
|
+
expect(hashed).toEqual([NFD]);
|
|
72
|
+
expect(timed.length).toBeGreaterThan(0);
|
|
73
|
+
expect(new Set(timed)).toEqual(new Set([NFD]));
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('regression: refreshPlan (Continue) keeps a re-spelled file\'s listedPath', async () => {
|
|
77
|
+
const source = memSource({ [NFD]: '# Café\nbody\n', 'ok.md': '# OK\n' });
|
|
78
|
+
const manifest = new InMemoryIngestManifest();
|
|
79
|
+
const detail = await planDetail(source, manifest, [DOCS_PACK]);
|
|
80
|
+
expect(detail.files.find((f) => f.path === NFC)!.listedPath).toBe(NFD);
|
|
81
|
+
const refreshed = await refreshPlan(detail, manifest);
|
|
82
|
+
expect(refreshed.files.find((f) => f.path === NFC)!.listedPath).toBe(NFD);
|
|
83
|
+
expect(refreshed.files.find((f) => f.path === 'ok.md')!.listedPath).toBeUndefined();
|
|
84
|
+
});
|
|
85
|
+
});
|
|
@@ -12,6 +12,8 @@
|
|
|
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,
|
|
@@ -19,6 +21,10 @@ import type {
|
|
|
19
21
|
RowChange, RowPersistence,
|
|
20
22
|
} from '../knowledge/index.js';
|
|
21
23
|
import type { PlannedFile } from '../knowledge/index.js';
|
|
24
|
+
import type {
|
|
25
|
+
AnalysisIssue, AnchorKind, CodeAnalysisSnapshot, ComparabilityMeta, Finding, FindingIdentity, LineageEntry,
|
|
26
|
+
comparable, compareAnalysis, identityOf, matchLineage,
|
|
27
|
+
} from '../knowledge/index.js';
|
|
22
28
|
import { placementOf } from '../knowledge/index.js';
|
|
23
29
|
import { canonicalDump, ExtractFailed, failuresOf, failureTotal, LocalSnapshotStore, localSnapshotStore, type ExtractorState } from '../knowledge/index.js';
|
|
24
30
|
|
|
@@ -103,6 +109,31 @@ export type ExtractFailed_constructor = Expect<Equal<ConstructorParameters<typeo
|
|
|
103
109
|
export type ExtractorState_failures = Expect<Equal<ExtractorState['failures'], ReadonlyMap<string, { hash: string; count: number }> | undefined>>;
|
|
104
110
|
// ExtractorState.oversized: claimed documents over the size cap, planned as assets; optional so a hand-built state stays valid.
|
|
105
111
|
export type ExtractorState_oversized = Expect<Equal<ExtractorState['oversized'], ReadonlySet<string> | undefined>>;
|
|
112
|
+
// 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.
|
|
113
|
+
export type ExtractorState_contentHashRule = Expect<Equal<ExtractorState['contentHashRule'], string | undefined>>;
|
|
114
|
+
|
|
115
|
+
/* ── Content identity and directory Merkle hashes (PRD 41 §B2 steps 0 and 4) ───────────────────────────────── */
|
|
116
|
+
export type contentHash_signature = Expect<Equal<typeof contentHash, (bytes: Uint8Array) => string>>;
|
|
117
|
+
export type CONTENT_HASH_RULE_type = Expect<Equal<typeof CONTENT_HASH_RULE, 'eol-lf@1'>>;
|
|
118
|
+
export type MerkleEntry_shape = Expect<Equal<MerkleEntry, { name: string; kind: 'file' | 'dir'; hash: string }>>;
|
|
119
|
+
export type MerkleTree_shape = Expect<Equal<MerkleTree, {
|
|
120
|
+
root: string; dirs: ReadonlyMap<string, string>; entries: ReadonlyMap<string, ReadonlyArray<MerkleEntry>>;
|
|
121
|
+
}>>;
|
|
122
|
+
export type merkleTree_signature = Expect<Equal<typeof merkleTree, (files: ReadonlyArray<{ path: string; hash: string }>) => MerkleTree>>;
|
|
123
|
+
export type changedPaths_signature = Expect<Equal<typeof changedPaths, (before: MerkleTree, after: MerkleTree) => string[]>>;
|
|
124
|
+
export type ReviewPlan_merkleRoot = Expect<Equal<ReviewPlan['merkleRoot'], string | undefined>>;
|
|
125
|
+
export type PlanDetail_merkle = Expect<Equal<PlanDetail['merkle'], MerkleTree | undefined>>;
|
|
126
|
+
export type BASELINE_CONTENT_HASH_RULE_type = Expect<Equal<typeof BASELINE_CONTENT_HASH_RULE, 'eol-lf@1'>>;
|
|
127
|
+
export type contentHashRuleOf_signature = Expect<Equal<typeof contentHashRuleOf, (recorded: string | undefined) => string>>;
|
|
128
|
+
// 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.
|
|
129
|
+
export type ReviewPlan_skipped_reason = Expect<Equal<
|
|
130
|
+
ReviewPlan['skipped'][number]['reason'], 'ignored' | 'too-large' | 'no-pack' | 'invalid-path' | 'duplicate-path'
|
|
131
|
+
>>;
|
|
132
|
+
export type PlannedFile_listedPath = Expect<Equal<PlannedFile['listedPath'], string | undefined>>;
|
|
133
|
+
export type canonicalListing_skipped = Expect<Equal<
|
|
134
|
+
ReturnType<typeof canonicalListing<{ path: string }>>['skipped'], Array<{ path: string; reason: ListingSkipReason }>
|
|
135
|
+
>>;
|
|
136
|
+
export type ListingSkipReason_values = Expect<Equal<ListingSkipReason, 'invalid-path' | 'duplicate-path'>>;
|
|
106
137
|
|
|
107
138
|
/* ── DirectorySource: optional per-path hooks ──────────────────────────────────────────────────────────────── */
|
|
108
139
|
// 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 +259,32 @@ export type NodePlacement_shape = Expect<Equal<NodePlacement, { kind: 'partition
|
|
|
228
259
|
export type placementOf_signature = Expect<Equal<ReturnType<typeof placementOf>, NodePlacement | undefined>>;
|
|
229
260
|
export type KEdge_verdict = Expect<Equal<KEdge['verdict'], 'allowed' | 'same' | 'skips' | 'upward' | undefined>>;
|
|
230
261
|
|
|
262
|
+
/* ── Finding identity v2, lineage, comparability (PRD 41 §C3/§C9) ─────────────────────────────────────────── */
|
|
263
|
+
export type AnchorKind_values = Expect<Equal<AnchorKind, 'symbol' | 'route' | 'package' | 'file' | 'group'>>;
|
|
264
|
+
export type Finding_anchor_is_optional = Expect<Equal<IsOptional<Finding, 'anchor'>, true>>;
|
|
265
|
+
export type Finding_anchorKind = Expect<Equal<Finding['anchorKind'], AnchorKind | undefined>>;
|
|
266
|
+
export type FindingIdentity_shape = Expect<Equal<FindingIdentity, { id: string; anchor: string; anchorKind: AnchorKind; members: string[] }>>;
|
|
267
|
+
export type identityOf_signature = Expect<Equal<typeof identityOf, (f: Finding, ruleVersion?: number) => FindingIdentity>>;
|
|
268
|
+
export type LineageEntry_shape = Expect<Equal<LineageEntry, {
|
|
269
|
+
lineage: 'introduced' | 'resolved' | 'changed' | 'persisting'; change?: 'grew' | 'shrank' | 'moved'; before?: string; after?: string;
|
|
270
|
+
}>>;
|
|
271
|
+
export type matchLineage_signature = Expect<Equal<
|
|
272
|
+
typeof matchLineage, (before: readonly FindingIdentity[], after: readonly FindingIdentity[]) => LineageEntry[]
|
|
273
|
+
>>;
|
|
274
|
+
export type ComparabilityMeta_shape = Expect<Equal<ComparabilityMeta, {
|
|
275
|
+
extractor?: string; extractorVersion?: string | number; contentHashRule?: string; tools?: Record<string, string>;
|
|
276
|
+
scope?: string; repo?: string; branch?: string; truncated?: boolean; failed?: string[];
|
|
277
|
+
}>>;
|
|
278
|
+
export type comparable_signature = Expect<Equal<
|
|
279
|
+
typeof comparable, (before: ComparabilityMeta, after: ComparabilityMeta) => { comparable: boolean; reasons: string[] }
|
|
280
|
+
>>;
|
|
281
|
+
export type AnalysisIssue_anchor_is_optional = Expect<Equal<IsOptional<AnalysisIssue, 'anchor'>, true>>;
|
|
282
|
+
export type compareAnalysis_result = Expect<Equal<
|
|
283
|
+
ReturnType<typeof compareAnalysis>,
|
|
284
|
+
{ comparable: boolean; reasons: string[]; added: AnalysisIssue[]; unchanged: AnalysisIssue[]; resolved: AnalysisIssue[] }
|
|
285
|
+
>>;
|
|
286
|
+
export type CodeAnalysisSnapshot_version = Expect<Equal<CodeAnalysisSnapshot['version'], 1>>;
|
|
287
|
+
|
|
231
288
|
describe('type contract', () => {
|
|
232
289
|
it('is enforced by `npm run check:contract-types` (tsc over tsconfig.contract.json), not at run time', () => {
|
|
233
290
|
// The values above only exist so the `satisfies` / `@ts-expect-error` lines are real code; this proves the file loads.
|
|
@@ -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. */
|