-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
459 lines (394 loc) Β· 17.9 KB
/
server.js
File metadata and controls
459 lines (394 loc) Β· 17.9 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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
import express from 'express';
import cors from 'cors';
import { createServer } from 'http';
import { Server } from 'socket.io';
import fs from 'fs';
import path from 'path';
import { exec } from 'child_process';
import { promisify } from 'util';
import { fileURLToPath } from 'url';
import crypto from 'crypto';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const execAsync = promisify(exec);
const app = express();
const server = createServer(app);
const io = new Server(server, { cors: { origin: '*' } });
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'docs/dashboard')));
app.use(express.static(path.join(__dirname, 'surgery-room')));
// ============================================================
// Configuration
// ============================================================
const ELITE_VERSION = '1.7.0';
const SURGERY_BASE = path.join(__dirname, 'surgery-room');
const REPAIRS_DIR = path.join(SURGERY_BASE, 'repairs');
const SUCCESS_DIR = path.join(SURGERY_BASE, 'successful');
const FAILED_DIR = path.join(SURGERY_BASE, 'failed');
const BLOCKCHAIN_DIR = path.join(__dirname, 'blockchain');
// Create directories
[SURGERY_BASE, REPAIRS_DIR, SUCCESS_DIR, FAILED_DIR, BLOCKCHAIN_DIR].forEach(dir => {
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
});
// ============================================================
// Data Storage
// ============================================================
let surgeryRecords = [];
let activeSurgeries = new Map();
let blockchainBlocks = [];
// Load records
function loadRecords() {
const recordsPath = path.join(SURGERY_BASE, 'surgery-records.json');
if (fs.existsSync(recordsPath)) {
try {
surgeryRecords = JSON.parse(fs.readFileSync(recordsPath, 'utf8'));
} catch(e) { surgeryRecords = []; }
}
}
loadRecords();
function saveRecords() {
fs.writeFileSync(path.join(SURGERY_BASE, 'surgery-records.json'), JSON.stringify(surgeryRecords, null, 2));
}
// ============================================================
// Blockchain Functions
// ============================================================
function generateBlockHash(data) {
return crypto.createHash('sha256')
.update(JSON.stringify(data) + Date.now())
.digest('hex');
}
function addToBlockchain(event, data) {
const block = {
index: blockchainBlocks.length,
timestamp: new Date().toISOString(),
hash: generateBlockHash(data),
previousHash: blockchainBlocks.length > 0 ? blockchainBlocks[blockchainBlocks.length - 1].hash : '0'.repeat(64),
data: { event, ...data, timestamp: new Date().toISOString() }
};
blockchainBlocks.push(block);
// Persist to disk
const blockPath = path.join(BLOCKCHAIN_DIR, `block-${block.index}.json`);
fs.writeFileSync(blockPath, JSON.stringify(block, null, 2));
return block.hash;
}
// ============================================================
// SurgerySession Class (Elite)
// ============================================================
class SurgerySession {
constructor(id, repoUrl, branchName, eliteConfig = {}) {
this.id = id;
this.repoUrl = repoUrl;
this.repoName = repoUrl.split('/').pop().replace('.git', '');
this.branchName = branchName;
this.surgeryPath = path.join(REPAIRS_DIR, `${this.repoName}_${id}`);
this.status = 'preparing';
this.steps = [];
this.prNumber = null;
this.startTime = new Date();
this.hasChanges = false;
this.language = 'unknown';
this.eliteConfig = {
dynamicShifting: true,
blockchainAudit: true,
selfHealing: true,
...eliteConfig
};
this.shiftMetrics = null;
this.auditHash = null;
this.blockchainHash = addToBlockchain('session_created', {
sessionId: id,
repo: this.repoName,
branch: branchName
});
}
addStep(stepName, status, detail = '') {
this.steps.push({ step: stepName, status, detail, timestamp: new Date() });
io.emit('repair-update', { sessionId: this.id, step: stepName, status, detail });
saveRecords();
}
complete(success, prNumber = null, prUrl = null) {
this.status = success ? 'successful' : 'failed';
if (prNumber) this.prNumber = prNumber;
addToBlockchain('session_completed', {
sessionId: this.id,
success,
prNumber,
stepsCount: this.steps.length
});
saveRecords();
io.emit('repair-complete', { sessionId: this.id, status: this.status, prNumber, prUrl });
}
}
// ============================================================
// Helper Functions
// ============================================================
async function execPS(command, cwd) {
if (!cwd || !fs.existsSync(cwd)) {
console.error(`Invalid cwd: ${cwd}`);
return { stdout: '', stderr: 'Invalid working directory' };
}
const tmpFile = path.join(SURGERY_BASE, `_ps_${Date.now()}.ps1`);
const scriptContent = `Set-Location "${cwd}"\n${command}\n`;
fs.writeFileSync(tmpFile, scriptContent, 'utf8');
try {
const { stdout, stderr } = await execAsync(`powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "${tmpFile}"`, {
maxBuffer: 20 * 1024 * 1024,
timeout: 120000
});
return { stdout, stderr };
} catch (error) {
return { stdout: error.stdout || '', stderr: error.stderr || error.message };
} finally {
try { fs.unlinkSync(tmpFile); } catch(e) { /* ignore */ }
}
}
async function detectLanguage(surgeryPath) {
try {
const files = fs.readdirSync(surgeryPath);
if (files.includes('package.json')) return 'node';
if (files.includes('requirements.txt') || files.includes('pyproject.toml')) return 'python';
if (files.includes('Cargo.toml')) return 'rust';
if (files.includes('go.mod')) return 'golang';
return 'unknown';
} catch(e) {
return 'unknown';
}
}
async function dynamicTestShifting(surgeryPath, strategy = 'adaptive') {
console.log(`π Dynamic Test Shifting - Strategy: ${strategy}`);
const testPatterns = ['*.test.js', '*.test.ts', '*.spec.js', '*.spec.ts'];
let testFiles = [];
for (const pattern of testPatterns) {
try {
const { stdout } = await execPS(`Get-ChildItem -Recurse -Filter ${pattern} | Select-Object -ExpandProperty Name`, surgeryPath);
testFiles.push(...stdout.split('\n').filter(f => f.trim()));
} catch(e) {}
}
testFiles = [...new Set(testFiles)];
// Apply strategy
if (strategy === 'chaos') {
testFiles.sort(() => Math.random() - 0.5);
} else if (strategy === 'weighted') {
testFiles.sort((a, b) => a.length - b.length);
}
return { count: testFiles.length, strategy, tests: testFiles.slice(0, 5) };
}
// ============================================================
// API Endpoints
// ============================================================
app.get('/health', (req, res) => res.json({
status: 'ELITE_UP',
version: ELITE_VERSION,
blockchainHeight: blockchainBlocks.length,
timestamp: new Date().toISOString()
}));
app.get('/metrics', (req, res) => res.json({
totalSurgeries: surgeryRecords.length,
activeSurgeries: activeSurgeries.size,
blockchainHeight: blockchainBlocks.length,
eliteVersion: ELITE_VERSION
}));
app.get('/api/blockchain', (req, res) => res.json(blockchainBlocks));
app.get('/api/surgery/records', (req, res) => res.json(surgeryRecords));
// Start surgery session
app.post('/api/surgery/start', async (req, res) => {
const { repoUrl, branchName, keepAfterRepair, eliteConfig } = req.body;
const sessionId = Date.now().toString();
const session = new SurgerySession(sessionId, repoUrl, branchName, eliteConfig);
session.keepAfterRepair = keepAfterRepair;
surgeryRecords.unshift({
id: sessionId,
repoName: session.repoName,
branchName,
status: 'running',
startTime: session.startTime,
eliteMode: session.eliteConfig.dynamicShifting
});
activeSurgeries.set(sessionId, session);
saveRecords();
res.json({ success: true, sessionId });
});
// Clone repository
app.post('/api/surgery/clone', async (req, res) => {
const { sessionId, repoUrl, branchName } = req.body;
const session = activeSurgeries.get(sessionId);
if (!session) return res.json({ success: false, error: 'Session not found' });
try {
if (!fs.existsSync(session.surgeryPath)) {
fs.mkdirSync(session.surgeryPath, { recursive: true });
}
await execAsync(`git clone ${repoUrl} "${session.surgeryPath}"`);
await execAsync(`cd "${session.surgeryPath}" && git checkout -b ${branchName} 2>/dev/null || git checkout ${branchName}`);
session.addStep('π‘ Clone', 'completed', `Cloned to ${session.surgeryPath}`);
res.json({ success: true });
} catch (error) {
session.addStep('π‘ Clone', 'failed', error.message);
res.json({ success: false, error: error.message });
}
});
// Run generic step
app.post('/api/surgery/step', async (req, res) => {
const { sessionId, step, command } = req.body;
const session = activeSurgeries.get(sessionId);
if (!session) return res.json({ success: false, error: 'Session not found' });
try {
const { stdout } = await execPS(command, session.surgeryPath);
session.addStep(step, 'completed', stdout.substring(0, 200));
res.json({ success: true, output: stdout });
} catch (error) {
session.addStep(step, 'failed', error.message);
res.json({ success: false, error: error.message });
}
});
// Elite auto-repair (NEW)
app.post('/api/surgery/elite-repair', async (req, res) => {
const { sessionId, shiftStrategy } = req.body;
const session = activeSurgeries.get(sessionId);
if (!session) return res.json({ success: false, error: 'Session not found' });
const fixes = [];
try {
// Dynamic test shifting
if (session.eliteConfig.dynamicShifting) {
const shiftResult = await dynamicTestShifting(session.surgeryPath, shiftStrategy || 'adaptive');
session.shiftMetrics = shiftResult;
session.addStep('π Dynamic Shift', 'completed', `${shiftResult.count} tests redistributed (${shiftResult.strategy})`);
fixes.push(`Dynamic test shifting: ${shiftResult.count} tests`);
}
// Detect language
const language = await detectLanguage(session.surgeryPath);
session.language = language;
session.addStep('π Detection', 'completed', `Detected: ${language}`);
fixes.push(`Detected language: ${language}`);
// Create package.json if missing (Node.js)
const pkgPath = path.join(session.surgeryPath, 'package.json');
if (!fs.existsSync(pkgPath) && language === 'node') {
const defaultPkg = {
name: session.repoName,
version: '1.0.0',
scripts: {
build: 'tsc || echo "Build configured"',
test: 'node --test || echo "Tests configured"'
},
devDependencies: {
typescript: '^5.4.0',
'@types/node': '^20.0.0'
}
};
fs.writeFileSync(pkgPath, JSON.stringify(defaultPkg, null, 2));
fixes.push('β
Created package.json');
}
// Create .gitignore if missing
const gitignorePath = path.join(session.surgeryPath, '.gitignore');
if (!fs.existsSync(gitignorePath)) {
const gitignoreContent = `node_modules/\ndist/\n.env\n*.log\ncoverage/\n.DS_Store\noracle-memory.json\nblockchain/\n`;
fs.writeFileSync(gitignorePath, gitignoreContent);
fixes.push('β
Created .gitignore');
}
// Install dependencies
if (language === 'node') {
await execPS('npm install', session.surgeryPath);
fixes.push('β
npm install completed');
await execPS('npm run build', session.surgeryPath).catch(() => {});
fixes.push('β
Build attempted');
}
// Blockchain audit
if (session.eliteConfig.blockchainAudit) {
const auditHash = addToBlockchain('repair_completed', {
sessionId: session.id,
repo: session.repoName,
fixes: fixes.length,
shiftMetrics: session.shiftMetrics
});
session.auditHash = auditHash;
session.addStep('βοΈ Blockchain', 'completed', `Hash: ${auditHash.substring(0, 16)}...`);
fixes.push(`Blockchain recorded: ${auditHash.substring(0, 16)}...`);
}
session.hasChanges = fixes.length > 2;
session.addStep('π§ Elite Repair', 'completed', `${fixes.length} actions performed`);
res.json({ success: true, fixes, shiftMetrics: session.shiftMetrics, auditHash: session.auditHash, hasChanges: session.hasChanges });
} catch (error) {
session.addStep('π§ Elite Repair', 'failed', error.message);
res.json({ success: false, error: error.message, fixes });
}
});
// Commit changes
app.post('/api/surgery/commit', async (req, res) => {
const { sessionId, commitMessage } = req.body;
const session = activeSurgeries.get(sessionId);
if (!session) return res.json({ success: false, error: 'Session not found' });
try {
const { stdout: statusOutput } = await execPS('git status --porcelain', session.surgeryPath);
if (!statusOutput.trim()) {
return res.json({ success: false, noChanges: true, error: 'No changes to commit' });
}
await execPS('git add .', session.surgeryPath);
await execPS(`git commit -m "${commitMessage.replace(/"/g, '\\"')}"`, session.surgeryPath);
await execPS(`git push origin ${session.branchName} -f`, session.surgeryPath);
session.addStep('πΎ Commit', 'completed', `Pushed changes`);
res.json({ success: true });
} catch (error) {
session.addStep('πΎ Commit', 'failed', error.message);
res.json({ success: false, error: error.message });
}
});
// Create PR
app.post('/api/surgery/create-pr', async (req, res) => {
const { sessionId, prTitle, prBody, baseBranch } = req.body;
const session = activeSurgeries.get(sessionId);
if (!session) return res.json({ success: false, error: 'Session not found' });
try {
const blockchainNote = session.auditHash ? `\n\nβοΈ **Blockchain Audit Hash:** \`${session.auditHash}\`` : '';
const fullBody = prBody + blockchainNote;
const { stdout } = await execPS(`gh pr create --title "${prTitle.replace(/"/g, '\\"')}" --body "${fullBody.replace(/"/g, '\\"')}" --base ${baseBranch || 'main'} --head ${session.branchName} 2>&1`, session.surgeryPath);
const prMatch = stdout.match(/\/pull\/(\d+)/);
const prNumber = prMatch ? prMatch[1] : 'unknown';
session.addStep('π PR', 'completed', `PR #${prNumber} created`);
session.complete(true, prNumber, stdout);
if (!session.keepAfterRepair && fs.existsSync(session.surgeryPath)) {
try { fs.rmSync(session.surgeryPath, { recursive: true, force: true }); } catch(e) {}
}
res.json({ success: true, prNumber, prUrl: stdout });
} catch (error) {
session.addStep('π PR', 'failed', error.message);
session.complete(false);
res.json({ success: false, error: error.message });
} finally {
activeSurgeries.delete(sessionId);
}
});
// Legacy autofix (for backward compatibility)
app.post('/api/surgery/autofix', async (req, res) => {
const { sessionId } = req.body;
const session = activeSurgeries.get(sessionId);
if (!session) return res.json({ success: false, error: 'Session not found' });
// Redirect to elite-repair
const result = await fetch(`http://localhost:${PORT}/api/surgery/elite-repair`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sessionId, shiftStrategy: 'adaptive' })
});
const data = await result.json();
res.json(data);
});
// ============================================================
// WebSocket
// ============================================================
io.on('connection', (socket) => {
console.log('π Elite client connected');
socket.emit('connected', { status: 'elite', version: ELITE_VERSION });
});
// ============================================================
// Start Server
// ============================================================
const PORT = process.env.PORT || 3001;
server.listen(PORT, () => {
console.log(`\nββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ`);
console.log(`β π₯ ATOMIC SWARM GODS ELITE v${ELITE_VERSION} - SURGERY ROOM β`);
console.log(`ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ`);
console.log(`\nπ Server: http://localhost:${PORT}`);
console.log(`π Dashboard: http://localhost:${PORT}/dashboard.html`);
console.log(`π Surgery Base: ${SURGERY_BASE}`);
console.log(`βοΈ Blockchain: ${BLOCKCHAIN_DIR} (${blockchainBlocks.length} blocks)`);
console.log(`\n⨠Elite Features: Dynamic Shifting | Blockchain Audit | Self-Healing\n`);
});