@aiready/pattern-detect 0.16.12 → 0.16.14

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