@seanhogg/builderforce-memory 2026.10.66 → 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 +12 -1
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +8 -1
- 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 +18 -2
- package/dist/knowledge/refs.d.ts.map +1 -1
- package/dist/knowledge/refs.js +38 -8
- 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 +29 -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/regression.refs.test.ts +49 -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 +18 -1
- 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 +36 -8
- 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,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
|
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import { hashText } from '../ingest/hash.js';
|
|
8
8
|
import type { Finding, NodeRef } from './model.js';
|
|
9
9
|
import { compareStr } from './refs.js';
|
|
10
|
+
import { anchorKindOfRef, anchorWithSnippet, type AnchorKind } from './findingIdentity.js';
|
|
10
11
|
|
|
11
12
|
/** Refs listed on one grouped finding, at most (the count rides in params). */
|
|
12
13
|
export const MAX_FINDING_NODES = 50;
|
|
@@ -20,18 +21,32 @@ export function requestKeyFor(kind: string): string {
|
|
|
20
21
|
return `knowledgeGraph.fix.${kind.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase())}`;
|
|
21
22
|
}
|
|
22
23
|
|
|
24
|
+
/** The primary anchor a rule names for its finding (PRD 41 §C3); `snippet` is hashed after normalization. */
|
|
25
|
+
export interface FindingAnchor {
|
|
26
|
+
anchor: string;
|
|
27
|
+
anchorKind: AnchorKind;
|
|
28
|
+
snippet?: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
23
31
|
/**
|
|
24
32
|
* The ONE finding builder: nodes deduped, sorted and capped at {@link MAX_FINDING_NODES}.
|
|
25
33
|
* The id hashes `idRefs` (default: all the nodes) — pass a narrower set to keep it stable
|
|
26
|
-
* while the listed nodes change.
|
|
34
|
+
* while the listed nodes change. `anchor` sets the finding's primary anchor (identity v2);
|
|
35
|
+
* omitted, `identityOf` falls back to its default.
|
|
27
36
|
*/
|
|
28
37
|
export function finding(
|
|
29
38
|
kind: string, pack: string, nodes: readonly NodeRef[], severity: Finding['severity'], params: Finding['params'],
|
|
30
|
-
idRefs?: readonly string[],
|
|
39
|
+
idRefs?: readonly string[], anchor?: FindingAnchor,
|
|
31
40
|
): Finding {
|
|
32
41
|
const sorted = [...new Set(nodes)].sort(compareStr);
|
|
33
42
|
return {
|
|
34
43
|
id: findingId(kind, idRefs ?? sorted), kind, pack, nodes: sorted.slice(0, MAX_FINDING_NODES), severity, params,
|
|
35
44
|
requestKey: requestKeyFor(kind),
|
|
45
|
+
...(anchor ? { anchor: anchorWithSnippet(anchor.anchor, anchor.snippet), anchorKind: anchor.anchorKind } : {}),
|
|
36
46
|
};
|
|
37
47
|
}
|
|
48
|
+
|
|
49
|
+
/** A {@link FindingAnchor} on a node ref, its kind read from the ref ({@link anchorKindOfRef}). */
|
|
50
|
+
export function refAnchor(ref: string): FindingAnchor {
|
|
51
|
+
return { anchor: ref, anchorKind: anchorKindOfRef(ref) };
|
|
52
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/knowledge/findingIdentity.test.ts — identity v2 anchors (PRD 41 §C3): stable when line numbers
|
|
3
|
+
* move and when members are added; never the member set; the documented default.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { CLONE_GROUP_BADGE, finding, genericFindings } from './findings.js';
|
|
7
|
+
import { anchorKindOfRef, anchorWithSnippet, defaultAnchorOf, identityOf, normalizeSnippet } from './findingIdentity.js';
|
|
8
|
+
import { godModuleFindings } from './godModule.js';
|
|
9
|
+
import { possibleSameFindings } from './resolve.js';
|
|
10
|
+
import { normalizeAnalysis } from './comparability.js';
|
|
11
|
+
import type { KEdge, KNode, KnowledgeGraph } from './model.js';
|
|
12
|
+
|
|
13
|
+
const ref = (p: string) => `src:r::${p}`;
|
|
14
|
+
const node = (p: string, extra: Partial<KNode> = {}): KNode => ({ ref: ref(p), kind: 'file', label: p, pack: 'code', importance: 0, origin: 'extracted', ...extra });
|
|
15
|
+
const edge = (a: string, b: string, extra: Partial<KEdge>): KEdge => ({ from: ref(a), to: ref(b), kind: 'references', weight: 1, origin: 'extracted', ...extra });
|
|
16
|
+
const graph = (nodes: KNode[], edges: KEdge[]): KnowledgeGraph => ({
|
|
17
|
+
scope: { rootId: 'r', packs: ['code'], digest: 'd' }, nodes, edges, findings: [],
|
|
18
|
+
stats: { sources: nodes.length, nodes: nodes.length, edges: edges.length, stale: 0, truncated: false },
|
|
19
|
+
});
|
|
20
|
+
const of = (g: KnowledgeGraph, kind: string) => genericFindings(g, new Map()).filter((f) => f.kind === kind).map((f) => identityOf(f));
|
|
21
|
+
|
|
22
|
+
describe('identityOf', () => {
|
|
23
|
+
it('composes kind@version:anchorKind:primary and keeps the v1 id', () => {
|
|
24
|
+
const f = finding('god-module', 'code', [ref('a.ts')], 'warn', {}, undefined, { anchor: ref('a.ts'), anchorKind: 'file' });
|
|
25
|
+
expect(identityOf(f)).toEqual({ id: f.id, anchor: `god-module@1:file:${ref('a.ts')}`, anchorKind: 'file', members: [ref('a.ts')] });
|
|
26
|
+
expect(identityOf(f, 3).anchor).toBe(`god-module@3:file:${ref('a.ts')}`);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it('defaults to the sorted-first node ref (never the set), else the pack', () => {
|
|
30
|
+
const f = finding('orphan', 'docs', [ref('z.md'), ref('a.md#intro')], 'info', {});
|
|
31
|
+
expect(f.anchor).toBeUndefined();
|
|
32
|
+
expect(defaultAnchorOf(f)).toEqual({ anchor: ref('a.md#intro'), anchorKind: 'symbol' });
|
|
33
|
+
expect(identityOf(f).anchor).toBe(`orphan@1:symbol:${ref('a.md#intro')}`);
|
|
34
|
+
expect(defaultAnchorOf({ nodes: [], pack: 'docs' })).toEqual({ anchor: 'pack:docs', anchorKind: 'group' });
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it('reads the anchor kind from a ref', () => {
|
|
38
|
+
expect(anchorKindOfRef(ref('a.ts'))).toBe('file');
|
|
39
|
+
expect(anchorKindOfRef(ref('a.ts#Foo.bar'))).toBe('symbol');
|
|
40
|
+
expect(anchorKindOfRef('ent:code:lease')).toBe('symbol');
|
|
41
|
+
expect(anchorKindOfRef('fact:x')).toBe('group');
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('a badged clone group keeps its anchor when it gains a member', () => {
|
|
45
|
+
const b = { badges: { [CLONE_GROUP_BADGE]: 'g1' } };
|
|
46
|
+
const two = of(graph([node('a.ts', b), node('b.ts', b)], [edge('a.ts', 'b.ts', { kind: 'duplicate' })]), 'clone-group')[0]!;
|
|
47
|
+
const three = of(graph([node('a.ts', b), node('b.ts', b), node('c.ts', b)],
|
|
48
|
+
[edge('a.ts', 'b.ts', { kind: 'duplicate' }), edge('b.ts', 'c.ts', { kind: 'duplicate' })]), 'clone-group')[0]!;
|
|
49
|
+
expect(three.anchor).toBe(two.anchor);
|
|
50
|
+
expect(two.anchor).toBe('clone-group@1:group:cloneGroup:g1');
|
|
51
|
+
expect(three.id).not.toBe(two.id);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('an unbadged clone group / cycle anchors on its sorted-first member, so a member sorting later keeps it', () => {
|
|
55
|
+
const cyc = (extra: string[]) => of(graph(
|
|
56
|
+
['a.ts', 'b.ts', ...extra].map((p) => node(p)),
|
|
57
|
+
[edge('a.ts', 'b.ts', { cycle: true }), edge('b.ts', 'a.ts', { cycle: true }), ...extra.map((p) => edge('b.ts', p, { cycle: true }))],
|
|
58
|
+
), 'cycle')[0]!;
|
|
59
|
+
expect(cyc(['z.ts']).anchor).toBe(cyc([]).anchor);
|
|
60
|
+
expect(cyc([]).anchor).toBe(`cycle@1:file:${ref('a.ts')}`);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it('a partition violation anchors on the layer pair and the from FILE, not the target', () => {
|
|
64
|
+
const nodes = [
|
|
65
|
+
node('ui/a.ts', { partition: 'ui' }), node('ui/a.ts#render', { kind: 'symbol', partition: 'ui' }),
|
|
66
|
+
node('db/x.ts', { partition: 'db' }), node('db/y.ts', { partition: 'db' }),
|
|
67
|
+
];
|
|
68
|
+
const v1 = of(graph(nodes, [edge('ui/a.ts', 'db/x.ts', { verdict: 'skips' })]), 'partition-violation')[0]!;
|
|
69
|
+
const v2 = of(graph(nodes, [edge('ui/a.ts#render', 'db/y.ts', { verdict: 'skips' })]), 'partition-violation')[0]!;
|
|
70
|
+
expect(v1.anchor).toBe(`partition-violation@1:file:ui->db@${ref('ui/a.ts')}`);
|
|
71
|
+
expect(v2.anchor).toBe(v1.anchor);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it('god-module and possible-same anchor on their item', () => {
|
|
75
|
+
const [god] = godModuleFindings(graph([node('big.ts', { badges: { patterns: 'god-module' } })], []));
|
|
76
|
+
expect(identityOf(god!).anchor).toBe(`god-module@1:file:${ref('big.ts')}`);
|
|
77
|
+
const [same] = possibleSameFindings([{ a: 'ent:code:zeta', b: 'ent:code:alpha', similarity: 0.9 }]);
|
|
78
|
+
expect(identityOf(same!).anchor).toBe('possible-same@1:symbol:ent:code:alpha');
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
describe('snippet anchors', () => {
|
|
83
|
+
it('re-indenting, CRLF and blank lines keep the normalized-snippet hash', () => {
|
|
84
|
+
expect(normalizeSnippet(' a = 1;\r\n\r\n\tb = 2; ')).toBe('a = 1;\nb = 2;');
|
|
85
|
+
expect(anchorWithSnippet('p', 'a = 1;\nb = 2;')).toBe(anchorWithSnippet('p', ' a = 1;\r\n\n b = 2;'));
|
|
86
|
+
expect(anchorWithSnippet('p', 'a = 1;')).not.toBe(anchorWithSnippet('p', 'a = 2;'));
|
|
87
|
+
expect(anchorWithSnippet('p')).toBe('p');
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it('jscpd / knip anchors hold no line numbers', () => {
|
|
91
|
+
const dups = (start: number) => ({ duplicates: [{ fragment: 'return x;', firstFile: { name: 'src/a.ts', start, end: start + 5 }, secondFile: { name: 'src/b.ts', start: 9, end: 14 } }] });
|
|
92
|
+
const unused = (line: number) => ({ files: ['src/dead.ts'], issues: [{ file: 'src/b.ts', exports: [{ name: 'x', line }], dependencies: [{ name: 'lib' }] }] });
|
|
93
|
+
const a = normalizeAnalysis({}, dups(2), unused(3)).issues, b = normalizeAnalysis({}, dups(80), unused(90)).issues;
|
|
94
|
+
expect(b.map((i) => i.anchor)).toEqual(a.map((i) => i.anchor));
|
|
95
|
+
expect(a.map((i) => i.anchor)).toEqual([
|
|
96
|
+
`duplicate@1:file:${anchorWithSnippet('src/a.ts', 'return x;')}`,
|
|
97
|
+
'unused-file@1:file:src/dead.ts',
|
|
98
|
+
'unused-export@1:symbol:src/b.ts#x',
|
|
99
|
+
'unused-dependency@1:package:src/b.ts#lib',
|
|
100
|
+
]);
|
|
101
|
+
});
|
|
102
|
+
});
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/findingIdentity.ts — finding identity v2 (PRD 41 §C3): the exact `id` (set membership,
|
|
3
|
+
* unchanged), a STABLE `anchor` that survives line movement and member churn, and the sorted
|
|
4
|
+
* `members` lineage compares by similarity.
|
|
5
|
+
*
|
|
6
|
+
* The anchor follows SARIF `partialFingerprints`:
|
|
7
|
+
*
|
|
8
|
+
* <kind>@<ruleVersion>:<anchorKind>:<primary anchor>[~<normalized-snippet hash>]
|
|
9
|
+
*
|
|
10
|
+
* It NEVER holds a line number or the member set. The rule that emits a finding names its primary
|
|
11
|
+
* anchor (`Finding.anchor`, `Finding.anchorKind`); {@link identityOf} composes the rest. A finding
|
|
12
|
+
* whose rule names none gets the {@link defaultAnchorOf default}: its lexicographically first node
|
|
13
|
+
* ref (one member, never the set; refs hold no line numbers), else its pack.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { hashText } from '../ingest/hash.js';
|
|
17
|
+
import type { Finding, NodeRef } from './model.js';
|
|
18
|
+
import { compareStr, fileRefOf } from './refs.js';
|
|
19
|
+
|
|
20
|
+
/** What a finding's primary anchor names. `group` is a named group (a clone-group badge, a pack). */
|
|
21
|
+
export type AnchorKind = NonNullable<Finding['anchorKind']>;
|
|
22
|
+
|
|
23
|
+
export interface FindingIdentity {
|
|
24
|
+
/** Exact identity (kind + all refs), unchanged from v1 — set membership. */
|
|
25
|
+
id: string;
|
|
26
|
+
/** `<kind>@<ruleVersion>:<anchorKind>:<primary>[~<snippetHash>]` — no line numbers, no member set. */
|
|
27
|
+
anchor: string;
|
|
28
|
+
anchorKind: AnchorKind;
|
|
29
|
+
/** Sorted, deduped refs (files/symbols) — lineage similarity. */
|
|
30
|
+
members: string[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The rule version an identity is composed with when the caller names none. */
|
|
34
|
+
export const DEFAULT_RULE_VERSION = 1;
|
|
35
|
+
|
|
36
|
+
/** Separates the primary anchor from its normalized-snippet hash. */
|
|
37
|
+
const SNIPPET_SEPARATOR = '~';
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* A snippet with formatting noise removed: CRLF → LF, each line trimmed, inner whitespace runs
|
|
41
|
+
* collapsed to one space, blank lines dropped. Re-indenting or re-wrapping blank lines keeps the hash.
|
|
42
|
+
*/
|
|
43
|
+
export function normalizeSnippet(snippet: string): string {
|
|
44
|
+
return snippet.replace(/\r\n?/g, '\n').split('\n')
|
|
45
|
+
.map((l) => l.trim().replace(/\s+/g, ' '))
|
|
46
|
+
.filter((l) => l.length > 0)
|
|
47
|
+
.join('\n');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** A primary anchor with the normalized-snippet hash appended (unchanged when there is no snippet). */
|
|
51
|
+
export function anchorWithSnippet(primary: string, snippet?: string): string {
|
|
52
|
+
return snippet === undefined ? primary : `${primary}${SNIPPET_SEPARATOR}${hashText(normalizeSnippet(snippet))}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The anchor kind a node ref implies: a section/symbol ref (`…#name`) → symbol, a source ref → file, else group. */
|
|
56
|
+
export function anchorKindOfRef(ref: string): AnchorKind {
|
|
57
|
+
if (!ref.startsWith('src:')) return ref.startsWith('ent:') ? 'symbol' : 'group';
|
|
58
|
+
return fileRefOf(ref as NodeRef) === ref ? 'file' : 'symbol';
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The ONE anchor string: `<kind>@<ruleVersion>:<anchorKind>:<primary>`. */
|
|
62
|
+
export function composeAnchor(kind: string, ruleVersion: number, anchorKind: AnchorKind, primary: string): string {
|
|
63
|
+
return `${kind}@${ruleVersion}:${anchorKind}:${primary}`;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The finding kind an identity anchor was composed for (the part before `@`). */
|
|
67
|
+
export function kindOfAnchor(anchor: string): string {
|
|
68
|
+
const at = anchor.indexOf('@');
|
|
69
|
+
return at < 0 ? anchor : anchor.slice(0, at);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The default primary anchor of a finding whose rule set none: the lexicographically first node
|
|
74
|
+
* ref (kind from {@link anchorKindOfRef}), else `pack:<pack>` (group). Never a line, never the set.
|
|
75
|
+
*/
|
|
76
|
+
export function defaultAnchorOf(f: Pick<Finding, 'nodes' | 'pack'>): { anchor: string; anchorKind: AnchorKind } {
|
|
77
|
+
const first = [...f.nodes].sort(compareStr)[0];
|
|
78
|
+
return first === undefined ? { anchor: `pack:${f.pack}`, anchorKind: 'group' } : { anchor: first, anchorKind: anchorKindOfRef(first) };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The v2 identity of a finding. `ruleVersion` is the emitting rule's version (default {@link DEFAULT_RULE_VERSION}). */
|
|
82
|
+
export function identityOf(f: Finding, ruleVersion: number = DEFAULT_RULE_VERSION): FindingIdentity {
|
|
83
|
+
const fallback = f.anchor === undefined ? defaultAnchorOf(f) : undefined;
|
|
84
|
+
const primary = f.anchor ?? fallback!.anchor;
|
|
85
|
+
const anchorKind = f.anchorKind ?? fallback?.anchorKind ?? anchorKindOfRef(primary);
|
|
86
|
+
return {
|
|
87
|
+
id: f.id,
|
|
88
|
+
anchor: composeAnchor(f.kind, ruleVersion, anchorKind, primary),
|
|
89
|
+
anchorKind,
|
|
90
|
+
members: [...new Set<string>(f.nodes as readonly NodeRef[])].sort(compareStr),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/findingModel.ts — the finding types: what a rule reports over a graph (moved out of model.ts,
|
|
3
|
+
* which re-exports them, so every import of `./model.js` keeps working). Identity v2 lives in findingIdentity.ts.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { KnowledgeGraph, NodeRef } from './model.js';
|
|
7
|
+
|
|
8
|
+
/** A finding a person can act on. `kind` is pack-defined; `requestKey` names an i18n template. */
|
|
9
|
+
export interface Finding {
|
|
10
|
+
id: string;
|
|
11
|
+
kind: string;
|
|
12
|
+
pack: string;
|
|
13
|
+
nodes: NodeRef[];
|
|
14
|
+
severity: 'info' | 'warn' | 'error';
|
|
15
|
+
/** Numbers/strings for the label and the Fix-with-agent template. */
|
|
16
|
+
params: Record<string, string | number>;
|
|
17
|
+
/** i18n key of the fixed Fix-with-agent request (e.g. 'knowledgeGraph.fix.cloneGroup'). */
|
|
18
|
+
requestKey?: string;
|
|
19
|
+
/**
|
|
20
|
+
* The PRIMARY anchor the emitting rule names (PRD 41 §C3): an enclosing symbol/file ref, route key,
|
|
21
|
+
* package name or group name, plus `~<normalized-snippet hash>` where a snippet exists. Never a line
|
|
22
|
+
* number, never the member set. Absent ⇒ `identityOf` uses its documented default.
|
|
23
|
+
*/
|
|
24
|
+
anchor?: string;
|
|
25
|
+
/** What {@link Finding.anchor} names. */
|
|
26
|
+
anchorKind?: 'symbol' | 'route' | 'package' | 'file' | 'group';
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface FindingRule {
|
|
30
|
+
id: string;
|
|
31
|
+
find(graph: KnowledgeGraph): Finding[];
|
|
32
|
+
}
|