-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
294 lines (251 loc) Β· 11 KB
/
server.js
File metadata and controls
294 lines (251 loc) Β· 11 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
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';
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')));
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');
[SURGERY_BASE, REPAIRS_DIR, SUCCESS_DIR, FAILED_DIR].forEach(dir => {
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
});
let surgeryRecords = [];
let activeSurgeries = new Map();
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));
}
class SurgerySession {
constructor(id, repoUrl, branchName) {
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';
}
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;
saveRecords();
io.emit('repair-complete', { sessionId: this.id, status: this.status, prNumber, prUrl });
}
}
// Fixed execPS - uses absolute paths
async function execPS(command, cwd) {
if (!cwd || !fs.existsSync(cwd)) {
console.error(`Invalid cwd: ${cwd}`);
return { stdout: '', stderr: 'Invalid working directory' };
}
// Create temp file in the surgery base
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 */ }
}
}
// Detect language
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';
}
}
// API Endpoints
app.get('/health', (req, res) => res.json({ status: 'UP', version: '1.6.0' }));
app.get('/api/surgery/records', (req, res) => res.json(surgeryRecords));
app.post('/api/surgery/start', async (req, res) => {
const { repoUrl, branchName, keepAfterRepair } = req.body;
const sessionId = Date.now().toString();
const session = new SurgerySession(sessionId, repoUrl, branchName);
session.keepAfterRepair = keepAfterRepair;
surgeryRecords.unshift({
id: sessionId,
repoName: session.repoName,
branchName,
status: 'running',
startTime: session.startTime
});
activeSurgeries.set(sessionId, session);
saveRecords();
res.json({ success: true, sessionId });
});
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 {
// Create directory first
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 });
}
});
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 });
}
});
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' });
const fixes = [];
try {
// 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: 'echo "Build configured"',
test: 'echo "Tests configured"'
},
devDependencies: {}
};
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\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');
// Try to build
await execPS('npm run build', session.surgeryPath).catch(() => {});
fixes.push('β
Build attempted');
}
session.hasChanges = true;
session.addStep('π§ Auto-Fix', 'completed', `${fixes.length} fixes applied`);
res.json({ success: true, fixes, language, hasChanges: session.hasChanges });
} catch (error) {
session.addStep('π§ Auto-Fix', 'failed', error.message);
res.json({ success: false, error: error.message, fixes });
}
});
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 {
// Check for changes
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 });
}
});
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 { stdout } = await execPS(`gh pr create --title "${prTitle.replace(/"/g, '\\"')}" --body "${prBody.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);
// Cleanup if requested
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);
}
});
io.on('connection', (socket) => {
console.log('π Client connected');
socket.emit('connected', { status: 'ok' });
});
const PORT = 3001;
server.listen(PORT, () => {
console.log(`π₯ Atomic Gods Surgery Room API running on http://localhost:${PORT}`);
console.log(`π Surgery Base: ${SURGERY_BASE}`);
});