@a2f0/agent-tool 0.1.84 → 0.1.86
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/package.json +1 -1
- package/skills/deslopify-refactor/SKILL.md +65 -10
- package/skills/deslopify-refactor/references/lessons.md +19 -1
- package/skills/deslopify-refactor/references/pathology-catalog.md +3 -2
- package/src/cli.ts +2 -2
- package/src/deslop/command.ts +81 -18
- package/src/deslop/scan.ts +98 -209
- package/src/deslop/structural.ts +712 -0
- package/src/review/pinnedReviewInput.ts +310 -10
- package/src/skills/bundled.ts +3 -3
|
@@ -0,0 +1,712 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Structural simplification detectors and shared clone-span aggregation for
|
|
3
|
+
* `agent-tool deslop`:
|
|
4
|
+
* - shared pair expansion, diagonal merging, and per-file clone summaries
|
|
5
|
+
* - parametric clones (identical token structure with renamed identifiers/literals)
|
|
6
|
+
* - over-fragmented micro-files (1 relative importer or non-index re-export shims)
|
|
7
|
+
* - directory-level hotspot rollups (duplication, candidate scores, and test/source ratios)
|
|
8
|
+
*/
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
|
|
11
|
+
export type DeslopSignalKind =
|
|
12
|
+
| "duplicate-block"
|
|
13
|
+
| "parametric-clone"
|
|
14
|
+
| "oversized-file"
|
|
15
|
+
| "long-function"
|
|
16
|
+
| "suppressions"
|
|
17
|
+
| "thin-wrapper"
|
|
18
|
+
| "micro-file";
|
|
19
|
+
|
|
20
|
+
export interface DeslopSignal {
|
|
21
|
+
readonly kind: DeslopSignalKind;
|
|
22
|
+
readonly count: number;
|
|
23
|
+
/** 1-based line numbers where the signal starts or appears. */
|
|
24
|
+
readonly lines: number[];
|
|
25
|
+
/** Optional function names, wrapper names, or peer clone locations. */
|
|
26
|
+
readonly details?: string[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface DeslopFileReport {
|
|
30
|
+
readonly path: string;
|
|
31
|
+
readonly score: number;
|
|
32
|
+
readonly signals: DeslopSignal[];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface DuplicateLocation {
|
|
36
|
+
readonly path: string;
|
|
37
|
+
readonly start: number;
|
|
38
|
+
readonly end: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface DuplicateCluster {
|
|
42
|
+
readonly lines: number;
|
|
43
|
+
readonly locations: DuplicateLocation[];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface ScannedSource {
|
|
47
|
+
readonly path: string;
|
|
48
|
+
readonly text: string;
|
|
49
|
+
readonly syntax: "c" | "hash";
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface NormalizedLine {
|
|
53
|
+
readonly line: number;
|
|
54
|
+
readonly text: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface CloneOccurrence {
|
|
58
|
+
readonly fileIndex: number;
|
|
59
|
+
readonly normIndex: number;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface DuplicateSpan {
|
|
63
|
+
readonly fileA: number;
|
|
64
|
+
readonly normStartA: number;
|
|
65
|
+
readonly normEndA: number;
|
|
66
|
+
readonly fileB: number;
|
|
67
|
+
readonly normStartB: number;
|
|
68
|
+
readonly normEndB: number;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface FileDuplicateSummary {
|
|
72
|
+
readonly duplicatedLines: number;
|
|
73
|
+
readonly startLines: number[];
|
|
74
|
+
readonly peers: string[];
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface MicroFileLead {
|
|
78
|
+
readonly codeLines: number;
|
|
79
|
+
readonly isReexportShim: boolean;
|
|
80
|
+
readonly detail: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface DeslopDirectoryReport {
|
|
84
|
+
readonly directory: string;
|
|
85
|
+
readonly sourceFiles: number;
|
|
86
|
+
readonly sourceLines: number;
|
|
87
|
+
readonly testFiles: number;
|
|
88
|
+
readonly testLines: number;
|
|
89
|
+
readonly testRatio: number | null;
|
|
90
|
+
readonly candidateFiles: number;
|
|
91
|
+
readonly duplicateLines: number;
|
|
92
|
+
readonly parametricLines: number;
|
|
93
|
+
readonly microFiles: number;
|
|
94
|
+
readonly totalScore: number;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export const PARAMETRIC_WINDOW = 8;
|
|
98
|
+
const PARAMETRIC_MIN_CHARS = 220;
|
|
99
|
+
const PARAMETRIC_MAX_OCCURRENCES = 12;
|
|
100
|
+
export const MICRO_FILE_MAX_LINES = 35;
|
|
101
|
+
const REEXPORT_SHIM_MAX_LINES = 15;
|
|
102
|
+
|
|
103
|
+
export function rangesOverlap(startA: number, endA: number, startB: number, endB: number): boolean {
|
|
104
|
+
return startA <= endB && startB <= endA;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Expands bucketed window occurrences into merged diagonal spans, keeps the
|
|
109
|
+
* longest non-overlapping spans per file pair, and aggregates per-file
|
|
110
|
+
* duplicate summaries and sorted clone clusters.
|
|
111
|
+
*/
|
|
112
|
+
export function collectAndSummarizeClones(
|
|
113
|
+
sources: ScannedSource[],
|
|
114
|
+
normalizedByFile: NormalizedLine[][],
|
|
115
|
+
buckets: Map<string, CloneOccurrence[] | null>,
|
|
116
|
+
windowSize: number,
|
|
117
|
+
shouldSkipSpan?: (span: DuplicateSpan) => boolean,
|
|
118
|
+
): { perFile: Map<number, FileDuplicateSummary>; clusters: DuplicateCluster[]; spans: DuplicateSpan[] } {
|
|
119
|
+
const pairStarts = new Map<string, Array<{ a: number; b: number }>>();
|
|
120
|
+
for (const occurrences of buckets.values()) {
|
|
121
|
+
if (!occurrences || occurrences.length < 2) continue;
|
|
122
|
+
for (let i = 0; i < occurrences.length; i++) {
|
|
123
|
+
for (let j = i + 1; j < occurrences.length; j++) {
|
|
124
|
+
const first = occurrences[i]!;
|
|
125
|
+
const second = occurrences[j]!;
|
|
126
|
+
if (first.fileIndex === second.fileIndex && second.normIndex - first.normIndex < windowSize) continue;
|
|
127
|
+
const key = `${first.fileIndex}:${second.fileIndex}`;
|
|
128
|
+
const list = pairStarts.get(key);
|
|
129
|
+
const item = { a: first.normIndex, b: second.normIndex };
|
|
130
|
+
if (list) list.push(item);
|
|
131
|
+
else pairStarts.set(key, [item]);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const rawSpans: DuplicateSpan[] = [];
|
|
137
|
+
for (const [pairKey, matches] of pairStarts) {
|
|
138
|
+
const [fileA, fileB] = pairKey.split(":").map(Number) as [number, number];
|
|
139
|
+
const byDiag = new Map<number, number[]>();
|
|
140
|
+
for (const { a, b } of matches) {
|
|
141
|
+
const diag = b - a;
|
|
142
|
+
const list = byDiag.get(diag);
|
|
143
|
+
if (list) list.push(a);
|
|
144
|
+
else byDiag.set(diag, [a]);
|
|
145
|
+
}
|
|
146
|
+
for (const [diag, starts] of byDiag) {
|
|
147
|
+
starts.sort((x, y) => x - y);
|
|
148
|
+
let runStart = starts[0]!;
|
|
149
|
+
let runEnd = runStart + windowSize - 1;
|
|
150
|
+
for (let i = 1; i < starts.length; i++) {
|
|
151
|
+
const next = starts[i]!;
|
|
152
|
+
const candidateEnd = Math.max(runEnd, next + windowSize - 1);
|
|
153
|
+
if (next <= runEnd + 1 && (fileA !== fileB || candidateEnd < runStart + diag)) {
|
|
154
|
+
runEnd = candidateEnd;
|
|
155
|
+
} else {
|
|
156
|
+
if (fileA !== fileB || runEnd < runStart + diag) {
|
|
157
|
+
rawSpans.push({ fileA, normStartA: runStart, normEndA: runEnd, fileB, normStartB: runStart + diag, normEndB: runEnd + diag });
|
|
158
|
+
}
|
|
159
|
+
runStart = next;
|
|
160
|
+
runEnd = next + windowSize - 1;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (fileA !== fileB || runEnd < runStart + diag) {
|
|
164
|
+
rawSpans.push({ fileA, normStartA: runStart, normEndA: runEnd, fileB, normStartB: runStart + diag, normEndB: runEnd + diag });
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
rawSpans.sort(
|
|
170
|
+
(x, y) =>
|
|
171
|
+
y.normEndA - y.normStartA - (x.normEndA - x.normStartA) ||
|
|
172
|
+
x.fileA - y.fileA ||
|
|
173
|
+
x.fileB - y.fileB ||
|
|
174
|
+
x.normStartA - y.normStartA ||
|
|
175
|
+
x.normStartB - y.normStartB,
|
|
176
|
+
);
|
|
177
|
+
|
|
178
|
+
const acceptedByPair = new Map<string, DuplicateSpan[]>();
|
|
179
|
+
const spans: DuplicateSpan[] = [];
|
|
180
|
+
for (const span of rawSpans) {
|
|
181
|
+
if (shouldSkipSpan?.(span)) continue;
|
|
182
|
+
const key = `${span.fileA}:${span.fileB}`;
|
|
183
|
+
const accepted = acceptedByPair.get(key) ?? [];
|
|
184
|
+
const redundant = accepted.some(
|
|
185
|
+
kept =>
|
|
186
|
+
rangesOverlap(span.normStartA, span.normEndA, kept.normStartA, kept.normEndA) &&
|
|
187
|
+
rangesOverlap(span.normStartB, span.normEndB, kept.normStartB, kept.normEndB),
|
|
188
|
+
);
|
|
189
|
+
if (redundant) continue;
|
|
190
|
+
accepted.push(span);
|
|
191
|
+
acceptedByPair.set(key, accepted);
|
|
192
|
+
spans.push(span);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const fileLineSets = new Map<number, Set<number>>();
|
|
196
|
+
const fileStarts = new Map<number, Set<number>>();
|
|
197
|
+
const filePeers = new Map<number, Set<string>>();
|
|
198
|
+
const clusters: DuplicateCluster[] = [];
|
|
199
|
+
|
|
200
|
+
const record = (fileIndex: number, normStart: number, normEnd: number, peerIndex: number, peerStart: number, peerEnd: number) => {
|
|
201
|
+
const norm = normalizedByFile[fileIndex]!;
|
|
202
|
+
const peerNorm = normalizedByFile[peerIndex]!;
|
|
203
|
+
const covered = fileLineSets.get(fileIndex) ?? new Set<number>();
|
|
204
|
+
for (let i = normStart; i <= normEnd; i++) covered.add(norm[i]!.line);
|
|
205
|
+
fileLineSets.set(fileIndex, covered);
|
|
206
|
+
const starts = fileStarts.get(fileIndex) ?? new Set<number>();
|
|
207
|
+
starts.add(norm[normStart]!.line);
|
|
208
|
+
fileStarts.set(fileIndex, starts);
|
|
209
|
+
const peers = filePeers.get(fileIndex) ?? new Set<string>();
|
|
210
|
+
const peerLabel = peerIndex === fileIndex
|
|
211
|
+
? `self:${peerNorm[peerStart]!.line}-${peerNorm[peerEnd]!.line}`
|
|
212
|
+
: `${sources[peerIndex]!.path}:${peerNorm[peerStart]!.line}-${peerNorm[peerEnd]!.line}`;
|
|
213
|
+
peers.add(peerLabel);
|
|
214
|
+
filePeers.set(fileIndex, peers);
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
for (const span of spans) {
|
|
218
|
+
const normA = normalizedByFile[span.fileA]!;
|
|
219
|
+
const normB = normalizedByFile[span.fileB]!;
|
|
220
|
+
const count = span.normEndA - span.normStartA + 1;
|
|
221
|
+
record(span.fileA, span.normStartA, span.normEndA, span.fileB, span.normStartB, span.normEndB);
|
|
222
|
+
record(span.fileB, span.normStartB, span.normEndB, span.fileA, span.normStartA, span.normEndA);
|
|
223
|
+
clusters.push({
|
|
224
|
+
lines: count,
|
|
225
|
+
locations: [
|
|
226
|
+
{ path: sources[span.fileA]!.path, start: normA[span.normStartA]!.line, end: normA[span.normEndA]!.line },
|
|
227
|
+
{ path: sources[span.fileB]!.path, start: normB[span.normStartB]!.line, end: normB[span.normEndB]!.line },
|
|
228
|
+
],
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const perFile = new Map<number, FileDuplicateSummary>();
|
|
233
|
+
for (const [fileIndex, covered] of fileLineSets) {
|
|
234
|
+
perFile.set(fileIndex, {
|
|
235
|
+
duplicatedLines: covered.size,
|
|
236
|
+
startLines: [...(fileStarts.get(fileIndex) ?? [])].sort((a, b) => a - b),
|
|
237
|
+
peers: [...(filePeers.get(fileIndex) ?? [])].sort().slice(0, 5),
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
clusters.sort(
|
|
242
|
+
(a, b) =>
|
|
243
|
+
b.lines - a.lines ||
|
|
244
|
+
a.locations[0]!.path.localeCompare(b.locations[0]!.path) ||
|
|
245
|
+
a.locations[0]!.start - b.locations[0]!.start,
|
|
246
|
+
);
|
|
247
|
+
return { perFile, clusters, spans };
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const PRESERVED_KEYWORDS = new Set([
|
|
251
|
+
"abstract",
|
|
252
|
+
"and",
|
|
253
|
+
"as",
|
|
254
|
+
"assert",
|
|
255
|
+
"async",
|
|
256
|
+
"await",
|
|
257
|
+
"break",
|
|
258
|
+
"case",
|
|
259
|
+
"catch",
|
|
260
|
+
"class",
|
|
261
|
+
"const",
|
|
262
|
+
"continue",
|
|
263
|
+
"def",
|
|
264
|
+
"default",
|
|
265
|
+
"defer",
|
|
266
|
+
"del",
|
|
267
|
+
"delete",
|
|
268
|
+
"do",
|
|
269
|
+
"elif",
|
|
270
|
+
"else",
|
|
271
|
+
"end",
|
|
272
|
+
"enum",
|
|
273
|
+
"except",
|
|
274
|
+
"export",
|
|
275
|
+
"extends",
|
|
276
|
+
"false",
|
|
277
|
+
"finally",
|
|
278
|
+
"fn",
|
|
279
|
+
"for",
|
|
280
|
+
"from",
|
|
281
|
+
"fun",
|
|
282
|
+
"func",
|
|
283
|
+
"function",
|
|
284
|
+
"go",
|
|
285
|
+
"if",
|
|
286
|
+
"implements",
|
|
287
|
+
"import",
|
|
288
|
+
"in",
|
|
289
|
+
"instanceof",
|
|
290
|
+
"interface",
|
|
291
|
+
"is",
|
|
292
|
+
"lambda",
|
|
293
|
+
"let",
|
|
294
|
+
"match",
|
|
295
|
+
"mut",
|
|
296
|
+
"namespace",
|
|
297
|
+
"new",
|
|
298
|
+
"nil",
|
|
299
|
+
"none",
|
|
300
|
+
"not",
|
|
301
|
+
"null",
|
|
302
|
+
"of",
|
|
303
|
+
"or",
|
|
304
|
+
"override",
|
|
305
|
+
"package",
|
|
306
|
+
"pass",
|
|
307
|
+
"private",
|
|
308
|
+
"protected",
|
|
309
|
+
"pub",
|
|
310
|
+
"public",
|
|
311
|
+
"raise",
|
|
312
|
+
"readonly",
|
|
313
|
+
"return",
|
|
314
|
+
"select",
|
|
315
|
+
"self",
|
|
316
|
+
"static",
|
|
317
|
+
"struct",
|
|
318
|
+
"super",
|
|
319
|
+
"switch",
|
|
320
|
+
"this",
|
|
321
|
+
"throw",
|
|
322
|
+
"true",
|
|
323
|
+
"try",
|
|
324
|
+
"type",
|
|
325
|
+
"typeof",
|
|
326
|
+
"undefined",
|
|
327
|
+
"unless",
|
|
328
|
+
"until",
|
|
329
|
+
"use",
|
|
330
|
+
"using",
|
|
331
|
+
"var",
|
|
332
|
+
"void",
|
|
333
|
+
"when",
|
|
334
|
+
"while",
|
|
335
|
+
"with",
|
|
336
|
+
"yield",
|
|
337
|
+
]);
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Compact per-line token encoding: fixed tokens are prefixed with `=` and
|
|
341
|
+
* non-keyword identifiers are prefixed with `~` so window alpha-renaming avoids
|
|
342
|
+
* per-token object allocations.
|
|
343
|
+
*/
|
|
344
|
+
function tokenizeStructuralLine(line: string, syntax: "c" | "hash"): string[] {
|
|
345
|
+
const tokens: string[] = [];
|
|
346
|
+
let i = 0;
|
|
347
|
+
while (i < line.length) {
|
|
348
|
+
const ch = line[i]!;
|
|
349
|
+
if (ch <= " ") {
|
|
350
|
+
i++;
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
if (ch === '"' || ch === "'" || (syntax === "c" && ch === "`")) {
|
|
354
|
+
const quote = ch;
|
|
355
|
+
i++;
|
|
356
|
+
while (i < line.length) {
|
|
357
|
+
const cur = line[i]!;
|
|
358
|
+
if (cur === "\\") i += 2;
|
|
359
|
+
else if (cur === quote) {
|
|
360
|
+
i++;
|
|
361
|
+
break;
|
|
362
|
+
} else {
|
|
363
|
+
i++;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
tokens.push("=$S");
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
369
|
+
if (ch >= "0" && ch <= "9") {
|
|
370
|
+
i++;
|
|
371
|
+
while (i < line.length && /[0-9A-Fa-fxXbBoO_.]/.test(line[i]!)) i++;
|
|
372
|
+
tokens.push("=$N");
|
|
373
|
+
continue;
|
|
374
|
+
}
|
|
375
|
+
if (/[A-Za-z_$]/.test(ch)) {
|
|
376
|
+
const start = i;
|
|
377
|
+
i++;
|
|
378
|
+
while (i < line.length && /[\w$]/.test(line[i]!)) i++;
|
|
379
|
+
const word = line.slice(start, i);
|
|
380
|
+
tokens.push(PRESERVED_KEYWORDS.has(word) ? `=${word}` : `~${word}`);
|
|
381
|
+
continue;
|
|
382
|
+
}
|
|
383
|
+
const three = line.slice(i, i + 3);
|
|
384
|
+
if (three === "===" || three === "!==" || three === "..." || three === ">>>" || three === "**=") {
|
|
385
|
+
tokens.push(`=${three}`);
|
|
386
|
+
i += 3;
|
|
387
|
+
continue;
|
|
388
|
+
}
|
|
389
|
+
const two = line.slice(i, i + 2);
|
|
390
|
+
if (
|
|
391
|
+
two === "=>" ||
|
|
392
|
+
two === "==" ||
|
|
393
|
+
two === "!=" ||
|
|
394
|
+
two === "<=" ||
|
|
395
|
+
two === ">=" ||
|
|
396
|
+
two === "&&" ||
|
|
397
|
+
two === "||" ||
|
|
398
|
+
two === "??" ||
|
|
399
|
+
two === "?." ||
|
|
400
|
+
two === "+=" ||
|
|
401
|
+
two === "-=" ||
|
|
402
|
+
two === "*=" ||
|
|
403
|
+
two === "/=" ||
|
|
404
|
+
two === "::" ||
|
|
405
|
+
two === "->"
|
|
406
|
+
) {
|
|
407
|
+
tokens.push(`=${two}`);
|
|
408
|
+
i += 2;
|
|
409
|
+
continue;
|
|
410
|
+
}
|
|
411
|
+
tokens.push(`=${ch}`);
|
|
412
|
+
i++;
|
|
413
|
+
}
|
|
414
|
+
return tokens;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function windowFingerprint(tokenizedLines: string[][], start: number): { key: string; distinctLines: number; distinctIdents: number } {
|
|
418
|
+
const identMap = new Map<string, string>();
|
|
419
|
+
let nextId = 0;
|
|
420
|
+
const rendered: string[] = [];
|
|
421
|
+
const distinct = new Set<string>();
|
|
422
|
+
for (let offset = 0; offset < PARAMETRIC_WINDOW; offset++) {
|
|
423
|
+
const lineTokens = tokenizedLines[start + offset]!;
|
|
424
|
+
const parts: string[] = [];
|
|
425
|
+
for (const token of lineTokens) {
|
|
426
|
+
if (token.startsWith("=")) {
|
|
427
|
+
parts.push(token.slice(1));
|
|
428
|
+
} else {
|
|
429
|
+
const name = token.slice(1);
|
|
430
|
+
let mapped = identMap.get(name);
|
|
431
|
+
if (!mapped) {
|
|
432
|
+
mapped = `$${nextId++}`;
|
|
433
|
+
identMap.set(name, mapped);
|
|
434
|
+
}
|
|
435
|
+
parts.push(mapped);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
const lineText = parts.join(" ");
|
|
439
|
+
rendered.push(lineText);
|
|
440
|
+
distinct.add(lineText);
|
|
441
|
+
}
|
|
442
|
+
return { key: rendered.join("\n"), distinctLines: distinct.size, distinctIdents: identMap.size };
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function isTextuallyIdentical(
|
|
446
|
+
normA: NormalizedLine[],
|
|
447
|
+
startA: number,
|
|
448
|
+
endA: number,
|
|
449
|
+
normB: NormalizedLine[],
|
|
450
|
+
startB: number,
|
|
451
|
+
): boolean {
|
|
452
|
+
for (let offset = 0; offset <= endA - startA; offset++) {
|
|
453
|
+
if (normA[startA + offset]!.text !== normB[startB + offset]!.text) return false;
|
|
454
|
+
}
|
|
455
|
+
return true;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* Counts how many lines of `span` are not already covered by exact duplicate
|
|
460
|
+
* spans on the same file pair, so a long renamed clone containing a short
|
|
461
|
+
* identical sub-block is kept rather than dropped.
|
|
462
|
+
*/
|
|
463
|
+
function uncoveredLinesCount(span: DuplicateSpan, exactSpans: DuplicateSpan[] | undefined): number {
|
|
464
|
+
const total = span.normEndA - span.normStartA + 1;
|
|
465
|
+
if (!exactSpans || exactSpans.length === 0) return total;
|
|
466
|
+
let uncovered = 0;
|
|
467
|
+
for (let offset = 0; offset < total; offset++) {
|
|
468
|
+
const posA = span.normStartA + offset;
|
|
469
|
+
const posB = span.normStartB + offset;
|
|
470
|
+
const covered = exactSpans.some(
|
|
471
|
+
kept => posA >= kept.normStartA && posA <= kept.normEndA && posB >= kept.normStartB && posB <= kept.normEndB,
|
|
472
|
+
);
|
|
473
|
+
if (!covered) uncovered++;
|
|
474
|
+
}
|
|
475
|
+
return uncovered;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* Finds structurally identical multi-line blocks whose identifiers or literals
|
|
480
|
+
* differ (alpha-renamed per window), skipping spans already covered by exact
|
|
481
|
+
* `duplicate-block` matches on the same file pair.
|
|
482
|
+
*/
|
|
483
|
+
export function findParametricClones(
|
|
484
|
+
sources: ScannedSource[],
|
|
485
|
+
normalizedByFile: NormalizedLine[][],
|
|
486
|
+
exactSpans: DuplicateSpan[],
|
|
487
|
+
): { perFile: Map<number, FileDuplicateSummary>; clusters: DuplicateCluster[] } {
|
|
488
|
+
const exactByPair = new Map<string, DuplicateSpan[]>();
|
|
489
|
+
for (const span of exactSpans) {
|
|
490
|
+
const key = `${span.fileA}:${span.fileB}`;
|
|
491
|
+
const list = exactByPair.get(key);
|
|
492
|
+
if (list) list.push(span);
|
|
493
|
+
else exactByPair.set(key, [span]);
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
const tokenizedByFile = sources.map((source, fileIndex) =>
|
|
497
|
+
normalizedByFile[fileIndex]!.map(entry => tokenizeStructuralLine(entry.text, source.syntax)),
|
|
498
|
+
);
|
|
499
|
+
|
|
500
|
+
const buckets = new Map<string, CloneOccurrence[] | null>();
|
|
501
|
+
for (let fileIndex = 0; fileIndex < normalizedByFile.length; fileIndex++) {
|
|
502
|
+
const lines = normalizedByFile[fileIndex]!;
|
|
503
|
+
const tokenized = tokenizedByFile[fileIndex]!;
|
|
504
|
+
for (let normIndex = 0; normIndex + PARAMETRIC_WINDOW <= lines.length; normIndex++) {
|
|
505
|
+
let chars = 0;
|
|
506
|
+
for (let offset = 0; offset < PARAMETRIC_WINDOW; offset++) {
|
|
507
|
+
chars += lines[normIndex + offset]!.text.length;
|
|
508
|
+
}
|
|
509
|
+
if (chars < PARAMETRIC_MIN_CHARS) continue;
|
|
510
|
+
const { key, distinctLines, distinctIdents } = windowFingerprint(tokenized, normIndex);
|
|
511
|
+
if (distinctLines < 3 || distinctIdents < 2) continue;
|
|
512
|
+
const existing = buckets.get(key);
|
|
513
|
+
if (existing === null) continue;
|
|
514
|
+
if (!existing) {
|
|
515
|
+
buckets.set(key, [{ fileIndex, normIndex }]);
|
|
516
|
+
} else if (existing.length >= PARAMETRIC_MAX_OCCURRENCES) {
|
|
517
|
+
buckets.set(key, null);
|
|
518
|
+
} else {
|
|
519
|
+
existing.push({ fileIndex, normIndex });
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
const { perFile, clusters } = collectAndSummarizeClones(
|
|
525
|
+
sources,
|
|
526
|
+
normalizedByFile,
|
|
527
|
+
buckets,
|
|
528
|
+
PARAMETRIC_WINDOW,
|
|
529
|
+
span => {
|
|
530
|
+
const normA = normalizedByFile[span.fileA]!;
|
|
531
|
+
const normB = normalizedByFile[span.fileB]!;
|
|
532
|
+
if (isTextuallyIdentical(normA, span.normStartA, span.normEndA, normB, span.normStartB)) return true;
|
|
533
|
+
const exact = exactByPair.get(`${span.fileA}:${span.fileB}`);
|
|
534
|
+
return uncoveredLinesCount(span, exact) < PARAMETRIC_WINDOW;
|
|
535
|
+
},
|
|
536
|
+
);
|
|
537
|
+
return { perFile, clusters };
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
const JS_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
|
|
541
|
+
const RELATIVE_IMPORT_SPECIFIER = /(?:(?:from|import)\s*\(?|require\s*\()\s*["'](\.[^"']+)["']/g;
|
|
542
|
+
const EXEMPT_MICRO_BASENAME = /^(?:index|main|cli|mod|lib|types|constants)\.[^.]+$|\.types\.[^.]+$/i;
|
|
543
|
+
const REEXPORT_LINE = /^export\s+(?:type\s+)?(?:\*(?:\s+as\s+[A-Za-z_$][\w$]*)?|\{[^}]*\})\s+from\s+["'][^"']+["']\s*;?$/;
|
|
544
|
+
|
|
545
|
+
function isJsModulePath(file: string): boolean {
|
|
546
|
+
const lower = file.toLowerCase();
|
|
547
|
+
return JS_EXTENSIONS.some(ext => lower.endsWith(ext));
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
function resolveRelativeTarget(fromFile: string, specifier: string, knownFiles: ReadonlySet<string>): string | undefined {
|
|
551
|
+
const baseDir = path.posix.dirname(fromFile);
|
|
552
|
+
const raw = path.posix.normalize(path.posix.join(baseDir, specifier));
|
|
553
|
+
if (knownFiles.has(raw)) return raw;
|
|
554
|
+
const withoutJs = raw.replace(/\.(?:[cm]?js|jsx)$/i, "");
|
|
555
|
+
for (const ext of JS_EXTENSIONS) {
|
|
556
|
+
const candidate = `${withoutJs}${ext}`;
|
|
557
|
+
if (knownFiles.has(candidate)) return candidate;
|
|
558
|
+
}
|
|
559
|
+
for (const ext of JS_EXTENSIONS) {
|
|
560
|
+
const indexCandidate = path.posix.join(raw, `index${ext}`);
|
|
561
|
+
if (knownFiles.has(indexCandidate)) return indexCandidate;
|
|
562
|
+
}
|
|
563
|
+
return undefined;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
function isPureReexportShim(stripped: string[]): boolean {
|
|
567
|
+
const nonEmpty = stripped.map(line => line.trim()).filter(Boolean);
|
|
568
|
+
if (nonEmpty.length === 0 || nonEmpty.length > REEXPORT_SHIM_MAX_LINES) return false;
|
|
569
|
+
return nonEmpty.every(line => REEXPORT_LINE.test(line));
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* Flags over-fragmented production micro-files: tiny JS/TS modules (<= 35 code
|
|
574
|
+
* lines, excluding entrypoints/barrels/type files and tests) that have exactly
|
|
575
|
+
* one relative importer in the scanned JS/TS tree (excluding `index.*` barrels),
|
|
576
|
+
* or non-index pure re-export shims.
|
|
577
|
+
*/
|
|
578
|
+
export function findMicroFiles(
|
|
579
|
+
sources: ScannedSource[],
|
|
580
|
+
strippedByFile: string[][],
|
|
581
|
+
codeLineCounts: number[],
|
|
582
|
+
isTestPath: (file: string) => boolean,
|
|
583
|
+
): Map<number, MicroFileLead> {
|
|
584
|
+
const knownFiles = new Set(sources.map(source => source.path));
|
|
585
|
+
const prodImporters = new Map<string, Set<string>>();
|
|
586
|
+
|
|
587
|
+
for (let index = 0; index < sources.length; index++) {
|
|
588
|
+
const source = sources[index]!;
|
|
589
|
+
if (source.syntax !== "c" || isTestPath(source.path) || !isJsModulePath(source.path)) continue;
|
|
590
|
+
const stripped = strippedByFile[index]!;
|
|
591
|
+
const joined = stripped.join("\n");
|
|
592
|
+
RELATIVE_IMPORT_SPECIFIER.lastIndex = 0;
|
|
593
|
+
let match = RELATIVE_IMPORT_SPECIFIER.exec(joined);
|
|
594
|
+
while (match) {
|
|
595
|
+
const target = resolveRelativeTarget(source.path, match[1]!, knownFiles);
|
|
596
|
+
if (target && target !== source.path) {
|
|
597
|
+
const callers = prodImporters.get(target) ?? new Set<string>();
|
|
598
|
+
callers.add(source.path);
|
|
599
|
+
prodImporters.set(target, callers);
|
|
600
|
+
}
|
|
601
|
+
match = RELATIVE_IMPORT_SPECIFIER.exec(joined);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
const leads = new Map<number, MicroFileLead>();
|
|
606
|
+
for (let index = 0; index < sources.length; index++) {
|
|
607
|
+
const source = sources[index]!;
|
|
608
|
+
if (source.syntax !== "c" || isTestPath(source.path) || !isJsModulePath(source.path)) continue;
|
|
609
|
+
const base = path.posix.basename(source.path);
|
|
610
|
+
if (EXEMPT_MICRO_BASENAME.test(base)) continue;
|
|
611
|
+
const lines = codeLineCounts[index]!;
|
|
612
|
+
if (lines === 0 || lines > MICRO_FILE_MAX_LINES) continue;
|
|
613
|
+
|
|
614
|
+
if (isPureReexportShim(strippedByFile[index]!)) {
|
|
615
|
+
leads.set(index, { codeLines: lines, isReexportShim: true, detail: `${lines} lines, re-export shim` });
|
|
616
|
+
continue;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
const callers = prodImporters.get(source.path);
|
|
620
|
+
if (callers && callers.size === 1) {
|
|
621
|
+
const soleCaller = [...callers][0]!;
|
|
622
|
+
if (!/^index\.[^.]+$/i.test(path.posix.basename(soleCaller))) {
|
|
623
|
+
leads.set(index, { codeLines: lines, isReexportShim: false, detail: `${lines} lines, 1 relative importer (${soleCaller})` });
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
return leads;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* Rolls up per-file metrics and candidate signals by parent directory to expose
|
|
632
|
+
* duplication clusters, over-fragmented modules, and test-to-source ratios when
|
|
633
|
+
* tests are included in the scan.
|
|
634
|
+
*/
|
|
635
|
+
export function summarizeDirectories(
|
|
636
|
+
sources: ScannedSource[],
|
|
637
|
+
codeLineCounts: number[],
|
|
638
|
+
reports: DeslopFileReport[],
|
|
639
|
+
isTestPath: (file: string) => boolean,
|
|
640
|
+
includeTests: boolean,
|
|
641
|
+
): DeslopDirectoryReport[] {
|
|
642
|
+
const reportByPath = new Map(reports.map(report => [report.path, report]));
|
|
643
|
+
const buckets = new Map<
|
|
644
|
+
string,
|
|
645
|
+
{
|
|
646
|
+
sourceFiles: number;
|
|
647
|
+
sourceLines: number;
|
|
648
|
+
testFiles: number;
|
|
649
|
+
testLines: number;
|
|
650
|
+
candidateFiles: number;
|
|
651
|
+
duplicateLines: number;
|
|
652
|
+
parametricLines: number;
|
|
653
|
+
microFiles: number;
|
|
654
|
+
totalScore: number;
|
|
655
|
+
}
|
|
656
|
+
>();
|
|
657
|
+
|
|
658
|
+
for (let index = 0; index < sources.length; index++) {
|
|
659
|
+
const source = sources[index]!;
|
|
660
|
+
const dir = path.posix.dirname(source.path);
|
|
661
|
+
const lines = codeLineCounts[index]!;
|
|
662
|
+
const entry = buckets.get(dir) ?? {
|
|
663
|
+
sourceFiles: 0,
|
|
664
|
+
sourceLines: 0,
|
|
665
|
+
testFiles: 0,
|
|
666
|
+
testLines: 0,
|
|
667
|
+
candidateFiles: 0,
|
|
668
|
+
duplicateLines: 0,
|
|
669
|
+
parametricLines: 0,
|
|
670
|
+
microFiles: 0,
|
|
671
|
+
totalScore: 0,
|
|
672
|
+
};
|
|
673
|
+
|
|
674
|
+
if (isTestPath(source.path)) {
|
|
675
|
+
entry.testFiles++;
|
|
676
|
+
entry.testLines += lines;
|
|
677
|
+
} else {
|
|
678
|
+
entry.sourceFiles++;
|
|
679
|
+
entry.sourceLines += lines;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
const report = reportByPath.get(source.path);
|
|
683
|
+
if (report) {
|
|
684
|
+
entry.candidateFiles++;
|
|
685
|
+
entry.totalScore += report.score;
|
|
686
|
+
for (const signal of report.signals) {
|
|
687
|
+
if (signal.kind === "duplicate-block") entry.duplicateLines += signal.count;
|
|
688
|
+
else if (signal.kind === "parametric-clone") entry.parametricLines += signal.count;
|
|
689
|
+
else if (signal.kind === "micro-file") entry.microFiles++;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
buckets.set(dir, entry);
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
const summaries: DeslopDirectoryReport[] = [];
|
|
696
|
+
for (const [directory, entry] of buckets) {
|
|
697
|
+
if (entry.candidateFiles === 0 && entry.testLines < 200) continue;
|
|
698
|
+
const testRatio = includeTests && entry.sourceLines > 0
|
|
699
|
+
? Math.round((entry.testLines / entry.sourceLines) * 100) / 100
|
|
700
|
+
: null;
|
|
701
|
+
summaries.push({ directory, ...entry, testRatio });
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
summaries.sort(
|
|
705
|
+
(a, b) =>
|
|
706
|
+
b.totalScore - a.totalScore ||
|
|
707
|
+
b.duplicateLines + b.parametricLines - (a.duplicateLines + a.parametricLines) ||
|
|
708
|
+
b.testLines + b.sourceLines - (a.testLines + a.sourceLines) ||
|
|
709
|
+
a.directory.localeCompare(b.directory),
|
|
710
|
+
);
|
|
711
|
+
return summaries;
|
|
712
|
+
}
|