-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdepgraph-server.mjs
More file actions
333 lines (301 loc) · 12.3 KB
/
depgraph-server.mjs
File metadata and controls
333 lines (301 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
#!/usr/bin/env node
// Tools dev server: static files + SSE for depgraph focus events
// Usage: node depgraph-server.mjs [port] [--simulate[=interval_ms]]
import { createServer } from 'node:http';
import { readFile, readFileSync, writeFile, watch } from 'node:fs';
import { join, extname, resolve } from 'node:path';
import { exec } from 'node:child_process';
import { generateHistory } from './codegen/historygen.mjs';
import { startSimulation } from './codegen/simulator.mjs';
// Parse args: support --simulate and --simulate=2000
const args = process.argv.slice(2);
const simArg = args.find(a => a.startsWith('--simulate'));
const SIMULATE = !!simArg;
const SIM_INTERVAL = simArg && simArg.includes('=') ? parseInt(simArg.split('=')[1], 10) : 3000;
const PORT = parseInt(args.find(a => !a.startsWith('-')) || '3800', 10);
const ROOT = resolve(import.meta.dirname, '.');
const FOCUS_FILE = join(ROOT, 'runtime/depgraph-focus.json');
// ── Load inspect.json ─────────────────────────────
const INSPECT_FILE = join(ROOT, 'inspect.json');
const inspect = JSON.parse(readFileSync(INSPECT_FILE, 'utf8'));
const TARGET_SRC = resolve(ROOT, inspect.src);
const CODEMAP_FILE = resolve(ROOT, inspect.codemap);
console.log(`\x1b[33minspect\x1b[0m ${inspect.name}`);
console.log(` src → ${TARGET_SRC}`);
console.log(` map → ${CODEMAP_FILE}`);
const MIME = {
'.html': 'text/html',
'.js': 'application/javascript',
'.mjs': 'application/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
};
// ── SSE clients ────────────────────────────────────
const clients = new Set();
function broadcast(data) {
const msg = `data: ${JSON.stringify(data)}\n\n`;
for (const res of clients) {
try { res.write(msg); } catch { clients.delete(res); }
}
}
// ── Watch focus file (macOS FSEvents via fs.watch) ─
let lastFocus = null;
function readFocus() {
readFile(FOCUS_FILE, 'utf8', (err, text) => {
if (err) return;
try {
const data = JSON.parse(text);
const key = JSON.stringify(data);
if (key === lastFocus) return;
lastFocus = key;
broadcast(data);
} catch { /* malformed json, skip */ }
});
}
watch(FOCUS_FILE, { persistent: true }, () => readFocus());
readFocus();
// ── Graph generation: watch src + codemap, regenerate CSVs ─
const HISTORY_FILE = join(ROOT, 'runtime/history.csv');
const graphClients = new Set();
function broadcastGraph(data) {
const msg = `data: ${JSON.stringify(data)}\n\n`;
for (const res of graphClients) {
try { res.write(msg); } catch { graphClients.delete(res); }
}
}
let graphgenTimer = null;
function triggerGraphgen() {
clearTimeout(graphgenTimer);
graphgenTimer = setTimeout(() => {
try {
const result = generateHistory(INSPECT_FILE);
if (result) broadcastGraph({ type: 'graph-update', nodes: result.nNodes, edges: result.nEdges });
} catch (e) {
console.error('[historygen] error:', e.message);
}
}, 200); // debounce 200ms
}
if (SIMULATE) {
// Simulation mode: generate evolving synthetic data instead of watching files
console.log(`\x1b[35m[sim]\x1b[0m simulation mode enabled (interval: ${SIM_INTERVAL}ms)`);
startSimulation(join(ROOT, 'runtime'), broadcastGraph, SIM_INTERVAL);
} else {
// Normal mode: generate on startup, watch for file changes
try { generateHistory(INSPECT_FILE); } catch (e) { console.error('[historygen] initial error:', e.message); }
watch(TARGET_SRC, { persistent: true }, () => {
console.log('[watch] src changed');
triggerGraphgen();
});
watch(CODEMAP_FILE, { persistent: true }, () => {
console.log('[watch] codemap changed');
triggerGraphgen();
});
}
// ── HTTP server ────────────────────────────────────
function isLocal(req) {
const remote = req.socket.remoteAddress;
return remote === '127.0.0.1' || remote === '::1' || remote === '::ffff:127.0.0.1';
}
const server = createServer((req, res) => {
if (!isLocal(req)) {
res.writeHead(403);
res.end('localhost only');
return;
}
const url = new URL(req.url, `http://localhost:${PORT}`);
// Cluster creation — immediately writes unnamed section, then renames async via Claude
if (url.pathname === '/cluster' && req.method === 'POST') {
let body = '';
req.on('data', chunk => { body += chunk; });
req.on('end', () => {
try {
const { nodeIds, existingClusters, nodeDetails } = JSON.parse(body);
const tempName = `Unnamed Cluster ${Date.now()}`;
const section = `\n## ${tempName}\n<!-- user-cluster -->\n` +
nodeIds.map(id => `- \`${id}\``).join('\n') + '\n';
// Step 1: write placeholder immediately
readFile(CODEMAP_FILE, 'utf8', (err, content) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'read error' }));
return;
}
writeFile(CODEMAP_FILE, content.trimEnd() + '\n' + section, 'utf8', (err2) => {
if (err2) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'write error' }));
return;
}
// Respond immediately with the temp name
console.log(`[cluster] created placeholder: ${tempName}`);
res.writeHead(200, { 'Content-Type': 'application/json', 'X-Content-Type-Options': 'nosniff' });
res.end(JSON.stringify({ name: tempName }));
// Step 2: spawn Claude in background to name it, then rename in codemap
const prompt = [
'You are naming a user-defined cluster of variables/functions in a dependency graph.',
'The user has selected these functions to group together:',
nodeIds.map(id => {
const d = nodeDetails[id];
if (!d) return `- ${id}`;
return `- ${id} (system: ${d.system}, reads: ${d.reads}, writes: ${d.writes}, calls: ${d.calls})`;
}).join('\n'),
'',
'Existing system clusters in this graph: ' + existingClusters.join(', '),
'',
'Give this cluster a short, descriptive name (4 words max) that captures what these functions have in common.',
'The name should be distinct from the existing clusters listed above.',
'Reply with ONLY the cluster name, nothing else.',
].join('\n');
const escaped = prompt.replace(/'/g, "'\\''");
exec(`claude -p '${escaped}' --model haiku`, {
timeout: 30000,
shell: '/bin/zsh',
}, (err3, stdout, stderr) => {
if (err3) {
console.error('[cluster] claude naming error:', err3.message, stderr);
return;
}
const finalName = stdout.trim().replace(/^["']|["']$/g, '');
console.log(`[cluster] renaming "${tempName}" → "${finalName}"`);
// Replace the temp name in codemap
readFile(CODEMAP_FILE, 'utf8', (err4, current) => {
if (err4) return;
const updated = current.replace(`## ${tempName}`, `## ${finalName}`);
if (updated !== current) {
writeFile(CODEMAP_FILE, updated, 'utf8', (err5) => {
if (err5) console.error('[cluster] rename write error:', err5.message);
else console.log(`[cluster] renamed to: ${finalName}`);
});
}
});
});
});
});
} catch (e) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'invalid JSON' }));
}
});
return;
}
// Delete a user cluster section from codemap
if (url.pathname === '/cluster' && req.method === 'DELETE') {
let body = '';
req.on('data', chunk => { body += chunk; });
req.on('end', () => {
try {
const { sectionName } = JSON.parse(body);
readFile(CODEMAP_FILE, 'utf8', (err, content) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'read error' }));
return;
}
// Remove the section: from "## Name\n<!-- user-cluster -->" to next "## " or EOF
const escaped = sectionName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const re = new RegExp(`\\n## ${escaped}\\n<!-- user-cluster -->\\n(?:- [^\\n]*\\n?)*`, 'g');
const updated = content.replace(re, '');
if (updated === content) {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'section not found' }));
return;
}
writeFile(CODEMAP_FILE, updated, 'utf8', (err2) => {
if (err2) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'write error' }));
return;
}
console.log(`[cluster] deleted: ${sectionName}`);
res.writeHead(200, { 'Content-Type': 'application/json', 'X-Content-Type-Options': 'nosniff' });
res.end(JSON.stringify({ deleted: true }));
});
});
} catch (e) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'invalid JSON' }));
}
});
return;
}
// SSE endpoint
if (url.pathname === '/focus-events') {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache, no-store',
'Connection': 'keep-alive',
'X-Content-Type-Options': 'nosniff',
});
res.write(`data: ${lastFocus || JSON.stringify({ focus: [] })}\n\n`);
clients.add(res);
req.on('close', () => clients.delete(res));
return;
}
// SSE endpoint for graph updates
if (url.pathname === '/graph-events') {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache, no-store',
'Connection': 'keep-alive',
'X-Content-Type-Options': 'nosniff',
});
res.write(`data: ${JSON.stringify({ type: 'connected' })}\n\n`);
graphClients.add(res);
req.on('close', () => graphClients.delete(res));
return;
}
// Serve history CSV (combined nodes + edges time-series)
if (url.pathname === '/runtime/history.csv') {
readFile(HISTORY_FILE, (err, data) => {
if (err) { res.writeHead(404); res.end('history.csv not found'); return; }
res.writeHead(200, { 'Content-Type': 'text/csv', 'X-Content-Type-Options': 'nosniff' });
res.end(data);
});
return;
}
// Serve inspect.json so the frontend can read it
if (url.pathname === '/inspect.json') {
readFile(INSPECT_FILE, (err, data) => {
if (err) { res.writeHead(500); res.end('error'); return; }
res.writeHead(200, { 'Content-Type': 'application/json', 'X-Content-Type-Options': 'nosniff' });
res.end(data);
});
return;
}
// Serve the target source file at /target/src
if (url.pathname === '/target/src') {
readFile(TARGET_SRC, (err, data) => {
if (err) { res.writeHead(404); res.end('target src not found'); return; }
res.writeHead(200, { 'Content-Type': MIME[extname(TARGET_SRC)] || 'text/plain', 'X-Content-Type-Options': 'nosniff' });
res.end(data);
});
return;
}
// Static files (project root)
let filePath = join(ROOT, '/prototypes/index.html');
if (url.pathname !== '/') {
filePath = join(ROOT, url.pathname);
}
readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404);
res.end('not found');
return;
}
res.writeHead(200, {
'Content-Type': MIME[extname(filePath)] || 'application/octet-stream',
'X-Content-Type-Options': 'nosniff',
});
res.end(data);
});
});
server.listen(PORT, '127.0.0.1', () => {
console.log(`\x1b[36mdepgraph\x1b[0m → http://127.0.0.1:${PORT}`);
console.log(` SSE → /focus-events, /graph-events`);
console.log(` CSV → /runtime/history.csv`);
console.log(` target → /target/src`);
console.log(` watch → src, codemap, ${FOCUS_FILE}`);
});