forked from Th0rgal/open-ralph-wiggum
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathralph.ts
More file actions
executable file
·1202 lines (1064 loc) · 38.1 KB
/
ralph.ts
File metadata and controls
executable file
·1202 lines (1064 loc) · 38.1 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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bun
/**
* Ralph Wiggum Loop for OpenCode
*
* Implementation of the Ralph Wiggum technique - continuous self-referential
* AI loops for iterative development. Based on ghuntley.com/ralph/
*/
import { $ } from "bun";
import { existsSync, readFileSync, writeFileSync, mkdirSync, statSync } from "fs";
import { join } from "path";
const VERSION = "1.0.9";
// Context file path for mid-loop injection
const stateDir = join(process.cwd(), ".opencode");
const statePath = join(stateDir, "ralph-loop.state.json");
const contextPath = join(stateDir, "ralph-context.md");
const historyPath = join(stateDir, "ralph-history.json");
// Parse arguments
const args = process.argv.slice(2);
if (args.includes("--help") || args.includes("-h")) {
console.log(`
Ralph Wiggum Loop - Iterative AI development with OpenCode
Usage:
ralph "<prompt>" [options]
ralph --prompt-file <path> [options]
Arguments:
prompt Task description for the AI to work on
Options:
--min-iterations N Minimum iterations before completion allowed (default: 1)
--max-iterations N Maximum iterations before stopping (default: unlimited)
--completion-promise TEXT Phrase that signals completion (default: COMPLETE)
--model MODEL Model to use (e.g., anthropic/claude-sonnet)
--prompt-file, --file, -f Read prompt content from a file
--no-stream Buffer OpenCode output and print at the end
--verbose-tools Print every tool line (disable compact tool summary)
--no-plugins Disable non-auth OpenCode plugins for this run
--no-commit Don't auto-commit after each iteration
--allow-all Auto-approve all tool permissions (for non-interactive use)
--version, -v Show version
--help, -h Show this help
Commands:
--status Show current Ralph loop status and history
--add-context TEXT Add context for the next iteration (or edit .opencode/ralph-context.md)
--clear-context Clear any pending context
Examples:
ralph "Build a REST API for todos"
ralph "Fix the auth bug" --max-iterations 10
ralph "Add tests" --completion-promise "ALL TESTS PASS" --model openai/gpt-5.1
ralph --prompt-file ./prompt.md --max-iterations 5
ralph --status # Check loop status
ralph --add-context "Focus on the auth module first" # Add hint for next iteration
How it works:
1. Sends your prompt to OpenCode
2. AI works on the task
3. Checks output for completion promise
4. If not complete, repeats with same prompt
5. AI sees its previous work in files
6. Continues until promise detected or max iterations
To stop manually: Ctrl+C
Learn more: https://ghuntley.com/ralph/
`);
process.exit(0);
}
if (args.includes("--version") || args.includes("-v")) {
console.log(`ralph ${VERSION}`);
process.exit(0);
}
// History tracking interface
interface IterationHistory {
iteration: number;
startedAt: string;
endedAt: string;
durationMs: number;
toolsUsed: Record<string, number>;
filesModified: string[];
exitCode: number;
completionDetected: boolean;
errors: string[];
}
interface RalphHistory {
iterations: IterationHistory[];
totalDurationMs: number;
struggleIndicators: {
repeatedErrors: Record<string, number>;
noProgressIterations: number;
shortIterations: number;
};
}
// Load history
function loadHistory(): RalphHistory {
if (!existsSync(historyPath)) {
return {
iterations: [],
totalDurationMs: 0,
struggleIndicators: { repeatedErrors: {}, noProgressIterations: 0, shortIterations: 0 }
};
}
try {
return JSON.parse(readFileSync(historyPath, "utf-8"));
} catch {
return {
iterations: [],
totalDurationMs: 0,
struggleIndicators: { repeatedErrors: {}, noProgressIterations: 0, shortIterations: 0 }
};
}
}
function saveHistory(history: RalphHistory): void {
if (!existsSync(stateDir)) {
mkdirSync(stateDir, { recursive: true });
}
writeFileSync(historyPath, JSON.stringify(history, null, 2));
}
function clearHistory(): void {
if (existsSync(historyPath)) {
try {
require("fs").unlinkSync(historyPath);
} catch {}
}
}
// Status command
if (args.includes("--status")) {
const state = loadState();
const history = loadHistory();
const context = existsSync(contextPath) ? readFileSync(contextPath, "utf-8").trim() : null;
console.log(`
╔══════════════════════════════════════════════════════════════════╗
║ Ralph Wiggum Status ║
╚══════════════════════════════════════════════════════════════════╝
`);
if (state?.active) {
const elapsed = Date.now() - new Date(state.startedAt).getTime();
const elapsedStr = formatDurationLong(elapsed);
console.log(`🔄 ACTIVE LOOP`);
console.log(` Iteration: ${state.iteration}${state.maxIterations > 0 ? ` / ${state.maxIterations}` : " (unlimited)"}`);
console.log(` Started: ${state.startedAt}`);
console.log(` Elapsed: ${elapsedStr}`);
console.log(` Promise: ${state.completionPromise}`);
if (state.model) console.log(` Model: ${state.model}`);
console.log(` Prompt: ${state.prompt.substring(0, 60)}${state.prompt.length > 60 ? "..." : ""}`);
} else {
console.log(`⏹️ No active loop`);
}
if (context) {
console.log(`\n📝 PENDING CONTEXT (will be injected next iteration):`);
console.log(` ${context.split("\n").join("\n ")}`);
}
if (history.iterations.length > 0) {
console.log(`\n📊 HISTORY (${history.iterations.length} iterations)`);
console.log(` Total time: ${formatDurationLong(history.totalDurationMs)}`);
// Show last 5 iterations
const recent = history.iterations.slice(-5);
console.log(`\n Recent iterations:`);
for (const iter of recent) {
const tools = Object.entries(iter.toolsUsed)
.sort((a, b) => b[1] - a[1])
.slice(0, 3)
.map(([k, v]) => `${k}:${v}`)
.join(" ");
const status = iter.completionDetected ? "✅" : iter.exitCode !== 0 ? "❌" : "🔄";
console.log(` ${status} #${iter.iteration}: ${formatDurationLong(iter.durationMs)} | ${tools || "no tools"}`);
}
// Struggle detection
const struggle = history.struggleIndicators;
const hasRepeatedErrors = Object.values(struggle.repeatedErrors).some(count => count >= 2);
if (struggle.noProgressIterations >= 3 || struggle.shortIterations >= 3 || hasRepeatedErrors) {
console.log(`\n⚠️ STRUGGLE INDICATORS:`);
if (struggle.noProgressIterations >= 3) {
console.log(` - No file changes in ${struggle.noProgressIterations} iterations`);
}
if (struggle.shortIterations >= 3) {
console.log(` - ${struggle.shortIterations} very short iterations (< 30s)`);
}
const topErrors = Object.entries(struggle.repeatedErrors)
.filter(([_, count]) => count >= 2)
.sort((a, b) => b[1] - a[1])
.slice(0, 3);
for (const [error, count] of topErrors) {
console.log(` - Same error ${count}x: "${error.substring(0, 50)}..."`);
}
console.log(`\n 💡 Consider using: ralph --add-context "your hint here"`);
}
}
console.log("");
process.exit(0);
}
// Add context command
const addContextIdx = args.indexOf("--add-context");
if (addContextIdx !== -1) {
const contextText = args[addContextIdx + 1];
if (!contextText) {
console.error("Error: --add-context requires a text argument");
console.error("Usage: ralph --add-context \"Your context or hint here\"");
process.exit(1);
}
if (!existsSync(stateDir)) {
mkdirSync(stateDir, { recursive: true });
}
// Append to existing context or create new
const timestamp = new Date().toISOString();
const newEntry = `\n## Context added at ${timestamp}\n${contextText}\n`;
if (existsSync(contextPath)) {
const existing = readFileSync(contextPath, "utf-8");
writeFileSync(contextPath, existing + newEntry);
} else {
writeFileSync(contextPath, `# Ralph Loop Context\n${newEntry}`);
}
console.log(`✅ Context added for next iteration`);
console.log(` File: ${contextPath}`);
const state = loadState();
if (state?.active) {
console.log(` Will be picked up in iteration ${state.iteration + 1}`);
} else {
console.log(` Will be used when loop starts`);
}
process.exit(0);
}
// Clear context command
if (args.includes("--clear-context")) {
if (existsSync(contextPath)) {
require("fs").unlinkSync(contextPath);
console.log(`✅ Context cleared`);
} else {
console.log(`ℹ️ No pending context to clear`);
}
process.exit(0);
}
function formatDurationLong(ms: number): string {
const totalSeconds = Math.max(0, Math.floor(ms / 1000));
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
if (hours > 0) {
return `${hours}h ${minutes}m ${seconds}s`;
}
if (minutes > 0) {
return `${minutes}m ${seconds}s`;
}
return `${seconds}s`;
}
// Parse options
let prompt = "";
let minIterations = 1; // default: 1 iteration minimum
let maxIterations = 0; // 0 = unlimited
let completionPromise = "COMPLETE";
let model = "";
let autoCommit = true;
let disablePlugins = false;
let allowAllPermissions = false;
let promptFile = "";
let streamOutput = true;
let verboseTools = false;
let promptSource = "";
const promptParts: string[] = [];
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === "--min-iterations") {
const val = args[++i];
if (!val || isNaN(parseInt(val))) {
console.error("Error: --min-iterations requires a number");
process.exit(1);
}
minIterations = parseInt(val);
} else if (arg === "--max-iterations") {
const val = args[++i];
if (!val || isNaN(parseInt(val))) {
console.error("Error: --max-iterations requires a number");
process.exit(1);
}
maxIterations = parseInt(val);
} else if (arg === "--completion-promise") {
const val = args[++i];
if (!val) {
console.error("Error: --completion-promise requires a value");
process.exit(1);
}
completionPromise = val;
} else if (arg === "--model") {
const val = args[++i];
if (!val) {
console.error("Error: --model requires a value");
process.exit(1);
}
model = val;
} else if (arg === "--prompt-file" || arg === "--file" || arg === "-f") {
const val = args[++i];
if (!val) {
console.error("Error: --prompt-file requires a file path");
process.exit(1);
}
promptFile = val;
} else if (arg === "--no-stream") {
streamOutput = false;
} else if (arg === "--stream") {
streamOutput = true;
} else if (arg === "--verbose-tools") {
verboseTools = true;
} else if (arg === "--no-commit") {
autoCommit = false;
} else if (arg === "--no-plugins") {
disablePlugins = true;
} else if (arg === "--allow-all") {
allowAllPermissions = true;
} else if (arg.startsWith("-")) {
console.error(`Error: Unknown option: ${arg}`);
console.error("Run 'ralph --help' for available options");
process.exit(1);
} else {
promptParts.push(arg);
}
}
function readPromptFile(path: string): string {
if (!existsSync(path)) {
console.error(`Error: Prompt file not found: ${path}`);
process.exit(1);
}
try {
const stat = statSync(path);
if (!stat.isFile()) {
console.error(`Error: Prompt path is not a file: ${path}`);
process.exit(1);
}
} catch {
console.error(`Error: Unable to stat prompt file: ${path}`);
process.exit(1);
}
try {
const content = readFileSync(path, "utf-8");
if (!content.trim()) {
console.error(`Error: Prompt file is empty: ${path}`);
process.exit(1);
}
return content;
} catch {
console.error(`Error: Unable to read prompt file: ${path}`);
process.exit(1);
}
}
if (promptFile) {
promptSource = promptFile;
prompt = readPromptFile(promptFile);
} else if (promptParts.length === 1 && existsSync(promptParts[0])) {
promptSource = promptParts[0];
prompt = readPromptFile(promptParts[0]);
} else {
prompt = promptParts.join(" ");
}
if (!prompt) {
console.error("Error: No prompt provided");
console.error("Usage: ralph \"Your task description\" [options]");
console.error("Run 'ralph --help' for more information");
process.exit(1);
}
// Validate min/max iterations
if (maxIterations > 0 && minIterations > maxIterations) {
console.error(`Error: --min-iterations (${minIterations}) cannot be greater than --max-iterations (${maxIterations})`);
process.exit(1);
}
interface RalphState {
active: boolean;
iteration: number;
minIterations: number;
maxIterations: number;
completionPromise: string;
prompt: string;
startedAt: string;
model: string;
}
// Create or update state
function saveState(state: RalphState): void {
if (!existsSync(stateDir)) {
mkdirSync(stateDir, { recursive: true });
}
writeFileSync(statePath, JSON.stringify(state, null, 2));
}
function loadState(): RalphState | null {
if (!existsSync(statePath)) {
return null;
}
try {
return JSON.parse(readFileSync(statePath, "utf-8"));
} catch {
return null;
}
}
function clearState(): void {
if (existsSync(statePath)) {
try {
require("fs").unlinkSync(statePath);
} catch {}
}
}
function loadPluginsFromConfig(configPath: string): string[] {
if (!existsSync(configPath)) {
return [];
}
try {
const raw = readFileSync(configPath, "utf-8");
// Basic JSONC support: strip // and /* */ comments.
const withoutBlock = raw.replace(/\/\*[\s\S]*?\*\//g, "");
const withoutLine = withoutBlock.replace(/^\s*\/\/.*$/gm, "");
const parsed = JSON.parse(withoutLine);
const plugins = parsed?.plugin;
return Array.isArray(plugins) ? plugins.filter(p => typeof p === "string") : [];
} catch {
return [];
}
}
function ensureRalphConfig(options: { filterPlugins?: boolean; allowAllPermissions?: boolean }): string {
if (!existsSync(stateDir)) {
mkdirSync(stateDir, { recursive: true });
}
const configPath = join(stateDir, "ralph-opencode.config.json");
const userConfigPath = join(process.env.XDG_CONFIG_HOME ?? join(process.env.HOME ?? "", ".config"), "opencode", "opencode.json");
const projectConfigPath = join(process.cwd(), ".opencode", "opencode.json");
const config: Record<string, unknown> = {
$schema: "https://opencode.ai/config.json",
};
// Filter plugins if requested (only keep auth plugins)
if (options.filterPlugins) {
const plugins = [
...loadPluginsFromConfig(userConfigPath),
...loadPluginsFromConfig(projectConfigPath),
];
config.plugin = Array.from(new Set(plugins)).filter(p => /auth/i.test(p));
}
// Auto-allow all permissions for non-interactive use
if (options.allowAllPermissions) {
config.permission = {
read: "allow",
edit: "allow",
glob: "allow",
grep: "allow",
list: "allow",
bash: "allow",
task: "allow",
webfetch: "allow",
websearch: "allow",
codesearch: "allow",
todowrite: "allow",
todoread: "allow",
question: "allow",
lsp: "allow",
external_directory: "allow",
};
}
writeFileSync(configPath, JSON.stringify(config, null, 2));
return configPath;
}
// Build the full prompt with iteration context
function loadContext(): string | null {
if (!existsSync(contextPath)) {
return null;
}
try {
const content = readFileSync(contextPath, "utf-8").trim();
return content || null;
} catch {
return null;
}
}
function clearContext(): void {
if (existsSync(contextPath)) {
try {
require("fs").unlinkSync(contextPath);
} catch {}
}
}
function buildPrompt(state: RalphState): string {
const context = loadContext();
const contextSection = context
? `
## Additional Context (added by user mid-loop)
${context}
---
`
: "";
return `
# Ralph Wiggum Loop - Iteration ${state.iteration}
You are in an iterative development loop. Work on the task below until you can genuinely complete it.
${contextSection}
## Your Task
${state.prompt}
## Instructions
1. Read the current state of files to understand what's been done
2. **Update your todo list** - Use the TodoWrite tool to track progress and plan remaining work
3. Make progress on the task
4. Run tests/verification if applicable
5. When the task is GENUINELY COMPLETE, output:
<promise>${state.completionPromise}</promise>
## Critical Rules
- ONLY output <promise>${state.completionPromise}</promise> when the task is truly done
- Do NOT lie or output false promises to exit the loop
- If stuck, try a different approach
- Check your work before claiming completion
- The loop will continue until you succeed
- **IMPORTANT**: Update your todo list at the start of each iteration to show progress
## Current Iteration: ${state.iteration}${state.maxIterations > 0 ? ` / ${state.maxIterations}` : " (unlimited)"} (min: ${state.minIterations ?? 1})
Now, work on the task. Good luck!
`.trim();
}
// Check if output contains the completion promise
function checkCompletion(output: string, promise: string): boolean {
const promisePattern = new RegExp(`<promise>\\s*${escapeRegex(promise)}\\s*</promise>`, "i");
return promisePattern.test(output);
}
function escapeRegex(str: string): string {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function detectPlaceholderPluginError(output: string): boolean {
return output.includes("ralph-wiggum is not yet ready for use. This is a placeholder package.");
}
function stripAnsi(input: string): string {
return input.replace(/\x1B\[[0-9;]*m/g, "");
}
function formatDuration(ms: number): string {
const totalSeconds = Math.max(0, Math.floor(ms / 1000));
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
if (hours > 0) {
return `${hours}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
}
return `${minutes}:${String(seconds).padStart(2, "0")}`;
}
function formatToolSummary(toolCounts: Map<string, number>, maxItems = 6): string {
if (!toolCounts.size) return "";
const entries = Array.from(toolCounts.entries()).sort((a, b) => b[1] - a[1]);
const shown = entries.slice(0, maxItems);
const remaining = entries.length - shown.length;
const parts = shown.map(([name, count]) => `${name} ${count}`);
if (remaining > 0) {
parts.push(`+${remaining} more`);
}
return parts.join(" • ");
}
function collectToolSummaryFromText(text: string): Map<string, number> {
const counts = new Map<string, number>();
const lines = text.split(/\r?\n/);
for (const line of lines) {
const match = stripAnsi(line).match(/^\|\s{2}([A-Za-z0-9_-]+)/);
if (match) {
const tool = match[1];
counts.set(tool, (counts.get(tool) ?? 0) + 1);
}
}
return counts;
}
function printIterationSummary(params: {
iteration: number;
elapsedMs: number;
toolCounts: Map<string, number>;
exitCode: number;
completionDetected: boolean;
}): void {
const toolSummary = formatToolSummary(params.toolCounts);
console.log("\nIteration Summary");
console.log("────────────────────────────────────────────────────────────────────");
console.log(`Iteration: ${params.iteration}`);
console.log(`Elapsed: ${formatDuration(params.elapsedMs)}`);
if (toolSummary) {
console.log(`Tools: ${toolSummary}`);
} else {
console.log("Tools: none");
}
console.log(`Exit code: ${params.exitCode}`);
console.log(`Completion promise: ${params.completionDetected ? "detected" : "not detected"}`);
}
async function streamProcessOutput(
proc: ReturnType<typeof Bun.spawn>,
options: {
compactTools: boolean;
toolSummaryIntervalMs: number;
heartbeatIntervalMs: number;
iterationStart: number;
},
): Promise<{ stdoutText: string; stderrText: string; toolCounts: Map<string, number> }> {
const toolCounts = new Map<string, number>();
let stdoutText = "";
let stderrText = "";
let lastPrintedAt = Date.now();
let lastActivityAt = Date.now();
let lastToolSummaryAt = 0;
const compactTools = options.compactTools;
const maybePrintToolSummary = (force = false) => {
if (!compactTools || toolCounts.size === 0) return;
const now = Date.now();
if (!force && now - lastToolSummaryAt < options.toolSummaryIntervalMs) {
return;
}
const summary = formatToolSummary(toolCounts);
if (summary) {
console.log(`| Tools ${summary}`);
lastPrintedAt = Date.now();
lastToolSummaryAt = Date.now();
}
};
const handleLine = (line: string, isError: boolean) => {
lastActivityAt = Date.now();
const match = stripAnsi(line).match(/^\|\s{2}([A-Za-z0-9_-]+)/);
if (compactTools && match) {
const tool = match[1];
toolCounts.set(tool, (toolCounts.get(tool) ?? 0) + 1);
maybePrintToolSummary();
return;
}
if (line.length === 0) {
console.log("");
lastPrintedAt = Date.now();
return;
}
if (isError) {
console.error(line);
} else {
console.log(line);
}
lastPrintedAt = Date.now();
};
const streamText = async (
stream: ReadableStream<Uint8Array> | null,
onText: (chunk: string) => void,
isError: boolean,
) => {
if (!stream) return;
const reader = stream.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
const text = decoder.decode(value, { stream: true });
if (text.length > 0) {
onText(text);
buffer += text;
const lines = buffer.split(/\r?\n/);
buffer = lines.pop() ?? "";
for (const line of lines) {
handleLine(line, isError);
}
}
}
const flushed = decoder.decode();
if (flushed.length > 0) {
onText(flushed);
buffer += flushed;
}
if (buffer.length > 0) {
handleLine(buffer, isError);
}
};
const heartbeatTimer = setInterval(() => {
const now = Date.now();
if (now - lastPrintedAt >= options.heartbeatIntervalMs) {
const elapsed = formatDuration(now - options.iterationStart);
const sinceActivity = formatDuration(now - lastActivityAt);
console.log(`⏳ working... elapsed ${elapsed} · last activity ${sinceActivity} ago`);
lastPrintedAt = now;
}
}, options.heartbeatIntervalMs);
try {
await Promise.all([
streamText(
proc.stdout,
chunk => {
stdoutText += chunk;
},
false,
),
streamText(
proc.stderr,
chunk => {
stderrText += chunk;
},
true,
),
]);
} finally {
clearInterval(heartbeatTimer);
}
if (compactTools) {
maybePrintToolSummary(true);
}
return { stdoutText, stderrText, toolCounts };
}
// Main loop
// Helper to detect per-iteration file changes using content hashes
// Works correctly with --no-commit by comparing file content hashes
interface FileSnapshot {
files: Map<string, string>; // filename -> hash/mtime
}
async function captureFileSnapshot(): Promise<FileSnapshot> {
const files = new Map<string, string>();
try {
// Get list of all tracked and modified files
const status = await $`git status --porcelain`.text();
const trackedFiles = await $`git ls-files`.text();
// Combine modified and tracked files
const allFiles = new Set<string>();
for (const line of status.split("\n")) {
if (line.trim()) {
allFiles.add(line.substring(3).trim());
}
}
for (const file of trackedFiles.split("\n")) {
if (file.trim()) {
allFiles.add(file.trim());
}
}
// Get hash for each file (using git hash-object for content comparison)
for (const file of allFiles) {
try {
const hash = await $`git hash-object ${file} 2>/dev/null || stat -f '%m' ${file} 2>/dev/null || echo ''`.text();
files.set(file, hash.trim());
} catch {
// File may not exist, skip
}
}
} catch {
// Git not available or error
}
return { files };
}
function getModifiedFilesSinceSnapshot(before: FileSnapshot, after: FileSnapshot): string[] {
const changedFiles: string[] = [];
// Check for new or modified files
for (const [file, hash] of after.files) {
const prevHash = before.files.get(file);
if (prevHash !== hash) {
changedFiles.push(file);
}
}
// Check for deleted files
for (const [file] of before.files) {
if (!after.files.has(file)) {
changedFiles.push(file);
}
}
return changedFiles;
}
// Helper to extract error patterns from output
function extractErrors(output: string): string[] {
const errors: string[] = [];
const lines = output.split("\n");
for (const line of lines) {
const lower = line.toLowerCase();
// Match common error patterns
if (
lower.includes("error:") ||
lower.includes("failed:") ||
lower.includes("exception:") ||
lower.includes("typeerror") ||
lower.includes("syntaxerror") ||
lower.includes("referenceerror") ||
(lower.includes("test") && lower.includes("fail"))
) {
const cleaned = line.trim().substring(0, 200);
if (cleaned && !errors.includes(cleaned)) {
errors.push(cleaned);
}
}
}
return errors.slice(0, 10); // Cap at 10 errors per iteration
}
async function runRalphLoop(): Promise<void> {
// Check if a loop is already running
const existingState = loadState();
if (existingState?.active) {
console.error(`Error: A Ralph loop is already active (iteration ${existingState.iteration})`);
console.error(`Started at: ${existingState.startedAt}`);
console.error(`To cancel it, press Ctrl+C in its terminal or delete ${statePath}`);
process.exit(1);
}
console.log(`
╔══════════════════════════════════════════════════════════════════╗
║ Ralph Wiggum Loop ║
║ Iterative AI Development with OpenCode ║
╚══════════════════════════════════════════════════════════════════╝
`);
// Initialize state
const state: RalphState = {
active: true,
iteration: 1,
minIterations,
maxIterations,
completionPromise,
prompt,
startedAt: new Date().toISOString(),
model,
};
saveState(state);
// Initialize history tracking
const history: RalphHistory = {
iterations: [],
totalDurationMs: 0,
struggleIndicators: { repeatedErrors: {}, noProgressIterations: 0, shortIterations: 0 }
};
saveHistory(history);
const promptPreview = prompt.replace(/\s+/g, " ").substring(0, 80) + (prompt.length > 80 ? "..." : "");
if (promptSource) {
console.log(`Task: ${promptSource}`);
console.log(`Preview: ${promptPreview}`);
} else {
console.log(`Task: ${promptPreview}`);
}
console.log(`Completion promise: ${completionPromise}`);
console.log(`Min iterations: ${minIterations}`);
console.log(`Max iterations: ${maxIterations > 0 ? maxIterations : "unlimited"}`);
if (model) console.log(`Model: ${model}`);
if (disablePlugins) console.log("OpenCode plugins: non-auth plugins disabled");
if (allowAllPermissions) console.log("Permissions: auto-approve all tools");
console.log("");
console.log("Starting loop... (Ctrl+C to stop)");
console.log("═".repeat(68));
// Track current subprocess for cleanup on SIGINT
let currentProc: ReturnType<typeof Bun.spawn> | null = null;
// Set up signal handler for graceful shutdown
let stopping = false;
process.on("SIGINT", () => {
if (stopping) {
console.log("\nForce stopping...");
process.exit(1);
}
stopping = true;
console.log("\nGracefully stopping Ralph loop...");
// Kill the subprocess if it's running
if (currentProc) {
try {
currentProc.kill();
} catch {
// Process may have already exited
}
}
clearState();
console.log("Loop cancelled.");
process.exit(0);
});
// Main loop
while (true) {
// Check max iterations
if (maxIterations > 0 && state.iteration > maxIterations) {
console.log(`\n╔══════════════════════════════════════════════════════════════════╗`);
console.log(`║ Max iterations (${maxIterations}) reached. Loop stopped.`);
console.log(`║ Total time: ${formatDurationLong(history.totalDurationMs)}`);
console.log(`╚══════════════════════════════════════════════════════════════════╝`);
clearState();
// Keep history for analysis via --status
break;
}
const iterInfo = maxIterations > 0 ? ` / ${maxIterations}` : "";
const minInfo = minIterations > 1 && state.iteration < minIterations ? ` (min: ${minIterations})` : "";
console.log(`\n🔄 Iteration ${state.iteration}${iterInfo}${minInfo}`);
console.log("─".repeat(68));
// Capture context at start of iteration (to only clear what was consumed)
const contextAtStart = loadContext();
// Capture git state before iteration to detect per-iteration changes
const snapshotBefore = await captureFileSnapshot();
// Build the prompt
const fullPrompt = buildPrompt(state);
const iterationStart = Date.now();
try {
// Build command arguments
const cmdArgs = ["run"];
if (model) {
cmdArgs.push("-m", model);
}
cmdArgs.push(fullPrompt);
const env = { ...process.env };
if (disablePlugins || allowAllPermissions) {
env.OPENCODE_CONFIG = ensureRalphConfig({
filterPlugins: disablePlugins,
allowAllPermissions: allowAllPermissions,
});
}
// Run opencode using spawn for better argument handling
// stdin is inherited so users can respond to permission prompts if needed
currentProc = Bun.spawn(["opencode", ...cmdArgs], {
env,
stdin: "inherit",
stdout: "pipe",
stderr: "pipe",
});
const proc = currentProc;
const exitCodePromise = proc.exited;
let result = "";
let stderr = "";
let toolCounts = new Map<string, number>();
if (streamOutput) {