pikakit 1.0.8 → 1.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -2
- package/bin/lib/commands/install.js +1 -1
- package/lib/agent-cli/dashboard/index.html +300 -322
- package/lib/agent-cli/lib/ab-testing.js +508 -0
- package/lib/agent-cli/lib/causality-engine.js +623 -0
- package/lib/agent-cli/lib/dashboard-data.js +365 -0
- package/lib/agent-cli/lib/fix.js +1 -1
- package/lib/agent-cli/lib/metrics-collector.js +523 -0
- package/lib/agent-cli/lib/metrics-schema.js +410 -0
- package/lib/agent-cli/lib/precision-skill-generator.js +584 -0
- package/lib/agent-cli/lib/recall.js +1 -1
- package/lib/agent-cli/lib/reinforcement.js +610 -0
- package/lib/agent-cli/lib/ui/index.js +37 -14
- package/lib/agent-cli/scripts/dashboard_server.js +189 -69
- package/package.json +2 -2
- package/lib/agent-cli/dashboard/dashboard_server.js +0 -340
- package/lib/agent-cli/lib/auto-learn.js +0 -319
- package/lib/agent-cli/scripts/adaptive_engine.js +0 -381
- package/lib/agent-cli/scripts/error_sensor.js +0 -565
- package/lib/agent-cli/scripts/learn_from_failure.js +0 -225
- package/lib/agent-cli/scripts/pattern_analyzer.js +0 -781
- package/lib/agent-cli/scripts/skill_injector.js +0 -387
- package/lib/agent-cli/scripts/success_sensor.js +0 -500
- package/lib/agent-cli/scripts/user_correction_sensor.js +0 -426
- package/lib/agent-cli/services/auto-learn-service.js +0 -247
|
@@ -1,340 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
/**
|
|
3
|
-
* Dashboard Server - Local web server for Auto-Learn Dashboard
|
|
4
|
-
*
|
|
5
|
-
* Bundled with PikaKit CLI
|
|
6
|
-
*
|
|
7
|
-
* Serves:
|
|
8
|
-
* - Static dashboard HTML
|
|
9
|
-
* - API endpoints for data
|
|
10
|
-
*
|
|
11
|
-
* Usage:
|
|
12
|
-
* node dashboard_server.js --port 3030
|
|
13
|
-
*/
|
|
14
|
-
|
|
15
|
-
import fs from 'fs';
|
|
16
|
-
import path from 'path';
|
|
17
|
-
import http from 'http';
|
|
18
|
-
import { fileURLToPath } from 'url';
|
|
19
|
-
|
|
20
|
-
const __filename = fileURLToPath(import.meta.url);
|
|
21
|
-
const __dirname = path.dirname(__filename);
|
|
22
|
-
|
|
23
|
-
// Colors
|
|
24
|
-
const c = {
|
|
25
|
-
reset: '\x1b[0m',
|
|
26
|
-
red: '\x1b[31m',
|
|
27
|
-
green: '\x1b[32m',
|
|
28
|
-
yellow: '\x1b[33m',
|
|
29
|
-
cyan: '\x1b[36m',
|
|
30
|
-
gray: '\x1b[90m',
|
|
31
|
-
bold: '\x1b[1m'
|
|
32
|
-
};
|
|
33
|
-
|
|
34
|
-
// Find project root (where .agent folder exists)
|
|
35
|
-
function findProjectRoot() {
|
|
36
|
-
let current = process.cwd();
|
|
37
|
-
while (current !== path.dirname(current)) {
|
|
38
|
-
if (fs.existsSync(path.join(current, '.agent'))) {
|
|
39
|
-
return current;
|
|
40
|
-
}
|
|
41
|
-
current = path.dirname(current);
|
|
42
|
-
}
|
|
43
|
-
return process.cwd();
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
// Find knowledge path - check multiple locations
|
|
47
|
-
function findKnowledgePath() {
|
|
48
|
-
const projectRoot = findProjectRoot();
|
|
49
|
-
const possiblePaths = [
|
|
50
|
-
path.join(projectRoot, '.agent', 'knowledge'),
|
|
51
|
-
path.join(projectRoot, '.agent', 'agentskillskit', '.agent', 'knowledge'),
|
|
52
|
-
];
|
|
53
|
-
|
|
54
|
-
for (const p of possiblePaths) {
|
|
55
|
-
if (fs.existsSync(p)) {
|
|
56
|
-
return p;
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// Create default if none exists
|
|
61
|
-
const defaultPath = path.join(projectRoot, '.agent', 'knowledge');
|
|
62
|
-
fs.mkdirSync(defaultPath, { recursive: true });
|
|
63
|
-
return defaultPath;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
const knowledgePath = findKnowledgePath();
|
|
67
|
-
// Dashboard is in same directory as this server
|
|
68
|
-
const dashboardPath = __dirname;
|
|
69
|
-
|
|
70
|
-
// Load JSON files
|
|
71
|
-
function loadJson(filename) {
|
|
72
|
-
const filePath = path.join(knowledgePath, filename);
|
|
73
|
-
try {
|
|
74
|
-
if (fs.existsSync(filePath)) {
|
|
75
|
-
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
76
|
-
}
|
|
77
|
-
} catch { }
|
|
78
|
-
return null;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
// API handlers
|
|
82
|
-
const api = {
|
|
83
|
-
'/api/errors': () => {
|
|
84
|
-
const data = loadJson('detected-errors.json');
|
|
85
|
-
return data || { errors: [], totalErrors: 0 };
|
|
86
|
-
},
|
|
87
|
-
|
|
88
|
-
'/api/corrections': () => {
|
|
89
|
-
const data = loadJson('user-corrections.json');
|
|
90
|
-
return data || { corrections: [], totalCorrections: 0 };
|
|
91
|
-
},
|
|
92
|
-
|
|
93
|
-
'/api/lessons': () => {
|
|
94
|
-
const data = loadJson('lessons-learned.json');
|
|
95
|
-
return data || { lessons: [] };
|
|
96
|
-
},
|
|
97
|
-
|
|
98
|
-
'/api/patterns': () => {
|
|
99
|
-
const data = loadJson('patterns.json');
|
|
100
|
-
return data || { errors: {}, corrections: {}, highFrequency: [] };
|
|
101
|
-
},
|
|
102
|
-
|
|
103
|
-
'/api/successes': () => {
|
|
104
|
-
const data = loadJson('successes.json');
|
|
105
|
-
return data || { successes: [], totalSuccesses: 0 };
|
|
106
|
-
},
|
|
107
|
-
|
|
108
|
-
'/api/summary': () => {
|
|
109
|
-
const errors = loadJson('detected-errors.json');
|
|
110
|
-
const corrections = loadJson('user-corrections.json');
|
|
111
|
-
const lessons = loadJson('lessons-learned.json');
|
|
112
|
-
const patterns = loadJson('patterns.json');
|
|
113
|
-
const successes = loadJson('successes.json');
|
|
114
|
-
|
|
115
|
-
// Calculate success/failure ratio
|
|
116
|
-
const totalErrors = errors?.errors?.length || 0;
|
|
117
|
-
const totalCorrections = corrections?.corrections?.length || 0;
|
|
118
|
-
const totalSuccesses = successes?.successes?.length || 0;
|
|
119
|
-
const totalFailures = totalErrors + totalCorrections;
|
|
120
|
-
const total = totalFailures + totalSuccesses;
|
|
121
|
-
|
|
122
|
-
let ratio = 0;
|
|
123
|
-
let status = 'NO_DATA';
|
|
124
|
-
if (total > 0) {
|
|
125
|
-
ratio = Math.round((totalSuccesses / total) * 100) / 100;
|
|
126
|
-
if (ratio > 0.7) status = 'EXCELLENT';
|
|
127
|
-
else if (ratio > 0.5) status = 'GOOD';
|
|
128
|
-
else if (ratio > 0.3) status = 'LEARNING';
|
|
129
|
-
else status = 'NEEDS_ATTENTION';
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
// Group successes by pattern
|
|
133
|
-
const successesByPattern = {};
|
|
134
|
-
for (const s of (successes?.successes || [])) {
|
|
135
|
-
successesByPattern[s.pattern] = (successesByPattern[s.pattern] || 0) + 1;
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
return {
|
|
139
|
-
errors: {
|
|
140
|
-
total: totalErrors,
|
|
141
|
-
byType: patterns?.errors?.byType || {},
|
|
142
|
-
bySeverity: patterns?.errors?.bySeverity || {}
|
|
143
|
-
},
|
|
144
|
-
corrections: {
|
|
145
|
-
total: totalCorrections,
|
|
146
|
-
byCategory: patterns?.corrections?.byCategory || {}
|
|
147
|
-
},
|
|
148
|
-
successes: {
|
|
149
|
-
total: totalSuccesses,
|
|
150
|
-
byPattern: successesByPattern
|
|
151
|
-
},
|
|
152
|
-
balance: {
|
|
153
|
-
ratio,
|
|
154
|
-
status,
|
|
155
|
-
failures: totalFailures,
|
|
156
|
-
successes: totalSuccesses
|
|
157
|
-
},
|
|
158
|
-
lessons: lessons?.lessons?.length || 0,
|
|
159
|
-
highFrequency: patterns?.highFrequency || [],
|
|
160
|
-
lastUpdated: patterns?.analyzedAt || null,
|
|
161
|
-
knowledgePath: knowledgePath
|
|
162
|
-
};
|
|
163
|
-
},
|
|
164
|
-
|
|
165
|
-
'/api/trends': () => {
|
|
166
|
-
const errors = loadJson('detected-errors.json');
|
|
167
|
-
const successes = loadJson('successes.json');
|
|
168
|
-
|
|
169
|
-
const errorList = errors?.errors || [];
|
|
170
|
-
const successList = successes?.successes || [];
|
|
171
|
-
|
|
172
|
-
// Calculate trends
|
|
173
|
-
const now = new Date();
|
|
174
|
-
const oneWeekAgo = new Date(now - 7 * 24 * 60 * 60 * 1000);
|
|
175
|
-
const twoWeeksAgo = new Date(now - 14 * 24 * 60 * 60 * 1000);
|
|
176
|
-
|
|
177
|
-
const thisWeekErrors = errorList.filter(e => new Date(e.timestamp) > oneWeekAgo).length;
|
|
178
|
-
const lastWeekErrors = errorList.filter(e => {
|
|
179
|
-
const d = new Date(e.timestamp);
|
|
180
|
-
return d > twoWeeksAgo && d <= oneWeekAgo;
|
|
181
|
-
}).length;
|
|
182
|
-
|
|
183
|
-
const thisWeekSuccesses = successList.filter(s => {
|
|
184
|
-
const d = new Date(s.detectedAt || s.timestamp);
|
|
185
|
-
return d > oneWeekAgo;
|
|
186
|
-
}).length;
|
|
187
|
-
|
|
188
|
-
// Daily breakdown (last 7 days)
|
|
189
|
-
const daily = [];
|
|
190
|
-
for (let i = 6; i >= 0; i--) {
|
|
191
|
-
const date = new Date(now - i * 24 * 60 * 60 * 1000);
|
|
192
|
-
const dateStr = date.toISOString().split('T')[0];
|
|
193
|
-
|
|
194
|
-
const dayErrors = errorList.filter(e =>
|
|
195
|
-
e.timestamp && e.timestamp.startsWith(dateStr)
|
|
196
|
-
).length;
|
|
197
|
-
|
|
198
|
-
const daySuccesses = successList.filter(s =>
|
|
199
|
-
(s.detectedAt || s.timestamp || '').startsWith(dateStr)
|
|
200
|
-
).length;
|
|
201
|
-
|
|
202
|
-
daily.push({ date: dateStr, errors: dayErrors, successes: daySuccesses });
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
const errorTrend = lastWeekErrors > 0
|
|
206
|
-
? Math.round(((thisWeekErrors - lastWeekErrors) / lastWeekErrors) * 100)
|
|
207
|
-
: 0;
|
|
208
|
-
|
|
209
|
-
let healthStatus = 'STABLE';
|
|
210
|
-
if (errorTrend < 0) healthStatus = 'IMPROVING';
|
|
211
|
-
else if (errorTrend > 20) healthStatus = 'DECLINING';
|
|
212
|
-
|
|
213
|
-
return {
|
|
214
|
-
thisWeek: { errors: thisWeekErrors, successes: thisWeekSuccesses },
|
|
215
|
-
lastWeek: { errors: lastWeekErrors },
|
|
216
|
-
trends: { errorChange: errorTrend },
|
|
217
|
-
healthStatus,
|
|
218
|
-
daily
|
|
219
|
-
};
|
|
220
|
-
}
|
|
221
|
-
};
|
|
222
|
-
|
|
223
|
-
// MIME types
|
|
224
|
-
const mimeTypes = {
|
|
225
|
-
'.html': 'text/html',
|
|
226
|
-
'.css': 'text/css',
|
|
227
|
-
'.js': 'application/javascript',
|
|
228
|
-
'.json': 'application/json',
|
|
229
|
-
'.png': 'image/png',
|
|
230
|
-
'.jpg': 'image/jpeg',
|
|
231
|
-
'.svg': 'image/svg+xml'
|
|
232
|
-
};
|
|
233
|
-
|
|
234
|
-
// Create server
|
|
235
|
-
function createServer(port) {
|
|
236
|
-
const server = http.createServer((req, res) => {
|
|
237
|
-
const url = req.url.split('?')[0];
|
|
238
|
-
|
|
239
|
-
// CORS headers for local development
|
|
240
|
-
res.setHeader('Access-Control-Allow-Origin', '*');
|
|
241
|
-
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
|
242
|
-
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
|
|
243
|
-
|
|
244
|
-
// Handle API requests
|
|
245
|
-
if (url.startsWith('/api/')) {
|
|
246
|
-
const handler = api[url];
|
|
247
|
-
if (handler) {
|
|
248
|
-
res.setHeader('Content-Type', 'application/json');
|
|
249
|
-
res.writeHead(200);
|
|
250
|
-
res.end(JSON.stringify(handler()));
|
|
251
|
-
} else {
|
|
252
|
-
res.writeHead(404);
|
|
253
|
-
res.end(JSON.stringify({ error: 'Not found' }));
|
|
254
|
-
}
|
|
255
|
-
return;
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
// Serve static files
|
|
259
|
-
let filePath = url === '/' ? '/index.html' : url;
|
|
260
|
-
filePath = path.join(dashboardPath, filePath);
|
|
261
|
-
|
|
262
|
-
if (fs.existsSync(filePath)) {
|
|
263
|
-
const ext = path.extname(filePath);
|
|
264
|
-
const mimeType = mimeTypes[ext] || 'text/plain';
|
|
265
|
-
|
|
266
|
-
res.setHeader('Content-Type', mimeType);
|
|
267
|
-
res.writeHead(200);
|
|
268
|
-
res.end(fs.readFileSync(filePath));
|
|
269
|
-
} else {
|
|
270
|
-
res.writeHead(404);
|
|
271
|
-
res.end('Not found');
|
|
272
|
-
}
|
|
273
|
-
});
|
|
274
|
-
|
|
275
|
-
return server;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
function startServer(port = 3030) {
|
|
279
|
-
const server = createServer(port);
|
|
280
|
-
|
|
281
|
-
server.listen(port, () => {
|
|
282
|
-
console.log(`${c.cyan}╔════════════════════════════════════════╗${c.reset}`);
|
|
283
|
-
console.log(`${c.cyan}║${c.reset} 🧠 Auto-Learn Dashboard Server ${c.cyan}║${c.reset}`);
|
|
284
|
-
console.log(`${c.cyan}╚════════════════════════════════════════╝${c.reset}\n`);
|
|
285
|
-
console.log(`${c.green}✓ Server running at:${c.reset}`);
|
|
286
|
-
console.log(` ${c.bold}http://localhost:${port}${c.reset}\n`);
|
|
287
|
-
console.log(`${c.gray}API Endpoints:${c.reset}`);
|
|
288
|
-
console.log(` GET /api/errors - Detected errors`);
|
|
289
|
-
console.log(` GET /api/corrections - User corrections`);
|
|
290
|
-
console.log(` GET /api/lessons - Lessons learned`);
|
|
291
|
-
console.log(` GET /api/patterns - Pattern analysis`);
|
|
292
|
-
console.log(` GET /api/summary - Dashboard summary\n`);
|
|
293
|
-
console.log(`${c.yellow}Press Ctrl+C to stop${c.reset}`);
|
|
294
|
-
});
|
|
295
|
-
|
|
296
|
-
server.on('error', (err) => {
|
|
297
|
-
if (err.code === 'EADDRINUSE') {
|
|
298
|
-
console.log(`${c.red}Error: Port ${port} is already in use${c.reset}`);
|
|
299
|
-
console.log(`${c.gray}Try: node dashboard_server.js --port ${port + 1}${c.reset}`);
|
|
300
|
-
} else {
|
|
301
|
-
console.error(`${c.red}Server error:${c.reset}`, err);
|
|
302
|
-
}
|
|
303
|
-
process.exit(1);
|
|
304
|
-
});
|
|
305
|
-
|
|
306
|
-
return server;
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
// Parse CLI args
|
|
310
|
-
const args = process.argv.slice(2);
|
|
311
|
-
|
|
312
|
-
if (args.includes('--start') || args.includes('-s') || args.length === 0 || args.includes('--port') || args.includes('-p')) {
|
|
313
|
-
let port = 3030;
|
|
314
|
-
const portIdx = args.findIndex(a => a === '--port' || a === '-p');
|
|
315
|
-
if (portIdx >= 0 && args[portIdx + 1]) {
|
|
316
|
-
port = parseInt(args[portIdx + 1], 10);
|
|
317
|
-
}
|
|
318
|
-
startServer(port);
|
|
319
|
-
} else if (args.includes('--help') || args.includes('-h')) {
|
|
320
|
-
console.log(`${c.cyan}dashboard_server - Auto-Learn Dashboard Web Server${c.reset}
|
|
321
|
-
|
|
322
|
-
${c.bold}Usage:${c.reset}
|
|
323
|
-
node dashboard_server.js Start server (default port 3030)
|
|
324
|
-
node dashboard_server.js --port 8080 Start on custom port
|
|
325
|
-
node dashboard_server.js --help Show this help
|
|
326
|
-
|
|
327
|
-
${c.bold}API Endpoints:${c.reset}
|
|
328
|
-
GET /api/errors - All detected errors
|
|
329
|
-
GET /api/corrections - All user corrections
|
|
330
|
-
GET /api/lessons - All lessons learned
|
|
331
|
-
GET /api/patterns - Pattern analysis results
|
|
332
|
-
GET /api/summary - Dashboard summary data
|
|
333
|
-
|
|
334
|
-
${c.bold}Example:${c.reset}
|
|
335
|
-
node dashboard_server.js --port 3030
|
|
336
|
-
# Open http://localhost:3030 in browser
|
|
337
|
-
`);
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
export { createServer, startServer };
|
|
@@ -1,319 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
/**
|
|
3
|
-
* Smart Auto-Learn - True Self-Learning Engine
|
|
4
|
-
*
|
|
5
|
-
* Automatically learns from:
|
|
6
|
-
* 1. ESLint output (runs ESLint and parses)
|
|
7
|
-
* 2. Test failures (runs tests and parses)
|
|
8
|
-
* 3. TypeScript errors (runs tsc and parses)
|
|
9
|
-
*
|
|
10
|
-
* Usage:
|
|
11
|
-
* agent auto-learn # Run all
|
|
12
|
-
* agent auto-learn --eslint # ESLint only
|
|
13
|
-
* agent auto-learn --test # Test failures only
|
|
14
|
-
* agent auto-learn --typescript # TypeScript only
|
|
15
|
-
*/
|
|
16
|
-
|
|
17
|
-
import fs from "fs";
|
|
18
|
-
import path from "path";
|
|
19
|
-
import { execSync, spawnSync } from "child_process";
|
|
20
|
-
import { loadKnowledge, saveKnowledge } from "./recall.js";
|
|
21
|
-
import { VERSION } from "./config.js";
|
|
22
|
-
|
|
23
|
-
// ============================================================================
|
|
24
|
-
// ESLINT AUTO-LEARN
|
|
25
|
-
// ============================================================================
|
|
26
|
-
|
|
27
|
-
const ESLINT_PATTERN_MAP = {
|
|
28
|
-
"no-console": { pattern: "console\\.(log|warn|error|info|debug)", message: "Avoid console statements in production" },
|
|
29
|
-
"no-debugger": { pattern: "\\bdebugger\\b", message: "Remove debugger statements" },
|
|
30
|
-
"no-var": { pattern: "\\bvar\\s+\\w", message: "Use const/let instead of var" },
|
|
31
|
-
"eqeqeq": { pattern: "[^!=]==[^=]", message: "Use === instead of ==" },
|
|
32
|
-
"no-eval": { pattern: "\\beval\\s*\\(", message: "Avoid eval() for security" },
|
|
33
|
-
"no-alert": { pattern: "\\balert\\s*\\(", message: "Avoid alert() in production" },
|
|
34
|
-
"no-implicit-globals": { pattern: "^(?!const|let|var|function|class|import|export)", message: "Avoid implicit globals" },
|
|
35
|
-
"prefer-const": { pattern: "\\blet\\s+\\w+\\s*=\\s*[^;]+;(?![\\s\\S]*\\1\\s*=)", message: "Use const for variables that are never reassigned" },
|
|
36
|
-
"no-unused-expressions": { pattern: "^\\s*['\"`]use strict['\"`];?\\s*$", message: "Remove unused expressions" },
|
|
37
|
-
"semi": { pattern: "[^;{}]\\s*$", message: "Missing semicolon" },
|
|
38
|
-
"quotes": { pattern: '(?<![\\w])"(?![^"]*"[,\\]\\}\\)])', message: "Prefer single quotes" },
|
|
39
|
-
"no-empty": { pattern: "\\{\\s*\\}", message: "Empty block statement" },
|
|
40
|
-
"no-extra-semi": { pattern: ";;", message: "Unnecessary semicolon" },
|
|
41
|
-
"no-unreachable": { pattern: "(?:return|throw|break|continue)[^}]*[\\n\\r]+[^}]+", message: "Unreachable code" }
|
|
42
|
-
};
|
|
43
|
-
|
|
44
|
-
function runEslintAutoLearn(projectRoot) {
|
|
45
|
-
console.log("\n🔍 Running ESLint analysis...\n");
|
|
46
|
-
|
|
47
|
-
try {
|
|
48
|
-
// Try to run ESLint with JSON output
|
|
49
|
-
const result = spawnSync("npx", ["eslint", ".", "--format", "json", "--no-error-on-unmatched-pattern"], {
|
|
50
|
-
cwd: projectRoot,
|
|
51
|
-
encoding: "utf8",
|
|
52
|
-
shell: true,
|
|
53
|
-
timeout: 60000
|
|
54
|
-
});
|
|
55
|
-
|
|
56
|
-
if (!result.stdout) {
|
|
57
|
-
console.log(" ℹ️ ESLint not configured or no files to lint.");
|
|
58
|
-
return [];
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
const eslintResults = JSON.parse(result.stdout);
|
|
62
|
-
const ruleViolations = {};
|
|
63
|
-
|
|
64
|
-
eslintResults.forEach(file => {
|
|
65
|
-
if (!file.messages) return;
|
|
66
|
-
file.messages.forEach(msg => {
|
|
67
|
-
if (!msg.ruleId) return;
|
|
68
|
-
if (!ruleViolations[msg.ruleId]) {
|
|
69
|
-
ruleViolations[msg.ruleId] = {
|
|
70
|
-
rule: msg.ruleId,
|
|
71
|
-
count: 0,
|
|
72
|
-
severity: msg.severity === 2 ? "ERROR" : "WARNING",
|
|
73
|
-
sample: msg.message
|
|
74
|
-
};
|
|
75
|
-
}
|
|
76
|
-
ruleViolations[msg.ruleId].count++;
|
|
77
|
-
});
|
|
78
|
-
});
|
|
79
|
-
|
|
80
|
-
return Object.values(ruleViolations).sort((a, b) => b.count - a.count);
|
|
81
|
-
} catch (e) {
|
|
82
|
-
console.log(" ⚠️ ESLint analysis skipped:", e.message);
|
|
83
|
-
return [];
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
// ============================================================================
|
|
88
|
-
// TEST FAILURE AUTO-LEARN
|
|
89
|
-
// ============================================================================
|
|
90
|
-
|
|
91
|
-
const TEST_PATTERN_MAP = {
|
|
92
|
-
"undefined is not a function": { pattern: "\\w+\\s*\\(", message: "Function may be undefined before call" },
|
|
93
|
-
"cannot read property": { pattern: "\\w+\\.\\w+", message: "Object property access may fail if undefined" },
|
|
94
|
-
"null is not an object": { pattern: "\\.\\w+", message: "Null check needed before property access" },
|
|
95
|
-
"expected.*to equal": { pattern: "expect\\s*\\(", message: "Assertion expectation mismatch" },
|
|
96
|
-
"timeout": { pattern: "async|await|Promise", message: "Async operation may need longer timeout" },
|
|
97
|
-
"not defined": { pattern: "\\b\\w+\\b", message: "Variable may not be defined in scope" }
|
|
98
|
-
};
|
|
99
|
-
|
|
100
|
-
function runTestAutoLearn(projectRoot) {
|
|
101
|
-
console.log("\n🧪 Running test analysis...\n");
|
|
102
|
-
|
|
103
|
-
try {
|
|
104
|
-
// Try common test runners
|
|
105
|
-
const testCommands = [
|
|
106
|
-
{ cmd: "npm", args: ["test", "--", "--json", "--passWithNoTests"], name: "npm test" },
|
|
107
|
-
{ cmd: "npx", args: ["vitest", "run", "--reporter=json"], name: "vitest" },
|
|
108
|
-
{ cmd: "npx", args: ["jest", "--json", "--passWithNoTests"], name: "jest" }
|
|
109
|
-
];
|
|
110
|
-
|
|
111
|
-
for (const tc of testCommands) {
|
|
112
|
-
const result = spawnSync(tc.cmd, tc.args, {
|
|
113
|
-
cwd: projectRoot,
|
|
114
|
-
encoding: "utf8",
|
|
115
|
-
shell: true,
|
|
116
|
-
timeout: 120000
|
|
117
|
-
});
|
|
118
|
-
|
|
119
|
-
// Look for test failures in output
|
|
120
|
-
const output = result.stdout + result.stderr;
|
|
121
|
-
const failures = [];
|
|
122
|
-
|
|
123
|
-
// Parse failure messages
|
|
124
|
-
const failurePatterns = [
|
|
125
|
-
/FAIL\s+(.+)/g,
|
|
126
|
-
/✕\s+(.+)/g,
|
|
127
|
-
/Error:\s+(.+)/g,
|
|
128
|
-
/AssertionError:\s+(.+)/g
|
|
129
|
-
];
|
|
130
|
-
|
|
131
|
-
failurePatterns.forEach(regex => {
|
|
132
|
-
let match;
|
|
133
|
-
while ((match = regex.exec(output)) !== null) {
|
|
134
|
-
failures.push(match[1].trim());
|
|
135
|
-
}
|
|
136
|
-
});
|
|
137
|
-
|
|
138
|
-
if (failures.length > 0) {
|
|
139
|
-
console.log(` Found ${failures.length} test failure(s) from ${tc.name}`);
|
|
140
|
-
return failures.map(f => ({ message: f, source: tc.name }));
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
console.log(" ✅ All tests passing or no tests found.");
|
|
145
|
-
return [];
|
|
146
|
-
} catch (e) {
|
|
147
|
-
console.log(" ⚠️ Test analysis skipped:", e.message);
|
|
148
|
-
return [];
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
// ============================================================================
|
|
153
|
-
// TYPESCRIPT ERROR AUTO-LEARN
|
|
154
|
-
// ============================================================================
|
|
155
|
-
|
|
156
|
-
const TS_PATTERN_MAP = {
|
|
157
|
-
"TS2304": { pattern: "\\b\\w+\\b", message: "TypeScript: Cannot find name" },
|
|
158
|
-
"TS2322": { pattern: ":\\s*\\w+", message: "TypeScript: Type mismatch" },
|
|
159
|
-
"TS2345": { pattern: "\\(.*\\)", message: "TypeScript: Argument type mismatch" },
|
|
160
|
-
"TS2339": { pattern: "\\.\\w+", message: "TypeScript: Property does not exist" },
|
|
161
|
-
"TS7006": { pattern: "\\(\\w+\\)", message: "TypeScript: Parameter implicitly has 'any' type" },
|
|
162
|
-
"TS2531": { pattern: "\\w+\\.", message: "TypeScript: Object is possibly 'null'" },
|
|
163
|
-
"TS2532": { pattern: "\\w+\\.", message: "TypeScript: Object is possibly 'undefined'" }
|
|
164
|
-
};
|
|
165
|
-
|
|
166
|
-
function runTypescriptAutoLearn(projectRoot) {
|
|
167
|
-
console.log("\n📘 Running TypeScript analysis...\n");
|
|
168
|
-
|
|
169
|
-
try {
|
|
170
|
-
const result = spawnSync("npx", ["tsc", "--noEmit", "--pretty", "false"], {
|
|
171
|
-
cwd: projectRoot,
|
|
172
|
-
encoding: "utf8",
|
|
173
|
-
shell: true,
|
|
174
|
-
timeout: 60000
|
|
175
|
-
});
|
|
176
|
-
|
|
177
|
-
const output = result.stdout + result.stderr;
|
|
178
|
-
const errors = {};
|
|
179
|
-
|
|
180
|
-
// Parse TS errors: file(line,col): error TS1234: message
|
|
181
|
-
const tsErrorRegex = /error (TS\d+):\s*(.+)/g;
|
|
182
|
-
let match;
|
|
183
|
-
|
|
184
|
-
while ((match = tsErrorRegex.exec(output)) !== null) {
|
|
185
|
-
const code = match[1];
|
|
186
|
-
const message = match[2];
|
|
187
|
-
|
|
188
|
-
if (!errors[code]) {
|
|
189
|
-
errors[code] = { code, message, count: 0 };
|
|
190
|
-
}
|
|
191
|
-
errors[code].count++;
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
const errorList = Object.values(errors).sort((a, b) => b.count - a.count);
|
|
195
|
-
|
|
196
|
-
if (errorList.length > 0) {
|
|
197
|
-
console.log(` Found ${errorList.length} unique TypeScript error type(s)`);
|
|
198
|
-
} else {
|
|
199
|
-
console.log(" ✅ No TypeScript errors found.");
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
return errorList;
|
|
203
|
-
} catch (e) {
|
|
204
|
-
console.log(" ⚠️ TypeScript analysis skipped:", e.message);
|
|
205
|
-
return [];
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
// ============================================================================
|
|
210
|
-
// MAIN AUTO-LEARN ENGINE
|
|
211
|
-
// ============================================================================
|
|
212
|
-
|
|
213
|
-
function autoLearn(projectRoot, options = {}) {
|
|
214
|
-
console.log(`\n🧠 Smart Auto-Learn Engine v${VERSION}`);
|
|
215
|
-
console.log(`📂 Project: ${projectRoot}\n`);
|
|
216
|
-
console.log("─".repeat(50));
|
|
217
|
-
|
|
218
|
-
const db = loadKnowledge();
|
|
219
|
-
let totalAdded = 0;
|
|
220
|
-
|
|
221
|
-
// ESLint
|
|
222
|
-
if (!options.onlyTest && !options.onlyTypescript) {
|
|
223
|
-
const eslintViolations = runEslintAutoLearn(projectRoot);
|
|
224
|
-
|
|
225
|
-
eslintViolations.forEach(v => {
|
|
226
|
-
const mapping = ESLINT_PATTERN_MAP[v.rule];
|
|
227
|
-
if (!mapping) return;
|
|
228
|
-
|
|
229
|
-
// Check if already exists
|
|
230
|
-
if (db.lessons.some(l => l.pattern === mapping.pattern)) return;
|
|
231
|
-
|
|
232
|
-
const id = `AUTO-${String(db.lessons.length + 1).padStart(3, "0")}`;
|
|
233
|
-
db.lessons.push({
|
|
234
|
-
id,
|
|
235
|
-
pattern: mapping.pattern,
|
|
236
|
-
message: `${mapping.message} (ESLint: ${v.rule})`,
|
|
237
|
-
severity: v.severity,
|
|
238
|
-
source: "auto-eslint",
|
|
239
|
-
hitCount: v.count,
|
|
240
|
-
autoEscalated: false,
|
|
241
|
-
addedAt: new Date().toISOString()
|
|
242
|
-
});
|
|
243
|
-
totalAdded++;
|
|
244
|
-
console.log(` ✅ Auto-learned: [${id}] ${v.rule} (${v.count} occurrences)`);
|
|
245
|
-
});
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
// TypeScript
|
|
249
|
-
if (!options.onlyEslint && !options.onlyTest) {
|
|
250
|
-
const tsErrors = runTypescriptAutoLearn(projectRoot);
|
|
251
|
-
|
|
252
|
-
tsErrors.slice(0, 5).forEach(e => { // Top 5 only
|
|
253
|
-
const mapping = TS_PATTERN_MAP[e.code];
|
|
254
|
-
if (!mapping) return;
|
|
255
|
-
|
|
256
|
-
if (db.lessons.some(l => l.message.includes(e.code))) return;
|
|
257
|
-
|
|
258
|
-
const id = `AUTO-${String(db.lessons.length + 1).padStart(3, "0")}`;
|
|
259
|
-
db.lessons.push({
|
|
260
|
-
id,
|
|
261
|
-
pattern: mapping.pattern,
|
|
262
|
-
message: `${mapping.message} (${e.code})`,
|
|
263
|
-
severity: "WARNING",
|
|
264
|
-
source: "auto-typescript",
|
|
265
|
-
hitCount: e.count,
|
|
266
|
-
autoEscalated: false,
|
|
267
|
-
addedAt: new Date().toISOString()
|
|
268
|
-
});
|
|
269
|
-
totalAdded++;
|
|
270
|
-
console.log(` ✅ Auto-learned: [${id}] ${e.code} (${e.count} occurrences)`);
|
|
271
|
-
});
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
// Summary
|
|
275
|
-
console.log("\n" + "─".repeat(50));
|
|
276
|
-
|
|
277
|
-
if (totalAdded > 0) {
|
|
278
|
-
saveKnowledge(db);
|
|
279
|
-
console.log(`\n🎓 Auto-learned ${totalAdded} new pattern(s)!`);
|
|
280
|
-
console.log(`📊 Total lessons in memory: ${db.lessons.length}\n`);
|
|
281
|
-
} else {
|
|
282
|
-
console.log("\n✅ No new patterns discovered. Code looks clean!\n");
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
return totalAdded;
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
// ============================================================================
|
|
289
|
-
// CLI
|
|
290
|
-
// ============================================================================
|
|
291
|
-
|
|
292
|
-
const args = process.argv.slice(2);
|
|
293
|
-
const projectRoot = process.cwd();
|
|
294
|
-
|
|
295
|
-
if (args.includes("--help")) {
|
|
296
|
-
console.log(`
|
|
297
|
-
🧠 Smart Auto-Learn - True Self-Learning Engine
|
|
298
|
-
|
|
299
|
-
Usage:
|
|
300
|
-
agent auto-learn Run all analyzers
|
|
301
|
-
agent auto-learn --eslint ESLint only
|
|
302
|
-
agent auto-learn --typescript TypeScript only
|
|
303
|
-
agent auto-learn --test Test failures only
|
|
304
|
-
|
|
305
|
-
The engine automatically:
|
|
306
|
-
1. Runs ESLint and learns from violations
|
|
307
|
-
2. Runs TypeScript and learns from type errors
|
|
308
|
-
3. Runs tests and learns from failures
|
|
309
|
-
|
|
310
|
-
Patterns are automatically added to knowledge base!
|
|
311
|
-
`);
|
|
312
|
-
process.exit(0);
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
autoLearn(projectRoot, {
|
|
316
|
-
onlyEslint: args.includes("--eslint"),
|
|
317
|
-
onlyTypescript: args.includes("--typescript"),
|
|
318
|
-
onlyTest: args.includes("--test")
|
|
319
|
-
});
|