@claude-flow/cli 3.1.0-alpha.22 → 3.1.0-alpha.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -45,6 +45,7 @@ function safeRequire(modulePath) {
|
|
|
45
45
|
const router = safeRequire(path.join(helpersDir, 'router.js'));
|
|
46
46
|
const session = safeRequire(path.join(helpersDir, 'session.js'));
|
|
47
47
|
const memory = safeRequire(path.join(helpersDir, 'memory.js'));
|
|
48
|
+
const intelligence = safeRequire(path.join(helpersDir, 'intelligence.cjs'));
|
|
48
49
|
|
|
49
50
|
// Get the command from argv
|
|
50
51
|
const [,, command, ...args] = process.argv;
|
|
@@ -54,6 +55,13 @@ const prompt = process.env.PROMPT || process.env.TOOL_INPUT_command || args.join
|
|
|
54
55
|
|
|
55
56
|
const handlers = {
|
|
56
57
|
'route': () => {
|
|
58
|
+
// Inject ranked intelligence context before routing
|
|
59
|
+
if (intelligence && intelligence.getContext) {
|
|
60
|
+
try {
|
|
61
|
+
const ctx = intelligence.getContext(prompt);
|
|
62
|
+
if (ctx) console.log(ctx);
|
|
63
|
+
} catch (e) { /* non-fatal */ }
|
|
64
|
+
}
|
|
57
65
|
if (router && router.routeTask) {
|
|
58
66
|
const result = router.routeTask(prompt);
|
|
59
67
|
// Format output for Claude Code hook consumption
|
|
@@ -114,6 +122,13 @@ const handlers = {
|
|
|
114
122
|
if (session && session.metric) {
|
|
115
123
|
session.metric('edits');
|
|
116
124
|
}
|
|
125
|
+
// Record edit for intelligence consolidation
|
|
126
|
+
if (intelligence && intelligence.recordEdit) {
|
|
127
|
+
try {
|
|
128
|
+
const file = process.env.TOOL_INPUT_file_path || args[0] || '';
|
|
129
|
+
intelligence.recordEdit(file);
|
|
130
|
+
} catch (e) { /* non-fatal */ }
|
|
131
|
+
}
|
|
117
132
|
console.log('[OK] Edit recorded');
|
|
118
133
|
},
|
|
119
134
|
|
|
@@ -141,9 +156,27 @@ const handlers = {
|
|
|
141
156
|
console.log('| Memory Entries | 0 |');
|
|
142
157
|
console.log('+----------------+-------+');
|
|
143
158
|
}
|
|
159
|
+
// Initialize intelligence graph after session restore
|
|
160
|
+
if (intelligence && intelligence.init) {
|
|
161
|
+
try {
|
|
162
|
+
const result = intelligence.init();
|
|
163
|
+
if (result && result.nodes > 0) {
|
|
164
|
+
console.log(`[INTELLIGENCE] Loaded ${result.nodes} patterns, ${result.edges} edges`);
|
|
165
|
+
}
|
|
166
|
+
} catch (e) { /* non-fatal */ }
|
|
167
|
+
}
|
|
144
168
|
},
|
|
145
169
|
|
|
146
170
|
'session-end': () => {
|
|
171
|
+
// Consolidate intelligence before ending session
|
|
172
|
+
if (intelligence && intelligence.consolidate) {
|
|
173
|
+
try {
|
|
174
|
+
const result = intelligence.consolidate();
|
|
175
|
+
if (result && result.entries > 0) {
|
|
176
|
+
console.log(`[INTELLIGENCE] Consolidated: ${result.entries} entries, ${result.edges} edges${result.newEntries > 0 ? `, ${result.newEntries} new` : ''}, PageRank recomputed`);
|
|
177
|
+
}
|
|
178
|
+
} catch (e) { /* non-fatal */ }
|
|
179
|
+
}
|
|
147
180
|
if (session && session.end) {
|
|
148
181
|
session.end();
|
|
149
182
|
} else {
|
|
@@ -165,6 +198,12 @@ const handlers = {
|
|
|
165
198
|
},
|
|
166
199
|
|
|
167
200
|
'post-task': () => {
|
|
201
|
+
// Implicit success feedback for intelligence
|
|
202
|
+
if (intelligence && intelligence.feedback) {
|
|
203
|
+
try {
|
|
204
|
+
intelligence.feedback(true);
|
|
205
|
+
} catch (e) { /* non-fatal */ }
|
|
206
|
+
}
|
|
168
207
|
console.log('[OK] Task completed');
|
|
169
208
|
},
|
|
170
209
|
};
|
|
@@ -0,0 +1,567 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Intelligence Layer (ADR-050)
|
|
4
|
+
*
|
|
5
|
+
* Closes the intelligence loop by wiring PageRank-ranked memory into
|
|
6
|
+
* the hook system. Pure CJS — no ESM imports of @claude-flow/memory.
|
|
7
|
+
*
|
|
8
|
+
* Data files (all under .claude-flow/data/):
|
|
9
|
+
* auto-memory-store.json — written by auto-memory-hook.mjs
|
|
10
|
+
* graph-state.json — serialized graph (nodes + edges + pageRanks)
|
|
11
|
+
* ranked-context.json — pre-computed ranked entries for fast lookup
|
|
12
|
+
* pending-insights.jsonl — append-only edit/task log
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
'use strict';
|
|
16
|
+
|
|
17
|
+
const fs = require('fs');
|
|
18
|
+
const path = require('path');
|
|
19
|
+
|
|
20
|
+
const DATA_DIR = path.join(process.cwd(), '.claude-flow', 'data');
|
|
21
|
+
const STORE_PATH = path.join(DATA_DIR, 'auto-memory-store.json');
|
|
22
|
+
const GRAPH_PATH = path.join(DATA_DIR, 'graph-state.json');
|
|
23
|
+
const RANKED_PATH = path.join(DATA_DIR, 'ranked-context.json');
|
|
24
|
+
const PENDING_PATH = path.join(DATA_DIR, 'pending-insights.jsonl');
|
|
25
|
+
const SESSION_DIR = path.join(process.cwd(), '.claude-flow', 'sessions');
|
|
26
|
+
const SESSION_FILE = path.join(SESSION_DIR, 'current.json');
|
|
27
|
+
|
|
28
|
+
// ── Stop words for trigram matching ──────────────────────────────────────────
|
|
29
|
+
|
|
30
|
+
const STOP_WORDS = new Set([
|
|
31
|
+
'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been', 'being',
|
|
32
|
+
'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could',
|
|
33
|
+
'should', 'may', 'might', 'shall', 'can', 'to', 'of', 'in', 'for',
|
|
34
|
+
'on', 'with', 'at', 'by', 'from', 'as', 'into', 'through', 'during',
|
|
35
|
+
'before', 'after', 'and', 'but', 'or', 'nor', 'not', 'so', 'yet',
|
|
36
|
+
'both', 'either', 'neither', 'each', 'every', 'all', 'any', 'few',
|
|
37
|
+
'more', 'most', 'other', 'some', 'such', 'no', 'only', 'own', 'same',
|
|
38
|
+
'than', 'too', 'very', 'just', 'because', 'if', 'when', 'which',
|
|
39
|
+
'who', 'whom', 'this', 'that', 'these', 'those', 'it', 'its',
|
|
40
|
+
]);
|
|
41
|
+
|
|
42
|
+
// ── Helpers ──────────────────────────────────────────────────────────────────
|
|
43
|
+
|
|
44
|
+
function ensureDataDir() {
|
|
45
|
+
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function readJSON(filePath) {
|
|
49
|
+
try {
|
|
50
|
+
if (fs.existsSync(filePath)) return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
|
51
|
+
} catch { /* corrupt file — start fresh */ }
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function writeJSON(filePath, data) {
|
|
56
|
+
ensureDataDir();
|
|
57
|
+
fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function tokenize(text) {
|
|
61
|
+
if (!text) return [];
|
|
62
|
+
return text.toLowerCase()
|
|
63
|
+
.replace(/[^a-z0-9\s-]/g, ' ')
|
|
64
|
+
.split(/\s+/)
|
|
65
|
+
.filter(w => w.length > 2 && !STOP_WORDS.has(w));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function trigrams(words) {
|
|
69
|
+
const t = new Set();
|
|
70
|
+
for (const w of words) {
|
|
71
|
+
for (let i = 0; i <= w.length - 3; i++) t.add(w.slice(i, i + 3));
|
|
72
|
+
}
|
|
73
|
+
return t;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function jaccardSimilarity(setA, setB) {
|
|
77
|
+
if (setA.size === 0 && setB.size === 0) return 0;
|
|
78
|
+
let intersection = 0;
|
|
79
|
+
for (const item of setA) { if (setB.has(item)) intersection++; }
|
|
80
|
+
return intersection / (setA.size + setB.size - intersection);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// ── Session state helpers ────────────────────────────────────────────────────
|
|
84
|
+
|
|
85
|
+
function sessionGet(key) {
|
|
86
|
+
try {
|
|
87
|
+
if (!fs.existsSync(SESSION_FILE)) return null;
|
|
88
|
+
const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));
|
|
89
|
+
return key ? (session.context || {})[key] : session.context;
|
|
90
|
+
} catch { return null; }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function sessionSet(key, value) {
|
|
94
|
+
try {
|
|
95
|
+
if (!fs.existsSync(SESSION_DIR)) fs.mkdirSync(SESSION_DIR, { recursive: true });
|
|
96
|
+
let session = {};
|
|
97
|
+
if (fs.existsSync(SESSION_FILE)) {
|
|
98
|
+
session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));
|
|
99
|
+
}
|
|
100
|
+
if (!session.context) session.context = {};
|
|
101
|
+
session.context[key] = value;
|
|
102
|
+
session.updatedAt = new Date().toISOString();
|
|
103
|
+
fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2), 'utf-8');
|
|
104
|
+
} catch { /* best effort */ }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// ── PageRank ─────────────────────────────────────────────────────────────────
|
|
108
|
+
|
|
109
|
+
function computePageRank(nodes, edges, damping, maxIter) {
|
|
110
|
+
damping = damping || 0.85;
|
|
111
|
+
maxIter = maxIter || 30;
|
|
112
|
+
|
|
113
|
+
const ids = Object.keys(nodes);
|
|
114
|
+
const n = ids.length;
|
|
115
|
+
if (n === 0) return {};
|
|
116
|
+
|
|
117
|
+
// Build adjacency: outgoing edges per node
|
|
118
|
+
const outLinks = {};
|
|
119
|
+
const inLinks = {};
|
|
120
|
+
for (const id of ids) { outLinks[id] = []; inLinks[id] = []; }
|
|
121
|
+
for (const edge of edges) {
|
|
122
|
+
if (outLinks[edge.sourceId]) outLinks[edge.sourceId].push(edge.targetId);
|
|
123
|
+
if (inLinks[edge.targetId]) inLinks[edge.targetId].push(edge.sourceId);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Initialize ranks
|
|
127
|
+
const ranks = {};
|
|
128
|
+
for (const id of ids) ranks[id] = 1 / n;
|
|
129
|
+
|
|
130
|
+
// Power iteration (with dangling node redistribution)
|
|
131
|
+
for (let iter = 0; iter < maxIter; iter++) {
|
|
132
|
+
const newRanks = {};
|
|
133
|
+
let diff = 0;
|
|
134
|
+
|
|
135
|
+
// Collect rank from dangling nodes (no outgoing edges)
|
|
136
|
+
let danglingSum = 0;
|
|
137
|
+
for (const id of ids) {
|
|
138
|
+
if (outLinks[id].length === 0) danglingSum += ranks[id];
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
for (const id of ids) {
|
|
142
|
+
let sum = 0;
|
|
143
|
+
for (const src of inLinks[id]) {
|
|
144
|
+
const outCount = outLinks[src].length;
|
|
145
|
+
if (outCount > 0) sum += ranks[src] / outCount;
|
|
146
|
+
}
|
|
147
|
+
// Dangling rank distributed evenly + teleport
|
|
148
|
+
newRanks[id] = (1 - damping) / n + damping * (sum + danglingSum / n);
|
|
149
|
+
diff += Math.abs(newRanks[id] - ranks[id]);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
for (const id of ids) ranks[id] = newRanks[id];
|
|
153
|
+
if (diff < 1e-6) break; // converged
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return ranks;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// ── Edge building ────────────────────────────────────────────────────────────
|
|
160
|
+
|
|
161
|
+
function buildEdges(entries) {
|
|
162
|
+
const edges = [];
|
|
163
|
+
const byCategory = {};
|
|
164
|
+
|
|
165
|
+
for (const entry of entries) {
|
|
166
|
+
const cat = entry.category || entry.namespace || 'default';
|
|
167
|
+
if (!byCategory[cat]) byCategory[cat] = [];
|
|
168
|
+
byCategory[cat].push(entry);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Temporal edges: entries from same sourceFile
|
|
172
|
+
const byFile = {};
|
|
173
|
+
for (const entry of entries) {
|
|
174
|
+
const file = (entry.metadata && entry.metadata.sourceFile) || null;
|
|
175
|
+
if (file) {
|
|
176
|
+
if (!byFile[file]) byFile[file] = [];
|
|
177
|
+
byFile[file].push(entry);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
for (const file of Object.keys(byFile)) {
|
|
181
|
+
const group = byFile[file];
|
|
182
|
+
for (let i = 0; i < group.length - 1; i++) {
|
|
183
|
+
edges.push({
|
|
184
|
+
sourceId: group[i].id,
|
|
185
|
+
targetId: group[i + 1].id,
|
|
186
|
+
type: 'temporal',
|
|
187
|
+
weight: 0.5,
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Similarity edges within categories (Jaccard > 0.3)
|
|
193
|
+
for (const cat of Object.keys(byCategory)) {
|
|
194
|
+
const group = byCategory[cat];
|
|
195
|
+
for (let i = 0; i < group.length; i++) {
|
|
196
|
+
const triA = trigrams(tokenize(group[i].content || group[i].summary || ''));
|
|
197
|
+
for (let j = i + 1; j < group.length; j++) {
|
|
198
|
+
const triB = trigrams(tokenize(group[j].content || group[j].summary || ''));
|
|
199
|
+
const sim = jaccardSimilarity(triA, triB);
|
|
200
|
+
if (sim > 0.3) {
|
|
201
|
+
edges.push({
|
|
202
|
+
sourceId: group[i].id,
|
|
203
|
+
targetId: group[j].id,
|
|
204
|
+
type: 'similar',
|
|
205
|
+
weight: sim,
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
return edges;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// ── Exported functions ───────────────────────────────────────────────────────
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* init() — Called from session-restore. Budget: <200ms.
|
|
219
|
+
* Reads auto-memory-store.json, builds graph, computes PageRank, writes caches.
|
|
220
|
+
*/
|
|
221
|
+
function init() {
|
|
222
|
+
ensureDataDir();
|
|
223
|
+
|
|
224
|
+
// Check if graph-state.json is fresh (within 60s of store)
|
|
225
|
+
const graphState = readJSON(GRAPH_PATH);
|
|
226
|
+
const store = readJSON(STORE_PATH);
|
|
227
|
+
|
|
228
|
+
if (!store || !Array.isArray(store) || store.length === 0) {
|
|
229
|
+
return { nodes: 0, edges: 0, message: 'No memory entries to index' };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// Skip rebuild if graph is fresh and store hasn't changed
|
|
233
|
+
if (graphState && graphState.nodeCount === store.length) {
|
|
234
|
+
const age = Date.now() - (graphState.updatedAt || 0);
|
|
235
|
+
if (age < 60000) {
|
|
236
|
+
return {
|
|
237
|
+
nodes: graphState.nodeCount || Object.keys(graphState.nodes || {}).length,
|
|
238
|
+
edges: (graphState.edges || []).length,
|
|
239
|
+
message: 'Graph cache hit',
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// Build nodes
|
|
245
|
+
const nodes = {};
|
|
246
|
+
for (const entry of store) {
|
|
247
|
+
const id = entry.id || entry.key || `entry-${Math.random().toString(36).slice(2, 8)}`;
|
|
248
|
+
nodes[id] = {
|
|
249
|
+
id,
|
|
250
|
+
category: entry.namespace || entry.type || 'default',
|
|
251
|
+
confidence: (entry.metadata && entry.metadata.confidence) || 0.5,
|
|
252
|
+
accessCount: (entry.metadata && entry.metadata.accessCount) || 0,
|
|
253
|
+
createdAt: entry.createdAt || Date.now(),
|
|
254
|
+
};
|
|
255
|
+
// Ensure entry has id for edge building
|
|
256
|
+
entry.id = id;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// Build edges
|
|
260
|
+
const edges = buildEdges(store);
|
|
261
|
+
|
|
262
|
+
// Compute PageRank
|
|
263
|
+
const pageRanks = computePageRank(nodes, edges, 0.85, 30);
|
|
264
|
+
|
|
265
|
+
// Write graph state
|
|
266
|
+
const graph = {
|
|
267
|
+
version: 1,
|
|
268
|
+
updatedAt: Date.now(),
|
|
269
|
+
nodeCount: Object.keys(nodes).length,
|
|
270
|
+
nodes,
|
|
271
|
+
edges,
|
|
272
|
+
pageRanks,
|
|
273
|
+
};
|
|
274
|
+
writeJSON(GRAPH_PATH, graph);
|
|
275
|
+
|
|
276
|
+
// Build ranked context for fast lookup
|
|
277
|
+
const rankedEntries = store.map(entry => {
|
|
278
|
+
const id = entry.id;
|
|
279
|
+
const content = entry.content || entry.value || '';
|
|
280
|
+
const summary = entry.summary || entry.key || '';
|
|
281
|
+
const words = tokenize(content + ' ' + summary);
|
|
282
|
+
return {
|
|
283
|
+
id,
|
|
284
|
+
content,
|
|
285
|
+
summary,
|
|
286
|
+
category: entry.namespace || entry.type || 'default',
|
|
287
|
+
confidence: nodes[id] ? nodes[id].confidence : 0.5,
|
|
288
|
+
pageRank: pageRanks[id] || 0,
|
|
289
|
+
accessCount: nodes[id] ? nodes[id].accessCount : 0,
|
|
290
|
+
words,
|
|
291
|
+
};
|
|
292
|
+
}).sort((a, b) => {
|
|
293
|
+
const scoreA = 0.6 * a.pageRank + 0.4 * a.confidence;
|
|
294
|
+
const scoreB = 0.6 * b.pageRank + 0.4 * b.confidence;
|
|
295
|
+
return scoreB - scoreA;
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
const ranked = {
|
|
299
|
+
version: 1,
|
|
300
|
+
computedAt: Date.now(),
|
|
301
|
+
entries: rankedEntries,
|
|
302
|
+
};
|
|
303
|
+
writeJSON(RANKED_PATH, ranked);
|
|
304
|
+
|
|
305
|
+
return {
|
|
306
|
+
nodes: Object.keys(nodes).length,
|
|
307
|
+
edges: edges.length,
|
|
308
|
+
message: 'Graph built and ranked',
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* getContext(prompt) — Called from route. Budget: <15ms.
|
|
314
|
+
* Matches prompt to ranked entries, returns top-5 formatted context.
|
|
315
|
+
*/
|
|
316
|
+
function getContext(prompt) {
|
|
317
|
+
if (!prompt) return null;
|
|
318
|
+
|
|
319
|
+
const ranked = readJSON(RANKED_PATH);
|
|
320
|
+
if (!ranked || !ranked.entries || ranked.entries.length === 0) return null;
|
|
321
|
+
|
|
322
|
+
const promptWords = tokenize(prompt);
|
|
323
|
+
if (promptWords.length === 0) return null;
|
|
324
|
+
const promptTrigrams = trigrams(promptWords);
|
|
325
|
+
|
|
326
|
+
const ALPHA = 0.6; // content match weight
|
|
327
|
+
const MIN_THRESHOLD = 0.05;
|
|
328
|
+
const TOP_K = 5;
|
|
329
|
+
|
|
330
|
+
// Score each entry
|
|
331
|
+
const scored = [];
|
|
332
|
+
for (const entry of ranked.entries) {
|
|
333
|
+
const entryTrigrams = trigrams(entry.words || []);
|
|
334
|
+
const contentMatch = jaccardSimilarity(promptTrigrams, entryTrigrams);
|
|
335
|
+
const score = ALPHA * contentMatch + (1 - ALPHA) * (entry.pageRank || 0);
|
|
336
|
+
if (score >= MIN_THRESHOLD) {
|
|
337
|
+
scored.push({ ...entry, score });
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
if (scored.length === 0) return null;
|
|
342
|
+
|
|
343
|
+
// Sort by score descending, take top-K
|
|
344
|
+
scored.sort((a, b) => b.score - a.score);
|
|
345
|
+
const topEntries = scored.slice(0, TOP_K);
|
|
346
|
+
|
|
347
|
+
// Boost previously matched patterns (implicit success: user continued working)
|
|
348
|
+
const prevMatched = sessionGet('lastMatchedPatterns');
|
|
349
|
+
|
|
350
|
+
// Store NEW matched IDs in session state for feedback
|
|
351
|
+
const matchedIds = topEntries.map(e => e.id);
|
|
352
|
+
sessionSet('lastMatchedPatterns', matchedIds);
|
|
353
|
+
|
|
354
|
+
// Only boost previous if they differ from current (avoid double-boosting)
|
|
355
|
+
if (prevMatched && Array.isArray(prevMatched)) {
|
|
356
|
+
const newSet = new Set(matchedIds);
|
|
357
|
+
const toBoost = prevMatched.filter(id => !newSet.has(id));
|
|
358
|
+
if (toBoost.length > 0) boostConfidence(toBoost, 0.03);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// Format output
|
|
362
|
+
const lines = ['[INTELLIGENCE] Relevant patterns for this task:'];
|
|
363
|
+
for (let i = 0; i < topEntries.length; i++) {
|
|
364
|
+
const e = topEntries[i];
|
|
365
|
+
const display = (e.summary || e.content || '').slice(0, 80);
|
|
366
|
+
const accessed = e.accessCount || 0;
|
|
367
|
+
lines.push(` * (${e.score.toFixed(2)}) ${display} [rank #${i + 1}, ${accessed}x accessed]`);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
return lines.join('\n');
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* recordEdit(file) — Called from post-edit. Budget: <2ms.
|
|
375
|
+
* Appends to pending-insights.jsonl.
|
|
376
|
+
*/
|
|
377
|
+
function recordEdit(file) {
|
|
378
|
+
ensureDataDir();
|
|
379
|
+
const entry = JSON.stringify({
|
|
380
|
+
type: 'edit',
|
|
381
|
+
file: file || 'unknown',
|
|
382
|
+
timestamp: Date.now(),
|
|
383
|
+
sessionId: sessionGet('sessionId') || null,
|
|
384
|
+
});
|
|
385
|
+
fs.appendFileSync(PENDING_PATH, entry + '\n', 'utf-8');
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* feedback(success) — Called from post-task. Budget: <10ms.
|
|
390
|
+
* Boosts or decays confidence for last-matched patterns.
|
|
391
|
+
*/
|
|
392
|
+
function feedback(success) {
|
|
393
|
+
const matchedIds = sessionGet('lastMatchedPatterns');
|
|
394
|
+
if (!matchedIds || !Array.isArray(matchedIds)) return;
|
|
395
|
+
|
|
396
|
+
const amount = success ? 0.05 : -0.02;
|
|
397
|
+
boostConfidence(matchedIds, amount);
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function boostConfidence(ids, amount) {
|
|
401
|
+
const ranked = readJSON(RANKED_PATH);
|
|
402
|
+
if (!ranked || !ranked.entries) return;
|
|
403
|
+
|
|
404
|
+
let changed = false;
|
|
405
|
+
for (const entry of ranked.entries) {
|
|
406
|
+
if (ids.includes(entry.id)) {
|
|
407
|
+
entry.confidence = Math.max(0, Math.min(1, (entry.confidence || 0.5) + amount));
|
|
408
|
+
entry.accessCount = (entry.accessCount || 0) + 1;
|
|
409
|
+
changed = true;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
if (changed) writeJSON(RANKED_PATH, ranked);
|
|
414
|
+
|
|
415
|
+
// Also update graph-state confidence
|
|
416
|
+
const graph = readJSON(GRAPH_PATH);
|
|
417
|
+
if (graph && graph.nodes) {
|
|
418
|
+
for (const id of ids) {
|
|
419
|
+
if (graph.nodes[id]) {
|
|
420
|
+
graph.nodes[id].confidence = Math.max(0, Math.min(1, (graph.nodes[id].confidence || 0.5) + amount));
|
|
421
|
+
graph.nodes[id].accessCount = (graph.nodes[id].accessCount || 0) + 1;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
writeJSON(GRAPH_PATH, graph);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* consolidate() — Called from session-end. Budget: <500ms.
|
|
430
|
+
* Processes pending insights, rebuilds edges, recomputes PageRank.
|
|
431
|
+
*/
|
|
432
|
+
function consolidate() {
|
|
433
|
+
ensureDataDir();
|
|
434
|
+
|
|
435
|
+
const store = readJSON(STORE_PATH);
|
|
436
|
+
if (!store || !Array.isArray(store)) {
|
|
437
|
+
return { entries: 0, edges: 0, newEntries: 0, message: 'No store to consolidate' };
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// 1. Process pending insights
|
|
441
|
+
let newEntries = 0;
|
|
442
|
+
if (fs.existsSync(PENDING_PATH)) {
|
|
443
|
+
const lines = fs.readFileSync(PENDING_PATH, 'utf-8').trim().split('\n').filter(Boolean);
|
|
444
|
+
const editCounts = {};
|
|
445
|
+
for (const line of lines) {
|
|
446
|
+
try {
|
|
447
|
+
const insight = JSON.parse(line);
|
|
448
|
+
if (insight.file) {
|
|
449
|
+
editCounts[insight.file] = (editCounts[insight.file] || 0) + 1;
|
|
450
|
+
}
|
|
451
|
+
} catch { /* skip malformed */ }
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// Create entries for frequently-edited files (3+ edits)
|
|
455
|
+
for (const [file, count] of Object.entries(editCounts)) {
|
|
456
|
+
if (count >= 3) {
|
|
457
|
+
const exists = store.some(e =>
|
|
458
|
+
(e.metadata && e.metadata.sourceFile === file && e.metadata.autoGenerated)
|
|
459
|
+
);
|
|
460
|
+
if (!exists) {
|
|
461
|
+
store.push({
|
|
462
|
+
id: `insight-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
|
463
|
+
key: `frequent-edit-${path.basename(file)}`,
|
|
464
|
+
content: `File ${file} was edited ${count} times this session — likely a hot path worth monitoring.`,
|
|
465
|
+
summary: `Frequently edited: ${path.basename(file)} (${count}x)`,
|
|
466
|
+
namespace: 'insights',
|
|
467
|
+
type: 'procedural',
|
|
468
|
+
metadata: { sourceFile: file, editCount: count, autoGenerated: true },
|
|
469
|
+
createdAt: Date.now(),
|
|
470
|
+
});
|
|
471
|
+
newEntries++;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// Clear pending
|
|
477
|
+
fs.writeFileSync(PENDING_PATH, '', 'utf-8');
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// 2. Confidence decay for unaccessed entries
|
|
481
|
+
const graph = readJSON(GRAPH_PATH);
|
|
482
|
+
if (graph && graph.nodes) {
|
|
483
|
+
const now = Date.now();
|
|
484
|
+
for (const id of Object.keys(graph.nodes)) {
|
|
485
|
+
const node = graph.nodes[id];
|
|
486
|
+
const hoursSinceCreation = (now - (node.createdAt || now)) / (1000 * 60 * 60);
|
|
487
|
+
if (node.accessCount === 0 && hoursSinceCreation > 24) {
|
|
488
|
+
node.confidence = Math.max(0.05, (node.confidence || 0.5) - 0.005 * Math.floor(hoursSinceCreation / 24));
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
// 3. Rebuild edges with updated store
|
|
494
|
+
for (const entry of store) {
|
|
495
|
+
if (!entry.id) entry.id = `entry-${Math.random().toString(36).slice(2, 8)}`;
|
|
496
|
+
}
|
|
497
|
+
const edges = buildEdges(store);
|
|
498
|
+
|
|
499
|
+
// 4. Build updated nodes
|
|
500
|
+
const nodes = {};
|
|
501
|
+
for (const entry of store) {
|
|
502
|
+
nodes[entry.id] = {
|
|
503
|
+
id: entry.id,
|
|
504
|
+
category: entry.namespace || entry.type || 'default',
|
|
505
|
+
confidence: (graph && graph.nodes && graph.nodes[entry.id])
|
|
506
|
+
? graph.nodes[entry.id].confidence
|
|
507
|
+
: (entry.metadata && entry.metadata.confidence) || 0.5,
|
|
508
|
+
accessCount: (graph && graph.nodes && graph.nodes[entry.id])
|
|
509
|
+
? graph.nodes[entry.id].accessCount
|
|
510
|
+
: (entry.metadata && entry.metadata.accessCount) || 0,
|
|
511
|
+
createdAt: entry.createdAt || Date.now(),
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
// 5. Recompute PageRank
|
|
516
|
+
const pageRanks = computePageRank(nodes, edges, 0.85, 30);
|
|
517
|
+
|
|
518
|
+
// 6. Write updated graph
|
|
519
|
+
writeJSON(GRAPH_PATH, {
|
|
520
|
+
version: 1,
|
|
521
|
+
updatedAt: Date.now(),
|
|
522
|
+
nodeCount: Object.keys(nodes).length,
|
|
523
|
+
nodes,
|
|
524
|
+
edges,
|
|
525
|
+
pageRanks,
|
|
526
|
+
});
|
|
527
|
+
|
|
528
|
+
// 7. Write updated ranked context
|
|
529
|
+
const rankedEntries = store.map(entry => {
|
|
530
|
+
const id = entry.id;
|
|
531
|
+
const content = entry.content || entry.value || '';
|
|
532
|
+
const summary = entry.summary || entry.key || '';
|
|
533
|
+
const words = tokenize(content + ' ' + summary);
|
|
534
|
+
return {
|
|
535
|
+
id,
|
|
536
|
+
content,
|
|
537
|
+
summary,
|
|
538
|
+
category: entry.namespace || entry.type || 'default',
|
|
539
|
+
confidence: nodes[id] ? nodes[id].confidence : 0.5,
|
|
540
|
+
pageRank: pageRanks[id] || 0,
|
|
541
|
+
accessCount: nodes[id] ? nodes[id].accessCount : 0,
|
|
542
|
+
words,
|
|
543
|
+
};
|
|
544
|
+
}).sort((a, b) => {
|
|
545
|
+
const scoreA = 0.6 * a.pageRank + 0.4 * a.confidence;
|
|
546
|
+
const scoreB = 0.6 * b.pageRank + 0.4 * b.confidence;
|
|
547
|
+
return scoreB - scoreA;
|
|
548
|
+
});
|
|
549
|
+
|
|
550
|
+
writeJSON(RANKED_PATH, {
|
|
551
|
+
version: 1,
|
|
552
|
+
computedAt: Date.now(),
|
|
553
|
+
entries: rankedEntries,
|
|
554
|
+
});
|
|
555
|
+
|
|
556
|
+
// 8. Persist updated store (with new insight entries)
|
|
557
|
+
if (newEntries > 0) writeJSON(STORE_PATH, store);
|
|
558
|
+
|
|
559
|
+
return {
|
|
560
|
+
entries: store.length,
|
|
561
|
+
edges: edges.length,
|
|
562
|
+
newEntries,
|
|
563
|
+
message: 'Consolidated',
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
module.exports = { init, getContext, recordEdit, feedback, consolidate };
|
|
@@ -100,6 +100,14 @@ const commands = {
|
|
|
100
100
|
return session;
|
|
101
101
|
},
|
|
102
102
|
|
|
103
|
+
get: (key) => {
|
|
104
|
+
if (!fs.existsSync(SESSION_FILE)) return null;
|
|
105
|
+
try {
|
|
106
|
+
const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));
|
|
107
|
+
return key ? (session.context || {})[key] : session.context;
|
|
108
|
+
} catch { return null; }
|
|
109
|
+
},
|
|
110
|
+
|
|
103
111
|
metric: (name) => {
|
|
104
112
|
if (!fs.existsSync(SESSION_FILE)) {
|
|
105
113
|
return null;
|
|
@@ -371,7 +371,7 @@ export async function executeUpgrade(targetDir, upgradeSettings = false) {
|
|
|
371
371
|
// 0. ALWAYS update critical helpers (force overwrite)
|
|
372
372
|
const sourceHelpersForUpgrade = findSourceHelpersDir();
|
|
373
373
|
if (sourceHelpersForUpgrade) {
|
|
374
|
-
const criticalHelpers = ['auto-memory-hook.mjs', 'hook-handler.cjs'];
|
|
374
|
+
const criticalHelpers = ['auto-memory-hook.mjs', 'hook-handler.cjs', 'intelligence.cjs'];
|
|
375
375
|
for (const helperName of criticalHelpers) {
|
|
376
376
|
const targetPath = path.join(targetDir, '.claude', 'helpers', helperName);
|
|
377
377
|
const sourcePath = path.join(sourceHelpersForUpgrade, helperName);
|