@angular-modernizer/adapter-mcp 0.1.1
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/LICENSE +21 -0
- package/README.md +917 -0
- package/dist/cli.d.ts +8 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +129 -0
- package/dist/cli.js.map +1 -0
- package/dist/core/project-analyzer.d.ts +59 -0
- package/dist/core/project-analyzer.d.ts.map +1 -0
- package/dist/core/project-analyzer.js +116 -0
- package/dist/core/project-analyzer.js.map +1 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +51 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp-watcher.d.ts +119 -0
- package/dist/mcp-watcher.d.ts.map +1 -0
- package/dist/mcp-watcher.js +380 -0
- package/dist/mcp-watcher.js.map +1 -0
- package/dist/server/json-rpc-handler.d.ts +57 -0
- package/dist/server/json-rpc-handler.d.ts.map +1 -0
- package/dist/server/json-rpc-handler.js +222 -0
- package/dist/server/json-rpc-handler.js.map +1 -0
- package/dist/server/mcp-server.d.ts +62 -0
- package/dist/server/mcp-server.d.ts.map +1 -0
- package/dist/server/mcp-server.js +184 -0
- package/dist/server/mcp-server.js.map +1 -0
- package/dist/server/tool-registry.d.ts +73 -0
- package/dist/server/tool-registry.d.ts.map +1 -0
- package/dist/server/tool-registry.js +102 -0
- package/dist/server/tool-registry.js.map +1 -0
- package/dist/streaming/progress-store.d.ts +120 -0
- package/dist/streaming/progress-store.d.ts.map +1 -0
- package/dist/streaming/progress-store.js +238 -0
- package/dist/streaming/progress-store.js.map +1 -0
- package/dist/tools/analyze-build-impact.d.ts +127 -0
- package/dist/tools/analyze-build-impact.d.ts.map +1 -0
- package/dist/tools/analyze-build-impact.js +194 -0
- package/dist/tools/analyze-build-impact.js.map +1 -0
- package/dist/tools/analyze-core-to-shared.d.ts +163 -0
- package/dist/tools/analyze-core-to-shared.d.ts.map +1 -0
- package/dist/tools/analyze-core-to-shared.js +436 -0
- package/dist/tools/analyze-core-to-shared.js.map +1 -0
- package/dist/tools/analyze-parser-performance.d.ts +105 -0
- package/dist/tools/analyze-parser-performance.d.ts.map +1 -0
- package/dist/tools/analyze-parser-performance.js +313 -0
- package/dist/tools/analyze-parser-performance.js.map +1 -0
- package/dist/tools/analyze-project.d.ts +277 -0
- package/dist/tools/analyze-project.d.ts.map +1 -0
- package/dist/tools/analyze-project.js +946 -0
- package/dist/tools/analyze-project.js.map +1 -0
- package/dist/tools/check-incremental-compatibility.d.ts +109 -0
- package/dist/tools/check-incremental-compatibility.d.ts.map +1 -0
- package/dist/tools/check-incremental-compatibility.js +302 -0
- package/dist/tools/check-incremental-compatibility.js.map +1 -0
- package/dist/tools/collect-feedback.d.ts +117 -0
- package/dist/tools/collect-feedback.d.ts.map +1 -0
- package/dist/tools/collect-feedback.js +773 -0
- package/dist/tools/collect-feedback.js.map +1 -0
- package/dist/tools/extract-libraries.d.ts +121 -0
- package/dist/tools/extract-libraries.d.ts.map +1 -0
- package/dist/tools/extract-libraries.js +223 -0
- package/dist/tools/extract-libraries.js.map +1 -0
- package/dist/tools/find-angular-symbol.d.ts +55 -0
- package/dist/tools/find-angular-symbol.d.ts.map +1 -0
- package/dist/tools/find-angular-symbol.js +104 -0
- package/dist/tools/find-angular-symbol.js.map +1 -0
- package/dist/tools/find-usages.d.ts +65 -0
- package/dist/tools/find-usages.d.ts.map +1 -0
- package/dist/tools/find-usages.js +108 -0
- package/dist/tools/find-usages.js.map +1 -0
- package/dist/tools/get-call-graph.d.ts +61 -0
- package/dist/tools/get-call-graph.d.ts.map +1 -0
- package/dist/tools/get-call-graph.js +119 -0
- package/dist/tools/get-call-graph.js.map +1 -0
- package/dist/tools/get-operation-progress-tool.d.ts +29 -0
- package/dist/tools/get-operation-progress-tool.d.ts.map +1 -0
- package/dist/tools/get-operation-progress-tool.js +36 -0
- package/dist/tools/get-operation-progress-tool.js.map +1 -0
- package/dist/tools/get-operation-progress.d.ts +51 -0
- package/dist/tools/get-operation-progress.d.ts.map +1 -0
- package/dist/tools/get-operation-progress.js +93 -0
- package/dist/tools/get-operation-progress.js.map +1 -0
- package/dist/tools/helpers/feedback-analyzer.d.ts +43 -0
- package/dist/tools/helpers/feedback-analyzer.d.ts.map +1 -0
- package/dist/tools/helpers/feedback-analyzer.js +196 -0
- package/dist/tools/helpers/feedback-analyzer.js.map +1 -0
- package/dist/tools/helpers/find-ts-config.d.ts +10 -0
- package/dist/tools/helpers/find-ts-config.d.ts.map +1 -0
- package/dist/tools/helpers/find-ts-config.js +32 -0
- package/dist/tools/helpers/find-ts-config.js.map +1 -0
- package/dist/tools/helpers/platform-root-resolver.d.ts +33 -0
- package/dist/tools/helpers/platform-root-resolver.d.ts.map +1 -0
- package/dist/tools/helpers/platform-root-resolver.js +60 -0
- package/dist/tools/helpers/platform-root-resolver.js.map +1 -0
- package/dist/tools/helpers/rule-matcher.d.ts +84 -0
- package/dist/tools/helpers/rule-matcher.d.ts.map +1 -0
- package/dist/tools/helpers/rule-matcher.js +212 -0
- package/dist/tools/helpers/rule-matcher.js.map +1 -0
- package/dist/tools/helpers/suggestion-generator.d.ts +66 -0
- package/dist/tools/helpers/suggestion-generator.d.ts.map +1 -0
- package/dist/tools/helpers/suggestion-generator.js +248 -0
- package/dist/tools/helpers/suggestion-generator.js.map +1 -0
- package/dist/tools/learn-patterns.d.ts +368 -0
- package/dist/tools/learn-patterns.d.ts.map +1 -0
- package/dist/tools/learn-patterns.js +1089 -0
- package/dist/tools/learn-patterns.js.map +1 -0
- package/dist/tools/orchestrate-migration.d.ts +187 -0
- package/dist/tools/orchestrate-migration.d.ts.map +1 -0
- package/dist/tools/orchestrate-migration.js +235 -0
- package/dist/tools/orchestrate-migration.js.map +1 -0
- package/dist/tools/parse-stack-trace.d.ts +63 -0
- package/dist/tools/parse-stack-trace.d.ts.map +1 -0
- package/dist/tools/parse-stack-trace.js +92 -0
- package/dist/tools/parse-stack-trace.js.map +1 -0
- package/dist/tools/plan-migration.d.ts +388 -0
- package/dist/tools/plan-migration.d.ts.map +1 -0
- package/dist/tools/plan-migration.js +826 -0
- package/dist/tools/plan-migration.js.map +1 -0
- package/dist/tools/resolve-type.d.ts +54 -0
- package/dist/tools/resolve-type.d.ts.map +1 -0
- package/dist/tools/resolve-type.js +101 -0
- package/dist/tools/resolve-type.js.map +1 -0
- package/dist/tools/review-feedback.d.ts +124 -0
- package/dist/tools/review-feedback.d.ts.map +1 -0
- package/dist/tools/review-feedback.js +276 -0
- package/dist/tools/review-feedback.js.map +1 -0
- package/dist/tools/rollback-changes.d.ts +42 -0
- package/dist/tools/rollback-changes.d.ts.map +1 -0
- package/dist/tools/rollback-changes.js +95 -0
- package/dist/tools/rollback-changes.js.map +1 -0
- package/dist/tools/run-angular-cli.d.ts +102 -0
- package/dist/tools/run-angular-cli.d.ts.map +1 -0
- package/dist/tools/run-angular-cli.js +152 -0
- package/dist/tools/run-angular-cli.js.map +1 -0
- package/dist/tools/run-build.d.ts +201 -0
- package/dist/tools/run-build.d.ts.map +1 -0
- package/dist/tools/run-build.js +554 -0
- package/dist/tools/run-build.js.map +1 -0
- package/dist/tools/run-schematic.d.ts +173 -0
- package/dist/tools/run-schematic.d.ts.map +1 -0
- package/dist/tools/run-schematic.js +410 -0
- package/dist/tools/run-schematic.js.map +1 -0
- package/dist/tools/scan-all.d.ts +160 -0
- package/dist/tools/scan-all.d.ts.map +1 -0
- package/dist/tools/scan-all.js +486 -0
- package/dist/tools/scan-all.js.map +1 -0
- package/dist/tools/scan-angular.d.ts +132 -0
- package/dist/tools/scan-angular.d.ts.map +1 -0
- package/dist/tools/scan-angular.js +411 -0
- package/dist/tools/scan-angular.js.map +1 -0
- package/dist/tools/scan-architecture.d.ts +351 -0
- package/dist/tools/scan-architecture.d.ts.map +1 -0
- package/dist/tools/scan-architecture.js +1290 -0
- package/dist/tools/scan-architecture.js.map +1 -0
- package/dist/tools/scan-solid.d.ts +132 -0
- package/dist/tools/scan-solid.d.ts.map +1 -0
- package/dist/tools/scan-solid.js +435 -0
- package/dist/tools/scan-solid.js.map +1 -0
- package/dist/tools/search-codebase.d.ts +64 -0
- package/dist/tools/search-codebase.d.ts.map +1 -0
- package/dist/tools/search-codebase.js +109 -0
- package/dist/tools/search-codebase.js.map +1 -0
- package/dist/tools/shared/scan-types.d.ts +200 -0
- package/dist/tools/shared/scan-types.d.ts.map +1 -0
- package/dist/tools/shared/scan-types.js +7 -0
- package/dist/tools/shared/scan-types.js.map +1 -0
- package/dist/tools/suggest-improvements.d.ts +96 -0
- package/dist/tools/suggest-improvements.d.ts.map +1 -0
- package/dist/tools/suggest-improvements.js +182 -0
- package/dist/tools/suggest-improvements.js.map +1 -0
- package/dist/tools/transform-code-batch.d.ts +57 -0
- package/dist/tools/transform-code-batch.d.ts.map +1 -0
- package/dist/tools/transform-code-batch.js +107 -0
- package/dist/tools/transform-code-batch.js.map +1 -0
- package/dist/tools/transform-code.d.ts +352 -0
- package/dist/tools/transform-code.d.ts.map +1 -0
- package/dist/tools/transform-code.js +1171 -0
- package/dist/tools/transform-code.js.map +1 -0
- package/dist/tools/validate-before-transform.d.ts +54 -0
- package/dist/tools/validate-before-transform.d.ts.map +1 -0
- package/dist/tools/validate-before-transform.js +141 -0
- package/dist/tools/validate-before-transform.js.map +1 -0
- package/dist/tools/validate-project-compatibility.d.ts +119 -0
- package/dist/tools/validate-project-compatibility.d.ts.map +1 -0
- package/dist/tools/validate-project-compatibility.js +243 -0
- package/dist/tools/validate-project-compatibility.js.map +1 -0
- package/dist/tools/validate-transformation.d.ts +105 -0
- package/dist/tools/validate-transformation.d.ts.map +1 -0
- package/dist/tools/validate-transformation.js +391 -0
- package/dist/tools/validate-transformation.js.map +1 -0
- package/dist/types.d.ts +153 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +38 -0
- package/dist/types.js.map +1 -0
- package/dist/utils/format-tool-response.d.ts +72 -0
- package/dist/utils/format-tool-response.d.ts.map +1 -0
- package/dist/utils/format-tool-response.js +149 -0
- package/dist/utils/format-tool-response.js.map +1 -0
- package/package.json +70 -0
|
@@ -0,0 +1,1089 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @angular-modernizer/adapter-mcp - Learn Patterns Tool
|
|
3
|
+
*
|
|
4
|
+
* MCP tool for discovering and learning patterns from codebases using
|
|
5
|
+
* ML-based pattern recognition. Identifies recurring architectural patterns,
|
|
6
|
+
* anti-patterns, and transformation opportunities.
|
|
7
|
+
*
|
|
8
|
+
* Enhancement: Self-learning with style-aware pattern discovery
|
|
9
|
+
*/
|
|
10
|
+
import { findTsConfig } from './helpers/find-ts-config.js';
|
|
11
|
+
import { Project, SyntaxKind } from 'ts-morph';
|
|
12
|
+
import { writeFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
|
|
13
|
+
import { resolve, dirname } from 'node:path';
|
|
14
|
+
import { PatternKnowledgeBase, StyleConventionDetector, ContextAwareScorer, ContextAwareRuleGenerator, RealFileSystemAdapter, } from '@angular-modernizer/core';
|
|
15
|
+
/**
|
|
16
|
+
* MCP tool for learning patterns from codebases.
|
|
17
|
+
*/
|
|
18
|
+
export class LearnPatternsTool {
|
|
19
|
+
name = 'learn-patterns';
|
|
20
|
+
description = 'Discover and learn patterns from codebases using ML-based pattern recognition with self-learning capabilities. Identifies recurring architectural patterns, anti-patterns, and transformation opportunities while respecting codebase style conventions.';
|
|
21
|
+
inputSchema = {
|
|
22
|
+
type: 'object',
|
|
23
|
+
properties: {
|
|
24
|
+
targetPath: {
|
|
25
|
+
type: 'string',
|
|
26
|
+
description: 'Path to the codebase to learn patterns from',
|
|
27
|
+
},
|
|
28
|
+
categories: {
|
|
29
|
+
type: 'array',
|
|
30
|
+
items: {
|
|
31
|
+
type: 'string',
|
|
32
|
+
enum: [
|
|
33
|
+
'rxjs-patterns',
|
|
34
|
+
'component-patterns',
|
|
35
|
+
'service-patterns',
|
|
36
|
+
'transformation-patterns',
|
|
37
|
+
'architectural-patterns',
|
|
38
|
+
'all',
|
|
39
|
+
],
|
|
40
|
+
},
|
|
41
|
+
default: ['all'],
|
|
42
|
+
description: 'Pattern categories to discover',
|
|
43
|
+
},
|
|
44
|
+
minOccurrences: {
|
|
45
|
+
type: 'number',
|
|
46
|
+
minimum: 1,
|
|
47
|
+
default: 3,
|
|
48
|
+
description: 'Minimum times pattern must appear',
|
|
49
|
+
},
|
|
50
|
+
complexity: {
|
|
51
|
+
type: 'string',
|
|
52
|
+
enum: ['low', 'medium', 'high', 'all'],
|
|
53
|
+
default: 'all',
|
|
54
|
+
description: 'Filter by complexity level',
|
|
55
|
+
},
|
|
56
|
+
outputFormat: {
|
|
57
|
+
type: 'string',
|
|
58
|
+
enum: ['fixtures', 'rules', 'both'],
|
|
59
|
+
default: 'fixtures',
|
|
60
|
+
description: 'Output format for generated artifacts',
|
|
61
|
+
},
|
|
62
|
+
outputPath: {
|
|
63
|
+
type: 'string',
|
|
64
|
+
description: 'Custom output path for generated artifacts',
|
|
65
|
+
},
|
|
66
|
+
anonymizationLevel: {
|
|
67
|
+
type: 'string',
|
|
68
|
+
enum: ['strict', 'moderate', 'minimal'],
|
|
69
|
+
default: 'strict',
|
|
70
|
+
description: 'Anonymization level for patterns',
|
|
71
|
+
},
|
|
72
|
+
validatePatterns: {
|
|
73
|
+
type: 'boolean',
|
|
74
|
+
default: true,
|
|
75
|
+
description: 'Whether to validate discovered patterns',
|
|
76
|
+
},
|
|
77
|
+
crossValidateWithExisting: {
|
|
78
|
+
type: 'boolean',
|
|
79
|
+
default: true,
|
|
80
|
+
description: 'Whether to cross-validate with existing rules',
|
|
81
|
+
},
|
|
82
|
+
// Phase 8: Self-learning options
|
|
83
|
+
enableLearning: {
|
|
84
|
+
type: 'boolean',
|
|
85
|
+
default: true,
|
|
86
|
+
description: 'Enable self-learning: persist patterns for future scans',
|
|
87
|
+
},
|
|
88
|
+
knowledgeBasePath: {
|
|
89
|
+
type: 'string',
|
|
90
|
+
description: 'Path to pattern knowledge base file (default: .angular-modernizer-cache/pattern-knowledge.json)',
|
|
91
|
+
},
|
|
92
|
+
compareWithPreviousScan: {
|
|
93
|
+
type: 'boolean',
|
|
94
|
+
default: true,
|
|
95
|
+
description: 'Compare with previous scan results to track pattern evolution',
|
|
96
|
+
},
|
|
97
|
+
respectCodebaseStyle: {
|
|
98
|
+
type: 'boolean',
|
|
99
|
+
default: true,
|
|
100
|
+
description: 'Align patterns with existing codebase style conventions',
|
|
101
|
+
},
|
|
102
|
+
generateStyleProfile: {
|
|
103
|
+
type: 'boolean',
|
|
104
|
+
default: true,
|
|
105
|
+
description: 'Auto-detect and generate style profile (RxJS, DI, state management)',
|
|
106
|
+
},
|
|
107
|
+
generateRules: {
|
|
108
|
+
type: 'boolean',
|
|
109
|
+
default: false,
|
|
110
|
+
description: 'Generate analysis rules from high-confidence patterns',
|
|
111
|
+
},
|
|
112
|
+
ruleOutputPath: {
|
|
113
|
+
type: 'string',
|
|
114
|
+
description: 'Output path for generated rule files',
|
|
115
|
+
},
|
|
116
|
+
filterRulesByStyle: {
|
|
117
|
+
type: 'boolean',
|
|
118
|
+
default: true,
|
|
119
|
+
description: 'Only generate rules that align with codebase style',
|
|
120
|
+
},
|
|
121
|
+
minConfidence: {
|
|
122
|
+
type: 'number',
|
|
123
|
+
minimum: 0,
|
|
124
|
+
maximum: 1,
|
|
125
|
+
default: 0.6,
|
|
126
|
+
description: 'Minimum confidence threshold for patterns (0.0 - 1.0)',
|
|
127
|
+
},
|
|
128
|
+
orchestration: {
|
|
129
|
+
type: 'object',
|
|
130
|
+
description: 'Orchestration options (subset for pattern discovery)',
|
|
131
|
+
properties: {
|
|
132
|
+
enableProgress: {
|
|
133
|
+
type: 'boolean',
|
|
134
|
+
description: 'Enable real-time progress reporting during pattern discovery',
|
|
135
|
+
default: false,
|
|
136
|
+
},
|
|
137
|
+
maxWorkers: {
|
|
138
|
+
type: 'number',
|
|
139
|
+
description: 'Maximum parallel workers for file analysis',
|
|
140
|
+
},
|
|
141
|
+
resourceLimits: {
|
|
142
|
+
type: 'object',
|
|
143
|
+
description: 'Resource limits for large codebase analysis',
|
|
144
|
+
properties: {
|
|
145
|
+
maxMemoryMB: {
|
|
146
|
+
type: 'number',
|
|
147
|
+
description: 'Maximum memory usage in MB',
|
|
148
|
+
},
|
|
149
|
+
maxWorkers: {
|
|
150
|
+
type: 'number',
|
|
151
|
+
description: 'Maximum concurrent workers',
|
|
152
|
+
},
|
|
153
|
+
},
|
|
154
|
+
},
|
|
155
|
+
},
|
|
156
|
+
},
|
|
157
|
+
},
|
|
158
|
+
required: ['targetPath'],
|
|
159
|
+
};
|
|
160
|
+
async execute(args) {
|
|
161
|
+
const params = args;
|
|
162
|
+
const targetPath = params.targetPath;
|
|
163
|
+
const categories = params.categories ?? ['all'];
|
|
164
|
+
const minOccurrences = params.minOccurrences ?? 3;
|
|
165
|
+
const complexity = params.complexity ?? 'all';
|
|
166
|
+
const outputFormat = params.outputFormat ?? 'fixtures';
|
|
167
|
+
const outputPath = params.outputPath;
|
|
168
|
+
const anonymizationLevel = params.anonymizationLevel ?? 'strict';
|
|
169
|
+
const validatePatterns = params.validatePatterns ?? true;
|
|
170
|
+
// Self-learning and style-awareness options
|
|
171
|
+
const enableLearning = params.enableLearning ?? true;
|
|
172
|
+
const respectCodebaseStyle = params.respectCodebaseStyle ?? true;
|
|
173
|
+
const generateStyleProfile = params.generateStyleProfile ?? true;
|
|
174
|
+
const generateRules = params.generateRules ?? false;
|
|
175
|
+
const filterRulesByStyle = params.filterRulesByStyle ?? true;
|
|
176
|
+
const minConfidence = params.minConfidence ?? 0.6;
|
|
177
|
+
if (!targetPath || typeof targetPath !== 'string') {
|
|
178
|
+
throw new Error('targetPath is required and must be a string');
|
|
179
|
+
}
|
|
180
|
+
const startTime = Date.now();
|
|
181
|
+
// Find tsconfig.json
|
|
182
|
+
const tsConfigPath = findTsConfig(targetPath);
|
|
183
|
+
if (!tsConfigPath) {
|
|
184
|
+
throw new Error(`Could not find tsconfig.json in ${targetPath}. Please ensure the target path contains a valid TypeScript project.`);
|
|
185
|
+
}
|
|
186
|
+
// Initialize Project
|
|
187
|
+
const project = new Project({
|
|
188
|
+
tsConfigFilePath: tsConfigPath,
|
|
189
|
+
});
|
|
190
|
+
const sourceFiles = project.getSourceFiles();
|
|
191
|
+
const filesAnalyzed = sourceFiles.filter((sf) => !sf.getFilePath().includes('node_modules') &&
|
|
192
|
+
!sf.getFilePath().includes('.spec.') &&
|
|
193
|
+
!sf.getFilePath().includes('.test.')).length;
|
|
194
|
+
// Self-learning and style-awareness components
|
|
195
|
+
const fileSystem = new RealFileSystemAdapter();
|
|
196
|
+
let knowledgeBase;
|
|
197
|
+
let styleDetector;
|
|
198
|
+
let contextScorer;
|
|
199
|
+
let ruleGenerator;
|
|
200
|
+
let detectedStyleProfile;
|
|
201
|
+
let learningEvolution;
|
|
202
|
+
if (enableLearning || respectCodebaseStyle || generateStyleProfile) {
|
|
203
|
+
try {
|
|
204
|
+
// Initialize knowledge base for self-learning
|
|
205
|
+
knowledgeBase = new PatternKnowledgeBase(fileSystem, targetPath, params.knowledgeBasePath
|
|
206
|
+
? { storagePath: params.knowledgeBasePath }
|
|
207
|
+
: undefined);
|
|
208
|
+
await knowledgeBase.initialize();
|
|
209
|
+
// Initialize style detector
|
|
210
|
+
styleDetector = new StyleConventionDetector();
|
|
211
|
+
// Detect codebase style profile
|
|
212
|
+
if (generateStyleProfile || respectCodebaseStyle) {
|
|
213
|
+
try {
|
|
214
|
+
const styleResult = styleDetector.detectStyles(project);
|
|
215
|
+
detectedStyleProfile = styleResult.styleProfile;
|
|
216
|
+
}
|
|
217
|
+
catch (styleError) {
|
|
218
|
+
// Style detection may fail in test environments with mock classes
|
|
219
|
+
// Continue without style profile
|
|
220
|
+
console.warn('Style detection failed (may be expected in test environments):', styleError instanceof Error
|
|
221
|
+
? styleError.message
|
|
222
|
+
: String(styleError));
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
// Initialize context-aware scorer
|
|
226
|
+
contextScorer = new ContextAwareScorer();
|
|
227
|
+
}
|
|
228
|
+
catch (initError) {
|
|
229
|
+
// Self-learning initialization may fail in test environments
|
|
230
|
+
// Continue without self-learning features
|
|
231
|
+
console.warn('Self-learning initialization failed (may be expected in test environments):', initError instanceof Error ? initError.message : String(initError));
|
|
232
|
+
knowledgeBase = undefined;
|
|
233
|
+
styleDetector = undefined;
|
|
234
|
+
contextScorer = undefined;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
// Discover patterns
|
|
238
|
+
const rawPatterns = await this.discoverPatterns(project, categories);
|
|
239
|
+
// Filter by occurrence count
|
|
240
|
+
const patternGroups = this.groupPatterns(rawPatterns);
|
|
241
|
+
const filteredPatterns = this.filterByOccurrence(patternGroups, minOccurrences);
|
|
242
|
+
// Anonymize patterns
|
|
243
|
+
const anonymizedPatterns = this.anonymizePatterns(filteredPatterns, anonymizationLevel);
|
|
244
|
+
// Calculate complexity
|
|
245
|
+
const patternsWithComplexity = anonymizedPatterns.map((p) => ({
|
|
246
|
+
...p,
|
|
247
|
+
complexity: this.calculateComplexity(p),
|
|
248
|
+
}));
|
|
249
|
+
// Filter by complexity
|
|
250
|
+
let finalPatterns = complexity === 'all'
|
|
251
|
+
? patternsWithComplexity
|
|
252
|
+
: patternsWithComplexity.filter((p) => p.complexity === complexity);
|
|
253
|
+
// Phase 8: Enhance patterns with confidence scoring and style alignment
|
|
254
|
+
let confidenceAnalysis;
|
|
255
|
+
if (contextScorer && detectedStyleProfile) {
|
|
256
|
+
// Score each pattern and add enhanced metadata
|
|
257
|
+
finalPatterns = finalPatterns.map((pattern) => {
|
|
258
|
+
// Convert to PatternEntry format for scoring
|
|
259
|
+
const patternEntry = {
|
|
260
|
+
id: pattern.id,
|
|
261
|
+
name: pattern.name,
|
|
262
|
+
category: pattern.category,
|
|
263
|
+
type: pattern.id.replace('learned-', '').replace(/-\d+$/, ''),
|
|
264
|
+
description: pattern.description,
|
|
265
|
+
occurrences: pattern.occurrences,
|
|
266
|
+
totalOccurrences: pattern.occurrences,
|
|
267
|
+
complexity: pattern.complexity,
|
|
268
|
+
confidence: 0.5, // Initial confidence
|
|
269
|
+
confidenceExplanation: '',
|
|
270
|
+
alignsWithStyle: true,
|
|
271
|
+
styleAlignment: 0.5,
|
|
272
|
+
dominancePercentage: (pattern.occurrences / filesAnalyzed) * 100,
|
|
273
|
+
firstSeen: new Date().toISOString(),
|
|
274
|
+
lastSeen: new Date().toISOString(),
|
|
275
|
+
scanCount: 1,
|
|
276
|
+
trending: 'stable',
|
|
277
|
+
fingerprint: pattern.id,
|
|
278
|
+
occurrenceHistory: [],
|
|
279
|
+
examples: pattern.examples,
|
|
280
|
+
suggestedRule: pattern.suggestedRule,
|
|
281
|
+
};
|
|
282
|
+
// Calculate confidence score
|
|
283
|
+
const scoreResult = contextScorer.scorePattern(patternEntry, detectedStyleProfile, filesAnalyzed);
|
|
284
|
+
// Check style alignment
|
|
285
|
+
const styleAlignment = contextScorer.patternAlignsWithStyle(patternEntry.type, detectedStyleProfile);
|
|
286
|
+
return {
|
|
287
|
+
...pattern,
|
|
288
|
+
confidence: scoreResult.overall,
|
|
289
|
+
confidenceExplanation: scoreResult.explanation,
|
|
290
|
+
alignsWithStyle: styleAlignment.aligns,
|
|
291
|
+
styleAlignment: styleAlignment.alignment,
|
|
292
|
+
dominancePercentage: patternEntry.dominancePercentage,
|
|
293
|
+
trending: 'stable',
|
|
294
|
+
scanCount: 1,
|
|
295
|
+
};
|
|
296
|
+
});
|
|
297
|
+
// Filter by confidence threshold
|
|
298
|
+
if (minConfidence > 0) {
|
|
299
|
+
finalPatterns = finalPatterns.filter((p) => (p.confidence ?? 0) >= minConfidence);
|
|
300
|
+
}
|
|
301
|
+
// Calculate confidence analysis
|
|
302
|
+
const highConfidence = finalPatterns.filter((p) => (p.confidence ?? 0) >= 0.8).length;
|
|
303
|
+
const mediumConfidence = finalPatterns.filter((p) => (p.confidence ?? 0) >= 0.6 && (p.confidence ?? 0) < 0.8).length;
|
|
304
|
+
const lowConfidence = finalPatterns.filter((p) => (p.confidence ?? 0) < 0.6).length;
|
|
305
|
+
const totalConfidence = finalPatterns.reduce((sum, p) => sum + (p.confidence ?? 0), 0);
|
|
306
|
+
const styleAlignedPatterns = finalPatterns.filter((p) => p.alignsWithStyle).length;
|
|
307
|
+
confidenceAnalysis = {
|
|
308
|
+
highConfidence,
|
|
309
|
+
mediumConfidence,
|
|
310
|
+
lowConfidence,
|
|
311
|
+
averageConfidence: finalPatterns.length > 0 ? totalConfidence / finalPatterns.length : 0,
|
|
312
|
+
styleAlignedPatterns,
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
// Update knowledge base with discovered patterns
|
|
316
|
+
if (knowledgeBase && detectedStyleProfile) {
|
|
317
|
+
try {
|
|
318
|
+
// Convert patterns to PatternEntry format for storage
|
|
319
|
+
const patternEntries = finalPatterns.map((p) => ({
|
|
320
|
+
id: p.id,
|
|
321
|
+
name: p.name,
|
|
322
|
+
category: p.category,
|
|
323
|
+
type: p.id.replace('learned-', '').replace(/-\d+$/, ''),
|
|
324
|
+
description: p.description,
|
|
325
|
+
occurrences: p.occurrences,
|
|
326
|
+
totalOccurrences: p.occurrences,
|
|
327
|
+
complexity: p.complexity,
|
|
328
|
+
confidence: p.confidence ?? 0.5,
|
|
329
|
+
confidenceExplanation: p.confidenceExplanation ?? '',
|
|
330
|
+
alignsWithStyle: p.alignsWithStyle ?? true,
|
|
331
|
+
styleAlignment: p.styleAlignment ?? 0.5,
|
|
332
|
+
dominancePercentage: p.dominancePercentage ?? 0,
|
|
333
|
+
firstSeen: new Date().toISOString(),
|
|
334
|
+
lastSeen: new Date().toISOString(),
|
|
335
|
+
scanCount: p.scanCount ?? 1,
|
|
336
|
+
trending: p.trending ?? 'stable',
|
|
337
|
+
fingerprint: p.id,
|
|
338
|
+
occurrenceHistory: [],
|
|
339
|
+
examples: p.examples,
|
|
340
|
+
suggestedRule: p.suggestedRule,
|
|
341
|
+
}));
|
|
342
|
+
// Update knowledge base and get learning evolution
|
|
343
|
+
learningEvolution = await knowledgeBase.updateFromScan(patternEntries, filesAnalyzed, detectedStyleProfile);
|
|
344
|
+
// Add confidence improvement from knowledge base
|
|
345
|
+
const improvement = knowledgeBase.getConfidenceImprovement();
|
|
346
|
+
learningEvolution = {
|
|
347
|
+
...learningEvolution,
|
|
348
|
+
confidenceImprovement: improvement,
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
catch (kbError) {
|
|
352
|
+
// Knowledge base update may fail in test environments
|
|
353
|
+
console.warn('Knowledge base update failed (may be expected in test environments):', kbError instanceof Error ? kbError.message : String(kbError));
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
// Self-learning and style-awareness: Generate rules if requested
|
|
357
|
+
let generatedRulesResult;
|
|
358
|
+
if (generateRules && detectedStyleProfile) {
|
|
359
|
+
ruleGenerator = new ContextAwareRuleGenerator({
|
|
360
|
+
minConfidence,
|
|
361
|
+
styleAlignedOnly: filterRulesByStyle,
|
|
362
|
+
});
|
|
363
|
+
// Convert patterns to PatternEntry format
|
|
364
|
+
const patternEntries = finalPatterns.map((p) => ({
|
|
365
|
+
id: p.id,
|
|
366
|
+
name: p.name,
|
|
367
|
+
category: p.category,
|
|
368
|
+
type: p.id.replace('learned-', '').replace(/-\d+$/, ''),
|
|
369
|
+
description: p.description,
|
|
370
|
+
occurrences: p.occurrences,
|
|
371
|
+
totalOccurrences: p.occurrences,
|
|
372
|
+
complexity: p.complexity,
|
|
373
|
+
confidence: p.confidence ?? 0.5,
|
|
374
|
+
confidenceExplanation: p.confidenceExplanation ?? '',
|
|
375
|
+
alignsWithStyle: p.alignsWithStyle ?? true,
|
|
376
|
+
styleAlignment: p.styleAlignment ?? 0.5,
|
|
377
|
+
dominancePercentage: p.dominancePercentage ?? 0,
|
|
378
|
+
firstSeen: new Date().toISOString(),
|
|
379
|
+
lastSeen: new Date().toISOString(),
|
|
380
|
+
scanCount: p.scanCount ?? 1,
|
|
381
|
+
trending: p.trending ?? 'stable',
|
|
382
|
+
fingerprint: p.id,
|
|
383
|
+
occurrenceHistory: [],
|
|
384
|
+
examples: p.examples,
|
|
385
|
+
suggestedRule: p.suggestedRule,
|
|
386
|
+
}));
|
|
387
|
+
const ruleResult = ruleGenerator.generateRules(patternEntries, detectedStyleProfile, filesAnalyzed);
|
|
388
|
+
generatedRulesResult = ruleResult.rules.map((rule) => ({
|
|
389
|
+
path: params.ruleOutputPath ?? './learned-rules',
|
|
390
|
+
ruleId: rule.ruleId,
|
|
391
|
+
confidence: rule.confidence,
|
|
392
|
+
alignedWithStyle: rule.alignsWithStyle,
|
|
393
|
+
rationale: rule.rationale,
|
|
394
|
+
}));
|
|
395
|
+
}
|
|
396
|
+
// Validate patterns if requested
|
|
397
|
+
let validation;
|
|
398
|
+
if (validatePatterns) {
|
|
399
|
+
validation = this.validatePatternQuality(finalPatterns);
|
|
400
|
+
}
|
|
401
|
+
// Generate artifacts if requested
|
|
402
|
+
let artifacts;
|
|
403
|
+
if (outputFormat !== 'fixtures' || outputPath) {
|
|
404
|
+
artifacts = this.generateArtifacts(finalPatterns, outputFormat, outputPath);
|
|
405
|
+
}
|
|
406
|
+
// Calculate statistics
|
|
407
|
+
const duration = Date.now() - startTime;
|
|
408
|
+
const statistics = {
|
|
409
|
+
totalPatternsFound: finalPatterns.length,
|
|
410
|
+
byCategory: this.countByCategory(finalPatterns),
|
|
411
|
+
byComplexity: this.countByComplexity(finalPatterns),
|
|
412
|
+
filesAnalyzed,
|
|
413
|
+
duration,
|
|
414
|
+
};
|
|
415
|
+
// Build result with Phase 8 enhancements
|
|
416
|
+
const result = {
|
|
417
|
+
patterns: finalPatterns,
|
|
418
|
+
statistics,
|
|
419
|
+
artifacts,
|
|
420
|
+
validation,
|
|
421
|
+
};
|
|
422
|
+
// Add Phase 8 fields if available
|
|
423
|
+
if (detectedStyleProfile) {
|
|
424
|
+
result.styleProfile = {
|
|
425
|
+
rxjsPreference: detectedStyleProfile.rxjsPreference,
|
|
426
|
+
rxjsRatio: {
|
|
427
|
+
behaviorSubject: detectedStyleProfile.rxjsRatio.behaviorSubject,
|
|
428
|
+
signal: detectedStyleProfile.rxjsRatio.signal,
|
|
429
|
+
},
|
|
430
|
+
diPreference: detectedStyleProfile.diPreference,
|
|
431
|
+
diRatio: detectedStyleProfile.diRatio,
|
|
432
|
+
stateManagement: detectedStyleProfile.stateManagement,
|
|
433
|
+
namingConventions: detectedStyleProfile.namingConventions.map((nc) => ({
|
|
434
|
+
suffix: nc.suffix,
|
|
435
|
+
count: nc.count,
|
|
436
|
+
})),
|
|
437
|
+
architectureStyle: detectedStyleProfile.architectureStyle,
|
|
438
|
+
dominantPatterns: detectedStyleProfile.dominantPatterns,
|
|
439
|
+
changeDetectionPreference: detectedStyleProfile.changeDetectionPreference,
|
|
440
|
+
moduleStyle: detectedStyleProfile.moduleStyle,
|
|
441
|
+
confidence: detectedStyleProfile.confidence,
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
if (learningEvolution) {
|
|
445
|
+
result.learningEvolution = {
|
|
446
|
+
isFirstScan: learningEvolution.isFirstScan,
|
|
447
|
+
patternStability: learningEvolution.patternStability,
|
|
448
|
+
newPatternsDiscovered: learningEvolution.newPatternsDiscovered,
|
|
449
|
+
deprecatedPatterns: learningEvolution.deprecatedPatterns,
|
|
450
|
+
patternVelocity: learningEvolution.patternVelocity,
|
|
451
|
+
styleShift: learningEvolution.styleShift,
|
|
452
|
+
confidenceImprovement: learningEvolution.confidenceImprovement,
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
if (confidenceAnalysis) {
|
|
456
|
+
result.confidenceAnalysis = confidenceAnalysis;
|
|
457
|
+
}
|
|
458
|
+
if (generatedRulesResult) {
|
|
459
|
+
result.generatedRules = generatedRulesResult;
|
|
460
|
+
}
|
|
461
|
+
return result;
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* Discover patterns from the project.
|
|
465
|
+
*/
|
|
466
|
+
async discoverPatterns(project, categories) {
|
|
467
|
+
const patterns = [];
|
|
468
|
+
const sourceFiles = project.getSourceFiles();
|
|
469
|
+
const activeCategories = categories.includes('all') || categories.length === 0
|
|
470
|
+
? [
|
|
471
|
+
'rxjs-patterns',
|
|
472
|
+
'component-patterns',
|
|
473
|
+
'service-patterns',
|
|
474
|
+
'transformation-patterns',
|
|
475
|
+
'architectural-patterns',
|
|
476
|
+
]
|
|
477
|
+
: categories;
|
|
478
|
+
for (const sourceFile of sourceFiles) {
|
|
479
|
+
const filePath = sourceFile.getFilePath();
|
|
480
|
+
// Skip node_modules and test files
|
|
481
|
+
if (filePath.includes('node_modules') ||
|
|
482
|
+
filePath.includes('.spec.') ||
|
|
483
|
+
filePath.includes('.test.')) {
|
|
484
|
+
continue;
|
|
485
|
+
}
|
|
486
|
+
for (const category of activeCategories) {
|
|
487
|
+
const categoryPatterns = this.detectPatternsInFile(sourceFile, category, filePath);
|
|
488
|
+
patterns.push(...categoryPatterns);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
return patterns;
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* Detect patterns in a single file based on category.
|
|
495
|
+
*/
|
|
496
|
+
detectPatternsInFile(sourceFile, category, filePath) {
|
|
497
|
+
const patterns = [];
|
|
498
|
+
switch (category) {
|
|
499
|
+
case 'rxjs-patterns':
|
|
500
|
+
patterns.push(...this.detectRxjsPatterns(sourceFile, filePath));
|
|
501
|
+
break;
|
|
502
|
+
case 'component-patterns':
|
|
503
|
+
patterns.push(...this.detectComponentPatterns(sourceFile, filePath));
|
|
504
|
+
break;
|
|
505
|
+
case 'service-patterns':
|
|
506
|
+
patterns.push(...this.detectServicePatterns(sourceFile, filePath));
|
|
507
|
+
break;
|
|
508
|
+
case 'transformation-patterns':
|
|
509
|
+
patterns.push(...this.detectTransformationPatterns(sourceFile, filePath));
|
|
510
|
+
break;
|
|
511
|
+
case 'architectural-patterns':
|
|
512
|
+
patterns.push(...this.detectArchitecturalPatterns(sourceFile, filePath));
|
|
513
|
+
break;
|
|
514
|
+
}
|
|
515
|
+
return patterns;
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Detect RxJS patterns (subscriptions, operators, etc.).
|
|
519
|
+
*/
|
|
520
|
+
detectRxjsPatterns(sourceFile, filePath) {
|
|
521
|
+
const patterns = [];
|
|
522
|
+
// Detect unsubscribed observables
|
|
523
|
+
const subscriptions = sourceFile
|
|
524
|
+
.getDescendantsOfKind(SyntaxKind.CallExpression)
|
|
525
|
+
.filter((call) => call.getExpression().getText().endsWith('.subscribe'));
|
|
526
|
+
if (subscriptions.length > 0) {
|
|
527
|
+
patterns.push({
|
|
528
|
+
type: 'unsubscribed-observable',
|
|
529
|
+
category: 'rxjs-patterns',
|
|
530
|
+
filePath,
|
|
531
|
+
code: subscriptions[0]?.getParent()?.getText() ?? '',
|
|
532
|
+
metadata: {
|
|
533
|
+
count: subscriptions.length,
|
|
534
|
+
hasOnDestroy: sourceFile.getText().includes('OnDestroy'),
|
|
535
|
+
},
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
// Detect multiple pipe chains
|
|
539
|
+
const pipeCalls = sourceFile
|
|
540
|
+
.getDescendantsOfKind(SyntaxKind.CallExpression)
|
|
541
|
+
.filter((call) => call.getExpression().getText().endsWith('.pipe'));
|
|
542
|
+
if (pipeCalls.length > 1) {
|
|
543
|
+
patterns.push({
|
|
544
|
+
type: 'multiple-pipe-chains',
|
|
545
|
+
category: 'rxjs-patterns',
|
|
546
|
+
filePath,
|
|
547
|
+
code: pipeCalls.map((p) => p.getText()).join('\n\n'),
|
|
548
|
+
metadata: {
|
|
549
|
+
count: pipeCalls.length,
|
|
550
|
+
},
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
return patterns;
|
|
554
|
+
}
|
|
555
|
+
/**
|
|
556
|
+
* Detect component patterns (lifecycle, inputs, etc.).
|
|
557
|
+
*/
|
|
558
|
+
detectComponentPatterns(sourceFile, filePath) {
|
|
559
|
+
const patterns = [];
|
|
560
|
+
const classes = sourceFile.getClasses();
|
|
561
|
+
for (const cls of classes) {
|
|
562
|
+
const componentDecorator = cls
|
|
563
|
+
.getDecorators()
|
|
564
|
+
.find((d) => d.getName() === 'Component');
|
|
565
|
+
if (componentDecorator) {
|
|
566
|
+
// Detect too many @Input properties
|
|
567
|
+
const inputs = cls
|
|
568
|
+
.getProperties()
|
|
569
|
+
.filter((p) => p.getDecorators().some((d) => d.getName() === 'Input'));
|
|
570
|
+
if (inputs.length > 5) {
|
|
571
|
+
patterns.push({
|
|
572
|
+
type: 'too-many-inputs',
|
|
573
|
+
category: 'component-patterns',
|
|
574
|
+
filePath,
|
|
575
|
+
code: cls.getText(),
|
|
576
|
+
metadata: {
|
|
577
|
+
inputCount: inputs.length,
|
|
578
|
+
className: cls.getName() ?? 'unknown',
|
|
579
|
+
},
|
|
580
|
+
});
|
|
581
|
+
}
|
|
582
|
+
// Detect missing OnPush change detection
|
|
583
|
+
const text = componentDecorator.getText();
|
|
584
|
+
if (!text.includes('OnPush') &&
|
|
585
|
+
!text.includes('changeDetection') &&
|
|
586
|
+
inputs.length > 0) {
|
|
587
|
+
patterns.push({
|
|
588
|
+
type: 'missing-onpush',
|
|
589
|
+
category: 'component-patterns',
|
|
590
|
+
filePath,
|
|
591
|
+
code: cls.getText(),
|
|
592
|
+
metadata: {
|
|
593
|
+
hasInputs: true,
|
|
594
|
+
className: cls.getName() ?? 'unknown',
|
|
595
|
+
},
|
|
596
|
+
});
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
return patterns;
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* Detect service patterns (DI, architecture, etc.).
|
|
604
|
+
*/
|
|
605
|
+
detectServicePatterns(sourceFile, filePath) {
|
|
606
|
+
const patterns = [];
|
|
607
|
+
const classes = sourceFile.getClasses();
|
|
608
|
+
for (const cls of classes) {
|
|
609
|
+
const injectableDecorator = cls
|
|
610
|
+
.getDecorators()
|
|
611
|
+
.find((d) => d.getName() === 'Injectable');
|
|
612
|
+
if (injectableDecorator) {
|
|
613
|
+
// Detect too many dependencies
|
|
614
|
+
const constructor = cls.getConstructors()[0];
|
|
615
|
+
if (constructor) {
|
|
616
|
+
const params = constructor.getParameters();
|
|
617
|
+
if (params.length > 5) {
|
|
618
|
+
patterns.push({
|
|
619
|
+
type: 'too-many-dependencies',
|
|
620
|
+
category: 'service-patterns',
|
|
621
|
+
filePath,
|
|
622
|
+
code: cls.getText(),
|
|
623
|
+
metadata: {
|
|
624
|
+
dependencyCount: params.length,
|
|
625
|
+
className: cls.getName() ?? 'unknown',
|
|
626
|
+
},
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
// Detect god objects (too many methods)
|
|
631
|
+
const methods = cls.getMethods();
|
|
632
|
+
if (methods.length > 10) {
|
|
633
|
+
patterns.push({
|
|
634
|
+
type: 'god-object',
|
|
635
|
+
category: 'service-patterns',
|
|
636
|
+
filePath,
|
|
637
|
+
code: cls.getText(),
|
|
638
|
+
metadata: {
|
|
639
|
+
methodCount: methods.length,
|
|
640
|
+
className: cls.getName() ?? 'unknown',
|
|
641
|
+
},
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
return patterns;
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* Detect transformation opportunities (constructor injection, etc.).
|
|
650
|
+
*/
|
|
651
|
+
detectTransformationPatterns(sourceFile, filePath) {
|
|
652
|
+
const patterns = [];
|
|
653
|
+
const classes = sourceFile.getClasses();
|
|
654
|
+
for (const cls of classes) {
|
|
655
|
+
// Detect constructor injection that can be migrated to inject()
|
|
656
|
+
const constructor = cls.getConstructors()[0];
|
|
657
|
+
if (constructor) {
|
|
658
|
+
const params = constructor.getParameters();
|
|
659
|
+
if (params.some((p) => p.hasModifier(SyntaxKind.PublicKeyword) ||
|
|
660
|
+
p.hasModifier(SyntaxKind.PrivateKeyword) ||
|
|
661
|
+
p.hasModifier(SyntaxKind.ProtectedKeyword))) {
|
|
662
|
+
patterns.push({
|
|
663
|
+
type: 'constructor-to-inject-candidate',
|
|
664
|
+
category: 'transformation-patterns',
|
|
665
|
+
filePath,
|
|
666
|
+
code: cls.getText(),
|
|
667
|
+
metadata: {
|
|
668
|
+
paramCount: params.length,
|
|
669
|
+
className: cls.getName() ?? 'unknown',
|
|
670
|
+
},
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
// Detect inline type literals that should be interfaces
|
|
675
|
+
const properties = cls.getProperties();
|
|
676
|
+
for (const prop of properties) {
|
|
677
|
+
const typeNode = prop.getTypeNode();
|
|
678
|
+
if (typeNode?.getKind() === SyntaxKind.TypeLiteral) {
|
|
679
|
+
patterns.push({
|
|
680
|
+
type: 'interface-extraction-candidate',
|
|
681
|
+
category: 'transformation-patterns',
|
|
682
|
+
filePath,
|
|
683
|
+
code: prop.getText(),
|
|
684
|
+
metadata: {
|
|
685
|
+
propertyName: prop.getName(),
|
|
686
|
+
className: cls.getName() ?? 'unknown',
|
|
687
|
+
},
|
|
688
|
+
});
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
return patterns;
|
|
693
|
+
}
|
|
694
|
+
/**
|
|
695
|
+
* Detect architectural patterns (circular dependencies, inheritance, etc.).
|
|
696
|
+
*/
|
|
697
|
+
detectArchitecturalPatterns(sourceFile, filePath) {
|
|
698
|
+
const patterns = [];
|
|
699
|
+
// Detect inheritance patterns
|
|
700
|
+
const classes = sourceFile.getClasses();
|
|
701
|
+
for (const cls of classes) {
|
|
702
|
+
const extendsClause = cls.getExtends();
|
|
703
|
+
if (extendsClause) {
|
|
704
|
+
const baseClassName = extendsClause.getText();
|
|
705
|
+
const methods = cls.getMethods();
|
|
706
|
+
const properties = cls.getProperties();
|
|
707
|
+
patterns.push({
|
|
708
|
+
type: 'inheritance-pattern',
|
|
709
|
+
category: 'architectural-patterns',
|
|
710
|
+
filePath,
|
|
711
|
+
code: cls.getText(),
|
|
712
|
+
metadata: {
|
|
713
|
+
derivedClass: cls.getName() ?? 'Unknown',
|
|
714
|
+
baseClass: baseClassName,
|
|
715
|
+
isAbstract: cls.isAbstract(),
|
|
716
|
+
methodCount: methods.length,
|
|
717
|
+
propertyCount: properties.length,
|
|
718
|
+
hasLifecycleHooks: methods.some((m) => ['ngOnInit', 'ngOnDestroy', 'ngOnChanges'].includes(m.getName())),
|
|
719
|
+
},
|
|
720
|
+
});
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
// Detect barrel file exports
|
|
724
|
+
const exports = sourceFile.getExportDeclarations();
|
|
725
|
+
if (exports.length > 10) {
|
|
726
|
+
patterns.push({
|
|
727
|
+
type: 'barrel-file',
|
|
728
|
+
category: 'architectural-patterns',
|
|
729
|
+
filePath,
|
|
730
|
+
code: exports.map((e) => e.getText()).join('\n'),
|
|
731
|
+
metadata: {
|
|
732
|
+
exportCount: exports.length,
|
|
733
|
+
},
|
|
734
|
+
});
|
|
735
|
+
}
|
|
736
|
+
// Detect feature module structure
|
|
737
|
+
const imports = sourceFile.getImportDeclarations();
|
|
738
|
+
const hasModuleImports = imports.some((imp) => imp.getText().includes('Module'));
|
|
739
|
+
const hasNgModuleDecorator = classes.some((cls) => cls.getDecorators().some((d) => d.getName() === 'NgModule'));
|
|
740
|
+
if (hasModuleImports && hasNgModuleDecorator) {
|
|
741
|
+
patterns.push({
|
|
742
|
+
type: 'feature-module',
|
|
743
|
+
category: 'architectural-patterns',
|
|
744
|
+
filePath,
|
|
745
|
+
code: sourceFile.getText(),
|
|
746
|
+
metadata: {
|
|
747
|
+
importCount: imports.length,
|
|
748
|
+
},
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
return patterns;
|
|
752
|
+
}
|
|
753
|
+
/**
|
|
754
|
+
* Group similar patterns together.
|
|
755
|
+
*/
|
|
756
|
+
groupPatterns(rawPatterns) {
|
|
757
|
+
const groups = new Map();
|
|
758
|
+
for (const pattern of rawPatterns) {
|
|
759
|
+
const key = `${pattern.category}:${pattern.type}`;
|
|
760
|
+
if (!groups.has(key)) {
|
|
761
|
+
groups.set(key, []);
|
|
762
|
+
}
|
|
763
|
+
groups.get(key)?.push(pattern);
|
|
764
|
+
}
|
|
765
|
+
return groups;
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* Filter patterns by minimum occurrence count.
|
|
769
|
+
*/
|
|
770
|
+
filterByOccurrence(patternGroups, minOccurrences) {
|
|
771
|
+
const result = [];
|
|
772
|
+
for (const [key, patterns] of patternGroups.entries()) {
|
|
773
|
+
if (patterns.length >= minOccurrences) {
|
|
774
|
+
const [category, type] = key.split(':');
|
|
775
|
+
result.push({
|
|
776
|
+
id: `learned-${type}-${Date.now()}`,
|
|
777
|
+
name: this.formatPatternName(type ?? ''),
|
|
778
|
+
category: category ?? 'unknown',
|
|
779
|
+
description: this.generatePatternDescription(type ?? '', patterns),
|
|
780
|
+
occurrences: patterns.length,
|
|
781
|
+
complexity: 'medium', // Will be calculated later
|
|
782
|
+
examples: patterns.slice(0, 3).map((p) => ({
|
|
783
|
+
filePath: p.filePath,
|
|
784
|
+
code: p.code,
|
|
785
|
+
metadata: p.metadata,
|
|
786
|
+
})),
|
|
787
|
+
suggestedRule: this.generateSuggestedRule(type ?? '', category ?? ''),
|
|
788
|
+
});
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
return result;
|
|
792
|
+
}
|
|
793
|
+
/**
|
|
794
|
+
* Anonymize patterns to remove business-specific terms.
|
|
795
|
+
*/
|
|
796
|
+
anonymizePatterns(patterns, level) {
|
|
797
|
+
if (level === 'minimal') {
|
|
798
|
+
return patterns; // No anonymization
|
|
799
|
+
}
|
|
800
|
+
return patterns.map((pattern) => ({
|
|
801
|
+
...pattern,
|
|
802
|
+
examples: pattern.examples.map((example) => ({
|
|
803
|
+
...example,
|
|
804
|
+
code: this.anonymizeCode(example.code, level),
|
|
805
|
+
})),
|
|
806
|
+
}));
|
|
807
|
+
}
|
|
808
|
+
/**
|
|
809
|
+
* Anonymize code while preserving framework terms.
|
|
810
|
+
*/
|
|
811
|
+
anonymizeCode(code, level) {
|
|
812
|
+
if (level === 'minimal') {
|
|
813
|
+
return code;
|
|
814
|
+
}
|
|
815
|
+
// Framework terms to preserve
|
|
816
|
+
const preservedTerms = [
|
|
817
|
+
'Component',
|
|
818
|
+
'Injectable',
|
|
819
|
+
'Input',
|
|
820
|
+
'Output',
|
|
821
|
+
'OnInit',
|
|
822
|
+
'OnDestroy',
|
|
823
|
+
'Observable',
|
|
824
|
+
'Subject',
|
|
825
|
+
'BehaviorSubject',
|
|
826
|
+
'subscribe',
|
|
827
|
+
'pipe',
|
|
828
|
+
'map',
|
|
829
|
+
'filter',
|
|
830
|
+
'switchMap',
|
|
831
|
+
'takeUntil',
|
|
832
|
+
'NgModule',
|
|
833
|
+
'Service',
|
|
834
|
+
'Directive',
|
|
835
|
+
'Pipe',
|
|
836
|
+
];
|
|
837
|
+
let anonymized = code;
|
|
838
|
+
// Simple anonymization: replace custom class names
|
|
839
|
+
// This is a simplified version - production would need more sophisticated anonymization
|
|
840
|
+
if (level === 'strict') {
|
|
841
|
+
anonymized = anonymized.replaceAll(/class\s+([A-Z][a-zA-Z0-9]*)/g, (match, className) => {
|
|
842
|
+
if (preservedTerms.some((term) => className.includes(term))) {
|
|
843
|
+
return match;
|
|
844
|
+
}
|
|
845
|
+
return `class GenericClass${Math.random().toString(36).substring(7)}`;
|
|
846
|
+
});
|
|
847
|
+
}
|
|
848
|
+
return anonymized;
|
|
849
|
+
}
|
|
850
|
+
/**
|
|
851
|
+
* Calculate complexity of a pattern.
|
|
852
|
+
*/
|
|
853
|
+
calculateComplexity(pattern) {
|
|
854
|
+
const codeLength = pattern.examples.reduce((sum, ex) => sum + ex.code.length, 0);
|
|
855
|
+
const avgLength = codeLength / pattern.examples.length;
|
|
856
|
+
if (avgLength < 500) {
|
|
857
|
+
return 'low';
|
|
858
|
+
}
|
|
859
|
+
if (avgLength < 2000) {
|
|
860
|
+
return 'medium';
|
|
861
|
+
}
|
|
862
|
+
return 'high';
|
|
863
|
+
}
|
|
864
|
+
/**
|
|
865
|
+
* Validate pattern quality.
|
|
866
|
+
*/
|
|
867
|
+
validatePatternQuality(patterns) {
|
|
868
|
+
const validationErrors = [];
|
|
869
|
+
for (const pattern of patterns) {
|
|
870
|
+
// Validate pattern has examples
|
|
871
|
+
if (pattern.examples.length === 0) {
|
|
872
|
+
validationErrors.push(`Pattern ${pattern.id} has no examples`);
|
|
873
|
+
}
|
|
874
|
+
// Validate pattern code is not empty
|
|
875
|
+
if (pattern.examples.some((ex) => !ex.code || ex.code.trim() === '')) {
|
|
876
|
+
validationErrors.push(`Pattern ${pattern.id} has empty code examples`);
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
return {
|
|
880
|
+
patternsValidated: patterns.length,
|
|
881
|
+
validationErrors,
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
/**
|
|
885
|
+
* Generate artifacts (fixtures or rules).
|
|
886
|
+
*/
|
|
887
|
+
generateArtifacts(patterns, format, outputPath) {
|
|
888
|
+
const artifacts = {};
|
|
889
|
+
if (format === 'fixtures' || format === 'both') {
|
|
890
|
+
artifacts.fixtures = this.generateFixtures(patterns, outputPath);
|
|
891
|
+
}
|
|
892
|
+
if (format === 'rules' || format === 'both') {
|
|
893
|
+
artifacts.rules = this.generateRules(patterns, outputPath);
|
|
894
|
+
}
|
|
895
|
+
return artifacts;
|
|
896
|
+
}
|
|
897
|
+
/**
|
|
898
|
+
* Generate fixture files.
|
|
899
|
+
*/
|
|
900
|
+
generateFixtures(patterns, basePath = './learned-patterns-fixtures') {
|
|
901
|
+
const fixtures = [];
|
|
902
|
+
// Group by category
|
|
903
|
+
const byCategory = new Map();
|
|
904
|
+
for (const pattern of patterns) {
|
|
905
|
+
if (!byCategory.has(pattern.category)) {
|
|
906
|
+
byCategory.set(pattern.category, []);
|
|
907
|
+
}
|
|
908
|
+
byCategory.get(pattern.category)?.push(pattern);
|
|
909
|
+
}
|
|
910
|
+
// Generate fixture file for each category
|
|
911
|
+
for (const [category, categoryPatterns] of byCategory.entries()) {
|
|
912
|
+
const fixturePath = resolve(basePath, `${category}.fixture.ts`);
|
|
913
|
+
const content = this.generateFixtureContent(categoryPatterns);
|
|
914
|
+
// Create directory if needed
|
|
915
|
+
const dir = dirname(fixturePath);
|
|
916
|
+
if (!existsSync(dir)) {
|
|
917
|
+
mkdirSync(dir, { recursive: true });
|
|
918
|
+
// Automatically add to .gitignore when directory is created
|
|
919
|
+
this.ensureGitignore(basePath);
|
|
920
|
+
}
|
|
921
|
+
writeFileSync(fixturePath, content, 'utf-8');
|
|
922
|
+
fixtures.push({
|
|
923
|
+
path: fixturePath,
|
|
924
|
+
patterns: categoryPatterns.map((p) => p.id),
|
|
925
|
+
});
|
|
926
|
+
}
|
|
927
|
+
return fixtures;
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* Generate fixture file content.
|
|
931
|
+
*/
|
|
932
|
+
generateFixtureContent(patterns) {
|
|
933
|
+
const lines = [];
|
|
934
|
+
lines.push('/**');
|
|
935
|
+
lines.push(` * Learned Patterns - ${patterns[0]?.category ?? 'Unknown'}`);
|
|
936
|
+
lines.push(' * Generated by learn-patterns tool');
|
|
937
|
+
lines.push(' * Auto-anonymized examples from real-world code');
|
|
938
|
+
lines.push(' */');
|
|
939
|
+
lines.push('');
|
|
940
|
+
for (const pattern of patterns) {
|
|
941
|
+
lines.push(`// Pattern: ${pattern.name}`);
|
|
942
|
+
lines.push(`// Occurrences: ${pattern.occurrences}`);
|
|
943
|
+
lines.push(`// Complexity: ${pattern.complexity}`);
|
|
944
|
+
lines.push(`// Description: ${pattern.description}`);
|
|
945
|
+
lines.push('');
|
|
946
|
+
for (let i = 0; i < pattern.examples.length; i++) {
|
|
947
|
+
const example = pattern.examples[i];
|
|
948
|
+
lines.push(`// Example ${i + 1}:`);
|
|
949
|
+
lines.push(example?.code ?? '');
|
|
950
|
+
lines.push('');
|
|
951
|
+
}
|
|
952
|
+
lines.push('');
|
|
953
|
+
}
|
|
954
|
+
return lines.join('\n');
|
|
955
|
+
}
|
|
956
|
+
/**
|
|
957
|
+
* Generate rule files (stub).
|
|
958
|
+
*/
|
|
959
|
+
generateRules(patterns, outputPath) {
|
|
960
|
+
// Simplified - would generate actual rule templates in production
|
|
961
|
+
return patterns.map((p) => ({
|
|
962
|
+
path: `${outputPath ?? './learned-rules'}/${p.id}.rule.ts`,
|
|
963
|
+
ruleIds: [p.suggestedRule?.ruleId ?? p.id],
|
|
964
|
+
}));
|
|
965
|
+
}
|
|
966
|
+
/**
|
|
967
|
+
* Format pattern name from type.
|
|
968
|
+
*/
|
|
969
|
+
formatPatternName(type) {
|
|
970
|
+
return type
|
|
971
|
+
.split('-')
|
|
972
|
+
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
|
|
973
|
+
.join(' ');
|
|
974
|
+
}
|
|
975
|
+
/**
|
|
976
|
+
* Generate pattern description.
|
|
977
|
+
*/
|
|
978
|
+
generatePatternDescription(type, patterns) {
|
|
979
|
+
const count = patterns.length;
|
|
980
|
+
const files = new Set(patterns.map((p) => p.filePath)).size;
|
|
981
|
+
// Special handling for inheritance patterns
|
|
982
|
+
if (type === 'inheritance-pattern') {
|
|
983
|
+
const withLifecycleHooks = patterns.filter((p) => p.metadata['hasLifecycleHooks'] === true).length;
|
|
984
|
+
const abstractClasses = patterns.filter((p) => p.metadata['isAbstract'] === true).length;
|
|
985
|
+
return `Found ${count} inheritance relationships across ${files} files. ${withLifecycleHooks} include lifecycle hooks, ${abstractClasses} extend abstract classes. Consider refactoring to composition using dependency injection.`;
|
|
986
|
+
}
|
|
987
|
+
return `Found ${count} instances of ${this.formatPatternName(type)} pattern across ${files} files. This pattern may indicate opportunities for refactoring or architectural improvements.`;
|
|
988
|
+
}
|
|
989
|
+
/**
|
|
990
|
+
* Generate suggested rule for pattern.
|
|
991
|
+
*/
|
|
992
|
+
generateSuggestedRule(type, category) {
|
|
993
|
+
return {
|
|
994
|
+
ruleId: `learned:${type}`,
|
|
995
|
+
severity: 'warning',
|
|
996
|
+
detection: `Detects ${type} pattern in ${category}`,
|
|
997
|
+
};
|
|
998
|
+
}
|
|
999
|
+
/**
|
|
1000
|
+
* Count patterns by category.
|
|
1001
|
+
*/
|
|
1002
|
+
countByCategory(patterns) {
|
|
1003
|
+
const counts = {};
|
|
1004
|
+
for (const pattern of patterns) {
|
|
1005
|
+
counts[pattern.category] = (counts[pattern.category] ?? 0) + 1;
|
|
1006
|
+
}
|
|
1007
|
+
return counts;
|
|
1008
|
+
}
|
|
1009
|
+
/**
|
|
1010
|
+
* Count patterns by complexity.
|
|
1011
|
+
*/
|
|
1012
|
+
countByComplexity(patterns) {
|
|
1013
|
+
const counts = {};
|
|
1014
|
+
for (const pattern of patterns) {
|
|
1015
|
+
counts[pattern.complexity] = (counts[pattern.complexity] ?? 0) + 1;
|
|
1016
|
+
}
|
|
1017
|
+
return counts;
|
|
1018
|
+
}
|
|
1019
|
+
/**
|
|
1020
|
+
* Ensure output directory is in .gitignore.
|
|
1021
|
+
* Automatically adds the directory to .gitignore when it's created.
|
|
1022
|
+
*/
|
|
1023
|
+
ensureGitignore(outputPath) {
|
|
1024
|
+
try {
|
|
1025
|
+
// Resolve the absolute path
|
|
1026
|
+
const absoluteOutputPath = resolve(outputPath);
|
|
1027
|
+
const currentDir = process.cwd();
|
|
1028
|
+
// Find .gitignore file (walk up from current directory)
|
|
1029
|
+
let gitignorePath = null;
|
|
1030
|
+
let searchDir = currentDir;
|
|
1031
|
+
// Search up to 5 levels for .gitignore
|
|
1032
|
+
for (let i = 0; i < 5; i++) {
|
|
1033
|
+
const candidatePath = resolve(searchDir, '.gitignore');
|
|
1034
|
+
if (existsSync(candidatePath)) {
|
|
1035
|
+
gitignorePath = candidatePath;
|
|
1036
|
+
break;
|
|
1037
|
+
}
|
|
1038
|
+
const parentDir = dirname(searchDir);
|
|
1039
|
+
if (parentDir === searchDir) {
|
|
1040
|
+
break;
|
|
1041
|
+
} // Reached root
|
|
1042
|
+
searchDir = parentDir;
|
|
1043
|
+
}
|
|
1044
|
+
// Calculate relative path from .gitignore location
|
|
1045
|
+
const gitignoreDir = gitignorePath ? dirname(gitignorePath) : currentDir;
|
|
1046
|
+
let relativeOutputPath = absoluteOutputPath.startsWith(gitignoreDir)
|
|
1047
|
+
? absoluteOutputPath.substring(gitignoreDir.length + 1)
|
|
1048
|
+
: outputPath;
|
|
1049
|
+
// Normalize path separators and ensure it ends with /
|
|
1050
|
+
relativeOutputPath = relativeOutputPath.replaceAll('\\', '/');
|
|
1051
|
+
if (!relativeOutputPath.endsWith('/')) {
|
|
1052
|
+
relativeOutputPath += '/';
|
|
1053
|
+
}
|
|
1054
|
+
// Ensure it starts with / for root-relative paths
|
|
1055
|
+
if (!relativeOutputPath.startsWith('/')) {
|
|
1056
|
+
relativeOutputPath = '/' + relativeOutputPath;
|
|
1057
|
+
}
|
|
1058
|
+
// Read existing .gitignore or create new one
|
|
1059
|
+
let gitignoreContent = '';
|
|
1060
|
+
if (gitignorePath && existsSync(gitignorePath)) {
|
|
1061
|
+
gitignoreContent = readFileSync(gitignorePath, 'utf-8');
|
|
1062
|
+
}
|
|
1063
|
+
else {
|
|
1064
|
+
// Create .gitignore in current directory
|
|
1065
|
+
gitignorePath = resolve(currentDir, '.gitignore');
|
|
1066
|
+
}
|
|
1067
|
+
// Check if path already exists in .gitignore
|
|
1068
|
+
const lines = gitignoreContent.split('\n');
|
|
1069
|
+
const pathExists = lines.some((line) => {
|
|
1070
|
+
const trimmed = line.trim();
|
|
1071
|
+
return (trimmed === relativeOutputPath ||
|
|
1072
|
+
trimmed === relativeOutputPath.slice(0, -1) || // Without trailing slash
|
|
1073
|
+
trimmed === outputPath ||
|
|
1074
|
+
trimmed === `${outputPath}/`);
|
|
1075
|
+
});
|
|
1076
|
+
if (!pathExists) {
|
|
1077
|
+
// Add entry to .gitignore
|
|
1078
|
+
const entry = `\n# Auto-generated pattern discovery output (learn-patterns tool)\n${relativeOutputPath}\n`;
|
|
1079
|
+
const updatedContent = gitignoreContent.trimEnd() + entry;
|
|
1080
|
+
writeFileSync(gitignorePath, updatedContent, 'utf-8');
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
catch (error) {
|
|
1084
|
+
// Silently fail - .gitignore management is not critical
|
|
1085
|
+
console.warn('Warning: Could not update .gitignore:', error.message);
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
//# sourceMappingURL=learn-patterns.js.map
|