@aiready/pattern-detect 0.14.21 → 0.16.0
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/chunk-EVBFDILL.mjs +927 -0
- package/dist/cli.js +2 -0
- package/dist/cli.mjs +1 -1
- package/dist/index.js +2 -0
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
|
@@ -0,0 +1,927 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { ToolRegistry, Severity as Severity5 } from "@aiready/core";
|
|
3
|
+
|
|
4
|
+
// src/provider.ts
|
|
5
|
+
import {
|
|
6
|
+
ToolName as ToolName2,
|
|
7
|
+
SpokeOutputSchema,
|
|
8
|
+
GLOBAL_SCAN_OPTIONS
|
|
9
|
+
} from "@aiready/core";
|
|
10
|
+
|
|
11
|
+
// src/analyzer.ts
|
|
12
|
+
import { scanFiles, readFileContent, Severity as Severity4, IssueType } from "@aiready/core";
|
|
13
|
+
|
|
14
|
+
// src/detector.ts
|
|
15
|
+
import { estimateTokens } from "@aiready/core";
|
|
16
|
+
|
|
17
|
+
// src/context-rules.ts
|
|
18
|
+
import { Severity } from "@aiready/core";
|
|
19
|
+
var CONTEXT_RULES = [
|
|
20
|
+
// Test Fixtures - Intentional duplication for test isolation
|
|
21
|
+
{
|
|
22
|
+
name: "test-fixtures",
|
|
23
|
+
detect: (file, code) => {
|
|
24
|
+
const isTestFile = file.includes(".test.") || file.includes(".spec.") || file.includes("__tests__") || file.includes("/test/") || file.includes("/tests/");
|
|
25
|
+
const hasTestFixtures = code.includes("beforeAll") || code.includes("afterAll") || code.includes("beforeEach") || code.includes("afterEach") || code.includes("setUp") || code.includes("tearDown");
|
|
26
|
+
return isTestFile && hasTestFixtures;
|
|
27
|
+
},
|
|
28
|
+
severity: Severity.Info,
|
|
29
|
+
reason: "Test fixture duplication is intentional for test isolation",
|
|
30
|
+
suggestion: "Consider if shared test setup would improve maintainability without coupling tests"
|
|
31
|
+
},
|
|
32
|
+
// Email/Document Templates - Often intentionally similar for consistency
|
|
33
|
+
{
|
|
34
|
+
name: "templates",
|
|
35
|
+
detect: (file, code) => {
|
|
36
|
+
const isTemplate = file.includes("/templates/") || file.includes("-template") || file.includes("/email-templates/") || file.includes("/emails/");
|
|
37
|
+
const hasTemplateContent = (code.includes("return") || code.includes("export")) && (code.includes("html") || code.includes("subject") || code.includes("body"));
|
|
38
|
+
return isTemplate && hasTemplateContent;
|
|
39
|
+
},
|
|
40
|
+
severity: Severity.Minor,
|
|
41
|
+
reason: "Template duplication may be intentional for maintainability and branding consistency",
|
|
42
|
+
suggestion: "Extract shared structure only if templates become hard to maintain"
|
|
43
|
+
},
|
|
44
|
+
// E2E/Integration Test Page Objects - Test independence
|
|
45
|
+
{
|
|
46
|
+
name: "e2e-page-objects",
|
|
47
|
+
detect: (file, code) => {
|
|
48
|
+
const isE2ETest = file.includes("e2e/") || file.includes("/e2e/") || file.includes(".e2e.") || file.includes("/playwright/") || file.includes("playwright/") || file.includes("/cypress/") || file.includes("cypress/") || file.includes("/integration/") || file.includes("integration/");
|
|
49
|
+
const hasPageObjectPatterns = code.includes("page.") || code.includes("await page") || code.includes("locator") || code.includes("getBy") || code.includes("selector") || code.includes("click(") || code.includes("fill(");
|
|
50
|
+
return isE2ETest && hasPageObjectPatterns;
|
|
51
|
+
},
|
|
52
|
+
severity: Severity.Minor,
|
|
53
|
+
reason: "E2E test duplication ensures test independence and reduces coupling",
|
|
54
|
+
suggestion: "Consider page object pattern only if duplication causes maintenance issues"
|
|
55
|
+
},
|
|
56
|
+
// Configuration Files - Often necessarily similar by design
|
|
57
|
+
{
|
|
58
|
+
name: "config-files",
|
|
59
|
+
detect: (file) => {
|
|
60
|
+
return file.endsWith(".config.ts") || file.endsWith(".config.js") || file.includes("jest.config") || file.includes("vite.config") || file.includes("webpack.config") || file.includes("rollup.config") || file.includes("tsconfig");
|
|
61
|
+
},
|
|
62
|
+
severity: Severity.Minor,
|
|
63
|
+
reason: "Configuration files often have similar structure by design",
|
|
64
|
+
suggestion: "Consider shared config base only if configurations become hard to maintain"
|
|
65
|
+
},
|
|
66
|
+
// Type Definitions - Duplication for type safety and module independence
|
|
67
|
+
{
|
|
68
|
+
name: "type-definitions",
|
|
69
|
+
detect: (file, code) => {
|
|
70
|
+
const isTypeFile = file.endsWith(".d.ts") || file.includes("/types/");
|
|
71
|
+
const hasTypeDefinitions = code.includes("interface ") || code.includes("type ") || code.includes("enum ");
|
|
72
|
+
return isTypeFile && hasTypeDefinitions;
|
|
73
|
+
},
|
|
74
|
+
severity: Severity.Info,
|
|
75
|
+
reason: "Type duplication may be intentional for module independence and type safety",
|
|
76
|
+
suggestion: "Extract to shared types package only if causing maintenance burden"
|
|
77
|
+
},
|
|
78
|
+
// Migration Scripts - One-off scripts that are similar by nature
|
|
79
|
+
{
|
|
80
|
+
name: "migration-scripts",
|
|
81
|
+
detect: (file) => {
|
|
82
|
+
return file.includes("/migrations/") || file.includes("/migrate/") || file.includes(".migration.");
|
|
83
|
+
},
|
|
84
|
+
severity: Severity.Info,
|
|
85
|
+
reason: "Migration scripts are typically one-off and intentionally similar",
|
|
86
|
+
suggestion: "Duplication is acceptable for migration scripts"
|
|
87
|
+
},
|
|
88
|
+
// Mock Data - Test data intentionally duplicated
|
|
89
|
+
{
|
|
90
|
+
name: "mock-data",
|
|
91
|
+
detect: (file, code) => {
|
|
92
|
+
const isMockFile = file.includes("/mocks/") || file.includes("/__mocks__/") || file.includes("/fixtures/") || file.includes(".mock.") || file.includes(".fixture.");
|
|
93
|
+
const hasMockData = code.includes("mock") || code.includes("Mock") || code.includes("fixture") || code.includes("stub") || code.includes("export const");
|
|
94
|
+
return isMockFile && hasMockData;
|
|
95
|
+
},
|
|
96
|
+
severity: Severity.Info,
|
|
97
|
+
reason: "Mock data duplication is expected for comprehensive test coverage",
|
|
98
|
+
suggestion: "Consider shared factories only for complex mock generation"
|
|
99
|
+
}
|
|
100
|
+
];
|
|
101
|
+
function calculateSeverity(file1, file2, code, similarity, linesOfCode) {
|
|
102
|
+
for (const rule of CONTEXT_RULES) {
|
|
103
|
+
if (rule.detect(file1, code) || rule.detect(file2, code)) {
|
|
104
|
+
return {
|
|
105
|
+
severity: rule.severity,
|
|
106
|
+
reason: rule.reason,
|
|
107
|
+
suggestion: rule.suggestion,
|
|
108
|
+
matchedRule: rule.name
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (similarity >= 0.95 && linesOfCode >= 30) {
|
|
113
|
+
return {
|
|
114
|
+
severity: Severity.Critical,
|
|
115
|
+
reason: "Large nearly-identical code blocks waste tokens and create maintenance burden",
|
|
116
|
+
suggestion: "Extract to shared utility module immediately"
|
|
117
|
+
};
|
|
118
|
+
} else if (similarity >= 0.95 && linesOfCode >= 15) {
|
|
119
|
+
return {
|
|
120
|
+
severity: Severity.Major,
|
|
121
|
+
reason: "Nearly identical code should be consolidated",
|
|
122
|
+
suggestion: "Move to shared utility file"
|
|
123
|
+
};
|
|
124
|
+
} else if (similarity >= 0.85) {
|
|
125
|
+
return {
|
|
126
|
+
severity: Severity.Major,
|
|
127
|
+
reason: "High similarity indicates significant duplication",
|
|
128
|
+
suggestion: "Extract common logic to shared function"
|
|
129
|
+
};
|
|
130
|
+
} else if (similarity >= 0.7) {
|
|
131
|
+
return {
|
|
132
|
+
severity: Severity.Minor,
|
|
133
|
+
reason: "Moderate similarity detected",
|
|
134
|
+
suggestion: "Consider extracting shared patterns if code evolves together"
|
|
135
|
+
};
|
|
136
|
+
} else {
|
|
137
|
+
return {
|
|
138
|
+
severity: Severity.Minor,
|
|
139
|
+
reason: "Minor similarity detected",
|
|
140
|
+
suggestion: "Monitor but refactoring may not be worthwhile"
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
function getSeverityLabel(severity) {
|
|
145
|
+
const labels = {
|
|
146
|
+
[Severity.Critical]: "\u{1F534} CRITICAL",
|
|
147
|
+
[Severity.Major]: "\u{1F7E1} MAJOR",
|
|
148
|
+
[Severity.Minor]: "\u{1F535} MINOR",
|
|
149
|
+
[Severity.Info]: "\u2139\uFE0F INFO"
|
|
150
|
+
};
|
|
151
|
+
return labels[severity];
|
|
152
|
+
}
|
|
153
|
+
function filterBySeverity(duplicates, minSeverity) {
|
|
154
|
+
const severityOrder = [
|
|
155
|
+
Severity.Info,
|
|
156
|
+
Severity.Minor,
|
|
157
|
+
Severity.Major,
|
|
158
|
+
Severity.Critical
|
|
159
|
+
];
|
|
160
|
+
const minIndex = severityOrder.indexOf(minSeverity);
|
|
161
|
+
if (minIndex === -1) return duplicates;
|
|
162
|
+
return duplicates.filter((dup) => {
|
|
163
|
+
const dupIndex = severityOrder.indexOf(dup.severity);
|
|
164
|
+
return dupIndex >= minIndex;
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
function getSeverityThreshold(severity) {
|
|
168
|
+
const thresholds = {
|
|
169
|
+
[Severity.Critical]: 0.95,
|
|
170
|
+
[Severity.Major]: 0.85,
|
|
171
|
+
[Severity.Minor]: 0.5,
|
|
172
|
+
[Severity.Info]: 0
|
|
173
|
+
};
|
|
174
|
+
return thresholds[severity] || 0;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// src/detector.ts
|
|
178
|
+
function normalizeCode(code, isPython = false) {
|
|
179
|
+
let normalized = code;
|
|
180
|
+
if (isPython) {
|
|
181
|
+
normalized = normalized.replace(/#.*/g, "");
|
|
182
|
+
} else {
|
|
183
|
+
normalized = normalized.replace(/\/\/.*/g, "").replace(/\/\*[\s\S]*?\*\//g, "");
|
|
184
|
+
}
|
|
185
|
+
return normalized.replace(/['"`]/g, '"').replace(/\s+/g, " ").trim().toLowerCase();
|
|
186
|
+
}
|
|
187
|
+
function extractBlocks(file, content) {
|
|
188
|
+
const isPython = file.toLowerCase().endsWith(".py");
|
|
189
|
+
if (isPython) {
|
|
190
|
+
return extractBlocksPython(file, content);
|
|
191
|
+
}
|
|
192
|
+
const blocks = [];
|
|
193
|
+
const lines = content.split("\n");
|
|
194
|
+
const blockRegex = /^\s*(?:export\s+)?(?:async\s+)?(?:public\s+|private\s+|protected\s+|internal\s+|static\s+|readonly\s+|virtual\s+|abstract\s+|override\s+)*(function|class|interface|type|enum|record|struct|void|func|[a-zA-Z0-9_<>\[\]]+)\s+([a-zA-Z0-9_]+)(?:\s*\(|(?:\s+extends|\s+implements|\s+where)?\s*\{)|^\s*(?:export\s+)?const\s+([a-zA-Z0-9_]+)\s*=\s*[a-zA-Z0-9_.]+\.object\(|^\s*(app\.(?:get|post|put|delete|patch|use))\(/gm;
|
|
195
|
+
let match;
|
|
196
|
+
while ((match = blockRegex.exec(content)) !== null) {
|
|
197
|
+
const startLine = content.substring(0, match.index).split("\n").length;
|
|
198
|
+
let type;
|
|
199
|
+
let name;
|
|
200
|
+
if (match[1]) {
|
|
201
|
+
type = match[1];
|
|
202
|
+
name = match[2];
|
|
203
|
+
} else if (match[3]) {
|
|
204
|
+
type = "const";
|
|
205
|
+
name = match[3];
|
|
206
|
+
} else {
|
|
207
|
+
type = "handler";
|
|
208
|
+
name = match[4];
|
|
209
|
+
}
|
|
210
|
+
let endLine = -1;
|
|
211
|
+
let openBraces = 0;
|
|
212
|
+
let foundStart = false;
|
|
213
|
+
for (let i = match.index; i < content.length; i++) {
|
|
214
|
+
if (content[i] === "{") {
|
|
215
|
+
openBraces++;
|
|
216
|
+
foundStart = true;
|
|
217
|
+
} else if (content[i] === "}") {
|
|
218
|
+
openBraces--;
|
|
219
|
+
}
|
|
220
|
+
if (foundStart && openBraces === 0) {
|
|
221
|
+
endLine = content.substring(0, i + 1).split("\n").length;
|
|
222
|
+
break;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
if (endLine === -1) {
|
|
226
|
+
const remaining = content.slice(match.index);
|
|
227
|
+
const nextLineMatch = remaining.indexOf("\n");
|
|
228
|
+
if (nextLineMatch !== -1) {
|
|
229
|
+
endLine = startLine;
|
|
230
|
+
} else {
|
|
231
|
+
endLine = lines.length;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
endLine = Math.max(startLine, endLine);
|
|
235
|
+
const blockCode = lines.slice(startLine - 1, endLine).join("\n");
|
|
236
|
+
const tokens = estimateTokens(blockCode);
|
|
237
|
+
blocks.push({
|
|
238
|
+
file,
|
|
239
|
+
startLine,
|
|
240
|
+
endLine,
|
|
241
|
+
code: blockCode,
|
|
242
|
+
tokens,
|
|
243
|
+
patternType: inferPatternType(type, name)
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
return blocks;
|
|
247
|
+
}
|
|
248
|
+
function extractBlocksPython(file, content) {
|
|
249
|
+
const blocks = [];
|
|
250
|
+
const lines = content.split("\n");
|
|
251
|
+
const blockRegex = /^\s*(?:async\s+)?(def|class)\s+([a-zA-Z0-9_]+)/gm;
|
|
252
|
+
let match;
|
|
253
|
+
while ((match = blockRegex.exec(content)) !== null) {
|
|
254
|
+
const startLinePos = content.substring(0, match.index).split("\n").length;
|
|
255
|
+
const startLineIdx = startLinePos - 1;
|
|
256
|
+
const initialIndent = lines[startLineIdx].search(/\S/);
|
|
257
|
+
let endLineIdx = startLineIdx;
|
|
258
|
+
for (let i = startLineIdx + 1; i < lines.length; i++) {
|
|
259
|
+
const line = lines[i];
|
|
260
|
+
if (line.trim().length === 0) {
|
|
261
|
+
endLineIdx = i;
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
const currentIndent = line.search(/\S/);
|
|
265
|
+
if (currentIndent <= initialIndent) {
|
|
266
|
+
break;
|
|
267
|
+
}
|
|
268
|
+
endLineIdx = i;
|
|
269
|
+
}
|
|
270
|
+
while (endLineIdx > startLineIdx && lines[endLineIdx].trim().length === 0) {
|
|
271
|
+
endLineIdx--;
|
|
272
|
+
}
|
|
273
|
+
const blockCode = lines.slice(startLineIdx, endLineIdx + 1).join("\n");
|
|
274
|
+
const tokens = estimateTokens(blockCode);
|
|
275
|
+
blocks.push({
|
|
276
|
+
file,
|
|
277
|
+
startLine: startLinePos,
|
|
278
|
+
endLine: endLineIdx + 1,
|
|
279
|
+
code: blockCode,
|
|
280
|
+
tokens,
|
|
281
|
+
patternType: inferPatternType(match[1], match[2])
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
return blocks;
|
|
285
|
+
}
|
|
286
|
+
function inferPatternType(keyword, name) {
|
|
287
|
+
const n = name.toLowerCase();
|
|
288
|
+
if (keyword === "handler" || n.includes("handler") || n.includes("controller") || n.startsWith("app.")) {
|
|
289
|
+
return "api-handler";
|
|
290
|
+
}
|
|
291
|
+
if (n.includes("validate") || n.includes("schema")) return "validator";
|
|
292
|
+
if (n.includes("util") || n.includes("helper")) return "utility";
|
|
293
|
+
if (keyword === "class") return "class-method";
|
|
294
|
+
if (n.match(/^[A-Z]/)) return "component";
|
|
295
|
+
if (keyword === "function") return "function";
|
|
296
|
+
return "unknown";
|
|
297
|
+
}
|
|
298
|
+
function calculateSimilarity(a, b) {
|
|
299
|
+
if (a === b) return 1;
|
|
300
|
+
const tokensA = a.split(/[^a-zA-Z0-9]+/).filter((t) => t.length > 0);
|
|
301
|
+
const tokensB = b.split(/[^a-zA-Z0-9]+/).filter((t) => t.length > 0);
|
|
302
|
+
if (tokensA.length === 0 || tokensB.length === 0) return 0;
|
|
303
|
+
const setA = new Set(tokensA);
|
|
304
|
+
const setB = new Set(tokensB);
|
|
305
|
+
const intersection = new Set([...setA].filter((x) => setB.has(x)));
|
|
306
|
+
const union = /* @__PURE__ */ new Set([...setA, ...setB]);
|
|
307
|
+
return intersection.size / union.size;
|
|
308
|
+
}
|
|
309
|
+
async function detectDuplicatePatterns(fileContents, options) {
|
|
310
|
+
const { minSimilarity, minLines, streamResults, onProgress } = options;
|
|
311
|
+
const allBlocks = [];
|
|
312
|
+
for (const { file, content } of fileContents) {
|
|
313
|
+
const blocks = extractBlocks(file, content);
|
|
314
|
+
allBlocks.push(
|
|
315
|
+
...blocks.filter((b) => b.endLine - b.startLine + 1 >= minLines)
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
const duplicates = [];
|
|
319
|
+
const totalBlocks = allBlocks.length;
|
|
320
|
+
let comparisons = 0;
|
|
321
|
+
const totalComparisons = totalBlocks * (totalBlocks - 1) / 2;
|
|
322
|
+
if (onProgress) {
|
|
323
|
+
onProgress(
|
|
324
|
+
0,
|
|
325
|
+
totalComparisons,
|
|
326
|
+
`Starting duplicate detection on ${totalBlocks} blocks...`
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
for (let i = 0; i < allBlocks.length; i++) {
|
|
330
|
+
if (i % 50 === 0 && i > 0) {
|
|
331
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
332
|
+
if (onProgress) {
|
|
333
|
+
onProgress(
|
|
334
|
+
comparisons,
|
|
335
|
+
totalComparisons,
|
|
336
|
+
`Analyzing blocks (${i}/${totalBlocks})...`
|
|
337
|
+
);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
const b1 = allBlocks[i];
|
|
341
|
+
const isPython1 = b1.file.toLowerCase().endsWith(".py");
|
|
342
|
+
const norm1 = normalizeCode(b1.code, isPython1);
|
|
343
|
+
for (let j = i + 1; j < allBlocks.length; j++) {
|
|
344
|
+
comparisons++;
|
|
345
|
+
const b2 = allBlocks[j];
|
|
346
|
+
if (b1.file === b2.file) continue;
|
|
347
|
+
const isPython2 = b2.file.toLowerCase().endsWith(".py");
|
|
348
|
+
const norm2 = normalizeCode(b2.code, isPython2);
|
|
349
|
+
const sim = calculateSimilarity(norm1, norm2);
|
|
350
|
+
if (sim >= minSimilarity) {
|
|
351
|
+
const { severity, reason, suggestion, matchedRule } = calculateSeverity(
|
|
352
|
+
b1.file,
|
|
353
|
+
b2.file,
|
|
354
|
+
b1.code,
|
|
355
|
+
sim,
|
|
356
|
+
b1.endLine - b1.startLine + 1
|
|
357
|
+
);
|
|
358
|
+
const dup = {
|
|
359
|
+
file1: b1.file,
|
|
360
|
+
line1: b1.startLine,
|
|
361
|
+
endLine1: b1.endLine,
|
|
362
|
+
file2: b2.file,
|
|
363
|
+
line2: b2.startLine,
|
|
364
|
+
endLine2: b2.endLine,
|
|
365
|
+
code1: b1.code,
|
|
366
|
+
code2: b2.code,
|
|
367
|
+
similarity: sim,
|
|
368
|
+
patternType: b1.patternType,
|
|
369
|
+
tokenCost: b1.tokens + b2.tokens,
|
|
370
|
+
severity,
|
|
371
|
+
reason,
|
|
372
|
+
suggestion,
|
|
373
|
+
matchedRule
|
|
374
|
+
};
|
|
375
|
+
duplicates.push(dup);
|
|
376
|
+
if (streamResults)
|
|
377
|
+
console.log(
|
|
378
|
+
`[DUPLICATE] ${dup.file1}:${dup.line1} <-> ${dup.file2}:${dup.line2} (${Math.round(sim * 100)}%)`
|
|
379
|
+
);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
if (onProgress) {
|
|
384
|
+
onProgress(
|
|
385
|
+
totalComparisons,
|
|
386
|
+
totalComparisons,
|
|
387
|
+
`Duplicate detection complete. Found ${duplicates.length} patterns.`
|
|
388
|
+
);
|
|
389
|
+
}
|
|
390
|
+
return duplicates.sort((a, b) => b.similarity - a.similarity);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// src/grouping.ts
|
|
394
|
+
import { Severity as Severity3 } from "@aiready/core";
|
|
395
|
+
import path from "path";
|
|
396
|
+
function getSeverityLevel(s) {
|
|
397
|
+
if (s === Severity3.Critical || s === "critical") return 4;
|
|
398
|
+
if (s === Severity3.Major || s === "major") return 3;
|
|
399
|
+
if (s === Severity3.Minor || s === "minor") return 2;
|
|
400
|
+
if (s === Severity3.Info || s === "info") return 1;
|
|
401
|
+
return 0;
|
|
402
|
+
}
|
|
403
|
+
function groupDuplicatesByFilePair(duplicates) {
|
|
404
|
+
const groups = /* @__PURE__ */ new Map();
|
|
405
|
+
for (const dup of duplicates) {
|
|
406
|
+
const files = [dup.file1, dup.file2].sort();
|
|
407
|
+
const key = files.join("::");
|
|
408
|
+
if (!groups.has(key)) {
|
|
409
|
+
groups.set(key, {
|
|
410
|
+
filePair: key,
|
|
411
|
+
severity: dup.severity,
|
|
412
|
+
occurrences: 0,
|
|
413
|
+
totalTokenCost: 0,
|
|
414
|
+
averageSimilarity: 0,
|
|
415
|
+
patternTypes: /* @__PURE__ */ new Set(),
|
|
416
|
+
lineRanges: []
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
const group = groups.get(key);
|
|
420
|
+
group.occurrences++;
|
|
421
|
+
group.totalTokenCost += dup.tokenCost;
|
|
422
|
+
group.averageSimilarity += dup.similarity;
|
|
423
|
+
group.patternTypes.add(dup.patternType);
|
|
424
|
+
group.lineRanges.push({
|
|
425
|
+
file1: { start: dup.line1, end: dup.endLine1 },
|
|
426
|
+
file2: { start: dup.line2, end: dup.endLine2 }
|
|
427
|
+
});
|
|
428
|
+
const currentSev = dup.severity;
|
|
429
|
+
if (getSeverityLevel(currentSev) > getSeverityLevel(group.severity)) {
|
|
430
|
+
group.severity = currentSev;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
return Array.from(groups.values()).map((g) => ({
|
|
434
|
+
...g,
|
|
435
|
+
averageSimilarity: g.averageSimilarity / g.occurrences
|
|
436
|
+
}));
|
|
437
|
+
}
|
|
438
|
+
function createRefactorClusters(duplicates) {
|
|
439
|
+
const adjacency = /* @__PURE__ */ new Map();
|
|
440
|
+
const visited = /* @__PURE__ */ new Set();
|
|
441
|
+
const components = [];
|
|
442
|
+
for (const dup of duplicates) {
|
|
443
|
+
if (!adjacency.has(dup.file1)) adjacency.set(dup.file1, /* @__PURE__ */ new Set());
|
|
444
|
+
if (!adjacency.has(dup.file2)) adjacency.set(dup.file2, /* @__PURE__ */ new Set());
|
|
445
|
+
adjacency.get(dup.file1).add(dup.file2);
|
|
446
|
+
adjacency.get(dup.file2).add(dup.file1);
|
|
447
|
+
}
|
|
448
|
+
for (const file of adjacency.keys()) {
|
|
449
|
+
if (visited.has(file)) continue;
|
|
450
|
+
const component = [];
|
|
451
|
+
const queue = [file];
|
|
452
|
+
visited.add(file);
|
|
453
|
+
while (queue.length > 0) {
|
|
454
|
+
const curr = queue.shift();
|
|
455
|
+
component.push(curr);
|
|
456
|
+
for (const neighbor of adjacency.get(curr) || []) {
|
|
457
|
+
if (!visited.has(neighbor)) {
|
|
458
|
+
visited.add(neighbor);
|
|
459
|
+
queue.push(neighbor);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
components.push(component);
|
|
464
|
+
}
|
|
465
|
+
const clusters = [];
|
|
466
|
+
for (const component of components) {
|
|
467
|
+
if (component.length < 2) continue;
|
|
468
|
+
const componentDups = duplicates.filter(
|
|
469
|
+
(d) => component.includes(d.file1) && component.includes(d.file2)
|
|
470
|
+
);
|
|
471
|
+
const totalTokenCost = componentDups.reduce(
|
|
472
|
+
(sum, d) => sum + d.tokenCost,
|
|
473
|
+
0
|
|
474
|
+
);
|
|
475
|
+
const avgSimilarity = componentDups.reduce((sum, d) => sum + d.similarity, 0) / Math.max(1, componentDups.length);
|
|
476
|
+
const name = determineClusterName(component);
|
|
477
|
+
const { severity, reason, suggestion } = calculateSeverity(
|
|
478
|
+
component[0],
|
|
479
|
+
component[1],
|
|
480
|
+
"",
|
|
481
|
+
// Code not available here
|
|
482
|
+
avgSimilarity,
|
|
483
|
+
30
|
|
484
|
+
// Assume substantial if clustered
|
|
485
|
+
);
|
|
486
|
+
clusters.push({
|
|
487
|
+
id: `cluster-${clusters.length}`,
|
|
488
|
+
name,
|
|
489
|
+
files: component,
|
|
490
|
+
severity,
|
|
491
|
+
duplicateCount: componentDups.length,
|
|
492
|
+
totalTokenCost,
|
|
493
|
+
averageSimilarity: avgSimilarity,
|
|
494
|
+
reason,
|
|
495
|
+
suggestion
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
return clusters;
|
|
499
|
+
}
|
|
500
|
+
function determineClusterName(files) {
|
|
501
|
+
if (files.length === 0) return "Unknown Cluster";
|
|
502
|
+
if (files.some((f) => f.includes("blog"))) return "Blog SEO Boilerplate";
|
|
503
|
+
if (files.some((f) => f.includes("buttons")))
|
|
504
|
+
return "Button Component Variants";
|
|
505
|
+
if (files.some((f) => f.includes("cards"))) return "Card Component Variants";
|
|
506
|
+
if (files.some((f) => f.includes("login.test"))) return "E2E Test Patterns";
|
|
507
|
+
const first = files[0];
|
|
508
|
+
const dirName = path.dirname(first).split(path.sep).pop();
|
|
509
|
+
if (dirName && dirName !== "." && dirName !== "..") {
|
|
510
|
+
return `${dirName.charAt(0).toUpperCase() + dirName.slice(1)} Domain Group`;
|
|
511
|
+
}
|
|
512
|
+
return "Shared Pattern Group";
|
|
513
|
+
}
|
|
514
|
+
function filterClustersByImpact(clusters, minTokenCost = 1e3, minFiles = 3) {
|
|
515
|
+
return clusters.filter(
|
|
516
|
+
(c) => c.totalTokenCost >= minTokenCost && c.files.length >= minFiles
|
|
517
|
+
);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// src/analyzer.ts
|
|
521
|
+
function getRefactoringSuggestion(patternType, similarity) {
|
|
522
|
+
const baseMessages = {
|
|
523
|
+
"api-handler": "Extract common middleware or create a base handler class",
|
|
524
|
+
validator: "Consolidate validation logic into shared schema validators (Zod/Yup)",
|
|
525
|
+
utility: "Move to a shared utilities file and reuse across modules",
|
|
526
|
+
"class-method": "Consider inheritance or composition to share behavior",
|
|
527
|
+
component: "Extract shared logic into a custom hook or HOC",
|
|
528
|
+
function: "Extract into a shared helper function",
|
|
529
|
+
unknown: "Extract common logic into a reusable module"
|
|
530
|
+
};
|
|
531
|
+
const urgency = similarity > 0.95 ? " (CRITICAL: Nearly identical code)" : similarity > 0.9 ? " (HIGH: Very similar, refactor soon)" : "";
|
|
532
|
+
return baseMessages[patternType] + urgency;
|
|
533
|
+
}
|
|
534
|
+
async function getSmartDefaults(directory, userOptions) {
|
|
535
|
+
if (userOptions.useSmartDefaults === false) {
|
|
536
|
+
return {
|
|
537
|
+
rootDir: directory,
|
|
538
|
+
minSimilarity: 0.6,
|
|
539
|
+
minLines: 8,
|
|
540
|
+
batchSize: 100,
|
|
541
|
+
approx: true,
|
|
542
|
+
minSharedTokens: 12,
|
|
543
|
+
maxCandidatesPerBlock: 5,
|
|
544
|
+
streamResults: false,
|
|
545
|
+
severity: "all",
|
|
546
|
+
includeTests: false
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
const scanOptions = {
|
|
550
|
+
rootDir: directory,
|
|
551
|
+
include: userOptions.include || ["**/*.{ts,tsx,js,jsx,py,java}"],
|
|
552
|
+
exclude: userOptions.exclude
|
|
553
|
+
};
|
|
554
|
+
const files = await scanFiles(scanOptions);
|
|
555
|
+
const fileCount = files.length;
|
|
556
|
+
const estimatedBlocks = fileCount * 5;
|
|
557
|
+
const minLines = Math.max(
|
|
558
|
+
6,
|
|
559
|
+
Math.min(20, 6 + Math.floor(estimatedBlocks / 1e3) * 2)
|
|
560
|
+
);
|
|
561
|
+
const minSimilarity = Math.min(0.85, 0.5 + estimatedBlocks / 5e3 * 0.3);
|
|
562
|
+
const batchSize = estimatedBlocks > 1e3 ? 200 : 100;
|
|
563
|
+
const severity = estimatedBlocks > 3e3 ? "high" : "all";
|
|
564
|
+
const maxCandidatesPerBlock = Math.max(
|
|
565
|
+
5,
|
|
566
|
+
Math.min(100, Math.floor(1e6 / estimatedBlocks))
|
|
567
|
+
);
|
|
568
|
+
const defaults = {
|
|
569
|
+
rootDir: directory,
|
|
570
|
+
minSimilarity,
|
|
571
|
+
minLines,
|
|
572
|
+
batchSize,
|
|
573
|
+
approx: true,
|
|
574
|
+
minSharedTokens: 10,
|
|
575
|
+
maxCandidatesPerBlock,
|
|
576
|
+
streamResults: false,
|
|
577
|
+
severity,
|
|
578
|
+
includeTests: false
|
|
579
|
+
};
|
|
580
|
+
const result = { ...defaults };
|
|
581
|
+
for (const [key, value] of Object.entries(defaults)) {
|
|
582
|
+
if (key in userOptions && userOptions[key] !== void 0) {
|
|
583
|
+
result[key] = userOptions[key];
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
return result;
|
|
587
|
+
}
|
|
588
|
+
function logConfiguration(config, estimatedBlocks) {
|
|
589
|
+
if (config.suppressToolConfig) return;
|
|
590
|
+
console.log("\u{1F4CB} Configuration:");
|
|
591
|
+
console.log(` Repository size: ~${estimatedBlocks} code blocks`);
|
|
592
|
+
console.log(` Similarity threshold: ${config.minSimilarity}`);
|
|
593
|
+
console.log(` Minimum lines: ${config.minLines}`);
|
|
594
|
+
console.log(` Approximate mode: ${config.approx ? "enabled" : "disabled"}`);
|
|
595
|
+
console.log(` Max candidates per block: ${config.maxCandidatesPerBlock}`);
|
|
596
|
+
console.log(` Min shared tokens: ${config.minSharedTokens}`);
|
|
597
|
+
console.log(` Severity filter: ${config.severity}`);
|
|
598
|
+
console.log(` Include tests: ${config.includeTests}`);
|
|
599
|
+
console.log("");
|
|
600
|
+
}
|
|
601
|
+
async function analyzePatterns(options) {
|
|
602
|
+
const smartDefaults = await getSmartDefaults(options.rootDir || ".", options);
|
|
603
|
+
const finalOptions = { ...smartDefaults, ...options };
|
|
604
|
+
const {
|
|
605
|
+
minSimilarity = 0.4,
|
|
606
|
+
minLines = 5,
|
|
607
|
+
batchSize = 100,
|
|
608
|
+
approx = true,
|
|
609
|
+
minSharedTokens = 8,
|
|
610
|
+
maxCandidatesPerBlock = 100,
|
|
611
|
+
streamResults = false,
|
|
612
|
+
severity = "all",
|
|
613
|
+
includeTests = false,
|
|
614
|
+
groupByFilePair = true,
|
|
615
|
+
createClusters = true,
|
|
616
|
+
minClusterTokenCost = 1e3,
|
|
617
|
+
minClusterFiles = 3,
|
|
618
|
+
...scanOptions
|
|
619
|
+
} = finalOptions;
|
|
620
|
+
const files = await scanFiles(scanOptions);
|
|
621
|
+
const estimatedBlocks = files.length * 3;
|
|
622
|
+
logConfiguration(finalOptions, estimatedBlocks);
|
|
623
|
+
const results = [];
|
|
624
|
+
const READ_BATCH_SIZE = 50;
|
|
625
|
+
const fileContents = [];
|
|
626
|
+
for (let i = 0; i < files.length; i += READ_BATCH_SIZE) {
|
|
627
|
+
const batch = files.slice(i, i + READ_BATCH_SIZE);
|
|
628
|
+
const batchContents = await Promise.all(
|
|
629
|
+
batch.map(async (file) => ({
|
|
630
|
+
file,
|
|
631
|
+
content: await readFileContent(file)
|
|
632
|
+
}))
|
|
633
|
+
);
|
|
634
|
+
fileContents.push(...batchContents);
|
|
635
|
+
}
|
|
636
|
+
const duplicates = await detectDuplicatePatterns(fileContents, {
|
|
637
|
+
minSimilarity,
|
|
638
|
+
minLines,
|
|
639
|
+
batchSize,
|
|
640
|
+
approx,
|
|
641
|
+
minSharedTokens,
|
|
642
|
+
maxCandidatesPerBlock,
|
|
643
|
+
streamResults,
|
|
644
|
+
onProgress: options.onProgress
|
|
645
|
+
});
|
|
646
|
+
for (const file of files) {
|
|
647
|
+
const fileDuplicates = duplicates.filter(
|
|
648
|
+
(dup) => dup.file1 === file || dup.file2 === file
|
|
649
|
+
);
|
|
650
|
+
const issues = fileDuplicates.map((dup) => {
|
|
651
|
+
const otherFile = dup.file1 === file ? dup.file2 : dup.file1;
|
|
652
|
+
const severity2 = dup.similarity > 0.95 ? Severity4.Critical : dup.similarity > 0.9 ? Severity4.Major : Severity4.Minor;
|
|
653
|
+
return {
|
|
654
|
+
type: IssueType.DuplicatePattern,
|
|
655
|
+
severity: severity2,
|
|
656
|
+
message: `${dup.patternType} pattern ${Math.round(dup.similarity * 100)}% similar to ${otherFile} (${dup.tokenCost} tokens wasted)`,
|
|
657
|
+
location: {
|
|
658
|
+
file,
|
|
659
|
+
line: dup.file1 === file ? dup.line1 : dup.line2
|
|
660
|
+
},
|
|
661
|
+
suggestion: getRefactoringSuggestion(dup.patternType, dup.similarity)
|
|
662
|
+
};
|
|
663
|
+
});
|
|
664
|
+
let filteredIssues = issues;
|
|
665
|
+
if (severity !== "all") {
|
|
666
|
+
const severityMap = {
|
|
667
|
+
critical: [Severity4.Critical],
|
|
668
|
+
high: [Severity4.Critical, Severity4.Major],
|
|
669
|
+
medium: [Severity4.Critical, Severity4.Major, Severity4.Minor]
|
|
670
|
+
};
|
|
671
|
+
const allowedSeverities = severityMap[severity] || [Severity4.Critical, Severity4.Major, Severity4.Minor];
|
|
672
|
+
filteredIssues = issues.filter(
|
|
673
|
+
(issue) => allowedSeverities.includes(issue.severity)
|
|
674
|
+
);
|
|
675
|
+
}
|
|
676
|
+
const totalTokenCost = fileDuplicates.reduce(
|
|
677
|
+
(sum, dup) => sum + dup.tokenCost,
|
|
678
|
+
0
|
|
679
|
+
);
|
|
680
|
+
results.push({
|
|
681
|
+
fileName: file,
|
|
682
|
+
issues: filteredIssues,
|
|
683
|
+
metrics: {
|
|
684
|
+
tokenCost: totalTokenCost,
|
|
685
|
+
consistencyScore: Math.max(0, 1 - fileDuplicates.length * 0.1)
|
|
686
|
+
}
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
let groups;
|
|
690
|
+
let clusters;
|
|
691
|
+
if (groupByFilePair) {
|
|
692
|
+
groups = groupDuplicatesByFilePair(duplicates);
|
|
693
|
+
}
|
|
694
|
+
if (createClusters) {
|
|
695
|
+
const allClusters = createRefactorClusters(duplicates);
|
|
696
|
+
clusters = filterClustersByImpact(
|
|
697
|
+
allClusters,
|
|
698
|
+
minClusterTokenCost,
|
|
699
|
+
minClusterFiles
|
|
700
|
+
);
|
|
701
|
+
}
|
|
702
|
+
return { results, duplicates, files, groups, clusters, config: finalOptions };
|
|
703
|
+
}
|
|
704
|
+
function generateSummary(results) {
|
|
705
|
+
const allIssues = results.flatMap((r) => r.issues);
|
|
706
|
+
const totalTokenCost = results.reduce(
|
|
707
|
+
(sum, r) => sum + (r.metrics.tokenCost || 0),
|
|
708
|
+
0
|
|
709
|
+
);
|
|
710
|
+
const patternsByType = {
|
|
711
|
+
"api-handler": 0,
|
|
712
|
+
validator: 0,
|
|
713
|
+
utility: 0,
|
|
714
|
+
"class-method": 0,
|
|
715
|
+
component: 0,
|
|
716
|
+
function: 0,
|
|
717
|
+
unknown: 0
|
|
718
|
+
};
|
|
719
|
+
allIssues.forEach((issue) => {
|
|
720
|
+
const match = issue.message.match(/^(\S+(?:-\S+)*) pattern/);
|
|
721
|
+
if (match) {
|
|
722
|
+
const type = match[1];
|
|
723
|
+
patternsByType[type] = (patternsByType[type] || 0) + 1;
|
|
724
|
+
}
|
|
725
|
+
});
|
|
726
|
+
const topDuplicates = allIssues.slice(0, 10).map((issue) => {
|
|
727
|
+
const similarityMatch = issue.message.match(/(\d+)% similar/);
|
|
728
|
+
const tokenMatch = issue.message.match(/\((\d+) tokens/);
|
|
729
|
+
const typeMatch = issue.message.match(/^(\S+(?:-\S+)*) pattern/);
|
|
730
|
+
const fileMatch = issue.message.match(/similar to (.+?) \(/);
|
|
731
|
+
return {
|
|
732
|
+
files: [
|
|
733
|
+
{
|
|
734
|
+
path: issue.location.file,
|
|
735
|
+
startLine: issue.location.line,
|
|
736
|
+
endLine: 0
|
|
737
|
+
},
|
|
738
|
+
{
|
|
739
|
+
path: fileMatch?.[1] || "unknown",
|
|
740
|
+
startLine: 0,
|
|
741
|
+
endLine: 0
|
|
742
|
+
}
|
|
743
|
+
],
|
|
744
|
+
similarity: similarityMatch ? parseInt(similarityMatch[1]) / 100 : 0,
|
|
745
|
+
patternType: typeMatch?.[1] || "unknown",
|
|
746
|
+
tokenCost: tokenMatch ? parseInt(tokenMatch[1]) : 0
|
|
747
|
+
};
|
|
748
|
+
});
|
|
749
|
+
return {
|
|
750
|
+
totalPatterns: allIssues.length,
|
|
751
|
+
totalTokenCost,
|
|
752
|
+
patternsByType,
|
|
753
|
+
topDuplicates
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
// src/scoring.ts
|
|
758
|
+
import {
|
|
759
|
+
calculateMonthlyCost,
|
|
760
|
+
calculateProductivityImpact,
|
|
761
|
+
DEFAULT_COST_CONFIG,
|
|
762
|
+
ToolName
|
|
763
|
+
} from "@aiready/core";
|
|
764
|
+
function calculatePatternScore(duplicates, totalFilesAnalyzed, costConfig) {
|
|
765
|
+
const totalDuplicates = duplicates.length;
|
|
766
|
+
const totalTokenCost = duplicates.reduce((sum, d) => sum + d.tokenCost, 0);
|
|
767
|
+
const highImpactDuplicates = duplicates.filter(
|
|
768
|
+
(d) => d.tokenCost > 1e3 || d.similarity > 0.7
|
|
769
|
+
).length;
|
|
770
|
+
if (totalFilesAnalyzed === 0) {
|
|
771
|
+
return {
|
|
772
|
+
toolName: ToolName.PatternDetect,
|
|
773
|
+
score: 100,
|
|
774
|
+
rawMetrics: {
|
|
775
|
+
totalDuplicates: 0,
|
|
776
|
+
totalTokenCost: 0,
|
|
777
|
+
highImpactDuplicates: 0,
|
|
778
|
+
totalFilesAnalyzed: 0
|
|
779
|
+
},
|
|
780
|
+
factors: [],
|
|
781
|
+
recommendations: []
|
|
782
|
+
};
|
|
783
|
+
}
|
|
784
|
+
const duplicatesPerFile = totalDuplicates / totalFilesAnalyzed * 100;
|
|
785
|
+
const tokenWastePerFile = totalTokenCost / totalFilesAnalyzed;
|
|
786
|
+
const duplicatesPenalty = Math.min(60, duplicatesPerFile * 0.6);
|
|
787
|
+
const tokenPenalty = Math.min(40, tokenWastePerFile / 125);
|
|
788
|
+
const highImpactPenalty = highImpactDuplicates > 0 ? Math.min(15, highImpactDuplicates * 2 - 5) : -5;
|
|
789
|
+
const score = 100 - duplicatesPenalty - tokenPenalty - highImpactPenalty;
|
|
790
|
+
const finalScore = Math.max(0, Math.min(100, Math.round(score)));
|
|
791
|
+
const factors = [
|
|
792
|
+
{
|
|
793
|
+
name: "Duplication Density",
|
|
794
|
+
impact: -Math.round(duplicatesPenalty),
|
|
795
|
+
description: `${duplicatesPerFile.toFixed(1)} duplicates per 100 files`
|
|
796
|
+
},
|
|
797
|
+
{
|
|
798
|
+
name: "Token Waste",
|
|
799
|
+
impact: -Math.round(tokenPenalty),
|
|
800
|
+
description: `${Math.round(tokenWastePerFile)} tokens wasted per file`
|
|
801
|
+
}
|
|
802
|
+
];
|
|
803
|
+
if (highImpactDuplicates > 0) {
|
|
804
|
+
factors.push({
|
|
805
|
+
name: "High-Impact Patterns",
|
|
806
|
+
impact: -Math.round(highImpactPenalty),
|
|
807
|
+
description: `${highImpactDuplicates} high-impact duplicates (>1000 tokens or >70% similar)`
|
|
808
|
+
});
|
|
809
|
+
} else {
|
|
810
|
+
factors.push({
|
|
811
|
+
name: "No High-Impact Patterns",
|
|
812
|
+
impact: 5,
|
|
813
|
+
description: "No severe duplicates detected"
|
|
814
|
+
});
|
|
815
|
+
}
|
|
816
|
+
const recommendations = [];
|
|
817
|
+
if (highImpactDuplicates > 0) {
|
|
818
|
+
const estimatedImpact = Math.min(15, highImpactDuplicates * 3);
|
|
819
|
+
recommendations.push({
|
|
820
|
+
action: `Deduplicate ${highImpactDuplicates} high-impact pattern${highImpactDuplicates > 1 ? "s" : ""}`,
|
|
821
|
+
estimatedImpact,
|
|
822
|
+
priority: "high"
|
|
823
|
+
});
|
|
824
|
+
}
|
|
825
|
+
if (totalDuplicates > 10 && duplicatesPerFile > 20) {
|
|
826
|
+
const estimatedImpact = Math.min(10, Math.round(duplicatesPenalty * 0.3));
|
|
827
|
+
recommendations.push({
|
|
828
|
+
action: "Extract common patterns into shared utilities",
|
|
829
|
+
estimatedImpact,
|
|
830
|
+
priority: "medium"
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
if (tokenWastePerFile > 2e3) {
|
|
834
|
+
const estimatedImpact = Math.min(8, Math.round(tokenPenalty * 0.4));
|
|
835
|
+
recommendations.push({
|
|
836
|
+
action: "Consolidate duplicated logic to reduce AI context waste",
|
|
837
|
+
estimatedImpact,
|
|
838
|
+
priority: totalTokenCost > 1e4 ? "high" : "medium"
|
|
839
|
+
});
|
|
840
|
+
}
|
|
841
|
+
const cfg = { ...DEFAULT_COST_CONFIG, ...costConfig };
|
|
842
|
+
const estimatedMonthlyCost = calculateMonthlyCost(totalTokenCost, cfg);
|
|
843
|
+
const issues = duplicates.map((d) => ({
|
|
844
|
+
severity: d.severity === "critical" ? "critical" : d.severity === "major" ? "major" : "minor"
|
|
845
|
+
}));
|
|
846
|
+
const productivityImpact = calculateProductivityImpact(issues);
|
|
847
|
+
return {
|
|
848
|
+
toolName: "pattern-detect",
|
|
849
|
+
score: finalScore,
|
|
850
|
+
rawMetrics: {
|
|
851
|
+
totalDuplicates,
|
|
852
|
+
totalTokenCost,
|
|
853
|
+
highImpactDuplicates,
|
|
854
|
+
totalFilesAnalyzed,
|
|
855
|
+
duplicatesPerFile: Math.round(duplicatesPerFile * 10) / 10,
|
|
856
|
+
tokenWastePerFile: Math.round(tokenWastePerFile),
|
|
857
|
+
// Business value metrics
|
|
858
|
+
estimatedMonthlyCost,
|
|
859
|
+
estimatedDeveloperHours: productivityImpact.totalHours
|
|
860
|
+
},
|
|
861
|
+
factors,
|
|
862
|
+
recommendations
|
|
863
|
+
};
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
// src/provider.ts
|
|
867
|
+
var PatternDetectProvider = {
|
|
868
|
+
id: ToolName2.PatternDetect,
|
|
869
|
+
alias: ["patterns", "duplicates", "duplication"],
|
|
870
|
+
async analyze(options) {
|
|
871
|
+
const results = await analyzePatterns(options);
|
|
872
|
+
return SpokeOutputSchema.parse({
|
|
873
|
+
results: results.results,
|
|
874
|
+
summary: {
|
|
875
|
+
totalFiles: results.files.length,
|
|
876
|
+
totalIssues: results.results.reduce(
|
|
877
|
+
(sum, r) => sum + r.issues.length,
|
|
878
|
+
0
|
|
879
|
+
),
|
|
880
|
+
duplicates: results.duplicates,
|
|
881
|
+
// Keep the raw duplicates for score calculation
|
|
882
|
+
clusters: results.clusters,
|
|
883
|
+
config: Object.fromEntries(
|
|
884
|
+
Object.entries(results.config).filter(
|
|
885
|
+
([key]) => !GLOBAL_SCAN_OPTIONS.includes(key) || key === "rootDir"
|
|
886
|
+
)
|
|
887
|
+
)
|
|
888
|
+
},
|
|
889
|
+
metadata: {
|
|
890
|
+
toolName: ToolName2.PatternDetect,
|
|
891
|
+
version: "0.12.5",
|
|
892
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
893
|
+
}
|
|
894
|
+
});
|
|
895
|
+
},
|
|
896
|
+
score(output, options) {
|
|
897
|
+
const duplicates = output.summary.duplicates || [];
|
|
898
|
+
const totalFiles = output.summary.totalFiles || output.results.length;
|
|
899
|
+
return calculatePatternScore(
|
|
900
|
+
duplicates,
|
|
901
|
+
totalFiles,
|
|
902
|
+
options.costConfig
|
|
903
|
+
);
|
|
904
|
+
},
|
|
905
|
+
defaultWeight: 22
|
|
906
|
+
};
|
|
907
|
+
|
|
908
|
+
// src/index.ts
|
|
909
|
+
ToolRegistry.register(PatternDetectProvider);
|
|
910
|
+
|
|
911
|
+
export {
|
|
912
|
+
CONTEXT_RULES,
|
|
913
|
+
calculateSeverity,
|
|
914
|
+
getSeverityLabel,
|
|
915
|
+
filterBySeverity,
|
|
916
|
+
getSeverityThreshold,
|
|
917
|
+
detectDuplicatePatterns,
|
|
918
|
+
groupDuplicatesByFilePair,
|
|
919
|
+
createRefactorClusters,
|
|
920
|
+
filterClustersByImpact,
|
|
921
|
+
getSmartDefaults,
|
|
922
|
+
analyzePatterns,
|
|
923
|
+
generateSummary,
|
|
924
|
+
calculatePatternScore,
|
|
925
|
+
PatternDetectProvider,
|
|
926
|
+
Severity5 as Severity
|
|
927
|
+
};
|
package/dist/cli.js
CHANGED
|
@@ -878,6 +878,8 @@ var PatternDetectProvider = {
|
|
|
878
878
|
(sum, r) => sum + r.issues.length,
|
|
879
879
|
0
|
|
880
880
|
),
|
|
881
|
+
duplicates: results.duplicates,
|
|
882
|
+
// Keep the raw duplicates for score calculation
|
|
881
883
|
clusters: results.clusters,
|
|
882
884
|
config: Object.fromEntries(
|
|
883
885
|
Object.entries(results.config).filter(
|
package/dist/cli.mjs
CHANGED
package/dist/index.js
CHANGED
|
@@ -916,6 +916,8 @@ var PatternDetectProvider = {
|
|
|
916
916
|
(sum, r) => sum + r.issues.length,
|
|
917
917
|
0
|
|
918
918
|
),
|
|
919
|
+
duplicates: results.duplicates,
|
|
920
|
+
// Keep the raw duplicates for score calculation
|
|
919
921
|
clusters: results.clusters,
|
|
920
922
|
config: Object.fromEntries(
|
|
921
923
|
Object.entries(results.config).filter(
|
package/dist/index.mjs
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aiready/pattern-detect",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.0",
|
|
4
4
|
"description": "Semantic duplicate pattern detection for AI-generated code - finds similar implementations that waste AI context tokens",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"module": "./dist/index.mjs",
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"dependencies": {
|
|
46
46
|
"commander": "^14.0.0",
|
|
47
47
|
"chalk": "^5.3.0",
|
|
48
|
-
"@aiready/core": "0.
|
|
48
|
+
"@aiready/core": "0.23.0"
|
|
49
49
|
},
|
|
50
50
|
"devDependencies": {
|
|
51
51
|
"tsup": "^8.3.5",
|