-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathralph-loop-implementation.js
More file actions
404 lines (329 loc) · 11 KB
/
ralph-loop-implementation.js
File metadata and controls
404 lines (329 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
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
#!/usr/bin/env node
import fs from 'fs';
import path from 'path';
import { execSync } from 'child_process';
import { fileURLToPath } from 'url';
class RalphLoop {
constructor(options = {}) {
this.baseDir = options.baseDir || '.ralph';
this.maxIterations = options.maxIterations || 50;
this.verbose = options.verbose || false;
this.paths = {
task: path.join(this.baseDir, 'task.md'),
criteria: path.join(this.baseDir, 'completion-criteria.md'),
iteration: path.join(this.baseDir, 'iteration.txt'),
feedback: path.join(this.baseDir, 'feedback.txt'),
state: path.join(this.baseDir, 'state.json'),
complete: path.join(this.baseDir, 'work-complete.txt'),
progress: path.join(this.baseDir, 'progress.jsonl'),
history: path.join(this.baseDir, 'history')
};
}
async initialize(task, criteria) {
// Create directory structure
fs.mkdirSync(this.baseDir, { recursive: true });
fs.mkdirSync(this.paths.history, { recursive: true });
// Initialize files
fs.writeFileSync(this.paths.task, task);
fs.writeFileSync(this.paths.criteria, criteria);
fs.writeFileSync(this.paths.iteration, '0');
fs.writeFileSync(this.paths.feedback, '');
// Initial state
const state = {
startTime: Date.now(),
task: task.substring(0, 100),
status: 'initialized'
};
fs.writeFileSync(this.paths.state, JSON.stringify(state, null, 2));
this.log('Ralph Loop initialized');
}
async runWorkerIteration() {
const iteration = this.getCurrentIteration();
const task = fs.readFileSync(this.paths.task, 'utf8');
const feedback = this.getFeedback();
this.log(`Worker iteration ${iteration} starting...`);
// Step 1: Analyze current state (fresh context)
const analysis = await this.analyzeCurrentState();
// Step 2: Plan based on task and feedback
const plan = await this.createPlan(task, feedback, analysis);
// Step 3: Execute changes
const changes = await this.executeChanges(plan);
// Step 4: Validate changes
const validation = await this.validateChanges();
// Step 5: Save iteration artifacts
await this.saveIterationArtifacts(iteration, {
analysis,
plan,
changes,
validation
});
// Step 6: Commit changes
this.commitChanges(iteration, plan.summary);
return {
iteration,
changes: changes.length,
validation
};
}
async runReviewerIteration() {
const iteration = this.getCurrentIteration();
const task = fs.readFileSync(this.paths.task, 'utf8');
const criteria = fs.readFileSync(this.paths.criteria, 'utf8');
this.log(`Reviewer iteration ${iteration} evaluating...`);
// Fresh evaluation of current state
const evaluation = await this.evaluateAgainstCriteria(criteria);
if (evaluation.complete) {
fs.writeFileSync(this.paths.complete, 'true');
this.log('Task completed successfully!');
return { complete: true };
}
// Generate feedback for next iteration
const feedback = this.generateFeedback(evaluation);
fs.writeFileSync(this.paths.feedback, feedback);
// Increment iteration
this.incrementIteration();
return {
complete: false,
feedback: feedback.substring(0, 200)
};
}
async analyzeCurrentState() {
// Simulate fresh analysis of codebase
const files = this.scanRelevantFiles();
const tests = this.getTestStatus();
const lastCommit = this.getLastCommit();
return {
filesCount: files.length,
testsPass: tests.passing,
testsFail: tests.failing,
lastChange: lastCommit
};
}
async createPlan(_task, feedback, _analysis) {
// In real implementation, this would use an LLM
// Here we simulate planning based on feedback
const needsWork = feedback.includes('failing') ||
feedback.includes('incomplete') ||
feedback === '';
return {
summary: `Iteration work based on: ${feedback.substring(0, 50)}`,
steps: needsWork ? ['Fix issues', 'Add features', 'Update tests'] : ['Polish'],
priority: needsWork ? 'high' : 'low'
};
}
async executeChanges(plan) {
// Simulate making code changes
const changes = [];
for (const step of plan.steps) {
changes.push({
step,
timestamp: Date.now(),
result: 'simulated'
});
}
return changes;
}
async validateChanges() {
// Run tests and checks
try {
const testResult = this.runTests();
const lintResult = this.runLint();
return {
testsPass: testResult.passing > 0,
lintClean: lintResult.clean,
errors: [...testResult.errors, ...lintResult.errors]
};
} catch (error) {
return {
testsPass: false,
lintClean: false,
errors: [error.message]
};
}
}
async evaluateAgainstCriteria(criteria) {
// Parse criteria and check each
const criteriaLines = criteria.split('\n').filter(l => l.trim().startsWith('-'));
const results = {};
for (const criterion of criteriaLines) {
const key = criterion.replace('-', '').trim().substring(0, 20);
// Simulate checking (in reality would analyze code)
results[key] = Math.random() > 0.3; // 70% chance of meeting each criterion
}
const complete = Object.values(results).every(v => v === true);
return {
complete,
criteria: results,
unmet: Object.entries(results)
.filter(([_, v]) => !v)
.map(([k]) => k)
};
}
generateFeedback(evaluation) {
if (evaluation.unmet.length === 0) {
return 'All criteria met';
}
return `Still need to address:\n${evaluation.unmet.map(c => `- ${c}`).join('\n')}`;
}
async saveIterationArtifacts(iteration, artifacts) {
const iterDir = path.join(this.paths.history, `iteration-${String(iteration).padStart(3, '0')}`);
fs.mkdirSync(iterDir, { recursive: true });
fs.writeFileSync(
path.join(iterDir, 'artifacts.json'),
JSON.stringify(artifacts, null, 2)
);
// Log progress
const progress = {
iteration,
timestamp: Date.now(),
changes: artifacts.changes.length,
validation: artifacts.validation.testsPass,
errors: artifacts.validation.errors.length
};
fs.appendFileSync(this.paths.progress, JSON.stringify(progress) + '\n');
}
commitChanges(iteration, summary) {
try {
execSync('git add -A', { stdio: 'pipe' });
execSync(`git commit -m "Ralph iteration ${iteration}: ${summary}" --allow-empty`, { stdio: 'pipe' });
this.log(`Committed iteration ${iteration}`);
} catch (error) {
this.log(`Commit failed: ${error.message}`);
}
}
scanRelevantFiles() {
// Simulate file scanning
return ['index.js', 'auth.js', 'test.js'];
}
getTestStatus() {
try {
execSync('npm test', { stdio: 'pipe' });
return { passing: 5, failing: 0 };
} catch {
return { passing: 3, failing: 2 };
}
}
runTests() {
const status = this.getTestStatus();
return {
passing: status.passing,
failing: status.failing,
errors: status.failing > 0 ? ['Some tests failed'] : []
};
}
runLint() {
try {
execSync('npm run lint', { stdio: 'pipe' });
return { clean: true, errors: [] };
} catch {
return { clean: false, errors: ['Lint issues found'] };
}
}
getLastCommit() {
try {
return execSync('git log -1 --oneline', { encoding: 'utf8' }).trim();
} catch {
return 'No commits yet';
}
}
getCurrentIteration() {
try {
return parseInt(fs.readFileSync(this.paths.iteration, 'utf8'));
} catch {
return 0;
}
}
incrementIteration() {
const current = this.getCurrentIteration();
fs.writeFileSync(this.paths.iteration, String(current + 1));
}
getFeedback() {
try {
return fs.readFileSync(this.paths.feedback, 'utf8');
} catch {
return '';
}
}
isComplete() {
return fs.existsSync(this.paths.complete);
}
log(message) {
if (this.verbose) {
console.log(`[Ralph] ${message}`);
}
}
async run() {
while (!this.isComplete()) {
const iteration = this.getCurrentIteration();
if (iteration >= this.maxIterations) {
console.log('Max iterations reached!');
break;
}
// Worker phase
await this.runWorkerIteration();
// Reviewer phase
const review = await this.runReviewerIteration();
if (review.complete) {
console.log('Task completed!');
break;
}
// Brief pause between iterations
await new Promise(resolve => setTimeout(resolve, 1000));
}
// Final summary
this.printSummary();
}
printSummary() {
const iterations = this.getCurrentIteration();
const progress = fs.readFileSync(this.paths.progress, 'utf8')
.split('\n')
.filter(Boolean)
.map(line => JSON.parse(line));
console.log('\n=== Ralph Loop Summary ===');
console.log(`Total iterations: ${iterations}`);
console.log(`Total changes: ${progress.reduce((sum, p) => sum + p.changes, 0)}`);
console.log(`Final status: ${this.isComplete() ? 'COMPLETE' : 'INCOMPLETE'}`);
}
}
// CLI Interface
async function main() {
const args = process.argv.slice(2);
const command = args[0];
if (command === 'init') {
const task = args[1] || 'Implement a feature';
const criteria = args[2] || '- Tests pass\n- Code works\n- No errors';
const loop = new RalphLoop({ verbose: true });
await loop.initialize(task, criteria);
console.log('Ralph Loop initialized. Run with: node ralph-loop-implementation.js run');
} else if (command === 'run') {
const loop = new RalphLoop({ verbose: true });
if (!fs.existsSync(loop.paths.task)) {
console.error('No task found. Initialize first with: node ralph-loop-implementation.js init');
process.exit(1);
}
await loop.run();
} else if (command === 'status') {
const loop = new RalphLoop();
const iteration = loop.getCurrentIteration();
const complete = loop.isComplete();
const feedback = loop.getFeedback();
console.log(`Iteration: ${iteration}`);
console.log(`Status: ${complete ? 'COMPLETE' : 'IN PROGRESS'}`);
console.log(`Last feedback: ${feedback.substring(0, 100)}`);
} else {
console.log(`
Ralph Loop Implementation
Usage:
node ralph-loop-implementation.js init [task] [criteria] - Initialize a new loop
node ralph-loop-implementation.js run - Run the loop
node ralph-loop-implementation.js status - Check current status
Example:
node ralph-loop-implementation.js init "Add login feature" "- Tests pass\\n- JWT works\\n- Error handling"
node ralph-loop-implementation.js run
`);
}
}
if (import.meta.url === `file://${process.argv[1]}`) {
main().catch(console.error);
}
export { RalphLoop };