@aiready/pattern-detect 0.7.7 → 0.7.11
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/README.md +130 -0
- package/dist/chunk-262N2JB7.mjs +497 -0
- package/dist/chunk-GSJFORRO.mjs +504 -0
- package/dist/chunk-M4PQMW34.mjs +480 -0
- package/dist/chunk-R2S73CVG.mjs +503 -0
- package/dist/chunk-S2KQFII2.mjs +491 -0
- package/dist/chunk-TJKDLVLN.mjs +503 -0
- package/dist/cli.js +57 -48
- package/dist/cli.mjs +16 -2
- package/dist/index.d.mts +5 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.js +46 -49
- package/dist/index.mjs +5 -3
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -388,6 +388,136 @@ Use these presets to quickly balance precision, recall, and runtime:
|
|
|
388
388
|
- `minLines 8–10` → `minSharedTokens 8–10` (precision-first)
|
|
389
389
|
- Default balance: `minLines=5`, `minSharedTokens=8` works well for most repos. Reduce `minSharedTokens` only when you specifically want to catch more short helpers.
|
|
390
390
|
|
|
391
|
+
## 🎯 Parameter Tuning Guide
|
|
392
|
+
|
|
393
|
+
### When You Get Too Few Results
|
|
394
|
+
|
|
395
|
+
If the tool finds fewer duplicates than expected, try these adjustments in order:
|
|
396
|
+
|
|
397
|
+
**1. Lower similarity threshold** (most effective)
|
|
398
|
+
```bash
|
|
399
|
+
# Default: 0.4, try lowering to find more potential duplicates
|
|
400
|
+
aiready-patterns ./src --similarity 0.3 # More sensitive
|
|
401
|
+
aiready-patterns ./src --similarity 0.2 # Very sensitive (may include noise)
|
|
402
|
+
```
|
|
403
|
+
*Tradeoff: More results but potentially more false positives*
|
|
404
|
+
|
|
405
|
+
**2. Reduce minimum lines**
|
|
406
|
+
```bash
|
|
407
|
+
# Default: 5, try lowering to catch smaller functions/utilities
|
|
408
|
+
aiready-patterns ./src --min-lines 3 # Include very small functions
|
|
409
|
+
aiready-patterns ./src --min-lines 1 # Include almost everything
|
|
410
|
+
```
|
|
411
|
+
*Tradeoff: More results but slower analysis and more noise*
|
|
412
|
+
|
|
413
|
+
**3. Lower shared tokens threshold**
|
|
414
|
+
```bash
|
|
415
|
+
# Default: 8, try lowering to expand candidate pool
|
|
416
|
+
aiready-patterns ./src --min-shared-tokens 5 # More candidates
|
|
417
|
+
aiready-patterns ./src --min-shared-tokens 3 # Many more candidates
|
|
418
|
+
```
|
|
419
|
+
*Tradeoff: More results but slower analysis*
|
|
420
|
+
|
|
421
|
+
**4. Include test files**
|
|
422
|
+
```bash
|
|
423
|
+
aiready-patterns ./src --include-tests
|
|
424
|
+
```
|
|
425
|
+
*Tradeoff: More results but may include test-specific patterns*
|
|
426
|
+
|
|
427
|
+
**5. Increase max candidates per block**
|
|
428
|
+
```bash
|
|
429
|
+
# Default: 100, try increasing for more thorough search
|
|
430
|
+
aiready-patterns ./src --max-candidates 200 # More thorough
|
|
431
|
+
```
|
|
432
|
+
*Tradeoff: Slower analysis but more comprehensive*
|
|
433
|
+
|
|
434
|
+
### When Analysis is Too Slow
|
|
435
|
+
|
|
436
|
+
If the tool takes too long to run, try these optimizations in order:
|
|
437
|
+
|
|
438
|
+
**1. Increase minimum lines** (most effective)
|
|
439
|
+
```bash
|
|
440
|
+
# Default: 5, try increasing to focus on substantial functions
|
|
441
|
+
aiready-patterns ./src --min-lines 10 # Focus on larger functions
|
|
442
|
+
aiready-patterns ./src --min-lines 15 # Only major functions
|
|
443
|
+
```
|
|
444
|
+
*Tradeoff: Faster but may miss small but important duplicates*
|
|
445
|
+
|
|
446
|
+
**2. Increase shared tokens threshold**
|
|
447
|
+
```bash
|
|
448
|
+
# Default: 8, try increasing to reduce candidate pool
|
|
449
|
+
aiready-patterns ./src --min-shared-tokens 12 # Fewer candidates
|
|
450
|
+
aiready-patterns ./src --min-shared-tokens 15 # Much fewer candidates
|
|
451
|
+
```
|
|
452
|
+
*Tradeoff: Faster but may miss some duplicates*
|
|
453
|
+
|
|
454
|
+
**3. Reduce max candidates per block**
|
|
455
|
+
```bash
|
|
456
|
+
# Default: 100, try reducing for faster analysis
|
|
457
|
+
aiready-patterns ./src --max-candidates 50 # Faster
|
|
458
|
+
aiready-patterns ./src --max-candidates 20 # Much faster
|
|
459
|
+
```
|
|
460
|
+
*Tradeoff: Faster but may miss some duplicates*
|
|
461
|
+
|
|
462
|
+
**4. Increase similarity threshold**
|
|
463
|
+
```bash
|
|
464
|
+
# Default: 0.4, try increasing to reduce comparisons
|
|
465
|
+
aiready-patterns ./src --similarity 0.6 # Fewer but more obvious duplicates
|
|
466
|
+
```
|
|
467
|
+
*Tradeoff: Faster but fewer results*
|
|
468
|
+
|
|
469
|
+
**5. Analyze by module/directory**
|
|
470
|
+
```bash
|
|
471
|
+
# Instead of analyzing the entire repo, analyze specific directories
|
|
472
|
+
aiready-patterns ./src/api --min-lines 8
|
|
473
|
+
aiready-patterns ./src/components --min-lines 8
|
|
474
|
+
```
|
|
475
|
+
*Tradeoff: Need to run multiple commands but each is faster*
|
|
476
|
+
|
|
477
|
+
### When You Get Too Many False Positives
|
|
478
|
+
|
|
479
|
+
If the results include many irrelevant duplicates:
|
|
480
|
+
|
|
481
|
+
**1. Increase similarity threshold**
|
|
482
|
+
```bash
|
|
483
|
+
# Default: 0.4, try increasing for more accurate matches
|
|
484
|
+
aiready-patterns ./src --similarity 0.6 # More accurate
|
|
485
|
+
aiready-patterns ./src --similarity 0.8 # Very accurate
|
|
486
|
+
```
|
|
487
|
+
*Tradeoff: Fewer results but higher quality*
|
|
488
|
+
|
|
489
|
+
**2. Increase minimum lines**
|
|
490
|
+
```bash
|
|
491
|
+
# Default: 5, try increasing to focus on substantial duplicates
|
|
492
|
+
aiready-patterns ./src --min-lines 10 # Larger patterns only
|
|
493
|
+
```
|
|
494
|
+
*Tradeoff: Fewer results but more significant ones*
|
|
495
|
+
|
|
496
|
+
**3. Use severity filtering**
|
|
497
|
+
```bash
|
|
498
|
+
aiready-patterns ./src --severity high # Only >90% similar
|
|
499
|
+
aiready-patterns ./src --severity critical # Only >95% similar
|
|
500
|
+
```
|
|
501
|
+
*Tradeoff: Fewer results but highest quality*
|
|
502
|
+
|
|
503
|
+
**4. Exclude specific patterns**
|
|
504
|
+
```bash
|
|
505
|
+
# Exclude generated files, migrations, etc.
|
|
506
|
+
aiready-patterns ./src --exclude "**/migrations/**,**/generated/**"
|
|
507
|
+
```
|
|
508
|
+
*Tradeoff: Fewer results but more relevant ones*
|
|
509
|
+
|
|
510
|
+
### Quick Troubleshooting Reference
|
|
511
|
+
|
|
512
|
+
| Problem | Symptom | Solution | Tradeoff |
|
|
513
|
+
|---------|---------|----------|----------|
|
|
514
|
+
| **No results** | "No duplicate patterns detected" | Lower `--similarity` to 0.3 | More noise |
|
|
515
|
+
| **Few results** | <5 duplicates found | Lower `--min-lines` to 3 | Slower analysis |
|
|
516
|
+
| **Too slow** | Takes >30 seconds | Increase `--min-lines` to 10 | Misses small duplicates |
|
|
517
|
+
| **Too many results** | 100+ duplicates | Increase `--similarity` to 0.6 | Misses subtle duplicates |
|
|
518
|
+
| **False positives** | Many irrelevant matches | Use `--severity critical` | Fewer results |
|
|
519
|
+
| **Memory issues** | Out of memory error | Analyze by directory | Multiple commands needed |
|
|
520
|
+
|
|
391
521
|
**CLI Options:**
|
|
392
522
|
- `--stream-results` - Output duplicates as found (enabled by default)
|
|
393
523
|
- `--no-approx` - Disable approximate mode (slower, O(B²) complexity, use with caution)
|
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { readFileContent } from "@aiready/core";
|
|
3
|
+
|
|
4
|
+
// src/detector.ts
|
|
5
|
+
import { estimateTokens } from "@aiready/core";
|
|
6
|
+
function categorizePattern(code) {
|
|
7
|
+
const lower = code.toLowerCase();
|
|
8
|
+
if (lower.includes("request") && lower.includes("response") || lower.includes("router.") || lower.includes("app.get") || lower.includes("app.post") || lower.includes("express") || lower.includes("ctx.body")) {
|
|
9
|
+
return "api-handler";
|
|
10
|
+
}
|
|
11
|
+
if (lower.includes("validate") || lower.includes("schema") || lower.includes("zod") || lower.includes("yup") || lower.includes("if") && lower.includes("throw")) {
|
|
12
|
+
return "validator";
|
|
13
|
+
}
|
|
14
|
+
if (lower.includes("return (") || lower.includes("jsx") || lower.includes("component") || lower.includes("props")) {
|
|
15
|
+
return "component";
|
|
16
|
+
}
|
|
17
|
+
if (lower.includes("class ") || lower.includes("this.")) {
|
|
18
|
+
return "class-method";
|
|
19
|
+
}
|
|
20
|
+
if (lower.includes("return ") && !lower.includes("this") && !lower.includes("new ")) {
|
|
21
|
+
return "utility";
|
|
22
|
+
}
|
|
23
|
+
if (lower.includes("function") || lower.includes("=>")) {
|
|
24
|
+
return "function";
|
|
25
|
+
}
|
|
26
|
+
return "unknown";
|
|
27
|
+
}
|
|
28
|
+
function extractCodeBlocks(content, minLines) {
|
|
29
|
+
const lines = content.split("\n");
|
|
30
|
+
const blocks = [];
|
|
31
|
+
let currentBlock = [];
|
|
32
|
+
let blockStart = 0;
|
|
33
|
+
let braceDepth = 0;
|
|
34
|
+
let inFunction = false;
|
|
35
|
+
for (let i = 0; i < lines.length; i++) {
|
|
36
|
+
const line = lines[i];
|
|
37
|
+
const trimmed = line.trim();
|
|
38
|
+
if (!inFunction && (trimmed.includes("function ") || trimmed.includes("=>") || trimmed.includes("async ") || /^(export\s+)?(async\s+)?function\s+/.test(trimmed) || /^(export\s+)?const\s+\w+\s*=\s*(async\s*)?\(/.test(trimmed))) {
|
|
39
|
+
inFunction = true;
|
|
40
|
+
blockStart = i;
|
|
41
|
+
}
|
|
42
|
+
for (const char of line) {
|
|
43
|
+
if (char === "{") braceDepth++;
|
|
44
|
+
if (char === "}") braceDepth--;
|
|
45
|
+
}
|
|
46
|
+
if (inFunction) {
|
|
47
|
+
currentBlock.push(line);
|
|
48
|
+
}
|
|
49
|
+
if (inFunction && braceDepth === 0 && currentBlock.length >= minLines) {
|
|
50
|
+
const blockContent = currentBlock.join("\n");
|
|
51
|
+
const linesOfCode = currentBlock.filter(
|
|
52
|
+
(l) => l.trim() && !l.trim().startsWith("//")
|
|
53
|
+
).length;
|
|
54
|
+
blocks.push({
|
|
55
|
+
content: blockContent,
|
|
56
|
+
startLine: blockStart + 1,
|
|
57
|
+
endLine: i + 1,
|
|
58
|
+
patternType: categorizePattern(blockContent),
|
|
59
|
+
linesOfCode
|
|
60
|
+
});
|
|
61
|
+
currentBlock = [];
|
|
62
|
+
inFunction = false;
|
|
63
|
+
} else if (inFunction && braceDepth === 0) {
|
|
64
|
+
currentBlock = [];
|
|
65
|
+
inFunction = false;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return blocks;
|
|
69
|
+
}
|
|
70
|
+
function normalizeCode(code) {
|
|
71
|
+
return code.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "").replace(/"[^"]*"/g, '"STR"').replace(/'[^']*'/g, "'STR'").replace(/`[^`]*`/g, "`STR`").replace(/\b\d+\b/g, "NUM").replace(/\s+/g, " ").trim();
|
|
72
|
+
}
|
|
73
|
+
function jaccardSimilarity(tokens1, tokens2) {
|
|
74
|
+
const set1 = new Set(tokens1);
|
|
75
|
+
const set2 = new Set(tokens2);
|
|
76
|
+
let intersection = 0;
|
|
77
|
+
for (const token of set1) {
|
|
78
|
+
if (set2.has(token)) intersection++;
|
|
79
|
+
}
|
|
80
|
+
const union = set1.size + set2.size - intersection;
|
|
81
|
+
return union === 0 ? 0 : intersection / union;
|
|
82
|
+
}
|
|
83
|
+
async function detectDuplicatePatterns(files, options) {
|
|
84
|
+
const {
|
|
85
|
+
minSimilarity,
|
|
86
|
+
minLines,
|
|
87
|
+
batchSize = 100,
|
|
88
|
+
approx = true,
|
|
89
|
+
minSharedTokens = 8,
|
|
90
|
+
maxCandidatesPerBlock = 100,
|
|
91
|
+
streamResults = false
|
|
92
|
+
} = options;
|
|
93
|
+
const duplicates = [];
|
|
94
|
+
const maxComparisons = approx ? Infinity : 5e5;
|
|
95
|
+
const allBlocks = files.flatMap(
|
|
96
|
+
(file) => extractCodeBlocks(file.content, minLines).map((block) => ({
|
|
97
|
+
content: block.content,
|
|
98
|
+
startLine: block.startLine,
|
|
99
|
+
endLine: block.endLine,
|
|
100
|
+
file: file.file,
|
|
101
|
+
normalized: normalizeCode(block.content),
|
|
102
|
+
patternType: block.patternType,
|
|
103
|
+
tokenCost: estimateTokens(block.content),
|
|
104
|
+
linesOfCode: block.linesOfCode
|
|
105
|
+
}))
|
|
106
|
+
);
|
|
107
|
+
console.log(`Extracted ${allBlocks.length} code blocks for analysis`);
|
|
108
|
+
if (!approx && allBlocks.length > 500) {
|
|
109
|
+
console.log(`\u26A0\uFE0F Using --no-approx mode with ${allBlocks.length} blocks may be slow (O(B\xB2) complexity).`);
|
|
110
|
+
console.log(` Consider using approximate mode (default) for better performance.`);
|
|
111
|
+
}
|
|
112
|
+
const stopwords = /* @__PURE__ */ new Set([
|
|
113
|
+
"return",
|
|
114
|
+
"const",
|
|
115
|
+
"let",
|
|
116
|
+
"var",
|
|
117
|
+
"function",
|
|
118
|
+
"class",
|
|
119
|
+
"new",
|
|
120
|
+
"if",
|
|
121
|
+
"else",
|
|
122
|
+
"for",
|
|
123
|
+
"while",
|
|
124
|
+
"async",
|
|
125
|
+
"await",
|
|
126
|
+
"try",
|
|
127
|
+
"catch",
|
|
128
|
+
"switch",
|
|
129
|
+
"case",
|
|
130
|
+
"default",
|
|
131
|
+
"import",
|
|
132
|
+
"export",
|
|
133
|
+
"from",
|
|
134
|
+
"true",
|
|
135
|
+
"false",
|
|
136
|
+
"null",
|
|
137
|
+
"undefined",
|
|
138
|
+
"this"
|
|
139
|
+
]);
|
|
140
|
+
const tokenize = (norm) => norm.split(/[\s(){}\[\];,\.]+/).filter((t) => t && t.length >= 3 && !stopwords.has(t.toLowerCase()));
|
|
141
|
+
const blockTokens = allBlocks.map((b) => tokenize(b.normalized));
|
|
142
|
+
const invertedIndex = /* @__PURE__ */ new Map();
|
|
143
|
+
if (approx) {
|
|
144
|
+
for (let i = 0; i < blockTokens.length; i++) {
|
|
145
|
+
for (const tok of blockTokens[i]) {
|
|
146
|
+
let arr = invertedIndex.get(tok);
|
|
147
|
+
if (!arr) {
|
|
148
|
+
arr = [];
|
|
149
|
+
invertedIndex.set(tok, arr);
|
|
150
|
+
}
|
|
151
|
+
arr.push(i);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
const totalComparisons = approx ? void 0 : allBlocks.length * (allBlocks.length - 1) / 2;
|
|
156
|
+
if (totalComparisons !== void 0) {
|
|
157
|
+
console.log(`Processing ${totalComparisons.toLocaleString()} comparisons in batches...`);
|
|
158
|
+
} else {
|
|
159
|
+
console.log(`Using approximate candidate selection to reduce comparisons...`);
|
|
160
|
+
}
|
|
161
|
+
let comparisonsProcessed = 0;
|
|
162
|
+
let comparisonsBudgetExhausted = false;
|
|
163
|
+
const startTime = Date.now();
|
|
164
|
+
for (let i = 0; i < allBlocks.length; i++) {
|
|
165
|
+
if (maxComparisons && comparisonsProcessed >= maxComparisons) {
|
|
166
|
+
comparisonsBudgetExhausted = true;
|
|
167
|
+
break;
|
|
168
|
+
}
|
|
169
|
+
if (i % batchSize === 0 && i > 0) {
|
|
170
|
+
const elapsed = ((Date.now() - startTime) / 1e3).toFixed(1);
|
|
171
|
+
const duplicatesFound = duplicates.length;
|
|
172
|
+
if (totalComparisons !== void 0) {
|
|
173
|
+
const progress = (comparisonsProcessed / totalComparisons * 100).toFixed(1);
|
|
174
|
+
const remaining = totalComparisons - comparisonsProcessed;
|
|
175
|
+
const rate = comparisonsProcessed / parseFloat(elapsed);
|
|
176
|
+
const eta = remaining > 0 ? (remaining / rate).toFixed(0) : 0;
|
|
177
|
+
console.log(` ${progress}% (${comparisonsProcessed.toLocaleString()}/${totalComparisons.toLocaleString()} comparisons, ${elapsed}s elapsed, ~${eta}s remaining, ${duplicatesFound} duplicates)`);
|
|
178
|
+
} else {
|
|
179
|
+
console.log(` Processed ${i.toLocaleString()}/${allBlocks.length} blocks (${elapsed}s elapsed, ${duplicatesFound} duplicates)`);
|
|
180
|
+
}
|
|
181
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
182
|
+
}
|
|
183
|
+
const block1 = allBlocks[i];
|
|
184
|
+
let candidates = null;
|
|
185
|
+
if (approx) {
|
|
186
|
+
const counts = /* @__PURE__ */ new Map();
|
|
187
|
+
for (const tok of blockTokens[i]) {
|
|
188
|
+
const ids = invertedIndex.get(tok);
|
|
189
|
+
if (!ids) continue;
|
|
190
|
+
for (const j of ids) {
|
|
191
|
+
if (j <= i) continue;
|
|
192
|
+
if (allBlocks[j].file === block1.file) continue;
|
|
193
|
+
counts.set(j, (counts.get(j) || 0) + 1);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
candidates = Array.from(counts.entries()).filter(([, shared]) => shared >= minSharedTokens).sort((a, b) => b[1] - a[1]).slice(0, maxCandidatesPerBlock).map(([j, shared]) => ({ j, shared }));
|
|
197
|
+
}
|
|
198
|
+
if (approx && candidates) {
|
|
199
|
+
for (const { j } of candidates) {
|
|
200
|
+
if (!approx && maxComparisons !== Infinity && comparisonsProcessed >= maxComparisons) {
|
|
201
|
+
console.log(`\u26A0\uFE0F Comparison safety limit reached (${maxComparisons.toLocaleString()} comparisons in --no-approx mode).`);
|
|
202
|
+
console.log(` This prevents excessive runtime on large repos. Consider using approximate mode (default) or --min-lines to reduce blocks.`);
|
|
203
|
+
break;
|
|
204
|
+
}
|
|
205
|
+
comparisonsProcessed++;
|
|
206
|
+
const block2 = allBlocks[j];
|
|
207
|
+
const similarity = jaccardSimilarity(blockTokens[i], blockTokens[j]);
|
|
208
|
+
if (similarity >= minSimilarity) {
|
|
209
|
+
const duplicate = {
|
|
210
|
+
file1: block1.file,
|
|
211
|
+
file2: block2.file,
|
|
212
|
+
line1: block1.startLine,
|
|
213
|
+
line2: block2.startLine,
|
|
214
|
+
endLine1: block1.endLine,
|
|
215
|
+
endLine2: block2.endLine,
|
|
216
|
+
similarity,
|
|
217
|
+
snippet: block1.content.split("\n").slice(0, 5).join("\n") + "\n...",
|
|
218
|
+
patternType: block1.patternType,
|
|
219
|
+
tokenCost: block1.tokenCost + block2.tokenCost,
|
|
220
|
+
linesOfCode: block1.linesOfCode
|
|
221
|
+
};
|
|
222
|
+
duplicates.push(duplicate);
|
|
223
|
+
if (streamResults) {
|
|
224
|
+
console.log(`
|
|
225
|
+
\u2705 Found: ${duplicate.patternType} ${Math.round(similarity * 100)}% similar`);
|
|
226
|
+
console.log(` ${duplicate.file1}:${duplicate.line1}-${duplicate.endLine1} \u21D4 ${duplicate.file2}:${duplicate.line2}-${duplicate.endLine2}`);
|
|
227
|
+
console.log(` Token cost: ${duplicate.tokenCost.toLocaleString()}`);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
} else {
|
|
232
|
+
for (let j = i + 1; j < allBlocks.length; j++) {
|
|
233
|
+
if (maxComparisons && comparisonsProcessed >= maxComparisons) break;
|
|
234
|
+
comparisonsProcessed++;
|
|
235
|
+
const block2 = allBlocks[j];
|
|
236
|
+
if (block1.file === block2.file) continue;
|
|
237
|
+
const similarity = jaccardSimilarity(blockTokens[i], blockTokens[j]);
|
|
238
|
+
if (similarity >= minSimilarity) {
|
|
239
|
+
const duplicate = {
|
|
240
|
+
file1: block1.file,
|
|
241
|
+
file2: block2.file,
|
|
242
|
+
line1: block1.startLine,
|
|
243
|
+
line2: block2.startLine,
|
|
244
|
+
endLine1: block1.endLine,
|
|
245
|
+
endLine2: block2.endLine,
|
|
246
|
+
similarity,
|
|
247
|
+
snippet: block1.content.split("\n").slice(0, 5).join("\n") + "\n...",
|
|
248
|
+
patternType: block1.patternType,
|
|
249
|
+
tokenCost: block1.tokenCost + block2.tokenCost,
|
|
250
|
+
linesOfCode: block1.linesOfCode
|
|
251
|
+
};
|
|
252
|
+
duplicates.push(duplicate);
|
|
253
|
+
if (streamResults) {
|
|
254
|
+
console.log(`
|
|
255
|
+
\u2705 Found: ${duplicate.patternType} ${Math.round(similarity * 100)}% similar`);
|
|
256
|
+
console.log(` ${duplicate.file1}:${duplicate.line1}-${duplicate.endLine1} \u21D4 ${duplicate.file2}:${duplicate.line2}-${duplicate.endLine2}`);
|
|
257
|
+
console.log(` Token cost: ${duplicate.tokenCost.toLocaleString()}`);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
if (comparisonsBudgetExhausted) {
|
|
264
|
+
console.log(`\u26A0\uFE0F Comparison budget exhausted (${maxComparisons.toLocaleString()} comparisons). Use --max-comparisons to increase.`);
|
|
265
|
+
}
|
|
266
|
+
return duplicates.sort(
|
|
267
|
+
(a, b) => b.similarity - a.similarity || b.tokenCost - a.tokenCost
|
|
268
|
+
);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// src/index.ts
|
|
272
|
+
function getRefactoringSuggestion(patternType, similarity) {
|
|
273
|
+
const baseMessages = {
|
|
274
|
+
"api-handler": "Extract common middleware or create a base handler class",
|
|
275
|
+
validator: "Consolidate validation logic into shared schema validators (Zod/Yup)",
|
|
276
|
+
utility: "Move to a shared utilities file and reuse across modules",
|
|
277
|
+
"class-method": "Consider inheritance or composition to share behavior",
|
|
278
|
+
component: "Extract shared logic into a custom hook or HOC",
|
|
279
|
+
function: "Extract into a shared helper function",
|
|
280
|
+
unknown: "Extract common logic into a reusable module"
|
|
281
|
+
};
|
|
282
|
+
const urgency = similarity > 0.95 ? " (CRITICAL: Nearly identical code)" : similarity > 0.9 ? " (HIGH: Very similar, refactor soon)" : "";
|
|
283
|
+
return baseMessages[patternType] + urgency;
|
|
284
|
+
}
|
|
285
|
+
async function getSmartDefaults(directory, userOptions) {
|
|
286
|
+
if (userOptions.useSmartDefaults === false) {
|
|
287
|
+
return {};
|
|
288
|
+
}
|
|
289
|
+
const scanOptions = {
|
|
290
|
+
rootDir: directory,
|
|
291
|
+
include: userOptions.include || ["**/*.{ts,tsx,js,jsx,py,java}"],
|
|
292
|
+
exclude: userOptions.exclude || [
|
|
293
|
+
"**/node_modules/**",
|
|
294
|
+
"**/dist/**",
|
|
295
|
+
"**/build/**",
|
|
296
|
+
"**/coverage/**",
|
|
297
|
+
"**/.git/**",
|
|
298
|
+
"**/.turbo/**"
|
|
299
|
+
]
|
|
300
|
+
};
|
|
301
|
+
const { scanFiles: scanFiles2 } = await import("@aiready/core");
|
|
302
|
+
const files = await scanFiles2(scanOptions);
|
|
303
|
+
const estimatedBlocks = files.length * 3;
|
|
304
|
+
let smartDefaults = {};
|
|
305
|
+
if (estimatedBlocks < 1e3) {
|
|
306
|
+
smartDefaults = {
|
|
307
|
+
minSimilarity: 0.4,
|
|
308
|
+
minLines: 5,
|
|
309
|
+
batchSize: 100,
|
|
310
|
+
approx: true,
|
|
311
|
+
minSharedTokens: 8,
|
|
312
|
+
maxCandidatesPerBlock: 100,
|
|
313
|
+
severity: "all"
|
|
314
|
+
};
|
|
315
|
+
} else if (estimatedBlocks < 5e3) {
|
|
316
|
+
smartDefaults = {
|
|
317
|
+
minSimilarity: 0.5,
|
|
318
|
+
minLines: 6,
|
|
319
|
+
batchSize: 200,
|
|
320
|
+
// Increased batch size for better performance
|
|
321
|
+
approx: true,
|
|
322
|
+
minSharedTokens: 12,
|
|
323
|
+
// Increased to reduce candidates
|
|
324
|
+
maxCandidatesPerBlock: 30,
|
|
325
|
+
// Reduced for faster processing
|
|
326
|
+
severity: "all"
|
|
327
|
+
};
|
|
328
|
+
} else {
|
|
329
|
+
smartDefaults = {
|
|
330
|
+
minSimilarity: 0.6,
|
|
331
|
+
minLines: 8,
|
|
332
|
+
batchSize: 200,
|
|
333
|
+
approx: true,
|
|
334
|
+
minSharedTokens: 12,
|
|
335
|
+
maxCandidatesPerBlock: 25,
|
|
336
|
+
severity: "high"
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
const result = {};
|
|
340
|
+
for (const [key, value] of Object.entries(smartDefaults)) {
|
|
341
|
+
if (!(key in userOptions) || userOptions[key] === void 0) {
|
|
342
|
+
result[key] = value;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return result;
|
|
346
|
+
}
|
|
347
|
+
function logConfiguration(config, estimatedBlocks) {
|
|
348
|
+
console.log("\u{1F4CB} Configuration:");
|
|
349
|
+
console.log(` Repository size: ~${estimatedBlocks} code blocks`);
|
|
350
|
+
console.log(` Similarity threshold: ${config.minSimilarity}`);
|
|
351
|
+
console.log(` Minimum lines: ${config.minLines}`);
|
|
352
|
+
console.log(` Approximate mode: ${config.approx ? "enabled" : "disabled"}`);
|
|
353
|
+
console.log(` Max candidates per block: ${config.maxCandidatesPerBlock}`);
|
|
354
|
+
console.log(` Min shared tokens: ${config.minSharedTokens}`);
|
|
355
|
+
console.log(` Severity filter: ${config.severity}`);
|
|
356
|
+
console.log(` Include tests: ${config.includeTests}`);
|
|
357
|
+
console.log("");
|
|
358
|
+
}
|
|
359
|
+
async function analyzePatterns(options) {
|
|
360
|
+
const smartDefaults = await getSmartDefaults(options.rootDir || ".", options);
|
|
361
|
+
const finalOptions = { ...smartDefaults, ...options };
|
|
362
|
+
const {
|
|
363
|
+
minSimilarity = 0.4,
|
|
364
|
+
minLines = 5,
|
|
365
|
+
batchSize = 100,
|
|
366
|
+
approx = true,
|
|
367
|
+
minSharedTokens = 8,
|
|
368
|
+
maxCandidatesPerBlock = 100,
|
|
369
|
+
streamResults = false,
|
|
370
|
+
severity = "all",
|
|
371
|
+
includeTests = false,
|
|
372
|
+
...scanOptions
|
|
373
|
+
} = finalOptions;
|
|
374
|
+
const { scanFiles: scanFiles2 } = await import("@aiready/core");
|
|
375
|
+
const files = await scanFiles2(scanOptions);
|
|
376
|
+
const estimatedBlocks = files.length * 3;
|
|
377
|
+
logConfiguration(finalOptions, estimatedBlocks);
|
|
378
|
+
const results = [];
|
|
379
|
+
const fileContents = await Promise.all(
|
|
380
|
+
files.map(async (file) => ({
|
|
381
|
+
file,
|
|
382
|
+
content: await readFileContent(file)
|
|
383
|
+
}))
|
|
384
|
+
);
|
|
385
|
+
const duplicates = await detectDuplicatePatterns(fileContents, {
|
|
386
|
+
minSimilarity,
|
|
387
|
+
minLines,
|
|
388
|
+
batchSize,
|
|
389
|
+
approx,
|
|
390
|
+
minSharedTokens,
|
|
391
|
+
maxCandidatesPerBlock,
|
|
392
|
+
streamResults
|
|
393
|
+
});
|
|
394
|
+
for (const file of files) {
|
|
395
|
+
const fileDuplicates = duplicates.filter(
|
|
396
|
+
(dup) => dup.file1 === file || dup.file2 === file
|
|
397
|
+
);
|
|
398
|
+
const issues = fileDuplicates.map((dup) => {
|
|
399
|
+
const otherFile = dup.file1 === file ? dup.file2 : dup.file1;
|
|
400
|
+
const severity2 = dup.similarity > 0.95 ? "critical" : dup.similarity > 0.9 ? "major" : "minor";
|
|
401
|
+
return {
|
|
402
|
+
type: "duplicate-pattern",
|
|
403
|
+
severity: severity2,
|
|
404
|
+
message: `${dup.patternType} pattern ${Math.round(dup.similarity * 100)}% similar to ${otherFile} (${dup.tokenCost} tokens wasted)`,
|
|
405
|
+
location: {
|
|
406
|
+
file,
|
|
407
|
+
line: dup.file1 === file ? dup.line1 : dup.line2
|
|
408
|
+
},
|
|
409
|
+
suggestion: getRefactoringSuggestion(dup.patternType, dup.similarity)
|
|
410
|
+
};
|
|
411
|
+
});
|
|
412
|
+
let filteredIssues = issues;
|
|
413
|
+
if (severity !== "all") {
|
|
414
|
+
const severityMap = {
|
|
415
|
+
critical: ["critical"],
|
|
416
|
+
high: ["critical", "major"],
|
|
417
|
+
medium: ["critical", "major", "minor"]
|
|
418
|
+
};
|
|
419
|
+
const allowedSeverities = severityMap[severity] || ["critical", "major", "minor"];
|
|
420
|
+
filteredIssues = issues.filter((issue) => allowedSeverities.includes(issue.severity));
|
|
421
|
+
}
|
|
422
|
+
const totalTokenCost = fileDuplicates.reduce(
|
|
423
|
+
(sum, dup) => sum + dup.tokenCost,
|
|
424
|
+
0
|
|
425
|
+
);
|
|
426
|
+
results.push({
|
|
427
|
+
fileName: file,
|
|
428
|
+
issues: filteredIssues,
|
|
429
|
+
metrics: {
|
|
430
|
+
tokenCost: totalTokenCost,
|
|
431
|
+
consistencyScore: Math.max(0, 1 - fileDuplicates.length * 0.1)
|
|
432
|
+
}
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
return { results, duplicates, files };
|
|
436
|
+
}
|
|
437
|
+
function generateSummary(results) {
|
|
438
|
+
const allIssues = results.flatMap((r) => r.issues);
|
|
439
|
+
const totalTokenCost = results.reduce(
|
|
440
|
+
(sum, r) => sum + (r.metrics.tokenCost || 0),
|
|
441
|
+
0
|
|
442
|
+
);
|
|
443
|
+
const patternsByType = {
|
|
444
|
+
"api-handler": 0,
|
|
445
|
+
validator: 0,
|
|
446
|
+
utility: 0,
|
|
447
|
+
"class-method": 0,
|
|
448
|
+
component: 0,
|
|
449
|
+
function: 0,
|
|
450
|
+
unknown: 0
|
|
451
|
+
};
|
|
452
|
+
allIssues.forEach((issue) => {
|
|
453
|
+
const match = issue.message.match(/^(\S+(?:-\S+)*) pattern/);
|
|
454
|
+
if (match) {
|
|
455
|
+
const type = match[1];
|
|
456
|
+
patternsByType[type] = (patternsByType[type] || 0) + 1;
|
|
457
|
+
}
|
|
458
|
+
});
|
|
459
|
+
const topDuplicates = allIssues.slice(0, 10).map((issue) => {
|
|
460
|
+
const similarityMatch = issue.message.match(/(\d+)% similar/);
|
|
461
|
+
const tokenMatch = issue.message.match(/\((\d+) tokens/);
|
|
462
|
+
const typeMatch = issue.message.match(/^(\S+(?:-\S+)*) pattern/);
|
|
463
|
+
const fileMatch = issue.message.match(/similar to (.+?) \(/);
|
|
464
|
+
return {
|
|
465
|
+
files: [
|
|
466
|
+
{
|
|
467
|
+
path: issue.location.file,
|
|
468
|
+
startLine: issue.location.line,
|
|
469
|
+
endLine: 0
|
|
470
|
+
// Not available from Issue
|
|
471
|
+
},
|
|
472
|
+
{
|
|
473
|
+
path: fileMatch?.[1] || "unknown",
|
|
474
|
+
startLine: 0,
|
|
475
|
+
// Not available from Issue
|
|
476
|
+
endLine: 0
|
|
477
|
+
// Not available from Issue
|
|
478
|
+
}
|
|
479
|
+
],
|
|
480
|
+
similarity: similarityMatch ? parseInt(similarityMatch[1]) / 100 : 0,
|
|
481
|
+
patternType: typeMatch?.[1] || "unknown",
|
|
482
|
+
tokenCost: tokenMatch ? parseInt(tokenMatch[1]) : 0
|
|
483
|
+
};
|
|
484
|
+
});
|
|
485
|
+
return {
|
|
486
|
+
totalPatterns: allIssues.length,
|
|
487
|
+
totalTokenCost,
|
|
488
|
+
patternsByType,
|
|
489
|
+
topDuplicates
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
export {
|
|
494
|
+
detectDuplicatePatterns,
|
|
495
|
+
analyzePatterns,
|
|
496
|
+
generateSummary
|
|
497
|
+
};
|