@aiready/pattern-detect 0.16.22 → 0.16.23

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.
Files changed (35) hide show
  1. package/dist/analyzer-entry/index.mjs +3 -3
  2. package/dist/chunk-J2G742QF.mjs +162 -0
  3. package/dist/chunk-J5CW6NYY.mjs +64 -0
  4. package/dist/chunk-NQBYYWHJ.mjs +143 -0
  5. package/dist/chunk-SUUZMLPS.mjs +391 -0
  6. package/dist/cli.js +336 -303
  7. package/dist/cli.mjs +347 -303
  8. package/dist/context-rules-entry/index.d.mts +2 -2
  9. package/dist/context-rules-entry/index.d.ts +2 -2
  10. package/dist/context-rules-entry/index.js +2 -25
  11. package/dist/context-rules-entry/index.mjs +1 -1
  12. package/dist/detector-entry/index.mjs +2 -2
  13. package/dist/index-szjQDBsm.d.mts +49 -0
  14. package/dist/index-szjQDBsm.d.ts +49 -0
  15. package/dist/index.d.mts +2 -2
  16. package/dist/index.d.ts +2 -2
  17. package/dist/index.js +4 -25
  18. package/dist/index.mjs +6 -4
  19. package/package.json +2 -2
  20. package/dist/__tests__/context-rules.test.d.ts +0 -2
  21. package/dist/__tests__/context-rules.test.d.ts.map +0 -1
  22. package/dist/__tests__/context-rules.test.js +0 -189
  23. package/dist/__tests__/context-rules.test.js.map +0 -1
  24. package/dist/__tests__/detector.test.d.ts +0 -2
  25. package/dist/__tests__/detector.test.d.ts.map +0 -1
  26. package/dist/__tests__/detector.test.js +0 -259
  27. package/dist/__tests__/detector.test.js.map +0 -1
  28. package/dist/__tests__/grouping.test.d.ts +0 -2
  29. package/dist/__tests__/grouping.test.d.ts.map +0 -1
  30. package/dist/__tests__/grouping.test.js +0 -443
  31. package/dist/__tests__/grouping.test.js.map +0 -1
  32. package/dist/__tests__/scoring.test.d.ts +0 -2
  33. package/dist/__tests__/scoring.test.d.ts.map +0 -1
  34. package/dist/__tests__/scoring.test.js +0 -102
  35. package/dist/__tests__/scoring.test.js.map +0 -1
@@ -2,9 +2,9 @@ import {
2
2
  analyzePatterns,
3
3
  generateSummary,
4
4
  getSmartDefaults
5
- } from "../chunk-DNZS4ESD.mjs";
6
- import "../chunk-VGMM3L3O.mjs";
7
- import "../chunk-I6ETJC7L.mjs";
5
+ } from "../chunk-SUUZMLPS.mjs";
6
+ import "../chunk-NQBYYWHJ.mjs";
7
+ import "../chunk-J2G742QF.mjs";
8
8
  export {
9
9
  analyzePatterns,
10
10
  generateSummary,
@@ -0,0 +1,162 @@
1
+ // src/context-rules.ts
2
+ import {
3
+ IssueType,
4
+ getSeverityLabel,
5
+ filterBySeverity,
6
+ Severity
7
+ } from "@aiready/core";
8
+ var CONTEXT_RULES = [
9
+ // Test Fixtures - Intentional duplication for test isolation
10
+ {
11
+ name: "test-fixtures",
12
+ detect: (file, code) => {
13
+ const isTestFile = file.includes(".test.") || file.includes(".spec.") || file.includes("__tests__") || file.includes("/test/") || file.includes("/tests/");
14
+ const hasTestFixtures = code.includes("beforeAll") || code.includes("afterAll") || code.includes("beforeEach") || code.includes("afterEach") || code.includes("setUp") || code.includes("tearDown");
15
+ return isTestFile && hasTestFixtures;
16
+ },
17
+ severity: Severity.Info,
18
+ reason: "Test fixture duplication is intentional for test isolation",
19
+ suggestion: "Consider if shared test setup would improve maintainability without coupling tests"
20
+ },
21
+ // Email/Document Templates - Often intentionally similar for consistency
22
+ {
23
+ name: "templates",
24
+ detect: (file, code) => {
25
+ const isTemplate = file.includes("/templates/") || file.includes("-template") || file.includes("/email-templates/") || file.includes("/emails/");
26
+ const hasTemplateContent = (code.includes("return") || code.includes("export")) && (code.includes("html") || code.includes("subject") || code.includes("body"));
27
+ return isTemplate && hasTemplateContent;
28
+ },
29
+ severity: Severity.Minor,
30
+ reason: "Template duplication may be intentional for maintainability and branding consistency",
31
+ suggestion: "Extract shared structure only if templates become hard to maintain"
32
+ },
33
+ // E2E/Integration Test Page Objects - Test independence
34
+ {
35
+ name: "e2e-page-objects",
36
+ detect: (file, code) => {
37
+ 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/");
38
+ const hasPageObjectPatterns = code.includes("page.") || code.includes("await page") || code.includes("locator") || code.includes("getBy") || code.includes("selector") || code.includes("click(") || code.includes("fill(");
39
+ return isE2ETest && hasPageObjectPatterns;
40
+ },
41
+ severity: Severity.Minor,
42
+ reason: "E2E test duplication ensures test independence and reduces coupling",
43
+ suggestion: "Consider page object pattern only if duplication causes maintenance issues"
44
+ },
45
+ // Configuration Files - Often necessarily similar by design
46
+ {
47
+ name: "config-files",
48
+ detect: (file) => {
49
+ 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");
50
+ },
51
+ severity: Severity.Minor,
52
+ reason: "Configuration files often have similar structure by design",
53
+ suggestion: "Consider shared config base only if configurations become hard to maintain"
54
+ },
55
+ // Type Definitions - Duplication for type safety and module independence
56
+ {
57
+ name: "type-definitions",
58
+ detect: (file, code) => {
59
+ const isTypeFile = file.endsWith(".d.ts") || file.includes("/types/");
60
+ const hasTypeDefinitions = code.includes("interface ") || code.includes("type ") || code.includes("enum ");
61
+ return isTypeFile && hasTypeDefinitions;
62
+ },
63
+ severity: Severity.Info,
64
+ reason: "Type duplication may be intentional for module independence and type safety",
65
+ suggestion: "Extract to shared types package only if causing maintenance burden"
66
+ },
67
+ // Migration Scripts - One-off scripts that are similar by nature
68
+ {
69
+ name: "migration-scripts",
70
+ detect: (file) => {
71
+ return file.includes("/migrations/") || file.includes("/migrate/") || file.includes(".migration.");
72
+ },
73
+ severity: Severity.Info,
74
+ reason: "Migration scripts are typically one-off and intentionally similar",
75
+ suggestion: "Duplication is acceptable for migration scripts"
76
+ },
77
+ // Mock Data - Test data intentionally duplicated
78
+ {
79
+ name: "mock-data",
80
+ detect: (file, code) => {
81
+ const isMockFile = file.includes("/mocks/") || file.includes("/__mocks__/") || file.includes("/fixtures/") || file.includes(".mock.") || file.includes(".fixture.");
82
+ const hasMockData = code.includes("mock") || code.includes("Mock") || code.includes("fixture") || code.includes("stub") || code.includes("export const");
83
+ return isMockFile && hasMockData;
84
+ },
85
+ severity: Severity.Info,
86
+ reason: "Mock data duplication is expected for comprehensive test coverage",
87
+ suggestion: "Consider shared factories only for complex mock generation"
88
+ },
89
+ // Tool Implementations - Structural Boilerplate
90
+ {
91
+ name: "tool-implementations",
92
+ detect: (file, code) => {
93
+ const isToolFile = file.includes("/tools/") || file.endsWith(".tool.ts") || code.includes("toolDefinitions");
94
+ const hasToolStructure = code.includes("execute") && (code.includes("try") || code.includes("catch"));
95
+ return isToolFile && hasToolStructure;
96
+ },
97
+ severity: Severity.Info,
98
+ reason: "Tool implementations share structural boilerplate but have distinct business logic",
99
+ suggestion: "Tool duplication is acceptable for boilerplate interface wrappers"
100
+ }
101
+ ];
102
+ function calculateSeverity(file1, file2, code, similarity, linesOfCode) {
103
+ for (const rule of CONTEXT_RULES) {
104
+ if (rule.detect(file1, code) || rule.detect(file2, code)) {
105
+ return {
106
+ severity: rule.severity,
107
+ reason: rule.reason,
108
+ suggestion: rule.suggestion,
109
+ matchedRule: rule.name
110
+ };
111
+ }
112
+ }
113
+ if (similarity >= 0.95 && linesOfCode >= 30) {
114
+ return {
115
+ severity: Severity.Critical,
116
+ reason: "Large nearly-identical code blocks waste tokens and create maintenance burden",
117
+ suggestion: "Extract to shared utility module immediately"
118
+ };
119
+ } else if (similarity >= 0.95 && linesOfCode >= 15) {
120
+ return {
121
+ severity: Severity.Major,
122
+ reason: "Nearly identical code should be consolidated",
123
+ suggestion: "Move to shared utility file"
124
+ };
125
+ } else if (similarity >= 0.85) {
126
+ return {
127
+ severity: Severity.Major,
128
+ reason: "High similarity indicates significant duplication",
129
+ suggestion: "Extract common logic to shared function"
130
+ };
131
+ } else if (similarity >= 0.7) {
132
+ return {
133
+ severity: Severity.Minor,
134
+ reason: "Moderate similarity detected",
135
+ suggestion: "Consider extracting shared patterns if code evolves together"
136
+ };
137
+ } else {
138
+ return {
139
+ severity: Severity.Minor,
140
+ reason: "Minor similarity detected",
141
+ suggestion: "Monitor but refactoring may not be worthwhile"
142
+ };
143
+ }
144
+ }
145
+ function getSeverityThreshold(severity) {
146
+ const thresholds = {
147
+ [Severity.Critical]: 0.95,
148
+ [Severity.Major]: 0.85,
149
+ [Severity.Minor]: 0.5,
150
+ [Severity.Info]: 0
151
+ };
152
+ return thresholds[severity] || 0;
153
+ }
154
+
155
+ export {
156
+ IssueType,
157
+ getSeverityLabel,
158
+ filterBySeverity,
159
+ CONTEXT_RULES,
160
+ calculateSeverity,
161
+ getSeverityThreshold
162
+ };
@@ -0,0 +1,64 @@
1
+ import {
2
+ analyzePatterns
3
+ } from "./chunk-SUUZMLPS.mjs";
4
+ import {
5
+ calculatePatternScore
6
+ } from "./chunk-WBBO35SC.mjs";
7
+
8
+ // src/index.ts
9
+ import { ToolRegistry, Severity } from "@aiready/core";
10
+
11
+ // src/provider.ts
12
+ import {
13
+ ToolName,
14
+ SpokeOutputSchema,
15
+ GLOBAL_SCAN_OPTIONS
16
+ } from "@aiready/core";
17
+ var PatternDetectProvider = {
18
+ id: ToolName.PatternDetect,
19
+ alias: ["patterns", "duplicates", "duplication"],
20
+ async analyze(options) {
21
+ const results = await analyzePatterns(options);
22
+ return SpokeOutputSchema.parse({
23
+ results: results.results,
24
+ summary: {
25
+ totalFiles: results.files.length,
26
+ totalIssues: results.results.reduce(
27
+ (sum, r) => sum + r.issues.length,
28
+ 0
29
+ ),
30
+ duplicates: results.duplicates,
31
+ // Keep the raw duplicates for score calculation
32
+ clusters: results.clusters,
33
+ config: Object.fromEntries(
34
+ Object.entries(results.config).filter(
35
+ ([key]) => !GLOBAL_SCAN_OPTIONS.includes(key) || key === "rootDir"
36
+ )
37
+ )
38
+ },
39
+ metadata: {
40
+ toolName: ToolName.PatternDetect,
41
+ version: "0.12.5",
42
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
43
+ }
44
+ });
45
+ },
46
+ score(output, options) {
47
+ const duplicates = output.summary.duplicates || [];
48
+ const totalFiles = output.summary.totalFiles || output.results.length;
49
+ return calculatePatternScore(
50
+ duplicates,
51
+ totalFiles,
52
+ options.costConfig
53
+ );
54
+ },
55
+ defaultWeight: 22
56
+ };
57
+
58
+ // src/index.ts
59
+ ToolRegistry.register(PatternDetectProvider);
60
+
61
+ export {
62
+ PatternDetectProvider,
63
+ Severity
64
+ };
@@ -0,0 +1,143 @@
1
+ import {
2
+ calculateSeverity
3
+ } from "./chunk-J2G742QF.mjs";
4
+
5
+ // src/detector.ts
6
+ import {
7
+ calculateStringSimilarity,
8
+ calculateHeuristicConfidence,
9
+ extractCodeBlocks
10
+ } from "@aiready/core";
11
+
12
+ // src/core/normalizer.ts
13
+ function normalizeCode(code, isPython = false) {
14
+ if (!code) return "";
15
+ let normalized = code;
16
+ if (isPython) {
17
+ normalized = normalized.replace(/#.*/g, "");
18
+ } else {
19
+ normalized = normalized.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "");
20
+ }
21
+ return normalized.replace(/"[^"]*"/g, '"STR"').replace(/'[^']*'/g, "'STR'").replace(/`[^`]*`/g, "`STR`").replace(/\b\d+\b/g, "NUM").replace(/\s+/g, " ").trim().toLowerCase();
22
+ }
23
+
24
+ // src/detector.ts
25
+ function extractBlocks(file, content) {
26
+ return extractCodeBlocks(file, content);
27
+ }
28
+ function calculateSimilarity(a, b) {
29
+ return calculateStringSimilarity(a, b);
30
+ }
31
+ function calculateConfidence(similarity, tokens, lines) {
32
+ return calculateHeuristicConfidence(similarity, tokens, lines);
33
+ }
34
+ async function detectDuplicatePatterns(fileContents, options) {
35
+ const {
36
+ minSimilarity,
37
+ minLines,
38
+ streamResults,
39
+ onProgress,
40
+ excludePatterns = [],
41
+ confidenceThreshold = 0,
42
+ ignoreWhitelist = []
43
+ } = options;
44
+ const allBlocks = [];
45
+ const excludeRegexes = excludePatterns.map((p) => new RegExp(p, "i"));
46
+ for (const { file, content } of fileContents) {
47
+ const blocks = extractBlocks(file, content);
48
+ for (const b of blocks) {
49
+ if (b.endLine - b.startLine + 1 < minLines) continue;
50
+ const isExcluded = excludeRegexes.some((regex) => regex.test(b.code));
51
+ if (isExcluded) continue;
52
+ allBlocks.push(b);
53
+ }
54
+ }
55
+ const duplicates = [];
56
+ const totalBlocks = allBlocks.length;
57
+ let comparisons = 0;
58
+ const totalComparisons = totalBlocks * (totalBlocks - 1) / 2;
59
+ if (onProgress) {
60
+ onProgress(
61
+ 0,
62
+ totalComparisons,
63
+ `Starting duplicate detection on ${totalBlocks} blocks...`
64
+ );
65
+ }
66
+ for (let i = 0; i < allBlocks.length; i++) {
67
+ if (i % 50 === 0 && i > 0) {
68
+ await new Promise((resolve) => setImmediate(resolve));
69
+ if (onProgress) {
70
+ onProgress(
71
+ comparisons,
72
+ totalComparisons,
73
+ `Analyzing blocks (${i}/${totalBlocks})...`
74
+ );
75
+ }
76
+ }
77
+ const b1 = allBlocks[i];
78
+ const isPython1 = b1.file.toLowerCase().endsWith(".py");
79
+ const norm1 = normalizeCode(b1.code, isPython1);
80
+ for (let j = i + 1; j < allBlocks.length; j++) {
81
+ comparisons++;
82
+ const b2 = allBlocks[j];
83
+ if (b1.file === b2.file) continue;
84
+ const isWhitelisted = ignoreWhitelist.some((pattern) => {
85
+ return b1.file.includes(pattern) && b2.file.includes(pattern) || pattern === `${b1.file}::${b2.file}` || pattern === `${b2.file}::${b1.file}`;
86
+ });
87
+ if (isWhitelisted) continue;
88
+ const isPython2 = b2.file.toLowerCase().endsWith(".py");
89
+ const norm2 = normalizeCode(b2.code, isPython2);
90
+ const sim = calculateSimilarity(norm1, norm2);
91
+ if (sim >= minSimilarity) {
92
+ const confidence = calculateConfidence(
93
+ sim,
94
+ b1.tokens,
95
+ b1.endLine - b1.startLine + 1
96
+ );
97
+ if (confidence < confidenceThreshold) continue;
98
+ const { severity, reason, suggestion, matchedRule } = calculateSeverity(
99
+ b1.file,
100
+ b2.file,
101
+ b1.code,
102
+ sim,
103
+ b1.endLine - b1.startLine + 1
104
+ );
105
+ const dup = {
106
+ file1: b1.file,
107
+ line1: b1.startLine,
108
+ endLine1: b1.endLine,
109
+ file2: b2.file,
110
+ line2: b2.startLine,
111
+ endLine2: b2.endLine,
112
+ code1: b1.code,
113
+ code2: b2.code,
114
+ similarity: sim,
115
+ confidence,
116
+ patternType: b1.patternType,
117
+ tokenCost: b1.tokens + b2.tokens,
118
+ severity,
119
+ reason,
120
+ suggestion,
121
+ matchedRule
122
+ };
123
+ duplicates.push(dup);
124
+ if (streamResults)
125
+ console.log(
126
+ `[DUPLICATE] ${dup.file1}:${dup.line1} <-> ${dup.file2}:${dup.line2} (${Math.round(sim * 100)}%, conf: ${Math.round(confidence * 100)}%)`
127
+ );
128
+ }
129
+ }
130
+ }
131
+ if (onProgress) {
132
+ onProgress(
133
+ totalComparisons,
134
+ totalComparisons,
135
+ `Duplicate detection complete. Found ${duplicates.length} patterns.`
136
+ );
137
+ }
138
+ return duplicates.sort((a, b) => b.similarity - a.similarity);
139
+ }
140
+
141
+ export {
142
+ detectDuplicatePatterns
143
+ };