@theihtisham/agent-shadow-brain 5.0.1 → 5.2.0
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 +1159 -888
- package/dist/adapters/copilot.d.ts +14 -0
- package/dist/adapters/copilot.d.ts.map +1 -0
- package/dist/adapters/copilot.js +93 -0
- package/dist/adapters/copilot.js.map +1 -0
- package/dist/adapters/cursor.d.ts +13 -0
- package/dist/adapters/cursor.d.ts.map +1 -0
- package/dist/adapters/cursor.js +96 -0
- package/dist/adapters/cursor.js.map +1 -0
- package/dist/adapters/index.d.ts +4 -1
- package/dist/adapters/index.d.ts.map +1 -1
- package/dist/adapters/index.js +7 -3
- package/dist/adapters/index.js.map +1 -1
- package/dist/adapters/windsurf.d.ts +14 -0
- package/dist/adapters/windsurf.d.ts.map +1 -0
- package/dist/adapters/windsurf.js +107 -0
- package/dist/adapters/windsurf.js.map +1 -0
- package/dist/brain/code-dna.d.ts +70 -0
- package/dist/brain/code-dna.d.ts.map +1 -0
- package/dist/brain/code-dna.js +611 -0
- package/dist/brain/code-dna.js.map +1 -0
- package/dist/brain/fine-tuning-engine.d.ts +99 -0
- package/dist/brain/fine-tuning-engine.d.ts.map +1 -0
- package/dist/brain/fine-tuning-engine.js +681 -0
- package/dist/brain/fine-tuning-engine.js.map +1 -0
- package/dist/brain/global-brain.d.ts +56 -0
- package/dist/brain/global-brain.d.ts.map +1 -0
- package/dist/brain/global-brain.js +324 -0
- package/dist/brain/global-brain.js.map +1 -0
- package/dist/brain/intent-engine.d.ts +64 -0
- package/dist/brain/intent-engine.d.ts.map +1 -0
- package/dist/brain/intent-engine.js +374 -0
- package/dist/brain/intent-engine.js.map +1 -0
- package/dist/brain/l0-cache.d.ts +40 -0
- package/dist/brain/l0-cache.d.ts.map +1 -0
- package/dist/brain/l0-cache.js +176 -0
- package/dist/brain/l0-cache.js.map +1 -0
- package/dist/brain/lsp-server.d.ts +62 -0
- package/dist/brain/lsp-server.d.ts.map +1 -0
- package/dist/brain/lsp-server.js +480 -0
- package/dist/brain/lsp-server.js.map +1 -0
- package/dist/brain/mcp-server.d.ts +4 -0
- package/dist/brain/mcp-server.d.ts.map +1 -1
- package/dist/brain/mcp-server.js +91 -0
- package/dist/brain/mcp-server.js.map +1 -1
- package/dist/brain/orchestrator.d.ts +13 -0
- package/dist/brain/orchestrator.d.ts.map +1 -1
- package/dist/brain/orchestrator.js +25 -1
- package/dist/brain/orchestrator.js.map +1 -1
- package/dist/brain/session-hooks.d.ts +28 -0
- package/dist/brain/session-hooks.d.ts.map +1 -0
- package/dist/brain/session-hooks.js +475 -0
- package/dist/brain/session-hooks.js.map +1 -0
- package/dist/brain/smart-cache.d.ts +100 -0
- package/dist/brain/smart-cache.d.ts.map +1 -0
- package/dist/brain/smart-cache.js +417 -0
- package/dist/brain/smart-cache.js.map +1 -0
- package/dist/brain/subconscious.d.ts +34 -0
- package/dist/brain/subconscious.d.ts.map +1 -0
- package/dist/brain/subconscious.js +275 -0
- package/dist/brain/subconscious.js.map +1 -0
- package/dist/brain/temporal-intelligence.d.ts +89 -0
- package/dist/brain/temporal-intelligence.d.ts.map +1 -0
- package/dist/brain/temporal-intelligence.js +378 -0
- package/dist/brain/temporal-intelligence.js.map +1 -0
- package/dist/cli.js +434 -4
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +8 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -1
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +333 -1
- package/dist/types.d.ts.map +1 -1
- package/package.json +46 -10
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
// src/brain/intent-engine.ts — Developer intent prediction from code changes
|
|
2
|
+
// v6.0.0 — Behavioral analysis engine
|
|
3
|
+
import * as path from 'path';
|
|
4
|
+
// ── Intent Signals Map ─────────────────────────────────────────────────────
|
|
5
|
+
const INTENT_SIGNALS = {
|
|
6
|
+
'adding-feature': [
|
|
7
|
+
{ pattern: /^(?:feat|feature|add|new|implement|create)/i, weight: 0.9, source: 'commit-msg' },
|
|
8
|
+
{ pattern: '.ts', weight: 0.3, source: 'new-file' },
|
|
9
|
+
{ pattern: /export\s+(?:class|function|const)\s+\w+/g, weight: 0.4, source: 'code-pattern' },
|
|
10
|
+
{ pattern: /import.*from/g, weight: 0.2, source: 'new-import' },
|
|
11
|
+
],
|
|
12
|
+
'fixing-bug': [
|
|
13
|
+
{ pattern: /^(?:fix|bug|patch|hotfix|resolve|close)/i, weight: 0.9, source: 'commit-msg' },
|
|
14
|
+
{ pattern: /if\s*\(\s*!\s*\w+/g, weight: 0.3, source: 'null-check-added' },
|
|
15
|
+
{ pattern: /try\s*\{/g, weight: 0.3, source: 'error-handling-added' },
|
|
16
|
+
{ pattern: /catch\s*\(/g, weight: 0.3, source: 'catch-added' },
|
|
17
|
+
{ pattern: /\.test\.|\.spec\./i, weight: 0.2, source: 'test-file-modified' },
|
|
18
|
+
],
|
|
19
|
+
'refactoring': [
|
|
20
|
+
{ pattern: /^(?:refactor|restructure|reorganize|simplify|extract|rename|move)/i, weight: 0.9, source: 'commit-msg' },
|
|
21
|
+
{ pattern: /import.*from\s+['"]\.\//g, weight: 0.3, source: 'import-change' },
|
|
22
|
+
{ pattern: 'delete', weight: 0.4, source: 'file-deleted' },
|
|
23
|
+
{ pattern: 'rename', weight: 0.5, source: 'file-renamed' },
|
|
24
|
+
],
|
|
25
|
+
'adding-tests': [
|
|
26
|
+
{ pattern: /^(?:test|spec|coverage|e2e)/i, weight: 0.9, source: 'commit-msg' },
|
|
27
|
+
{ pattern: /\.test\.|\.spec\.|__tests__/i, weight: 0.8, source: 'test-file' },
|
|
28
|
+
{ pattern: /describe\s*\(|it\s*\(|expect\s*\(/g, weight: 0.7, source: 'test-code' },
|
|
29
|
+
{ pattern: /jest|vitest|mocha|cypress|playwright/i, weight: 0.4, source: 'test-framework' },
|
|
30
|
+
],
|
|
31
|
+
'updating-deps': [
|
|
32
|
+
{ pattern: /^(?:deps|dependencies|upgrade|update|bump)/i, weight: 0.9, source: 'commit-msg' },
|
|
33
|
+
{ pattern: 'package.json', weight: 0.7, source: 'package-json' },
|
|
34
|
+
{ pattern: 'package-lock.json', weight: 0.6, source: 'lockfile' },
|
|
35
|
+
{ pattern: 'requirements.txt', weight: 0.7, source: 'requirements' },
|
|
36
|
+
{ pattern: 'go.mod', weight: 0.7, source: 'gomod' },
|
|
37
|
+
],
|
|
38
|
+
'improving-perf': [
|
|
39
|
+
{ pattern: /^(?:perf|performance|optimize|speed|cache|lazy|memo)/i, weight: 0.9, source: 'commit-msg' },
|
|
40
|
+
{ pattern: /useMemo|useCallback|React\.memo/g, weight: 0.5, source: 'react-memo' },
|
|
41
|
+
{ pattern: /cache|memoize|lazy|debounce|throttle/gi, weight: 0.4, source: 'perf-keyword' },
|
|
42
|
+
{ pattern: /index|INDEX|CREATE INDEX/gi, weight: 0.5, source: 'db-index' },
|
|
43
|
+
],
|
|
44
|
+
'adding-docs': [
|
|
45
|
+
{ pattern: /^(?:docs|documentation|readme|jsdoc|comment)/i, weight: 0.9, source: 'commit-msg' },
|
|
46
|
+
{ pattern: /\.md$/i, weight: 0.7, source: 'markdown-file' },
|
|
47
|
+
{ pattern: /\/\*\*[\s\S]*?\*\//g, weight: 0.4, source: 'jsdoc' },
|
|
48
|
+
{ pattern: 'README', weight: 0.8, source: 'readme' },
|
|
49
|
+
],
|
|
50
|
+
'cleanup': [
|
|
51
|
+
{ pattern: /^(?:cleanup|clean|remove|delete|prune|lint)/i, weight: 0.9, source: 'commit-msg' },
|
|
52
|
+
{ pattern: /console\.\w+/g, weight: 0.3, source: 'console-removed' },
|
|
53
|
+
{ pattern: /TODO|FIXME|HACK/g, weight: 0.3, source: 'todo-addressed' },
|
|
54
|
+
],
|
|
55
|
+
'security-fix': [
|
|
56
|
+
{ pattern: /^(?:security|vuln|cve|auth|xss|csrf|injection|sanitize)/i, weight: 0.9, source: 'commit-msg' },
|
|
57
|
+
{ pattern: /sanitize|escape|validate|csrf|helmet|cors/gi, weight: 0.5, source: 'security-code' },
|
|
58
|
+
{ pattern: /bcrypt|argon2|jwt|oauth/gi, weight: 0.4, source: 'auth-code' },
|
|
59
|
+
],
|
|
60
|
+
'api-change': [
|
|
61
|
+
{ pattern: /^(?:api|endpoint|route|controller|handler)/i, weight: 0.9, source: 'commit-msg' },
|
|
62
|
+
{ pattern: /router\.\w+|app\.\w+\s*\(/g, weight: 0.5, source: 'route-code' },
|
|
63
|
+
{ pattern: /openapi|swagger|graphql|rest/gi, weight: 0.4, source: 'api-spec' },
|
|
64
|
+
],
|
|
65
|
+
'ui-change': [
|
|
66
|
+
{ pattern: /^(?:ui|ux|style|css|layout|component|page|view)/i, weight: 0.9, source: 'commit-msg' },
|
|
67
|
+
{ pattern: /\.css$|\.scss$|\.less$|\.styled\./i, weight: 0.7, source: 'style-file' },
|
|
68
|
+
{ pattern: /\.tsx$|\.jsx$|\.vue$|\.svelte$/i, weight: 0.5, source: 'component-file' },
|
|
69
|
+
{ pattern: /className|style=|styled\./g, weight: 0.3, source: 'style-code' },
|
|
70
|
+
],
|
|
71
|
+
'config-change': [
|
|
72
|
+
{ pattern: /^(?:config|env|settings|setup)/i, weight: 0.9, source: 'commit-msg' },
|
|
73
|
+
{ pattern: /\.config\.|\.env|tsconfig|webpack|vite\.config/i, weight: 0.7, source: 'config-file' },
|
|
74
|
+
{ pattern: /docker|kubernetes|terraform|ansible/i, weight: 0.5, source: 'infra-config' },
|
|
75
|
+
],
|
|
76
|
+
'ci-cd': [
|
|
77
|
+
{ pattern: /^(?:ci|cd|pipeline|deploy|build|workflow|action)/i, weight: 0.9, source: 'commit-msg' },
|
|
78
|
+
{ pattern: /\.github\/workflows|\.gitlab-ci|Jenkinsfile|\.circleci/i, weight: 0.8, source: 'ci-file' },
|
|
79
|
+
{ pattern: 'Dockerfile', weight: 0.5, source: 'docker' },
|
|
80
|
+
],
|
|
81
|
+
'database-migration': [
|
|
82
|
+
{ pattern: /^(?:migration|schema|db|database|migrate|seed)/i, weight: 0.9, source: 'commit-msg' },
|
|
83
|
+
{ pattern: /migration|\.sql$/i, weight: 0.7, source: 'migration-file' },
|
|
84
|
+
{ pattern: /CREATE TABLE|ALTER TABLE|DROP TABLE|ADD COLUMN/gi, weight: 0.8, source: 'sql' },
|
|
85
|
+
{ pattern: /prisma|sequelize|typeorm|knex|drizzle/gi, weight: 0.5, source: 'orm' },
|
|
86
|
+
],
|
|
87
|
+
'unknown': [],
|
|
88
|
+
};
|
|
89
|
+
// ── Intent Engine ──────────────────────────────────────────────────────────
|
|
90
|
+
export class IntentEngine {
|
|
91
|
+
constructor() {
|
|
92
|
+
this.predictions = [];
|
|
93
|
+
this.signals = [];
|
|
94
|
+
this.sessions = [];
|
|
95
|
+
this.currentSession = null;
|
|
96
|
+
this.intentHistory = new Map();
|
|
97
|
+
this.fileIntentMap = new Map(); // file -> past intents
|
|
98
|
+
this.accuracy = 0;
|
|
99
|
+
this.correctPredictions = 0;
|
|
100
|
+
this.totalPredictions = 0;
|
|
101
|
+
this.startNewSession();
|
|
102
|
+
}
|
|
103
|
+
// ── Prediction ──────────────────────────────────────────────────────
|
|
104
|
+
predictIntent(changes, commitMsg) {
|
|
105
|
+
const scores = new Map();
|
|
106
|
+
// Initialize all intents
|
|
107
|
+
for (const action of Object.keys(INTENT_SIGNALS)) {
|
|
108
|
+
scores.set(action, { score: 0, evidence: [] });
|
|
109
|
+
}
|
|
110
|
+
// Score from commit message
|
|
111
|
+
if (commitMsg) {
|
|
112
|
+
for (const [action, signalDefs] of Object.entries(INTENT_SIGNALS)) {
|
|
113
|
+
for (const signal of signalDefs) {
|
|
114
|
+
if (signal.source === 'commit-msg' && signal.pattern instanceof RegExp) {
|
|
115
|
+
if (signal.pattern.test(commitMsg)) {
|
|
116
|
+
const entry = scores.get(action);
|
|
117
|
+
entry.score += signal.weight;
|
|
118
|
+
entry.evidence.push(`Commit message matches ${action} pattern`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
// Score from file changes
|
|
125
|
+
for (const change of changes) {
|
|
126
|
+
const fileName = path.basename(change.file);
|
|
127
|
+
const ext = path.extname(change.file);
|
|
128
|
+
const relPath = change.file;
|
|
129
|
+
for (const [action, signalDefs] of Object.entries(INTENT_SIGNALS)) {
|
|
130
|
+
for (const signal of signalDefs) {
|
|
131
|
+
if (signal.source === 'commit-msg')
|
|
132
|
+
continue;
|
|
133
|
+
let matched = false;
|
|
134
|
+
if (signal.pattern instanceof RegExp) {
|
|
135
|
+
const testContent = change.content || change.diff || '';
|
|
136
|
+
matched = signal.pattern.test(testContent);
|
|
137
|
+
// Reset regex lastIndex
|
|
138
|
+
if (signal.pattern.global)
|
|
139
|
+
signal.pattern.lastIndex = 0;
|
|
140
|
+
}
|
|
141
|
+
else if (typeof signal.pattern === 'string') {
|
|
142
|
+
matched = fileName.includes(signal.pattern) || relPath.includes(signal.pattern) || ext === signal.pattern;
|
|
143
|
+
}
|
|
144
|
+
if (matched) {
|
|
145
|
+
const entry = scores.get(action);
|
|
146
|
+
entry.score += signal.weight;
|
|
147
|
+
entry.evidence.push(`${signal.source}: ${fileName}`);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
// File-type heuristics
|
|
152
|
+
if (change.type === 'add') {
|
|
153
|
+
scores.get('adding-feature').score += 0.3;
|
|
154
|
+
scores.get('adding-feature').evidence.push(`New file: ${fileName}`);
|
|
155
|
+
}
|
|
156
|
+
if (change.type === 'delete') {
|
|
157
|
+
scores.get('refactoring').score += 0.3;
|
|
158
|
+
scores.get('cleanup').score += 0.2;
|
|
159
|
+
scores.get('refactoring').evidence.push(`Deleted: ${fileName}`);
|
|
160
|
+
}
|
|
161
|
+
// Historical file intent correlation
|
|
162
|
+
const pastIntents = this.fileIntentMap.get(relPath);
|
|
163
|
+
if (pastIntents && pastIntents.length > 0) {
|
|
164
|
+
const lastIntent = pastIntents[pastIntents.length - 1];
|
|
165
|
+
const entry = scores.get(lastIntent);
|
|
166
|
+
if (entry) {
|
|
167
|
+
entry.score += 0.15;
|
|
168
|
+
entry.evidence.push(`Historical pattern: ${relPath} → ${lastIntent}`);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
// Find top intent
|
|
173
|
+
let topAction = 'unknown';
|
|
174
|
+
let topScore = 0;
|
|
175
|
+
let topEvidence = [];
|
|
176
|
+
for (const [action, data] of scores) {
|
|
177
|
+
if (data.score > topScore) {
|
|
178
|
+
topScore = data.score;
|
|
179
|
+
topAction = action;
|
|
180
|
+
topEvidence = data.evidence;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
// Normalize confidence
|
|
184
|
+
const totalScores = Array.from(scores.values()).reduce((s, d) => s + d.score, 0);
|
|
185
|
+
const confidence = totalScores > 0 ? Math.min(1, topScore / totalScores) : 0;
|
|
186
|
+
// Generate suggestions based on intent
|
|
187
|
+
const suggestions = this.generateSuggestions(topAction, changes);
|
|
188
|
+
const relatedFiles = this.findRelatedFiles(topAction, changes);
|
|
189
|
+
const intent = {
|
|
190
|
+
action: topAction,
|
|
191
|
+
confidence,
|
|
192
|
+
evidence: topEvidence.slice(0, 10),
|
|
193
|
+
prediction: this.describePrediction(topAction, changes),
|
|
194
|
+
suggestions,
|
|
195
|
+
relatedFiles,
|
|
196
|
+
estimatedScope: this.estimateScope(changes),
|
|
197
|
+
};
|
|
198
|
+
// Track
|
|
199
|
+
this.predictions.push(intent);
|
|
200
|
+
if (this.predictions.length > 1000)
|
|
201
|
+
this.predictions = this.predictions.slice(-500);
|
|
202
|
+
this.totalPredictions++;
|
|
203
|
+
this.intentHistory.set(topAction, (this.intentHistory.get(topAction) || 0) + 1);
|
|
204
|
+
// Update file-intent map
|
|
205
|
+
for (const change of changes) {
|
|
206
|
+
if (!this.fileIntentMap.has(change.file)) {
|
|
207
|
+
this.fileIntentMap.set(change.file, []);
|
|
208
|
+
}
|
|
209
|
+
const history = this.fileIntentMap.get(change.file);
|
|
210
|
+
history.push(topAction);
|
|
211
|
+
if (history.length > 10)
|
|
212
|
+
this.fileIntentMap.set(change.file, history.slice(-10));
|
|
213
|
+
}
|
|
214
|
+
// Update session
|
|
215
|
+
if (this.currentSession) {
|
|
216
|
+
this.currentSession.lastActivity = Date.now();
|
|
217
|
+
this.currentSession.filesModified.push(...changes.map(c => c.file));
|
|
218
|
+
this.currentSession.intents.push(intent);
|
|
219
|
+
this.currentSession.focusArea = topAction;
|
|
220
|
+
const sessionDuration = (Date.now() - this.currentSession.startedAt) / 60000;
|
|
221
|
+
this.currentSession.velocity = sessionDuration > 0 ? this.currentSession.filesModified.length / sessionDuration : 0;
|
|
222
|
+
}
|
|
223
|
+
return intent;
|
|
224
|
+
}
|
|
225
|
+
confirmPrediction(correct) {
|
|
226
|
+
if (correct)
|
|
227
|
+
this.correctPredictions++;
|
|
228
|
+
this.accuracy = this.totalPredictions > 0 ? this.correctPredictions / this.totalPredictions : 0;
|
|
229
|
+
}
|
|
230
|
+
// ── Suggestions ─────────────────────────────────────────────────────
|
|
231
|
+
generateSuggestions(action, changes) {
|
|
232
|
+
const suggestions = [];
|
|
233
|
+
const files = changes.map(c => c.file);
|
|
234
|
+
switch (action) {
|
|
235
|
+
case 'adding-feature':
|
|
236
|
+
suggestions.push('Consider writing tests for the new feature');
|
|
237
|
+
suggestions.push('Update README/docs if the feature is user-facing');
|
|
238
|
+
if (!files.some(f => /index\.|barrel|export/i.test(f))) {
|
|
239
|
+
suggestions.push('Don\'t forget to export from the barrel file / index');
|
|
240
|
+
}
|
|
241
|
+
break;
|
|
242
|
+
case 'fixing-bug':
|
|
243
|
+
suggestions.push('Add a regression test to prevent recurrence');
|
|
244
|
+
suggestions.push('Check for similar patterns elsewhere in the codebase');
|
|
245
|
+
suggestions.push('Update CHANGELOG with the fix');
|
|
246
|
+
break;
|
|
247
|
+
case 'refactoring':
|
|
248
|
+
suggestions.push('Run the full test suite after refactoring');
|
|
249
|
+
suggestions.push('Check for broken imports or references');
|
|
250
|
+
suggestions.push('Consider creating an ADR for the refactoring decision');
|
|
251
|
+
break;
|
|
252
|
+
case 'adding-tests':
|
|
253
|
+
suggestions.push('Ensure edge cases and error paths are covered');
|
|
254
|
+
suggestions.push('Check test naming follows team conventions');
|
|
255
|
+
break;
|
|
256
|
+
case 'updating-deps':
|
|
257
|
+
suggestions.push('Run security audit on updated packages');
|
|
258
|
+
suggestions.push('Check for breaking changes in changelogs');
|
|
259
|
+
suggestions.push('Run full test suite to catch compatibility issues');
|
|
260
|
+
break;
|
|
261
|
+
case 'improving-perf':
|
|
262
|
+
suggestions.push('Benchmark before and after to measure improvement');
|
|
263
|
+
suggestions.push('Consider caching strategies for hot paths');
|
|
264
|
+
break;
|
|
265
|
+
case 'security-fix':
|
|
266
|
+
suggestions.push('Run security scanner to verify the fix');
|
|
267
|
+
suggestions.push('Check for similar vulnerabilities elsewhere');
|
|
268
|
+
suggestions.push('Consider adding security test cases');
|
|
269
|
+
break;
|
|
270
|
+
case 'api-change':
|
|
271
|
+
suggestions.push('Update API documentation / OpenAPI spec');
|
|
272
|
+
suggestions.push('Check for backward compatibility');
|
|
273
|
+
suggestions.push('Notify API consumers of the change');
|
|
274
|
+
break;
|
|
275
|
+
case 'database-migration':
|
|
276
|
+
suggestions.push('Ensure migration is reversible (add down migration)');
|
|
277
|
+
suggestions.push('Test migration with production-like data volume');
|
|
278
|
+
suggestions.push('Check for potential data loss');
|
|
279
|
+
break;
|
|
280
|
+
default:
|
|
281
|
+
suggestions.push('Consider running lint and tests before committing');
|
|
282
|
+
}
|
|
283
|
+
return suggestions;
|
|
284
|
+
}
|
|
285
|
+
findRelatedFiles(action, changes) {
|
|
286
|
+
const related = new Set();
|
|
287
|
+
for (const change of changes) {
|
|
288
|
+
const dir = path.dirname(change.file);
|
|
289
|
+
const name = path.basename(change.file, path.extname(change.file));
|
|
290
|
+
// Suggest test file if modifying source
|
|
291
|
+
if (action !== 'adding-tests' && !change.file.includes('.test.') && !change.file.includes('.spec.')) {
|
|
292
|
+
related.add(path.join(dir, `${name}.test${path.extname(change.file)}`));
|
|
293
|
+
related.add(path.join(dir, '__tests__', `${name}.test${path.extname(change.file)}`));
|
|
294
|
+
}
|
|
295
|
+
// Suggest barrel file
|
|
296
|
+
related.add(path.join(dir, 'index.ts'));
|
|
297
|
+
related.add(path.join(dir, 'index.js'));
|
|
298
|
+
}
|
|
299
|
+
return Array.from(related).slice(0, 10);
|
|
300
|
+
}
|
|
301
|
+
describePrediction(action, changes) {
|
|
302
|
+
const fileCount = changes.length;
|
|
303
|
+
const descriptions = {
|
|
304
|
+
'adding-feature': `Adding a new feature (${fileCount} file${fileCount !== 1 ? 's' : ''} modified)`,
|
|
305
|
+
'fixing-bug': `Fixing a bug (${fileCount} file${fileCount !== 1 ? 's' : ''} patched)`,
|
|
306
|
+
'refactoring': `Refactoring code (${fileCount} file${fileCount !== 1 ? 's' : ''} restructured)`,
|
|
307
|
+
'adding-tests': `Adding tests (${fileCount} test file${fileCount !== 1 ? 's' : ''})`,
|
|
308
|
+
'updating-deps': `Updating dependencies`,
|
|
309
|
+
'improving-perf': `Improving performance (${fileCount} file${fileCount !== 1 ? 's' : ''} optimized)`,
|
|
310
|
+
'adding-docs': `Updating documentation`,
|
|
311
|
+
'cleanup': `Code cleanup (${fileCount} file${fileCount !== 1 ? 's' : ''} cleaned)`,
|
|
312
|
+
'security-fix': `Security fix (${fileCount} file${fileCount !== 1 ? 's' : ''} hardened)`,
|
|
313
|
+
'api-change': `API changes (${fileCount} endpoint${fileCount !== 1 ? 's' : ''} modified)`,
|
|
314
|
+
'ui-change': `UI/UX changes (${fileCount} component${fileCount !== 1 ? 's' : ''} modified)`,
|
|
315
|
+
'config-change': `Configuration changes`,
|
|
316
|
+
'ci-cd': `CI/CD pipeline changes`,
|
|
317
|
+
'database-migration': `Database schema migration`,
|
|
318
|
+
'unknown': `Code changes (${fileCount} file${fileCount !== 1 ? 's' : ''})`,
|
|
319
|
+
};
|
|
320
|
+
return descriptions[action] || descriptions.unknown;
|
|
321
|
+
}
|
|
322
|
+
estimateScope(changes) {
|
|
323
|
+
const fileCount = changes.length;
|
|
324
|
+
const dirs = new Set(changes.map(c => path.dirname(c.file)));
|
|
325
|
+
const hasDeletes = changes.some(c => c.type === 'delete');
|
|
326
|
+
if (fileCount <= 2)
|
|
327
|
+
return 'small';
|
|
328
|
+
if (fileCount <= 5 && dirs.size <= 2)
|
|
329
|
+
return 'medium';
|
|
330
|
+
if (hasDeletes && fileCount > 5)
|
|
331
|
+
return 'refactor';
|
|
332
|
+
return 'large';
|
|
333
|
+
}
|
|
334
|
+
// ── Session Management ──────────────────────────────────────────────
|
|
335
|
+
startNewSession() {
|
|
336
|
+
this.currentSession = {
|
|
337
|
+
id: `session-${Date.now()}`,
|
|
338
|
+
startedAt: Date.now(),
|
|
339
|
+
lastActivity: Date.now(),
|
|
340
|
+
filesModified: [],
|
|
341
|
+
intents: [],
|
|
342
|
+
focusArea: 'unknown',
|
|
343
|
+
velocity: 0,
|
|
344
|
+
};
|
|
345
|
+
this.sessions.push(this.currentSession);
|
|
346
|
+
if (this.sessions.length > 50)
|
|
347
|
+
this.sessions = this.sessions.slice(-25);
|
|
348
|
+
}
|
|
349
|
+
getCurrentSession() {
|
|
350
|
+
return this.currentSession;
|
|
351
|
+
}
|
|
352
|
+
getRecentIntents(n = 10) {
|
|
353
|
+
return this.predictions.slice(-n);
|
|
354
|
+
}
|
|
355
|
+
// ── Stats ────────────────────────────────────────────────────────────
|
|
356
|
+
stats() {
|
|
357
|
+
const topIntents = Array.from(this.intentHistory.entries())
|
|
358
|
+
.map(([action, count]) => ({ action, count }))
|
|
359
|
+
.sort((a, b) => b.count - a.count)
|
|
360
|
+
.slice(0, 10);
|
|
361
|
+
const avgConfidence = this.predictions.length > 0
|
|
362
|
+
? this.predictions.reduce((s, p) => s + p.confidence, 0) / this.predictions.length
|
|
363
|
+
: 0;
|
|
364
|
+
return {
|
|
365
|
+
totalPredictions: this.totalPredictions,
|
|
366
|
+
accuracy: this.accuracy,
|
|
367
|
+
topIntents,
|
|
368
|
+
currentSession: this.currentSession,
|
|
369
|
+
avgConfidence,
|
|
370
|
+
patternCount: this.fileIntentMap.size,
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
//# sourceMappingURL=intent-engine.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"intent-engine.js","sourceRoot":"","sources":["../../src/brain/intent-engine.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,sCAAsC;AAEtC,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAyD7B,8EAA8E;AAE9E,MAAM,cAAc,GAA8F;IAChH,gBAAgB,EAAE;QAChB,EAAE,OAAO,EAAE,6CAA6C,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,YAAY,EAAE;QAC7F,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE;QACnD,EAAE,OAAO,EAAE,0CAA0C,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,cAAc,EAAE;QAC5F,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,YAAY,EAAE;KAChE;IACD,YAAY,EAAE;QACZ,EAAE,OAAO,EAAE,0CAA0C,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,YAAY,EAAE;QAC1F,EAAE,OAAO,EAAE,oBAAoB,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,kBAAkB,EAAE;QAC1E,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,sBAAsB,EAAE;QACrE,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,aAAa,EAAE;QAC9D,EAAE,OAAO,EAAE,oBAAoB,EAAE,MAAM,EAAE,GAAG,EA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AAK;QACH,MAAM,UAAU,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,CAAC;aACxD,GAAG,CAAC,CAAC,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;aAC7C,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC;aACjC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QAEhB,MAAM,aAAa,GAAG,IAAI,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC;YAC/C,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,CAAC,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC,MAAM;YAClF,CAAC,CAAC,CAAC,CAAC;QAEN,OAAO;YACL,gBAAgB,EAAE,IAAI,CAAC,gBAAgB;YACvC,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,UAAU;YACV,cAAc,EAAE,IAAI,CAAC,cAAc;YACnC,aAAa;YACb,YAAY,EAAE,IAAI,CAAC,aAAa,CAAC,IAAI;SACtC,CAAC;IACJ,CAAC;CACF"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { L0CacheEntry, L0CacheStats } from '../types.js';
|
|
2
|
+
export interface L0CacheOptions {
|
|
3
|
+
bytesLimit?: number;
|
|
4
|
+
/** Estimate bytes for a value when computing budget */
|
|
5
|
+
byteEstimator?: (value: unknown) => number;
|
|
6
|
+
}
|
|
7
|
+
/** Generic L0 cache. Construct one per logical namespace (recall, vectors, etc.) */
|
|
8
|
+
export declare class L0Cache<T = unknown> {
|
|
9
|
+
private map;
|
|
10
|
+
private bytesUsed;
|
|
11
|
+
private bytesLimit;
|
|
12
|
+
private byteEstimator;
|
|
13
|
+
private hits;
|
|
14
|
+
private misses;
|
|
15
|
+
private evictions;
|
|
16
|
+
private accessTimingsNs;
|
|
17
|
+
constructor(opts?: L0CacheOptions);
|
|
18
|
+
/** Get a value from the cache — sub-microsecond on hit */
|
|
19
|
+
get(key: string): T | undefined;
|
|
20
|
+
/** Set a value — evicts LRU entries if over budget */
|
|
21
|
+
set(key: string, value: T): void;
|
|
22
|
+
/** Check existence without touching LRU */
|
|
23
|
+
has(key: string): boolean;
|
|
24
|
+
/** Remove a single entry */
|
|
25
|
+
delete(key: string): boolean;
|
|
26
|
+
/** Clear all entries */
|
|
27
|
+
clear(): void;
|
|
28
|
+
/** Get cache stats */
|
|
29
|
+
getStats(): L0CacheStats;
|
|
30
|
+
/** Iterate entries (for warm-restart persistence) */
|
|
31
|
+
entries(): IterableIterator<[string, L0CacheEntry<T>]>;
|
|
32
|
+
/** Resize the byte budget — evicts if shrinking */
|
|
33
|
+
resize(newBytesLimit: number): void;
|
|
34
|
+
private evictOldest;
|
|
35
|
+
private recordTiming;
|
|
36
|
+
}
|
|
37
|
+
export declare function getCache<T = unknown>(namespace: string, opts?: L0CacheOptions): L0Cache<T>;
|
|
38
|
+
export declare function getAllCacheStats(): Record<string, L0CacheStats>;
|
|
39
|
+
export declare function clearAllCaches(): void;
|
|
40
|
+
//# sourceMappingURL=l0-cache.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"l0-cache.d.ts","sourceRoot":"","sources":["../../src/brain/l0-cache.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAIzD,MAAM,WAAW,cAAc;IAC7B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,uDAAuD;IACvD,aAAa,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,MAAM,CAAC;CAC5C;AAgBD,oFAAoF;AACpF,qBAAa,OAAO,CAA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2
|
+
//
|
|
3
|
+
// Sub-millisecond recall for the hottest brain entries. Sits in front of the
|
|
4
|
+
// global SQLite brain. Map-based, LRU-evicted, byte-budget-bounded.
|
|
5
|
+
//
|
|
6
|
+
// Design:
|
|
7
|
+
// - Pure JavaScript Map (insertion-ordered → easy LRU)
|
|
8
|
+
// - Byte budget (default 64MB) prevents memory bloat
|
|
9
|
+
// - Tracks hit/miss for adaptive prefetch decisions
|
|
10
|
+
// - Auto-evict least-recently-accessed when budget exceeded
|
|
11
|
+
const DEFAULT_BYTES_LIMIT = 64 * 1024 * 1024; // 64MB
|
|
12
|
+
/** Default byte estimator — works for strings, objects, arrays */
|
|
13
|
+
function defaultByteEstimator(value) {
|
|
14
|
+
if (value == null)
|
|
15
|
+
return 8;
|
|
16
|
+
if (typeof value === 'string')
|
|
17
|
+
return value.length * 2;
|
|
18
|
+
if (typeof value === 'number')
|
|
19
|
+
return 8;
|
|
20
|
+
if (typeof value === 'boolean')
|
|
21
|
+
return 4;
|
|
22
|
+
if (value instanceof Uint8Array)
|
|
23
|
+
return value.byteLength;
|
|
24
|
+
try {
|
|
25
|
+
return JSON.stringify(value).length * 2;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return 64;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** Generic L0 cache. Construct one per logical namespace (recall, vectors, etc.) */
|
|
32
|
+
export class L0Cache {
|
|
33
|
+
constructor(opts = {}) {
|
|
34
|
+
this.map = new Map();
|
|
35
|
+
this.bytesUsed = 0;
|
|
36
|
+
this.hits = 0;
|
|
37
|
+
this.misses = 0;
|
|
38
|
+
this.evictions = 0;
|
|
39
|
+
this.accessTimingsNs = [];
|
|
40
|
+
this.bytesLimit = opts.bytesLimit ?? DEFAULT_BYTES_LIMIT;
|
|
41
|
+
this.byteEstimator = opts.byteEstimator ?? defaultByteEstimator;
|
|
42
|
+
}
|
|
43
|
+
/** Get a value from the cache — sub-microsecond on hit */
|
|
44
|
+
get(key) {
|
|
45
|
+
const start = process.hrtime.bigint();
|
|
46
|
+
const entry = this.map.get(key);
|
|
47
|
+
if (!entry) {
|
|
48
|
+
this.misses++;
|
|
49
|
+
this.recordTiming(start);
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
// LRU touch — re-insert at end of map
|
|
53
|
+
this.map.delete(key);
|
|
54
|
+
entry.hits++;
|
|
55
|
+
entry.lastAccessed = Date.now();
|
|
56
|
+
this.map.set(key, entry);
|
|
57
|
+
this.hits++;
|
|
58
|
+
this.recordTiming(start);
|
|
59
|
+
return entry.value;
|
|
60
|
+
}
|
|
61
|
+
/** Set a value — evicts LRU entries if over budget */
|
|
62
|
+
set(key, value) {
|
|
63
|
+
const bytes = this.byteEstimator(value);
|
|
64
|
+
// If key already exists, subtract its bytes first
|
|
65
|
+
const existing = this.map.get(key);
|
|
66
|
+
if (existing) {
|
|
67
|
+
this.bytesUsed -= existing.bytes;
|
|
68
|
+
this.map.delete(key);
|
|
69
|
+
}
|
|
70
|
+
// Make room
|
|
71
|
+
while (this.bytesUsed + bytes > this.bytesLimit && this.map.size > 0) {
|
|
72
|
+
this.evictOldest();
|
|
73
|
+
}
|
|
74
|
+
const entry = {
|
|
75
|
+
key,
|
|
76
|
+
value,
|
|
77
|
+
hits: 0,
|
|
78
|
+
insertedAt: Date.now(),
|
|
79
|
+
lastAccessed: Date.now(),
|
|
80
|
+
bytes,
|
|
81
|
+
};
|
|
82
|
+
this.map.set(key, entry);
|
|
83
|
+
this.bytesUsed += bytes;
|
|
84
|
+
}
|
|
85
|
+
/** Check existence without touching LRU */
|
|
86
|
+
has(key) {
|
|
87
|
+
return this.map.has(key);
|
|
88
|
+
}
|
|
89
|
+
/** Remove a single entry */
|
|
90
|
+
delete(key) {
|
|
91
|
+
const entry = this.map.get(key);
|
|
92
|
+
if (!entry)
|
|
93
|
+
return false;
|
|
94
|
+
this.bytesUsed -= entry.bytes;
|
|
95
|
+
return this.map.delete(key);
|
|
96
|
+
}
|
|
97
|
+
/** Clear all entries */
|
|
98
|
+
clear() {
|
|
99
|
+
this.map.clear();
|
|
100
|
+
this.bytesUsed = 0;
|
|
101
|
+
}
|
|
102
|
+
/** Get cache stats */
|
|
103
|
+
getStats() {
|
|
104
|
+
const total = this.hits + this.misses;
|
|
105
|
+
const avgAccessNs = this.accessTimingsNs.length
|
|
106
|
+
? this.accessTimingsNs.reduce((a, b) => a + b, 0) / this.accessTimingsNs.length
|
|
107
|
+
: 0;
|
|
108
|
+
// Top 10 most-hit keys
|
|
109
|
+
const topKeys = Array.from(this.map.values())
|
|
110
|
+
.sort((a, b) => b.hits - a.hits)
|
|
111
|
+
.slice(0, 10)
|
|
112
|
+
.map(e => ({ key: e.key, hits: e.hits }));
|
|
113
|
+
return {
|
|
114
|
+
entries: this.map.size,
|
|
115
|
+
bytesUsed: this.bytesUsed,
|
|
116
|
+
bytesLimit: this.bytesLimit,
|
|
117
|
+
hits: this.hits,
|
|
118
|
+
misses: this.misses,
|
|
119
|
+
hitRate: total ? this.hits / total : 0,
|
|
120
|
+
evictions: this.evictions,
|
|
121
|
+
avgAccessNs,
|
|
122
|
+
topKeys,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
/** Iterate entries (for warm-restart persistence) */
|
|
126
|
+
entries() {
|
|
127
|
+
return this.map.entries();
|
|
128
|
+
}
|
|
129
|
+
/** Resize the byte budget — evicts if shrinking */
|
|
130
|
+
resize(newBytesLimit) {
|
|
131
|
+
this.bytesLimit = newBytesLimit;
|
|
132
|
+
while (this.bytesUsed > this.bytesLimit && this.map.size > 0) {
|
|
133
|
+
this.evictOldest();
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
evictOldest() {
|
|
137
|
+
// First entry in Map = oldest by insertion (and we re-insert on touch → LRU)
|
|
138
|
+
const oldest = this.map.keys().next().value;
|
|
139
|
+
if (oldest === undefined)
|
|
140
|
+
return;
|
|
141
|
+
const entry = this.map.get(oldest);
|
|
142
|
+
if (entry)
|
|
143
|
+
this.bytesUsed -= entry.bytes;
|
|
144
|
+
this.map.delete(oldest);
|
|
145
|
+
this.evictions++;
|
|
146
|
+
}
|
|
147
|
+
recordTiming(startNs) {
|
|
148
|
+
const elapsedNs = Number(process.hrtime.bigint() - startNs);
|
|
149
|
+
this.accessTimingsNs.push(elapsedNs);
|
|
150
|
+
if (this.accessTimingsNs.length > 1000) {
|
|
151
|
+
this.accessTimingsNs.shift();
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/** Process-wide singleton caches — one per logical namespace */
|
|
156
|
+
const caches = new Map();
|
|
157
|
+
export function getCache(namespace, opts) {
|
|
158
|
+
let cache = caches.get(namespace);
|
|
159
|
+
if (!cache) {
|
|
160
|
+
cache = new L0Cache(opts);
|
|
161
|
+
caches.set(namespace, cache);
|
|
162
|
+
}
|
|
163
|
+
return cache;
|
|
164
|
+
}
|
|
165
|
+
export function getAllCacheStats() {
|
|
166
|
+
const out = {};
|
|
167
|
+
for (const [name, cache] of caches.entries()) {
|
|
168
|
+
out[name] = cache.getStats();
|
|
169
|
+
}
|
|
170
|
+
return out;
|
|
171
|
+
}
|
|
172
|
+
export function clearAllCaches() {
|
|
173
|
+
for (const cache of caches.values())
|
|
174
|
+
cache.clear();
|
|
175
|
+
}
|
|
176
|
+
//# sourceMappingURL=l0-cache.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"l0-cache.js","sourceRoot":"","sources":["../../src/brain/l0-cache.ts"],"names":[],"mappings":"AAAA,yDAAyD;AACzD,EAAE;AACF,6EAA6E;AAC7E,oEAAoE;AACpE,EAAE;AACF,UAAU;AACV,yDAAyD;AACzD,uDAAuD;AACvD,sDAAsD;AACtD,8DAA8D;AAI9D,MAAM,mBAAmB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC,CAAC,OAAO;AAQrD,kEAAkE;AAClE,SAAS,oBAAoB,CAAC,KAAc;IAC1C,IAAI,KAAK,IAAI,IAAI;QAA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