@a2f0/agent-tool 0.1.83 → 0.1.85
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 +213 -0
- package/skills/deslopify-refactor/agents/openai.yaml +4 -0
- package/skills/deslopify-refactor/references/lessons.md +73 -0
- package/skills/deslopify-refactor/references/pathology-catalog.md +105 -0
- package/src/cli.ts +4 -0
- package/src/deslop/command.ts +287 -0
- package/src/deslop/scan.ts +731 -0
- package/src/deslop/structural.ts +712 -0
- package/src/permissions/catalog.ts +1 -1
- package/src/skills/bundled.ts +6 -0
|
@@ -0,0 +1,731 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read-only structural leads for `agent-tool deslop`: duplicated code blocks,
|
|
3
|
+
* oversized files, long functions, lint/type suppression clusters, and exported
|
|
4
|
+
* thin-wrapper cascades. Pure and linear-time per file; it ranks files for a
|
|
5
|
+
* person or agent to inspect and never edits anything.
|
|
6
|
+
*/
|
|
7
|
+
import { codeLines, MAX_BYTES } from "../stateMachines/scan";
|
|
8
|
+
import {
|
|
9
|
+
type CloneOccurrence,
|
|
10
|
+
collectAndSummarizeClones,
|
|
11
|
+
type DeslopDirectoryReport,
|
|
12
|
+
type DeslopFileReport,
|
|
13
|
+
type DeslopSignal,
|
|
14
|
+
type DeslopSignalKind,
|
|
15
|
+
type DuplicateCluster,
|
|
16
|
+
type DuplicateLocation,
|
|
17
|
+
type DuplicateSpan,
|
|
18
|
+
type FileDuplicateSummary,
|
|
19
|
+
findMicroFiles,
|
|
20
|
+
findParametricClones,
|
|
21
|
+
type NormalizedLine,
|
|
22
|
+
PARAMETRIC_WINDOW,
|
|
23
|
+
type ScannedSource,
|
|
24
|
+
summarizeDirectories,
|
|
25
|
+
} from "./structural";
|
|
26
|
+
|
|
27
|
+
export {
|
|
28
|
+
MAX_BYTES,
|
|
29
|
+
type DeslopDirectoryReport,
|
|
30
|
+
type DeslopFileReport,
|
|
31
|
+
type DeslopSignal,
|
|
32
|
+
type DeslopSignalKind,
|
|
33
|
+
type DuplicateCluster,
|
|
34
|
+
type DuplicateLocation,
|
|
35
|
+
type ScannedSource,
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const LANGUAGES: Record<string, "c" | "hash"> = {
|
|
39
|
+
".ts": "c",
|
|
40
|
+
".tsx": "c",
|
|
41
|
+
".mts": "c",
|
|
42
|
+
".cts": "c",
|
|
43
|
+
".js": "c",
|
|
44
|
+
".jsx": "c",
|
|
45
|
+
".mjs": "c",
|
|
46
|
+
".cjs": "c",
|
|
47
|
+
".swift": "c",
|
|
48
|
+
".kt": "c",
|
|
49
|
+
".kts": "c",
|
|
50
|
+
".go": "c",
|
|
51
|
+
".rs": "c",
|
|
52
|
+
".java": "c",
|
|
53
|
+
".dart": "c",
|
|
54
|
+
".py": "hash",
|
|
55
|
+
".rb": "hash",
|
|
56
|
+
".sh": "hash",
|
|
57
|
+
".bash": "hash",
|
|
58
|
+
".zsh": "hash",
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const INTERPRETER = /^(?:sh|bash|zsh|dash|ksh|python[\d.]*|ruby)$/;
|
|
62
|
+
|
|
63
|
+
const ALWAYS_SKIPPED = [
|
|
64
|
+
/(^|\/)(node_modules|vendor|dist|build|out|coverage|Pods|DerivedData|\.next|\.turbo|generated|__generated__)\//,
|
|
65
|
+
/(^|\/)\.(agents|claude|codex|opencode)\//,
|
|
66
|
+
/\.d\.[cm]?ts$/,
|
|
67
|
+
/\.min\.[a-z]+$/,
|
|
68
|
+
];
|
|
69
|
+
|
|
70
|
+
const TEST_SKIPPED = [
|
|
71
|
+
/(^|\/)(__tests__|__mocks__|e2e|fixtures?|test|tests)\//,
|
|
72
|
+
/\.(test|spec|stories|e2e)\.[a-z]+$/,
|
|
73
|
+
/\.(test|spec)(Utils|Helpers|-utils|-helpers)\.[a-z]+$/,
|
|
74
|
+
/_test\.(go|py)$/,
|
|
75
|
+
/(^|\/)(test_[^/]*|conftest)\.py$/,
|
|
76
|
+
/(Tests?|Spec)\.(swift|kt|java)$/,
|
|
77
|
+
];
|
|
78
|
+
|
|
79
|
+
const GENERATED_HEADER = /^(?:\/\/|\/\*|#)\s*(?:Generated by\b|Code generated\b|DO NOT EDIT\b|AUTO-?GENERATED\b|@generated\b)/i;
|
|
80
|
+
|
|
81
|
+
function readsShebang(firstLine: string): boolean {
|
|
82
|
+
if (!firstLine.startsWith("#!")) return false;
|
|
83
|
+
const tokens = firstLine.slice(2, 512).trim().split(/\s+/);
|
|
84
|
+
const base = (token: string | undefined) => token?.slice(token.lastIndexOf("/") + 1) ?? "";
|
|
85
|
+
let index = 0;
|
|
86
|
+
if (base(tokens[0]) === "env") {
|
|
87
|
+
index = 1;
|
|
88
|
+
while (index < tokens.length && (tokens[index]!.startsWith("-") || tokens[index]!.includes("="))) index++;
|
|
89
|
+
}
|
|
90
|
+
return INTERPRETER.test(base(tokens[index]));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Whether a repository-relative path is classified as a test or fixture file. */
|
|
94
|
+
export function isTestPath(file: string): boolean {
|
|
95
|
+
return TEST_SKIPPED.some(pattern => pattern.test(file));
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Comment syntax for a tracked source path. Test and fixture files are skipped
|
|
100
|
+
* unless `includeTests` is true. Extensionless files return `"maybe"` until
|
|
101
|
+
* their first line is checked for a supported shebang.
|
|
102
|
+
*/
|
|
103
|
+
export function sourceLanguage(file: string, firstLine?: string, includeTests = false): "c" | "hash" | "maybe" | undefined {
|
|
104
|
+
if (ALWAYS_SKIPPED.some(pattern => pattern.test(file))) return undefined;
|
|
105
|
+
if (!includeTests && isTestPath(file)) return undefined;
|
|
106
|
+
const base = file.slice(file.lastIndexOf("/") + 1);
|
|
107
|
+
const dot = base.lastIndexOf(".");
|
|
108
|
+
if (dot > 0) return LANGUAGES[base.slice(dot).toLowerCase()];
|
|
109
|
+
if (firstLine === undefined) return "maybe";
|
|
110
|
+
return readsShebang(firstLine) ? "hash" : undefined;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Whether the file's opening lines mark it as generated output. */
|
|
114
|
+
export function isGeneratedSource(text: string): boolean {
|
|
115
|
+
const head = text.split("\n", 3);
|
|
116
|
+
return head.some(line => GENERATED_HEADER.test(line.trimStart()));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const OVERSIZED_LOW = 500;
|
|
120
|
+
const OVERSIZED_MEDIUM = 800;
|
|
121
|
+
const OVERSIZED_HIGH = 1200;
|
|
122
|
+
const LONG_FUNCTION_MIN = 80;
|
|
123
|
+
const LONG_FUNCTION_HIGH = 120;
|
|
124
|
+
const SUPPRESSION_MIN = 3;
|
|
125
|
+
const THIN_WRAPPER_MIN = 2;
|
|
126
|
+
const MAX_DECLARATION_LINE = 1024;
|
|
127
|
+
const CLONE_WINDOW = 6;
|
|
128
|
+
const CLONE_MIN_CHARS = 180;
|
|
129
|
+
const CLONE_MAX_OCCURRENCES = 12;
|
|
130
|
+
|
|
131
|
+
const CONTROL_KEYWORDS = new Set([
|
|
132
|
+
"if",
|
|
133
|
+
"else",
|
|
134
|
+
"for",
|
|
135
|
+
"while",
|
|
136
|
+
"switch",
|
|
137
|
+
"catch",
|
|
138
|
+
"try",
|
|
139
|
+
"finally",
|
|
140
|
+
"do",
|
|
141
|
+
"return",
|
|
142
|
+
"new",
|
|
143
|
+
"class",
|
|
144
|
+
"interface",
|
|
145
|
+
"type",
|
|
146
|
+
"enum",
|
|
147
|
+
"struct",
|
|
148
|
+
"namespace",
|
|
149
|
+
"match",
|
|
150
|
+
"select",
|
|
151
|
+
"defer",
|
|
152
|
+
"go",
|
|
153
|
+
"case",
|
|
154
|
+
"default",
|
|
155
|
+
"when",
|
|
156
|
+
"with",
|
|
157
|
+
]);
|
|
158
|
+
|
|
159
|
+
const C_FUNC_DECLARATION = /^\s*(?:export\s+)?(?:default\s+)?(?:(?:public|private|protected|internal|fileprivate|open|static|override|suspend|async)\s+|pub(?:\([^()]*\))?\s+)*(?:function\*?|func|fun|fn)\s+([A-Za-z_$][\w$]*)\s*[<(]/;
|
|
160
|
+
const C_ARROW_PREFIX = /^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\b/;
|
|
161
|
+
const C_METHOD_PREFIX = /^(?:(?:public|private|protected|static|override|readonly|async)\s+)*([A-Za-z_$#][\w$]*)$/;
|
|
162
|
+
const HASH_DEF_DECLARATION = /^(\s*)(?:async\s+)?def\s+([A-Za-z_][\w?!]*)\b/;
|
|
163
|
+
|
|
164
|
+
interface FunctionSpan {
|
|
165
|
+
readonly name: string;
|
|
166
|
+
readonly start: number;
|
|
167
|
+
readonly length: number;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
interface LineDelimiters {
|
|
171
|
+
readonly open: number;
|
|
172
|
+
readonly close: number;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Scans braces on one comment-stripped line in linear time, ignoring strings. */
|
|
176
|
+
function scanLineBraces(line: string): LineDelimiters {
|
|
177
|
+
let open = 0;
|
|
178
|
+
let close = 0;
|
|
179
|
+
let quote: string | undefined;
|
|
180
|
+
for (let i = 0; i < line.length; i++) {
|
|
181
|
+
const ch = line[i]!;
|
|
182
|
+
if (quote) {
|
|
183
|
+
if (ch === "\\") i++;
|
|
184
|
+
else if (ch === quote) quote = undefined;
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
if (ch === '"' || ch === "'" || ch === "`") quote = ch;
|
|
188
|
+
else if (ch === "{") open++;
|
|
189
|
+
else if (ch === "}") close++;
|
|
190
|
+
}
|
|
191
|
+
return { open, close };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Matches a C-family function, arrow function, or method header in linear time
|
|
196
|
+
* (no nested quantifiers or backtracking on untrusted long lines).
|
|
197
|
+
*/
|
|
198
|
+
function matchCFunctionHeader(line: string): { name: string; paramScanStart: number; isArrow: boolean } | undefined {
|
|
199
|
+
if (line.length > MAX_DECLARATION_LINE) return undefined;
|
|
200
|
+
const trimmed = line.trim();
|
|
201
|
+
if (!trimmed || trimmed.endsWith(";")) return undefined;
|
|
202
|
+
|
|
203
|
+
const fn = C_FUNC_DECLARATION.exec(line);
|
|
204
|
+
if (fn) return { name: fn[1]!, paramScanStart: fn.index + fn[0].length - 1, isArrow: false };
|
|
205
|
+
|
|
206
|
+
const arrow = C_ARROW_PREFIX.exec(line);
|
|
207
|
+
if (arrow) {
|
|
208
|
+
const eq = line.indexOf("=", arrow.index + arrow[0].length);
|
|
209
|
+
const arrowAt = eq >= 0 ? line.indexOf("=>", eq + 1) : -1;
|
|
210
|
+
if (arrowAt >= 0 && trimmed.endsWith("{") && line.indexOf("{", arrowAt + 2) >= 0) {
|
|
211
|
+
return { name: arrow[1]!, paramScanStart: arrowAt + 2, isArrow: true };
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
if (trimmed.endsWith("{")) {
|
|
216
|
+
const openParen = trimmed.indexOf("(");
|
|
217
|
+
if (openParen > 0) {
|
|
218
|
+
const prefix = trimmed.slice(0, openParen).trim();
|
|
219
|
+
const method = C_METHOD_PREFIX.exec(prefix);
|
|
220
|
+
if (method && !CONTROL_KEYWORDS.has(method[1]!)) {
|
|
221
|
+
// Confirm the balanced closing `)` has no `;` or extra `{` before the trailing `{`.
|
|
222
|
+
let parenDepth = 0;
|
|
223
|
+
let closeParen = -1;
|
|
224
|
+
for (let i = openParen; i < trimmed.length; i++) {
|
|
225
|
+
const ch = trimmed[i]!;
|
|
226
|
+
if (ch === "(") parenDepth++;
|
|
227
|
+
else if (ch === ")") {
|
|
228
|
+
parenDepth--;
|
|
229
|
+
if (parenDepth === 0) {
|
|
230
|
+
closeParen = i;
|
|
231
|
+
break;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
if (closeParen > openParen) {
|
|
236
|
+
const between = trimmed.slice(closeParen + 1, -1);
|
|
237
|
+
if (!between.includes(";") && !between.includes("{")) {
|
|
238
|
+
return { name: method[1]!, paramScanStart: line.indexOf("("), isArrow: false };
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
return undefined;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
type HeaderState =
|
|
248
|
+
| { readonly status: "idle" }
|
|
249
|
+
| { readonly status: "awaiting-params"; readonly name: string; readonly start: number }
|
|
250
|
+
| { readonly status: "in-params"; readonly name: string; readonly start: number; readonly parenDepth: number }
|
|
251
|
+
| { readonly status: "awaiting-body"; readonly name: string; readonly start: number }
|
|
252
|
+
| { readonly status: "body-found"; readonly name: string; readonly start: number; readonly braceCol: number }
|
|
253
|
+
| { readonly status: "aborted" };
|
|
254
|
+
|
|
255
|
+
/** Pure single-character transition for locating a function header's body `{` past its parameter list. */
|
|
256
|
+
function stepHeaderChar(state: HeaderState, ch: string, col: number): HeaderState {
|
|
257
|
+
switch (state.status) {
|
|
258
|
+
case "awaiting-params":
|
|
259
|
+
return ch === "(" ? { status: "in-params", name: state.name, start: state.start, parenDepth: 1 } : state;
|
|
260
|
+
case "in-params":
|
|
261
|
+
if (ch === "(") return { ...state, parenDepth: state.parenDepth + 1 };
|
|
262
|
+
if (ch === ")") {
|
|
263
|
+
return state.parenDepth === 1
|
|
264
|
+
? { status: "awaiting-body", name: state.name, start: state.start }
|
|
265
|
+
: { ...state, parenDepth: state.parenDepth - 1 };
|
|
266
|
+
}
|
|
267
|
+
return state;
|
|
268
|
+
case "awaiting-body":
|
|
269
|
+
if (ch === "{") return { status: "body-found", name: state.name, start: state.start, braceCol: col };
|
|
270
|
+
if (ch === ";") return { status: "aborted" };
|
|
271
|
+
return state;
|
|
272
|
+
case "idle":
|
|
273
|
+
case "body-found":
|
|
274
|
+
case "aborted":
|
|
275
|
+
return state;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function advanceHeaderOnLine(initial: HeaderState, line: string, startCol: number): HeaderState {
|
|
280
|
+
let state = initial;
|
|
281
|
+
let quote: string | undefined;
|
|
282
|
+
for (let i = startCol; i < line.length; i++) {
|
|
283
|
+
const ch = line[i]!;
|
|
284
|
+
if (quote) {
|
|
285
|
+
if (ch === "\\") i++;
|
|
286
|
+
else if (ch === quote) quote = undefined;
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
if (ch === '"' || ch === "'" || ch === "`") {
|
|
290
|
+
quote = ch;
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
state = stepHeaderChar(state, ch, i);
|
|
294
|
+
if (state.status === "body-found" || state.status === "aborted") break;
|
|
295
|
+
}
|
|
296
|
+
return state;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Lightweight brace/indent tracker for functions spanning at least `LONG_FUNCTION_MIN`
|
|
301
|
+
* lines. Waits for the parameter list's closing `)` before treating `{` as the body,
|
|
302
|
+
* so multi-line object-typed or destructured parameters do not close early.
|
|
303
|
+
*/
|
|
304
|
+
function findLongFunctions(lines: string[], syntax: "c" | "hash"): FunctionSpan[] {
|
|
305
|
+
if (syntax === "hash") return findHashLongFunctions(lines);
|
|
306
|
+
const spans: FunctionSpan[] = [];
|
|
307
|
+
const stack: Array<{ name: string; start: number; depth: number }> = [];
|
|
308
|
+
let headerState: HeaderState = { status: "idle" };
|
|
309
|
+
let depth = 0;
|
|
310
|
+
|
|
311
|
+
for (let index = 0; index < lines.length; index++) {
|
|
312
|
+
const line = lines[index]!;
|
|
313
|
+
const at = index + 1;
|
|
314
|
+
const trimmed = line.trim();
|
|
315
|
+
if (!trimmed) continue;
|
|
316
|
+
|
|
317
|
+
let scanCol = 0;
|
|
318
|
+
if (headerState.status === "idle") {
|
|
319
|
+
const header = matchCFunctionHeader(line);
|
|
320
|
+
if (header) {
|
|
321
|
+
headerState = header.isArrow
|
|
322
|
+
? { status: "awaiting-body", name: header.name, start: at }
|
|
323
|
+
: { status: "awaiting-params", name: header.name, start: at };
|
|
324
|
+
scanCol = header.paramScanStart;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const { open, close } = scanLineBraces(line);
|
|
329
|
+
if (headerState.status !== "idle") {
|
|
330
|
+
headerState = advanceHeaderOnLine(headerState, line, scanCol);
|
|
331
|
+
if (headerState.status === "body-found") {
|
|
332
|
+
let bodyDepth = depth;
|
|
333
|
+
let quote: string | undefined;
|
|
334
|
+
for (let i = 0; i < headerState.braceCol; i++) {
|
|
335
|
+
const ch = line[i]!;
|
|
336
|
+
if (quote) {
|
|
337
|
+
if (ch === "\\") i++;
|
|
338
|
+
else if (ch === quote) quote = undefined;
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
if (ch === '"' || ch === "'" || ch === "`") quote = ch;
|
|
342
|
+
else if (ch === "{") bodyDepth++;
|
|
343
|
+
else if (ch === "}") bodyDepth = Math.max(0, bodyDepth - 1);
|
|
344
|
+
}
|
|
345
|
+
stack.push({ name: headerState.name, start: headerState.start, depth: bodyDepth });
|
|
346
|
+
headerState = { status: "idle" };
|
|
347
|
+
} else if (headerState.status === "aborted" || headerState.status === "idle" || at - headerState.start >= 25) {
|
|
348
|
+
headerState = { status: "idle" };
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
depth = Math.max(0, depth + open - close);
|
|
353
|
+
while (stack.length > 0 && depth <= stack.at(-1)!.depth) {
|
|
354
|
+
const finished = stack.pop()!;
|
|
355
|
+
const length = at - finished.start + 1;
|
|
356
|
+
if (length >= LONG_FUNCTION_MIN) spans.push({ name: finished.name, start: finished.start, length });
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
return spans.sort((a, b) => b.length - a.length || a.start - b.start);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** Counts net `(` / `)` outside quotes on one hash-language line. */
|
|
363
|
+
function parenDelta(line: string): number {
|
|
364
|
+
let delta = 0;
|
|
365
|
+
let quote: string | undefined;
|
|
366
|
+
for (let i = 0; i < line.length; i++) {
|
|
367
|
+
const ch = line[i]!;
|
|
368
|
+
if (quote) {
|
|
369
|
+
if (ch === "\\") i++;
|
|
370
|
+
else if (ch === quote) quote = undefined;
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
if (ch === '"' || ch === "'") quote = ch;
|
|
374
|
+
else if (ch === "(") delta++;
|
|
375
|
+
else if (ch === ")") delta--;
|
|
376
|
+
}
|
|
377
|
+
return delta;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Tracks nested Python/Ruby `def` blocks on an indentation stack so inner helpers
|
|
382
|
+
* do not truncate outer functions, and waits until multi-line `def (...) -> ...:`
|
|
383
|
+
* headers close before popping on indentation.
|
|
384
|
+
*/
|
|
385
|
+
function findHashLongFunctions(lines: string[]): FunctionSpan[] {
|
|
386
|
+
const spans: FunctionSpan[] = [];
|
|
387
|
+
const stack: Array<{ name: string; start: number; indent: number; lastCode: number; headerParenDepth: number }> = [];
|
|
388
|
+
|
|
389
|
+
const popToIndent = (indent: number) => {
|
|
390
|
+
while (stack.length > 0 && indent <= stack.at(-1)!.indent) {
|
|
391
|
+
const finished = stack.pop()!;
|
|
392
|
+
const length = finished.lastCode - finished.start + 1;
|
|
393
|
+
if (length >= LONG_FUNCTION_MIN) spans.push({ name: finished.name, start: finished.start, length });
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
|
|
397
|
+
for (let index = 0; index < lines.length; index++) {
|
|
398
|
+
const line = lines[index]!;
|
|
399
|
+
const at = index + 1;
|
|
400
|
+
if (!line.trim()) continue;
|
|
401
|
+
const indent = line.length - line.trimStart().length;
|
|
402
|
+
const top = stack.at(-1);
|
|
403
|
+
if (top && top.headerParenDepth > 0) {
|
|
404
|
+
top.headerParenDepth = Math.max(0, top.headerParenDepth + parenDelta(line));
|
|
405
|
+
for (const frame of stack) frame.lastCode = at;
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
popToIndent(indent);
|
|
409
|
+
for (const frame of stack) frame.lastCode = at;
|
|
410
|
+
const def = HASH_DEF_DECLARATION.exec(line);
|
|
411
|
+
if (def) {
|
|
412
|
+
const headerParenDepth = Math.max(0, parenDelta(line));
|
|
413
|
+
stack.push({ name: def[2]!, start: at, indent: def[1]!.length, lastCode: at, headerParenDepth });
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
popToIndent(-1);
|
|
417
|
+
return spans.sort((a, b) => b.length - a.length || a.start - b.start);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
const SUPPRESSION_COMMENT = /(?:\/\/|\/\*|#)\s*(?:biome-ignore\b|eslint-disable(?:-next-line|-line)?\b|@ts-(?:ignore|expect-error|nocheck)\b|noqa\b|type:\s*ignore\b|rubocop:disable\b|nolint\b|swiftlint:disable\b)/i;
|
|
421
|
+
const SUPPRESSION_ATTR = /^\s*(?:#\[allow\(|@Suppress(?:Warnings)?\()/;
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* Counts lint/type suppression directives in comments or attributes, ignoring
|
|
425
|
+
* string literals that merely mention suppression names (even after inline `/* ... *\/` comments).
|
|
426
|
+
*/
|
|
427
|
+
function findSuppressions(rawLines: string[], syntax: "c" | "hash"): number[] {
|
|
428
|
+
const hitLines: number[] = [];
|
|
429
|
+
for (let index = 0; index < rawLines.length; index++) {
|
|
430
|
+
const line = rawLines[index]!;
|
|
431
|
+
if (SUPPRESSION_ATTR.test(line)) {
|
|
432
|
+
hitLines.push(index + 1);
|
|
433
|
+
continue;
|
|
434
|
+
}
|
|
435
|
+
const segments = extractCommentSegments(line, syntax);
|
|
436
|
+
if (segments.some(segment => SUPPRESSION_COMMENT.test(segment))) hitLines.push(index + 1);
|
|
437
|
+
}
|
|
438
|
+
return hitLines;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function extractCommentSegments(line: string, syntax: "c" | "hash"): string[] {
|
|
442
|
+
const segments: string[] = [];
|
|
443
|
+
let quote: string | undefined;
|
|
444
|
+
let i = 0;
|
|
445
|
+
while (i < line.length) {
|
|
446
|
+
const ch = line[i]!;
|
|
447
|
+
if (quote) {
|
|
448
|
+
if (ch === "\\") i += 2;
|
|
449
|
+
else {
|
|
450
|
+
if (ch === quote) quote = undefined;
|
|
451
|
+
i++;
|
|
452
|
+
}
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
if (ch === '"' || ch === "'" || (syntax === "c" && ch === "`")) {
|
|
456
|
+
quote = ch;
|
|
457
|
+
i++;
|
|
458
|
+
} else if (syntax === "hash" && ch === "#") {
|
|
459
|
+
segments.push(line.slice(i));
|
|
460
|
+
break;
|
|
461
|
+
} else if (syntax === "c" && line.startsWith("//", i)) {
|
|
462
|
+
segments.push(line.slice(i));
|
|
463
|
+
break;
|
|
464
|
+
} else if (syntax === "c" && line.startsWith("/*", i)) {
|
|
465
|
+
const close = line.indexOf("*/", i + 2);
|
|
466
|
+
const end = close >= 0 ? close + 2 : line.length;
|
|
467
|
+
segments.push(line.slice(i, end));
|
|
468
|
+
i = end;
|
|
469
|
+
} else {
|
|
470
|
+
i++;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
return segments;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
const EXPORT_FUNC_WRAPPER = /^\s*export\s+(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*(?:<[^<>{}]*>)?\(([^()]*)\)(?:\s*:[^{;]+)?\s*\{\s*return\s+(?:await\s+)?([A-Za-z_$][\w$.]*)\(([^()]*)\)\s*;?\s*\}\s*$/;
|
|
477
|
+
const EXPORT_ARROW_HEAD = /^\s*export\s+const\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s+)?(?:<[^<>{}]*>\s*)?\(([^()]*)\)/;
|
|
478
|
+
const ARROW_FORWARD_BODY = /^(?:await\s+)?([A-Za-z_$][\w$.]*)\(([^()]*)\)\s*;?\s*$/;
|
|
479
|
+
|
|
480
|
+
function matchThinWrapper(line: string): { name: string; rawParams: string; target: string; rawArgs: string } | undefined {
|
|
481
|
+
const fn = EXPORT_FUNC_WRAPPER.exec(line);
|
|
482
|
+
if (fn) return { name: fn[1]!, rawParams: fn[2]!, target: fn[3]!, rawArgs: fn[4]! };
|
|
483
|
+
const arrow = EXPORT_ARROW_HEAD.exec(line);
|
|
484
|
+
if (!arrow) return undefined;
|
|
485
|
+
const afterParams = line.slice(arrow.index + arrow[0].length);
|
|
486
|
+
const arrowAt = afterParams.indexOf("=>");
|
|
487
|
+
if (arrowAt < 0) return undefined;
|
|
488
|
+
const returnType = afterParams.slice(0, arrowAt).trim();
|
|
489
|
+
if (returnType && (!returnType.startsWith(":") || returnType.includes(";") || returnType.includes("{"))) return undefined;
|
|
490
|
+
const body = ARROW_FORWARD_BODY.exec(afterParams.slice(arrowAt + 2).trim());
|
|
491
|
+
if (!body) return undefined;
|
|
492
|
+
return { name: arrow[1]!, rawParams: arrow[2]!, target: body[1]!, rawArgs: body[2]! };
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
function parseParamNames(raw: string): string[] | undefined {
|
|
496
|
+
const trimmed = raw.trim();
|
|
497
|
+
if (!trimmed) return [];
|
|
498
|
+
const names: string[] = [];
|
|
499
|
+
for (const part of trimmed.split(",")) {
|
|
500
|
+
const piece = part.trim();
|
|
501
|
+
if (!piece || piece.includes("=") || piece.startsWith("{") || piece.startsWith("[")) return undefined;
|
|
502
|
+
const match = /^(?:\.\.\.)?([A-Za-z_$][\w$]*)/.exec(piece);
|
|
503
|
+
if (!match) return undefined;
|
|
504
|
+
names.push(piece.startsWith("...") ? `...${match[1]!}` : match[1]!);
|
|
505
|
+
}
|
|
506
|
+
return names;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
function parseArgNames(raw: string): string[] | undefined {
|
|
510
|
+
const trimmed = raw.trim();
|
|
511
|
+
if (!trimmed) return [];
|
|
512
|
+
const args: string[] = [];
|
|
513
|
+
for (const part of trimmed.split(",")) {
|
|
514
|
+
const piece = part.trim();
|
|
515
|
+
if (!/^(?:\.\.\.)?[A-Za-z_$][\w$]*$/.test(piece)) return undefined;
|
|
516
|
+
args.push(piece);
|
|
517
|
+
}
|
|
518
|
+
return args;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function sameList(a: string[], b: string[]): boolean {
|
|
522
|
+
return a.length === b.length && a.every((item, index) => item === b[index]);
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/** Exported single-statement pass-through functions that forward their exact parameters in order. */
|
|
526
|
+
function findThinWrappers(lines: string[], syntax: "c" | "hash"): Array<{ name: string; line: number }> {
|
|
527
|
+
if (syntax !== "c") return [];
|
|
528
|
+
const found: Array<{ name: string; line: number }> = [];
|
|
529
|
+
for (let index = 0; index < lines.length; index++) {
|
|
530
|
+
const line = lines[index]!;
|
|
531
|
+
if (line.length > MAX_DECLARATION_LINE) continue;
|
|
532
|
+
const match = matchThinWrapper(line);
|
|
533
|
+
if (!match || match.name === match.target) continue;
|
|
534
|
+
const params = parseParamNames(match.rawParams);
|
|
535
|
+
const args = parseArgNames(match.rawArgs);
|
|
536
|
+
if (params && args && sameList(params, args)) found.push({ name: match.name, line: index + 1 });
|
|
537
|
+
}
|
|
538
|
+
return found;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
const SKIPPED_CLONE_LINE = /^(?:import\b|export\s+(?:type\s+)?\{|from\s+["']|package\s+|using\s+|use\s+|#include\b|[\s{}()[\];,]+$|else\s*\{?$|try\s*\{?$|finally\s*\{?$|break;?$|continue;?$)/;
|
|
542
|
+
const MULTILINE_IMPORT_START = /^(?:import|export)\s+(?:type\s+)?(?:\*\s+as\s+[A-Za-z_$][\w$]*\s+from|[A-Za-z_$][\w$]*\s*,\s*\{|\{)/;
|
|
543
|
+
const IMPORT_END_RE = /\bfrom\s+["'][^"']+["']\s*;?$|;\s*$/;
|
|
544
|
+
|
|
545
|
+
function normalizedCodeLines(stripped: string[]): NormalizedLine[] {
|
|
546
|
+
const result: NormalizedLine[] = [];
|
|
547
|
+
let inImportBlock = false;
|
|
548
|
+
for (let index = 0; index < stripped.length; index++) {
|
|
549
|
+
const collapsed = stripped[index]!.trim().replace(/\s+/g, " ");
|
|
550
|
+
if (!collapsed) continue;
|
|
551
|
+
if (inImportBlock) {
|
|
552
|
+
if (IMPORT_END_RE.test(collapsed) || collapsed.startsWith("}")) inImportBlock = false;
|
|
553
|
+
continue;
|
|
554
|
+
}
|
|
555
|
+
if (MULTILINE_IMPORT_START.test(collapsed) && !IMPORT_END_RE.test(collapsed) && !collapsed.includes("}")) {
|
|
556
|
+
inImportBlock = true;
|
|
557
|
+
continue;
|
|
558
|
+
}
|
|
559
|
+
if (SKIPPED_CLONE_LINE.test(collapsed)) continue;
|
|
560
|
+
result.push({ line: index + 1, text: collapsed });
|
|
561
|
+
}
|
|
562
|
+
return result;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* Finds contiguous duplicated normalized code blocks across and within files.
|
|
567
|
+
* Each distinct window hash is capped at `CLONE_MAX_OCCURRENCES` so boilerplate
|
|
568
|
+
* never triggers quadratic pair expansion, and overlapping shifted-diagonal
|
|
569
|
+
* sub-spans for the same file pair are filtered out, keeping the longest span.
|
|
570
|
+
*/
|
|
571
|
+
function findDuplicates(
|
|
572
|
+
sources: ScannedSource[],
|
|
573
|
+
normalizedByFile: NormalizedLine[][],
|
|
574
|
+
): { perFile: Map<number, FileDuplicateSummary>; clusters: DuplicateCluster[]; spans: DuplicateSpan[] } {
|
|
575
|
+
const buckets = new Map<string, CloneOccurrence[] | null>();
|
|
576
|
+
|
|
577
|
+
for (let fileIndex = 0; fileIndex < normalizedByFile.length; fileIndex++) {
|
|
578
|
+
const lines = normalizedByFile[fileIndex]!;
|
|
579
|
+
for (let normIndex = 0; normIndex + CLONE_WINDOW <= lines.length; normIndex++) {
|
|
580
|
+
let chars = 0;
|
|
581
|
+
const distinct = new Set<string>();
|
|
582
|
+
const slice: string[] = [];
|
|
583
|
+
for (let offset = 0; offset < CLONE_WINDOW; offset++) {
|
|
584
|
+
const text = lines[normIndex + offset]!.text;
|
|
585
|
+
chars += text.length;
|
|
586
|
+
distinct.add(text);
|
|
587
|
+
slice.push(text);
|
|
588
|
+
}
|
|
589
|
+
if (chars < CLONE_MIN_CHARS || distinct.size < 2) continue;
|
|
590
|
+
const key = slice.join("\n");
|
|
591
|
+
const existing = buckets.get(key);
|
|
592
|
+
if (existing === null) continue;
|
|
593
|
+
if (!existing) {
|
|
594
|
+
buckets.set(key, [{ fileIndex, normIndex }]);
|
|
595
|
+
} else if (existing.length >= CLONE_MAX_OCCURRENCES) {
|
|
596
|
+
buckets.set(key, null);
|
|
597
|
+
} else {
|
|
598
|
+
existing.push({ fileIndex, normIndex });
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
return collectAndSummarizeClones(sources, normalizedByFile, buckets, CLONE_WINDOW);
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
function scoreSignals(signals: DeslopSignal[], longFunctionMax: number, microIsReexportShim: boolean): number {
|
|
607
|
+
let total = 0;
|
|
608
|
+
for (const signal of signals) {
|
|
609
|
+
switch (signal.kind) {
|
|
610
|
+
case "duplicate-block":
|
|
611
|
+
total += Math.min(8, Math.floor(signal.count / 4) + 2);
|
|
612
|
+
break;
|
|
613
|
+
case "parametric-clone":
|
|
614
|
+
total += Math.min(7, Math.floor(signal.count / 6) + 2);
|
|
615
|
+
break;
|
|
616
|
+
case "oversized-file":
|
|
617
|
+
total += signal.count >= OVERSIZED_HIGH ? 7 : signal.count >= OVERSIZED_MEDIUM ? 5 : 3;
|
|
618
|
+
break;
|
|
619
|
+
case "long-function":
|
|
620
|
+
total += Math.min(8, 2 * signal.count + (signal.count === 1 && longFunctionMax >= LONG_FUNCTION_HIGH ? 1 : 0));
|
|
621
|
+
break;
|
|
622
|
+
case "suppressions":
|
|
623
|
+
total += Math.min(6, signal.count);
|
|
624
|
+
break;
|
|
625
|
+
case "thin-wrapper":
|
|
626
|
+
total += Math.min(6, 2 * signal.count - 1);
|
|
627
|
+
break;
|
|
628
|
+
case "micro-file":
|
|
629
|
+
total += microIsReexportShim ? 3 : 2;
|
|
630
|
+
break;
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
return total;
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/** Scans a set of tracked source files and returns ranked file leads, duplicate spans, and directory hotspots. */
|
|
637
|
+
export function scanSources(sources: ScannedSource[], minScore = 3, includeTests?: boolean): {
|
|
638
|
+
files: DeslopFileReport[];
|
|
639
|
+
duplicates: DuplicateCluster[];
|
|
640
|
+
parametricDuplicates: DuplicateCluster[];
|
|
641
|
+
directories: DeslopDirectoryReport[];
|
|
642
|
+
} {
|
|
643
|
+
const hasTests = includeTests ?? sources.some(source => isTestPath(source.path));
|
|
644
|
+
const strippedByFile = sources.map(source => codeLines(source.text, source.syntax));
|
|
645
|
+
const codeLineCounts = strippedByFile.map(stripped => stripped.filter(line => line.trim().length > 0).length);
|
|
646
|
+
const normalizedByFile = strippedByFile.map(normalizedCodeLines);
|
|
647
|
+
const { perFile, clusters, spans: exactSpans } = findDuplicates(sources, normalizedByFile);
|
|
648
|
+
const { perFile: parametricPerFile, clusters: parametricClusters } = findParametricClones(
|
|
649
|
+
sources,
|
|
650
|
+
normalizedByFile,
|
|
651
|
+
exactSpans,
|
|
652
|
+
);
|
|
653
|
+
const microFiles = findMicroFiles(sources, strippedByFile, codeLineCounts, isTestPath);
|
|
654
|
+
|
|
655
|
+
const files: DeslopFileReport[] = [];
|
|
656
|
+
for (let index = 0; index < sources.length; index++) {
|
|
657
|
+
const source = sources[index]!;
|
|
658
|
+
const rawLines = source.text.split("\n");
|
|
659
|
+
const stripped = strippedByFile[index]!;
|
|
660
|
+
const signals: DeslopSignal[] = [];
|
|
661
|
+
|
|
662
|
+
const dup = perFile.get(index);
|
|
663
|
+
if (dup && dup.duplicatedLines >= CLONE_WINDOW) {
|
|
664
|
+
signals.push({
|
|
665
|
+
kind: "duplicate-block",
|
|
666
|
+
count: dup.duplicatedLines,
|
|
667
|
+
lines: dup.startLines,
|
|
668
|
+
details: dup.peers,
|
|
669
|
+
});
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
const parametric = parametricPerFile.get(index);
|
|
673
|
+
if (parametric && parametric.duplicatedLines >= PARAMETRIC_WINDOW) {
|
|
674
|
+
signals.push({
|
|
675
|
+
kind: "parametric-clone",
|
|
676
|
+
count: parametric.duplicatedLines,
|
|
677
|
+
lines: parametric.startLines,
|
|
678
|
+
details: parametric.peers,
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
const nonBlankCode = codeLineCounts[index]!;
|
|
683
|
+
if (nonBlankCode >= OVERSIZED_LOW) {
|
|
684
|
+
signals.push({ kind: "oversized-file", count: nonBlankCode, lines: [1] });
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
const longFns = findLongFunctions(stripped, source.syntax);
|
|
688
|
+
const maxLongFn = longFns[0]?.length ?? 0;
|
|
689
|
+
if (longFns.length > 0) {
|
|
690
|
+
signals.push({
|
|
691
|
+
kind: "long-function",
|
|
692
|
+
count: longFns.length,
|
|
693
|
+
lines: longFns.map(fn => fn.start),
|
|
694
|
+
details: longFns.slice(0, 5).map(fn => `${fn.name} (${fn.length} lines)`),
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
const suppressions = findSuppressions(rawLines, source.syntax);
|
|
699
|
+
if (suppressions.length >= SUPPRESSION_MIN) {
|
|
700
|
+
signals.push({ kind: "suppressions", count: suppressions.length, lines: suppressions });
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
const wrappers = findThinWrappers(stripped, source.syntax);
|
|
704
|
+
if (wrappers.length >= THIN_WRAPPER_MIN) {
|
|
705
|
+
signals.push({
|
|
706
|
+
kind: "thin-wrapper",
|
|
707
|
+
count: wrappers.length,
|
|
708
|
+
lines: wrappers.map(wrapper => wrapper.line),
|
|
709
|
+
details: wrappers.slice(0, 6).map(wrapper => wrapper.name),
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
const micro = microFiles.get(index);
|
|
714
|
+
if (micro) {
|
|
715
|
+
signals.push({
|
|
716
|
+
kind: "micro-file",
|
|
717
|
+
count: micro.codeLines,
|
|
718
|
+
lines: [1],
|
|
719
|
+
details: [micro.detail],
|
|
720
|
+
});
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
if (signals.length === 0) continue;
|
|
724
|
+
const score = scoreSignals(signals, maxLongFn, micro?.isReexportShim ?? false);
|
|
725
|
+
if (score >= minScore) files.push({ path: source.path, score, signals });
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
files.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));
|
|
729
|
+
const directories = summarizeDirectories(sources, codeLineCounts, files, isTestPath, hasTests);
|
|
730
|
+
return { files, duplicates: clusters, parametricDuplicates: parametricClusters, directories };
|
|
731
|
+
}
|