@sureshsankaran/ralph-wiggum 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,243 @@
1
+ # Ralph Wiggum Plugin
2
+
3
+ Implementation of the Ralph Wiggum technique for iterative, self-referential AI development loops in OpenCode.
4
+
5
+ ## What is Ralph?
6
+
7
+ Ralph is a development methodology based on continuous AI agent loops. As Geoffrey Huntley describes it: **"Ralph is a Bash loop"** - a simple `while true` that repeatedly feeds an AI agent a prompt file, allowing it to iteratively improve its work until completion.
8
+
9
+ The technique is named after Ralph Wiggum from The Simpsons, embodying the philosophy of persistent iteration despite setbacks.
10
+
11
+ ### Core Concept
12
+
13
+ This plugin implements Ralph using a **session.idle hook** that intercepts session completion:
14
+
15
+ ```bash
16
+ # You run ONCE:
17
+ /ralph-loop "Your task description" --completion-promise "DONE"
18
+
19
+ # Then OpenCode automatically:
20
+ # 1. Works on the task
21
+ # 2. Session becomes idle
22
+ # 3. session.idle hook intercepts
23
+ # 4. Hook feeds the SAME prompt back
24
+ # 5. Repeat until completion
25
+ ```
26
+
27
+ The loop happens **inside your current session** - you don't need external bash loops. The plugin creates a self-referential feedback loop by intercepting session idle events.
28
+
29
+ This creates a **self-referential feedback loop** where:
30
+
31
+ - The prompt never changes between iterations
32
+ - Previous work persists in files
33
+ - Each iteration sees modified files and git history
34
+ - OpenCode autonomously improves by reading its own past work in files
35
+
36
+ ## Installation
37
+
38
+ ### Option 1: NPM Package (Recommended)
39
+
40
+ ```bash
41
+ npm install opencode-ralph-wiggum
42
+ ```
43
+
44
+ The postinstall script automatically copies the command files to `~/.config/opencode/command/`.
45
+
46
+ Then add the plugin to your `opencode.json`:
47
+
48
+ ```json
49
+ {
50
+ "plugin": ["opencode-ralph-wiggum"]
51
+ }
52
+ ```
53
+
54
+ ### Option 2: Manual Installation
55
+
56
+ Copy the files from this plugin to your opencode config:
57
+
58
+ ```bash
59
+ # Copy plugin
60
+ cp plugins/ralph-wiggum/src/index.ts ~/.config/opencode/plugin/ralph-wiggum.ts
61
+
62
+ # Copy commands
63
+ cp plugins/ralph-wiggum/commands/*.md ~/.config/opencode/command/
64
+ ```
65
+
66
+ Then configure in your `opencode.json`:
67
+
68
+ ```json
69
+ {
70
+ "plugin": ["~/.config/opencode/plugin/ralph-wiggum.ts"]
71
+ }
72
+ ```
73
+
74
+ ## Quick Start
75
+
76
+ ```bash
77
+ /ralph-loop "Build a REST API for todos. Requirements: CRUD operations, input validation, tests. Output <promise>COMPLETE</promise> when done." --completion-promise "COMPLETE" --max-iterations 50
78
+ ```
79
+
80
+ OpenCode will:
81
+
82
+ - Implement the API iteratively
83
+ - Run tests and see failures
84
+ - Fix bugs based on test output
85
+ - Iterate until all requirements met
86
+ - Output the completion promise when done
87
+
88
+ ## Commands
89
+
90
+ ### /ralph-loop
91
+
92
+ Start a Ralph loop in your current session.
93
+
94
+ **Usage:**
95
+
96
+ ```bash
97
+ /ralph-loop "<prompt>" --max-iterations <n> --completion-promise "<text>"
98
+ ```
99
+
100
+ **Options:**
101
+
102
+ - `--max-iterations <n>` - Stop after N iterations (default: unlimited)
103
+ - `--completion-promise <text>` - Phrase that signals completion
104
+
105
+ ### /cancel-ralph
106
+
107
+ Cancel the active Ralph loop.
108
+
109
+ **Usage:**
110
+
111
+ ```bash
112
+ /cancel-ralph
113
+ ```
114
+
115
+ ### /help
116
+
117
+ Get detailed help on the Ralph Wiggum technique and commands.
118
+
119
+ **Usage:**
120
+
121
+ ```bash
122
+ /help
123
+ ```
124
+
125
+ ## Prompt Writing Best Practices
126
+
127
+ ### 1. Clear Completion Criteria
128
+
129
+ Bad: "Build a todo API and make it good."
130
+
131
+ Good:
132
+
133
+ ```markdown
134
+ Build a REST API for todos.
135
+
136
+ When complete:
137
+
138
+ - All CRUD endpoints working
139
+ - Input validation in place
140
+ - Tests passing (coverage > 80%)
141
+ - README with API docs
142
+ - Output: <promise>COMPLETE</promise>
143
+ ```
144
+
145
+ ### 2. Incremental Goals
146
+
147
+ Bad: "Create a complete e-commerce platform."
148
+
149
+ Good:
150
+
151
+ ```markdown
152
+ Phase 1: User authentication (JWT, tests)
153
+ Phase 2: Product catalog (list/search, tests)
154
+ Phase 3: Shopping cart (add/remove, tests)
155
+
156
+ Output <promise>COMPLETE</promise> when all phases done.
157
+ ```
158
+
159
+ ### 3. Self-Correction
160
+
161
+ Bad: "Write code for feature X."
162
+
163
+ Good:
164
+
165
+ ```markdown
166
+ Implement feature X following TDD:
167
+
168
+ 1. Write failing tests
169
+ 2. Implement feature
170
+ 3. Run tests
171
+ 4. If any fail, debug and fix
172
+ 5. Refactor if needed
173
+ 6. Repeat until all green
174
+ 7. Output: <promise>COMPLETE</promise>
175
+ ```
176
+
177
+ ### 4. Escape Hatches
178
+
179
+ Always use `--max-iterations` as a safety net to prevent infinite loops on impossible tasks:
180
+
181
+ ```bash
182
+ # Recommended: Always set a reasonable iteration limit
183
+ /ralph-loop "Try to implement feature X" --max-iterations 20
184
+
185
+ # In your prompt, include what to do if stuck:
186
+ # "After 15 iterations, if not complete:
187
+ # - Document what's blocking progress
188
+ # - List what was attempted
189
+ # - Suggest alternative approaches"
190
+ ```
191
+
192
+ **Note**: The `--completion-promise` uses exact string matching, so you cannot use it for multiple completion conditions (like "SUCCESS" vs "BLOCKED"). Always rely on `--max-iterations` as your primary safety mechanism.
193
+
194
+ ## Philosophy
195
+
196
+ Ralph embodies several key principles:
197
+
198
+ ### 1. Iteration > Perfection
199
+
200
+ Don't aim for perfect on first try. Let the loop refine the work.
201
+
202
+ ### 2. Failures Are Data
203
+
204
+ "Deterministically bad" means failures are predictable and informative. Use them to tune prompts.
205
+
206
+ ### 3. Operator Skill Matters
207
+
208
+ Success depends on writing good prompts, not just having a good model.
209
+
210
+ ### 4. Persistence Wins
211
+
212
+ Keep trying until success. The loop handles retry logic automatically.
213
+
214
+ ## When to Use Ralph
215
+
216
+ **Good for:**
217
+
218
+ - Well-defined tasks with clear success criteria
219
+ - Tasks requiring iteration and refinement (e.g., getting tests to pass)
220
+ - Greenfield projects where you can walk away
221
+ - Tasks with automatic verification (tests, linters)
222
+
223
+ **Not good for:**
224
+
225
+ - Tasks requiring human judgment or design decisions
226
+ - One-shot operations
227
+ - Tasks with unclear success criteria
228
+ - Production debugging (use targeted debugging instead)
229
+
230
+ ## Real-World Results
231
+
232
+ - Successfully generated 6 repositories overnight in Y Combinator hackathon testing
233
+ - One $50k contract completed for $297 in API costs
234
+ - Created entire programming language ("cursed") over 3 months using this approach
235
+
236
+ ## Learn More
237
+
238
+ - Original technique: https://ghuntley.com/ralph/
239
+ - Ralph Orchestrator: https://github.com/mikeyobrien/ralph-orchestrator
240
+
241
+ ## For Help
242
+
243
+ Run `/help` in OpenCode for detailed command reference and examples.
@@ -0,0 +1,16 @@
1
+ ---
2
+ description: "Cancel active Ralph Wiggum loop"
3
+ ---
4
+
5
+ # Cancel Ralph
6
+
7
+ To cancel the Ralph loop:
8
+
9
+ 1. Check if `.opencode/ralph-loop.local.md` exists using Bash: `test -f .opencode/ralph-loop.local.md && echo "EXISTS" || echo "NOT_FOUND"`
10
+
11
+ 2. **If NOT_FOUND**: Say "No active Ralph loop found."
12
+
13
+ 3. **If EXISTS**:
14
+ - Read `.opencode/ralph-loop.local.md` to get the current iteration number from the `iteration:` field
15
+ - Remove the file using Bash: `rm .opencode/ralph-loop.local.md`
16
+ - Report: "Cancelled Ralph loop (was at iteration N)" where N is the iteration value
@@ -0,0 +1,81 @@
1
+ ---
2
+ description: "Start Ralph Wiggum loop in current session"
3
+ ---
4
+
5
+ # Ralph Loop Command
6
+
7
+ !`export RALPH_ARGS='$ARGUMENTS' && node -e "
8
+ var args = process.env.RALPH_ARGS || '';
9
+ var fs = require('fs');
10
+ var path = require('path');
11
+
12
+ // Unescape the CLI escaping - remove outer quotes and unescape inner quotes
13
+ args = args.trim();
14
+ if ((args.startsWith('\"') && args.endsWith('\"')) || (args.startsWith(\"'\") && args.endsWith(\"'\"))) {
15
+ args = args.slice(1, -1);
16
+ }
17
+ args = args.replace(/\\\\\"/g, '\"');
18
+
19
+ var maxIterations = 0;
20
+ var completionPromise = 'null';
21
+ var prompt = args;
22
+
23
+ var maxMatch = args.match(/--max-iterations\s+(\d+)/);
24
+ if (maxMatch) {
25
+ maxIterations = parseInt(maxMatch[1], 10);
26
+ prompt = prompt.replace(/--max-iterations\s+\d+/, '');
27
+ }
28
+
29
+ var cpMatch = args.match(/--completion-promise\s+\"([^\"]+)\"/);
30
+ if (cpMatch) {
31
+ completionPromise = cpMatch[1];
32
+ prompt = prompt.replace(/--completion-promise\s+\"[^\"]+\"/, '');
33
+ } else {
34
+ var cpMatch2 = args.match(/--completion-promise\s+(\S+)/);
35
+ if (cpMatch2) {
36
+ completionPromise = cpMatch2[1];
37
+ prompt = prompt.replace(/--completion-promise\s+\S+/, '');
38
+ }
39
+ }
40
+
41
+ prompt = prompt.trim().replace(/^\"|\"$/g, '');
42
+
43
+ if (!prompt) {
44
+ console.log('Error: No prompt provided.');
45
+ console.log('Usage: /ralph-loop \"<prompt>\" [--max-iterations N] [--completion-promise TEXT]');
46
+ process.exit(1);
47
+ }
48
+
49
+ var dir = '.opencode';
50
+ fs.mkdirSync(dir, { recursive: true });
51
+
52
+ var cpYaml = completionPromise === 'null' ? 'null' : '\"' + completionPromise + '\"';
53
+ var lines = [
54
+ '---',
55
+ 'active: true',
56
+ 'iteration: 1',
57
+ 'max_iterations: ' + maxIterations,
58
+ 'completion_promise: ' + cpYaml,
59
+ 'started_at: \"' + new Date().toISOString() + '\"',
60
+ '---',
61
+ '',
62
+ prompt
63
+ ];
64
+
65
+ fs.writeFileSync(path.join(dir, 'ralph-loop.local.md'), lines.join('\n') + '\n');
66
+
67
+ console.log('Ralph loop activated!');
68
+ console.log('Iteration: 1');
69
+ console.log('Max iterations: ' + (maxIterations > 0 ? maxIterations : 'unlimited'));
70
+ console.log('Completion promise: ' + (completionPromise !== 'null' ? completionPromise : 'none'));
71
+ console.log('');
72
+ console.log(prompt);
73
+ "`
74
+
75
+ Please work on the task described above. The Ralph loop is now active.
76
+
77
+ When the session becomes idle, the session.idle hook will feed the SAME PROMPT back to you for the next iteration. You'll see your previous work in files and git history, allowing you to iterate and improve.
78
+
79
+ CRITICAL RULE: If a completion promise is set, you may ONLY output it when the statement is completely and unequivocally TRUE. Do not output false promises to escape the loop, even if you think you're stuck or should exit for other reasons. The loop is designed to continue until genuine completion.
80
+
81
+ To complete the loop, output: `<promise>YOUR_COMPLETION_PROMISE</promise>`
@@ -0,0 +1,15 @@
1
+ import type { Plugin } from "@opencode-ai/plugin";
2
+ /**
3
+ * Ralph Wiggum Plugin - Iterative AI Development
4
+ *
5
+ * This plugin implements the Ralph Wiggum technique: continuously feeding
6
+ * the same prompt to the AI until the task is complete.
7
+ *
8
+ * Usage:
9
+ * 1. Start a loop: /ralph-loop "Your task description" --max-iterations 10 --completion-promise "DONE"
10
+ * 2. Cancel a loop: /cancel-ralph
11
+ *
12
+ * The AI should output <promise>DONE</promise> when the task is complete.
13
+ */
14
+ export declare const RalphWiggumPlugin: Plugin;
15
+ export default RalphWiggumPlugin;
package/dist/index.js ADDED
@@ -0,0 +1,155 @@
1
+ import { existsSync, readFileSync, writeFileSync, unlinkSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ const STATE_FILE = ".opencode/ralph-loop.local.md";
4
+ function parseState(content) {
5
+ const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
6
+ if (!frontmatterMatch)
7
+ return null;
8
+ const [, frontmatter, prompt] = frontmatterMatch;
9
+ const lines = frontmatter.split("\n");
10
+ const state = { prompt: prompt.trim() };
11
+ for (const line of lines) {
12
+ const [key, ...valueParts] = line.split(":");
13
+ if (!key)
14
+ continue;
15
+ const value = valueParts.join(":").trim();
16
+ switch (key.trim()) {
17
+ case "active":
18
+ state.active = value === "true";
19
+ break;
20
+ case "iteration":
21
+ state.iteration = parseInt(value, 10);
22
+ break;
23
+ case "max_iterations":
24
+ state.max_iterations = parseInt(value, 10);
25
+ break;
26
+ case "completion_promise":
27
+ state.completion_promise = value === "null" ? null : value.replace(/^"|"$/g, "");
28
+ break;
29
+ case "started_at":
30
+ state.started_at = value.replace(/^"|"$/g, "");
31
+ break;
32
+ }
33
+ }
34
+ if (state.active === undefined ||
35
+ state.iteration === undefined ||
36
+ state.max_iterations === undefined ||
37
+ !state.prompt) {
38
+ return null;
39
+ }
40
+ return state;
41
+ }
42
+ function extractPromiseText(text) {
43
+ const match = text.match(/<promise>(.*?)<\/promise>/s);
44
+ return match ? match[1].trim().replace(/\s+/g, " ") : null;
45
+ }
46
+ function updateIteration(filePath, newIteration) {
47
+ const content = readFileSync(filePath, "utf-8");
48
+ const updated = content.replace(/^iteration: \d+$/m, `iteration: ${newIteration}`);
49
+ writeFileSync(filePath, updated);
50
+ }
51
+ /**
52
+ * Ralph Wiggum Plugin - Iterative AI Development
53
+ *
54
+ * This plugin implements the Ralph Wiggum technique: continuously feeding
55
+ * the same prompt to the AI until the task is complete.
56
+ *
57
+ * Usage:
58
+ * 1. Start a loop: /ralph-loop "Your task description" --max-iterations 10 --completion-promise "DONE"
59
+ * 2. Cancel a loop: /cancel-ralph
60
+ *
61
+ * The AI should output <promise>DONE</promise> when the task is complete.
62
+ */
63
+ export const RalphWiggumPlugin = async ({ client, directory }) => {
64
+ const stateFilePath = join(directory, STATE_FILE);
65
+ // Track if completion was detected to prevent race conditions
66
+ let completionDetected = false;
67
+ return {
68
+ event: async ({ event }) => {
69
+ // Check message.part.updated events for completion promise
70
+ // This happens BEFORE session goes idle, so we can detect early
71
+ if (event.type === "message.part.updated") {
72
+ const props = event.properties;
73
+ const part = props?.part;
74
+ // Only check text parts with completed status (time.end is set)
75
+ if (part?.type === "text" && part?.text && part?.time?.end && existsSync(stateFilePath)) {
76
+ const content = readFileSync(stateFilePath, "utf-8");
77
+ const state = parseState(content);
78
+ if (state?.completion_promise && !completionDetected) {
79
+ // Skip if this text is part of the user's prompt
80
+ if (part.text.includes(state.prompt.slice(0, 30))) {
81
+ return;
82
+ }
83
+ const promiseText = extractPromiseText(part.text);
84
+ if (promiseText === state.completion_promise) {
85
+ console.log(`Ralph loop: Detected <promise>${state.completion_promise}</promise> - task complete!`);
86
+ completionDetected = true;
87
+ unlinkSync(stateFilePath);
88
+ return;
89
+ }
90
+ }
91
+ }
92
+ return;
93
+ }
94
+ // Handle session idle to continue the loop
95
+ const isIdle = event.type === "session.idle" ||
96
+ (event.type === "session.status" && event.properties?.status?.type === "idle");
97
+ if (!isIdle)
98
+ return;
99
+ // If completion was already detected, don't continue
100
+ if (completionDetected) {
101
+ return;
102
+ }
103
+ const sessionID = event.properties?.sessionID;
104
+ // Check if ralph-loop is active
105
+ if (!existsSync(stateFilePath))
106
+ return;
107
+ const content = readFileSync(stateFilePath, "utf-8");
108
+ const state = parseState(content);
109
+ if (!state || !state.active) {
110
+ return;
111
+ }
112
+ console.log("Ralph loop: session idle, iteration " + state.iteration);
113
+ // Validate numeric fields
114
+ if (isNaN(state.iteration) || isNaN(state.max_iterations)) {
115
+ console.error("Ralph loop: State file corrupted - invalid numeric fields");
116
+ unlinkSync(stateFilePath);
117
+ return;
118
+ }
119
+ // Check if max iterations reached
120
+ if (state.max_iterations > 0 && state.iteration >= state.max_iterations) {
121
+ console.log(`Ralph loop: Max iterations (${state.max_iterations}) reached.`);
122
+ unlinkSync(stateFilePath);
123
+ return;
124
+ }
125
+ // Not complete - continue loop with SAME PROMPT
126
+ const nextIteration = state.iteration + 1;
127
+ updateIteration(stateFilePath, nextIteration);
128
+ // Build system message
129
+ const systemMsg = state.completion_promise
130
+ ? `Ralph iteration ${nextIteration} | To stop: output <promise>${state.completion_promise}</promise> (ONLY when statement is TRUE - do not lie to exit!)`
131
+ : `Ralph iteration ${nextIteration} | No completion promise set - loop runs infinitely`;
132
+ console.log(systemMsg);
133
+ // Send the same prompt back to continue the session
134
+ try {
135
+ if (sessionID) {
136
+ await client.session.promptAsync({
137
+ path: { id: sessionID },
138
+ body: {
139
+ parts: [
140
+ {
141
+ type: "text",
142
+ text: `[${systemMsg}]\n\n${state.prompt}`,
143
+ },
144
+ ],
145
+ },
146
+ });
147
+ }
148
+ }
149
+ catch (err) {
150
+ console.error("Ralph loop: Failed to send prompt", err);
151
+ }
152
+ },
153
+ };
154
+ };
155
+ export default RalphWiggumPlugin;
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@sureshsankaran/ralph-wiggum",
3
+ "version": "0.1.0",
4
+ "description": "Ralph Wiggum iterative AI development plugin for OpenCode - continuously loops the same prompt until task completion",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/index.js",
11
+ "types": "./dist/index.d.ts"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "commands",
17
+ "scripts"
18
+ ],
19
+ "scripts": {
20
+ "build": "tsc",
21
+ "prepublishOnly": "npm run build",
22
+ "postinstall": "node scripts/postinstall.js"
23
+ },
24
+ "keywords": [
25
+ "opencode",
26
+ "plugin",
27
+ "ralph-wiggum",
28
+ "ai",
29
+ "iterative",
30
+ "automation"
31
+ ],
32
+ "author": "",
33
+ "license": "MIT",
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "https://github.com/anomalyco/opencode.git",
37
+ "directory": "plugins/ralph-wiggum"
38
+ },
39
+ "peerDependencies": {
40
+ "@opencode-ai/plugin": ">=1.0.0"
41
+ },
42
+ "devDependencies": {
43
+ "@opencode-ai/plugin": "^1.0.224",
44
+ "@types/node": "^22.0.0",
45
+ "typescript": "^5.0.0"
46
+ }
47
+ }
@@ -0,0 +1,48 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { copyFileSync, mkdirSync, existsSync } from "node:fs"
4
+ import { join, dirname } from "node:path"
5
+ import { homedir } from "node:os"
6
+ import { fileURLToPath } from "node:url"
7
+
8
+ const __dirname = dirname(fileURLToPath(import.meta.url))
9
+ const packageRoot = join(__dirname, "..")
10
+
11
+ const configDir = join(homedir(), ".config", "opencode", "command")
12
+
13
+ // Create command directory if it doesn't exist
14
+ if (!existsSync(configDir)) {
15
+ mkdirSync(configDir, { recursive: true })
16
+ console.log(`Created directory: ${configDir}`)
17
+ }
18
+
19
+ // Copy command files
20
+ const commands = ["ralph-loop.md", "cancel-ralph.md"]
21
+ const commandsDir = join(packageRoot, "commands")
22
+
23
+ for (const cmd of commands) {
24
+ const src = join(commandsDir, cmd)
25
+ const dest = join(configDir, cmd)
26
+
27
+ if (existsSync(src)) {
28
+ copyFileSync(src, dest)
29
+ console.log(`Installed command: ${cmd}`)
30
+ } else {
31
+ console.warn(`Warning: Command file not found: ${src}`)
32
+ }
33
+ }
34
+
35
+ console.log("")
36
+ console.log("Ralph Wiggum commands installed!")
37
+ console.log("")
38
+ console.log("Next step: Add the plugin to your opencode config:")
39
+ console.log("")
40
+ console.log(" In opencode.json:")
41
+ console.log(" {")
42
+ console.log(' "plugin": ["opencode-ralph-wiggum"]')
43
+ console.log(" }")
44
+ console.log("")
45
+ console.log("Usage:")
46
+ console.log(' /ralph-loop "Your task" --max-iterations 10 --completion-promise "DONE"')
47
+ console.log(" /cancel-ralph")
48
+ console.log("")