Rewrite Ralph loop recipes: split into simple vs ideal versions

Align all 4 language recipes (Node.js, Python, .NET, Go) with the
Ralph Playbook architecture:

- Simple version: minimal outer loop with fresh session per iteration
- Ideal version: planning/building modes, backpressure, git integration
- Fresh context isolation instead of in-session context accumulation
- Disk-based shared state via IMPLEMENTATION_PLAN.md
- Example prompt templates (PROMPT_plan.md, PROMPT_build.md, AGENTS.md)
- Updated cookbook README descriptions
This commit is contained in:
Anthony Shaw
2026-02-11 11:28:41 -08:00
parent ab82accc08
commit 952372c1ec
9 changed files with 1052 additions and 1122 deletions

View File

@@ -1,128 +1,79 @@
import { readFile } from "fs/promises";
import { execSync } from "child_process";
import { CopilotClient } from "@github/copilot-sdk";
/**
* RALPH-loop implementation: Iterative self-referential AI loops.
* The same prompt is sent repeatedly, with AI reading its own previous output.
* Loop continues until completion promise is detected in the response.
* Ralph loop: autonomous AI task loop with fresh context per iteration.
*
* Two modes:
* - "plan": reads PROMPT_plan.md, generates/updates IMPLEMENTATION_PLAN.md
* - "build": reads PROMPT_build.md, implements tasks, runs tests, commits
*
* Each iteration creates a fresh session so the agent always operates in
* the "smart zone" of its context window. State is shared between
* iterations via files on disk (IMPLEMENTATION_PLAN.md, AGENTS.md, specs/*).
*
* Usage:
* npx tsx ralph-loop.ts # build mode, 50 iterations
* npx tsx ralph-loop.ts plan # planning mode
* npx tsx ralph-loop.ts 20 # build mode, 20 iterations
* npx tsx ralph-loop.ts plan 5 # planning mode, 5 iterations
*/
class RalphLoop {
private client: CopilotClient;
private iteration: number = 0;
private readonly maxIterations: number;
private readonly completionPromise: string;
public lastResponse: string | null = null;
constructor(maxIterations: number = 10, completionPromise: string = "COMPLETE") {
this.client = new CopilotClient();
this.maxIterations = maxIterations;
this.completionPromise = completionPromise;
}
type Mode = "plan" | "build";
/**
* Run the RALPH-loop until completion promise is detected or max iterations reached.
*/
async run(initialPrompt: string): Promise<string> {
let session: Awaited<ReturnType<CopilotClient["createSession"]>> | null = null;
async function ralphLoop(mode: Mode, maxIterations: number) {
const promptFile = mode === "plan" ? "PROMPT_plan.md" : "PROMPT_build.md";
await this.client.start();
try {
session = await this.client.createSession({
model: "gpt-5.1-codex-mini"
const client = new CopilotClient();
await client.start();
const branch = execSync("git branch --show-current", { encoding: "utf-8" }).trim();
console.log("━".repeat(40));
console.log(`Mode: ${mode}`);
console.log(`Prompt: ${promptFile}`);
console.log(`Branch: ${branch}`);
console.log(`Max: ${maxIterations} iterations`);
console.log("━".repeat(40));
try {
const prompt = await readFile(promptFile, "utf-8");
for (let i = 1; i <= maxIterations; i++) {
console.log(`\n=== Iteration ${i}/${maxIterations} ===`);
// Fresh session — each task gets full context budget
const session = await client.createSession({
model: "claude-sonnet-4.5",
});
try {
while (this.iteration < this.maxIterations) {
this.iteration++;
console.log(`\n=== Iteration ${this.iteration}/${this.maxIterations} ===`);
// Build the prompt for this iteration
const currentPrompt = this.buildIterationPrompt(initialPrompt);
console.log(`Sending prompt (length: ${currentPrompt.length})...`);
const response = await session.sendAndWait({ prompt: currentPrompt }, 300_000);
this.lastResponse = response?.data.content || "";
// Display response summary
const summary = this.lastResponse.length > 200
? this.lastResponse.substring(0, 200) + "..."
: this.lastResponse;
console.log(`Response: ${summary}`);
// Check for completion promise
if (this.lastResponse.includes(this.completionPromise)) {
console.log(`\n✓ Success! Completion promise detected: '${this.completionPromise}'`);
return this.lastResponse;
}
console.log(`Iteration ${this.iteration} complete. Checking for next iteration...`);
}
// Max iterations reached without completion
throw new Error(
`Maximum iterations (${this.maxIterations}) reached without detecting completion promise: '${this.completionPromise}'`
);
} catch (error) {
console.error(`\nError during RALPH-loop: ${error instanceof Error ? error.message : String(error)}`);
throw error;
await session.sendAndWait({ prompt }, 600_000);
} finally {
if (session) {
await session.destroy();
}
await session.destroy();
}
} finally {
await this.client.stop();
}
}
/**
* Build the prompt for the current iteration, including previous output as context.
*/
private buildIterationPrompt(initialPrompt: string): string {
if (this.iteration === 1) {
// First iteration: just the initial prompt
return initialPrompt;
// Push changes after each iteration
try {
execSync(`git push origin ${branch}`, { stdio: "inherit" });
} catch {
execSync(`git push -u origin ${branch}`, { stdio: "inherit" });
}
console.log(`\nIteration ${i} complete.`);
}
// Subsequent iterations: include previous output as context
return `${initialPrompt}
=== CONTEXT FROM PREVIOUS ITERATION ===
${this.lastResponse}
=== END CONTEXT ===
Continue working on this task. Review the previous attempt and improve upon it.`;
console.log(`\nReached max iterations: ${maxIterations}`);
} finally {
await client.stop();
}
}
// Example usage demonstrating RALPH-loop
async function main() {
const prompt = `You are iteratively building a small library. Follow these phases IN ORDER.
Do NOT skip ahead — only do the current phase, then stop and wait for the next iteration.
// Parse CLI args
const args = process.argv.slice(2);
const mode: Mode = args.includes("plan") ? "plan" : "build";
const maxArg = args.find((a) => /^\d+$/.test(a));
const maxIterations = maxArg ? parseInt(maxArg) : 50;
Phase 1: Design a DataValidator class that validates records against a schema.
- Schema defines field names, types (str, int, float, bool), and whether required.
- Return a list of validation errors per record.
- Show the class code only. Do NOT output COMPLETE.
Phase 2: Write at least 4 unit tests covering: missing required field, wrong type,
valid record, and empty input. Show test code only. Do NOT output COMPLETE.
Phase 3: Review the code from phases 1 and 2. Fix any bugs, add docstrings, and add
an extra edge-case test. Show the final consolidated code with all fixes.
When this phase is fully done, output the exact text: COMPLETE`;
const loop = new RalphLoop(5, "COMPLETE");
try {
const result = await loop.run(prompt);
console.log("\n=== FINAL RESULT ===");
console.log(result);
} catch (error) {
console.error(`\nTask did not complete: ${error instanceof Error ? error.message : String(error)}`);
if (loop.lastResponse) {
console.log(`\nLast attempt:\n${loop.lastResponse}`);
}
}
}
main().catch(console.error);
ralphLoop(mode, maxIterations).catch(console.error);