Ralph 2.0 — Phased Autonomous Build System
Orchestrator-driven build system that treats context windows as managed resources. Each phase gets a fresh worker with a scoped brief. Quality gates run between every phase. State checkpoints to disk so sessions can resume cleanly.
When to Use
- Building a multi-phase feature from a PRD
- Any task too large for a single context window
- When you need verified, incremental progress with no accumulated context degradation
Trigger Phrases
/ralph2/ralph2 [prd-path]- "run ralph 2"
- "build this with ralph"
Input Detection
Parse user input for:
- PRD path: explicit path, or auto-detect by globbing
docs/**/*PRD*,docs/**/*prd*,**/*plan*PRD* - Resume: if
.ralph/state.yamlexists in the project root, offer to resume
If no PRD found, ask the user.
Overview
Orchestrator (this skill, main context)
│
├── Stage 0: Codebase scan → .ralph/codebase-map.md
├── Stage 1: Decompose PRD → phase briefs
│
├── Stage 2: Execute phases (loop)
│ │
│ ├── Dispatch worker agent (brief → code)
│ ├── Deterministic gate (typecheck, lint, build)
│ ├── Audit agents FIND (2 agents, read-only, parallel)
│ ├── Fix agent FIXES (1 agent, all severities)
│ ├── Verify agent CONFIRMS (1 agent, read-only)
│ ├── Commit
│ └── Checkpoint to .ralph/state.yaml
│
└── Stage 3: Final /ralph-review (full 6-agent audit)
Stage 0: Ground Truth
Before generating any briefs, build a grounded understanding of the codebase. This prevents briefs from referencing files that don't exist or patterns that have changed.
0A: Read Project Context
Read these files (skip if missing):
CLAUDE.md— project constraints, dev commandsAGENTS.md— patterns, conventions, tech stackpackage.json— dependencies, scripts, workspace structure- The PRD file — full implementation plan
Extract:
- Quality gate commands: typecheck, lint, test, build (detect from package.json scripts + CLAUDE.md)
- Project conventions: import patterns, naming, file organization
- Known constraints: isolation rules, API contracts, deployment concerns
0B: Codebase Scanner
Run targeted searches to build a map of what actually exists:
For each file referenced in the PRD:
1. Verify it exists (glob)
2. Read it — note key exports, functions, patterns
3. Flag any discrepancies with what the PRD assumes
Write the result to .ralph/codebase-map.md:
# Codebase Map
Generated: {date}
PRD: {path}
## Files Referenced in PRD
| File | Exists | Key Exports / Notes |
|------|--------|---------------------|
| src/db/schema.ts | YES | reportOrders, reportDomains, reportOutputs, tierEnum |
| src/lib/stripe.ts | YES | TIER_PRICES, createCheckout() |
| ... | ... | ... |
## Discrepancies
- PRD says X but code shows Y
## Quality Gate Commands
- Typecheck: `pnpm typecheck`
- Lint: {command or "none"}
- Test: {command or "none"}
- Build: {command or "none"}
0C: Initialize State
Create .ralph/state.yaml:
project: {name from PRD or directory}
prd: {path}
started: {ISO timestamp}
codebase_map: .ralph/codebase-map.md
quality_gates:
typecheck: "pnpm typecheck"
lint: null
test: null
build: null
phases: [] # populated in Stage 1
final_review: pending
Stage 1: Decompose PRD into Phase Briefs
Read the PRD. For each phase/section, generate a self-contained brief.
Brief Generation Rules
- One brief per phase — each brief maps to one worker agent invocation
- Self-contained — the worker never reads the PRD. Everything it needs is in the brief.
- Grounded — file paths come from codebase-map.md (verified to exist), not assumed
- Bounded — clear "done when" criteria the gate can check deterministically
- Context-aware — if Phase 2 depends on Phase 1, the Phase 2 brief states what Phase 1 produced
Brief Template
Write each brief to .ralph/briefs/{N}-{slug}.md:
# Phase {N} Brief: {Title}
## Context
You are implementing Phase {N} of {project name}.
{Previous phase summary: what was built, what now exists.}
## Objective
{2-3 sentences: what this phase accomplishes and why.}
## Files to Read First
{Ordered list. Include line ranges for large files. Only files relevant to this phase.}
1. `{path}` — {why: "tier config pattern to copy", "current schema to extend", etc.}
## Files to Modify
{Exact list with specific instructions per file.}
### `{file path}`
- {specific change 1}
- {specific change 2}
## Files to Create
{If any. Include the pattern to follow.}
### `{new file path}`
- Follow pattern from `{existing file path}`
- {specific requirements}
## Constraints
{Project-specific rules this worker must follow.}
- {constraint 1}
- {constraint 2}
## Patterns to Follow
{Only the patterns relevant to this phase, extracted from AGENTS.md/CLAUDE.md.}
## Done When
{Deterministic criteria. These feed directly into the gate.}
- [ ] `pnpm typecheck` passes
- [ ] {specific file} exports {specific function/type}
- [ ] {specific behavior is wired}
Update State
After generating all briefs, update .ralph/state.yaml:
phases:
- id: "1-schema"
brief: .ralph/briefs/1-schema.md
status: pending
complexity: simple # simple | medium | complex
gate: typecheck_only # typecheck_only | find_fix_verify
- id: "2-checkout"
brief: .ralph/briefs/2-checkout.md
status: pending
complexity: medium
gate: find_fix_verify
depends_on: ["1-schema"]
Complexity scoring:
- Simple (schema-only, config-only, single file): typecheck gate only
- Medium (2-3 files, clear patterns): find→fix→verify gate
- Complex (4+ files, cross-cutting, business logic): find→fix→verify gate
Present Plan to User
Before executing, show the user:
Ralph 2.0 — Execution Plan
===========================
PRD: {path}
Phases: {count}
Estimated workers: {count} (phases) + {count} (audit/fix/verify agents)
Phase 1: {title} [{complexity}] — gate: {gate type}
Phase 2: {title} [{complexity}] — gate: {gate type}
...
Proceed? (y/n)
Wait for user confirmation before executing.
Stage 2: Execute Phases
For each phase in order:
Step 2.1: Dispatch Worker
Launch a general-purpose agent with the phase brief as its prompt.
Agent tool:
subagent_type: "general-purpose"
description: "Phase {N}: {title}"
prompt: {contents of .ralph/briefs/{N}-{slug}.md}
The worker:
- Reads referenced files
- Makes the changes described in the brief
- Does NOT run typecheck or tests — that's the gate's job
- Returns a summary of what it changed
After the worker completes, note which files were changed.
Step 2.2: Deterministic Gate
Run quality checks BEFORE spending tokens on AI audit:
{typecheck command}
If typecheck fails:
- Read the error output
- Fix the errors directly (orchestrator fixes these — they're deterministic)
- Re-run typecheck
- Max 3 attempts, then escalate to user
Also run lint and test if available. These are hard gates — must pass.
Phase-specific commands: After standard gates pass, run any phase-specific verification commands from the PRD. Common examples:
| Phase type | Command to run | Why |
|---|---|---|
| Schema/migration | {db:generate command} (e.g. pnpm db:generate) |
Schema changes WITHOUT a migration = deploy blocker |
| New CSS classes referenced | Grep the stylesheet to verify all referenced classes exist | Missing classes = silent rendering failures |
| New env vars added | Verify they appear in both env validation AND .env.example |
Missing vars = runtime crash in deploy |
| New Trigger.dev jobs | Verify task ID strings match between trigger file and worker dispatch | Mismatched IDs = jobs never fire |
The PRD often lists these in its "Verify" sections — execute them, don't skip them. This is the #1 source of deploy blockers when omitted.
If phase complexity is simple and deterministic gates pass → skip to Step 2.6 (commit).
Step 2.3: Audit — FIND Only
Launch 2 Explore agents in parallel (run_in_background: true). These agents only read and report. They do NOT write code.
Agent 1: Integration Auditor
{project context from Stage 0}
## Phase {N} Brief (what the worker was told to build)
{paste the brief}
## Files Changed
{list of files the worker modified/created}
## Your Job: Integration Audit (READ ONLY — do NOT fix anything)
For each file changed, verify:
1. Follows project conventions (from CLAUDE.md / AGENTS.md)
2. Respects isolation rules (e.g., Worker cannot import from src/lib/)
3. API contract compliance (if applicable)
4. Existing functionality unbroken — check that unchanged code paths still work
5. New code wires into existing systems correctly (registrations, exports, imports)
## OUTPUT FORMAT (MANDATORY)
INTEGRATION AUDIT — Phase {N}
==============================
Files Reviewed: {count}
Findings:
- [H-001]: {title} | {file:line} | {description}
- [M-001]: {title} | {file:line} | {description}
- [L-001]: {title} | {file:line} | {description}
Or: "No findings — phase looks clean."
Agent 2: Gotcha Hunter
{project context from Stage 0}
## Phase {N} Brief (what the worker was told to build)
{paste the brief}
## Files Changed
{list of files the worker modified/created}
## Your Job: Gotcha Hunt (READ ONLY — do NOT fix anything)
Search all changed files for:
1. Hardcoded values (URLs, prices, limits, magic numbers) that should use constants/helpers
2. Missing `await` on async function calls
3. `console.log` statements that should be removed or converted to proper logging
4. TODO/FIXME/HACK comments left behind
5. Commented-out code that should be deleted
6. Copy-paste errors (duplicated logic that diverged)
7. Type assertions (`as any`, `as unknown`) that bypass safety
### Cross-File Reference Check
8. CSS/HTML: for every CSS class name used in templates/HTML, verify the class is defined in the stylesheet
9. Imports: verify imported functions/types actually exist in the target module
10. String IDs: verify task IDs, queue names, template slugs match their definitions
## OUTPUT FORMAT (MANDATORY)
GOTCHA HUNT — Phase {N}
========================
Files Reviewed: {count}
Findings:
- [H-001]: {title} | {file:line} | {description}
- [M-001]: {title} | {file:line} | {description}
- [L-001]: {title} | {file:line} | {description}
Or: "No findings — phase looks clean."
Parallel Product Builds — Extra Audit Scope
When the PRD builds a second product type alongside an existing one (e.g., "sale readiness" alongside "activation"), both audit agents must also verify:
- Email templates: Does the notification use a product-appropriate template or template model? Reusing activation email metrics (e.g.,
keep_count/drop_count) for a different product type will confuse customers. - Display names: Every user-visible string derived from enum values (tier names, strategy labels, status messages) must have a display name mapping — raw enum values like
portfolio_deepmust NOT appear in PDFs, emails, or UI. - PDF sections: If the new product has different per-item fields than the existing product, verify all fields are surfaced consistently (e.g., don't show
reasonin 3 of 4 section types but omit it from the 4th). - Shared pipelines: If the new product reuses an existing pipeline (e.g., data collection), verify that product-specific parameters (tiers, limits, feature flags) are mapped correctly — not silently cast with
as. - DB migrations: Verify that schema changes have corresponding migration files generated.
Step 2.4: Fix — Dedicated Fix Agent
After both audit agents report back, consolidate all findings.
If zero findings from both agents → skip to Step 2.6 (commit).
Otherwise, launch a single general-purpose agent with the consolidated findings:
Agent tool:
subagent_type: "general-purpose"
description: "Fix Phase {N} findings"
prompt: (below)
## Project Context
{CLAUDE.md constraints, key conventions, isolation rules}
## Findings to Fix
{Consolidated list from both auditors, numbered globally}
1. [H-001] {title} — {file:line} — {description}
2. [M-001] {title} — {file:line} — {description}
3. [L-001] {title} — {file:line} — {description}
...
## Instructions
Fix ALL findings above (HIGH, MEDIUM, and LOW).
Rules:
- Read each flagged file before modifying it
- Fix only what's described — do not refactor surrounding code
- Do not add tests, comments, or documentation beyond the fix
- Do not run typecheck or verify — another agent handles that
- Report what you changed for each finding
Step 2.5: Verify Fixes
After the fix agent completes:
1. Deterministic re-check:
{typecheck command}
Must pass. If it fails, fix directly (orchestrator) — max 2 attempts.
2. Verification agent — launch an Explore agent (read-only):
## Files Modified by Fix Agent
{list of files changed}
## Original Findings
{the findings list}
## Your Job: Verify Fixes (READ ONLY)
For each finding, confirm:
1. The fix actually resolves the issue (not just papered over)
2. The fix didn't introduce new issues
3. The fix follows project conventions
## OUTPUT FORMAT (MANDATORY)
FIX VERIFICATION — Phase {N}
=============================
Per Finding:
- [H-001]: {RESOLVED / INCOMPLETE / REGRESSION}
{evidence}
- [M-001]: {RESOLVED / INCOMPLETE / REGRESSION}
{evidence}
New Issues Introduced: {list or "none"}
Overall: {PASS / NEEDS ANOTHER CYCLE}
If verification reports INCOMPLETE or REGRESSION:
- Launch one more fix cycle (Steps 2.4 + 2.5) with only the unresolved findings
- Max 2 total cycles
- If still failing after 2 cycles → commit what works, log the unresolved findings, ask user
Step 2.6: Commit & Checkpoint
Commit all phase work + fixes:
Phase {N}: {brief title}
{one-line summary of what was built}
{one-line per audit finding that was fixed, if any}
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Update .ralph/state.yaml:
- id: "{N}-{slug}"
status: complete
commit: {sha}
findings_found: {count}
findings_resolved: {count}
findings_unresolved: {count}
fix_cycles: {count}
Update .ralph/context.md (append):
## Phase {N}: {title}
- Commit: {sha}
- Changed: {file list}
- Decisions: {any deviations from the brief and why}
- Gotchas discovered: {anything the next phase should know}
- Unresolved: {any findings that couldn't be fixed}
Step 2.7: Context Window Check
Before starting the next phase, assess your own context usage:
- If context is getting heavy (you've run 3+ phases with full gates): consider running
/last-ritesto create a handoff, then the next session resumes from.ralph/state.yaml. - If context is fine: proceed to next phase.
The orchestrator should prioritize staying sharp over powering through. A fresh context window reading .ralph/state.yaml + .ralph/context.md + the next brief is better than a degraded context trying to push through.
Stage 3: Final Review
After all phases complete, run /ralph-review as the final quality gate.
This is the full 6-agent audit with cross-examination from the ralph-review skill. It audits the entire body of work across all phases.
If /ralph-review finds issues, its remediation cycle handles them.
After final review passes, update state:
final_review: complete
completed: {ISO timestamp}
Resume Protocol
When invoked and .ralph/state.yaml exists:
- Read
.ralph/state.yaml— determine current progress - Read
.ralph/context.md— get cross-phase knowledge - Read
.ralph/codebase-map.md— get grounded file state - Find the next pending phase
- Read its brief
- Continue from Step 2.1
Show the user:
Ralph 2.0 — Resuming
======================
Project: {name}
Progress: {N}/{total} phases complete
Last completed: Phase {N} ({title}) — {commit sha}
Next: Phase {N+1} ({title})
Continue? (y/n)
If the codebase has changed since the last checkpoint (files modified outside Ralph), re-run Stage 0B (codebase scanner) to update the map before proceeding.
.ralph/ Directory Structure
.ralph/
state.yaml # progress tracker — source of truth
context.md # cross-phase knowledge (structured, append-only)
codebase-map.md # grounded file inventory
briefs/
1-schema.md # self-contained worker brief
2-checkout.md
3-synthesis.md
...
audits/
2-checkout.md # consolidated audit findings (preserved for reference)
3-synthesis.md
...
Important: .ralph/ should be gitignored. It's orchestration state, not project code. Add to .gitignore if not already present.
Context File Structure
.ralph/context.md uses a fixed structure — never freeform:
# Ralph 2.0 Context
Project: {name}
PRD: {path}
## Decisions
{Decisions made during execution and why. One bullet per decision.}
## Known Issues
{Issues discovered but not yet resolved.}
## Deviations from PRD
{Anything that diverged from the original plan and why.}
## New Patterns Introduced
{Any new patterns or conventions established during this build.}
## Per-Phase Notes
### Phase 1: {title}
- Commit: {sha}
- Changed: {files}
- Gotchas: {anything relevant for later phases}
### Phase 2: {title}
...
Failure Escalation Rules
| Condition | Action |
|---|---|
| Typecheck fails 3x after worker | Escalate to user with error output |
| Audit finds 10+ HIGH findings | Mark brief as flawed, ask user before fixing |
| Fix agent cycles > 2 | Commit what works, log unresolved, ask user |
| Verify agent finds regressions after 2 fix cycles | Stop, present full state to user |
| Worker produces no changes | Brief may be wrong — re-read target files, regenerate brief |
| Codebase changed between sessions | Re-run codebase scanner, re-validate remaining briefs |
Key Principles
- Context windows are managed resources — checkpoint and restart rather than degrade
- Deterministic before probabilistic — run typecheck before AI auditors
- Separation of concerns — workers build, auditors find, fixers fix, verifiers verify. No agent wears two hats.
- Briefs are grounded — file paths verified against actual codebase, not assumed from PRD
- Build on verified ground — never start Phase N+1 until Phase N passes its gate
- State lives on disk —
.ralph/state.yamlis the source of truth, survives session boundaries - The brief generator is the system — bad briefs → bad workers. Invest in brief quality.
- Fail loudly, not silently — escalate to user rather than loop or paper over issues