Self-referential loop until task completion with configurable verification reviewer
复制下面这句话,粘贴给 Claude Code、Codex、Cursor 等 AI 编程工具,它会读取安装说明并在你确认后完成安装。
请阅读 https://ai.atlankj.com/install/asset/gh-ralph-4ecfc0a6a640 ,按照其中的说明把「ralph」安装到你(当前 AI 工具)中。执行前先告诉我将运行的命令和写入的位置,等我确认。
查看 AI 将读取的安装说明正在读取 GitHub 原文…
内容来自 GitHub 原始文件,由原作者维护。在 GitHub 查看
[RALPH - ITERATION {{ITERATION}}/{{MAX}}]
Your previous attempt did not output the completion promise. Continue working on the task.
Ralph is a PRD-driven persistence loop that keeps working on a task until ALL user stories in prd.json have passes: true and are reviewer-verified. It combines session persistence, automatic retry on failure, structured story tracking, and mandatory verification before completion.<Use_When>
<Do_Not_Use_When>
autopilot insteadplan skill instead/goal and only wants that native goal loop monitored -- adopt the existing /goal explicitly or use artifact-only Ultragoal notes instead of starting Ralph as a competing persistence loop
</Do_Not_Use_When><Why_This_Exists> Complex tasks often fail silently: partial implementations get declared "done", tests get skipped, edge cases get forgotten. Ralph prevents this by:
<PRD_Mode>
By default, ralph operates in PRD mode. A scaffold prd.json is auto-generated when ralph starts if none exists. Active transient PRD state is session-scoped at .omc/state/sessions/{sessionId}/prd.json when a session ID is available; legacy project-level prd.json / .omc/prd.json files are read as startup migration inputs.
Startup gate: Ralph always initializes and validates prd.json at startup. Legacy --no-prd text is sanitized from the prompt for backward compatibility, but it no longer bypasses PRD creation or validation.
Deslop opt-out: If {{PROMPT}} contains --no-deslop, skip the mandatory post-review deslop pass entirely. Use this only when the cleanup pass is intentionally out of scope for the run.
Reviewer selection: Pass --critic=architect, --critic=critic, or --critic=codex in the Ralph prompt to choose the completion reviewer for that run. architect remains the default.
Stale-state detection & reconciliation (#3669): If a PRD is left unfinished by an abnormal/non-Step 8 exit (crash, force-kill, cancel before /oh-my-claudecode:cancel, session end), Ralph surfaces an explicit [STALE PRD WARNING] at startup/resume, in the continuation context, and at session end — with unfinished counts, last-touched age, and stale-pointer signals (PRD branchName merged/gone). Completion is NEVER inferred from PR/branch/merge status alone; git state is a warning signal only. A story is auto-reconciled to passes: true ONLY when the PRD carries configured observable evidence and every check passes:
{
"reconciliation": {
"staleAfterMs": 7200000,
"observableChecks": {
"US-001": [
{ "type": "fileContains", "path": "src/landed.ts", "pattern": "LANDED_SYMBOL" },
{ "type": "gitGrep", "ref": "origin/dev", "pattern": "LANDED_SYMBOL" }
]
}
}
}
Check types: fileExists / fileContains (working tree) and gitGrep (content at a ref — this is "verified by content on trunk", never PR status). Stories without configured checks are never auto-marked. Reconciled stories keep architectVerified: false and still require Step 7 reviewer verification before Step 8; every decision is appended to the prd-reconciliation.jsonl audit log and summarized in the story notes.
</PRD_Mode>
<PRD_Criterion_Amendments> Acceptance criteria are the PRD's completion authority: Step 4 verifies EACH active criterion and Step 7 reviews against them. A criterion can stop governing ONLY through the evidence-preserving amendment path — never by silent deletion or by "satisfying" a criterion measurement has refuted.
When implementation proves a criterion empirically false (e.g. a count in the dispatching brief is wrong), amend it:
criterionAmendments ledger. The original criterion text is retained verbatim (never rewritten or deleted) alongside:
kind: "replaced" or "superseded"original: the verbatim refuted criterion (must still be active when the amendment is recorded)replacement: the corrected criterion (only for replaced)reason: why the original no longer governsevidence: the bounded measurement that refuted it (e.g. "enumerated 12 setters, not 16: ...")authority: who made the amendment (use the ralph session id)timestamp: ISO 8601 timestampRules:
amendCriterion(dir, storyId, { original, replacement, reason, evidence, authority }) and supersedeCriterion(dir, storyId, { original, reason, evidence, authority }).<Execution_Policy>
run_in_background: true for long operations (installs, builds, test suites)model parameter explicitly when delegating to agentsdocs/shared/agent-tiers.md before first delegation to select correct agent tiers/goal is mentioned, treat it as a native session-loop handoff/evidence source only and use the deterministic conflict policies refuse, adopt_existing, and artifact_only rather than non-deterministic warning handling. Ralph remains the OMC loop authority for this run; do not claim /goal independently ran tests or read files, and do not treat evaluator success as a substitute for Ralph reviewer verification.
</Execution_Policy>Pick next story: Read the active PRD file and select the highest-priority story with passes: false. This is your current focus.
Implement the current story:
run_in_background: trueVerify the current story's acceptance criteria:
a. For EACH active acceptance criterion in the story, verify it is met with fresh evidence
b. Run relevant checks (test, build, lint, typecheck) and read the output
c. If implementation proves a criterion empirically FALSE (the measurement refutes it), do NOT mark the story complete and do NOT silently delete or weaken the criterion. Instead amend it through the evidence-preserving path described in <PRD_Criterion_Amendments>: replace or supersede it in the active criteria and append the original (verbatim) with kind, reason, evidence, authority, and timestamp to the story's criterionAmendments ledger. Then continue verifying the remaining ACTIVE criteria
d. If any active criterion is NOT met and NOT amended, continue working -- do NOT mark the story as complete
Mark story complete:
a. When ALL active acceptance criteria are verified, create a revision-bound completion claim: set passes: true and set completionCriteriaRevision to the story's current governingCriteriaRevision. Do not set architectVerified; reviewer approval binds that separately.
b. Record progress in progress.txt: what was implemented, files changed, learnings for future iterations
c. Add any discovered codebase patterns to progress.txt
Check PRD completion:
a. Read the active PRD file -- are ALL stories marked passes: true (with no active criteria left unverified)?
b. If NOT all complete, loop back to Step 2 (pick next story)
c. If ALL complete, proceed to Step 7 (architect verification)
Reviewer verification (tiered, against acceptance criteria):
7.5 Mandatory Deslop Pass (runs unconditionally after Step 7 approval, unless {{PROMPT}} contains --no-deslop):
Invoke the ai-slop-cleaner skill via the Skill tool: Skill("oh-my-claudecode:ai-slop-cleaner") — it is a Skill, not an agent. If you mistakenly call it via Task(subagent_type="oh-my-claudecode:ai-slop-cleaner"), OMC's PreToolUse hook denies the call with the correct Skill-tool identifier; do not substitute a similarly-named agent. Run in standard mode (not --review) on the files changed during the current Ralph session only.
Keep the scope bounded to the Ralph changed-file set; do not broaden the cleanup pass to unrelated files.
If the reviewer approved the implementation but the deslop pass introduces follow-up edits, keep those edits inside the same changed-file scope before proceeding.
7.6 Regression Re-verification:
After the deslop pass, re-run all relevant tests, build, and lint checks for the Ralph session.
Read the output and confirm the post-deslop regression run actually passes.
If regression fails, roll back the cleaner changes or fix the regression, then rerun the verification loop until it passes.
Only proceed to completion after the post-deslop regression run passes (or --no-deslop was explicitly specified).
On approval: After Step 7.6 passes (with Step 7.5 completed, or skipped via --no-deslop), run /oh-my-claudecode:cancel to cleanly exit and clean up all state files
On rejection: Fix the issues raised, re-verify with the same reviewer, then loop back to check if the story needs to be marked incomplete
<Tool_Usage>
Task(subagent_type="oh-my-claudecode:architect", ...) for architect verification cross-checks when changes are security-sensitive, architectural, or involve complex multi-system integrationTask(subagent_type="oh-my-claudecode:critic", ...) when --critic=criticomc ask codex --agent-prompt critic "..." when --critic=codex. Construct the prompt to include: (a) prd.json acceptance criteria, (b) files changed + related files, (c) explicit optimality question: "Is there a meaningfully simpler, faster, or more maintainable approach that achieves the same acceptance criteria?"state_write / state_read for ralph mode state persistence between iterationsai-slop-cleaner) are invoked via the Skill tool: Skill("oh-my-claudecode:ai-slop-cleaner"); agents (e.g. architect, critic, executor) via Task(subagent_type="oh-my-claudecode:<name>"). OMC's PreToolUse hook denies a Task/Agent call whose subagent_type names a bundled skill and returns the correct Skill-tool identifier — do not substitute a similarly-named agent as a "closest match".
</Tool_Usage>After refinement: acceptanceCriteria: [ "Legacy --no-prd text is stripped from the Ralph working prompt", "Ralph startup still creates or validates prd.json when legacy --no-prd text is present", "TypeScript compiles with no errors (npm run build)" ]
Why good: Generic criteria replaced with specific, testable criteria.
</Good>
<Good>
Correct parallel delegation:
Task(subagent_type="oh-my-claudecode:executor", model="haiku", prompt="Add type export for UserConfig") Task(subagent_type="oh-my-claudecode:executor", model="sonnet", prompt="Implement the caching layer for API responses") Task(subagent_type="oh-my-claudecode:executor", model="opus", prompt="Refactor auth module to support OAuth2 flow")
Why good: Three independent tasks fired simultaneously at appropriate tiers.
</Good>
<Good>
Story-by-story verification:
passes: true and completionCriteriaRevision equal to its current governingCriteriaRevisionWhy good: Each story verified against its own acceptance criteria before marking complete.
</Good>
<Bad>
Claiming completion without PRD verification:
"All the changes look good, the implementation should work correctly. Task complete."
Why bad: Uses "should" and "look good" -- no fresh evidence, no story-by-story verification, no architect review.
</Bad>
<Bad>
Sequential execution of independent tasks:
Task(executor, "Add type export") → wait → Task(executor, "Implement caching") → wait → Task(executor, "Refactor auth")
Why bad: These are independent tasks that should run in parallel, not sequentially.
</Bad>
<Bad>
Keeping generic acceptance criteria:
"prd.json created with criteria: Implementation is complete, Code compiles. Moving on to coding."
Why bad: Did not refine scaffold criteria into task-specific ones. This is PRD theater.
</Bad>
<Good>
Evidence-preserving criterion amendment:
Criterion: "All 16 files that set FDFT_WHALE_STREAM=1 are classified affected/not-affected WITH EVIDENCE"
Implementation enumerated the setters: 12 exist, not 16 (7 listed names are readers/asserters/doc-recipes). Two of those mis-classified readers are the ONLY affected files — the wrong count was hiding the answer.
Active criteria become: acceptanceCriteria: [ "All 12 files that set FDFT_WHALE_STREAM=1 are classified affected/not-affected WITH EVIDENCE" ] criterionAmendments: [ { "kind": "replaced", "original": "All 16 files that set FDFT_WHALE_STREAM=1 are classified affected/not-affected WITH EVIDENCE", "replacement": "All 12 files that set FDFT_WHALE_STREAM=1 are classified affected/not-affected WITH EVIDENCE", "reason": "The brief count was wrong: 7 listed names are readers/asserters/doc-recipes, not setters", "evidence": "Enumerated setters via grep FDFT_WHALE_STREAM=1: 12 setters, 16 total matches", "authority": "ses_", "timestamp": "2026-08-10T03:15:00.000Z" } ]
Why good: The falsified criterion stops governing, the measurement is preserved verbatim with proof/reason/authority/timestamp, and the loop keeps verifying the corrected criterion.
</Good>
</Examples>
<Escalation_And_Stop_Conditions>
- Stop and report when a fundamental blocker requires user input (missing credentials, unclear requirements, external service down)
- Stop when the user says "stop", "cancel", or "abort" -- run `/oh-my-claudecode:cancel`
- Continue working when the hook system sends "The boulder never stops" -- this means the iteration continues
- If the selected reviewer rejects verification, fix the issues and re-verify (do not stop)
- If the same issue recurs across 3+ iterations, report it as a potential fundamental problem
- **Do NOT stop after Step 7 approval.** The boulder continues through 7 → 7.5 → 7.6 → 8 in the same turn as a single chain. Step 7 is a checkpoint inside the loop, not a reporting moment. Treating an architect/critic APPROVED verdict as "time to summarise and wait for user acknowledgment" is a polite-stop anti-pattern — the only reporting moments in Ralph are Step 8 (successful cancel) or Step 9 (rejection).
</Escalation_And_Stop_Conditions>
<Final_Checklist>
- [ ] All prd.json stories have `passes: true` (no incomplete stories)
- [ ] Any refuted acceptance criterion was amended through the evidence ledger (original retained), not silently deleted
- [ ] prd.json acceptance criteria are task-specific (not generic boilerplate)
- [ ] All requirements from the original task are met (no scope reduction)
- [ ] Zero pending or in_progress TODO items
- [ ] Fresh test run output shows all tests pass
- [ ] Fresh build output shows success
- [ ] lsp_diagnostics shows 0 errors on affected files
- [ ] progress.txt records implementation details and learnings
- [ ] Selected reviewer verification passed against specific acceptance criteria
- [ ] ai-slop-cleaner pass completed on changed files (or `--no-deslop` specified)
- [ ] Post-deslop regression tests pass
- [ ] `/oh-my-claudecode:cancel` run for clean state cleanup
</Final_Checklist>
## Parallel session caveats
- **Multi-repo workspace anchor:** drop a `.omc-workspace` marker at the parent directory so multiple sessions across sub-repos share one `.omc/`. Resolution order: `OMC_STATE_DIR > .omc-workspace > git > cwd`. See `docs/REFERENCE.md`.
- **Session id source:** OMC_SESSION_ID env var wins in CLI contexts; hook payload data.session_id wins in hook contexts.
- **Plan id (when applicable):** Two ralph runs in the same workspace will conflict on `prd.json`. Use distinct session IDs (the hook payload session_id is already isolated per Claude Code session). For parallel ultragoal-backed ralph runs, use `--plan-id`.
- **Parallel verdict:** supported (each session writes its own session-scoped state)
<Advanced>
## Background Execution Rules
**Run in background** (`run_in_background: true`):
- Package installation (npm install, pip install, cargo build)
- Build processes (make, project build commands)
- Test suites
- Docker operations (docker build, docker pull)
**Run blocking** (foreground):
- Quick status checks (git status, ls, pwd)
- File reads and edits
- Simple commands
</Advanced>
Original task:
{{PROMPT}}
20 files or security/architectural changes: THOROUGH tier (architect / Opus)
--critic=critic, use the Claude critic agent for the approval pass--critic=codex, run omc ask codex --agent-prompt critic "..." for the approval pass. The Codex critic prompt MUST include:
/oh-my-claudecode:cancel) or on rejection (Step 9). Treating an approved verdict as a reporting checkpoint is a polite-stop anti-pattern.